code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
from __future__ import annotations def lowerCamelCase__ ( a ) -> bool: _A: List[str] = len(a ) # We need to create solution object to save path. _A: Optional[Any] = [[0 for _ in range(a )] for _ in range(a )] _A: List[Any] = run_maze(a , 0 , 0 , a ) if solved: print('''\n'''.join(str(a ) for row in solutions ) ) else: print('''No solution exists!''' ) return solved def lowerCamelCase__ ( a , a , a , a ) -> bool: _A: Tuple = len(a ) # Final check point. if i == j == (size - 1): _A: List[str] = 1 return True _A: Optional[Any] = (not i < 0) and (not j < 0) # Check lower bounds _A: int = (i < size) and (j < size) # Check upper bounds if lower_flag and upper_flag: # check for already visited and block points. _A: Any = (not solutions[i][j]) and (not maze[i][j]) if block_flag: # check visited _A: Optional[Any] = 1 # check for directions if ( run_maze(a , i + 1 , a , a ) or run_maze(a , a , j + 1 , a ) or run_maze(a , i - 1 , a , a ) or run_maze(a , a , j - 1 , a ) ): return True _A: Dict = 0 return False return False if __name__ == "__main__": import doctest doctest.testmod()
301
from __future__ import annotations UpperCAmelCase__ : List[str] = list[list[int]] # assigning initial values to the grid UpperCAmelCase__ : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution UpperCAmelCase__ : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def lowerCamelCase__ ( a , a , a , a ) -> bool: for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def lowerCamelCase__ ( a ) -> tuple[int, int] | None: for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def lowerCamelCase__ ( a ) -> Matrix | None: if location := find_empty_location(a ): _A , _A: Optional[Any] = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(a , a , a , a ): _A: str = digit if sudoku(a ) is not None: return grid _A: Tuple = 0 return None def lowerCamelCase__ ( a ) -> None: for row in grid: for cell in row: print(a , end=''' ''' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('\nExample grid:\n' + '=' * 20) print_solution(example_grid) print('\nExample grid solution:') UpperCAmelCase__ : int = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('Cannot find a solution.')
301
1
from unittest import TestCase from datasets import Dataset from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters def lowerCamelCase__ ( ) -> Optional[int]: _A: List[Any] = { '''repo_name''': ['''test_repo1''', '''test_repo2''', '''test_repo3'''], '''path''': ['''test_1.py''', '''test_2.py''', '''unit_test.py'''], '''content''': ['''a ''' * 20, '''a ''' * 30, '''b ''' * 7], } _A: Dict = Dataset.from_dict(a ) return dataset class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def __magic_name__ ( self : int ): """simple docstring""" _A: List[Any] = get_dataset() _A: Tuple = make_duplicate_clusters(lowerCAmelCase_ , 0.85 ) self.assertEqual(len(duplicate_clusters[0] ) , 2 ) def __magic_name__ ( self : str ): """simple docstring""" _A: Optional[Any] = get_dataset() _A , _A: List[str] = deduplicate_dataset(lowerCAmelCase_ ) self.assertEqual(len(lowerCAmelCase_ ) , 2 ) print(lowerCAmelCase_ ) self.assertEqual(duplicate_clusters[0][0]['''copies'''] , 2 ) self.assertEqual(duplicate_clusters[0][0]['''is_extreme'''] , lowerCAmelCase_ )
301
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests UpperCAmelCase__ : str = open # noqa: we just need to have a builtin inside this module to test it properly
301
1
from __future__ import annotations import os import tempfile import unittest from transformers import ConvBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertModel, ) class UpperCAmelCase : '''simple docstring''' def __init__( self : Tuple , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : str=1_3 , lowerCAmelCase_ : Any=7 , lowerCAmelCase_ : Optional[Any]=True , lowerCAmelCase_ : List[Any]=True , lowerCAmelCase_ : int=True , lowerCAmelCase_ : List[str]=True , lowerCAmelCase_ : Dict=9_9 , lowerCAmelCase_ : int=3_2 , lowerCAmelCase_ : Optional[int]=2 , lowerCAmelCase_ : List[Any]=4 , lowerCAmelCase_ : str=3_7 , lowerCAmelCase_ : int="gelu" , lowerCAmelCase_ : str=0.1 , lowerCAmelCase_ : Optional[int]=0.1 , lowerCAmelCase_ : int=5_1_2 , lowerCAmelCase_ : List[Any]=1_6 , lowerCAmelCase_ : List[str]=2 , lowerCAmelCase_ : Tuple=0.02 , lowerCAmelCase_ : Union[str, Any]=3 , lowerCAmelCase_ : Dict=4 , lowerCAmelCase_ : List[Any]=None , ): """simple docstring""" _A: Tuple = parent _A: int = 1_3 _A: List[str] = 7 _A: List[str] = True _A: int = True _A: Union[str, Any] = True _A: Dict = True _A: Union[str, Any] = 9_9 _A: Any = 3_8_4 _A: Dict = 2 _A: Optional[int] = 4 _A: Any = 3_7 _A: int = '''gelu''' _A: List[str] = 0.1 _A: List[Any] = 0.1 _A: Tuple = 5_1_2 _A: Dict = 1_6 _A: Tuple = 2 _A: List[Any] = 0.02 _A: str = 3 _A: str = 4 _A: int = 1_2_8 _A: str = 2 _A: Tuple = 9 _A: Tuple = 1 _A: str = None def __magic_name__ ( self : int ): """simple docstring""" _A: str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _A: Optional[int] = None if self.use_input_mask: _A: str = random_attention_mask([self.batch_size, self.seq_length] ) _A: Optional[int] = None if self.use_token_type_ids: _A: Dict = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _A: Any = None _A: Any = None _A: Union[str, Any] = None if self.use_labels: _A: Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _A: int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _A: List[Any] = ids_tensor([self.batch_size] , self.num_choices ) _A: Union[str, Any] = ConvBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=lowerCAmelCase_ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __magic_name__ ( self : Tuple , lowerCAmelCase_ : Any , lowerCAmelCase_ : Dict , lowerCAmelCase_ : str , lowerCAmelCase_ : int , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Dict ): """simple docstring""" _A: Optional[Any] = TFConvBertModel(config=lowerCAmelCase_ ) _A: List[str] = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} _A: List[str] = [input_ids, input_mask] _A: List[Any] = model(lowerCAmelCase_ ) _A: Tuple = model(lowerCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __magic_name__ ( self : Optional[Any] , lowerCAmelCase_ : str , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : str , lowerCAmelCase_ : Any , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Any , lowerCAmelCase_ : int ): """simple docstring""" _A: Optional[Any] = TFConvBertForMaskedLM(config=lowerCAmelCase_ ) _A: Optional[int] = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _A: List[Any] = model(lowerCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __magic_name__ ( self : Any , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Any , lowerCAmelCase_ : str ): """simple docstring""" _A: Union[str, Any] = self.num_labels _A: List[Any] = TFConvBertForSequenceClassification(config=lowerCAmelCase_ ) _A: Tuple = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _A: str = model(lowerCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __magic_name__ ( self : Optional[Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Any , lowerCAmelCase_ : Union[str, Any] ): """simple docstring""" _A: Optional[int] = self.num_choices _A: Union[str, Any] = TFConvBertForMultipleChoice(config=lowerCAmelCase_ ) _A: Optional[Any] = tf.tile(tf.expand_dims(lowerCAmelCase_ , 1 ) , (1, self.num_choices, 1) ) _A: Dict = tf.tile(tf.expand_dims(lowerCAmelCase_ , 1 ) , (1, self.num_choices, 1) ) _A: Any = tf.tile(tf.expand_dims(lowerCAmelCase_ , 1 ) , (1, self.num_choices, 1) ) _A: Tuple = { '''input_ids''': multiple_choice_inputs_ids, '''attention_mask''': multiple_choice_input_mask, '''token_type_ids''': multiple_choice_token_type_ids, } _A: Union[str, Any] = model(lowerCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __magic_name__ ( self : Optional[Any] , lowerCAmelCase_ : int , lowerCAmelCase_ : Any , lowerCAmelCase_ : Dict , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Any ): """simple docstring""" _A: List[Any] = self.num_labels _A: Union[str, Any] = TFConvBertForTokenClassification(config=lowerCAmelCase_ ) _A: Tuple = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _A: List[str] = model(lowerCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __magic_name__ ( self : Any , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : str , lowerCAmelCase_ : Any , lowerCAmelCase_ : Dict , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" _A: Any = TFConvBertForQuestionAnswering(config=lowerCAmelCase_ ) _A: int = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _A: Dict = model(lowerCAmelCase_ ) 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 __magic_name__ ( self : Optional[Any] ): """simple docstring""" _A: List[str] = self.prepare_config_and_inputs() ( ( _A ) , ( _A ) , ( _A ) , ( _A ) , ( _A ) , ( _A ) , ( _A ) , ): Optional[Any] = config_and_inputs _A: int = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase : int = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) __UpperCamelCase : Tuple = ( { '''feature-extraction''': TFConvBertModel, '''fill-mask''': TFConvBertForMaskedLM, '''question-answering''': TFConvBertForQuestionAnswering, '''text-classification''': TFConvBertForSequenceClassification, '''token-classification''': TFConvBertForTokenClassification, '''zero-shot''': TFConvBertForSequenceClassification, } if is_tf_available() else {} ) __UpperCamelCase : str = False __UpperCamelCase : Dict = False __UpperCamelCase : int = False def __magic_name__ ( self : Any ): """simple docstring""" _A: str = TFConvBertModelTester(self ) _A: List[Any] = ConfigTester(self , config_class=lowerCAmelCase_ , hidden_size=3_7 ) def __magic_name__ ( self : Tuple ): """simple docstring""" self.config_tester.run_common_tests() def __magic_name__ ( self : Optional[int] ): """simple docstring""" _A: Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase_ ) def __magic_name__ ( self : int ): """simple docstring""" _A: List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*lowerCAmelCase_ ) def __magic_name__ ( self : Any ): """simple docstring""" _A: str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*lowerCAmelCase_ ) def __magic_name__ ( self : Tuple ): """simple docstring""" _A: List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowerCAmelCase_ ) def __magic_name__ ( self : List[Any] ): """simple docstring""" _A: List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*lowerCAmelCase_ ) def __magic_name__ ( self : Any ): """simple docstring""" _A: Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowerCAmelCase_ ) @slow def __magic_name__ ( self : List[Any] ): """simple docstring""" _A , _A: Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() _A: Optional[int] = True _A: str = True if hasattr(lowerCAmelCase_ , '''use_cache''' ): _A: List[Any] = True _A: Optional[Any] = getattr(self.model_tester , '''encoder_seq_length''' , self.model_tester.seq_length ) _A: str = getattr(self.model_tester , '''key_length''' , lowerCAmelCase_ ) for model_class in self.all_model_classes: _A: Any = self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ ) _A: int = model_class(lowerCAmelCase_ ) _A: Tuple = len(model(lowerCAmelCase_ ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(lowerCAmelCase_ , saved_model=lowerCAmelCase_ ) _A: str = os.path.join(lowerCAmelCase_ , '''saved_model''' , '''1''' ) _A: List[str] = tf.keras.models.load_model(lowerCAmelCase_ ) _A: List[Any] = model(lowerCAmelCase_ ) if self.is_encoder_decoder: _A: Optional[int] = outputs['''encoder_hidden_states'''] _A: List[Any] = outputs['''encoder_attentions'''] else: _A: List[str] = outputs['''hidden_states'''] _A: Any = outputs['''attentions'''] self.assertEqual(len(lowerCAmelCase_ ) , lowerCAmelCase_ ) _A: Any = getattr( self.model_tester , '''expected_num_hidden_layers''' , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(lowerCAmelCase_ ) , lowerCAmelCase_ ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(lowerCAmelCase_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) @slow def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" _A: Union[str, Any] = TFConvBertModel.from_pretrained('''YituTech/conv-bert-base''' ) self.assertIsNotNone(lowerCAmelCase_ ) def __magic_name__ ( self : Optional[Any] ): """simple docstring""" _A , _A: Any = self.model_tester.prepare_config_and_inputs_for_common() _A: Optional[Any] = True _A: Optional[int] = getattr(self.model_tester , '''decoder_seq_length''' , self.model_tester.seq_length ) _A: List[str] = getattr(self.model_tester , '''encoder_seq_length''' , self.model_tester.seq_length ) _A: Optional[int] = getattr(self.model_tester , '''key_length''' , lowerCAmelCase_ ) _A: Union[str, Any] = getattr(self.model_tester , '''key_length''' , lowerCAmelCase_ ) def check_decoder_attentions_output(lowerCAmelCase_ : Union[str, Any] ): _A: Any = len(lowerCAmelCase_ ) self.assertEqual(out_len % 2 , 0 ) _A: List[Any] = outputs.decoder_attentions self.assertEqual(len(lowerCAmelCase_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , ) def check_encoder_attentions_output(lowerCAmelCase_ : Union[str, Any] ): _A: Optional[Any] = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(lowerCAmelCase_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) for model_class in self.all_model_classes: _A: List[str] = True _A: List[str] = False _A: List[Any] = model_class(lowerCAmelCase_ ) _A: Any = model(self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ ) ) _A: Tuple = len(lowerCAmelCase_ ) self.assertEqual(config.output_hidden_states , lowerCAmelCase_ ) check_encoder_attentions_output(lowerCAmelCase_ ) if self.is_encoder_decoder: _A: Optional[Any] = model_class(lowerCAmelCase_ ) _A: Optional[Any] = model(self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ ) ) self.assertEqual(config.output_hidden_states , lowerCAmelCase_ ) check_decoder_attentions_output(lowerCAmelCase_ ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] _A: Any = True _A: int = model_class(lowerCAmelCase_ ) _A: Tuple = model(self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ ) ) self.assertEqual(config.output_hidden_states , lowerCAmelCase_ ) check_encoder_attentions_output(lowerCAmelCase_ ) # Check attention is always last and order is fine _A: Any = True _A: Union[str, Any] = True _A: Union[str, Any] = model_class(lowerCAmelCase_ ) _A: Any = model(self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(lowerCAmelCase_ ) ) self.assertEqual(model.config.output_hidden_states , lowerCAmelCase_ ) check_encoder_attentions_output(lowerCAmelCase_ ) @require_tf class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __magic_name__ ( self : Optional[Any] ): """simple docstring""" _A: int = TFConvBertModel.from_pretrained('''YituTech/conv-bert-base''' ) _A: Tuple = tf.constant([[0, 1, 2, 3, 4, 5]] ) _A: str = model(lowerCAmelCase_ )[0] _A: str = [1, 6, 7_6_8] self.assertEqual(output.shape , lowerCAmelCase_ ) _A: Tuple = tf.constant( [ [ [-0.03475493, -0.4686034, -0.30638832], [0.22637248, -0.26988646, -0.7423424], [0.10324868, -0.45013508, -0.58280784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , lowerCAmelCase_ , atol=1e-4 )
301
import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Optional[Any] , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : List[str]=3 , lowerCAmelCase_ : List[str]=3_2 , lowerCAmelCase_ : Union[str, Any]=3 , lowerCAmelCase_ : int=1_0 , lowerCAmelCase_ : Tuple=[1_0, 2_0, 3_0, 4_0] , lowerCAmelCase_ : Optional[Any]=[1, 1, 2, 1] , lowerCAmelCase_ : Optional[Any]=True , lowerCAmelCase_ : str=True , lowerCAmelCase_ : Optional[Any]="relu" , lowerCAmelCase_ : int=3 , lowerCAmelCase_ : List[Any]=None , ): """simple docstring""" _A: str = parent _A: List[Any] = batch_size _A: Optional[int] = image_size _A: Dict = num_channels _A: str = embeddings_size _A: Any = hidden_sizes _A: Dict = depths _A: Any = is_training _A: int = use_labels _A: Tuple = hidden_act _A: int = num_labels _A: int = scope _A: str = len(lowerCAmelCase_ ) def __magic_name__ ( self : Dict ): """simple docstring""" _A: Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _A: Union[str, Any] = self.get_config() return config, pixel_values def __magic_name__ ( self : str ): """simple docstring""" return RegNetConfig( 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 , image_size=self.image_size , ) def __magic_name__ ( self : str , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : str ): """simple docstring""" _A: str = FlaxRegNetModel(config=lowerCAmelCase_ ) _A: Optional[int] = model(lowerCAmelCase_ ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , ) def __magic_name__ ( self : str , lowerCAmelCase_ : str , lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Union[str, Any] = self.num_labels _A: Union[str, Any] = FlaxRegNetForImageClassification(config=lowerCAmelCase_ ) _A: str = model(lowerCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __magic_name__ ( self : List[Any] ): """simple docstring""" _A: str = self.prepare_config_and_inputs() _A , _A: Optional[int] = config_and_inputs _A: Union[str, Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_flax class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Tuple = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () __UpperCamelCase : Union[str, Any] = False __UpperCamelCase : List[Any] = False __UpperCamelCase : int = False def __magic_name__ ( self : int ): """simple docstring""" _A: int = FlaxRegNetModelTester(self ) _A: Union[str, Any] = ConfigTester(self , config_class=lowerCAmelCase_ , has_text_modality=lowerCAmelCase_ ) def __magic_name__ ( self : str ): """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __magic_name__ ( self : int ): """simple docstring""" return def __magic_name__ ( self : Tuple ): """simple docstring""" _A: int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase_ ) def __magic_name__ ( self : Tuple ): """simple docstring""" _A: Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_ ) @unittest.skip(reason='''RegNet does not use inputs_embeds''' ) def __magic_name__ ( self : str ): """simple docstring""" pass @unittest.skip(reason='''RegNet does not support input and output embeddings''' ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" pass def __magic_name__ ( self : List[Any] ): """simple docstring""" _A , _A: int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A: Union[str, Any] = model_class(lowerCAmelCase_ ) _A: Any = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _A: Any = [*signature.parameters.keys()] _A: Union[str, Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowerCAmelCase_ ) def __magic_name__ ( self : str ): """simple docstring""" def check_hidden_states_output(lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Tuple ): _A: int = model_class(lowerCAmelCase_ ) _A: List[str] = model(**self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ ) ) _A: str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _A: Tuple = self.model_tester.num_stages self.assertEqual(len(lowerCAmelCase_ ) , expected_num_stages + 1 ) _A , _A: List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A: Optional[Any] = True check_hidden_states_output(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _A: int = True check_hidden_states_output(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) def __magic_name__ ( self : Dict ): """simple docstring""" _A , _A: str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): _A: int = self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ ) _A: Union[str, Any] = model_class(lowerCAmelCase_ ) @jax.jit def model_jitted(lowerCAmelCase_ : Optional[Any] , **lowerCAmelCase_ : Optional[Any] ): return model(pixel_values=lowerCAmelCase_ , **lowerCAmelCase_ ) with self.subTest('''JIT Enabled''' ): _A: str = model_jitted(**lowerCAmelCase_ ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): _A: List[Any] = model_jitted(**lowerCAmelCase_ ).to_tuple() self.assertEqual(len(lowerCAmelCase_ ) , len(lowerCAmelCase_ ) ) for jitted_output, output in zip(lowerCAmelCase_ , lowerCAmelCase_ ): self.assertEqual(jitted_output.shape , output.shape ) def lowerCamelCase__ ( ) -> Tuple: _A: List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_flax class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" return AutoImageProcessor.from_pretrained('''facebook/regnet-y-040''' ) if is_vision_available() else None @slow def __magic_name__ ( self : List[str] ): """simple docstring""" _A: List[str] = FlaxRegNetForImageClassification.from_pretrained('''facebook/regnet-y-040''' ) _A: str = self.default_image_processor _A: int = prepare_img() _A: List[Any] = image_processor(images=lowerCAmelCase_ , return_tensors='''np''' ) _A: str = model(**lowerCAmelCase_ ) # verify the logits _A: str = (1, 1_0_0_0) self.assertEqual(outputs.logits.shape , lowerCAmelCase_ ) _A: Tuple = jnp.array([-0.4180, -1.5051, -3.4836] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] , lowerCAmelCase_ , atol=1e-4 ) )
301
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ : List[Any] = logging.get_logger(__name__) UpperCAmelCase__ : Optional[int] = { 'tiiuae/falcon-40b': 'https://huggingface.co/tiiuae/falcon-40b/resolve/main/config.json', 'tiiuae/falcon-7b': 'https://huggingface.co/tiiuae/falcon-7b/resolve/main/config.json', } class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Optional[int] = '''falcon''' __UpperCamelCase : List[Any] = ['''past_key_values'''] def __init__( self : Any , lowerCAmelCase_ : int=6_5_0_2_4 , lowerCAmelCase_ : str=4_5_4_4 , lowerCAmelCase_ : str=3_2 , lowerCAmelCase_ : List[Any]=7_1 , lowerCAmelCase_ : Tuple=1e-5 , lowerCAmelCase_ : Union[str, Any]=0.02 , lowerCAmelCase_ : Union[str, Any]=True , lowerCAmelCase_ : Optional[int]=0.0 , lowerCAmelCase_ : int=0.0 , lowerCAmelCase_ : List[Any]=None , lowerCAmelCase_ : Any=False , lowerCAmelCase_ : Optional[Any]=False , lowerCAmelCase_ : Optional[Any]=True , lowerCAmelCase_ : str=True , lowerCAmelCase_ : int=False , lowerCAmelCase_ : Optional[Any]=1_1 , lowerCAmelCase_ : int=1_1 , **lowerCAmelCase_ : Optional[Any] , ): """simple docstring""" _A: Tuple = vocab_size # Backward compatibility with n_embed kwarg _A: Dict = kwargs.pop('''n_embed''' , lowerCAmelCase_ ) _A: Tuple = hidden_size if n_embed is None else n_embed _A: int = num_hidden_layers _A: int = num_attention_heads _A: Optional[int] = layer_norm_epsilon _A: Dict = initializer_range _A: Optional[Any] = use_cache _A: Any = hidden_dropout _A: List[str] = attention_dropout _A: Dict = bos_token_id _A: Any = eos_token_id _A: Dict = num_attention_heads if num_kv_heads is None else num_kv_heads _A: int = alibi _A: Optional[Any] = new_decoder_architecture _A: Dict = multi_query # Ignored when new_decoder_architecture is True _A: int = parallel_attn _A: str = bias super().__init__(bos_token_id=lowerCAmelCase_ , eos_token_id=lowerCAmelCase_ , **lowerCAmelCase_ ) @property def __magic_name__ ( self : int ): """simple docstring""" return self.hidden_size // self.num_attention_heads @property def __magic_name__ ( self : Optional[int] ): """simple docstring""" return not self.alibi
301
from __future__ import annotations from bisect import bisect_left from functools import total_ordering from heapq import merge @total_ordering class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def __lt__( self : Dict , lowerCAmelCase_ : Optional[int] ): """simple docstring""" return self[-1] < other[-1] def __eq__( self : int , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" return self[-1] == other[-1] def lowerCamelCase__ ( a ) -> list: _A: list[Stack] = [] # sort into stacks for element in collection: _A: Any = Stack([element] ) _A: Optional[Any] = bisect_left(a , a ) if i != len(a ): stacks[i].append(a ) else: stacks.append(a ) # use a heap-based merge to merge stack efficiently _A: Tuple = merge(*(reversed(a ) for stack in stacks) ) return collection if __name__ == "__main__": UpperCAmelCase__ : Tuple = input('Enter numbers separated by a comma:\n').strip() UpperCAmelCase__ : Optional[Any] = [int(item) for item in user_input.split(',')] print(patience_sort(unsorted))
301
1
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 UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" _A: Dict = torch.tensor([-1_0_0, -1, -0.1, 0, 0.1, 1.0, 1_0_0] ) _A: str = get_activation('''gelu''' ) self.assertTrue(torch.allclose(gelu_python(lowerCAmelCase_ ) , torch_builtin(lowerCAmelCase_ ) ) ) self.assertFalse(torch.allclose(gelu_python(lowerCAmelCase_ ) , gelu_new(lowerCAmelCase_ ) ) ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" _A: List[str] = torch.tensor([-1_0_0, -1, -0.1, 0, 0.1, 1.0, 1_0_0] ) _A: Union[str, Any] = get_activation('''gelu''' ) _A: Tuple = get_activation('''gelu_10''' ) _A: Any = torch_builtin(lowerCAmelCase_ ) _A: List[str] = geluaa(lowerCAmelCase_ ) _A: Optional[Any] = torch.where(y_gelu_aa < 10.0 , 1 , 0 ) self.assertTrue(torch.max(lowerCAmelCase_ ).item() == 10.0 ) self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) ) def __magic_name__ ( self : List[Any] ): """simple docstring""" 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(lowerCAmelCase_ ): get_activation('''bogus''' ) with self.assertRaises(lowerCAmelCase_ ): get_activation(lowerCAmelCase_ ) def __magic_name__ ( self : int ): """simple docstring""" _A: int = get_activation('''gelu''' ) _A: List[Any] = 1 _A: Tuple = get_activation('''gelu''' ) self.assertEqual(acta.a , 1 ) with self.assertRaises(lowerCAmelCase_ ): _A: Any = acta.a
301
import argparse import datetime import json import time import warnings from logging import getLogger from pathlib import Path from typing import Dict, List import torch from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils import calculate_bleu, calculate_rouge, chunks, parse_numeric_n_bool_cl_kwargs, use_task_specific_params UpperCAmelCase__ : Any = getLogger(__name__) UpperCAmelCase__ : Optional[Any] = 'cuda' if torch.cuda.is_available() else 'cpu' def lowerCamelCase__ ( a , a , a , a = 8 , a = DEFAULT_DEVICE , a=False , a="summarization" , a=None , **a , ) -> Dict: _A: str = Path(a ).open('''w''' , encoding='''utf-8''' ) _A: Optional[Any] = str(a ) _A: Union[str, Any] = AutoModelForSeqaSeqLM.from_pretrained(a ).to(a ) if fpaa: _A: Any = model.half() _A: Optional[int] = AutoTokenizer.from_pretrained(a ) logger.info(f"""Inferred tokenizer type: {tokenizer.__class__}""" ) # if this is wrong, check config.model_type. _A: Any = time.time() # update config with task specific params use_task_specific_params(a , a ) if prefix is None: _A: int = prefix or getattr(model.config , '''prefix''' , '''''' ) or '''''' for examples_chunk in tqdm(list(chunks(a , a ) ) ): _A: int = [prefix + text for text in examples_chunk] _A: str = tokenizer(a , return_tensors='''pt''' , truncation=a , padding='''longest''' ).to(a ) _A: str = model.generate( input_ids=batch.input_ids , attention_mask=batch.attention_mask , **a , ) _A: str = tokenizer.batch_decode(a , skip_special_tokens=a , clean_up_tokenization_spaces=a ) for hypothesis in dec: fout.write(hypothesis + '''\n''' ) fout.flush() fout.close() _A: Optional[int] = int(time.time() - start_time ) # seconds _A: Union[str, Any] = len(a ) return {"n_obs": n_obs, "runtime": runtime, "seconds_per_sample": round(runtime / n_obs , 4 )} def lowerCamelCase__ ( ) -> Tuple: return datetime.datetime.now().strftime('''%Y-%m-%d %H:%M:%S''' ) def lowerCamelCase__ ( a=True ) -> Optional[Any]: _A: str = argparse.ArgumentParser() parser.add_argument('''model_name''' , type=a , help='''like facebook/bart-large-cnn,t5-base, etc.''' ) parser.add_argument('''input_path''' , type=a , help='''like cnn_dm/test.source''' ) parser.add_argument('''save_path''' , type=a , help='''where to save summaries''' ) parser.add_argument('''--reference_path''' , type=a , required=a , help='''like cnn_dm/test.target''' ) parser.add_argument('''--score_path''' , type=a , required=a , default='''metrics.json''' , help='''where to save metrics''' ) parser.add_argument('''--device''' , type=a , required=a , default=a , help='''cuda, cuda:1, cpu etc.''' ) parser.add_argument( '''--prefix''' , type=a , required=a , default=a , help='''will be added to the begininng of src examples''' ) parser.add_argument('''--task''' , type=a , default='''summarization''' , help='''used for task_specific_params + metrics''' ) parser.add_argument('''--bs''' , type=a , default=8 , required=a , help='''batch size''' ) parser.add_argument( '''--n_obs''' , type=a , default=-1 , required=a , help='''How many observations. Defaults to all.''' ) parser.add_argument('''--fp16''' , action='''store_true''' ) parser.add_argument('''--dump-args''' , action='''store_true''' , help='''print the custom hparams with the results''' ) parser.add_argument( '''--info''' , nargs='''?''' , type=a , const=datetime_now() , help=( '''use in conjunction w/ --dump-args to print with the results whatever other info you\'d like, e.g.''' ''' lang=en-ru. If no value is passed, the current datetime string will be used.''' ) , ) # Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate _A , _A: Tuple = parser.parse_known_args() _A: List[str] = parse_numeric_n_bool_cl_kwargs(a ) if parsed_args and verbose: print(f"""parsed the following generate kwargs: {parsed_args}""" ) _A: int = [''' ''' + x.rstrip() if '''t5''' in args.model_name else x.rstrip() for x in open(args.input_path ).readlines()] if args.n_obs > 0: _A: List[str] = examples[: args.n_obs] Path(args.save_path ).parent.mkdir(exist_ok=a ) if args.reference_path is None and Path(args.score_path ).exists(): warnings.warn(f"""score_path {args.score_path} will be overwritten unless you type ctrl-c.""" ) if args.device == "cpu" and args.fpaa: # this mix leads to RuntimeError: "threshold_cpu" not implemented for 'Half' raise ValueError('''Can\'t mix --fp16 and --device cpu''' ) _A: Dict = generate_summaries_or_translations( a , args.save_path , args.model_name , batch_size=args.bs , device=args.device , fpaa=args.fpaa , task=args.task , prefix=args.prefix , **a , ) if args.reference_path is None: return {} # Compute scores _A: Dict = calculate_bleu if '''translation''' in args.task else calculate_rouge _A: List[Any] = [x.rstrip() for x in open(args.save_path ).readlines()] _A: Any = [x.rstrip() for x in open(args.reference_path ).readlines()][: len(a )] _A: dict = score_fn(a , a ) scores.update(a ) if args.dump_args: scores.update(a ) if args.info: _A: Optional[Any] = args.info if verbose: print(a ) if args.score_path is not None: json.dump(a , open(args.score_path , '''w''' ) ) return scores if __name__ == "__main__": # Usage for MT: # python run_eval.py MODEL_NAME $DATA_DIR/test.source $save_dir/test_translations.txt --reference_path $DATA_DIR/test.target --score_path $save_dir/test_bleu.json --task translation $@ run_generate(verbose=True)
301
1
def lowerCamelCase__ ( a = 10_00 ) -> int: _A: Tuple = -1 _A: Optional[Any] = 0 for a in range(1 , n // 3 ): # Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c _A: str = (n * n - 2 * a * n) // (2 * n - 2 * a) _A: str = n - a - b if c * c == (a * a + b * b): _A: Dict = a * b * c if candidate >= product: _A: List[str] = candidate return product if __name__ == "__main__": print(F"""{solution() = }""")
301
import math import random from typing import Any from .hill_climbing import SearchProblem def lowerCamelCase__ ( a , a = True , a = math.inf , a = -math.inf , a = math.inf , a = -math.inf , a = False , a = 1_00 , a = 0.01 , a = 1 , ) -> Any: _A: Optional[Any] = False _A: Dict = search_prob _A: str = start_temperate _A: Optional[int] = [] _A: int = 0 _A: Dict = None while not search_end: _A: Dict = current_state.score() if best_state is None or current_score > best_state.score(): _A: List[Any] = current_state scores.append(a ) iterations += 1 _A: List[str] = None _A: str = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to _A: Any = random.randint(0 , len(a ) - 1 ) # picking a random neighbor _A: Union[str, Any] = neighbors.pop(a ) _A: List[str] = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: _A: Optional[Any] = change * -1 # in case we are finding minimum if change > 0: # improves the solution _A: str = picked_neighbor else: _A: Tuple = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability _A: Optional[int] = picked_neighbor _A: Dict = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor _A: Any = True else: _A: List[Any] = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(a ) , a ) plt.xlabel('''Iterations''' ) plt.ylabel('''Function values''' ) plt.show() return best_state if __name__ == "__main__": def lowerCamelCase__ ( a , a ) -> Optional[Any]: return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) UpperCAmelCase__ : Optional[int] = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) UpperCAmelCase__ : Optional[Any] = simulated_annealing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( 'The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) # starting the problem with initial coordinates (12, 47) UpperCAmelCase__ : Optional[Any] = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) UpperCAmelCase__ : List[str] = simulated_annealing( prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( 'The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) def lowerCamelCase__ ( a , a ) -> Optional[Any]: return (3 * x**2) - (6 * y) UpperCAmelCase__ : Union[str, Any] = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) UpperCAmelCase__ : List[str] = simulated_annealing(prob, find_max=False, visualization=True) print( 'The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ' F"""{local_min.score()}""" ) UpperCAmelCase__ : Optional[Any] = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) UpperCAmelCase__ : List[Any] = simulated_annealing(prob, find_max=True, visualization=True) print( 'The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ' F"""{local_min.score()}""" )
301
1
import webbrowser from sys import argv from urllib.parse import parse_qs, quote import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": UpperCAmelCase__ : List[Any] = '%20'.join(argv[1:]) if len(argv) > 1 else quote(str(input('Search: '))) print('Googling.....') UpperCAmelCase__ : List[str] = F"""https://www.google.com/search?q={query}&num=100""" UpperCAmelCase__ : Dict = requests.get( url, headers={'User-Agent': str(UserAgent().random)}, ) try: UpperCAmelCase__ : Optional[Any] = ( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'yuRUbf'}) .find('a') .get('href') ) except AttributeError: UpperCAmelCase__ : Any = parse_qs( BeautifulSoup(res.text, 'html.parser') .find('div', attrs={'class': 'kCrYT'}) .find('a') .get('href') )['url'][0] webbrowser.open(link)
301
import json import os from typing import Dict, List, Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase__ : List[Any] = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } UpperCAmelCase__ : Tuple = { '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__ : Optional[int] = {'facebook/blenderbot_small-90M': 512} def lowerCamelCase__ ( a ) -> Optional[Any]: _A: List[Any] = set() _A: List[Any] = word[0] for char in word[1:]: pairs.add((prev_char, char) ) _A: List[Any] = char _A: Union[str, Any] = set(a ) return pairs class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : str = VOCAB_FILES_NAMES __UpperCamelCase : List[Any] = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase : Union[str, Any] = ['''input_ids''', '''attention_mask'''] def __init__( self : int , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : List[str]="__start__" , lowerCAmelCase_ : Any="__end__" , lowerCAmelCase_ : Any="__unk__" , lowerCAmelCase_ : Any="__null__" , **lowerCAmelCase_ : int , ): """simple docstring""" super().__init__(unk_token=lowerCAmelCase_ , bos_token=lowerCAmelCase_ , eos_token=lowerCAmelCase_ , pad_token=lowerCAmelCase_ , **lowerCAmelCase_ ) with open(lowerCAmelCase_ , encoding='''utf-8''' ) as vocab_handle: _A: Optional[int] = json.load(lowerCAmelCase_ ) _A: int = {v: k for k, v in self.encoder.items()} with open(lowerCAmelCase_ , encoding='''utf-8''' ) as merges_handle: _A: Dict = merges_handle.read().split('''\n''' )[1:-1] _A: int = [tuple(merge.split() ) for merge in merges] _A: Dict = dict(zip(lowerCAmelCase_ , range(len(lowerCAmelCase_ ) ) ) ) _A: Union[str, Any] = {} @property def __magic_name__ ( self : Optional[int] ): """simple docstring""" return len(self.encoder ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def __magic_name__ ( self : str , lowerCAmelCase_ : str ): """simple docstring""" if token in self.cache: return self.cache[token] _A: List[Any] = re.sub('''([.,!?()])''' , R''' \1''' , lowerCAmelCase_ ) _A: List[Any] = re.sub('''(\')''' , R''' \1 ''' , lowerCAmelCase_ ) _A: List[Any] = re.sub(R'''\s{2,}''' , ''' ''' , lowerCAmelCase_ ) if "\n" in token: _A: Dict = token.replace('''\n''' , ''' __newln__''' ) _A: Any = token.split(''' ''' ) _A: Optional[Any] = [] for token in tokens: if not len(lowerCAmelCase_ ): continue _A: str = token.lower() _A: List[str] = tuple(lowerCAmelCase_ ) _A: str = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] ) _A: Dict = get_pairs(lowerCAmelCase_ ) if not pairs: words.append(lowerCAmelCase_ ) continue while True: _A: str = min(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : self.bpe_ranks.get(lowerCAmelCase_ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break _A , _A: Optional[int] = bigram _A: str = [] _A: Dict = 0 while i < len(lowerCAmelCase_ ): try: _A: List[Any] = word.index(lowerCAmelCase_ , lowerCAmelCase_ ) new_word.extend(word[i:j] ) _A: Optional[int] = j except ValueError: new_word.extend(word[i:] ) break if word[i] == first and i < len(lowerCAmelCase_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 _A: Union[str, Any] = tuple(lowerCAmelCase_ ) _A: Tuple = new_word if len(lowerCAmelCase_ ) == 1: break else: _A: Optional[int] = get_pairs(lowerCAmelCase_ ) _A: str = '''@@ '''.join(lowerCAmelCase_ ) _A: Tuple = word[:-4] _A: List[Any] = word words.append(lowerCAmelCase_ ) return " ".join(lowerCAmelCase_ ) def __magic_name__ ( self : str , lowerCAmelCase_ : str ): """simple docstring""" _A: List[Any] = [] _A: List[Any] = re.findall(R'''\S+\n?''' , lowerCAmelCase_ ) for token in words: split_tokens.extend(list(self.bpe(lowerCAmelCase_ ).split(''' ''' ) ) ) return split_tokens def __magic_name__ ( self : str , lowerCAmelCase_ : str ): """simple docstring""" _A: List[str] = token.lower() return self.encoder.get(lowerCAmelCase_ , self.encoder.get(self.unk_token ) ) def __magic_name__ ( self : int , lowerCAmelCase_ : int ): """simple docstring""" return self.decoder.get(lowerCAmelCase_ , self.unk_token ) def __magic_name__ ( self : List[str] , lowerCAmelCase_ : List[str] ): """simple docstring""" _A: List[str] = ''' '''.join(lowerCAmelCase_ ).replace('''@@ ''' , '''''' ).strip() return out_string def __magic_name__ ( self : List[Any] , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[str] = None ): """simple docstring""" if not os.path.isdir(lowerCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _A: Dict = os.path.join( lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) _A: Any = os.path.join( lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(lowerCAmelCase_ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=lowerCAmelCase_ , ensure_ascii=lowerCAmelCase_ ) + '''\n''' ) _A: List[str] = 0 with open(lowerCAmelCase_ , '''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 lowerCAmelCase_ : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" ''' Please check that the tokenizer is not corrupted!''' ) _A: Optional[int] = token_index writer.write(''' '''.join(lowerCAmelCase_ ) + '''\n''' ) index += 1 return vocab_file, merge_file
301
1
import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer UpperCAmelCase__ : Optional[int] = 'bart' UpperCAmelCase__ : Dict = True @st.cache(allow_output_mutation=a ) def lowerCamelCase__ ( ) -> Dict: if LOAD_DENSE_INDEX: _A: Optional[Any] = AutoTokenizer.from_pretrained('''yjernite/retribert-base-uncased''' ) _A: Any = AutoModel.from_pretrained('''yjernite/retribert-base-uncased''' ).to('''cuda:0''' ) _A: Any = qar_model.eval() else: _A , _A: Union[str, Any] = (None, None) if MODEL_TYPE == "bart": _A: Union[str, Any] = AutoTokenizer.from_pretrained('''yjernite/bart_eli5''' ) _A: Dict = AutoModelForSeqaSeqLM.from_pretrained('''yjernite/bart_eli5''' ).to('''cuda:0''' ) _A: Union[str, Any] = torch.load('''seq2seq_models/eli5_bart_model_blm_2.pth''' ) sas_model.load_state_dict(save_dict['''model'''] ) _A: int = sas_model.eval() else: _A , _A: Tuple = make_qa_sas_model( model_name='''t5-small''' , from_file='''seq2seq_models/eli5_t5_model_1024_4.pth''' , device='''cuda:0''' ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=a ) def lowerCamelCase__ ( ) -> Tuple: if LOAD_DENSE_INDEX: _A: List[Any] = faiss.StandardGpuResources() _A: int = datasets.load_dataset(path='''wiki_snippets''' , name='''wiki40b_en_100_0''' )['''train'''] _A: Dict = np.memmap( '''wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat''' , dtype='''float32''' , mode='''r''' , shape=(wikiaab_passages.num_rows, 1_28) , ) _A: str = faiss.IndexFlatIP(1_28 ) _A: Optional[int] = faiss.index_cpu_to_gpu(a , 1 , a ) wikiaab_gpu_index_flat.add(a ) # TODO fix for larger GPU else: _A , _A: str = (None, None) _A: Tuple = Elasticsearch([{'''host''': '''localhost''', '''port''': '''9200'''}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=a ) def lowerCamelCase__ ( ) -> str: _A: Dict = datasets.load_dataset('''eli5''' , name='''LFQA_reddit''' ) _A: Dict = elia['''train_eli5'''] _A: List[Any] = np.memmap( '''eli5_questions_reps.dat''' , dtype='''float32''' , mode='''r''' , shape=(elia_train.num_rows, 1_28) ) _A: Any = faiss.IndexFlatIP(1_28 ) eli5_train_q_index.add(a ) return (elia_train, eli5_train_q_index) UpperCAmelCase__ ,UpperCAmelCase__ ,UpperCAmelCase__ : int = load_indexes() UpperCAmelCase__ ,UpperCAmelCase__ ,UpperCAmelCase__ ,UpperCAmelCase__ : Any = load_models() UpperCAmelCase__ ,UpperCAmelCase__ : Tuple = load_train_data() def lowerCamelCase__ ( a , a=10 ) -> str: _A: Optional[int] = embed_questions_for_retrieval([question] , a , a ) _A , _A: List[str] = eli5_train_q_index.search(a , a ) _A: Dict = [elia_train[int(a )] for i in I[0]] return nn_examples def lowerCamelCase__ ( a , a="wiki40b" , a="dense" , a=10 ) -> str: if source == "none": _A , _A: Any = (''' <P> '''.join(['''''' for _ in range(11 )] ).strip(), []) else: if method == "dense": _A , _A: List[Any] = query_qa_dense_index( a , a , a , a , a , a ) else: _A , _A: Tuple = query_es_index( a , a , index_name='''english_wiki40b_snippets_100w''' , n_results=a , ) _A: Union[str, Any] = [ (res['''article_title'''], res['''section_title'''].strip(), res['''score'''], res['''passage_text''']) for res in hit_lst ] _A: str = '''question: {} context: {}'''.format(a , a ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda a : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda a : None), } ) def lowerCamelCase__ ( a , a , a , a=64 , a=2_56 , a=False , a=2 , a=0.95 , a=0.8 ) -> str: with torch.no_grad(): _A: Optional[int] = qa_sas_generate( a , a , a , num_answers=1 , num_beams=a , min_len=a , max_len=a , do_sample=a , temp=a , top_p=a , top_k=a , max_input_length=10_24 , device='''cuda:0''' , )[0] return (answer, support_list) st.title('Long Form Question Answering with ELI5') # Start sidebar UpperCAmelCase__ : List[Any] = '<img src=\'https://huggingface.co/front/assets/huggingface_logo.svg\'>' UpperCAmelCase__ : Optional[Any] = '\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class="img-container"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n' % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia UpperCAmelCase__ : str = '\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n' st.sidebar.markdown(description, unsafe_allow_html=True) UpperCAmelCase__ : str = [ 'Answer the question', 'View the retrieved document only', 'View the most similar ELI5 question and answer', 'Show me everything, please!', ] UpperCAmelCase__ : Optional[int] = st.sidebar.checkbox('Demo options') if demo_options: UpperCAmelCase__ : Any = st.sidebar.selectbox( '', action_list, index=3, ) UpperCAmelCase__ : List[str] = action_list.index(action_st) UpperCAmelCase__ : Optional[Any] = st.sidebar.selectbox( '', ['Show full text of passages', 'Show passage section titles'], index=0, ) UpperCAmelCase__ : List[Any] = show_type == 'Show full text of passages' else: UpperCAmelCase__ : Dict = 3 UpperCAmelCase__ : str = True UpperCAmelCase__ : Optional[Any] = st.sidebar.checkbox('Retrieval options') if retrieval_options: UpperCAmelCase__ : List[str] = '\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n ' st.sidebar.markdown(retriever_info) UpperCAmelCase__ : Optional[int] = st.sidebar.selectbox('Which Wikipedia format should the model use?', ['wiki40b', 'none']) UpperCAmelCase__ : int = st.sidebar.selectbox('Which Wikipedia indexer should the model use?', ['dense', 'sparse', 'mixed']) else: UpperCAmelCase__ : Tuple = 'wiki40b' UpperCAmelCase__ : List[Any] = 'dense' UpperCAmelCase__ : Tuple = 'beam' UpperCAmelCase__ : Any = 2 UpperCAmelCase__ : Dict = 64 UpperCAmelCase__ : Any = 256 UpperCAmelCase__ : int = None UpperCAmelCase__ : List[str] = None UpperCAmelCase__ : Optional[int] = st.sidebar.checkbox('Generation options') if generate_options: UpperCAmelCase__ : Any = '\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder\'s output probabilities.\n ' st.sidebar.markdown(generate_info) UpperCAmelCase__ : Optional[int] = st.sidebar.selectbox('Would you like to use beam search or sample an answer?', ['beam', 'sampled']) UpperCAmelCase__ : int = st.sidebar.slider( 'Minimum generation length', min_value=8, max_value=256, value=64, step=8, format=None, key=None ) UpperCAmelCase__ : str = st.sidebar.slider( 'Maximum generation length', min_value=64, max_value=512, value=256, step=16, format=None, key=None ) if sampled == "beam": UpperCAmelCase__ : Tuple = st.sidebar.slider('Beam size', min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: UpperCAmelCase__ : List[Any] = st.sidebar.slider( 'Nucleus sampling p', min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None ) UpperCAmelCase__ : Union[str, Any] = st.sidebar.slider( 'Temperature', min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None ) UpperCAmelCase__ : Optional[int] = None # start main text UpperCAmelCase__ : Any = [ '<MY QUESTION>', 'How do people make chocolate?', 'Why do we get a fever when we are sick?', 'How can different animals perceive different colors?', 'What is natural language processing?', 'What\'s the best way to treat a sunburn?', 'What exactly are vitamins ?', 'How does nuclear energy provide electricity?', 'What\'s the difference between viruses and bacteria?', 'Why are flutes classified as woodwinds when most of them are made out of metal ?', 'Why do people like drinking coffee even though it tastes so bad?', 'What happens when wine ages? How does it make the wine taste better?', 'If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?', 'How can we set a date to the beginning or end of an artistic period? Doesn\'t the change happen gradually?', 'How does New Zealand have so many large bird predators?', ] UpperCAmelCase__ : List[Any] = st.selectbox( 'What would you like to ask? ---- select <MY QUESTION> to enter a new query', questions_list, index=1, ) if question_s == "<MY QUESTION>": UpperCAmelCase__ : Any = st.text_input('Enter your question here:', '') else: UpperCAmelCase__ : int = question_s if st.button('Show me!'): if action in [0, 1, 3]: if index_type == "mixed": UpperCAmelCase__ ,UpperCAmelCase__ : Tuple = make_support(question, source=wiki_source, method='dense', n_results=10) UpperCAmelCase__ ,UpperCAmelCase__ : Optional[Any] = make_support(question, source=wiki_source, method='sparse', n_results=10) UpperCAmelCase__ : Dict = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] UpperCAmelCase__ : str = support_list[:10] UpperCAmelCase__ : str = '<P> ' + ' <P> '.join([res[-1] for res in support_list]) else: UpperCAmelCase__ ,UpperCAmelCase__ : List[Any] = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: UpperCAmelCase__ ,UpperCAmelCase__ : Optional[Any] = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == 'sampled'), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown('### The model generated answer is:') st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown('--- \n ### The model is drawing information from the following Wikipedia passages:') for i, res in enumerate(support_list): UpperCAmelCase__ : Any = 'https://en.wikipedia.org/wiki/{}'.format(res[0].replace(' ', '_')) UpperCAmelCase__ : Tuple = res[1].strip() if sec_titles == "": UpperCAmelCase__ : Optional[int] = '[{}]({})'.format(res[0], wiki_url) else: UpperCAmelCase__ : int = sec_titles.split(' & ') UpperCAmelCase__ : Union[str, Any] = ' & '.join( ['[{}]({}#{})'.format(sec.strip(), wiki_url, sec.strip().replace(' ', '_')) for sec in sec_list] ) st.markdown( '{0:02d} - **Article**: {1:<18} <br> _Section_: {2}'.format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( '> <span style="font-family:arial; font-size:10pt;">' + res[-1] + '</span>', unsafe_allow_html=True ) if action in [2, 3]: UpperCAmelCase__ : Union[str, Any] = find_nearest_training(question) UpperCAmelCase__ : int = nn_train_list[0] st.markdown( '--- \n ### The most similar question in the ELI5 training set was: \n\n {}'.format(train_exple['title']) ) UpperCAmelCase__ : Tuple = [ '{}. {}'.format(i + 1, ' \n'.join([line.strip() for line in ans.split('\n') if line.strip() != ''])) for i, (ans, sc) in enumerate(zip(train_exple['answers']['text'], train_exple['answers']['score'])) if i == 0 or sc > 2 ] st.markdown('##### Its answers were: \n\n {}'.format('\n'.join(answers_st))) UpperCAmelCase__ : Any = '\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n' st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
301
import os from pathlib import Path def lowerCamelCase__ ( ) -> Optional[Any]: from torch.utils.cpp_extension import load _A: str = Path(a ).resolve().parent.parent.parent / '''kernels''' / '''deformable_detr''' _A: Tuple = [ root / filename for filename in [ '''vision.cpp''', os.path.join('''cpu''' , '''ms_deform_attn_cpu.cpp''' ), os.path.join('''cuda''' , '''ms_deform_attn_cuda.cu''' ), ] ] load( '''MultiScaleDeformableAttention''' , a , with_cuda=a , extra_include_paths=[str(a )] , extra_cflags=['''-DWITH_CUDA=1'''] , extra_cuda_cflags=[ '''-DCUDA_HAS_FP16=1''', '''-D__CUDA_NO_HALF_OPERATORS__''', '''-D__CUDA_NO_HALF_CONVERSIONS__''', '''-D__CUDA_NO_HALF2_OPERATORS__''', ] , ) import MultiScaleDeformableAttention as MSDA return MSDA
301
1
import warnings from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch from ...models import UNetaDModel from ...schedulers import RePaintScheduler from ...utils import PIL_INTERPOLATION, logging, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput UpperCAmelCase__ : List[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name def lowerCamelCase__ ( a ) -> List[Any]: warnings.warn( '''The preprocess method is deprecated and will be removed in a future version. Please''' ''' use VaeImageProcessor.preprocess instead''' , a , ) if isinstance(a , torch.Tensor ): return image elif isinstance(a , PIL.Image.Image ): _A: List[Any] = [image] if isinstance(image[0] , PIL.Image.Image ): _A , _A: Union[str, Any] = image[0].size _A , _A: List[str] = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 _A: List[Any] = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image] _A: str = np.concatenate(a , axis=0 ) _A: Union[str, Any] = np.array(a ).astype(np.floataa ) / 255.0 _A: Optional[int] = image.transpose(0 , 3 , 1 , 2 ) _A: Optional[Any] = 2.0 * image - 1.0 _A: Tuple = torch.from_numpy(a ) elif isinstance(image[0] , torch.Tensor ): _A: str = torch.cat(a , dim=0 ) return image def lowerCamelCase__ ( a ) -> List[Any]: if isinstance(a , torch.Tensor ): return mask elif isinstance(a , PIL.Image.Image ): _A: List[str] = [mask] if isinstance(mask[0] , PIL.Image.Image ): _A , _A: Optional[Any] = mask[0].size _A , _A: Tuple = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 _A: Optional[int] = [np.array(m.convert('''L''' ).resize((w, h) , resample=PIL_INTERPOLATION['''nearest'''] ) )[None, :] for m in mask] _A: Dict = np.concatenate(a , axis=0 ) _A: Optional[Any] = mask.astype(np.floataa ) / 255.0 _A: Any = 0 _A: Any = 1 _A: Tuple = torch.from_numpy(a ) elif isinstance(mask[0] , torch.Tensor ): _A: Any = torch.cat(a , dim=0 ) return mask class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : UNetaDModel __UpperCamelCase : RePaintScheduler def __init__( self : Dict , lowerCAmelCase_ : str , lowerCAmelCase_ : Tuple ): """simple docstring""" super().__init__() self.register_modules(unet=lowerCAmelCase_ , scheduler=lowerCAmelCase_ ) @torch.no_grad() def __call__( self : List[str] , lowerCAmelCase_ : Union[torch.Tensor, PIL.Image.Image] , lowerCAmelCase_ : Union[torch.Tensor, PIL.Image.Image] , lowerCAmelCase_ : int = 2_5_0 , lowerCAmelCase_ : float = 0.0 , lowerCAmelCase_ : int = 1_0 , lowerCAmelCase_ : int = 1_0 , lowerCAmelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowerCAmelCase_ : Optional[str] = "pil" , lowerCAmelCase_ : bool = True , ): """simple docstring""" _A: List[str] = image _A: Optional[Any] = _preprocess_image(lowerCAmelCase_ ) _A: List[Any] = original_image.to(device=self.device , dtype=self.unet.dtype ) _A: List[Any] = _preprocess_mask(lowerCAmelCase_ ) _A: Union[str, Any] = mask_image.to(device=self.device , dtype=self.unet.dtype ) _A: List[str] = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and len(lowerCAmelCase_ ) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(lowerCAmelCase_ )}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) _A: Any = original_image.shape _A: Optional[int] = randn_tensor(lowerCAmelCase_ , generator=lowerCAmelCase_ , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , self.device ) _A: Dict = eta _A: int = self.scheduler.timesteps[0] + 1 _A: List[Any] = generator[0] if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual _A: Union[str, Any] = self.unet(lowerCAmelCase_ , lowerCAmelCase_ ).sample # compute previous image: x_t -> x_t-1 _A: Optional[int] = self.scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ).prev_sample else: # compute the reverse: x_t-1 -> x_t _A: Optional[Any] = self.scheduler.undo_step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) _A: List[Any] = t _A: Dict = (image / 2 + 0.5).clamp(0 , 1 ) _A: Union[str, Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": _A: Any = self.numpy_to_pil(lowerCAmelCase_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCAmelCase_ )
301
from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Optional[int] = ['''image_processor''', '''tokenizer'''] __UpperCamelCase : Optional[Any] = '''BlipImageProcessor''' __UpperCamelCase : int = ('''BertTokenizer''', '''BertTokenizerFast''') def __init__( self : Optional[int] , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" _A: Optional[Any] = False super().__init__(lowerCAmelCase_ , lowerCAmelCase_ ) _A: List[Any] = self.image_processor def __call__( self : Optional[Any] , lowerCAmelCase_ : ImageInput = None , lowerCAmelCase_ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , lowerCAmelCase_ : bool = True , lowerCAmelCase_ : Union[bool, str, PaddingStrategy] = False , lowerCAmelCase_ : Union[bool, str, TruncationStrategy] = None , lowerCAmelCase_ : Optional[int] = None , lowerCAmelCase_ : int = 0 , lowerCAmelCase_ : Optional[int] = None , lowerCAmelCase_ : Optional[bool] = None , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = True , lowerCAmelCase_ : Optional[Union[str, TensorType]] = None , **lowerCAmelCase_ : Union[str, Any] , ): """simple docstring""" if images is None and text is None: raise ValueError('''You have to specify either images or text.''' ) # Get only text if images is None: _A: Tuple = self.tokenizer _A: Optional[int] = self.tokenizer( text=lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ , padding=lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ , stride=lowerCAmelCase_ , pad_to_multiple_of=lowerCAmelCase_ , return_attention_mask=lowerCAmelCase_ , return_overflowing_tokens=lowerCAmelCase_ , return_special_tokens_mask=lowerCAmelCase_ , return_offsets_mapping=lowerCAmelCase_ , return_token_type_ids=lowerCAmelCase_ , return_length=lowerCAmelCase_ , verbose=lowerCAmelCase_ , return_tensors=lowerCAmelCase_ , **lowerCAmelCase_ , ) return text_encoding # add pixel_values _A: List[Any] = self.image_processor(lowerCAmelCase_ , return_tensors=lowerCAmelCase_ ) if text is not None: _A: Tuple = self.tokenizer( text=lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ , padding=lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ , stride=lowerCAmelCase_ , pad_to_multiple_of=lowerCAmelCase_ , return_attention_mask=lowerCAmelCase_ , return_overflowing_tokens=lowerCAmelCase_ , return_special_tokens_mask=lowerCAmelCase_ , return_offsets_mapping=lowerCAmelCase_ , return_token_type_ids=lowerCAmelCase_ , return_length=lowerCAmelCase_ , verbose=lowerCAmelCase_ , return_tensors=lowerCAmelCase_ , **lowerCAmelCase_ , ) else: _A: str = None if text_encoding is not None: encoding_image_processor.update(lowerCAmelCase_ ) return encoding_image_processor def __magic_name__ ( self : Optional[Any] , *lowerCAmelCase_ : Union[str, Any] , **lowerCAmelCase_ : Tuple ): """simple docstring""" return self.tokenizer.batch_decode(*lowerCAmelCase_ , **lowerCAmelCase_ ) def __magic_name__ ( self : Union[str, Any] , *lowerCAmelCase_ : int , **lowerCAmelCase_ : Optional[int] ): """simple docstring""" return self.tokenizer.decode(*lowerCAmelCase_ , **lowerCAmelCase_ ) @property def __magic_name__ ( self : Dict ): """simple docstring""" _A: Dict = self.tokenizer.model_input_names _A: List[str] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
301
1
from math import pi, sqrt def lowerCamelCase__ ( a ) -> float: if num <= 0: raise ValueError('''math domain error''' ) if num > 171.5: raise OverflowError('''math range error''' ) elif num - int(a ) not in (0, 0.5): raise NotImplementedError('''num must be an integer or a half-integer''' ) elif num == 0.5: return sqrt(a ) else: return 1.0 if num == 1 else (num - 1) * gamma(num - 1 ) def lowerCamelCase__ ( ) -> None: assert gamma(0.5 ) == sqrt(a ) assert gamma(1 ) == 1.0 assert gamma(2 ) == 1.0 if __name__ == "__main__": from doctest import testmod testmod() UpperCAmelCase__ : Dict = 1.0 while num: UpperCAmelCase__ : Optional[Any] = float(input('Gamma of: ')) print(F"""gamma({num}) = {gamma(num)}""") print('\nEnter 0 to exit...')
301
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : Union[str, Any] = { 'google/mobilenet_v1_1.0_224': 'https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json', 'google/mobilenet_v1_0.75_192': 'https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 } class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Optional[int] = '''mobilenet_v1''' def __init__( self : Optional[int] , lowerCAmelCase_ : Any=3 , lowerCAmelCase_ : str=2_2_4 , lowerCAmelCase_ : List[str]=1.0 , lowerCAmelCase_ : Any=8 , lowerCAmelCase_ : Tuple="relu6" , lowerCAmelCase_ : List[Any]=True , lowerCAmelCase_ : Optional[int]=0.999 , lowerCAmelCase_ : List[str]=0.02 , lowerCAmelCase_ : List[Any]=0.001 , **lowerCAmelCase_ : Optional[Any] , ): """simple docstring""" super().__init__(**lowerCAmelCase_ ) if depth_multiplier <= 0: raise ValueError('''depth_multiplier must be greater than zero.''' ) _A: Any = num_channels _A: Optional[int] = image_size _A: Optional[Any] = depth_multiplier _A: Tuple = min_depth _A: Any = hidden_act _A: Dict = tf_padding _A: List[Any] = classifier_dropout_prob _A: Tuple = initializer_range _A: Tuple = layer_norm_eps class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Dict = version.parse('''1.11''' ) @property def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" return OrderedDict([('''pixel_values''', {0: '''batch'''})] ) @property def __magic_name__ ( self : Optional[Any] ): """simple docstring""" if self.task == "image-classification": return OrderedDict([('''logits''', {0: '''batch'''})] ) else: return OrderedDict([('''last_hidden_state''', {0: '''batch'''}), ('''pooler_output''', {0: '''batch'''})] ) @property def __magic_name__ ( self : Dict ): """simple docstring""" return 1e-4
301
1
import argparse import json import os from tensorflow.core.protobuf.saved_model_pba import SavedModel # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py UpperCAmelCase__ : Any = '.' # Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model) UpperCAmelCase__ : Optional[Any] = [ 'Assert', 'AssignVariableOp', 'EmptyTensorList', 'MergeV2Checkpoints', 'ReadVariableOp', 'ResourceGather', 'RestoreV2', 'SaveV2', 'ShardedFilename', 'StatefulPartitionedCall', 'StaticRegexFullMatch', 'VarHandleOp', ] def lowerCamelCase__ ( a , a , a ) -> Union[str, Any]: _A: Optional[int] = SavedModel() _A: int = [] with open(os.path.join(a , '''utils''' , '''tf_ops''' , '''onnx.json''' ) ) as f: _A: List[Any] = json.load(a )['''opsets'''] for i in range(1 , opset + 1 ): onnx_ops.extend(onnx_opsets[str(a )] ) with open(a , '''rb''' ) as f: saved_model.ParseFromString(f.read() ) _A: Optional[Any] = set() # Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs) for meta_graph in saved_model.meta_graphs: # Add operations in the graph definition model_op_names.update(node.op for node in meta_graph.graph_def.node ) # Go through the functions in the graph definition for func in meta_graph.graph_def.library.function: # Add operations in each function model_op_names.update(node.op for node in func.node_def ) # Convert to list, sorted if you want _A: Optional[int] = sorted(a ) _A: Tuple = [] for op in model_op_names: if op not in onnx_ops and op not in INTERNAL_OPS: incompatible_ops.append(a ) if strict and len(a ) > 0: raise Exception(f"""Found the following incompatible ops for the opset {opset}:\n""" + incompatible_ops ) elif len(a ) > 0: print(f"""Found the following incompatible ops for the opset {opset}:""" ) print(*a , sep='''\n''' ) else: print(f"""The saved model {saved_model_path} can properly be converted with ONNX.""" ) if __name__ == "__main__": UpperCAmelCase__ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument('--saved_model_path', help='Path of the saved model to check (the .pb file).') parser.add_argument( '--opset', default=12, type=int, help='The ONNX opset against which the model has to be tested.' ) parser.add_argument( '--framework', choices=['onnx'], default='onnx', help='Frameworks against which to test the saved model.' ) parser.add_argument( '--strict', action='store_true', help='Whether make the checking strict (raise errors) or not (raise warnings)' ) UpperCAmelCase__ : int = parser.parse_args() if args.framework == "onnx": onnx_compliancy(args.saved_model_path, args.strict, args.opset)
301
import argparse import json import os from tensorflow.core.protobuf.saved_model_pba import SavedModel # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py UpperCAmelCase__ : Any = '.' # Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model) UpperCAmelCase__ : Optional[Any] = [ 'Assert', 'AssignVariableOp', 'EmptyTensorList', 'MergeV2Checkpoints', 'ReadVariableOp', 'ResourceGather', 'RestoreV2', 'SaveV2', 'ShardedFilename', 'StatefulPartitionedCall', 'StaticRegexFullMatch', 'VarHandleOp', ] def lowerCamelCase__ ( a , a , a ) -> Union[str, Any]: _A: Optional[int] = SavedModel() _A: int = [] with open(os.path.join(a , '''utils''' , '''tf_ops''' , '''onnx.json''' ) ) as f: _A: List[Any] = json.load(a )['''opsets'''] for i in range(1 , opset + 1 ): onnx_ops.extend(onnx_opsets[str(a )] ) with open(a , '''rb''' ) as f: saved_model.ParseFromString(f.read() ) _A: Optional[Any] = set() # Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs) for meta_graph in saved_model.meta_graphs: # Add operations in the graph definition model_op_names.update(node.op for node in meta_graph.graph_def.node ) # Go through the functions in the graph definition for func in meta_graph.graph_def.library.function: # Add operations in each function model_op_names.update(node.op for node in func.node_def ) # Convert to list, sorted if you want _A: Optional[int] = sorted(a ) _A: Tuple = [] for op in model_op_names: if op not in onnx_ops and op not in INTERNAL_OPS: incompatible_ops.append(a ) if strict and len(a ) > 0: raise Exception(f"""Found the following incompatible ops for the opset {opset}:\n""" + incompatible_ops ) elif len(a ) > 0: print(f"""Found the following incompatible ops for the opset {opset}:""" ) print(*a , sep='''\n''' ) else: print(f"""The saved model {saved_model_path} can properly be converted with ONNX.""" ) if __name__ == "__main__": UpperCAmelCase__ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument('--saved_model_path', help='Path of the saved model to check (the .pb file).') parser.add_argument( '--opset', default=12, type=int, help='The ONNX opset against which the model has to be tested.' ) parser.add_argument( '--framework', choices=['onnx'], default='onnx', help='Frameworks against which to test the saved model.' ) parser.add_argument( '--strict', action='store_true', help='Whether make the checking strict (raise errors) or not (raise warnings)' ) UpperCAmelCase__ : int = parser.parse_args() if args.framework == "onnx": onnx_compliancy(args.saved_model_path, args.strict, args.opset)
301
1
from __future__ import annotations UpperCAmelCase__ : Tuple = { 'A': ['B', 'C', 'E'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B', 'D'], 'F': ['C'], 'G': ['C'], } class UpperCAmelCase : '''simple docstring''' def __init__( self : str , lowerCAmelCase_ : dict[str, list[str]] , lowerCAmelCase_ : str ): """simple docstring""" _A: Dict = graph # mapping node to its parent in resulting breadth first tree _A: dict[str, str | None] = {} _A: int = source_vertex def __magic_name__ ( self : Any ): """simple docstring""" _A: List[str] = {self.source_vertex} _A: Optional[int] = None _A: Dict = [self.source_vertex] # first in first out queue while queue: _A: List[Any] = queue.pop(0 ) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(lowerCAmelCase_ ) _A: int = vertex queue.append(lowerCAmelCase_ ) def __magic_name__ ( self : List[Any] , lowerCAmelCase_ : str ): """simple docstring""" if target_vertex == self.source_vertex: return self.source_vertex _A: Union[str, Any] = self.parent.get(lowerCAmelCase_ ) if target_vertex_parent is None: _A: str = ( F"""No path from vertex: {self.source_vertex} to vertex: {target_vertex}""" ) raise ValueError(lowerCAmelCase_ ) return self.shortest_path(lowerCAmelCase_ ) + F"""->{target_vertex}""" if __name__ == "__main__": UpperCAmelCase__ : Optional[Any] = Graph(graph, 'G') g.breath_first_search() print(g.shortest_path('D')) print(g.shortest_path('G')) print(g.shortest_path('Foo'))
301
import json import os from typing import Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ : int = logging.get_logger(__name__) UpperCAmelCase__ : Union[str, Any] = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', } UpperCAmelCase__ : str = { '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__ : Dict = { 'ctrl': 256, } UpperCAmelCase__ : Any = { 'Pregnancy': 168629, 'Christianity': 7675, 'Explain': 106423, 'Fitness': 63440, 'Saving': 63163, 'Ask': 27171, 'Ass': 95985, 'Joke': 163509, 'Questions': 45622, 'Thoughts': 49605, 'Retail': 52342, 'Feminism': 164338, 'Writing': 11992, 'Atheism': 192263, 'Netflix': 48616, 'Computing': 39639, 'Opinion': 43213, 'Alone': 44967, 'Funny': 58917, 'Gaming': 40358, 'Human': 4088, 'India': 1331, 'Joker': 77138, 'Diet': 36206, 'Legal': 11859, 'Norman': 4939, 'Tip': 72689, 'Weight': 52343, 'Movies': 46273, 'Running': 23425, 'Science': 2090, 'Horror': 37793, 'Confession': 60572, 'Finance': 12250, 'Politics': 16360, 'Scary': 191985, 'Support': 12654, 'Technologies': 32516, 'Teenage': 66160, 'Event': 32769, 'Learned': 67460, 'Notion': 182770, 'Wikipedia': 37583, 'Books': 6665, 'Extract': 76050, 'Confessions': 102701, 'Conspiracy': 75932, 'Links': 63674, 'Narcissus': 150425, 'Relationship': 54766, 'Relationships': 134796, 'Reviews': 41671, 'News': 4256, 'Translation': 26820, 'multilingual': 128406, } def lowerCamelCase__ ( a ) -> Optional[Any]: _A: Optional[int] = set() _A: Dict = word[0] for char in word[1:]: pairs.add((prev_char, char) ) _A: Any = char _A: Dict = set(a ) return pairs class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Any = VOCAB_FILES_NAMES __UpperCamelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase : Optional[int] = CONTROL_CODES def __init__( self : Dict , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[Any]="<unk>" , **lowerCAmelCase_ : Optional[int] ): """simple docstring""" super().__init__(unk_token=lowerCAmelCase_ , **lowerCAmelCase_ ) with open(lowerCAmelCase_ , encoding='''utf-8''' ) as vocab_handle: _A: str = json.load(lowerCAmelCase_ ) _A: List[Any] = {v: k for k, v in self.encoder.items()} with open(lowerCAmelCase_ , encoding='''utf-8''' ) as merges_handle: _A: int = merges_handle.read().split('''\n''' )[1:-1] _A: List[Any] = [tuple(merge.split() ) for merge in merges] _A: List[str] = dict(zip(lowerCAmelCase_ , range(len(lowerCAmelCase_ ) ) ) ) _A: Union[str, Any] = {} @property def __magic_name__ ( self : Any ): """simple docstring""" return len(self.encoder ) def __magic_name__ ( self : Dict ): """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def __magic_name__ ( self : List[str] , lowerCAmelCase_ : Tuple ): """simple docstring""" if token in self.cache: return self.cache[token] _A: List[Any] = tuple(lowerCAmelCase_ ) _A: Optional[Any] = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] ) _A: Optional[int] = get_pairs(lowerCAmelCase_ ) if not pairs: return token while True: _A: Optional[int] = min(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : self.bpe_ranks.get(lowerCAmelCase_ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break _A , _A: Any = bigram _A: int = [] _A: int = 0 while i < len(lowerCAmelCase_ ): try: _A: Any = word.index(lowerCAmelCase_ , lowerCAmelCase_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) _A: Optional[int] = j if word[i] == first and i < len(lowerCAmelCase_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 _A: Dict = tuple(lowerCAmelCase_ ) _A: Union[str, Any] = new_word if len(lowerCAmelCase_ ) == 1: break else: _A: Tuple = get_pairs(lowerCAmelCase_ ) _A: Optional[int] = '''@@ '''.join(lowerCAmelCase_ ) _A: List[str] = word[:-4] _A: Optional[Any] = word return word def __magic_name__ ( self : Optional[Any] , lowerCAmelCase_ : Union[str, Any] ): """simple docstring""" _A: List[Any] = [] _A: List[str] = re.findall(R'''\S+\n?''' , lowerCAmelCase_ ) for token in words: split_tokens.extend(list(self.bpe(lowerCAmelCase_ ).split(''' ''' ) ) ) return split_tokens def __magic_name__ ( self : Dict , lowerCAmelCase_ : Optional[int] ): """simple docstring""" return self.encoder.get(lowerCAmelCase_ , self.encoder.get(self.unk_token ) ) def __magic_name__ ( self : Dict , lowerCAmelCase_ : Tuple ): """simple docstring""" return self.decoder.get(lowerCAmelCase_ , self.unk_token ) def __magic_name__ ( self : Any , lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Any = ''' '''.join(lowerCAmelCase_ ).replace('''@@ ''' , '''''' ).strip() return out_string def __magic_name__ ( self : List[str] , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[str] = None ): """simple docstring""" if not os.path.isdir(lowerCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _A: List[str] = os.path.join( lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) _A: List[Any] = os.path.join( lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(lowerCAmelCase_ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=lowerCAmelCase_ , ensure_ascii=lowerCAmelCase_ ) + '''\n''' ) _A: str = 0 with open(lowerCAmelCase_ , '''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 lowerCAmelCase_ : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" ''' Please check that the tokenizer is not corrupted!''' ) _A: Tuple = token_index writer.write(''' '''.join(lowerCAmelCase_ ) + '''\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)
301
1
from __future__ import annotations class UpperCAmelCase : '''simple docstring''' def __init__( self : Dict , lowerCAmelCase_ : list[list[int]] ): """simple docstring""" _A: Any = TypeError( '''Matrices must be formed from a list of zero or more lists containing at ''' '''least one and the same number of values, each of which must be of type ''' '''int or float.''' ) if len(lowerCAmelCase_ ) != 0: _A: Tuple = len(rows[0] ) if cols == 0: raise error for row in rows: if len(lowerCAmelCase_ ) != cols: raise error for value in row: if not isinstance(lowerCAmelCase_ , (int, float) ): raise error _A: int = rows else: _A: Any = [] def __magic_name__ ( self : List[Any] ): """simple docstring""" return [[row[i] for row in self.rows] for i in range(len(self.rows[0] ) )] @property def __magic_name__ ( self : List[Any] ): """simple docstring""" return len(self.rows ) @property def __magic_name__ ( self : Optional[int] ): """simple docstring""" return len(self.rows[0] ) @property def __magic_name__ ( self : Any ): """simple docstring""" return (self.num_rows, self.num_columns) @property def __magic_name__ ( self : Tuple ): """simple docstring""" return self.order[0] == self.order[1] def __magic_name__ ( self : Optional[int] ): """simple docstring""" _A: Dict = [ [0 if column_num != row_num else 1 for column_num in range(self.num_rows )] for row_num in range(self.num_rows ) ] return Matrix(lowerCAmelCase_ ) def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" if not self.is_square: return 0 if self.order == (0, 0): return 1 if self.order == (1, 1): return int(self.rows[0][0] ) if self.order == (2, 2): return int( (self.rows[0][0] * self.rows[1][1]) - (self.rows[0][1] * self.rows[1][0]) ) else: return sum( self.rows[0][column] * self.cofactors().rows[0][column] for column in range(self.num_columns ) ) def __magic_name__ ( self : Any ): """simple docstring""" return bool(self.determinant() ) def __magic_name__ ( self : Tuple , lowerCAmelCase_ : int , lowerCAmelCase_ : int ): """simple docstring""" _A: Union[str, Any] = [ [ self.rows[other_row][other_column] for other_column in range(self.num_columns ) if other_column != column ] for other_row in range(self.num_rows ) if other_row != row ] return Matrix(lowerCAmelCase_ ).determinant() def __magic_name__ ( self : Optional[int] , lowerCAmelCase_ : int , lowerCAmelCase_ : int ): """simple docstring""" if (row + column) % 2 == 0: return self.get_minor(lowerCAmelCase_ , lowerCAmelCase_ ) return -1 * self.get_minor(lowerCAmelCase_ , lowerCAmelCase_ ) def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" return Matrix( [ [self.get_minor(lowerCAmelCase_ , lowerCAmelCase_ ) for column in range(self.num_columns )] for row in range(self.num_rows ) ] ) def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" return Matrix( [ [ self.minors().rows[row][column] if (row + column) % 2 == 0 else self.minors().rows[row][column] * -1 for column in range(self.minors().num_columns ) ] for row in range(self.minors().num_rows ) ] ) def __magic_name__ ( self : Dict ): """simple docstring""" _A: Union[str, Any] = [ [self.cofactors().rows[column][row] for column in range(self.num_columns )] for row in range(self.num_rows ) ] return Matrix(lowerCAmelCase_ ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" _A: str = self.determinant() if not determinant: raise TypeError('''Only matrices with a non-zero determinant have an inverse''' ) return self.adjugate() * (1 / determinant) def __repr__( self : Optional[int] ): """simple docstring""" return str(self.rows ) def __str__( self : Dict ): """simple docstring""" if self.num_rows == 0: return "[]" if self.num_rows == 1: return "[[" + ". ".join(str(self.rows[0] ) ) + "]]" return ( "[" + "\n ".join( [ '''[''' + '''. '''.join([str(lowerCAmelCase_ ) for value in row] ) + '''.]''' for row in self.rows ] ) + "]" ) def __magic_name__ ( self : Any , lowerCAmelCase_ : list[int] , lowerCAmelCase_ : int | None = None ): """simple docstring""" _A: Any = TypeError('''Row must be a list containing all ints and/or floats''' ) if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise type_error for value in row: if not isinstance(lowerCAmelCase_ , (int, float) ): raise type_error if len(lowerCAmelCase_ ) != self.num_columns: raise ValueError( '''Row must be equal in length to the other rows in the matrix''' ) if position is None: self.rows.append(lowerCAmelCase_ ) else: _A: Optional[int] = self.rows[0:position] + [row] + self.rows[position:] def __magic_name__ ( self : Union[str, Any] , lowerCAmelCase_ : list[int] , lowerCAmelCase_ : int | None = None ): """simple docstring""" _A: List[str] = TypeError( '''Column must be a list containing all ints and/or floats''' ) if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise type_error for value in column: if not isinstance(lowerCAmelCase_ , (int, float) ): raise type_error if len(lowerCAmelCase_ ) != self.num_rows: raise ValueError( '''Column must be equal in length to the other columns in the matrix''' ) if position is None: _A: Optional[int] = [self.rows[i] + [column[i]] for i in range(self.num_rows )] else: _A: Any = [ self.rows[i][0:position] + [column[i]] + self.rows[i][position:] for i in range(self.num_rows ) ] def __eq__( self : str , lowerCAmelCase_ : object ): """simple docstring""" if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return NotImplemented return self.rows == other.rows def __ne__( self : Optional[int] , lowerCAmelCase_ : object ): """simple docstring""" return not self == other def __neg__( self : Tuple ): """simple docstring""" return self * -1 def __add__( self : Tuple , lowerCAmelCase_ : Matrix ): """simple docstring""" if self.order != other.order: raise ValueError('''Addition requires matrices of the same order''' ) return Matrix( [ [self.rows[i][j] + other.rows[i][j] for j in range(self.num_columns )] for i in range(self.num_rows ) ] ) def __sub__( self : Optional[Any] , lowerCAmelCase_ : Matrix ): """simple docstring""" if self.order != other.order: raise ValueError('''Subtraction requires matrices of the same order''' ) return Matrix( [ [self.rows[i][j] - other.rows[i][j] for j in range(self.num_columns )] for i in range(self.num_rows ) ] ) def __mul__( self : int , lowerCAmelCase_ : Matrix | int | float ): """simple docstring""" if isinstance(lowerCAmelCase_ , (int, float) ): return Matrix( [[int(element * other ) for element in row] for row in self.rows] ) elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): if self.num_columns != other.num_rows: raise ValueError( '''The number of columns in the first matrix must ''' '''be equal to the number of rows in the second''' ) return Matrix( [ [Matrix.dot_product(lowerCAmelCase_ , lowerCAmelCase_ ) for column in other.columns()] for row in self.rows ] ) else: raise TypeError( '''A Matrix can only be multiplied by an int, float, or another matrix''' ) def __pow__( self : Union[str, Any] , lowerCAmelCase_ : int ): """simple docstring""" if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError('''A Matrix can only be raised to the power of an int''' ) if not self.is_square: raise ValueError('''Only square matrices can be raised to a power''' ) if other == 0: return self.identity() if other < 0: if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( '''Only invertable matrices can be raised to a negative power''' ) _A: int = self for _ in range(other - 1 ): result *= self return result @classmethod def __magic_name__ ( cls : Dict , lowerCAmelCase_ : list[int] , lowerCAmelCase_ : list[int] ): """simple docstring""" return sum(row[i] * column[i] for i in range(len(lowerCAmelCase_ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
301
def lowerCamelCase__ ( a = 10 ) -> str: if not isinstance(a , a ) or n < 0: raise ValueError('''Invalid input''' ) _A: int = 10**n _A: List[Any] = 2_84_33 * (pow(2 , 7_83_04_57 , a )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(F"""{solution(10) = }""")
301
1
import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Dict = ShapEImgaImgPipeline __UpperCamelCase : int = ['''image'''] __UpperCamelCase : Any = ['''image'''] __UpperCamelCase : List[str] = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] __UpperCamelCase : List[str] = False @property def __magic_name__ ( self : str ): """simple docstring""" return 3_2 @property def __magic_name__ ( self : Tuple ): """simple docstring""" return 3_2 @property def __magic_name__ ( self : Any ): """simple docstring""" return self.time_input_dim * 4 @property def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" return 8 @property def __magic_name__ ( self : Optional[Any] ): """simple docstring""" torch.manual_seed(0 ) _A: Optional[int] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=6_4 , projection_dim=self.text_embedder_hidden_size , intermediate_size=3_7 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) _A: str = CLIPVisionModel(lowerCAmelCase_ ) return model @property def __magic_name__ ( self : List[Any] ): """simple docstring""" _A: Any = CLIPImageProcessor( crop_size=2_2_4 , do_center_crop=lowerCAmelCase_ , do_normalize=lowerCAmelCase_ , do_resize=lowerCAmelCase_ , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=2_2_4 , ) return image_processor @property def __magic_name__ ( self : int ): """simple docstring""" torch.manual_seed(0 ) _A: Optional[Any] = { '''num_attention_heads''': 2, '''attention_head_dim''': 1_6, '''embedding_dim''': self.time_input_dim, '''num_embeddings''': 3_2, '''embedding_proj_dim''': self.text_embedder_hidden_size, '''time_embed_dim''': self.time_embed_dim, '''num_layers''': 1, '''clip_embed_dim''': self.time_input_dim * 2, '''additional_embeddings''': 0, '''time_embed_act_fn''': '''gelu''', '''norm_in_type''': '''layer''', '''embedding_proj_norm_type''': '''layer''', '''encoder_hid_proj_type''': None, '''added_emb_type''': None, } _A: Optional[Any] = PriorTransformer(**lowerCAmelCase_ ) return model @property def __magic_name__ ( self : Optional[int] ): """simple docstring""" torch.manual_seed(0 ) _A: Dict = { '''param_shapes''': ( (self.renderer_dim, 9_3), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), '''d_latent''': self.time_input_dim, '''d_hidden''': self.renderer_dim, '''n_output''': 1_2, '''background''': ( 0.1, 0.1, 0.1, ), } _A: Dict = ShapERenderer(**lowerCAmelCase_ ) return model def __magic_name__ ( self : List[Any] ): """simple docstring""" _A: Union[str, Any] = self.dummy_prior _A: Tuple = self.dummy_image_encoder _A: Tuple = self.dummy_image_processor _A: List[str] = self.dummy_renderer _A: Union[str, Any] = HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=1_0_2_4 , prediction_type='''sample''' , use_karras_sigmas=lowerCAmelCase_ , clip_sample=lowerCAmelCase_ , clip_sample_range=1.0 , ) _A: List[str] = { '''prior''': prior, '''image_encoder''': image_encoder, '''image_processor''': image_processor, '''renderer''': renderer, '''scheduler''': scheduler, } return components def __magic_name__ ( self : Any , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Tuple=0 ): """simple docstring""" _A: Any = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(lowerCAmelCase_ ) ).to(lowerCAmelCase_ ) if str(lowerCAmelCase_ ).startswith('''mps''' ): _A: Union[str, Any] = torch.manual_seed(lowerCAmelCase_ ) else: _A: Optional[int] = torch.Generator(device=lowerCAmelCase_ ).manual_seed(lowerCAmelCase_ ) _A: Optional[int] = { '''image''': input_image, '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 3_2, '''output_type''': '''np''', } return inputs def __magic_name__ ( self : str ): """simple docstring""" _A: int = '''cpu''' _A: int = self.get_dummy_components() _A: int = self.pipeline_class(**lowerCAmelCase_ ) _A: Dict = pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _A: List[str] = pipe(**self.get_dummy_inputs(lowerCAmelCase_ ) ) _A: Any = output.images[0] _A: str = image[0, -3:, -3:, -1] assert image.shape == (2_0, 3_2, 3_2, 3) _A: Dict = np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __magic_name__ ( self : Optional[int] ): """simple docstring""" # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" _A: str = torch_device == '''cpu''' _A: int = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=lowerCAmelCase_ , relax_max_difference=lowerCAmelCase_ , ) def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" _A: Dict = self.get_dummy_components() _A: Union[str, Any] = self.pipeline_class(**lowerCAmelCase_ ) _A: Optional[Any] = pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _A: Any = 1 _A: Dict = 2 _A: int = self.get_dummy_inputs(lowerCAmelCase_ ) for key in inputs.keys(): if key in self.batch_params: _A: Optional[int] = batch_size * [inputs[key]] _A: str = pipe(**lowerCAmelCase_ , num_images_per_prompt=lowerCAmelCase_ )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __magic_name__ ( self : int ): """simple docstring""" _A: Dict = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/corgi.png''' ) _A: List[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_img2img_out.npy''' ) _A: Dict = ShapEImgaImgPipeline.from_pretrained('''openai/shap-e-img2img''' ) _A: Optional[int] = pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _A: Dict = torch.Generator(device=lowerCAmelCase_ ).manual_seed(0 ) _A: Optional[Any] = pipe( lowerCAmelCase_ , generator=lowerCAmelCase_ , guidance_scale=3.0 , num_inference_steps=6_4 , frame_size=6_4 , output_type='''np''' , ).images[0] assert images.shape == (2_0, 6_4, 6_4, 3) assert_mean_pixel_difference(lowerCAmelCase_ , lowerCAmelCase_ )
301
from __future__ import annotations import unittest from transformers import AutoTokenizer, MBartConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel @require_tf class UpperCAmelCase : '''simple docstring''' __UpperCamelCase : Any = MBartConfig __UpperCamelCase : Tuple = {} __UpperCamelCase : Dict = '''gelu''' def __init__( self : Dict , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : List[Any]=1_3 , lowerCAmelCase_ : Dict=7 , lowerCAmelCase_ : Optional[Any]=True , lowerCAmelCase_ : Optional[Any]=False , lowerCAmelCase_ : Union[str, Any]=9_9 , lowerCAmelCase_ : Dict=3_2 , lowerCAmelCase_ : str=2 , lowerCAmelCase_ : int=4 , lowerCAmelCase_ : Union[str, Any]=3_7 , lowerCAmelCase_ : Dict=0.1 , lowerCAmelCase_ : str=0.1 , lowerCAmelCase_ : List[str]=2_0 , lowerCAmelCase_ : str=2 , lowerCAmelCase_ : Optional[int]=1 , lowerCAmelCase_ : List[Any]=0 , ): """simple docstring""" _A: Union[str, Any] = parent _A: List[Any] = batch_size _A: Dict = seq_length _A: Dict = is_training _A: str = use_labels _A: int = vocab_size _A: str = hidden_size _A: Tuple = num_hidden_layers _A: Optional[Any] = num_attention_heads _A: Tuple = intermediate_size _A: int = hidden_dropout_prob _A: Tuple = attention_probs_dropout_prob _A: Tuple = max_position_embeddings _A: Dict = eos_token_id _A: int = pad_token_id _A: Any = bos_token_id def __magic_name__ ( self : Dict ): """simple docstring""" _A: Optional[int] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _A: Dict = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _A: List[Any] = tf.concat([input_ids, eos_tensor] , axis=1 ) _A: Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _A: int = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) _A: Any = prepare_mbart_inputs_dict(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return config, inputs_dict def __magic_name__ ( self : Union[str, Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : List[str] ): """simple docstring""" _A: Tuple = TFMBartModel(config=lowerCAmelCase_ ).get_decoder() _A: List[str] = inputs_dict['''input_ids'''] _A: Tuple = input_ids[:1, :] _A: List[Any] = inputs_dict['''attention_mask'''][:1, :] _A: str = inputs_dict['''head_mask'''] _A: Optional[Any] = 1 # first forward pass _A: Any = model(lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , head_mask=lowerCAmelCase_ , use_cache=lowerCAmelCase_ ) _A , _A: List[str] = outputs.to_tuple() _A: Dict = past_key_values[1] def lowerCamelCase__ ( a , a , a , a=None , a=None , a=None , a=None , a=None , ) -> Tuple: if attention_mask is None: _A: Union[str, Any] = tf.cast(tf.math.not_equal(a , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: _A: Optional[int] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: _A: Tuple = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _A: Union[str, Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: _A: Optional[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Union[str, Any] = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else () __UpperCamelCase : int = (TFMBartForConditionalGeneration,) if is_tf_available() else () __UpperCamelCase : Tuple = ( { '''conversational''': TFMBartForConditionalGeneration, '''feature-extraction''': TFMBartModel, '''summarization''': TFMBartForConditionalGeneration, '''text2text-generation''': TFMBartForConditionalGeneration, '''translation''': TFMBartForConditionalGeneration, } if is_tf_available() else {} ) __UpperCamelCase : List[Any] = True __UpperCamelCase : int = False __UpperCamelCase : Optional[Any] = False def __magic_name__ ( self : int , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : int , lowerCAmelCase_ : str , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : int ): """simple docstring""" if pipeline_test_casse_name != "FeatureExtractionPipelineTests": # Exception encountered when calling layer '...' return True return False def __magic_name__ ( self : Any ): """simple docstring""" _A: Dict = TFMBartModelTester(self ) _A: Tuple = ConfigTester(self , config_class=lowerCAmelCase_ ) def __magic_name__ ( self : List[str] ): """simple docstring""" self.config_tester.run_common_tests() def __magic_name__ ( self : Optional[Any] ): """simple docstring""" _A: str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*lowerCAmelCase_ ) @require_sentencepiece @require_tokenizers @require_tf class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Optional[int] = [ ''' UN Chief Says There Is No Military Solution in Syria''', ] __UpperCamelCase : List[str] = [ '''Şeful ONU declară că nu există o soluţie militară în Siria''', ] __UpperCamelCase : Union[str, Any] = '''facebook/mbart-large-en-ro''' @cached_property def __magic_name__ ( self : Tuple ): """simple docstring""" return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def __magic_name__ ( self : str ): """simple docstring""" _A: Union[str, Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def __magic_name__ ( self : Union[str, Any] , **lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Optional[Any] = self.translate_src_text(**lowerCAmelCase_ ) self.assertListEqual(self.expected_text , lowerCAmelCase_ ) def __magic_name__ ( self : Dict , **lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Any = self.tokenizer(self.src_text , **lowerCAmelCase_ , return_tensors='''tf''' ) _A: Any = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 ) _A: Optional[Any] = self.tokenizer.batch_decode(lowerCAmelCase_ , skip_special_tokens=lowerCAmelCase_ ) return generated_words @slow def __magic_name__ ( self : List[str] ): """simple docstring""" self._assert_generated_batch_equal_expected()
301
1
import os import pytest from datasets import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, ) UpperCAmelCase__ : Any = pytest.mark.integration @pytest.mark.parametrize('''path''' , ['''paws''', '''csv'''] ) def lowerCamelCase__ ( a , a ) -> Any: inspect_dataset(a , a ) _A: Any = path + '''.py''' assert script_name in os.listdir(a ) assert "__pycache__" not in os.listdir(a ) @pytest.mark.filterwarnings('''ignore:inspect_metric is deprecated:FutureWarning''' ) @pytest.mark.filterwarnings('''ignore:metric_module_factory is deprecated:FutureWarning''' ) @pytest.mark.parametrize('''path''' , ['''accuracy'''] ) def lowerCamelCase__ ( a , a ) -> Tuple: inspect_metric(a , a ) _A: str = path + '''.py''' assert script_name in os.listdir(a ) assert "__pycache__" not in os.listdir(a ) @pytest.mark.parametrize( '''path, config_name, expected_splits''' , [ ('''squad''', '''plain_text''', ['''train''', '''validation''']), ('''dalle-mini/wit''', '''dalle-mini--wit''', ['''train''']), ('''paws''', '''labeled_final''', ['''train''', '''test''', '''validation''']), ] , ) def lowerCamelCase__ ( a , a , a ) -> List[Any]: _A: int = get_dataset_config_info(a , config_name=a ) assert info.config_name == config_name assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( '''path, config_name, expected_exception''' , [ ('''paws''', None, ValueError), ] , ) def lowerCamelCase__ ( a , a , a ) -> Union[str, Any]: with pytest.raises(a ): get_dataset_config_info(a , config_name=a ) @pytest.mark.parametrize( '''path, expected''' , [ ('''squad''', '''plain_text'''), ('''acronym_identification''', '''default'''), ('''lhoestq/squad''', '''plain_text'''), ('''lhoestq/test''', '''default'''), ('''lhoestq/demo1''', '''lhoestq--demo1'''), ('''dalle-mini/wit''', '''dalle-mini--wit'''), ] , ) def lowerCamelCase__ ( a , a ) -> Optional[Any]: _A: Optional[Any] = get_dataset_config_names(a ) assert expected in config_names @pytest.mark.parametrize( '''path, expected_configs, expected_splits_in_first_config''' , [ ('''squad''', ['''plain_text'''], ['''train''', '''validation''']), ('''dalle-mini/wit''', ['''dalle-mini--wit'''], ['''train''']), ('''paws''', ['''labeled_final''', '''labeled_swap''', '''unlabeled_final'''], ['''train''', '''test''', '''validation''']), ] , ) def lowerCamelCase__ ( a , a , a ) -> Tuple: _A: List[Any] = get_dataset_infos(a ) assert list(infos.keys() ) == expected_configs _A: Union[str, Any] = expected_configs[0] assert expected_config in infos _A: Any = infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits_in_first_config @pytest.mark.parametrize( '''path, expected_config, expected_splits''' , [ ('''squad''', '''plain_text''', ['''train''', '''validation''']), ('''dalle-mini/wit''', '''dalle-mini--wit''', ['''train''']), ('''paws''', '''labeled_final''', ['''train''', '''test''', '''validation''']), ] , ) def lowerCamelCase__ ( a , a , a ) -> List[Any]: _A: Any = get_dataset_infos(a ) assert expected_config in infos _A: str = infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( '''path, config_name, expected_exception''' , [ ('''paws''', None, ValueError), ] , ) def lowerCamelCase__ ( a , a , a ) -> Optional[Any]: with pytest.raises(a ): get_dataset_split_names(a , config_name=a )
301
from typing import TYPE_CHECKING from ..utils import _LazyModule UpperCAmelCase__ : Tuple = { 'config': [ 'EXTERNAL_DATA_FORMAT_SIZE_LIMIT', 'OnnxConfig', 'OnnxConfigWithPast', 'OnnxSeq2SeqConfigWithPast', 'PatchingSpec', ], 'convert': ['export', 'validate_model_outputs'], 'features': ['FeaturesManager'], 'utils': ['ParameterFormat', 'compute_serialized_parameters_size'], } if TYPE_CHECKING: from .config import ( EXTERNAL_DATA_FORMAT_SIZE_LIMIT, OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast, PatchingSpec, ) from .convert import export, validate_model_outputs from .features import FeaturesManager from .utils import ParameterFormat, compute_serialized_parameters_size else: import sys UpperCAmelCase__ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
301
1
import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, PerceiverTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): UpperCAmelCase__ : Union[str, Any] = 'pt' elif is_tf_available(): UpperCAmelCase__ : int = 'tf' else: UpperCAmelCase__ : Any = 'jax' class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Optional[int] = PerceiverTokenizer __UpperCamelCase : Tuple = False def __magic_name__ ( self : Tuple ): """simple docstring""" super().setUp() _A: int = PerceiverTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __magic_name__ ( self : Optional[int] ): """simple docstring""" return PerceiverTokenizer.from_pretrained('''deepmind/language-perceiver''' ) def __magic_name__ ( self : Dict , **lowerCAmelCase_ : Optional[Any] ): """simple docstring""" return self.tokenizer_class.from_pretrained(self.tmpdirname , **lowerCAmelCase_ ) def __magic_name__ ( self : int , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : str=False , lowerCAmelCase_ : str=2_0 , lowerCAmelCase_ : Dict=5 ): """simple docstring""" # XXX The default common tokenizer tests assume that every ID is decodable on its own. # This assumption is invalid for Perceiver because single bytes might not be # valid utf-8 (byte 128 for instance). # Here we're overriding the smallest possible method to provide # a clean sequence without making the same assumption. _A: List[Any] = [] for i in range(len(lowerCAmelCase_ ) ): try: _A: Dict = tokenizer.decode([i] , clean_up_tokenization_spaces=lowerCAmelCase_ ) except UnicodeDecodeError: pass toks.append((i, tok) ) _A: str = list(filter(lambda lowerCAmelCase_ : re.match(R'''^[ a-zA-Z]+$''' , t[1] ) , lowerCAmelCase_ ) ) _A: Union[str, Any] = list(filter(lambda lowerCAmelCase_ : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=lowerCAmelCase_ ) , lowerCAmelCase_ ) ) if max_length is not None and len(lowerCAmelCase_ ) > max_length: _A: Tuple = toks[:max_length] if min_length is not None and len(lowerCAmelCase_ ) < min_length and len(lowerCAmelCase_ ) > 0: while len(lowerCAmelCase_ ) < min_length: _A: Dict = toks + toks # toks_str = [t[1] for t in toks] _A: Tuple = [t[0] for t in toks] # Ensure consistency _A: str = tokenizer.decode(lowerCAmelCase_ , clean_up_tokenization_spaces=lowerCAmelCase_ ) if " " not in output_txt and len(lowerCAmelCase_ ) > 1: _A: Optional[Any] = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=lowerCAmelCase_ ) + ''' ''' + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=lowerCAmelCase_ ) ) if with_prefix_space: _A: Optional[int] = ''' ''' + output_txt _A: List[Any] = tokenizer.encode(lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ ) return output_txt, output_ids def __magic_name__ ( self : Optional[Any] ): """simple docstring""" _A: List[Any] = self.perceiver_tokenizer _A: Dict = '''Unicode €.''' _A: str = tokenizer(lowerCAmelCase_ ) _A: Tuple = [4, 9_1, 1_1_6, 1_1_1, 1_0_5, 1_1_7, 1_0_6, 1_0_7, 3_8, 2_3_2, 1_3_6, 1_7_8, 5_2, 5] self.assertEqual(encoded['''input_ids'''] , lowerCAmelCase_ ) # decoding _A: str = tokenizer.decode(lowerCAmelCase_ ) self.assertEqual(lowerCAmelCase_ , '''[CLS]Unicode €.[SEP]''' ) _A: Dict = tokenizer('''e è é ê ë''' ) _A: Dict = [4, 1_0_7, 3_8, 2_0_1, 1_7_4, 3_8, 2_0_1, 1_7_5, 3_8, 2_0_1, 1_7_6, 3_8, 2_0_1, 1_7_7, 5] self.assertEqual(encoded['''input_ids'''] , lowerCAmelCase_ ) # decoding _A: int = tokenizer.decode(lowerCAmelCase_ ) self.assertEqual(lowerCAmelCase_ , '''[CLS]e è é ê ë[SEP]''' ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('''e è é ê ë''' ) ) , '''[CLS]e è é ê ë[SEP]''' ) def __magic_name__ ( self : Any ): """simple docstring""" _A: List[str] = self.perceiver_tokenizer _A: Optional[int] = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] # fmt: off _A: List[str] = [4, 7_1, 3_8, 1_1_4, 1_1_7, 1_1_6, 1_0_9, 3_8, 1_1_8, 1_0_3, 1_2_0, 1_0_3, 1_0_9, 1_2_0, 1_0_3, 1_1_8, 1_1_0, 3_8, 1_0_8, 1_1_7, 1_2_0, 3_8, 1_2_1, 1_2_3, 1_1_5, 1_1_5, 1_0_3, 1_2_0, 1_1_1, 1_2_8, 1_0_3, 1_2_2, 1_1_1, 1_1_7, 1_1_6, 5_2, 5, 0] # fmt: on _A: str = tokenizer(lowerCAmelCase_ , padding=lowerCAmelCase_ , return_tensors=lowerCAmelCase_ ) self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ ) if FRAMEWORK != "jax": _A: Tuple = list(batch.input_ids.numpy()[0] ) else: _A: Tuple = list(batch.input_ids.tolist()[0] ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertEqual((2, 3_8) , batch.input_ids.shape ) self.assertEqual((2, 3_8) , batch.attention_mask.shape ) def __magic_name__ ( self : int ): """simple docstring""" _A: List[Any] = self.perceiver_tokenizer _A: List[Any] = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] _A: Union[str, Any] = tokenizer(lowerCAmelCase_ , padding=lowerCAmelCase_ , return_tensors=lowerCAmelCase_ ) # check if input_ids are returned and no decoder_input_ids self.assertIn('''input_ids''' , lowerCAmelCase_ ) self.assertIn('''attention_mask''' , lowerCAmelCase_ ) self.assertNotIn('''decoder_input_ids''' , lowerCAmelCase_ ) self.assertNotIn('''decoder_attention_mask''' , lowerCAmelCase_ ) def __magic_name__ ( self : int ): """simple docstring""" _A: List[Any] = self.perceiver_tokenizer _A: Tuple = [ '''Summary of the text.''', '''Another summary.''', ] _A: str = tokenizer( text_target=lowerCAmelCase_ , max_length=3_2 , padding='''max_length''' , truncation=lowerCAmelCase_ , return_tensors=lowerCAmelCase_ ) self.assertEqual(3_2 , targets['''input_ids'''].shape[1] ) def __magic_name__ ( self : List[str] ): """simple docstring""" # safety check on max_len default value so we are sure the test works _A: Optional[int] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): self.assertNotEqual(tokenizer.model_max_length , 4_2 ) # Now let's start the test _A: str = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): # Isolate this from the other tests because we save additional tokens/etc _A: str = tempfile.mkdtemp() _A: Dict = ''' He is very happy, UNwant\u00E9d,running''' _A: Union[str, Any] = tokenizer.encode(lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ ) tokenizer.save_pretrained(lowerCAmelCase_ ) _A: List[Any] = tokenizer.__class__.from_pretrained(lowerCAmelCase_ ) _A: str = after_tokenizer.encode(lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) shutil.rmtree(lowerCAmelCase_ ) _A: List[str] = self.get_tokenizers(model_max_length=4_2 ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): # Isolate this from the other tests because we save additional tokens/etc _A: List[Any] = tempfile.mkdtemp() _A: Optional[int] = ''' He is very happy, UNwant\u00E9d,running''' tokenizer.add_tokens(['''bim''', '''bambam'''] ) _A: Dict = tokenizer.additional_special_tokens additional_special_tokens.append('''new_additional_special_token''' ) tokenizer.add_special_tokens({'''additional_special_tokens''': additional_special_tokens} ) _A: List[str] = tokenizer.encode(lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ ) tokenizer.save_pretrained(lowerCAmelCase_ ) _A: int = tokenizer.__class__.from_pretrained(lowerCAmelCase_ ) _A: Union[str, Any] = after_tokenizer.encode(lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertIn('''new_additional_special_token''' , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 4_2 ) _A: Optional[Any] = tokenizer.__class__.from_pretrained(lowerCAmelCase_ , model_max_length=4_3 ) self.assertEqual(tokenizer.model_max_length , 4_3 ) shutil.rmtree(lowerCAmelCase_ ) def __magic_name__ ( self : int ): """simple docstring""" _A: Optional[Any] = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(lowerCAmelCase_ ) with open(os.path.join(lowerCAmelCase_ , '''special_tokens_map.json''' ) , encoding='''utf-8''' ) as json_file: _A: str = json.load(lowerCAmelCase_ ) with open(os.path.join(lowerCAmelCase_ , '''tokenizer_config.json''' ) , encoding='''utf-8''' ) as json_file: _A: Optional[int] = json.load(lowerCAmelCase_ ) _A: Any = [F"""<extra_id_{i}>""" for i in range(1_2_5 )] _A: Union[str, Any] = added_tokens_extra_ids + [ '''an_additional_special_token''' ] _A: Optional[int] = added_tokens_extra_ids + [ '''an_additional_special_token''' ] with open(os.path.join(lowerCAmelCase_ , '''special_tokens_map.json''' ) , '''w''' , encoding='''utf-8''' ) as outfile: json.dump(lowerCAmelCase_ , lowerCAmelCase_ ) with open(os.path.join(lowerCAmelCase_ , '''tokenizer_config.json''' ) , '''w''' , encoding='''utf-8''' ) as outfile: json.dump(lowerCAmelCase_ , lowerCAmelCase_ ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files _A: Any = tokenizer_class.from_pretrained( lowerCAmelCase_ , ) self.assertIn( '''an_additional_special_token''' , tokenizer_without_change_in_init.additional_special_tokens ) self.assertEqual( ['''an_additional_special_token'''] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(['''an_additional_special_token'''] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained _A: Tuple = added_tokens_extra_ids + [AddedToken('''a_new_additional_special_token''' , lstrip=lowerCAmelCase_ )] _A: Optional[Any] = tokenizer_class.from_pretrained( lowerCAmelCase_ , additional_special_tokens=lowerCAmelCase_ , ) self.assertIn('''a_new_additional_special_token''' , tokenizer.additional_special_tokens ) self.assertEqual( ['''a_new_additional_special_token'''] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(['''a_new_additional_special_token'''] ) ) , ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" _A: Optional[Any] = self.perceiver_tokenizer self.assertEqual(tokenizer.decode([1_7_8] ) , '''�''' ) def __magic_name__ ( self : Any ): """simple docstring""" pass def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" pass def __magic_name__ ( self : List[str] ): """simple docstring""" pass def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" pass def __magic_name__ ( self : List[str] ): """simple docstring""" # The default common tokenizer tests uses invalid tokens for Perceiver that can only accept one-character # strings and special added tokens as tokens _A: Any = self.get_tokenizers(fast=lowerCAmelCase_ , do_lower_case=lowerCAmelCase_ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): _A: int = ['''[CLS]''', '''t''', '''h''', '''i''', '''s''', ''' ''', '''i''', '''s''', ''' ''', '''a''', ''' ''', '''t''', '''e''', '''s''', '''t''', '''[SEP]'''] _A: Dict = tokenizer.convert_tokens_to_string(lowerCAmelCase_ ) self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ )
301
import torch from diffusers import DDPMParallelScheduler from .test_schedulers import SchedulerCommonTest class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Any = (DDPMParallelScheduler,) def __magic_name__ ( self : Optional[int] , **lowerCAmelCase_ : Any ): """simple docstring""" _A: Optional[int] = { '''num_train_timesteps''': 1_0_0_0, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''variance_type''': '''fixed_small''', '''clip_sample''': True, } config.update(**lowerCAmelCase_ ) return config def __magic_name__ ( self : int ): """simple docstring""" for timesteps in [1, 5, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=lowerCAmelCase_ ) def __magic_name__ ( self : Tuple ): """simple docstring""" for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=lowerCAmelCase_ , beta_end=lowerCAmelCase_ ) def __magic_name__ ( self : Optional[Any] ): """simple docstring""" for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=lowerCAmelCase_ ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=lowerCAmelCase_ ) def __magic_name__ ( self : Tuple ): """simple docstring""" for clip_sample in [True, False]: self.check_over_configs(clip_sample=lowerCAmelCase_ ) def __magic_name__ ( self : List[str] ): """simple docstring""" self.check_over_configs(thresholding=lowerCAmelCase_ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=lowerCAmelCase_ , prediction_type=lowerCAmelCase_ , sample_max_value=lowerCAmelCase_ , ) def __magic_name__ ( self : Dict ): """simple docstring""" for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=lowerCAmelCase_ ) def __magic_name__ ( self : int ): """simple docstring""" for t in [0, 5_0_0, 9_9_9]: self.check_over_forward(time_step=lowerCAmelCase_ ) def __magic_name__ ( self : Any ): """simple docstring""" _A: List[Any] = self.scheduler_classes[0] _A: Union[str, Any] = self.get_scheduler_config() _A: Optional[Any] = scheduler_class(**lowerCAmelCase_ ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_8_7 ) - 0.00979 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_9_9 ) - 0.02 ) ) < 1e-5 def __magic_name__ ( self : Optional[int] ): """simple docstring""" _A: Any = self.scheduler_classes[0] _A: List[str] = self.get_scheduler_config() _A: Union[str, Any] = scheduler_class(**lowerCAmelCase_ ) _A: List[Any] = len(lowerCAmelCase_ ) _A: Union[str, Any] = self.dummy_model() _A: Dict = self.dummy_sample_deter _A: Dict = self.dummy_sample_deter + 0.1 _A: str = self.dummy_sample_deter - 0.1 _A: str = samplea.shape[0] _A: Optional[Any] = torch.stack([samplea, samplea, samplea] , dim=0 ) _A: List[str] = torch.arange(lowerCAmelCase_ )[0:3, None].repeat(1 , lowerCAmelCase_ ) _A: List[Any] = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) _A: Optional[int] = scheduler.batch_step_no_noise(lowerCAmelCase_ , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) ) _A: Dict = torch.sum(torch.abs(lowerCAmelCase_ ) ) _A: List[str] = torch.mean(torch.abs(lowerCAmelCase_ ) ) assert abs(result_sum.item() - 1153.1833 ) < 1e-2 assert abs(result_mean.item() - 0.5005 ) < 1e-3 def __magic_name__ ( self : Tuple ): """simple docstring""" _A: Optional[Any] = self.scheduler_classes[0] _A: List[Any] = self.get_scheduler_config() _A: Any = scheduler_class(**lowerCAmelCase_ ) _A: Union[str, Any] = len(lowerCAmelCase_ ) _A: Any = self.dummy_model() _A: Optional[int] = self.dummy_sample_deter _A: List[str] = torch.manual_seed(0 ) for t in reversed(range(lowerCAmelCase_ ) ): # 1. predict noise residual _A: Optional[int] = model(lowerCAmelCase_ , lowerCAmelCase_ ) # 2. predict previous mean of sample x_t-1 _A: Optional[int] = scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , generator=lowerCAmelCase_ ).prev_sample _A: List[Any] = pred_prev_sample _A: Optional[int] = torch.sum(torch.abs(lowerCAmelCase_ ) ) _A: Any = torch.mean(torch.abs(lowerCAmelCase_ ) ) assert abs(result_sum.item() - 258.9606 ) < 1e-2 assert abs(result_mean.item() - 0.3372 ) < 1e-3 def __magic_name__ ( self : Tuple ): """simple docstring""" _A: Optional[int] = self.scheduler_classes[0] _A: Union[str, Any] = self.get_scheduler_config(prediction_type='''v_prediction''' ) _A: List[str] = scheduler_class(**lowerCAmelCase_ ) _A: Union[str, Any] = len(lowerCAmelCase_ ) _A: Any = self.dummy_model() _A: Any = self.dummy_sample_deter _A: str = torch.manual_seed(0 ) for t in reversed(range(lowerCAmelCase_ ) ): # 1. predict noise residual _A: Any = model(lowerCAmelCase_ , lowerCAmelCase_ ) # 2. predict previous mean of sample x_t-1 _A: int = scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , generator=lowerCAmelCase_ ).prev_sample _A: Tuple = pred_prev_sample _A: List[Any] = torch.sum(torch.abs(lowerCAmelCase_ ) ) _A: str = torch.mean(torch.abs(lowerCAmelCase_ ) ) assert abs(result_sum.item() - 202.0296 ) < 1e-2 assert abs(result_mean.item() - 0.2631 ) < 1e-3 def __magic_name__ ( self : Optional[int] ): """simple docstring""" _A: Optional[int] = self.scheduler_classes[0] _A: Optional[Any] = self.get_scheduler_config() _A: Dict = scheduler_class(**lowerCAmelCase_ ) _A: Any = [1_0_0, 8_7, 5_0, 1, 0] scheduler.set_timesteps(timesteps=lowerCAmelCase_ ) _A: Tuple = scheduler.timesteps for i, timestep in enumerate(lowerCAmelCase_ ): if i == len(lowerCAmelCase_ ) - 1: _A: Dict = -1 else: _A: int = timesteps[i + 1] _A: List[str] = scheduler.previous_timestep(lowerCAmelCase_ ) _A: str = prev_t.item() self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) def __magic_name__ ( self : Any ): """simple docstring""" _A: Tuple = self.scheduler_classes[0] _A: int = self.get_scheduler_config() _A: Any = scheduler_class(**lowerCAmelCase_ ) _A: Union[str, Any] = [1_0_0, 8_7, 5_0, 5_1, 0] with self.assertRaises(lowerCAmelCase_ , msg='''`custom_timesteps` must be in descending order.''' ): scheduler.set_timesteps(timesteps=lowerCAmelCase_ ) def __magic_name__ ( self : int ): """simple docstring""" _A: List[str] = self.scheduler_classes[0] _A: Optional[Any] = self.get_scheduler_config() _A: Union[str, Any] = scheduler_class(**lowerCAmelCase_ ) _A: Union[str, Any] = [1_0_0, 8_7, 5_0, 1, 0] _A: Dict = len(lowerCAmelCase_ ) with self.assertRaises(lowerCAmelCase_ , msg='''Can only pass one of `num_inference_steps` or `custom_timesteps`.''' ): scheduler.set_timesteps(num_inference_steps=lowerCAmelCase_ , timesteps=lowerCAmelCase_ ) def __magic_name__ ( self : Any ): """simple docstring""" _A: List[Any] = self.scheduler_classes[0] _A: int = self.get_scheduler_config() _A: str = scheduler_class(**lowerCAmelCase_ ) _A: Any = [scheduler.config.num_train_timesteps] with self.assertRaises( lowerCAmelCase_ , msg='''`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}''' , ): scheduler.set_timesteps(timesteps=lowerCAmelCase_ )
301
1
def lowerCamelCase__ ( a , a , a ) -> float: _A: Any = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series return total def lowerCamelCase__ ( ) -> Union[str, Any]: print(sum_of_series(1 , 1 , 10 ) ) if __name__ == "__main__": import doctest doctest.testmod()
301
import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Any = GPTSanJapaneseTokenizer __UpperCamelCase : Optional[int] = False __UpperCamelCase : str = {'''do_clean_text''': False, '''add_prefix_space''': False} def __magic_name__ ( self : Any ): """simple docstring""" super().setUp() # fmt: off _A: Union[str, Any] = ['''こん''', '''こんに''', '''にちは''', '''ばんは''', '''世界,㔺界''', '''、''', '''。''', '''<BR>''', '''<SP>''', '''<TAB>''', '''<URL>''', '''<EMAIL>''', '''<TEL>''', '''<DATE>''', '''<PRICE>''', '''<BLOCK>''', '''<KIGOU>''', '''<U2000U2BFF>''', '''<|emoji1|>''', '''<unk>''', '''<|bagoftoken|>''', '''<|endoftext|>'''] # fmt: on _A: Union[str, Any] = {'''emoji''': {'''\ud83d\ude00''': '''<|emoji1|>'''}, '''emoji_inv''': {'''<|emoji1|>''': '''\ud83d\ude00'''}} # 😀 _A: str = {'''unk_token''': '''<unk>'''} _A: Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) _A: Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''emoji_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) with open(self.emoji_file , '''w''' ) as emoji_writer: emoji_writer.write(json.dumps(lowerCAmelCase_ ) ) def __magic_name__ ( self : Optional[int] , **lowerCAmelCase_ : List[Any] ): """simple docstring""" kwargs.update(self.special_tokens_map ) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **lowerCAmelCase_ ) def __magic_name__ ( self : Optional[int] , lowerCAmelCase_ : List[str] ): """simple docstring""" _A: Optional[Any] = '''こんにちは、世界。 \nこんばんは、㔺界。😀''' _A: str = '''こんにちは、世界。 \nこんばんは、世界。😀''' return input_text, output_text def __magic_name__ ( self : List[str] , lowerCAmelCase_ : Optional[int] ): """simple docstring""" _A , _A: Optional[int] = self.get_input_output_texts(lowerCAmelCase_ ) _A: Union[str, Any] = tokenizer.encode(lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ ) _A: Tuple = tokenizer.decode(lowerCAmelCase_ , clean_up_tokenization_spaces=lowerCAmelCase_ ) return text, ids def __magic_name__ ( self : Tuple ): """simple docstring""" pass # TODO add if relevant def __magic_name__ ( self : List[str] ): """simple docstring""" pass # TODO add if relevant def __magic_name__ ( self : Dict ): """simple docstring""" pass # TODO add if relevant def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" _A: List[str] = self.get_tokenizer() # Testing tokenization _A: List[Any] = '''こんにちは、世界。 こんばんは、㔺界。''' _A: Dict = ['''こん''', '''にちは''', '''、''', '''世界''', '''。''', '''<SP>''', '''こん''', '''ばんは''', '''、''', '''㔺界''', '''。'''] _A: List[Any] = tokenizer.tokenize(lowerCAmelCase_ ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) # Testing conversion to ids without special tokens _A: Optional[int] = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] _A: Optional[int] = tokenizer.convert_tokens_to_ids(lowerCAmelCase_ ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) # Testing conversion to ids with special tokens _A: Dict = tokens + [tokenizer.unk_token] _A: str = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 1_9] _A: Optional[int] = tokenizer.convert_tokens_to_ids(lowerCAmelCase_ ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" _A: Dict = self.get_tokenizer() # Testing tokenization _A: Optional[int] = '''こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。''' _A: str = '''こんにちは、、、、世界。こんばんは、、、、世界。''' _A: Tuple = tokenizer.encode(lowerCAmelCase_ ) _A: List[str] = tokenizer.decode(lowerCAmelCase_ ) self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) @slow def __magic_name__ ( self : Any ): """simple docstring""" _A: List[Any] = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' ) # Testing tokenization _A: Union[str, Any] = '''こんにちは、世界。''' _A: Optional[int] = '''こんばんは、㔺界。😀''' _A: str = '''こんにちは、世界。こんばんは、世界。😀''' _A: List[Any] = tokenizer.encode(prefix_text + input_text ) _A: Optional[Any] = tokenizer.encode('''''' , prefix_text=prefix_text + input_text ) _A: List[Any] = tokenizer.encode(lowerCAmelCase_ , prefix_text=lowerCAmelCase_ ) _A: Union[str, Any] = tokenizer.decode(lowerCAmelCase_ ) _A: Any = tokenizer.decode(lowerCAmelCase_ ) _A: Dict = tokenizer.decode(lowerCAmelCase_ ) self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) @slow def __magic_name__ ( self : Optional[Any] ): """simple docstring""" _A: str = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' ) # Testing tokenization _A: Optional[int] = '''こんにちは、世界。''' _A: Optional[int] = '''こんばんは、㔺界。😀''' _A: Any = len(tokenizer.encode(lowerCAmelCase_ ) ) - 2 _A: int = len(tokenizer.encode(lowerCAmelCase_ ) ) - 2 _A: Optional[Any] = [1] + [0] * (len_prefix + len_text + 1) _A: Any = [1] * (len_prefix + len_text + 1) + [0] _A: Optional[int] = [1] + [1] * (len_prefix) + [0] * (len_text + 1) _A: Optional[Any] = tokenizer(prefix_text + input_text ).token_type_ids _A: List[str] = tokenizer('''''' , prefix_text=prefix_text + input_text ).token_type_ids _A: Dict = tokenizer(lowerCAmelCase_ , prefix_text=lowerCAmelCase_ ).token_type_ids self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) @slow def __magic_name__ ( self : Any ): """simple docstring""" _A: str = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' ) _A: List[Any] = tokenizer.encode('''あンいワ''' ) _A: Any = tokenizer.encode('''''' , prefix_text='''あンいワ''' ) _A: Union[str, Any] = tokenizer.encode('''いワ''' , prefix_text='''あン''' ) self.assertEqual(tokenizer.decode(lowerCAmelCase_ ) , tokenizer.decode(lowerCAmelCase_ ) ) self.assertEqual(tokenizer.decode(lowerCAmelCase_ ) , tokenizer.decode(lowerCAmelCase_ ) ) self.assertNotEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertNotEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token @slow def __magic_name__ ( self : List[Any] ): """simple docstring""" _A: Tuple = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' ) _A: Optional[Any] = [['''武田信玄''', '''は、'''], ['''織田信長''', '''の配下の、''']] _A: Optional[int] = tokenizer(lowerCAmelCase_ , padding=lowerCAmelCase_ ) _A: Optional[Any] = tokenizer.batch_encode_plus(lowerCAmelCase_ , padding=lowerCAmelCase_ ) # fmt: off _A: Tuple = [[3_5_9_9_3, 8_6_4_0, 2_5_9_4_8, 3_5_9_9_8, 3_0_6_4_7, 3_5_6_7_5, 3_5_9_9_9, 3_5_9_9_9], [3_5_9_9_3, 1_0_3_8_2, 9_8_6_8, 3_5_9_9_8, 3_0_6_4_6, 9_4_5_9, 3_0_6_4_6, 3_5_6_7_5]] _A: Optional[int] = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] _A: Dict = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids , lowerCAmelCase_ ) self.assertListEqual(x_token.token_type_ids , lowerCAmelCase_ ) self.assertListEqual(x_token.attention_mask , lowerCAmelCase_ ) self.assertListEqual(x_token_a.input_ids , lowerCAmelCase_ ) self.assertListEqual(x_token_a.token_type_ids , lowerCAmelCase_ ) self.assertListEqual(x_token_a.attention_mask , lowerCAmelCase_ ) def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" # Intentionally convert some words to accommodate character fluctuations unique to Japanese pass def __magic_name__ ( self : Tuple ): """simple docstring""" # tokenizer has no padding token pass
301
1
from math import isqrt, loga def lowerCamelCase__ ( a ) -> list[int]: _A: Union[str, Any] = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , a , a ): _A: Optional[int] = False return [i for i in range(2 , a ) if is_prime[i]] def lowerCamelCase__ ( a = 80_08_00 , a = 80_08_00 ) -> int: _A: Dict = degree * loga(a ) _A: List[str] = int(a ) _A: str = calculate_prime_numbers(a ) _A: List[Any] = 0 _A: str = 0 _A: int = len(a ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(F"""{solution() = }""")
301
def lowerCamelCase__ ( a = 10**9 ) -> int: _A: Dict = 1 _A: Union[str, Any] = 2 _A: List[str] = 0 _A: List[Any] = 0 _A: int = 0 while perimeter <= max_perimeter: perimeters_sum += perimeter prev_value += 2 * value value += prev_value _A: List[Any] = 2 * value + 2 if i % 2 == 0 else 2 * value - 2 i += 1 return perimeters_sum if __name__ == "__main__": print(F"""{solution() = }""")
301
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) UpperCAmelCase__ : Dict = { 'configuration_layoutlmv3': [ 'LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LayoutLMv3Config', 'LayoutLMv3OnnxConfig', ], 'processing_layoutlmv3': ['LayoutLMv3Processor'], 'tokenization_layoutlmv3': ['LayoutLMv3Tokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Tuple = ['LayoutLMv3TokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : int = [ 'LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'LayoutLMv3ForQuestionAnswering', 'LayoutLMv3ForSequenceClassification', 'LayoutLMv3ForTokenClassification', 'LayoutLMv3Model', 'LayoutLMv3PreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Any = [ 'TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLayoutLMv3ForQuestionAnswering', 'TFLayoutLMv3ForSequenceClassification', 'TFLayoutLMv3ForTokenClassification', 'TFLayoutLMv3Model', 'TFLayoutLMv3PreTrainedModel', ] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Dict = ['LayoutLMv3FeatureExtractor'] UpperCAmelCase__ : int = ['LayoutLMv3ImageProcessor'] if TYPE_CHECKING: from .configuration_layoutlmva import ( LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig, LayoutLMvaOnnxConfig, ) from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_layoutlmva import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, TFLayoutLMvaPreTrainedModel, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor from .image_processing_layoutlmva import LayoutLMvaImageProcessor else: import sys UpperCAmelCase__ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
301
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase__ : Union[str, Any] = { 'configuration_roc_bert': ['ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoCBertConfig'], 'tokenization_roc_bert': ['RoCBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: pass try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[Any] = [ 'ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'RoCBertForCausalLM', 'RoCBertForMaskedLM', 'RoCBertForMultipleChoice', 'RoCBertForPreTraining', 'RoCBertForQuestionAnswering', 'RoCBertForSequenceClassification', 'RoCBertForTokenClassification', 'RoCBertLayer', 'RoCBertModel', 'RoCBertPreTrainedModel', 'load_tf_weights_in_roc_bert', ] if TYPE_CHECKING: from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig from .tokenization_roc_bert import RoCBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: raise OptionalDependencyNotAvailable() try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) else: import sys UpperCAmelCase__ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
301
1
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__ : Tuple = True except ImportError: UpperCAmelCase__ : Tuple = False try: from torch.hub import _get_torch_home UpperCAmelCase__ : str = _get_torch_home() except ImportError: UpperCAmelCase__ : str = os.path.expanduser( os.getenv('TORCH_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'torch')) ) UpperCAmelCase__ : List[str] = os.path.join(torch_cache_home, 'transformers') UpperCAmelCase__ : int = 'https://cdn.huggingface.co' UpperCAmelCase__ : List[Any] = 'https://s3.amazonaws.com/models.huggingface.co/bert' UpperCAmelCase__ : Union[str, Any] = '/'.join(str(Path(__file__).resolve()).split('/')[:-1]) UpperCAmelCase__ : Optional[int] = os.path.join(PATH, 'config.yaml') UpperCAmelCase__ : Union[str, Any] = os.path.join(PATH, 'attributes.txt') UpperCAmelCase__ : Optional[int] = os.path.join(PATH, 'objects.txt') UpperCAmelCase__ : Any = os.getenv('PYTORCH_PRETRAINED_BERT_CACHE', default_cache_path) UpperCAmelCase__ : List[Any] = os.getenv('PYTORCH_TRANSFORMERS_CACHE', PYTORCH_PRETRAINED_BERT_CACHE) UpperCAmelCase__ : str = os.getenv('TRANSFORMERS_CACHE', PYTORCH_TRANSFORMERS_CACHE) UpperCAmelCase__ : Optional[Any] = 'pytorch_model.bin' UpperCAmelCase__ : Any = 'config.yaml' def lowerCamelCase__ ( a=OBJECTS , a=ATTRIBUTES ) -> Optional[Any]: _A: List[Any] = [] with open(a ) as f: for object in f.readlines(): vg_classes.append(object.split(''',''' )[0].lower().strip() ) _A: Dict = [] with open(a ) as f: for object in f.readlines(): vg_attrs.append(object.split(''',''' )[0].lower().strip() ) return vg_classes, vg_attrs def lowerCamelCase__ ( a ) -> Optional[Any]: _A: List[str] = OrderedDict() with open(a , '''rb''' ) as f: _A: Dict = pkl.load(a )['''model'''] for k in copy.deepcopy(list(ckp.keys() ) ): _A: List[str] = ckp.pop(a ) if isinstance(a , np.ndarray ): _A: Tuple = torch.tensor(a ) else: assert isinstance(a , torch.tensor ), type(a ) _A: Dict = v return r class UpperCAmelCase : '''simple docstring''' __UpperCamelCase : Dict = {} def __init__( self : str , lowerCAmelCase_ : dict , lowerCAmelCase_ : str = "root" , lowerCAmelCase_ : Tuple=0 ): """simple docstring""" _A: List[Any] = name _A: Dict = level _A: List[Any] = {} for k, v in dictionary.items(): if v is None: raise ValueError() _A: int = copy.deepcopy(lowerCAmelCase_ ) _A: Union[str, Any] = copy.deepcopy(lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): _A: List[str] = Config(lowerCAmelCase_ , name=lowerCAmelCase_ , level=level + 1 ) _A: Any = v setattr(self , lowerCAmelCase_ , lowerCAmelCase_ ) _A: Any = d def __repr__( self : List[Any] ): """simple docstring""" return str(list((self._pointer.keys()) ) ) def __setattr__( self : Dict , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Dict ): """simple docstring""" _A: Optional[Any] = val _A: int = val _A: Optional[int] = key.split('''.''' ) _A: Union[str, Any] = len(lowerCAmelCase_ ) - 1 _A: Dict = self._pointer if len(lowerCAmelCase_ ) > 1: for i, l in enumerate(lowerCAmelCase_ ): if hasattr(self , lowerCAmelCase_ ) and isinstance(getattr(self , lowerCAmelCase_ ) , lowerCAmelCase_ ): setattr(getattr(self , lowerCAmelCase_ ) , '''.'''.join(levels[i:] ) , lowerCAmelCase_ ) if l == last_level: _A: int = val else: _A: Union[str, Any] = pointer[l] def __magic_name__ ( self : List[Any] ): """simple docstring""" return self._pointer def __magic_name__ ( self : Union[str, Any] , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Any ): """simple docstring""" with open(F"""{file_name}""" , '''w''' ) as stream: dump(lowerCAmelCase_ , lowerCAmelCase_ ) def __magic_name__ ( self : int , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : List[str] ): """simple docstring""" with open(F"""{file_name}""" , '''w''' ) as stream: json.dump(lowerCAmelCase_ , lowerCAmelCase_ ) @staticmethod def __magic_name__ ( lowerCAmelCase_ : Any ): """simple docstring""" with open(lowerCAmelCase_ ) as stream: _A: List[str] = load(lowerCAmelCase_ , Loader=lowerCAmelCase_ ) return data def __str__( self : str ): """simple docstring""" _A: List[str] = ''' ''' if self._name != "root": _A: str = F"""{t * (self._level-1)}{self._name}:\n""" else: _A: Dict = '''''' _A: Optional[Any] = self._level for i, (k, v) in enumerate(self._pointer.items() ): if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): r += F"""{t * (self._level)}{v}\n""" self._level += 1 else: r += F"""{t * (self._level)}{k}: {v} ({type(lowerCAmelCase_ ).__name__})\n""" _A: Optional[Any] = level return r[:-1] @classmethod def __magic_name__ ( cls : Union[str, Any] , lowerCAmelCase_ : str , **lowerCAmelCase_ : List[str] ): """simple docstring""" _A , _A: str = cls.get_config_dict(lowerCAmelCase_ , **lowerCAmelCase_ ) return cls(lowerCAmelCase_ ) @classmethod def __magic_name__ ( cls : Dict , lowerCAmelCase_ : str , **lowerCAmelCase_ : Union[str, Any] ): """simple docstring""" _A: int = kwargs.pop('''cache_dir''' , lowerCAmelCase_ ) _A: Optional[Any] = kwargs.pop('''force_download''' , lowerCAmelCase_ ) _A: int = kwargs.pop('''resume_download''' , lowerCAmelCase_ ) _A: Any = kwargs.pop('''proxies''' , lowerCAmelCase_ ) _A: Optional[int] = kwargs.pop('''local_files_only''' , lowerCAmelCase_ ) if os.path.isdir(lowerCAmelCase_ ): _A: Any = os.path.join(lowerCAmelCase_ , lowerCAmelCase_ ) elif os.path.isfile(lowerCAmelCase_ ) or is_remote_url(lowerCAmelCase_ ): _A: List[Any] = pretrained_model_name_or_path else: _A: Any = hf_bucket_url(lowerCAmelCase_ , filename=lowerCAmelCase_ , use_cdn=lowerCAmelCase_ ) try: # Load from URL or cache if already cached _A: Tuple = cached_path( lowerCAmelCase_ , cache_dir=lowerCAmelCase_ , force_download=lowerCAmelCase_ , proxies=lowerCAmelCase_ , resume_download=lowerCAmelCase_ , local_files_only=lowerCAmelCase_ , ) # Load config dict if resolved_config_file is None: raise EnvironmentError _A: Union[str, Any] = Config.load_yaml(lowerCAmelCase_ ) except EnvironmentError: _A: List[Any] = '''Can\'t load config for''' raise EnvironmentError(lowerCAmelCase_ ) if resolved_config_file == config_file: print('''loading configuration file from path''' ) else: print('''loading configuration file cache''' ) return Config.load_yaml(lowerCAmelCase_ ), kwargs def lowerCamelCase__ ( a ) -> List[str]: _A: Optional[Any] = torch.load('''dump.pt''' , map_location=in_tensor.device ) _A: Union[str, Any] = in_tensor.numpy() _A: int = out_tensor.numpy()[0] print(na.shape , na[0, 0, :5] ) print(na.shape , na[0, 0, :5] ) assert np.allclose(a , a , rtol=0.01 , atol=0.1 ), ( f"""{sum([1 for x in np.isclose(a , a , rtol=0.01 , atol=0.1 ).flatten() if x is False] )/len(na.flatten() )*1_00:.4f} %""" " element-wise mismatch" ) raise Exception('''tensors are all good''' ) # Hugging face functions below def lowerCamelCase__ ( a ) -> List[str]: _A: Optional[int] = urlparse(a ) return parsed.scheme in ("http", "https") def lowerCamelCase__ ( a , a , a=True ) -> str: _A: Any = CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX _A: Tuple = '''/''' not in model_id if legacy_format: return f"""{endpoint}/{model_id}-{filename}""" else: return f"""{endpoint}/{model_id}/{filename}""" def lowerCamelCase__ ( a , a , a=None , a=0 , a=None , ) -> str: _A: Optional[int] = '''python/{}'''.format(sys.version.split()[0] ) if _torch_available: ua += "; torch/{}".format(torch.__version__ ) if isinstance(a , a ): ua += "; " + "; ".join('''{}/{}'''.format(a , a ) for k, v in user_agent.items() ) elif isinstance(a , a ): ua += "; " + user_agent _A: Optional[int] = {'''user-agent''': ua} if resume_size > 0: _A: List[Any] = '''bytes=%d-''' % (resume_size,) _A: List[str] = requests.get(a , stream=a , proxies=a , headers=a ) if response.status_code == 4_16: # Range not satisfiable return _A: List[str] = response.headers.get('''Content-Length''' ) _A: Union[str, Any] = resume_size + int(a ) if content_length is not None else None _A: str = tqdm( unit='''B''' , unit_scale=a , total=a , initial=a , desc='''Downloading''' , ) for chunk in response.iter_content(chunk_size=10_24 ): if chunk: # filter out keep-alive new chunks progress.update(len(a ) ) temp_file.write(a ) progress.close() def lowerCamelCase__ ( a , a=None , a=False , a=None , a=10 , a=False , a=None , a=False , ) -> List[str]: if cache_dir is None: _A: str = TRANSFORMERS_CACHE if isinstance(a , a ): _A: int = str(a ) os.makedirs(a , exist_ok=a ) _A: Tuple = None if not local_files_only: try: _A: Optional[int] = requests.head(a , allow_redirects=a , proxies=a , timeout=a ) if response.status_code == 2_00: _A: str = response.headers.get('''ETag''' ) except (EnvironmentError, requests.exceptions.Timeout): # etag is already None pass _A: Optional[Any] = url_to_filename(a , a ) # get cache path to put the file _A: Optional[Any] = os.path.join(a , a ) # 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(a ): return cache_path else: _A: Optional[Any] = [ file for file in fnmatch.filter(os.listdir(a ) , filename + '''.*''' ) if not file.endswith('''.json''' ) and not file.endswith('''.lock''' ) ] if len(a ) > 0: return os.path.join(a , 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(a ) and not force_download: return cache_path # Prevent parallel downloads of the same file with a lock. _A: List[Any] = cache_path + '''.lock''' with FileLock(a ): # If the download just completed while the lock was activated. if os.path.exists(a ) and not force_download: # Even if returning early like here, the lock will be released. return cache_path if resume_download: _A: Optional[Any] = cache_path + '''.incomplete''' @contextmanager def _resumable_file_manager(): with open(a , '''a+b''' ) as f: yield f _A: Any = _resumable_file_manager if os.path.exists(a ): _A: List[str] = os.stat(a ).st_size else: _A: Any = 0 else: _A: Dict = partial(tempfile.NamedTemporaryFile , dir=a , delete=a ) _A: List[Any] = 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''' , a , temp_file.name , ) http_get( a , a , proxies=a , resume_size=a , user_agent=a , ) os.replace(temp_file.name , a ) _A: Optional[Any] = {'''url''': url, '''etag''': etag} _A: List[str] = cache_path + '''.json''' with open(a , '''w''' ) as meta_file: json.dump(a , a ) return cache_path def lowerCamelCase__ ( a , a=None ) -> Dict: _A: Optional[int] = url.encode('''utf-8''' ) _A: int = shaaaa(a ) _A: Optional[Any] = url_hash.hexdigest() if etag: _A: List[Any] = etag.encode('''utf-8''' ) _A: Optional[int] = shaaaa(a ) filename += "." + etag_hash.hexdigest() if url.endswith('''.h5''' ): filename += ".h5" return filename def lowerCamelCase__ ( a , a=None , a=False , a=None , a=False , a=None , a=False , a=False , a=False , ) -> Optional[int]: if cache_dir is None: _A: int = TRANSFORMERS_CACHE if isinstance(a , a ): _A: List[str] = str(a ) if isinstance(a , a ): _A: str = str(a ) if is_remote_url(a ): # URL, so get it from the cache (downloading if necessary) _A: Union[str, Any] = get_from_cache( a , cache_dir=a , force_download=a , proxies=a , resume_download=a , user_agent=a , local_files_only=a , ) elif os.path.exists(a ): # File, and it exists. _A: Tuple = url_or_filename elif urlparse(a ).scheme == "": # File, but it doesn't exist. raise EnvironmentError('''file {} not found'''.format(a ) ) else: # Something unknown raise ValueError('''unable to parse {} as a URL or as a local path'''.format(a ) ) if extract_compressed_file: if not is_zipfile(a ) and not tarfile.is_tarfile(a ): 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/" _A , _A: Union[str, Any] = os.path.split(a ) _A: Union[str, Any] = output_file.replace('''.''' , '''-''' ) + '''-extracted''' _A: Union[str, Any] = os.path.join(a , a ) if os.path.isdir(a ) and os.listdir(a ) and not force_extract: return output_path_extracted # Prevent parallel extractions _A: Tuple = output_path + '''.lock''' with FileLock(a ): shutil.rmtree(a , ignore_errors=a ) os.makedirs(a ) if is_zipfile(a ): with ZipFile(a , '''r''' ) as zip_file: zip_file.extractall(a ) zip_file.close() elif tarfile.is_tarfile(a ): _A: Tuple = tarfile.open(a ) tar_file.extractall(a ) tar_file.close() else: raise EnvironmentError('''Archive format of {} could not be identified'''.format(a ) ) return output_path_extracted return output_path def lowerCamelCase__ ( a , a="," ) -> List[Any]: assert isinstance(a , a ) if os.path.isfile(a ): with open(a ) as f: _A: Optional[Any] = eval(f.read() ) else: _A: Optional[int] = requests.get(a ) try: _A: Tuple = requests.json() except Exception: _A: Optional[Any] = req.content.decode() assert data is not None, "could not connect" try: _A: Tuple = eval(a ) except Exception: _A: List[str] = data.split('''\n''' ) req.close() return data def lowerCamelCase__ ( a ) -> Union[str, Any]: _A: str = requests.get(a ) _A: Any = np.array(Image.open(BytesIO(response.content ) ) ) return img def lowerCamelCase__ ( a ) -> Union[str, Any]: _A: Any = url.split('''/''' )[-1] if fn not in os.listdir(os.getcwd() ): wget.download(a ) with open(a , '''rb''' ) as stream: _A: Dict = pkl.load(a ) _A: Dict = weights.pop('''model''' ) _A: int = {} for k, v in model.items(): _A: List[Any] = torch.from_numpy(a ) if "running_var" in k: _A: List[Any] = torch.tensor([0] ) _A: Union[str, Any] = k.replace('''running_var''' , '''num_batches_tracked''' ) _A: Any = zero return new def lowerCamelCase__ ( ) -> int: print(f"""{os.path.abspath(os.path.join(a , os.pardir ) )}/demo.ipynb""" ) def lowerCamelCase__ ( a , a="RGB" ) -> List[str]: assert isinstance(a , a ) if os.path.isfile(a ): _A: Optional[int] = cva.imread(a ) else: _A: Tuple = get_image_from_url(a ) assert img is not None, f"""could not connect to: {im}""" _A: Dict = cva.cvtColor(a , cva.COLOR_BGR2RGB ) if input_format == "RGB": _A: Dict = img[:, :, ::-1] return img def lowerCamelCase__ ( a , a=1 ) -> str: return (images[i : i + batch] for i in range(0 , len(a ) , a ))
301
import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def lowerCamelCase__ ( a , a=0.999 , a="cosine" , ) -> int: if alpha_transform_type == "cosine": def alpha_bar_fn(a ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(a ): return math.exp(t * -12.0 ) else: raise ValueError(f"""Unsupported alpha_tranform_type: {alpha_transform_type}""" ) _A: Dict = [] for i in range(a ): _A: Optional[int] = i / num_diffusion_timesteps _A: Optional[int] = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(a ) / alpha_bar_fn(a ) , a ) ) return torch.tensor(a , dtype=torch.floataa ) class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Optional[int] = [e.name for e in KarrasDiffusionSchedulers] __UpperCamelCase : Tuple = 2 @register_to_config def __init__( self : str , lowerCAmelCase_ : int = 1_0_0_0 , lowerCAmelCase_ : float = 0.00085 , lowerCAmelCase_ : float = 0.012 , lowerCAmelCase_ : str = "linear" , lowerCAmelCase_ : Optional[Union[np.ndarray, List[float]]] = None , lowerCAmelCase_ : str = "epsilon" , lowerCAmelCase_ : Optional[bool] = False , lowerCAmelCase_ : Optional[bool] = False , lowerCAmelCase_ : float = 1.0 , lowerCAmelCase_ : str = "linspace" , lowerCAmelCase_ : int = 0 , ): """simple docstring""" if trained_betas is not None: _A: Optional[Any] = torch.tensor(lowerCAmelCase_ , dtype=torch.floataa ) elif beta_schedule == "linear": _A: List[str] = torch.linspace(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. _A: Optional[Any] = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , lowerCAmelCase_ , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule _A: Tuple = betas_for_alpha_bar(lowerCAmelCase_ , alpha_transform_type='''cosine''' ) elif beta_schedule == "exp": _A: int = betas_for_alpha_bar(lowerCAmelCase_ , alpha_transform_type='''exp''' ) else: raise NotImplementedError(F"""{beta_schedule} does is not implemented for {self.__class__}""" ) _A: Union[str, Any] = 1.0 - self.betas _A: Dict = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) _A: str = use_karras_sigmas def __magic_name__ ( self : List[str] , lowerCAmelCase_ : Any , lowerCAmelCase_ : Optional[int]=None ): """simple docstring""" if schedule_timesteps is None: _A: List[str] = self.timesteps _A: int = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: _A: Optional[int] = 1 if len(lowerCAmelCase_ ) > 1 else 0 else: _A: int = timestep.cpu().item() if torch.is_tensor(lowerCAmelCase_ ) else timestep _A: List[str] = self._index_counter[timestep_int] return indices[pos].item() @property def __magic_name__ ( self : int ): """simple docstring""" # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def __magic_name__ ( self : List[str] , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : Union[float, torch.FloatTensor] , ): """simple docstring""" _A: List[str] = self.index_for_timestep(lowerCAmelCase_ ) _A: str = self.sigmas[step_index] _A: str = sample / ((sigma**2 + 1) ** 0.5) return sample def __magic_name__ ( self : Optional[int] , lowerCAmelCase_ : int , lowerCAmelCase_ : Union[str, torch.device] = None , lowerCAmelCase_ : Optional[int] = None , ): """simple docstring""" _A: Union[str, Any] = num_inference_steps _A: str = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": _A: Optional[Any] = np.linspace(0 , num_train_timesteps - 1 , lowerCAmelCase_ , dtype=lowerCAmelCase_ )[::-1].copy() elif self.config.timestep_spacing == "leading": _A: List[Any] = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 _A: Dict = (np.arange(0 , lowerCAmelCase_ ) * step_ratio).round()[::-1].copy().astype(lowerCAmelCase_ ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": _A: Union[str, Any] = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 _A: List[Any] = (np.arange(lowerCAmelCase_ , 0 , -step_ratio )).round().copy().astype(lowerCAmelCase_ ) timesteps -= 1 else: raise ValueError( F"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.""" ) _A: Optional[int] = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) _A: str = np.log(lowerCAmelCase_ ) _A: int = np.interp(lowerCAmelCase_ , np.arange(0 , len(lowerCAmelCase_ ) ) , lowerCAmelCase_ ) if self.config.use_karras_sigmas: _A: Optional[int] = self._convert_to_karras(in_sigmas=lowerCAmelCase_ , num_inference_steps=self.num_inference_steps ) _A: List[str] = np.array([self._sigma_to_t(lowerCAmelCase_ , lowerCAmelCase_ ) for sigma in sigmas] ) _A: Optional[int] = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) _A: Optional[Any] = torch.from_numpy(lowerCAmelCase_ ).to(device=lowerCAmelCase_ ) _A: Tuple = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) _A: str = torch.from_numpy(lowerCAmelCase_ ) _A: str = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(lowerCAmelCase_ ).startswith('''mps''' ): # mps does not support float64 _A: List[Any] = timesteps.to(lowerCAmelCase_ , dtype=torch.floataa ) else: _A: Optional[int] = timesteps.to(device=lowerCAmelCase_ ) # empty dt and derivative _A: Dict = None _A: List[Any] = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter _A: Dict = defaultdict(lowerCAmelCase_ ) def __magic_name__ ( self : Dict , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Dict ): """simple docstring""" # get log sigma _A: Tuple = np.log(lowerCAmelCase_ ) # get distribution _A: List[str] = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range _A: Dict = np.cumsum((dists >= 0) , axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) _A: int = low_idx + 1 _A: Optional[int] = log_sigmas[low_idx] _A: Dict = log_sigmas[high_idx] # interpolate sigmas _A: Union[str, Any] = (low - log_sigma) / (low - high) _A: Optional[Any] = np.clip(lowerCAmelCase_ , 0 , 1 ) # transform interpolation to time range _A: Any = (1 - w) * low_idx + w * high_idx _A: List[Any] = t.reshape(sigma.shape ) return t def __magic_name__ ( self : Any , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" _A: float = in_sigmas[-1].item() _A: float = in_sigmas[0].item() _A: Union[str, Any] = 7.0 # 7.0 is the value used in the paper _A: Optional[Any] = np.linspace(0 , 1 , lowerCAmelCase_ ) _A: Tuple = sigma_min ** (1 / rho) _A: Optional[Any] = sigma_max ** (1 / rho) _A: List[str] = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def __magic_name__ ( self : Optional[Any] ): """simple docstring""" return self.dt is None def __magic_name__ ( self : Tuple , lowerCAmelCase_ : Union[torch.FloatTensor, np.ndarray] , lowerCAmelCase_ : Union[float, torch.FloatTensor] , lowerCAmelCase_ : Union[torch.FloatTensor, np.ndarray] , lowerCAmelCase_ : bool = True , ): """simple docstring""" _A: Optional[int] = self.index_for_timestep(lowerCAmelCase_ ) # advance index counter by 1 _A: Union[str, Any] = timestep.cpu().item() if torch.is_tensor(lowerCAmelCase_ ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: _A: Optional[int] = self.sigmas[step_index] _A: Union[str, Any] = self.sigmas[step_index + 1] else: # 2nd order / Heun's method _A: Union[str, Any] = self.sigmas[step_index - 1] _A: Optional[int] = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API _A: List[Any] = 0 _A: Tuple = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": _A: Union[str, Any] = sigma_hat if self.state_in_first_order else sigma_next _A: List[str] = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": _A: int = sigma_hat if self.state_in_first_order else sigma_next _A: List[str] = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": _A: Optional[int] = model_output else: raise ValueError( F"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`""" ) if self.config.clip_sample: _A: Tuple = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order _A: Optional[int] = (sample - pred_original_sample) / sigma_hat # 3. delta timestep _A: List[Any] = sigma_next - sigma_hat # store for 2nd order step _A: str = derivative _A: Any = dt _A: Dict = sample else: # 2. 2nd order / Heun's method _A: List[str] = (sample - pred_original_sample) / sigma_next _A: str = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample _A: Dict = self.dt _A: int = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" _A: int = None _A: int = None _A: Optional[Any] = None _A: Optional[Any] = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=lowerCAmelCase_ ) def __magic_name__ ( self : Any , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : torch.FloatTensor , ): """simple docstring""" # Make sure sigmas and timesteps have the same device and dtype as original_samples _A: str = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(lowerCAmelCase_ ): # mps does not support float64 _A: Optional[int] = self.timesteps.to(original_samples.device , dtype=torch.floataa ) _A: Any = timesteps.to(original_samples.device , dtype=torch.floataa ) else: _A: Union[str, Any] = self.timesteps.to(original_samples.device ) _A: int = timesteps.to(original_samples.device ) _A: str = [self.index_for_timestep(lowerCAmelCase_ , lowerCAmelCase_ ) for t in timesteps] _A: Optional[Any] = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): _A: List[str] = sigma.unsqueeze(-1 ) _A: Any = original_samples + noise * sigma return noisy_samples def __len__( self : Dict ): """simple docstring""" return self.config.num_train_timesteps
301
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase__ : List[str] = { 'configuration_longformer': [ 'LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LongformerConfig', 'LongformerOnnxConfig', ], 'tokenization_longformer': ['LongformerTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Union[str, Any] = ['LongformerTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Tuple = [ 'LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'LongformerForMaskedLM', 'LongformerForMultipleChoice', 'LongformerForQuestionAnswering', 'LongformerForSequenceClassification', 'LongformerForTokenClassification', 'LongformerModel', 'LongformerPreTrainedModel', 'LongformerSelfAttention', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : List[Any] = [ 'TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLongformerForMaskedLM', 'TFLongformerForMultipleChoice', 'TFLongformerForQuestionAnswering', 'TFLongformerForSequenceClassification', 'TFLongformerForTokenClassification', 'TFLongformerModel', 'TFLongformerPreTrainedModel', 'TFLongformerSelfAttention', ] if TYPE_CHECKING: from .configuration_longformer import ( LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, LongformerConfig, LongformerOnnxConfig, ) from .tokenization_longformer import LongformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_longformer_fast import LongformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longformer import ( LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, LongformerForMaskedLM, LongformerForMultipleChoice, LongformerForQuestionAnswering, LongformerForSequenceClassification, LongformerForTokenClassification, LongformerModel, LongformerPreTrainedModel, LongformerSelfAttention, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_longformer import ( TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFLongformerForMaskedLM, TFLongformerForMultipleChoice, TFLongformerForQuestionAnswering, TFLongformerForSequenceClassification, TFLongformerForTokenClassification, TFLongformerModel, TFLongformerPreTrainedModel, TFLongformerSelfAttention, ) else: import sys UpperCAmelCase__ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
301
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=SCREAMING_SNAKE_CASE__ ) class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : str = field(default='''automatic-speech-recognition''' , metadata={'''include_in_asdict_even_if_is_default''': True} ) __UpperCamelCase : ClassVar[Features] = Features({'''audio''': Audio()} ) __UpperCamelCase : ClassVar[Features] = Features({'''transcription''': Value('''string''' )} ) __UpperCamelCase : str = "audio" __UpperCamelCase : str = "transcription" def __magic_name__ ( self : List[Any] , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" if self.audio_column not in features: raise ValueError(F"""Column {self.audio_column} is not present in features.""" ) if not isinstance(features[self.audio_column] , lowerCAmelCase_ ): raise ValueError(F"""Column {self.audio_column} is not an Audio type.""" ) _A: Optional[int] = copy.deepcopy(self ) _A: str = self.input_schema.copy() _A: List[str] = features[self.audio_column] _A: Dict = input_schema return task_template @property def __magic_name__ ( self : str ): """simple docstring""" return {self.audio_column: "audio", self.transcription_column: "transcription"}
301
1
import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex UpperCAmelCase__ : Optional[Any] = logging.getLogger(__name__) class UpperCAmelCase : '''simple docstring''' def __init__( self : Dict ): """simple docstring""" _A: Union[str, Any] = False def __magic_name__ ( self : Dict , lowerCAmelCase_ : Any , lowerCAmelCase_ : Any , lowerCAmelCase_ : int , lowerCAmelCase_ : Dict ): """simple docstring""" if not self.initialized: _A: Dict = RagRetriever( lowerCAmelCase_ , question_encoder_tokenizer=lowerCAmelCase_ , generator_tokenizer=lowerCAmelCase_ , index=lowerCAmelCase_ , init_retrieval=lowerCAmelCase_ , ) _A: List[str] = True def __magic_name__ ( self : Any ): """simple docstring""" self.retriever.index.init_index() def __magic_name__ ( self : int , lowerCAmelCase_ : Any , lowerCAmelCase_ : List[Any] ): """simple docstring""" _A , _A: Any = self.retriever._main_retrieve(lowerCAmelCase_ , lowerCAmelCase_ ) return doc_ids, retrieved_doc_embeds class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def __init__( self : Optional[int] , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : Any , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : int , lowerCAmelCase_ : Dict=None ): """simple docstring""" if index is not None and index.is_initialized() and len(lowerCAmelCase_ ) > 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__( lowerCAmelCase_ , question_encoder_tokenizer=lowerCAmelCase_ , generator_tokenizer=lowerCAmelCase_ , index=lowerCAmelCase_ , init_retrieval=lowerCAmelCase_ , ) _A: int = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) for worker in self.retrieval_workers ] ) def __magic_name__ ( self : List[Any] ): """simple docstring""" 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 __magic_name__ ( self : Tuple , lowerCAmelCase_ : Dict , lowerCAmelCase_ : List[str] ): """simple docstring""" if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. _A: Optional[int] = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] _A , _A: Optional[int] = ray.get(random_worker.retrieve.remote(lowerCAmelCase_ , lowerCAmelCase_ ) ) else: _A , _A: Dict = self._main_retrieve(lowerCAmelCase_ , lowerCAmelCase_ ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(lowerCAmelCase_ ) @classmethod def __magic_name__ ( cls : Any , lowerCAmelCase_ : Any , lowerCAmelCase_ : Optional[int]=None , **lowerCAmelCase_ : Any ): """simple docstring""" return super(lowerCAmelCase_ , cls ).get_tokenizers(lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ) @classmethod def __magic_name__ ( cls : int , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : int=None , **lowerCAmelCase_ : Optional[Any] ): """simple docstring""" _A: Dict = kwargs.pop('''config''' , lowerCAmelCase_ ) or RagConfig.from_pretrained(lowerCAmelCase_ , **lowerCAmelCase_ ) _A: List[Any] = RagTokenizer.from_pretrained(lowerCAmelCase_ , config=lowerCAmelCase_ ) _A: Tuple = rag_tokenizer.question_encoder _A: Union[str, Any] = rag_tokenizer.generator if indexed_dataset is not None: _A: List[str] = '''custom''' _A: str = CustomHFIndex(config.retrieval_vector_size , lowerCAmelCase_ ) else: _A: Optional[Any] = cls._build_index(lowerCAmelCase_ ) return cls( lowerCAmelCase_ , question_encoder_tokenizer=lowerCAmelCase_ , generator_tokenizer=lowerCAmelCase_ , retrieval_workers=lowerCAmelCase_ , index=lowerCAmelCase_ , )
301
import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer UpperCAmelCase__ : Optional[int] = 'bart' UpperCAmelCase__ : Dict = True @st.cache(allow_output_mutation=a ) def lowerCamelCase__ ( ) -> Dict: if LOAD_DENSE_INDEX: _A: Optional[Any] = AutoTokenizer.from_pretrained('''yjernite/retribert-base-uncased''' ) _A: Any = AutoModel.from_pretrained('''yjernite/retribert-base-uncased''' ).to('''cuda:0''' ) _A: Any = qar_model.eval() else: _A , _A: Union[str, Any] = (None, None) if MODEL_TYPE == "bart": _A: Union[str, Any] = AutoTokenizer.from_pretrained('''yjernite/bart_eli5''' ) _A: Dict = AutoModelForSeqaSeqLM.from_pretrained('''yjernite/bart_eli5''' ).to('''cuda:0''' ) _A: Union[str, Any] = torch.load('''seq2seq_models/eli5_bart_model_blm_2.pth''' ) sas_model.load_state_dict(save_dict['''model'''] ) _A: int = sas_model.eval() else: _A , _A: Tuple = make_qa_sas_model( model_name='''t5-small''' , from_file='''seq2seq_models/eli5_t5_model_1024_4.pth''' , device='''cuda:0''' ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=a ) def lowerCamelCase__ ( ) -> Tuple: if LOAD_DENSE_INDEX: _A: List[Any] = faiss.StandardGpuResources() _A: int = datasets.load_dataset(path='''wiki_snippets''' , name='''wiki40b_en_100_0''' )['''train'''] _A: Dict = np.memmap( '''wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat''' , dtype='''float32''' , mode='''r''' , shape=(wikiaab_passages.num_rows, 1_28) , ) _A: str = faiss.IndexFlatIP(1_28 ) _A: Optional[int] = faiss.index_cpu_to_gpu(a , 1 , a ) wikiaab_gpu_index_flat.add(a ) # TODO fix for larger GPU else: _A , _A: str = (None, None) _A: Tuple = Elasticsearch([{'''host''': '''localhost''', '''port''': '''9200'''}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=a ) def lowerCamelCase__ ( ) -> str: _A: Dict = datasets.load_dataset('''eli5''' , name='''LFQA_reddit''' ) _A: Dict = elia['''train_eli5'''] _A: List[Any] = np.memmap( '''eli5_questions_reps.dat''' , dtype='''float32''' , mode='''r''' , shape=(elia_train.num_rows, 1_28) ) _A: Any = faiss.IndexFlatIP(1_28 ) eli5_train_q_index.add(a ) return (elia_train, eli5_train_q_index) UpperCAmelCase__ ,UpperCAmelCase__ ,UpperCAmelCase__ : int = load_indexes() UpperCAmelCase__ ,UpperCAmelCase__ ,UpperCAmelCase__ ,UpperCAmelCase__ : Any = load_models() UpperCAmelCase__ ,UpperCAmelCase__ : Tuple = load_train_data() def lowerCamelCase__ ( a , a=10 ) -> str: _A: Optional[int] = embed_questions_for_retrieval([question] , a , a ) _A , _A: List[str] = eli5_train_q_index.search(a , a ) _A: Dict = [elia_train[int(a )] for i in I[0]] return nn_examples def lowerCamelCase__ ( a , a="wiki40b" , a="dense" , a=10 ) -> str: if source == "none": _A , _A: Any = (''' <P> '''.join(['''''' for _ in range(11 )] ).strip(), []) else: if method == "dense": _A , _A: List[Any] = query_qa_dense_index( a , a , a , a , a , a ) else: _A , _A: Tuple = query_es_index( a , a , index_name='''english_wiki40b_snippets_100w''' , n_results=a , ) _A: Union[str, Any] = [ (res['''article_title'''], res['''section_title'''].strip(), res['''score'''], res['''passage_text''']) for res in hit_lst ] _A: str = '''question: {} context: {}'''.format(a , a ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda a : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda a : None), } ) def lowerCamelCase__ ( a , a , a , a=64 , a=2_56 , a=False , a=2 , a=0.95 , a=0.8 ) -> str: with torch.no_grad(): _A: Optional[int] = qa_sas_generate( a , a , a , num_answers=1 , num_beams=a , min_len=a , max_len=a , do_sample=a , temp=a , top_p=a , top_k=a , max_input_length=10_24 , device='''cuda:0''' , )[0] return (answer, support_list) st.title('Long Form Question Answering with ELI5') # Start sidebar UpperCAmelCase__ : List[Any] = '<img src=\'https://huggingface.co/front/assets/huggingface_logo.svg\'>' UpperCAmelCase__ : Optional[Any] = '\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class="img-container"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n' % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia UpperCAmelCase__ : str = '\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n' st.sidebar.markdown(description, unsafe_allow_html=True) UpperCAmelCase__ : str = [ 'Answer the question', 'View the retrieved document only', 'View the most similar ELI5 question and answer', 'Show me everything, please!', ] UpperCAmelCase__ : Optional[int] = st.sidebar.checkbox('Demo options') if demo_options: UpperCAmelCase__ : Any = st.sidebar.selectbox( '', action_list, index=3, ) UpperCAmelCase__ : List[str] = action_list.index(action_st) UpperCAmelCase__ : Optional[Any] = st.sidebar.selectbox( '', ['Show full text of passages', 'Show passage section titles'], index=0, ) UpperCAmelCase__ : List[Any] = show_type == 'Show full text of passages' else: UpperCAmelCase__ : Dict = 3 UpperCAmelCase__ : str = True UpperCAmelCase__ : Optional[Any] = st.sidebar.checkbox('Retrieval options') if retrieval_options: UpperCAmelCase__ : List[str] = '\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n ' st.sidebar.markdown(retriever_info) UpperCAmelCase__ : Optional[int] = st.sidebar.selectbox('Which Wikipedia format should the model use?', ['wiki40b', 'none']) UpperCAmelCase__ : int = st.sidebar.selectbox('Which Wikipedia indexer should the model use?', ['dense', 'sparse', 'mixed']) else: UpperCAmelCase__ : Tuple = 'wiki40b' UpperCAmelCase__ : List[Any] = 'dense' UpperCAmelCase__ : Tuple = 'beam' UpperCAmelCase__ : Any = 2 UpperCAmelCase__ : Dict = 64 UpperCAmelCase__ : Any = 256 UpperCAmelCase__ : int = None UpperCAmelCase__ : List[str] = None UpperCAmelCase__ : Optional[int] = st.sidebar.checkbox('Generation options') if generate_options: UpperCAmelCase__ : Any = '\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder\'s output probabilities.\n ' st.sidebar.markdown(generate_info) UpperCAmelCase__ : Optional[int] = st.sidebar.selectbox('Would you like to use beam search or sample an answer?', ['beam', 'sampled']) UpperCAmelCase__ : int = st.sidebar.slider( 'Minimum generation length', min_value=8, max_value=256, value=64, step=8, format=None, key=None ) UpperCAmelCase__ : str = st.sidebar.slider( 'Maximum generation length', min_value=64, max_value=512, value=256, step=16, format=None, key=None ) if sampled == "beam": UpperCAmelCase__ : Tuple = st.sidebar.slider('Beam size', min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: UpperCAmelCase__ : List[Any] = st.sidebar.slider( 'Nucleus sampling p', min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None ) UpperCAmelCase__ : Union[str, Any] = st.sidebar.slider( 'Temperature', min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None ) UpperCAmelCase__ : Optional[int] = None # start main text UpperCAmelCase__ : Any = [ '<MY QUESTION>', 'How do people make chocolate?', 'Why do we get a fever when we are sick?', 'How can different animals perceive different colors?', 'What is natural language processing?', 'What\'s the best way to treat a sunburn?', 'What exactly are vitamins ?', 'How does nuclear energy provide electricity?', 'What\'s the difference between viruses and bacteria?', 'Why are flutes classified as woodwinds when most of them are made out of metal ?', 'Why do people like drinking coffee even though it tastes so bad?', 'What happens when wine ages? How does it make the wine taste better?', 'If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?', 'How can we set a date to the beginning or end of an artistic period? Doesn\'t the change happen gradually?', 'How does New Zealand have so many large bird predators?', ] UpperCAmelCase__ : List[Any] = st.selectbox( 'What would you like to ask? ---- select <MY QUESTION> to enter a new query', questions_list, index=1, ) if question_s == "<MY QUESTION>": UpperCAmelCase__ : Any = st.text_input('Enter your question here:', '') else: UpperCAmelCase__ : int = question_s if st.button('Show me!'): if action in [0, 1, 3]: if index_type == "mixed": UpperCAmelCase__ ,UpperCAmelCase__ : Tuple = make_support(question, source=wiki_source, method='dense', n_results=10) UpperCAmelCase__ ,UpperCAmelCase__ : Optional[Any] = make_support(question, source=wiki_source, method='sparse', n_results=10) UpperCAmelCase__ : Dict = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] UpperCAmelCase__ : str = support_list[:10] UpperCAmelCase__ : str = '<P> ' + ' <P> '.join([res[-1] for res in support_list]) else: UpperCAmelCase__ ,UpperCAmelCase__ : List[Any] = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: UpperCAmelCase__ ,UpperCAmelCase__ : Optional[Any] = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == 'sampled'), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown('### The model generated answer is:') st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown('--- \n ### The model is drawing information from the following Wikipedia passages:') for i, res in enumerate(support_list): UpperCAmelCase__ : Any = 'https://en.wikipedia.org/wiki/{}'.format(res[0].replace(' ', '_')) UpperCAmelCase__ : Tuple = res[1].strip() if sec_titles == "": UpperCAmelCase__ : Optional[int] = '[{}]({})'.format(res[0], wiki_url) else: UpperCAmelCase__ : int = sec_titles.split(' & ') UpperCAmelCase__ : Union[str, Any] = ' & '.join( ['[{}]({}#{})'.format(sec.strip(), wiki_url, sec.strip().replace(' ', '_')) for sec in sec_list] ) st.markdown( '{0:02d} - **Article**: {1:<18} <br> _Section_: {2}'.format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( '> <span style="font-family:arial; font-size:10pt;">' + res[-1] + '</span>', unsafe_allow_html=True ) if action in [2, 3]: UpperCAmelCase__ : Union[str, Any] = find_nearest_training(question) UpperCAmelCase__ : int = nn_train_list[0] st.markdown( '--- \n ### The most similar question in the ELI5 training set was: \n\n {}'.format(train_exple['title']) ) UpperCAmelCase__ : Tuple = [ '{}. {}'.format(i + 1, ' \n'.join([line.strip() for line in ans.split('\n') if line.strip() != ''])) for i, (ans, sc) in enumerate(zip(train_exple['answers']['text'], train_exple['answers']['score'])) if i == 0 or sc > 2 ] st.markdown('##### Its answers were: \n\n {}'.format('\n'.join(answers_st))) UpperCAmelCase__ : Any = '\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n' st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
301
1
from __future__ import annotations UpperCAmelCase__ : Any = [True] * 1000001 UpperCAmelCase__ : Dict = 2 while i * i <= 1000000: if seive[i]: for j in range(i * i, 1000001, i): UpperCAmelCase__ : List[str] = False i += 1 def lowerCamelCase__ ( a ) -> bool: return seive[n] def lowerCamelCase__ ( a ) -> bool: return any(digit in '''02468''' for digit in str(a ) ) def lowerCamelCase__ ( a = 1_00_00_00 ) -> list[int]: _A: str = [2] # result already includes the number 2. for num in range(3 , limit + 1 , 2 ): if is_prime(a ) and not contains_an_even_digit(a ): _A: Tuple = str(a ) _A: Dict = [int(str_num[j:] + str_num[:j] ) for j in range(len(a ) )] if all(is_prime(a ) for i in list_nums ): result.append(a ) return result def lowerCamelCase__ ( ) -> int: return len(find_circular_primes() ) if __name__ == "__main__": print(F"""{len(find_circular_primes()) = }""")
301
from __future__ import annotations UpperCAmelCase__ : List[str] = list[list[int]] # assigning initial values to the grid UpperCAmelCase__ : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution UpperCAmelCase__ : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def lowerCamelCase__ ( a , a , a , a ) -> bool: for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def lowerCamelCase__ ( a ) -> tuple[int, int] | None: for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def lowerCamelCase__ ( a ) -> Matrix | None: if location := find_empty_location(a ): _A , _A: Optional[Any] = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(a , a , a , a ): _A: str = digit if sudoku(a ) is not None: return grid _A: Tuple = 0 return None def lowerCamelCase__ ( a ) -> None: for row in grid: for cell in row: print(a , end=''' ''' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('\nExample grid:\n' + '=' * 20) print_solution(example_grid) print('\nExample grid solution:') UpperCAmelCase__ : int = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('Cannot find a solution.')
301
1
import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase__ : List[Any] = logging.get_logger(__name__) def lowerCamelCase__ ( a ) -> Any: _A: List[Any] = torch.load(a , map_location='''cpu''' ) if "model" in sd.keys(): _A: str = torch.load(a , map_location='''cpu''' )['''model'''] # pop unnecessary weights _A: str = [ '''decoder.version''', '''decoder.output_projection.weight''', ] for key in keys_to_delete: if key in sd: sd.pop(a ) _A: Dict = { '''decoder.project_in_dim.weight''': '''decoder.project_in.weight''', '''decoder.project_out_dim.weight''': '''decoder.project_out.weight''', '''decoder.layer_norm.weight''': '''decoder.final_layer_norm.weight''', '''decoder.layer_norm.bias''': '''decoder.final_layer_norm.bias''', } for old_key, new_key in keys_to_rename.items(): if old_key in sd: _A: str = sd.pop(a ) _A: Optional[int] = list(sd.keys() ) for key in keys: if ".qkv_proj." in key: _A: str = sd[key] # We split QKV in separate Q,K,V _A: Any = key.replace('''.qkv_proj.''' , '''.q_proj.''' ) _A: Union[str, Any] = key.replace('''.qkv_proj.''' , '''.k_proj.''' ) _A: str = key.replace('''.qkv_proj.''' , '''.v_proj.''' ) _A: int = value.shape[0] assert depth % 3 == 0 # `SequeuceParallelTransformerBlock` has QKV weight is separated in K,V,Q despite the naming: # https://cs.github.com/facebookresearch/metaseq/blob/51871bd73cd04c038f239ea2a26db1d7f6b37927/metaseq/modules/sequence_parallel_transformer_layer.py#L97 _A , _A , _A: Dict = torch.split(a , depth // 3 , dim=0 ) _A: List[Any] = q _A: str = k _A: List[Any] = v del sd[key] return sd @torch.no_grad() def lowerCamelCase__ ( a , a , a=None ) -> Union[str, Any]: _A: int = load_checkpoint(a ) if config is not None: _A: Dict = OPTConfig.from_pretrained(a ) else: _A: Optional[Any] = OPTConfig() _A: List[str] = OPTModel(a ).half().eval() model.load_state_dict(a ) # Check results Path(a ).mkdir(exist_ok=a ) model.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase__ : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--fairseq_path', type=str, help=( 'path to fairseq checkpoint in correct format. You can find all checkpoints in the correct format here:' ' https://huggingface.co/models?other=opt_metasq' ), ) parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--hf_config', default=None, type=str, help='Define HF config.') UpperCAmelCase__ : Any = parser.parse_args() convert_opt_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, config=args.hf_config)
301
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests UpperCAmelCase__ : str = open # noqa: we just need to have a builtin inside this module to test it properly
301
1
import sys def lowerCamelCase__ ( a ) -> Any: _A: Optional[Any] = len(a ) _A: Union[str, Any] = [[0 for x in range(a )] for x in range(a )] _A: int = [[0 for x in range(a )] for x in range(a )] for chain_length in range(2 , a ): for a in range(1 , n - chain_length + 1 ): _A: int = a + chain_length - 1 _A: Any = sys.maxsize for c in range(a , a ): _A: str = ( matrix[a][c] + matrix[c + 1][b] + array[a - 1] * array[c] * array[b] ) if cost < matrix[a][b]: _A: str = cost _A: Dict = c return matrix, sol def lowerCamelCase__ ( a , a , a ) -> Union[str, Any]: if i == j: print('''A''' + str(a ) , end=''' ''' ) else: print('''(''' , end=''' ''' ) print_optiomal_solution(a , a , optimal_solution[i][j] ) print_optiomal_solution(a , optimal_solution[i][j] + 1 , a ) print(''')''' , end=''' ''' ) def lowerCamelCase__ ( ) -> Union[str, Any]: _A: int = [30, 35, 15, 5, 10, 20, 25] _A: Tuple = len(a ) # Size of matrix created from above array will be # 30*35 35*15 15*5 5*10 10*20 20*25 _A , _A: int = matrix_chain_order(a ) print('''No. of Operation required: ''' + str(matrix[1][n - 1] ) ) print_optiomal_solution(a , 1 , n - 1 ) if __name__ == "__main__": main()
301
import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Optional[Any] , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : List[str]=3 , lowerCAmelCase_ : List[str]=3_2 , lowerCAmelCase_ : Union[str, Any]=3 , lowerCAmelCase_ : int=1_0 , lowerCAmelCase_ : Tuple=[1_0, 2_0, 3_0, 4_0] , lowerCAmelCase_ : Optional[Any]=[1, 1, 2, 1] , lowerCAmelCase_ : Optional[Any]=True , lowerCAmelCase_ : str=True , lowerCAmelCase_ : Optional[Any]="relu" , lowerCAmelCase_ : int=3 , lowerCAmelCase_ : List[Any]=None , ): """simple docstring""" _A: str = parent _A: List[Any] = batch_size _A: Optional[int] = image_size _A: Dict = num_channels _A: str = embeddings_size _A: Any = hidden_sizes _A: Dict = depths _A: Any = is_training _A: int = use_labels _A: Tuple = hidden_act _A: int = num_labels _A: int = scope _A: str = len(lowerCAmelCase_ ) def __magic_name__ ( self : Dict ): """simple docstring""" _A: Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _A: Union[str, Any] = self.get_config() return config, pixel_values def __magic_name__ ( self : str ): """simple docstring""" return RegNetConfig( 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 , image_size=self.image_size , ) def __magic_name__ ( self : str , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : str ): """simple docstring""" _A: str = FlaxRegNetModel(config=lowerCAmelCase_ ) _A: Optional[int] = model(lowerCAmelCase_ ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , ) def __magic_name__ ( self : str , lowerCAmelCase_ : str , lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Union[str, Any] = self.num_labels _A: Union[str, Any] = FlaxRegNetForImageClassification(config=lowerCAmelCase_ ) _A: str = model(lowerCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __magic_name__ ( self : List[Any] ): """simple docstring""" _A: str = self.prepare_config_and_inputs() _A , _A: Optional[int] = config_and_inputs _A: Union[str, Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_flax class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Tuple = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () __UpperCamelCase : Union[str, Any] = False __UpperCamelCase : List[Any] = False __UpperCamelCase : int = False def __magic_name__ ( self : int ): """simple docstring""" _A: int = FlaxRegNetModelTester(self ) _A: Union[str, Any] = ConfigTester(self , config_class=lowerCAmelCase_ , has_text_modality=lowerCAmelCase_ ) def __magic_name__ ( self : str ): """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __magic_name__ ( self : int ): """simple docstring""" return def __magic_name__ ( self : Tuple ): """simple docstring""" _A: int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase_ ) def __magic_name__ ( self : Tuple ): """simple docstring""" _A: Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_ ) @unittest.skip(reason='''RegNet does not use inputs_embeds''' ) def __magic_name__ ( self : str ): """simple docstring""" pass @unittest.skip(reason='''RegNet does not support input and output embeddings''' ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" pass def __magic_name__ ( self : List[Any] ): """simple docstring""" _A , _A: int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A: Union[str, Any] = model_class(lowerCAmelCase_ ) _A: Any = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _A: Any = [*signature.parameters.keys()] _A: Union[str, Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowerCAmelCase_ ) def __magic_name__ ( self : str ): """simple docstring""" def check_hidden_states_output(lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Tuple ): _A: int = model_class(lowerCAmelCase_ ) _A: List[str] = model(**self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ ) ) _A: str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _A: Tuple = self.model_tester.num_stages self.assertEqual(len(lowerCAmelCase_ ) , expected_num_stages + 1 ) _A , _A: List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A: Optional[Any] = True check_hidden_states_output(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _A: int = True check_hidden_states_output(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) def __magic_name__ ( self : Dict ): """simple docstring""" _A , _A: str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): _A: int = self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ ) _A: Union[str, Any] = model_class(lowerCAmelCase_ ) @jax.jit def model_jitted(lowerCAmelCase_ : Optional[Any] , **lowerCAmelCase_ : Optional[Any] ): return model(pixel_values=lowerCAmelCase_ , **lowerCAmelCase_ ) with self.subTest('''JIT Enabled''' ): _A: str = model_jitted(**lowerCAmelCase_ ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): _A: List[Any] = model_jitted(**lowerCAmelCase_ ).to_tuple() self.assertEqual(len(lowerCAmelCase_ ) , len(lowerCAmelCase_ ) ) for jitted_output, output in zip(lowerCAmelCase_ , lowerCAmelCase_ ): self.assertEqual(jitted_output.shape , output.shape ) def lowerCamelCase__ ( ) -> Tuple: _A: List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_flax class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" return AutoImageProcessor.from_pretrained('''facebook/regnet-y-040''' ) if is_vision_available() else None @slow def __magic_name__ ( self : List[str] ): """simple docstring""" _A: List[str] = FlaxRegNetForImageClassification.from_pretrained('''facebook/regnet-y-040''' ) _A: str = self.default_image_processor _A: int = prepare_img() _A: List[Any] = image_processor(images=lowerCAmelCase_ , return_tensors='''np''' ) _A: str = model(**lowerCAmelCase_ ) # verify the logits _A: str = (1, 1_0_0_0) self.assertEqual(outputs.logits.shape , lowerCAmelCase_ ) _A: Tuple = jnp.array([-0.4180, -1.5051, -3.4836] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] , lowerCAmelCase_ , atol=1e-4 ) )
301
1
import os from distutils.util import strtobool def lowerCamelCase__ ( a , a ) -> Tuple: for e in env_keys: _A: Optional[Any] = int(os.environ.get(a , -1 ) ) if val >= 0: return val return default def lowerCamelCase__ ( a , a=False ) -> Tuple: _A: Optional[Any] = os.environ.get(a , str(a ) ) return strtobool(a ) == 1 # As its name indicates `strtobool` actually returns an int... def lowerCamelCase__ ( a , a="no" ) -> List[str]: _A: Any = os.environ.get(a , str(a ) ) return value
301
from __future__ import annotations from bisect import bisect_left from functools import total_ordering from heapq import merge @total_ordering class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def __lt__( self : Dict , lowerCAmelCase_ : Optional[int] ): """simple docstring""" return self[-1] < other[-1] def __eq__( self : int , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" return self[-1] == other[-1] def lowerCamelCase__ ( a ) -> list: _A: list[Stack] = [] # sort into stacks for element in collection: _A: Any = Stack([element] ) _A: Optional[Any] = bisect_left(a , a ) if i != len(a ): stacks[i].append(a ) else: stacks.append(a ) # use a heap-based merge to merge stack efficiently _A: Tuple = merge(*(reversed(a ) for stack in stacks) ) return collection if __name__ == "__main__": UpperCAmelCase__ : Tuple = input('Enter numbers separated by a comma:\n').strip() UpperCAmelCase__ : Optional[Any] = [int(item) for item in user_input.split(',')] print(patience_sort(unsorted))
301
1
import os from pathlib import Path import numpy as np import pytest from pack_dataset import pack_data_dir from parameterized import parameterized from save_len_file import save_len_file from torch.utils.data import DataLoader from transformers import AutoTokenizer from transformers.models.mbart.modeling_mbart import shift_tokens_right from transformers.testing_utils import TestCasePlus, slow from utils import FAIRSEQ_AVAILABLE, DistributedSortishSampler, LegacySeqaSeqDataset, SeqaSeqDataset UpperCAmelCase__ : List[Any] = 'bert-base-cased' UpperCAmelCase__ : Any = 'google/pegasus-xsum' UpperCAmelCase__ : int = [' Sam ate lunch today.', 'Sams lunch ingredients.'] UpperCAmelCase__ : List[Any] = ['A very interesting story about what I ate for lunch.', 'Avocado, celery, turkey, coffee'] UpperCAmelCase__ : Dict = 'patrickvonplaten/t5-tiny-random' UpperCAmelCase__ : Any = 'sshleifer/bart-tiny-random' UpperCAmelCase__ : int = 'sshleifer/tiny-mbart' UpperCAmelCase__ : str = 'sshleifer/tiny-marian-en-de' def lowerCamelCase__ ( a , a ) -> int: _A: int = '''\n'''.join(a ) Path(a ).open('''w''' ).writelines(a ) def lowerCamelCase__ ( a ) -> Optional[int]: for split in ["train", "val", "test"]: _dump_articles(os.path.join(a , f"""{split}.source""" ) , a ) _dump_articles(os.path.join(a , f"""{split}.target""" ) , a ) return tmp_dir class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) @slow def __magic_name__ ( self : Any , lowerCAmelCase_ : str ): """simple docstring""" _A: Optional[int] = AutoTokenizer.from_pretrained(lowerCAmelCase_ ) _A: int = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) _A: List[Any] = max(len(tokenizer.encode(lowerCAmelCase_ ) ) for a in ARTICLES ) _A: Any = max(len(tokenizer.encode(lowerCAmelCase_ ) ) for a in SUMMARIES ) _A: Optional[int] = 4 _A: Optional[Any] = 8 assert max_len_target > max_src_len # Will be truncated assert max_len_source > max_src_len # Will be truncated _A , _A: Optional[Any] = '''ro_RO''', '''de_DE''' # ignored for all but mbart, but never causes error. _A: Tuple = SeqaSeqDataset( lowerCAmelCase_ , data_dir=lowerCAmelCase_ , type_path='''train''' , max_source_length=lowerCAmelCase_ , max_target_length=lowerCAmelCase_ , src_lang=lowerCAmelCase_ , tgt_lang=lowerCAmelCase_ , ) _A: str = DataLoader(lowerCAmelCase_ , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_src_len # show that targets are the same len assert batch["labels"].shape[1] == max_tgt_len if tok_name != MBART_TINY: continue # check language codes in correct place _A: Union[str, Any] = shift_tokens_right(batch['''labels'''] , tokenizer.pad_token_id ) assert batch["decoder_input_ids"][0, 0].item() == tokenizer.lang_code_to_id[tgt_lang] assert batch["decoder_input_ids"][0, -1].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -2].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -1].item() == tokenizer.lang_code_to_id[src_lang] break # No need to test every batch @parameterized.expand([BART_TINY, BERT_BASE_CASED] ) def __magic_name__ ( self : Optional[int] , lowerCAmelCase_ : Optional[int] ): """simple docstring""" _A: str = AutoTokenizer.from_pretrained(lowerCAmelCase_ ) _A: List[str] = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) _A: str = max(len(tokenizer.encode(lowerCAmelCase_ ) ) for a in ARTICLES ) _A: List[str] = max(len(tokenizer.encode(lowerCAmelCase_ ) ) for a in SUMMARIES ) _A: List[Any] = 4 _A: Union[str, Any] = LegacySeqaSeqDataset( lowerCAmelCase_ , data_dir=lowerCAmelCase_ , type_path='''train''' , max_source_length=2_0 , max_target_length=lowerCAmelCase_ , ) _A: Dict = DataLoader(lowerCAmelCase_ , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_len_source assert 2_0 >= batch["input_ids"].shape[1] # trimmed significantly # show that targets were truncated assert batch["labels"].shape[1] == trunc_target # Truncated assert max_len_target > trunc_target # Truncated break # No need to test every batch def __magic_name__ ( self : List[str] ): """simple docstring""" _A: Union[str, Any] = AutoTokenizer.from_pretrained('''facebook/mbart-large-cc25''' ) _A: int = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) _A: Union[str, Any] = tmp_dir.joinpath('''train.source''' ).open().readlines() _A: Any = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) pack_data_dir(lowerCAmelCase_ , lowerCAmelCase_ , 1_2_8 , lowerCAmelCase_ ) _A: Optional[int] = {x.name for x in tmp_dir.iterdir()} _A: str = {x.name for x in save_dir.iterdir()} _A: List[Any] = save_dir.joinpath('''train.source''' ).open().readlines() # orig: [' Sam ate lunch today.\n', 'Sams lunch ingredients.'] # desired_packed: [' Sam ate lunch today.\n Sams lunch ingredients.'] assert len(lowerCAmelCase_ ) < len(lowerCAmelCase_ ) assert len(lowerCAmelCase_ ) == 1 assert len(packed_examples[0] ) == sum(len(lowerCAmelCase_ ) for x in orig_examples ) assert orig_paths == new_paths @pytest.mark.skipif(not FAIRSEQ_AVAILABLE , reason='''This test requires fairseq''' ) def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" if not FAIRSEQ_AVAILABLE: return _A , _A , _A: int = self._get_dataset(max_len=6_4 ) _A: List[str] = 6_4 _A: Union[str, Any] = ds.make_dynamic_sampler(lowerCAmelCase_ , required_batch_size_multiple=lowerCAmelCase_ ) _A: Optional[Any] = [len(lowerCAmelCase_ ) for x in batch_sampler] assert len(set(lowerCAmelCase_ ) ) > 1 # it's not dynamic batch size if every batch is the same length assert sum(lowerCAmelCase_ ) == len(lowerCAmelCase_ ) # no dropped or added examples _A: int = DataLoader(lowerCAmelCase_ , batch_sampler=lowerCAmelCase_ , collate_fn=ds.collate_fn , num_workers=2 ) _A: Tuple = [] _A: List[Any] = [] for batch in data_loader: _A: List[str] = batch['''input_ids'''].shape _A: List[str] = src_shape[0] assert bs % required_batch_size_multiple == 0 or bs < required_batch_size_multiple _A: Any = np.product(batch['''input_ids'''].shape ) num_src_per_batch.append(lowerCAmelCase_ ) if num_src_tokens > (max_tokens * 1.1): failures.append(lowerCAmelCase_ ) assert num_src_per_batch[0] == max(lowerCAmelCase_ ) if failures: raise AssertionError(F"""too many tokens in {len(lowerCAmelCase_ )} batches""" ) def __magic_name__ ( self : Tuple ): """simple docstring""" _A , _A , _A: Union[str, Any] = self._get_dataset(max_len=5_1_2 ) _A: Optional[Any] = 2 _A: List[Any] = ds.make_sortish_sampler(lowerCAmelCase_ , shuffle=lowerCAmelCase_ ) _A: Union[str, Any] = DataLoader(lowerCAmelCase_ , batch_size=lowerCAmelCase_ , collate_fn=ds.collate_fn , num_workers=2 ) _A: List[str] = DataLoader(lowerCAmelCase_ , batch_size=lowerCAmelCase_ , collate_fn=ds.collate_fn , num_workers=2 , sampler=lowerCAmelCase_ ) _A: Union[str, Any] = tokenizer.pad_token_id def count_pad_tokens(lowerCAmelCase_ : Any , lowerCAmelCase_ : Dict="input_ids" ): return [batch[k].eq(lowerCAmelCase_ ).sum().item() for batch in data_loader] assert sum(count_pad_tokens(lowerCAmelCase_ , k='''labels''' ) ) < sum(count_pad_tokens(lowerCAmelCase_ , k='''labels''' ) ) assert sum(count_pad_tokens(lowerCAmelCase_ ) ) < sum(count_pad_tokens(lowerCAmelCase_ ) ) assert len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ) def __magic_name__ ( self : Union[str, Any] , lowerCAmelCase_ : str=1_0_0_0 , lowerCAmelCase_ : Any=1_2_8 ): """simple docstring""" if os.getenv('''USE_REAL_DATA''' , lowerCAmelCase_ ): _A: Tuple = '''examples/seq2seq/wmt_en_ro''' _A: Tuple = max_len * 2 * 6_4 if not Path(lowerCAmelCase_ ).joinpath('''train.len''' ).exists(): save_len_file(lowerCAmelCase_ , lowerCAmelCase_ ) else: _A: List[str] = '''examples/seq2seq/test_data/wmt_en_ro''' _A: Any = max_len * 4 save_len_file(lowerCAmelCase_ , lowerCAmelCase_ ) _A: Union[str, Any] = AutoTokenizer.from_pretrained(lowerCAmelCase_ ) _A: Optional[Any] = SeqaSeqDataset( lowerCAmelCase_ , data_dir=lowerCAmelCase_ , type_path='''train''' , max_source_length=lowerCAmelCase_ , max_target_length=lowerCAmelCase_ , n_obs=lowerCAmelCase_ , ) return ds, max_tokens, tokenizer def __magic_name__ ( self : Optional[int] ): """simple docstring""" _A , _A , _A: Optional[Any] = self._get_dataset() _A: int = set(DistributedSortishSampler(lowerCAmelCase_ , 2_5_6 , num_replicas=2 , rank=0 , add_extra_examples=lowerCAmelCase_ ) ) _A: Optional[int] = set(DistributedSortishSampler(lowerCAmelCase_ , 2_5_6 , num_replicas=2 , rank=1 , add_extra_examples=lowerCAmelCase_ ) ) assert idsa.intersection(lowerCAmelCase_ ) == set() @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) def __magic_name__ ( self : Optional[int] , lowerCAmelCase_ : str ): """simple docstring""" _A: str = AutoTokenizer.from_pretrained(lowerCAmelCase_ , use_fast=lowerCAmelCase_ ) if tok_name == MBART_TINY: _A: Tuple = SeqaSeqDataset( lowerCAmelCase_ , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path='''train''' , max_source_length=4 , max_target_length=8 , src_lang='''EN''' , tgt_lang='''FR''' , ) _A: Optional[int] = train_dataset.dataset_kwargs assert "src_lang" in kwargs and "tgt_lang" in kwargs else: _A: int = SeqaSeqDataset( lowerCAmelCase_ , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path='''train''' , max_source_length=4 , max_target_length=8 , ) _A: str = train_dataset.dataset_kwargs assert "add_prefix_space" not in kwargs if tok_name != BART_TINY else "add_prefix_space" in kwargs assert len(lowerCAmelCase_ ) == 1 if tok_name == BART_TINY else len(lowerCAmelCase_ ) == 0
301
import argparse import datetime import json import time import warnings from logging import getLogger from pathlib import Path from typing import Dict, List import torch from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils import calculate_bleu, calculate_rouge, chunks, parse_numeric_n_bool_cl_kwargs, use_task_specific_params UpperCAmelCase__ : Any = getLogger(__name__) UpperCAmelCase__ : Optional[Any] = 'cuda' if torch.cuda.is_available() else 'cpu' def lowerCamelCase__ ( a , a , a , a = 8 , a = DEFAULT_DEVICE , a=False , a="summarization" , a=None , **a , ) -> Dict: _A: str = Path(a ).open('''w''' , encoding='''utf-8''' ) _A: Optional[Any] = str(a ) _A: Union[str, Any] = AutoModelForSeqaSeqLM.from_pretrained(a ).to(a ) if fpaa: _A: Any = model.half() _A: Optional[int] = AutoTokenizer.from_pretrained(a ) logger.info(f"""Inferred tokenizer type: {tokenizer.__class__}""" ) # if this is wrong, check config.model_type. _A: Any = time.time() # update config with task specific params use_task_specific_params(a , a ) if prefix is None: _A: int = prefix or getattr(model.config , '''prefix''' , '''''' ) or '''''' for examples_chunk in tqdm(list(chunks(a , a ) ) ): _A: int = [prefix + text for text in examples_chunk] _A: str = tokenizer(a , return_tensors='''pt''' , truncation=a , padding='''longest''' ).to(a ) _A: str = model.generate( input_ids=batch.input_ids , attention_mask=batch.attention_mask , **a , ) _A: str = tokenizer.batch_decode(a , skip_special_tokens=a , clean_up_tokenization_spaces=a ) for hypothesis in dec: fout.write(hypothesis + '''\n''' ) fout.flush() fout.close() _A: Optional[int] = int(time.time() - start_time ) # seconds _A: Union[str, Any] = len(a ) return {"n_obs": n_obs, "runtime": runtime, "seconds_per_sample": round(runtime / n_obs , 4 )} def lowerCamelCase__ ( ) -> Tuple: return datetime.datetime.now().strftime('''%Y-%m-%d %H:%M:%S''' ) def lowerCamelCase__ ( a=True ) -> Optional[Any]: _A: str = argparse.ArgumentParser() parser.add_argument('''model_name''' , type=a , help='''like facebook/bart-large-cnn,t5-base, etc.''' ) parser.add_argument('''input_path''' , type=a , help='''like cnn_dm/test.source''' ) parser.add_argument('''save_path''' , type=a , help='''where to save summaries''' ) parser.add_argument('''--reference_path''' , type=a , required=a , help='''like cnn_dm/test.target''' ) parser.add_argument('''--score_path''' , type=a , required=a , default='''metrics.json''' , help='''where to save metrics''' ) parser.add_argument('''--device''' , type=a , required=a , default=a , help='''cuda, cuda:1, cpu etc.''' ) parser.add_argument( '''--prefix''' , type=a , required=a , default=a , help='''will be added to the begininng of src examples''' ) parser.add_argument('''--task''' , type=a , default='''summarization''' , help='''used for task_specific_params + metrics''' ) parser.add_argument('''--bs''' , type=a , default=8 , required=a , help='''batch size''' ) parser.add_argument( '''--n_obs''' , type=a , default=-1 , required=a , help='''How many observations. Defaults to all.''' ) parser.add_argument('''--fp16''' , action='''store_true''' ) parser.add_argument('''--dump-args''' , action='''store_true''' , help='''print the custom hparams with the results''' ) parser.add_argument( '''--info''' , nargs='''?''' , type=a , const=datetime_now() , help=( '''use in conjunction w/ --dump-args to print with the results whatever other info you\'d like, e.g.''' ''' lang=en-ru. If no value is passed, the current datetime string will be used.''' ) , ) # Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate _A , _A: Tuple = parser.parse_known_args() _A: List[str] = parse_numeric_n_bool_cl_kwargs(a ) if parsed_args and verbose: print(f"""parsed the following generate kwargs: {parsed_args}""" ) _A: int = [''' ''' + x.rstrip() if '''t5''' in args.model_name else x.rstrip() for x in open(args.input_path ).readlines()] if args.n_obs > 0: _A: List[str] = examples[: args.n_obs] Path(args.save_path ).parent.mkdir(exist_ok=a ) if args.reference_path is None and Path(args.score_path ).exists(): warnings.warn(f"""score_path {args.score_path} will be overwritten unless you type ctrl-c.""" ) if args.device == "cpu" and args.fpaa: # this mix leads to RuntimeError: "threshold_cpu" not implemented for 'Half' raise ValueError('''Can\'t mix --fp16 and --device cpu''' ) _A: Dict = generate_summaries_or_translations( a , args.save_path , args.model_name , batch_size=args.bs , device=args.device , fpaa=args.fpaa , task=args.task , prefix=args.prefix , **a , ) if args.reference_path is None: return {} # Compute scores _A: Dict = calculate_bleu if '''translation''' in args.task else calculate_rouge _A: List[Any] = [x.rstrip() for x in open(args.save_path ).readlines()] _A: Any = [x.rstrip() for x in open(args.reference_path ).readlines()][: len(a )] _A: dict = score_fn(a , a ) scores.update(a ) if args.dump_args: scores.update(a ) if args.info: _A: Optional[Any] = args.info if verbose: print(a ) if args.score_path is not None: json.dump(a , open(args.score_path , '''w''' ) ) return scores if __name__ == "__main__": # Usage for MT: # python run_eval.py MODEL_NAME $DATA_DIR/test.source $save_dir/test_translations.txt --reference_path $DATA_DIR/test.target --score_path $save_dir/test_bleu.json --task translation $@ run_generate(verbose=True)
301
1
def lowerCamelCase__ ( a = 4_00_00_00 ) -> int: _A: Union[str, Any] = [] _A , _A: Dict = 0, 1 while b <= n: if b % 2 == 0: even_fibs.append(a ) _A , _A: Any = b, a + b return sum(a ) if __name__ == "__main__": print(F"""{solution() = }""")
301
import math import random from typing import Any from .hill_climbing import SearchProblem def lowerCamelCase__ ( a , a = True , a = math.inf , a = -math.inf , a = math.inf , a = -math.inf , a = False , a = 1_00 , a = 0.01 , a = 1 , ) -> Any: _A: Optional[Any] = False _A: Dict = search_prob _A: str = start_temperate _A: Optional[int] = [] _A: int = 0 _A: Dict = None while not search_end: _A: Dict = current_state.score() if best_state is None or current_score > best_state.score(): _A: List[Any] = current_state scores.append(a ) iterations += 1 _A: List[str] = None _A: str = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to _A: Any = random.randint(0 , len(a ) - 1 ) # picking a random neighbor _A: Union[str, Any] = neighbors.pop(a ) _A: List[str] = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: _A: Optional[Any] = change * -1 # in case we are finding minimum if change > 0: # improves the solution _A: str = picked_neighbor else: _A: Tuple = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability _A: Optional[int] = picked_neighbor _A: Dict = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor _A: Any = True else: _A: List[Any] = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(a ) , a ) plt.xlabel('''Iterations''' ) plt.ylabel('''Function values''' ) plt.show() return best_state if __name__ == "__main__": def lowerCamelCase__ ( a , a ) -> Optional[Any]: return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) UpperCAmelCase__ : Optional[int] = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) UpperCAmelCase__ : Optional[Any] = simulated_annealing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( 'The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) # starting the problem with initial coordinates (12, 47) UpperCAmelCase__ : Optional[Any] = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) UpperCAmelCase__ : List[str] = simulated_annealing( prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( 'The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) def lowerCamelCase__ ( a , a ) -> Optional[Any]: return (3 * x**2) - (6 * y) UpperCAmelCase__ : Union[str, Any] = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) UpperCAmelCase__ : List[str] = simulated_annealing(prob, find_max=False, visualization=True) print( 'The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ' F"""{local_min.score()}""" ) UpperCAmelCase__ : Optional[Any] = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) UpperCAmelCase__ : List[Any] = simulated_annealing(prob, find_max=True, visualization=True) print( 'The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ' F"""{local_min.score()}""" )
301
1
from __future__ import annotations from random import random from typing import Generic, TypeVar UpperCAmelCase__ : int = TypeVar('KT') UpperCAmelCase__ : Tuple = TypeVar('VT') class UpperCAmelCase ( Generic[KT, VT] ): '''simple docstring''' def __init__( self : Tuple , lowerCAmelCase_ : KT | str = "root" , lowerCAmelCase_ : VT | None = None ): """simple docstring""" _A: str = key _A: Union[str, Any] = value _A: list[Node[KT, VT]] = [] def __repr__( self : int ): """simple docstring""" return F"""Node({self.key}: {self.value})""" @property def __magic_name__ ( self : Dict ): """simple docstring""" return len(self.forward ) class UpperCAmelCase ( Generic[KT, VT] ): '''simple docstring''' def __init__( self : Union[str, Any] , lowerCAmelCase_ : float = 0.5 , lowerCAmelCase_ : int = 1_6 ): """simple docstring""" _A: Node[KT, VT] = Node[KT, VT]() _A: Union[str, Any] = 0 _A: List[str] = p _A: str = max_level def __str__( self : str ): """simple docstring""" _A: Any = list(self ) if len(lowerCAmelCase_ ) == 0: return F"""SkipList(level={self.level})""" _A: Dict = max((len(str(lowerCAmelCase_ ) ) for item in items) , default=4 ) _A: List[Any] = max(lowerCAmelCase_ , 4 ) + 4 _A: List[Any] = self.head _A: Optional[Any] = [] _A: str = node.forward.copy() lines.append(F"""[{node.key}]""".ljust(lowerCAmelCase_ , '''-''' ) + '''* ''' * len(lowerCAmelCase_ ) ) lines.append(''' ''' * label_size + '''| ''' * len(lowerCAmelCase_ ) ) while len(node.forward ) != 0: _A: Optional[int] = node.forward[0] lines.append( F"""[{node.key}]""".ljust(lowerCAmelCase_ , '''-''' ) + ''' '''.join(str(n.key ) if n.key == node.key else '''|''' for n in forwards ) ) lines.append(''' ''' * label_size + '''| ''' * len(lowerCAmelCase_ ) ) _A: List[Any] = node.forward lines.append('''None'''.ljust(lowerCAmelCase_ ) + '''* ''' * len(lowerCAmelCase_ ) ) return F"""SkipList(level={self.level})\n""" + "\n".join(lowerCAmelCase_ ) def __iter__( self : str ): """simple docstring""" _A: Optional[int] = self.head while len(node.forward ) != 0: yield node.forward[0].key _A: Dict = node.forward[0] def __magic_name__ ( self : List[str] ): """simple docstring""" _A: List[str] = 1 while random() < self.p and level < self.max_level: level += 1 return level def __magic_name__ ( self : int , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" _A: Optional[int] = [] _A: Optional[Any] = self.head for i in reversed(range(self.level ) ): # i < node.level - When node level is lesser than `i` decrement `i`. # node.forward[i].key < key - Jumping to node with key value higher # or equal to searched key would result # in skipping searched key. while i < node.level and node.forward[i].key < key: _A: List[Any] = node.forward[i] # Each leftmost node (relative to searched node) will potentially have to # be updated. update_vector.append(lowerCAmelCase_ ) update_vector.reverse() # Note that we were inserting values in reverse order. # len(node.forward) != 0 - If current node doesn't contain any further # references then searched key is not present. # node.forward[0].key == key - Next node key should be equal to search key # if key is present. if len(node.forward ) != 0 and node.forward[0].key == key: return node.forward[0], update_vector else: return None, update_vector def __magic_name__ ( self : Optional[int] , lowerCAmelCase_ : KT ): """simple docstring""" _A , _A: str = self._locate_node(lowerCAmelCase_ ) if node is not None: for i, update_node in enumerate(lowerCAmelCase_ ): # Remove or replace all references to removed node. if update_node.level > i and update_node.forward[i].key == key: if node.level > i: _A: Optional[Any] = node.forward[i] else: _A: List[Any] = update_node.forward[:i] def __magic_name__ ( self : str , lowerCAmelCase_ : KT , lowerCAmelCase_ : VT ): """simple docstring""" _A , _A: Dict = self._locate_node(lowerCAmelCase_ ) if node is not None: _A: Dict = value else: _A: Tuple = self.random_level() if level > self.level: # After level increase we have to add additional nodes to head. for _ in range(self.level - 1 , lowerCAmelCase_ ): update_vector.append(self.head ) _A: Dict = level _A: Tuple = Node(lowerCAmelCase_ , lowerCAmelCase_ ) for i, update_node in enumerate(update_vector[:level] ): # Change references to pass through new node. if update_node.level > i: new_node.forward.append(update_node.forward[i] ) if update_node.level < i + 1: update_node.forward.append(lowerCAmelCase_ ) else: _A: str = new_node def __magic_name__ ( self : Dict , lowerCAmelCase_ : VT ): """simple docstring""" _A , _A: Union[str, Any] = self._locate_node(lowerCAmelCase_ ) if node is not None: return node.value return None def lowerCamelCase__ ( ) -> Tuple: _A: Any = SkipList() skip_list.insert('''Key1''' , 3 ) skip_list.insert('''Key2''' , 12 ) skip_list.insert('''Key3''' , 41 ) skip_list.insert('''Key4''' , -19 ) _A: int = skip_list.head _A: Optional[int] = {} while node.level != 0: _A: Tuple = node.forward[0] _A: List[str] = node.value assert len(a ) == 4 assert all_values["Key1"] == 3 assert all_values["Key2"] == 12 assert all_values["Key3"] == 41 assert all_values["Key4"] == -19 def lowerCamelCase__ ( ) -> Optional[int]: _A: Optional[int] = SkipList() skip_list.insert('''Key1''' , 10 ) skip_list.insert('''Key1''' , 12 ) skip_list.insert('''Key5''' , 7 ) skip_list.insert('''Key7''' , 10 ) skip_list.insert('''Key10''' , 5 ) skip_list.insert('''Key7''' , 7 ) skip_list.insert('''Key5''' , 5 ) skip_list.insert('''Key10''' , 10 ) _A: str = skip_list.head _A: List[str] = {} while node.level != 0: _A: Tuple = node.forward[0] _A: int = node.value if len(a ) != 4: print() assert len(a ) == 4 assert all_values["Key1"] == 12 assert all_values["Key7"] == 7 assert all_values["Key5"] == 5 assert all_values["Key10"] == 10 def lowerCamelCase__ ( ) -> Any: _A: Optional[int] = SkipList() assert skip_list.find('''Some key''' ) is None def lowerCamelCase__ ( ) -> Union[str, Any]: _A: List[str] = SkipList() skip_list.insert('''Key2''' , 20 ) assert skip_list.find('''Key2''' ) == 20 skip_list.insert('''Some Key''' , 10 ) skip_list.insert('''Key2''' , 8 ) skip_list.insert('''V''' , 13 ) assert skip_list.find('''Y''' ) is None assert skip_list.find('''Key2''' ) == 8 assert skip_list.find('''Some Key''' ) == 10 assert skip_list.find('''V''' ) == 13 def lowerCamelCase__ ( ) -> Union[str, Any]: _A: Tuple = SkipList() skip_list.delete('''Some key''' ) assert len(skip_list.head.forward ) == 0 def lowerCamelCase__ ( ) -> Dict: _A: int = SkipList() skip_list.insert('''Key1''' , 12 ) skip_list.insert('''V''' , 13 ) skip_list.insert('''X''' , 14 ) skip_list.insert('''Key2''' , 15 ) skip_list.delete('''V''' ) skip_list.delete('''Key2''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''Key2''' ) is None def lowerCamelCase__ ( ) -> Optional[Any]: _A: Union[str, Any] = SkipList() skip_list.insert('''Key1''' , 12 ) skip_list.insert('''V''' , 13 ) skip_list.insert('''X''' , 14 ) skip_list.insert('''Key2''' , 15 ) skip_list.delete('''V''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''X''' ) == 14 assert skip_list.find('''Key1''' ) == 12 assert skip_list.find('''Key2''' ) == 15 skip_list.delete('''X''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''X''' ) is None assert skip_list.find('''Key1''' ) == 12 assert skip_list.find('''Key2''' ) == 15 skip_list.delete('''Key1''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''X''' ) is None assert skip_list.find('''Key1''' ) is None assert skip_list.find('''Key2''' ) == 15 skip_list.delete('''Key2''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''X''' ) is None assert skip_list.find('''Key1''' ) is None assert skip_list.find('''Key2''' ) is None def lowerCamelCase__ ( ) -> List[Any]: _A: Any = SkipList() skip_list.insert('''Key1''' , 12 ) skip_list.insert('''V''' , 13 ) skip_list.insert('''X''' , 1_42 ) skip_list.insert('''Key2''' , 15 ) skip_list.delete('''X''' ) def traverse_keys(a ): yield node.key for forward_node in node.forward: yield from traverse_keys(a ) assert len(set(traverse_keys(skip_list.head ) ) ) == 4 def lowerCamelCase__ ( ) -> Optional[Any]: def is_sorted(a ): return all(next_item >= item for item, next_item in zip(a , lst[1:] ) ) _A: Dict = SkipList() for i in range(10 ): skip_list.insert(a , a ) assert is_sorted(list(a ) ) skip_list.delete(5 ) skip_list.delete(8 ) skip_list.delete(2 ) assert is_sorted(list(a ) ) skip_list.insert(-12 , -12 ) skip_list.insert(77 , 77 ) assert is_sorted(list(a ) ) def lowerCamelCase__ ( ) -> Tuple: for _ in range(1_00 ): # Repeat test 100 times due to the probabilistic nature of skip list # random values == random bugs test_insert() test_insert_overrides_existing_value() test_searching_empty_list_returns_none() test_search() test_deleting_item_from_empty_list_do_nothing() test_deleted_items_are_not_founded_by_find_method() test_delete_removes_only_given_key() test_delete_doesnt_leave_dead_nodes() test_iter_always_yields_sorted_values() def lowerCamelCase__ ( ) -> int: _A: Tuple = SkipList() skip_list.insert(2 , '''2''' ) skip_list.insert(4 , '''4''' ) skip_list.insert(6 , '''4''' ) skip_list.insert(4 , '''5''' ) skip_list.insert(8 , '''4''' ) skip_list.insert(9 , '''4''' ) skip_list.delete(4 ) print(a ) if __name__ == "__main__": import doctest doctest.testmod() main()
301
import json import os from typing import Dict, List, Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase__ : List[Any] = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } UpperCAmelCase__ : Tuple = { '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__ : Optional[int] = {'facebook/blenderbot_small-90M': 512} def lowerCamelCase__ ( a ) -> Optional[Any]: _A: List[Any] = set() _A: List[Any] = word[0] for char in word[1:]: pairs.add((prev_char, char) ) _A: List[Any] = char _A: Union[str, Any] = set(a ) return pairs class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : str = VOCAB_FILES_NAMES __UpperCamelCase : List[Any] = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase : Union[str, Any] = ['''input_ids''', '''attention_mask'''] def __init__( self : int , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : List[str]="__start__" , lowerCAmelCase_ : Any="__end__" , lowerCAmelCase_ : Any="__unk__" , lowerCAmelCase_ : Any="__null__" , **lowerCAmelCase_ : int , ): """simple docstring""" super().__init__(unk_token=lowerCAmelCase_ , bos_token=lowerCAmelCase_ , eos_token=lowerCAmelCase_ , pad_token=lowerCAmelCase_ , **lowerCAmelCase_ ) with open(lowerCAmelCase_ , encoding='''utf-8''' ) as vocab_handle: _A: Optional[int] = json.load(lowerCAmelCase_ ) _A: int = {v: k for k, v in self.encoder.items()} with open(lowerCAmelCase_ , encoding='''utf-8''' ) as merges_handle: _A: Dict = merges_handle.read().split('''\n''' )[1:-1] _A: int = [tuple(merge.split() ) for merge in merges] _A: Dict = dict(zip(lowerCAmelCase_ , range(len(lowerCAmelCase_ ) ) ) ) _A: Union[str, Any] = {} @property def __magic_name__ ( self : Optional[int] ): """simple docstring""" return len(self.encoder ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def __magic_name__ ( self : str , lowerCAmelCase_ : str ): """simple docstring""" if token in self.cache: return self.cache[token] _A: List[Any] = re.sub('''([.,!?()])''' , R''' \1''' , lowerCAmelCase_ ) _A: List[Any] = re.sub('''(\')''' , R''' \1 ''' , lowerCAmelCase_ ) _A: List[Any] = re.sub(R'''\s{2,}''' , ''' ''' , lowerCAmelCase_ ) if "\n" in token: _A: Dict = token.replace('''\n''' , ''' __newln__''' ) _A: Any = token.split(''' ''' ) _A: Optional[Any] = [] for token in tokens: if not len(lowerCAmelCase_ ): continue _A: str = token.lower() _A: List[str] = tuple(lowerCAmelCase_ ) _A: str = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] ) _A: Dict = get_pairs(lowerCAmelCase_ ) if not pairs: words.append(lowerCAmelCase_ ) continue while True: _A: str = min(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : self.bpe_ranks.get(lowerCAmelCase_ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break _A , _A: Optional[int] = bigram _A: str = [] _A: Dict = 0 while i < len(lowerCAmelCase_ ): try: _A: List[Any] = word.index(lowerCAmelCase_ , lowerCAmelCase_ ) new_word.extend(word[i:j] ) _A: Optional[int] = j except ValueError: new_word.extend(word[i:] ) break if word[i] == first and i < len(lowerCAmelCase_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 _A: Union[str, Any] = tuple(lowerCAmelCase_ ) _A: Tuple = new_word if len(lowerCAmelCase_ ) == 1: break else: _A: Optional[int] = get_pairs(lowerCAmelCase_ ) _A: str = '''@@ '''.join(lowerCAmelCase_ ) _A: Tuple = word[:-4] _A: List[Any] = word words.append(lowerCAmelCase_ ) return " ".join(lowerCAmelCase_ ) def __magic_name__ ( self : str , lowerCAmelCase_ : str ): """simple docstring""" _A: List[Any] = [] _A: List[Any] = re.findall(R'''\S+\n?''' , lowerCAmelCase_ ) for token in words: split_tokens.extend(list(self.bpe(lowerCAmelCase_ ).split(''' ''' ) ) ) return split_tokens def __magic_name__ ( self : str , lowerCAmelCase_ : str ): """simple docstring""" _A: List[str] = token.lower() return self.encoder.get(lowerCAmelCase_ , self.encoder.get(self.unk_token ) ) def __magic_name__ ( self : int , lowerCAmelCase_ : int ): """simple docstring""" return self.decoder.get(lowerCAmelCase_ , self.unk_token ) def __magic_name__ ( self : List[str] , lowerCAmelCase_ : List[str] ): """simple docstring""" _A: List[str] = ''' '''.join(lowerCAmelCase_ ).replace('''@@ ''' , '''''' ).strip() return out_string def __magic_name__ ( self : List[Any] , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[str] = None ): """simple docstring""" if not os.path.isdir(lowerCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _A: Dict = os.path.join( lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) _A: Any = os.path.join( lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(lowerCAmelCase_ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=lowerCAmelCase_ , ensure_ascii=lowerCAmelCase_ ) + '''\n''' ) _A: List[str] = 0 with open(lowerCAmelCase_ , '''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 lowerCAmelCase_ : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" ''' Please check that the tokenizer is not corrupted!''' ) _A: Optional[int] = token_index writer.write(''' '''.join(lowerCAmelCase_ ) + '''\n''' ) index += 1 return vocab_file, merge_file
301
1
import os import sys import tempfile import torch from .state import AcceleratorState from .utils import PrecisionType, PrepareForLaunch, is_mps_available, patch_environment def lowerCamelCase__ ( a , a=() , a=None , a="no" , a="29500" ) -> int: _A: Dict = False _A: Dict = False if any(key.startswith('''KAGGLE''' ) for key in os.environ.keys() ): _A: Any = True elif "IPython" in sys.modules: _A: Any = '''google.colab''' in str(sys.modules['''IPython'''].get_ipython() ) try: _A: Tuple = PrecisionType(mixed_precision.lower() ) except ValueError: raise ValueError( f"""Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}.""" ) if (in_colab or in_kaggle) and (os.environ.get('''TPU_NAME''' , a ) is not None): # TPU launch import torch_xla.distributed.xla_multiprocessing as xmp if len(AcceleratorState._shared_state ) > 0: raise ValueError( '''To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside ''' '''your training function. Restart your notebook and make sure no cells initializes an ''' '''`Accelerator`.''' ) if num_processes is None: _A: Dict = 8 _A: Tuple = PrepareForLaunch(a , distributed_type='''TPU''' ) print(f"""Launching a training on {num_processes} TPU cores.""" ) xmp.spawn(a , args=a , nprocs=a , start_method='''fork''' ) elif in_colab: # No need for a distributed launch otherwise as it's either CPU or one GPU. if torch.cuda.is_available(): print('''Launching training on one GPU.''' ) else: print('''Launching training on one CPU.''' ) function(*a ) else: if num_processes is None: raise ValueError( '''You have to specify the number of GPUs you would like to use, add `num_processes=...` to your call.''' ) if num_processes > 1: # Multi-GPU launch from torch.multiprocessing import start_processes from torch.multiprocessing.spawn import ProcessRaisedException if len(AcceleratorState._shared_state ) > 0: raise ValueError( '''To launch a multi-GPU training from your notebook, the `Accelerator` should only be initialized ''' '''inside your training function. Restart your notebook and make sure no cells initializes an ''' '''`Accelerator`.''' ) if torch.cuda.is_initialized(): raise ValueError( '''To launch a multi-GPU training from your notebook, you need to avoid running any instruction ''' '''using `torch.cuda` in any cell. Restart your notebook and make sure no cells use any CUDA ''' '''function.''' ) # torch.distributed will expect a few environment variable to be here. We set the ones common to each # process here (the other ones will be set be the launcher). with patch_environment( world_size=a , master_addr='''127.0.01''' , master_port=a , mixed_precision=a ): _A: Optional[Any] = PrepareForLaunch(a , distributed_type='''MULTI_GPU''' ) print(f"""Launching training on {num_processes} GPUs.""" ) try: start_processes(a , args=a , nprocs=a , start_method='''fork''' ) except ProcessRaisedException as e: if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]: raise RuntimeError( '''CUDA has been initialized before the `notebook_launcher` could create a forked subprocess. ''' '''This likely stems from an outside import causing issues once the `notebook_launcher()` is called. ''' '''Please review your imports and test them when running the `notebook_launcher()` to identify ''' '''which one is problematic.''' ) from e else: # No need for a distributed launch otherwise as it's either CPU, GPU or MPS. if is_mps_available(): _A: Any = '''1''' print('''Launching training on MPS.''' ) elif torch.cuda.is_available(): print('''Launching training on one GPU.''' ) else: print('''Launching training on CPU.''' ) function(*a ) def lowerCamelCase__ ( a , a=() , a=2 ) -> List[str]: from torch.multiprocessing import start_processes with tempfile.NamedTemporaryFile() as tmp_file: # torch.distributed will expect a few environment variable to be here. We set the ones common to each # process here (the other ones will be set be the launcher). with patch_environment( world_size=a , master_addr='''127.0.01''' , master_port='''29500''' , accelerate_mixed_precision='''no''' , accelerate_debug_rdv_file=tmp_file.name , accelerate_use_cpu='''yes''' , ): _A: int = PrepareForLaunch(a , debug=a ) start_processes(a , args=a , nprocs=a , start_method='''fork''' )
301
import os from pathlib import Path def lowerCamelCase__ ( ) -> Optional[Any]: from torch.utils.cpp_extension import load _A: str = Path(a ).resolve().parent.parent.parent / '''kernels''' / '''deformable_detr''' _A: Tuple = [ root / filename for filename in [ '''vision.cpp''', os.path.join('''cpu''' , '''ms_deform_attn_cpu.cpp''' ), os.path.join('''cuda''' , '''ms_deform_attn_cuda.cu''' ), ] ] load( '''MultiScaleDeformableAttention''' , a , with_cuda=a , extra_include_paths=[str(a )] , extra_cflags=['''-DWITH_CUDA=1'''] , extra_cuda_cflags=[ '''-DCUDA_HAS_FP16=1''', '''-D__CUDA_NO_HALF_OPERATORS__''', '''-D__CUDA_NO_HALF_CONVERSIONS__''', '''-D__CUDA_NO_HALF2_OPERATORS__''', ] , ) import MultiScaleDeformableAttention as MSDA return MSDA
301
1
import sys import turtle def lowerCamelCase__ ( a , a ) -> tuple[float, float]: return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def lowerCamelCase__ ( a , a , a , a , ) -> None: 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(a , get_mid(a , a ) , get_mid(a , a ) , depth - 1 ) triangle(a , get_mid(a , a ) , get_mid(a , a ) , depth - 1 ) triangle(a , get_mid(a , a ) , get_mid(a , a ) , 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>' ) UpperCAmelCase__ : Union[str, Any] = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor('red') UpperCAmelCase__ : Union[str, Any] = [(-175, -125), (0, 175), (175, -125)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
301
from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Optional[int] = ['''image_processor''', '''tokenizer'''] __UpperCamelCase : Optional[Any] = '''BlipImageProcessor''' __UpperCamelCase : int = ('''BertTokenizer''', '''BertTokenizerFast''') def __init__( self : Optional[int] , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" _A: Optional[Any] = False super().__init__(lowerCAmelCase_ , lowerCAmelCase_ ) _A: List[Any] = self.image_processor def __call__( self : Optional[Any] , lowerCAmelCase_ : ImageInput = None , lowerCAmelCase_ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , lowerCAmelCase_ : bool = True , lowerCAmelCase_ : Union[bool, str, PaddingStrategy] = False , lowerCAmelCase_ : Union[bool, str, TruncationStrategy] = None , lowerCAmelCase_ : Optional[int] = None , lowerCAmelCase_ : int = 0 , lowerCAmelCase_ : Optional[int] = None , lowerCAmelCase_ : Optional[bool] = None , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = True , lowerCAmelCase_ : Optional[Union[str, TensorType]] = None , **lowerCAmelCase_ : Union[str, Any] , ): """simple docstring""" if images is None and text is None: raise ValueError('''You have to specify either images or text.''' ) # Get only text if images is None: _A: Tuple = self.tokenizer _A: Optional[int] = self.tokenizer( text=lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ , padding=lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ , stride=lowerCAmelCase_ , pad_to_multiple_of=lowerCAmelCase_ , return_attention_mask=lowerCAmelCase_ , return_overflowing_tokens=lowerCAmelCase_ , return_special_tokens_mask=lowerCAmelCase_ , return_offsets_mapping=lowerCAmelCase_ , return_token_type_ids=lowerCAmelCase_ , return_length=lowerCAmelCase_ , verbose=lowerCAmelCase_ , return_tensors=lowerCAmelCase_ , **lowerCAmelCase_ , ) return text_encoding # add pixel_values _A: List[Any] = self.image_processor(lowerCAmelCase_ , return_tensors=lowerCAmelCase_ ) if text is not None: _A: Tuple = self.tokenizer( text=lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ , padding=lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ , stride=lowerCAmelCase_ , pad_to_multiple_of=lowerCAmelCase_ , return_attention_mask=lowerCAmelCase_ , return_overflowing_tokens=lowerCAmelCase_ , return_special_tokens_mask=lowerCAmelCase_ , return_offsets_mapping=lowerCAmelCase_ , return_token_type_ids=lowerCAmelCase_ , return_length=lowerCAmelCase_ , verbose=lowerCAmelCase_ , return_tensors=lowerCAmelCase_ , **lowerCAmelCase_ , ) else: _A: str = None if text_encoding is not None: encoding_image_processor.update(lowerCAmelCase_ ) return encoding_image_processor def __magic_name__ ( self : Optional[Any] , *lowerCAmelCase_ : Union[str, Any] , **lowerCAmelCase_ : Tuple ): """simple docstring""" return self.tokenizer.batch_decode(*lowerCAmelCase_ , **lowerCAmelCase_ ) def __magic_name__ ( self : Union[str, Any] , *lowerCAmelCase_ : int , **lowerCAmelCase_ : Optional[int] ): """simple docstring""" return self.tokenizer.decode(*lowerCAmelCase_ , **lowerCAmelCase_ ) @property def __magic_name__ ( self : Dict ): """simple docstring""" _A: Dict = self.tokenizer.model_input_names _A: List[str] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
301
1
import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all feature extractors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...feature_extraction_utils import FeatureExtractionMixin from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) UpperCAmelCase__ : Any = logging.get_logger(__name__) UpperCAmelCase__ : Tuple = OrderedDict( [ ('audio-spectrogram-transformer', 'ASTFeatureExtractor'), ('beit', 'BeitFeatureExtractor'), ('chinese_clip', 'ChineseCLIPFeatureExtractor'), ('clap', 'ClapFeatureExtractor'), ('clip', 'CLIPFeatureExtractor'), ('clipseg', 'ViTFeatureExtractor'), ('conditional_detr', 'ConditionalDetrFeatureExtractor'), ('convnext', 'ConvNextFeatureExtractor'), ('cvt', 'ConvNextFeatureExtractor'), ('data2vec-audio', 'Wav2Vec2FeatureExtractor'), ('data2vec-vision', 'BeitFeatureExtractor'), ('deformable_detr', 'DeformableDetrFeatureExtractor'), ('deit', 'DeiTFeatureExtractor'), ('detr', 'DetrFeatureExtractor'), ('dinat', 'ViTFeatureExtractor'), ('donut-swin', 'DonutFeatureExtractor'), ('dpt', 'DPTFeatureExtractor'), ('encodec', 'EncodecFeatureExtractor'), ('flava', 'FlavaFeatureExtractor'), ('glpn', 'GLPNFeatureExtractor'), ('groupvit', 'CLIPFeatureExtractor'), ('hubert', 'Wav2Vec2FeatureExtractor'), ('imagegpt', 'ImageGPTFeatureExtractor'), ('layoutlmv2', 'LayoutLMv2FeatureExtractor'), ('layoutlmv3', 'LayoutLMv3FeatureExtractor'), ('levit', 'LevitFeatureExtractor'), ('maskformer', 'MaskFormerFeatureExtractor'), ('mctct', 'MCTCTFeatureExtractor'), ('mobilenet_v1', 'MobileNetV1FeatureExtractor'), ('mobilenet_v2', 'MobileNetV2FeatureExtractor'), ('mobilevit', 'MobileViTFeatureExtractor'), ('nat', 'ViTFeatureExtractor'), ('owlvit', 'OwlViTFeatureExtractor'), ('perceiver', 'PerceiverFeatureExtractor'), ('poolformer', 'PoolFormerFeatureExtractor'), ('regnet', 'ConvNextFeatureExtractor'), ('resnet', 'ConvNextFeatureExtractor'), ('segformer', 'SegformerFeatureExtractor'), ('sew', 'Wav2Vec2FeatureExtractor'), ('sew-d', 'Wav2Vec2FeatureExtractor'), ('speech_to_text', 'Speech2TextFeatureExtractor'), ('speecht5', 'SpeechT5FeatureExtractor'), ('swiftformer', 'ViTFeatureExtractor'), ('swin', 'ViTFeatureExtractor'), ('swinv2', 'ViTFeatureExtractor'), ('table-transformer', 'DetrFeatureExtractor'), ('timesformer', 'VideoMAEFeatureExtractor'), ('tvlt', 'TvltFeatureExtractor'), ('unispeech', 'Wav2Vec2FeatureExtractor'), ('unispeech-sat', 'Wav2Vec2FeatureExtractor'), ('van', 'ConvNextFeatureExtractor'), ('videomae', 'VideoMAEFeatureExtractor'), ('vilt', 'ViltFeatureExtractor'), ('vit', 'ViTFeatureExtractor'), ('vit_mae', 'ViTFeatureExtractor'), ('vit_msn', 'ViTFeatureExtractor'), ('wav2vec2', 'Wav2Vec2FeatureExtractor'), ('wav2vec2-conformer', 'Wav2Vec2FeatureExtractor'), ('wavlm', 'Wav2Vec2FeatureExtractor'), ('whisper', 'WhisperFeatureExtractor'), ('xclip', 'CLIPFeatureExtractor'), ('yolos', 'YolosFeatureExtractor'), ] ) UpperCAmelCase__ : int = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES) def lowerCamelCase__ ( a ) -> int: for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items(): if class_name in extractors: _A: Any = model_type_to_module_name(a ) _A: List[str] = importlib.import_module(f""".{module_name}""" , '''transformers.models''' ) try: return getattr(a , a ) except AttributeError: continue for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items(): if getattr(a , '''__name__''' , a ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. _A: Dict = importlib.import_module('''transformers''' ) if hasattr(a , a ): return getattr(a , a ) return None def lowerCamelCase__ ( a , a = None , a = False , a = False , a = None , a = None , a = None , a = False , **a , ) -> Any: _A: int = get_file_from_repo( a , a , cache_dir=a , force_download=a , resume_download=a , proxies=a , use_auth_token=a , revision=a , local_files_only=a , ) if resolved_config_file is None: logger.info( '''Could not locate the feature extractor configuration file, will try to use the model config instead.''' ) return {} with open(a , encoding='''utf-8''' ) as reader: return json.load(a ) class UpperCAmelCase : '''simple docstring''' def __init__( self : Any ): """simple docstring""" raise EnvironmentError( '''AutoFeatureExtractor is designed to be instantiated ''' '''using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method.''' ) @classmethod @replace_list_option_in_docstrings(lowerCAmelCase_ ) def __magic_name__ ( cls : Union[str, Any] , lowerCAmelCase_ : str , **lowerCAmelCase_ : Any ): """simple docstring""" _A: Tuple = kwargs.pop('''config''' , lowerCAmelCase_ ) _A: Optional[Any] = kwargs.pop('''trust_remote_code''' , lowerCAmelCase_ ) _A: int = True _A , _A: List[str] = FeatureExtractionMixin.get_feature_extractor_dict(lowerCAmelCase_ , **lowerCAmelCase_ ) _A: Union[str, Any] = config_dict.get('''feature_extractor_type''' , lowerCAmelCase_ ) _A: int = None if "AutoFeatureExtractor" in config_dict.get('''auto_map''' , {} ): _A: List[str] = config_dict['''auto_map''']['''AutoFeatureExtractor'''] # If we don't find the feature extractor class in the feature extractor config, let's try the model config. if feature_extractor_class is None and feature_extractor_auto_map is None: if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): _A: Dict = AutoConfig.from_pretrained(lowerCAmelCase_ , **lowerCAmelCase_ ) # It could be in `config.feature_extractor_type`` _A: List[str] = getattr(lowerCAmelCase_ , '''feature_extractor_type''' , lowerCAmelCase_ ) if hasattr(lowerCAmelCase_ , '''auto_map''' ) and "AutoFeatureExtractor" in config.auto_map: _A: List[str] = config.auto_map['''AutoFeatureExtractor'''] if feature_extractor_class is not None: _A: Dict = feature_extractor_class_from_name(lowerCAmelCase_ ) _A: int = feature_extractor_auto_map is not None _A: List[Any] = feature_extractor_class is not None or type(lowerCAmelCase_ ) in FEATURE_EXTRACTOR_MAPPING _A: Any = resolve_trust_remote_code( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) if has_remote_code and trust_remote_code: _A: Optional[Any] = get_class_from_dynamic_module( lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ) _A: List[str] = kwargs.pop('''code_revision''' , lowerCAmelCase_ ) if os.path.isdir(lowerCAmelCase_ ): feature_extractor_class.register_for_auto_class() return feature_extractor_class.from_dict(lowerCAmelCase_ , **lowerCAmelCase_ ) elif feature_extractor_class is not None: return feature_extractor_class.from_dict(lowerCAmelCase_ , **lowerCAmelCase_ ) # Last try: we use the FEATURE_EXTRACTOR_MAPPING. elif type(lowerCAmelCase_ ) in FEATURE_EXTRACTOR_MAPPING: _A: Any = FEATURE_EXTRACTOR_MAPPING[type(lowerCAmelCase_ )] return feature_extractor_class.from_dict(lowerCAmelCase_ , **lowerCAmelCase_ ) raise ValueError( F"""Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a """ F"""`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following """ F"""`model_type` keys in its {CONFIG_NAME}: {', '.join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys() )}""" ) @staticmethod def __magic_name__ ( lowerCAmelCase_ : Tuple , lowerCAmelCase_ : List[Any] ): """simple docstring""" FEATURE_EXTRACTOR_MAPPING.register(lowerCAmelCase_ , lowerCAmelCase_ )
301
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : Union[str, Any] = { 'google/mobilenet_v1_1.0_224': 'https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json', 'google/mobilenet_v1_0.75_192': 'https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 } class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Optional[int] = '''mobilenet_v1''' def __init__( self : Optional[int] , lowerCAmelCase_ : Any=3 , lowerCAmelCase_ : str=2_2_4 , lowerCAmelCase_ : List[str]=1.0 , lowerCAmelCase_ : Any=8 , lowerCAmelCase_ : Tuple="relu6" , lowerCAmelCase_ : List[Any]=True , lowerCAmelCase_ : Optional[int]=0.999 , lowerCAmelCase_ : List[str]=0.02 , lowerCAmelCase_ : List[Any]=0.001 , **lowerCAmelCase_ : Optional[Any] , ): """simple docstring""" super().__init__(**lowerCAmelCase_ ) if depth_multiplier <= 0: raise ValueError('''depth_multiplier must be greater than zero.''' ) _A: Any = num_channels _A: Optional[int] = image_size _A: Optional[Any] = depth_multiplier _A: Tuple = min_depth _A: Any = hidden_act _A: Dict = tf_padding _A: List[Any] = classifier_dropout_prob _A: Tuple = initializer_range _A: Tuple = layer_norm_eps class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Dict = version.parse('''1.11''' ) @property def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" return OrderedDict([('''pixel_values''', {0: '''batch'''})] ) @property def __magic_name__ ( self : Optional[Any] ): """simple docstring""" if self.task == "image-classification": return OrderedDict([('''logits''', {0: '''batch'''})] ) else: return OrderedDict([('''last_hidden_state''', {0: '''batch'''}), ('''pooler_output''', {0: '''batch'''})] ) @property def __magic_name__ ( self : Dict ): """simple docstring""" return 1e-4
301
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ : List[str] = logging.get_logger(__name__) UpperCAmelCase__ : Union[str, Any] = { 'facebook/dpr-ctx_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json' ), 'facebook/dpr-question_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json' ), 'facebook/dpr-reader-single-nq-base': ( 'https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json' ), 'facebook/dpr-ctx_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json' ), 'facebook/dpr-question_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json' ), 'facebook/dpr-reader-multiset-base': ( 'https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json' ), } class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Optional[Any] = '''dpr''' def __init__( self : Tuple , lowerCAmelCase_ : str=3_0_5_2_2 , lowerCAmelCase_ : List[Any]=7_6_8 , lowerCAmelCase_ : Optional[int]=1_2 , lowerCAmelCase_ : Optional[int]=1_2 , lowerCAmelCase_ : int=3_0_7_2 , lowerCAmelCase_ : Optional[Any]="gelu" , lowerCAmelCase_ : List[str]=0.1 , lowerCAmelCase_ : Optional[int]=0.1 , lowerCAmelCase_ : List[str]=5_1_2 , lowerCAmelCase_ : Tuple=2 , lowerCAmelCase_ : str=0.02 , lowerCAmelCase_ : Optional[int]=1e-12 , lowerCAmelCase_ : Tuple=0 , lowerCAmelCase_ : Optional[Any]="absolute" , lowerCAmelCase_ : int = 0 , **lowerCAmelCase_ : Optional[Any] , ): """simple docstring""" super().__init__(pad_token_id=lowerCAmelCase_ , **lowerCAmelCase_ ) _A: Tuple = vocab_size _A: Optional[Any] = hidden_size _A: int = num_hidden_layers _A: List[str] = num_attention_heads _A: Dict = hidden_act _A: Tuple = intermediate_size _A: Dict = hidden_dropout_prob _A: Optional[Any] = attention_probs_dropout_prob _A: str = max_position_embeddings _A: Any = type_vocab_size _A: Dict = initializer_range _A: str = layer_norm_eps _A: Union[str, Any] = projection_dim _A: Union[str, Any] = position_embedding_type
301
import argparse import json import os from tensorflow.core.protobuf.saved_model_pba import SavedModel # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py UpperCAmelCase__ : Any = '.' # Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model) UpperCAmelCase__ : Optional[Any] = [ 'Assert', 'AssignVariableOp', 'EmptyTensorList', 'MergeV2Checkpoints', 'ReadVariableOp', 'ResourceGather', 'RestoreV2', 'SaveV2', 'ShardedFilename', 'StatefulPartitionedCall', 'StaticRegexFullMatch', 'VarHandleOp', ] def lowerCamelCase__ ( a , a , a ) -> Union[str, Any]: _A: Optional[int] = SavedModel() _A: int = [] with open(os.path.join(a , '''utils''' , '''tf_ops''' , '''onnx.json''' ) ) as f: _A: List[Any] = json.load(a )['''opsets'''] for i in range(1 , opset + 1 ): onnx_ops.extend(onnx_opsets[str(a )] ) with open(a , '''rb''' ) as f: saved_model.ParseFromString(f.read() ) _A: Optional[Any] = set() # Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs) for meta_graph in saved_model.meta_graphs: # Add operations in the graph definition model_op_names.update(node.op for node in meta_graph.graph_def.node ) # Go through the functions in the graph definition for func in meta_graph.graph_def.library.function: # Add operations in each function model_op_names.update(node.op for node in func.node_def ) # Convert to list, sorted if you want _A: Optional[int] = sorted(a ) _A: Tuple = [] for op in model_op_names: if op not in onnx_ops and op not in INTERNAL_OPS: incompatible_ops.append(a ) if strict and len(a ) > 0: raise Exception(f"""Found the following incompatible ops for the opset {opset}:\n""" + incompatible_ops ) elif len(a ) > 0: print(f"""Found the following incompatible ops for the opset {opset}:""" ) print(*a , sep='''\n''' ) else: print(f"""The saved model {saved_model_path} can properly be converted with ONNX.""" ) if __name__ == "__main__": UpperCAmelCase__ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument('--saved_model_path', help='Path of the saved model to check (the .pb file).') parser.add_argument( '--opset', default=12, type=int, help='The ONNX opset against which the model has to be tested.' ) parser.add_argument( '--framework', choices=['onnx'], default='onnx', help='Frameworks against which to test the saved model.' ) parser.add_argument( '--strict', action='store_true', help='Whether make the checking strict (raise errors) or not (raise warnings)' ) UpperCAmelCase__ : int = parser.parse_args() if args.framework == "onnx": onnx_compliancy(args.saved_model_path, args.strict, args.opset)
301
1
import torch from diffusers import DDPMParallelScheduler from .test_schedulers import SchedulerCommonTest class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Any = (DDPMParallelScheduler,) def __magic_name__ ( self : Optional[int] , **lowerCAmelCase_ : Any ): """simple docstring""" _A: Optional[int] = { '''num_train_timesteps''': 1_0_0_0, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''variance_type''': '''fixed_small''', '''clip_sample''': True, } config.update(**lowerCAmelCase_ ) return config def __magic_name__ ( self : int ): """simple docstring""" for timesteps in [1, 5, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=lowerCAmelCase_ ) def __magic_name__ ( self : Tuple ): """simple docstring""" for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=lowerCAmelCase_ , beta_end=lowerCAmelCase_ ) def __magic_name__ ( self : Optional[Any] ): """simple docstring""" for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=lowerCAmelCase_ ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=lowerCAmelCase_ ) def __magic_name__ ( self : Tuple ): """simple docstring""" for clip_sample in [True, False]: self.check_over_configs(clip_sample=lowerCAmelCase_ ) def __magic_name__ ( self : List[str] ): """simple docstring""" self.check_over_configs(thresholding=lowerCAmelCase_ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=lowerCAmelCase_ , prediction_type=lowerCAmelCase_ , sample_max_value=lowerCAmelCase_ , ) def __magic_name__ ( self : Dict ): """simple docstring""" for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=lowerCAmelCase_ ) def __magic_name__ ( self : int ): """simple docstring""" for t in [0, 5_0_0, 9_9_9]: self.check_over_forward(time_step=lowerCAmelCase_ ) def __magic_name__ ( self : Any ): """simple docstring""" _A: List[Any] = self.scheduler_classes[0] _A: Union[str, Any] = self.get_scheduler_config() _A: Optional[Any] = scheduler_class(**lowerCAmelCase_ ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_8_7 ) - 0.00979 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_9_9 ) - 0.02 ) ) < 1e-5 def __magic_name__ ( self : Optional[int] ): """simple docstring""" _A: Any = self.scheduler_classes[0] _A: List[str] = self.get_scheduler_config() _A: Union[str, Any] = scheduler_class(**lowerCAmelCase_ ) _A: List[Any] = len(lowerCAmelCase_ ) _A: Union[str, Any] = self.dummy_model() _A: Dict = self.dummy_sample_deter _A: Dict = self.dummy_sample_deter + 0.1 _A: str = self.dummy_sample_deter - 0.1 _A: str = samplea.shape[0] _A: Optional[Any] = torch.stack([samplea, samplea, samplea] , dim=0 ) _A: List[str] = torch.arange(lowerCAmelCase_ )[0:3, None].repeat(1 , lowerCAmelCase_ ) _A: List[Any] = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) _A: Optional[int] = scheduler.batch_step_no_noise(lowerCAmelCase_ , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) ) _A: Dict = torch.sum(torch.abs(lowerCAmelCase_ ) ) _A: List[str] = torch.mean(torch.abs(lowerCAmelCase_ ) ) assert abs(result_sum.item() - 1153.1833 ) < 1e-2 assert abs(result_mean.item() - 0.5005 ) < 1e-3 def __magic_name__ ( self : Tuple ): """simple docstring""" _A: Optional[Any] = self.scheduler_classes[0] _A: List[Any] = self.get_scheduler_config() _A: Any = scheduler_class(**lowerCAmelCase_ ) _A: Union[str, Any] = len(lowerCAmelCase_ ) _A: Any = self.dummy_model() _A: Optional[int] = self.dummy_sample_deter _A: List[str] = torch.manual_seed(0 ) for t in reversed(range(lowerCAmelCase_ ) ): # 1. predict noise residual _A: Optional[int] = model(lowerCAmelCase_ , lowerCAmelCase_ ) # 2. predict previous mean of sample x_t-1 _A: Optional[int] = scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , generator=lowerCAmelCase_ ).prev_sample _A: List[Any] = pred_prev_sample _A: Optional[int] = torch.sum(torch.abs(lowerCAmelCase_ ) ) _A: Any = torch.mean(torch.abs(lowerCAmelCase_ ) ) assert abs(result_sum.item() - 258.9606 ) < 1e-2 assert abs(result_mean.item() - 0.3372 ) < 1e-3 def __magic_name__ ( self : Tuple ): """simple docstring""" _A: Optional[int] = self.scheduler_classes[0] _A: Union[str, Any] = self.get_scheduler_config(prediction_type='''v_prediction''' ) _A: List[str] = scheduler_class(**lowerCAmelCase_ ) _A: Union[str, Any] = len(lowerCAmelCase_ ) _A: Any = self.dummy_model() _A: Any = self.dummy_sample_deter _A: str = torch.manual_seed(0 ) for t in reversed(range(lowerCAmelCase_ ) ): # 1. predict noise residual _A: Any = model(lowerCAmelCase_ , lowerCAmelCase_ ) # 2. predict previous mean of sample x_t-1 _A: int = scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , generator=lowerCAmelCase_ ).prev_sample _A: Tuple = pred_prev_sample _A: List[Any] = torch.sum(torch.abs(lowerCAmelCase_ ) ) _A: str = torch.mean(torch.abs(lowerCAmelCase_ ) ) assert abs(result_sum.item() - 202.0296 ) < 1e-2 assert abs(result_mean.item() - 0.2631 ) < 1e-3 def __magic_name__ ( self : Optional[int] ): """simple docstring""" _A: Optional[int] = self.scheduler_classes[0] _A: Optional[Any] = self.get_scheduler_config() _A: Dict = scheduler_class(**lowerCAmelCase_ ) _A: Any = [1_0_0, 8_7, 5_0, 1, 0] scheduler.set_timesteps(timesteps=lowerCAmelCase_ ) _A: Tuple = scheduler.timesteps for i, timestep in enumerate(lowerCAmelCase_ ): if i == len(lowerCAmelCase_ ) - 1: _A: Dict = -1 else: _A: int = timesteps[i + 1] _A: List[str] = scheduler.previous_timestep(lowerCAmelCase_ ) _A: str = prev_t.item() self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) def __magic_name__ ( self : Any ): """simple docstring""" _A: Tuple = self.scheduler_classes[0] _A: int = self.get_scheduler_config() _A: Any = scheduler_class(**lowerCAmelCase_ ) _A: Union[str, Any] = [1_0_0, 8_7, 5_0, 5_1, 0] with self.assertRaises(lowerCAmelCase_ , msg='''`custom_timesteps` must be in descending order.''' ): scheduler.set_timesteps(timesteps=lowerCAmelCase_ ) def __magic_name__ ( self : int ): """simple docstring""" _A: List[str] = self.scheduler_classes[0] _A: Optional[Any] = self.get_scheduler_config() _A: Union[str, Any] = scheduler_class(**lowerCAmelCase_ ) _A: Union[str, Any] = [1_0_0, 8_7, 5_0, 1, 0] _A: Dict = len(lowerCAmelCase_ ) with self.assertRaises(lowerCAmelCase_ , msg='''Can only pass one of `num_inference_steps` or `custom_timesteps`.''' ): scheduler.set_timesteps(num_inference_steps=lowerCAmelCase_ , timesteps=lowerCAmelCase_ ) def __magic_name__ ( self : Any ): """simple docstring""" _A: List[Any] = self.scheduler_classes[0] _A: int = self.get_scheduler_config() _A: str = scheduler_class(**lowerCAmelCase_ ) _A: Any = [scheduler.config.num_train_timesteps] with self.assertRaises( lowerCAmelCase_ , msg='''`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}''' , ): scheduler.set_timesteps(timesteps=lowerCAmelCase_ )
301
import json import os from typing import Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ : int = logging.get_logger(__name__) UpperCAmelCase__ : Union[str, Any] = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', } UpperCAmelCase__ : str = { '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__ : Dict = { 'ctrl': 256, } UpperCAmelCase__ : Any = { 'Pregnancy': 168629, 'Christianity': 7675, 'Explain': 106423, 'Fitness': 63440, 'Saving': 63163, 'Ask': 27171, 'Ass': 95985, 'Joke': 163509, 'Questions': 45622, 'Thoughts': 49605, 'Retail': 52342, 'Feminism': 164338, 'Writing': 11992, 'Atheism': 192263, 'Netflix': 48616, 'Computing': 39639, 'Opinion': 43213, 'Alone': 44967, 'Funny': 58917, 'Gaming': 40358, 'Human': 4088, 'India': 1331, 'Joker': 77138, 'Diet': 36206, 'Legal': 11859, 'Norman': 4939, 'Tip': 72689, 'Weight': 52343, 'Movies': 46273, 'Running': 23425, 'Science': 2090, 'Horror': 37793, 'Confession': 60572, 'Finance': 12250, 'Politics': 16360, 'Scary': 191985, 'Support': 12654, 'Technologies': 32516, 'Teenage': 66160, 'Event': 32769, 'Learned': 67460, 'Notion': 182770, 'Wikipedia': 37583, 'Books': 6665, 'Extract': 76050, 'Confessions': 102701, 'Conspiracy': 75932, 'Links': 63674, 'Narcissus': 150425, 'Relationship': 54766, 'Relationships': 134796, 'Reviews': 41671, 'News': 4256, 'Translation': 26820, 'multilingual': 128406, } def lowerCamelCase__ ( a ) -> Optional[Any]: _A: Optional[int] = set() _A: Dict = word[0] for char in word[1:]: pairs.add((prev_char, char) ) _A: Any = char _A: Dict = set(a ) return pairs class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Any = VOCAB_FILES_NAMES __UpperCamelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase : Optional[int] = CONTROL_CODES def __init__( self : Dict , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[Any]="<unk>" , **lowerCAmelCase_ : Optional[int] ): """simple docstring""" super().__init__(unk_token=lowerCAmelCase_ , **lowerCAmelCase_ ) with open(lowerCAmelCase_ , encoding='''utf-8''' ) as vocab_handle: _A: str = json.load(lowerCAmelCase_ ) _A: List[Any] = {v: k for k, v in self.encoder.items()} with open(lowerCAmelCase_ , encoding='''utf-8''' ) as merges_handle: _A: int = merges_handle.read().split('''\n''' )[1:-1] _A: List[Any] = [tuple(merge.split() ) for merge in merges] _A: List[str] = dict(zip(lowerCAmelCase_ , range(len(lowerCAmelCase_ ) ) ) ) _A: Union[str, Any] = {} @property def __magic_name__ ( self : Any ): """simple docstring""" return len(self.encoder ) def __magic_name__ ( self : Dict ): """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def __magic_name__ ( self : List[str] , lowerCAmelCase_ : Tuple ): """simple docstring""" if token in self.cache: return self.cache[token] _A: List[Any] = tuple(lowerCAmelCase_ ) _A: Optional[Any] = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] ) _A: Optional[int] = get_pairs(lowerCAmelCase_ ) if not pairs: return token while True: _A: Optional[int] = min(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : self.bpe_ranks.get(lowerCAmelCase_ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break _A , _A: Any = bigram _A: int = [] _A: int = 0 while i < len(lowerCAmelCase_ ): try: _A: Any = word.index(lowerCAmelCase_ , lowerCAmelCase_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) _A: Optional[int] = j if word[i] == first and i < len(lowerCAmelCase_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 _A: Dict = tuple(lowerCAmelCase_ ) _A: Union[str, Any] = new_word if len(lowerCAmelCase_ ) == 1: break else: _A: Tuple = get_pairs(lowerCAmelCase_ ) _A: Optional[int] = '''@@ '''.join(lowerCAmelCase_ ) _A: List[str] = word[:-4] _A: Optional[Any] = word return word def __magic_name__ ( self : Optional[Any] , lowerCAmelCase_ : Union[str, Any] ): """simple docstring""" _A: List[Any] = [] _A: List[str] = re.findall(R'''\S+\n?''' , lowerCAmelCase_ ) for token in words: split_tokens.extend(list(self.bpe(lowerCAmelCase_ ).split(''' ''' ) ) ) return split_tokens def __magic_name__ ( self : Dict , lowerCAmelCase_ : Optional[int] ): """simple docstring""" return self.encoder.get(lowerCAmelCase_ , self.encoder.get(self.unk_token ) ) def __magic_name__ ( self : Dict , lowerCAmelCase_ : Tuple ): """simple docstring""" return self.decoder.get(lowerCAmelCase_ , self.unk_token ) def __magic_name__ ( self : Any , lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Any = ''' '''.join(lowerCAmelCase_ ).replace('''@@ ''' , '''''' ).strip() return out_string def __magic_name__ ( self : List[str] , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[str] = None ): """simple docstring""" if not os.path.isdir(lowerCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _A: List[str] = os.path.join( lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) _A: List[Any] = os.path.join( lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(lowerCAmelCase_ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=lowerCAmelCase_ , ensure_ascii=lowerCAmelCase_ ) + '''\n''' ) _A: str = 0 with open(lowerCAmelCase_ , '''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 lowerCAmelCase_ : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" ''' Please check that the tokenizer is not corrupted!''' ) _A: Tuple = token_index writer.write(''' '''.join(lowerCAmelCase_ ) + '''\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)
301
1
import argparse import datetime import json import time import warnings from logging import getLogger from pathlib import Path from typing import Dict, List import torch from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils import calculate_bleu, calculate_rouge, chunks, parse_numeric_n_bool_cl_kwargs, use_task_specific_params UpperCAmelCase__ : Any = getLogger(__name__) UpperCAmelCase__ : Optional[Any] = 'cuda' if torch.cuda.is_available() else 'cpu' def lowerCamelCase__ ( a , a , a , a = 8 , a = DEFAULT_DEVICE , a=False , a="summarization" , a=None , **a , ) -> Dict: _A: str = Path(a ).open('''w''' , encoding='''utf-8''' ) _A: Optional[Any] = str(a ) _A: Union[str, Any] = AutoModelForSeqaSeqLM.from_pretrained(a ).to(a ) if fpaa: _A: Any = model.half() _A: Optional[int] = AutoTokenizer.from_pretrained(a ) logger.info(f"""Inferred tokenizer type: {tokenizer.__class__}""" ) # if this is wrong, check config.model_type. _A: Any = time.time() # update config with task specific params use_task_specific_params(a , a ) if prefix is None: _A: int = prefix or getattr(model.config , '''prefix''' , '''''' ) or '''''' for examples_chunk in tqdm(list(chunks(a , a ) ) ): _A: int = [prefix + text for text in examples_chunk] _A: str = tokenizer(a , return_tensors='''pt''' , truncation=a , padding='''longest''' ).to(a ) _A: str = model.generate( input_ids=batch.input_ids , attention_mask=batch.attention_mask , **a , ) _A: str = tokenizer.batch_decode(a , skip_special_tokens=a , clean_up_tokenization_spaces=a ) for hypothesis in dec: fout.write(hypothesis + '''\n''' ) fout.flush() fout.close() _A: Optional[int] = int(time.time() - start_time ) # seconds _A: Union[str, Any] = len(a ) return {"n_obs": n_obs, "runtime": runtime, "seconds_per_sample": round(runtime / n_obs , 4 )} def lowerCamelCase__ ( ) -> Tuple: return datetime.datetime.now().strftime('''%Y-%m-%d %H:%M:%S''' ) def lowerCamelCase__ ( a=True ) -> Optional[Any]: _A: str = argparse.ArgumentParser() parser.add_argument('''model_name''' , type=a , help='''like facebook/bart-large-cnn,t5-base, etc.''' ) parser.add_argument('''input_path''' , type=a , help='''like cnn_dm/test.source''' ) parser.add_argument('''save_path''' , type=a , help='''where to save summaries''' ) parser.add_argument('''--reference_path''' , type=a , required=a , help='''like cnn_dm/test.target''' ) parser.add_argument('''--score_path''' , type=a , required=a , default='''metrics.json''' , help='''where to save metrics''' ) parser.add_argument('''--device''' , type=a , required=a , default=a , help='''cuda, cuda:1, cpu etc.''' ) parser.add_argument( '''--prefix''' , type=a , required=a , default=a , help='''will be added to the begininng of src examples''' ) parser.add_argument('''--task''' , type=a , default='''summarization''' , help='''used for task_specific_params + metrics''' ) parser.add_argument('''--bs''' , type=a , default=8 , required=a , help='''batch size''' ) parser.add_argument( '''--n_obs''' , type=a , default=-1 , required=a , help='''How many observations. Defaults to all.''' ) parser.add_argument('''--fp16''' , action='''store_true''' ) parser.add_argument('''--dump-args''' , action='''store_true''' , help='''print the custom hparams with the results''' ) parser.add_argument( '''--info''' , nargs='''?''' , type=a , const=datetime_now() , help=( '''use in conjunction w/ --dump-args to print with the results whatever other info you\'d like, e.g.''' ''' lang=en-ru. If no value is passed, the current datetime string will be used.''' ) , ) # Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate _A , _A: Tuple = parser.parse_known_args() _A: List[str] = parse_numeric_n_bool_cl_kwargs(a ) if parsed_args and verbose: print(f"""parsed the following generate kwargs: {parsed_args}""" ) _A: int = [''' ''' + x.rstrip() if '''t5''' in args.model_name else x.rstrip() for x in open(args.input_path ).readlines()] if args.n_obs > 0: _A: List[str] = examples[: args.n_obs] Path(args.save_path ).parent.mkdir(exist_ok=a ) if args.reference_path is None and Path(args.score_path ).exists(): warnings.warn(f"""score_path {args.score_path} will be overwritten unless you type ctrl-c.""" ) if args.device == "cpu" and args.fpaa: # this mix leads to RuntimeError: "threshold_cpu" not implemented for 'Half' raise ValueError('''Can\'t mix --fp16 and --device cpu''' ) _A: Dict = generate_summaries_or_translations( a , args.save_path , args.model_name , batch_size=args.bs , device=args.device , fpaa=args.fpaa , task=args.task , prefix=args.prefix , **a , ) if args.reference_path is None: return {} # Compute scores _A: Dict = calculate_bleu if '''translation''' in args.task else calculate_rouge _A: List[Any] = [x.rstrip() for x in open(args.save_path ).readlines()] _A: Any = [x.rstrip() for x in open(args.reference_path ).readlines()][: len(a )] _A: dict = score_fn(a , a ) scores.update(a ) if args.dump_args: scores.update(a ) if args.info: _A: Optional[Any] = args.info if verbose: print(a ) if args.score_path is not None: json.dump(a , open(args.score_path , '''w''' ) ) return scores if __name__ == "__main__": # Usage for MT: # python run_eval.py MODEL_NAME $DATA_DIR/test.source $save_dir/test_translations.txt --reference_path $DATA_DIR/test.target --score_path $save_dir/test_bleu.json --task translation $@ run_generate(verbose=True)
301
def lowerCamelCase__ ( a = 10 ) -> str: if not isinstance(a , a ) or n < 0: raise ValueError('''Invalid input''' ) _A: int = 10**n _A: List[Any] = 2_84_33 * (pow(2 , 7_83_04_57 , a )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(F"""{solution(10) = }""")
301
1
def lowerCamelCase__ ( a = 50 ) -> int: _A: int = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(F"""{solution() = }""")
301
from __future__ import annotations import unittest from transformers import AutoTokenizer, MBartConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel @require_tf class UpperCAmelCase : '''simple docstring''' __UpperCamelCase : Any = MBartConfig __UpperCamelCase : Tuple = {} __UpperCamelCase : Dict = '''gelu''' def __init__( self : Dict , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : List[Any]=1_3 , lowerCAmelCase_ : Dict=7 , lowerCAmelCase_ : Optional[Any]=True , lowerCAmelCase_ : Optional[Any]=False , lowerCAmelCase_ : Union[str, Any]=9_9 , lowerCAmelCase_ : Dict=3_2 , lowerCAmelCase_ : str=2 , lowerCAmelCase_ : int=4 , lowerCAmelCase_ : Union[str, Any]=3_7 , lowerCAmelCase_ : Dict=0.1 , lowerCAmelCase_ : str=0.1 , lowerCAmelCase_ : List[str]=2_0 , lowerCAmelCase_ : str=2 , lowerCAmelCase_ : Optional[int]=1 , lowerCAmelCase_ : List[Any]=0 , ): """simple docstring""" _A: Union[str, Any] = parent _A: List[Any] = batch_size _A: Dict = seq_length _A: Dict = is_training _A: str = use_labels _A: int = vocab_size _A: str = hidden_size _A: Tuple = num_hidden_layers _A: Optional[Any] = num_attention_heads _A: Tuple = intermediate_size _A: int = hidden_dropout_prob _A: Tuple = attention_probs_dropout_prob _A: Tuple = max_position_embeddings _A: Dict = eos_token_id _A: int = pad_token_id _A: Any = bos_token_id def __magic_name__ ( self : Dict ): """simple docstring""" _A: Optional[int] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _A: Dict = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _A: List[Any] = tf.concat([input_ids, eos_tensor] , axis=1 ) _A: Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _A: int = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) _A: Any = prepare_mbart_inputs_dict(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return config, inputs_dict def __magic_name__ ( self : Union[str, Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : List[str] ): """simple docstring""" _A: Tuple = TFMBartModel(config=lowerCAmelCase_ ).get_decoder() _A: List[str] = inputs_dict['''input_ids'''] _A: Tuple = input_ids[:1, :] _A: List[Any] = inputs_dict['''attention_mask'''][:1, :] _A: str = inputs_dict['''head_mask'''] _A: Optional[Any] = 1 # first forward pass _A: Any = model(lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , head_mask=lowerCAmelCase_ , use_cache=lowerCAmelCase_ ) _A , _A: List[str] = outputs.to_tuple() _A: Dict = past_key_values[1] def lowerCamelCase__ ( a , a , a , a=None , a=None , a=None , a=None , a=None , ) -> Tuple: if attention_mask is None: _A: Union[str, Any] = tf.cast(tf.math.not_equal(a , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: _A: Optional[int] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: _A: Tuple = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _A: Union[str, Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: _A: Optional[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Union[str, Any] = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else () __UpperCamelCase : int = (TFMBartForConditionalGeneration,) if is_tf_available() else () __UpperCamelCase : Tuple = ( { '''conversational''': TFMBartForConditionalGeneration, '''feature-extraction''': TFMBartModel, '''summarization''': TFMBartForConditionalGeneration, '''text2text-generation''': TFMBartForConditionalGeneration, '''translation''': TFMBartForConditionalGeneration, } if is_tf_available() else {} ) __UpperCamelCase : List[Any] = True __UpperCamelCase : int = False __UpperCamelCase : Optional[Any] = False def __magic_name__ ( self : int , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : int , lowerCAmelCase_ : str , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : int ): """simple docstring""" if pipeline_test_casse_name != "FeatureExtractionPipelineTests": # Exception encountered when calling layer '...' return True return False def __magic_name__ ( self : Any ): """simple docstring""" _A: Dict = TFMBartModelTester(self ) _A: Tuple = ConfigTester(self , config_class=lowerCAmelCase_ ) def __magic_name__ ( self : List[str] ): """simple docstring""" self.config_tester.run_common_tests() def __magic_name__ ( self : Optional[Any] ): """simple docstring""" _A: str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*lowerCAmelCase_ ) @require_sentencepiece @require_tokenizers @require_tf class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Optional[int] = [ ''' UN Chief Says There Is No Military Solution in Syria''', ] __UpperCamelCase : List[str] = [ '''Şeful ONU declară că nu există o soluţie militară în Siria''', ] __UpperCamelCase : Union[str, Any] = '''facebook/mbart-large-en-ro''' @cached_property def __magic_name__ ( self : Tuple ): """simple docstring""" return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def __magic_name__ ( self : str ): """simple docstring""" _A: Union[str, Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def __magic_name__ ( self : Union[str, Any] , **lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Optional[Any] = self.translate_src_text(**lowerCAmelCase_ ) self.assertListEqual(self.expected_text , lowerCAmelCase_ ) def __magic_name__ ( self : Dict , **lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Any = self.tokenizer(self.src_text , **lowerCAmelCase_ , return_tensors='''tf''' ) _A: Any = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 ) _A: Optional[Any] = self.tokenizer.batch_decode(lowerCAmelCase_ , skip_special_tokens=lowerCAmelCase_ ) return generated_words @slow def __magic_name__ ( self : List[str] ): """simple docstring""" self._assert_generated_batch_equal_expected()
301
1
import json import os from typing import Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ : int = logging.get_logger(__name__) UpperCAmelCase__ : Union[str, Any] = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', } UpperCAmelCase__ : str = { '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__ : Dict = { 'ctrl': 256, } UpperCAmelCase__ : Any = { 'Pregnancy': 168629, 'Christianity': 7675, 'Explain': 106423, 'Fitness': 63440, 'Saving': 63163, 'Ask': 27171, 'Ass': 95985, 'Joke': 163509, 'Questions': 45622, 'Thoughts': 49605, 'Retail': 52342, 'Feminism': 164338, 'Writing': 11992, 'Atheism': 192263, 'Netflix': 48616, 'Computing': 39639, 'Opinion': 43213, 'Alone': 44967, 'Funny': 58917, 'Gaming': 40358, 'Human': 4088, 'India': 1331, 'Joker': 77138, 'Diet': 36206, 'Legal': 11859, 'Norman': 4939, 'Tip': 72689, 'Weight': 52343, 'Movies': 46273, 'Running': 23425, 'Science': 2090, 'Horror': 37793, 'Confession': 60572, 'Finance': 12250, 'Politics': 16360, 'Scary': 191985, 'Support': 12654, 'Technologies': 32516, 'Teenage': 66160, 'Event': 32769, 'Learned': 67460, 'Notion': 182770, 'Wikipedia': 37583, 'Books': 6665, 'Extract': 76050, 'Confessions': 102701, 'Conspiracy': 75932, 'Links': 63674, 'Narcissus': 150425, 'Relationship': 54766, 'Relationships': 134796, 'Reviews': 41671, 'News': 4256, 'Translation': 26820, 'multilingual': 128406, } def lowerCamelCase__ ( a ) -> Optional[Any]: _A: Optional[int] = set() _A: Dict = word[0] for char in word[1:]: pairs.add((prev_char, char) ) _A: Any = char _A: Dict = set(a ) return pairs class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Any = VOCAB_FILES_NAMES __UpperCamelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase : Optional[int] = CONTROL_CODES def __init__( self : Dict , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[Any]="<unk>" , **lowerCAmelCase_ : Optional[int] ): """simple docstring""" super().__init__(unk_token=lowerCAmelCase_ , **lowerCAmelCase_ ) with open(lowerCAmelCase_ , encoding='''utf-8''' ) as vocab_handle: _A: str = json.load(lowerCAmelCase_ ) _A: List[Any] = {v: k for k, v in self.encoder.items()} with open(lowerCAmelCase_ , encoding='''utf-8''' ) as merges_handle: _A: int = merges_handle.read().split('''\n''' )[1:-1] _A: List[Any] = [tuple(merge.split() ) for merge in merges] _A: List[str] = dict(zip(lowerCAmelCase_ , range(len(lowerCAmelCase_ ) ) ) ) _A: Union[str, Any] = {} @property def __magic_name__ ( self : Any ): """simple docstring""" return len(self.encoder ) def __magic_name__ ( self : Dict ): """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def __magic_name__ ( self : List[str] , lowerCAmelCase_ : Tuple ): """simple docstring""" if token in self.cache: return self.cache[token] _A: List[Any] = tuple(lowerCAmelCase_ ) _A: Optional[Any] = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] ) _A: Optional[int] = get_pairs(lowerCAmelCase_ ) if not pairs: return token while True: _A: Optional[int] = min(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : self.bpe_ranks.get(lowerCAmelCase_ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break _A , _A: Any = bigram _A: int = [] _A: int = 0 while i < len(lowerCAmelCase_ ): try: _A: Any = word.index(lowerCAmelCase_ , lowerCAmelCase_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) _A: Optional[int] = j if word[i] == first and i < len(lowerCAmelCase_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 _A: Dict = tuple(lowerCAmelCase_ ) _A: Union[str, Any] = new_word if len(lowerCAmelCase_ ) == 1: break else: _A: Tuple = get_pairs(lowerCAmelCase_ ) _A: Optional[int] = '''@@ '''.join(lowerCAmelCase_ ) _A: List[str] = word[:-4] _A: Optional[Any] = word return word def __magic_name__ ( self : Optional[Any] , lowerCAmelCase_ : Union[str, Any] ): """simple docstring""" _A: List[Any] = [] _A: List[str] = re.findall(R'''\S+\n?''' , lowerCAmelCase_ ) for token in words: split_tokens.extend(list(self.bpe(lowerCAmelCase_ ).split(''' ''' ) ) ) return split_tokens def __magic_name__ ( self : Dict , lowerCAmelCase_ : Optional[int] ): """simple docstring""" return self.encoder.get(lowerCAmelCase_ , self.encoder.get(self.unk_token ) ) def __magic_name__ ( self : Dict , lowerCAmelCase_ : Tuple ): """simple docstring""" return self.decoder.get(lowerCAmelCase_ , self.unk_token ) def __magic_name__ ( self : Any , lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Any = ''' '''.join(lowerCAmelCase_ ).replace('''@@ ''' , '''''' ).strip() return out_string def __magic_name__ ( self : List[str] , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[str] = None ): """simple docstring""" if not os.path.isdir(lowerCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _A: List[str] = os.path.join( lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) _A: List[Any] = os.path.join( lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(lowerCAmelCase_ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=lowerCAmelCase_ , ensure_ascii=lowerCAmelCase_ ) + '''\n''' ) _A: str = 0 with open(lowerCAmelCase_ , '''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 lowerCAmelCase_ : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" ''' Please check that the tokenizer is not corrupted!''' ) _A: Tuple = token_index writer.write(''' '''.join(lowerCAmelCase_ ) + '''\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)
301
from typing import TYPE_CHECKING from ..utils import _LazyModule UpperCAmelCase__ : Tuple = { 'config': [ 'EXTERNAL_DATA_FORMAT_SIZE_LIMIT', 'OnnxConfig', 'OnnxConfigWithPast', 'OnnxSeq2SeqConfigWithPast', 'PatchingSpec', ], 'convert': ['export', 'validate_model_outputs'], 'features': ['FeaturesManager'], 'utils': ['ParameterFormat', 'compute_serialized_parameters_size'], } if TYPE_CHECKING: from .config import ( EXTERNAL_DATA_FORMAT_SIZE_LIMIT, OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast, PatchingSpec, ) from .convert import export, validate_model_outputs from .features import FeaturesManager from .utils import ParameterFormat, compute_serialized_parameters_size else: import sys UpperCAmelCase__ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
301
1
from __future__ import annotations def lowerCamelCase__ ( a , a ) -> list[list[int]]: _A: list[list[int]] = [] create_all_state(1 , a , a , [] , a ) return result def lowerCamelCase__ ( a , a , a , a , a , ) -> None: if level == 0: total_list.append(current_list[:] ) return for i in range(a , total_number - level + 2 ): current_list.append(a ) create_all_state(i + 1 , a , level - 1 , a , a ) current_list.pop() def lowerCamelCase__ ( a ) -> None: for i in total_list: print(*a ) if __name__ == "__main__": UpperCAmelCase__ : Tuple = 4 UpperCAmelCase__ : Any = 2 UpperCAmelCase__ : Optional[int] = generate_all_combinations(n, k) print_all_state(total_list)
301
import torch from diffusers import DDPMParallelScheduler from .test_schedulers import SchedulerCommonTest class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Any = (DDPMParallelScheduler,) def __magic_name__ ( self : Optional[int] , **lowerCAmelCase_ : Any ): """simple docstring""" _A: Optional[int] = { '''num_train_timesteps''': 1_0_0_0, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''variance_type''': '''fixed_small''', '''clip_sample''': True, } config.update(**lowerCAmelCase_ ) return config def __magic_name__ ( self : int ): """simple docstring""" for timesteps in [1, 5, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=lowerCAmelCase_ ) def __magic_name__ ( self : Tuple ): """simple docstring""" for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=lowerCAmelCase_ , beta_end=lowerCAmelCase_ ) def __magic_name__ ( self : Optional[Any] ): """simple docstring""" for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=lowerCAmelCase_ ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=lowerCAmelCase_ ) def __magic_name__ ( self : Tuple ): """simple docstring""" for clip_sample in [True, False]: self.check_over_configs(clip_sample=lowerCAmelCase_ ) def __magic_name__ ( self : List[str] ): """simple docstring""" self.check_over_configs(thresholding=lowerCAmelCase_ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=lowerCAmelCase_ , prediction_type=lowerCAmelCase_ , sample_max_value=lowerCAmelCase_ , ) def __magic_name__ ( self : Dict ): """simple docstring""" for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=lowerCAmelCase_ ) def __magic_name__ ( self : int ): """simple docstring""" for t in [0, 5_0_0, 9_9_9]: self.check_over_forward(time_step=lowerCAmelCase_ ) def __magic_name__ ( self : Any ): """simple docstring""" _A: List[Any] = self.scheduler_classes[0] _A: Union[str, Any] = self.get_scheduler_config() _A: Optional[Any] = scheduler_class(**lowerCAmelCase_ ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_8_7 ) - 0.00979 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_9_9 ) - 0.02 ) ) < 1e-5 def __magic_name__ ( self : Optional[int] ): """simple docstring""" _A: Any = self.scheduler_classes[0] _A: List[str] = self.get_scheduler_config() _A: Union[str, Any] = scheduler_class(**lowerCAmelCase_ ) _A: List[Any] = len(lowerCAmelCase_ ) _A: Union[str, Any] = self.dummy_model() _A: Dict = self.dummy_sample_deter _A: Dict = self.dummy_sample_deter + 0.1 _A: str = self.dummy_sample_deter - 0.1 _A: str = samplea.shape[0] _A: Optional[Any] = torch.stack([samplea, samplea, samplea] , dim=0 ) _A: List[str] = torch.arange(lowerCAmelCase_ )[0:3, None].repeat(1 , lowerCAmelCase_ ) _A: List[Any] = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) _A: Optional[int] = scheduler.batch_step_no_noise(lowerCAmelCase_ , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) ) _A: Dict = torch.sum(torch.abs(lowerCAmelCase_ ) ) _A: List[str] = torch.mean(torch.abs(lowerCAmelCase_ ) ) assert abs(result_sum.item() - 1153.1833 ) < 1e-2 assert abs(result_mean.item() - 0.5005 ) < 1e-3 def __magic_name__ ( self : Tuple ): """simple docstring""" _A: Optional[Any] = self.scheduler_classes[0] _A: List[Any] = self.get_scheduler_config() _A: Any = scheduler_class(**lowerCAmelCase_ ) _A: Union[str, Any] = len(lowerCAmelCase_ ) _A: Any = self.dummy_model() _A: Optional[int] = self.dummy_sample_deter _A: List[str] = torch.manual_seed(0 ) for t in reversed(range(lowerCAmelCase_ ) ): # 1. predict noise residual _A: Optional[int] = model(lowerCAmelCase_ , lowerCAmelCase_ ) # 2. predict previous mean of sample x_t-1 _A: Optional[int] = scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , generator=lowerCAmelCase_ ).prev_sample _A: List[Any] = pred_prev_sample _A: Optional[int] = torch.sum(torch.abs(lowerCAmelCase_ ) ) _A: Any = torch.mean(torch.abs(lowerCAmelCase_ ) ) assert abs(result_sum.item() - 258.9606 ) < 1e-2 assert abs(result_mean.item() - 0.3372 ) < 1e-3 def __magic_name__ ( self : Tuple ): """simple docstring""" _A: Optional[int] = self.scheduler_classes[0] _A: Union[str, Any] = self.get_scheduler_config(prediction_type='''v_prediction''' ) _A: List[str] = scheduler_class(**lowerCAmelCase_ ) _A: Union[str, Any] = len(lowerCAmelCase_ ) _A: Any = self.dummy_model() _A: Any = self.dummy_sample_deter _A: str = torch.manual_seed(0 ) for t in reversed(range(lowerCAmelCase_ ) ): # 1. predict noise residual _A: Any = model(lowerCAmelCase_ , lowerCAmelCase_ ) # 2. predict previous mean of sample x_t-1 _A: int = scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , generator=lowerCAmelCase_ ).prev_sample _A: Tuple = pred_prev_sample _A: List[Any] = torch.sum(torch.abs(lowerCAmelCase_ ) ) _A: str = torch.mean(torch.abs(lowerCAmelCase_ ) ) assert abs(result_sum.item() - 202.0296 ) < 1e-2 assert abs(result_mean.item() - 0.2631 ) < 1e-3 def __magic_name__ ( self : Optional[int] ): """simple docstring""" _A: Optional[int] = self.scheduler_classes[0] _A: Optional[Any] = self.get_scheduler_config() _A: Dict = scheduler_class(**lowerCAmelCase_ ) _A: Any = [1_0_0, 8_7, 5_0, 1, 0] scheduler.set_timesteps(timesteps=lowerCAmelCase_ ) _A: Tuple = scheduler.timesteps for i, timestep in enumerate(lowerCAmelCase_ ): if i == len(lowerCAmelCase_ ) - 1: _A: Dict = -1 else: _A: int = timesteps[i + 1] _A: List[str] = scheduler.previous_timestep(lowerCAmelCase_ ) _A: str = prev_t.item() self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) def __magic_name__ ( self : Any ): """simple docstring""" _A: Tuple = self.scheduler_classes[0] _A: int = self.get_scheduler_config() _A: Any = scheduler_class(**lowerCAmelCase_ ) _A: Union[str, Any] = [1_0_0, 8_7, 5_0, 5_1, 0] with self.assertRaises(lowerCAmelCase_ , msg='''`custom_timesteps` must be in descending order.''' ): scheduler.set_timesteps(timesteps=lowerCAmelCase_ ) def __magic_name__ ( self : int ): """simple docstring""" _A: List[str] = self.scheduler_classes[0] _A: Optional[Any] = self.get_scheduler_config() _A: Union[str, Any] = scheduler_class(**lowerCAmelCase_ ) _A: Union[str, Any] = [1_0_0, 8_7, 5_0, 1, 0] _A: Dict = len(lowerCAmelCase_ ) with self.assertRaises(lowerCAmelCase_ , msg='''Can only pass one of `num_inference_steps` or `custom_timesteps`.''' ): scheduler.set_timesteps(num_inference_steps=lowerCAmelCase_ , timesteps=lowerCAmelCase_ ) def __magic_name__ ( self : Any ): """simple docstring""" _A: List[Any] = self.scheduler_classes[0] _A: int = self.get_scheduler_config() _A: str = scheduler_class(**lowerCAmelCase_ ) _A: Any = [scheduler.config.num_train_timesteps] with self.assertRaises( lowerCAmelCase_ , msg='''`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}''' , ): scheduler.set_timesteps(timesteps=lowerCAmelCase_ )
301
1
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer import diffusers from diffusers import ( AutoencoderKL, EulerDiscreteScheduler, StableDiffusionLatentUpscalePipeline, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.schedulers import KarrasDiffusionSchedulers from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() def lowerCamelCase__ ( a ) -> Any: _A: str = [tensor.shape for tensor in tensor_list] return all(shape == shapes[0] for shape in shapes[1:] ) class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Optional[Any] = StableDiffusionLatentUpscalePipeline __UpperCamelCase : Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - { '''height''', '''width''', '''cross_attention_kwargs''', '''negative_prompt_embeds''', '''prompt_embeds''', } __UpperCamelCase : List[str] = PipelineTesterMixin.required_optional_params - {'''num_images_per_prompt'''} __UpperCamelCase : Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __UpperCamelCase : Optional[int] = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess __UpperCamelCase : Dict = frozenset([] ) __UpperCamelCase : Tuple = True @property def __magic_name__ ( self : List[Any] ): """simple docstring""" _A: Tuple = 1 _A: List[Any] = 4 _A: Any = (1_6, 1_6) _A: Optional[int] = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(lowerCAmelCase_ ) return image def __magic_name__ ( self : int ): """simple docstring""" torch.manual_seed(0 ) _A: Dict = UNetaDConditionModel( act_fn='''gelu''' , attention_head_dim=8 , norm_num_groups=lowerCAmelCase_ , block_out_channels=[3_2, 3_2, 6_4, 6_4] , time_cond_proj_dim=1_6_0 , conv_in_kernel=1 , conv_out_kernel=1 , cross_attention_dim=3_2 , down_block_types=( '''KDownBlock2D''', '''KCrossAttnDownBlock2D''', '''KCrossAttnDownBlock2D''', '''KCrossAttnDownBlock2D''', ) , in_channels=8 , mid_block_type=lowerCAmelCase_ , only_cross_attention=lowerCAmelCase_ , out_channels=5 , resnet_time_scale_shift='''scale_shift''' , time_embedding_type='''fourier''' , timestep_post_act='''gelu''' , up_block_types=('''KCrossAttnUpBlock2D''', '''KCrossAttnUpBlock2D''', '''KCrossAttnUpBlock2D''', '''KUpBlock2D''') , ) _A: Optional[int] = AutoencoderKL( block_out_channels=[3_2, 3_2, 6_4, 6_4] , in_channels=3 , out_channels=3 , down_block_types=[ '''DownEncoderBlock2D''', '''DownEncoderBlock2D''', '''DownEncoderBlock2D''', '''DownEncoderBlock2D''', ] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''', '''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) _A: Any = EulerDiscreteScheduler(prediction_type='''sample''' ) _A: List[Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act='''quick_gelu''' , projection_dim=5_1_2 , ) _A: List[Any] = CLIPTextModel(lowerCAmelCase_ ) _A: Dict = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) _A: Tuple = { '''unet''': model.eval(), '''vae''': vae.eval(), '''scheduler''': scheduler, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, } return components def __magic_name__ ( self : Tuple , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Tuple=0 ): """simple docstring""" if str(lowerCAmelCase_ ).startswith('''mps''' ): _A: Dict = torch.manual_seed(lowerCAmelCase_ ) else: _A: Dict = torch.Generator(device=lowerCAmelCase_ ).manual_seed(lowerCAmelCase_ ) _A: List[Any] = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': self.dummy_image.cpu(), '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def __magic_name__ ( self : str ): """simple docstring""" _A: Any = '''cpu''' _A: List[Any] = self.get_dummy_components() _A: List[str] = self.pipeline_class(**lowerCAmelCase_ ) pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _A: Optional[int] = self.get_dummy_inputs(lowerCAmelCase_ ) _A: int = pipe(**lowerCAmelCase_ ).images _A: Optional[int] = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 2_5_6, 2_5_6, 3) ) _A: List[str] = np.array( [0.47222412, 0.41921633, 0.44717434, 0.46874192, 0.42588258, 0.46150726, 0.4677534, 0.45583832, 0.48579055] ) _A: int = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(lowerCAmelCase_ , 1e-3 ) def __magic_name__ ( self : List[str] ): """simple docstring""" super().test_attention_slicing_forward_pass(expected_max_diff=7e-3 ) def __magic_name__ ( self : List[str] ): """simple docstring""" super().test_cpu_offload_forward_pass(expected_max_diff=3e-3 ) def __magic_name__ ( self : Optional[Any] ): """simple docstring""" super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def __magic_name__ ( self : List[Any] ): """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=7e-3 ) def __magic_name__ ( self : List[str] ): """simple docstring""" super().test_pt_np_pil_outputs_equivalent(expected_max_diff=3e-3 ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" super().test_save_load_local(expected_max_difference=3e-3 ) def __magic_name__ ( self : int ): """simple docstring""" super().test_save_load_optional_components(expected_max_difference=3e-3 ) def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" _A: List[Any] = [ '''DDIMScheduler''', '''DDPMScheduler''', '''PNDMScheduler''', '''HeunDiscreteScheduler''', '''EulerAncestralDiscreteScheduler''', '''KDPM2DiscreteScheduler''', '''KDPM2AncestralDiscreteScheduler''', '''DPMSolverSDEScheduler''', ] _A: Tuple = self.get_dummy_components() _A: Any = self.pipeline_class(**lowerCAmelCase_ ) # make sure that PNDM does not need warm-up pipe.scheduler.register_to_config(skip_prk_steps=lowerCAmelCase_ ) pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _A: Union[str, Any] = self.get_dummy_inputs(lowerCAmelCase_ ) _A: Optional[Any] = 2 _A: Union[str, Any] = [] for scheduler_enum in KarrasDiffusionSchedulers: if scheduler_enum.name in skip_schedulers: # no sigma schedulers are not supported # no schedulers continue _A: Union[str, Any] = getattr(lowerCAmelCase_ , scheduler_enum.name ) _A: int = scheduler_cls.from_config(pipe.scheduler.config ) _A: int = pipe(**lowerCAmelCase_ )[0] outputs.append(lowerCAmelCase_ ) assert check_same_shape(lowerCAmelCase_ ) @require_torch_gpu @slow class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __magic_name__ ( self : str ): """simple docstring""" _A: List[str] = torch.manual_seed(3_3 ) _A: List[str] = StableDiffusionPipeline.from_pretrained('''CompVis/stable-diffusion-v1-4''' , torch_dtype=torch.floataa ) pipe.to('''cuda''' ) _A: List[Any] = StableDiffusionLatentUpscalePipeline.from_pretrained( '''stabilityai/sd-x2-latent-upscaler''' , torch_dtype=torch.floataa ) upscaler.to('''cuda''' ) _A: Union[str, Any] = '''a photo of an astronaut high resolution, unreal engine, ultra realistic''' _A: Union[str, Any] = pipe(lowerCAmelCase_ , generator=lowerCAmelCase_ , output_type='''latent''' ).images _A: Optional[int] = upscaler( prompt=lowerCAmelCase_ , image=lowerCAmelCase_ , num_inference_steps=2_0 , guidance_scale=0 , generator=lowerCAmelCase_ , output_type='''np''' , ).images[0] _A: Dict = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/astronaut_1024.npy''' ) assert np.abs((expected_image - image).mean() ) < 5e-2 def __magic_name__ ( self : str ): """simple docstring""" _A: List[str] = torch.manual_seed(3_3 ) _A: List[str] = StableDiffusionLatentUpscalePipeline.from_pretrained( '''stabilityai/sd-x2-latent-upscaler''' , torch_dtype=torch.floataa ) upscaler.to('''cuda''' ) _A: Dict = '''the temple of fire by Ross Tran and Gerardo Dottori, oil on canvas''' _A: int = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_512.png''' ) _A: Any = upscaler( prompt=lowerCAmelCase_ , image=lowerCAmelCase_ , num_inference_steps=2_0 , guidance_scale=0 , generator=lowerCAmelCase_ , output_type='''np''' , ).images[0] _A: List[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_1024.npy''' ) assert np.abs((expected_image - image).max() ) < 5e-2
301
import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Any = GPTSanJapaneseTokenizer __UpperCamelCase : Optional[int] = False __UpperCamelCase : str = {'''do_clean_text''': False, '''add_prefix_space''': False} def __magic_name__ ( self : Any ): """simple docstring""" super().setUp() # fmt: off _A: Union[str, Any] = ['''こん''', '''こんに''', '''にちは''', '''ばんは''', '''世界,㔺界''', '''、''', '''。''', '''<BR>''', '''<SP>''', '''<TAB>''', '''<URL>''', '''<EMAIL>''', '''<TEL>''', '''<DATE>''', '''<PRICE>''', '''<BLOCK>''', '''<KIGOU>''', '''<U2000U2BFF>''', '''<|emoji1|>''', '''<unk>''', '''<|bagoftoken|>''', '''<|endoftext|>'''] # fmt: on _A: Union[str, Any] = {'''emoji''': {'''\ud83d\ude00''': '''<|emoji1|>'''}, '''emoji_inv''': {'''<|emoji1|>''': '''\ud83d\ude00'''}} # 😀 _A: str = {'''unk_token''': '''<unk>'''} _A: Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) _A: Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''emoji_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) with open(self.emoji_file , '''w''' ) as emoji_writer: emoji_writer.write(json.dumps(lowerCAmelCase_ ) ) def __magic_name__ ( self : Optional[int] , **lowerCAmelCase_ : List[Any] ): """simple docstring""" kwargs.update(self.special_tokens_map ) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **lowerCAmelCase_ ) def __magic_name__ ( self : Optional[int] , lowerCAmelCase_ : List[str] ): """simple docstring""" _A: Optional[Any] = '''こんにちは、世界。 \nこんばんは、㔺界。😀''' _A: str = '''こんにちは、世界。 \nこんばんは、世界。😀''' return input_text, output_text def __magic_name__ ( self : List[str] , lowerCAmelCase_ : Optional[int] ): """simple docstring""" _A , _A: Optional[int] = self.get_input_output_texts(lowerCAmelCase_ ) _A: Union[str, Any] = tokenizer.encode(lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ ) _A: Tuple = tokenizer.decode(lowerCAmelCase_ , clean_up_tokenization_spaces=lowerCAmelCase_ ) return text, ids def __magic_name__ ( self : Tuple ): """simple docstring""" pass # TODO add if relevant def __magic_name__ ( self : List[str] ): """simple docstring""" pass # TODO add if relevant def __magic_name__ ( self : Dict ): """simple docstring""" pass # TODO add if relevant def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" _A: List[str] = self.get_tokenizer() # Testing tokenization _A: List[Any] = '''こんにちは、世界。 こんばんは、㔺界。''' _A: Dict = ['''こん''', '''にちは''', '''、''', '''世界''', '''。''', '''<SP>''', '''こん''', '''ばんは''', '''、''', '''㔺界''', '''。'''] _A: List[Any] = tokenizer.tokenize(lowerCAmelCase_ ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) # Testing conversion to ids without special tokens _A: Optional[int] = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] _A: Optional[int] = tokenizer.convert_tokens_to_ids(lowerCAmelCase_ ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) # Testing conversion to ids with special tokens _A: Dict = tokens + [tokenizer.unk_token] _A: str = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 1_9] _A: Optional[int] = tokenizer.convert_tokens_to_ids(lowerCAmelCase_ ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" _A: Dict = self.get_tokenizer() # Testing tokenization _A: Optional[int] = '''こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。''' _A: str = '''こんにちは、、、、世界。こんばんは、、、、世界。''' _A: Tuple = tokenizer.encode(lowerCAmelCase_ ) _A: List[str] = tokenizer.decode(lowerCAmelCase_ ) self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) @slow def __magic_name__ ( self : Any ): """simple docstring""" _A: List[Any] = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' ) # Testing tokenization _A: Union[str, Any] = '''こんにちは、世界。''' _A: Optional[int] = '''こんばんは、㔺界。😀''' _A: str = '''こんにちは、世界。こんばんは、世界。😀''' _A: List[Any] = tokenizer.encode(prefix_text + input_text ) _A: Optional[Any] = tokenizer.encode('''''' , prefix_text=prefix_text + input_text ) _A: List[Any] = tokenizer.encode(lowerCAmelCase_ , prefix_text=lowerCAmelCase_ ) _A: Union[str, Any] = tokenizer.decode(lowerCAmelCase_ ) _A: Any = tokenizer.decode(lowerCAmelCase_ ) _A: Dict = tokenizer.decode(lowerCAmelCase_ ) self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) @slow def __magic_name__ ( self : Optional[Any] ): """simple docstring""" _A: str = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' ) # Testing tokenization _A: Optional[int] = '''こんにちは、世界。''' _A: Optional[int] = '''こんばんは、㔺界。😀''' _A: Any = len(tokenizer.encode(lowerCAmelCase_ ) ) - 2 _A: int = len(tokenizer.encode(lowerCAmelCase_ ) ) - 2 _A: Optional[Any] = [1] + [0] * (len_prefix + len_text + 1) _A: Any = [1] * (len_prefix + len_text + 1) + [0] _A: Optional[int] = [1] + [1] * (len_prefix) + [0] * (len_text + 1) _A: Optional[Any] = tokenizer(prefix_text + input_text ).token_type_ids _A: List[str] = tokenizer('''''' , prefix_text=prefix_text + input_text ).token_type_ids _A: Dict = tokenizer(lowerCAmelCase_ , prefix_text=lowerCAmelCase_ ).token_type_ids self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) @slow def __magic_name__ ( self : Any ): """simple docstring""" _A: str = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' ) _A: List[Any] = tokenizer.encode('''あンいワ''' ) _A: Any = tokenizer.encode('''''' , prefix_text='''あンいワ''' ) _A: Union[str, Any] = tokenizer.encode('''いワ''' , prefix_text='''あン''' ) self.assertEqual(tokenizer.decode(lowerCAmelCase_ ) , tokenizer.decode(lowerCAmelCase_ ) ) self.assertEqual(tokenizer.decode(lowerCAmelCase_ ) , tokenizer.decode(lowerCAmelCase_ ) ) self.assertNotEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertNotEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token @slow def __magic_name__ ( self : List[Any] ): """simple docstring""" _A: Tuple = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' ) _A: Optional[Any] = [['''武田信玄''', '''は、'''], ['''織田信長''', '''の配下の、''']] _A: Optional[int] = tokenizer(lowerCAmelCase_ , padding=lowerCAmelCase_ ) _A: Optional[Any] = tokenizer.batch_encode_plus(lowerCAmelCase_ , padding=lowerCAmelCase_ ) # fmt: off _A: Tuple = [[3_5_9_9_3, 8_6_4_0, 2_5_9_4_8, 3_5_9_9_8, 3_0_6_4_7, 3_5_6_7_5, 3_5_9_9_9, 3_5_9_9_9], [3_5_9_9_3, 1_0_3_8_2, 9_8_6_8, 3_5_9_9_8, 3_0_6_4_6, 9_4_5_9, 3_0_6_4_6, 3_5_6_7_5]] _A: Optional[int] = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] _A: Dict = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids , lowerCAmelCase_ ) self.assertListEqual(x_token.token_type_ids , lowerCAmelCase_ ) self.assertListEqual(x_token.attention_mask , lowerCAmelCase_ ) self.assertListEqual(x_token_a.input_ids , lowerCAmelCase_ ) self.assertListEqual(x_token_a.token_type_ids , lowerCAmelCase_ ) self.assertListEqual(x_token_a.attention_mask , lowerCAmelCase_ ) def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" # Intentionally convert some words to accommodate character fluctuations unique to Japanese pass def __magic_name__ ( self : Tuple ): """simple docstring""" # tokenizer has no padding token pass
301
1
import math from collections.abc import Callable def lowerCamelCase__ ( a , a , a ) -> float: _A: float = xa _A: float = xa while True: if x_n == x_na or function(a ) == function(a ): raise ZeroDivisionError('''float division by zero, could not find root''' ) _A: float = x_na - ( function(a ) / ((function(a ) - function(a )) / (x_na - x_n)) ) if abs(x_na - x_na ) < 10**-5: return x_na _A: List[Any] = x_na _A: str = x_na def lowerCamelCase__ ( a ) -> float: return math.pow(a , 3 ) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
301
def lowerCamelCase__ ( a = 10**9 ) -> int: _A: Dict = 1 _A: Union[str, Any] = 2 _A: List[str] = 0 _A: List[Any] = 0 _A: int = 0 while perimeter <= max_perimeter: perimeters_sum += perimeter prev_value += 2 * value value += prev_value _A: List[Any] = 2 * value + 2 if i % 2 == 0 else 2 * value - 2 i += 1 return perimeters_sum if __name__ == "__main__": print(F"""{solution() = }""")
301
1
import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def lowerCamelCase__ ( a , a=10 ) -> int: _A: List[str] = [] for _ in range(a ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def lowerCamelCase__ ( a , a=10 ) -> Dict: _A: int = [] for step in range(a ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: _A: List[str] = os.path.join(a , '''schedule.bin''' ) torch.save(scheduler.state_dict() , a ) _A: Tuple = torch.load(a ) scheduler.load_state_dict(a ) return lrs @require_torch class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __magic_name__ ( self : str , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : List[str] ): """simple docstring""" self.assertEqual(len(lowerCAmelCase_ ) , len(lowerCAmelCase_ ) ) for a, b in zip(lowerCAmelCase_ , lowerCAmelCase_ ): self.assertAlmostEqual(lowerCAmelCase_ , lowerCAmelCase_ , delta=lowerCAmelCase_ ) def __magic_name__ ( self : Any ): """simple docstring""" _A: int = torch.tensor([0.1, -0.2, -0.1] , requires_grad=lowerCAmelCase_ ) _A: Optional[Any] = torch.tensor([0.4, 0.2, -0.5] ) _A: Tuple = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _A: Any = AdamW(params=[w] , lr=2e-1 , weight_decay=0.0 ) for _ in range(1_0_0 ): _A: Tuple = criterion(lowerCAmelCase_ , lowerCAmelCase_ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" _A: List[Any] = torch.tensor([0.1, -0.2, -0.1] , requires_grad=lowerCAmelCase_ ) _A: Any = torch.tensor([0.4, 0.2, -0.5] ) _A: Union[str, Any] = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _A: Any = Adafactor( params=[w] , lr=1e-2 , eps=(1e-30, 1e-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=lowerCAmelCase_ , weight_decay=0.0 , relative_step=lowerCAmelCase_ , scale_parameter=lowerCAmelCase_ , warmup_init=lowerCAmelCase_ , ) for _ in range(1_0_0_0 ): _A: Optional[int] = criterion(lowerCAmelCase_ , lowerCAmelCase_ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) @require_torch class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Any = nn.Linear(50 , 50 ) if is_torch_available() else None __UpperCamelCase : Union[str, Any] = AdamW(m.parameters() , lr=10.0 ) if is_torch_available() else None __UpperCamelCase : List[Any] = 10 def __magic_name__ ( self : Optional[Any] , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : int , lowerCAmelCase_ : Tuple=None ): """simple docstring""" self.assertEqual(len(lowerCAmelCase_ ) , len(lowerCAmelCase_ ) ) for a, b in zip(lowerCAmelCase_ , lowerCAmelCase_ ): self.assertAlmostEqual(lowerCAmelCase_ , lowerCAmelCase_ , delta=lowerCAmelCase_ , msg=lowerCAmelCase_ ) def __magic_name__ ( self : Optional[Any] ): """simple docstring""" _A: Tuple = {'''num_warmup_steps''': 2, '''num_training_steps''': 1_0} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) _A: Union[str, Any] = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {'''num_warmup_steps''': 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, '''num_cycles''': 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, '''power''': 2.0, '''lr_end''': 1e-7}, [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156], ), get_inverse_sqrt_schedule: ( {'''num_warmup_steps''': 2}, [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714], ), } for scheduler_func, data in scheds.items(): _A , _A: Optional[Any] = data _A: Tuple = scheduler_func(self.optimizer , **lowerCAmelCase_ ) self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 ) _A: List[str] = unwrap_schedule(lowerCAmelCase_ , self.num_steps ) self.assertListAlmostEqual( lowerCAmelCase_ , lowerCAmelCase_ , tol=1e-2 , msg=F"""failed for {scheduler_func} in normal scheduler""" , ) _A: int = scheduler_func(self.optimizer , **lowerCAmelCase_ ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(lowerCAmelCase_ ) # wrap to test picklability of the schedule _A: Dict = unwrap_and_save_reload_schedule(lowerCAmelCase_ , self.num_steps ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ , msg=F"""failed for {scheduler_func} in save and reload""" ) class UpperCAmelCase : '''simple docstring''' def __init__( self : List[str] , lowerCAmelCase_ : Any ): """simple docstring""" _A: str = fn def __call__( self : Union[str, Any] , *lowerCAmelCase_ : List[str] , **lowerCAmelCase_ : List[str] ): """simple docstring""" return self.fn(*lowerCAmelCase_ , **lowerCAmelCase_ ) @classmethod def __magic_name__ ( self : List[Any] , lowerCAmelCase_ : List[Any] ): """simple docstring""" _A: Any = list(map(self , scheduler.lr_lambdas ) )
301
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase__ : Union[str, Any] = { 'configuration_roc_bert': ['ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoCBertConfig'], 'tokenization_roc_bert': ['RoCBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: pass try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[Any] = [ 'ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'RoCBertForCausalLM', 'RoCBertForMaskedLM', 'RoCBertForMultipleChoice', 'RoCBertForPreTraining', 'RoCBertForQuestionAnswering', 'RoCBertForSequenceClassification', 'RoCBertForTokenClassification', 'RoCBertLayer', 'RoCBertModel', 'RoCBertPreTrainedModel', 'load_tf_weights_in_roc_bert', ] if TYPE_CHECKING: from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig from .tokenization_roc_bert import RoCBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: raise OptionalDependencyNotAvailable() try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) else: import sys UpperCAmelCase__ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
301
1
from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging UpperCAmelCase__ : Dict = logging.get_logger(__name__) UpperCAmelCase__ : str = { 'google/umt5-small': 'https://huggingface.co/google/umt5-small/resolve/main/config.json', # See all umt5 models at https://huggingface.co/models?filter=umt5 } class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Tuple = '''umt5''' __UpperCamelCase : Tuple = ['''past_key_values'''] def __init__( self : str , lowerCAmelCase_ : Any=2_5_0_1_1_2 , lowerCAmelCase_ : int=5_1_2 , lowerCAmelCase_ : List[Any]=6_4 , lowerCAmelCase_ : List[Any]=1_0_2_4 , lowerCAmelCase_ : int=8 , lowerCAmelCase_ : Union[str, Any]=None , lowerCAmelCase_ : Dict=6 , lowerCAmelCase_ : int=3_2 , lowerCAmelCase_ : Any=1_2_8 , lowerCAmelCase_ : Union[str, Any]=0.1 , lowerCAmelCase_ : List[str]=1e-6 , lowerCAmelCase_ : int=1.0 , lowerCAmelCase_ : Dict="gated-gelu" , lowerCAmelCase_ : Union[str, Any]=True , lowerCAmelCase_ : str=True , lowerCAmelCase_ : Optional[Any]="T5Tokenizer" , lowerCAmelCase_ : Optional[int]=True , lowerCAmelCase_ : Optional[Any]=0 , lowerCAmelCase_ : List[Any]=1 , lowerCAmelCase_ : Any=0 , **lowerCAmelCase_ : Dict , ): """simple docstring""" super().__init__( is_encoder_decoder=lowerCAmelCase_ , tokenizer_class=lowerCAmelCase_ , tie_word_embeddings=lowerCAmelCase_ , pad_token_id=lowerCAmelCase_ , eos_token_id=lowerCAmelCase_ , decoder_start_token_id=lowerCAmelCase_ , **lowerCAmelCase_ , ) _A: List[Any] = vocab_size _A: Dict = d_model _A: int = d_kv _A: List[str] = d_ff _A: Any = num_layers _A: List[str] = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry _A: int = num_heads _A: str = relative_attention_num_buckets _A: Optional[Any] = relative_attention_max_distance _A: Tuple = dropout_rate _A: Union[str, Any] = layer_norm_epsilon _A: Optional[int] = initializer_factor _A: List[Any] = feed_forward_proj _A: int = use_cache _A: Tuple = self.feed_forward_proj.split('''-''' ) _A: List[Any] = act_info[-1] _A: int = act_info[0] == '''gated''' if len(lowerCAmelCase_ ) > 1 and act_info[0] != "gated" or len(lowerCAmelCase_ ) > 2: raise ValueError( F"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" '''Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ''' '''\'gated-gelu\' or \'relu\'''' ) if feed_forward_proj == "gated-gelu": _A: Tuple = '''gelu_new''' @property def __magic_name__ ( self : Optional[Any] ): """simple docstring""" return self.d_model @property def __magic_name__ ( self : Dict ): """simple docstring""" return self.num_heads @property def __magic_name__ ( self : str ): """simple docstring""" return self.num_layers class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs def __magic_name__ ( self : List[Any] ): """simple docstring""" _A: str = { '''input_ids''': {0: '''batch''', 1: '''encoder_sequence'''}, '''attention_mask''': {0: '''batch''', 1: '''encoder_sequence'''}, } if self.use_past: _A: List[str] = '''past_encoder_sequence + sequence''' _A: Optional[Any] = {0: '''batch'''} _A: List[Any] = {0: '''batch''', 1: '''past_decoder_sequence + sequence'''} else: _A: Any = {0: '''batch''', 1: '''decoder_sequence'''} _A: List[str] = {0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(lowerCAmelCase_ , direction='''inputs''' ) return common_inputs @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset def __magic_name__ ( self : int ): """simple docstring""" return 1_3 @property def __magic_name__ ( self : Tuple ): """simple docstring""" return 5e-4
301
import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def lowerCamelCase__ ( a , a=0.999 , a="cosine" , ) -> int: if alpha_transform_type == "cosine": def alpha_bar_fn(a ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(a ): return math.exp(t * -12.0 ) else: raise ValueError(f"""Unsupported alpha_tranform_type: {alpha_transform_type}""" ) _A: Dict = [] for i in range(a ): _A: Optional[int] = i / num_diffusion_timesteps _A: Optional[int] = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(a ) / alpha_bar_fn(a ) , a ) ) return torch.tensor(a , dtype=torch.floataa ) class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Optional[int] = [e.name for e in KarrasDiffusionSchedulers] __UpperCamelCase : Tuple = 2 @register_to_config def __init__( self : str , lowerCAmelCase_ : int = 1_0_0_0 , lowerCAmelCase_ : float = 0.00085 , lowerCAmelCase_ : float = 0.012 , lowerCAmelCase_ : str = "linear" , lowerCAmelCase_ : Optional[Union[np.ndarray, List[float]]] = None , lowerCAmelCase_ : str = "epsilon" , lowerCAmelCase_ : Optional[bool] = False , lowerCAmelCase_ : Optional[bool] = False , lowerCAmelCase_ : float = 1.0 , lowerCAmelCase_ : str = "linspace" , lowerCAmelCase_ : int = 0 , ): """simple docstring""" if trained_betas is not None: _A: Optional[Any] = torch.tensor(lowerCAmelCase_ , dtype=torch.floataa ) elif beta_schedule == "linear": _A: List[str] = torch.linspace(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. _A: Optional[Any] = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , lowerCAmelCase_ , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule _A: Tuple = betas_for_alpha_bar(lowerCAmelCase_ , alpha_transform_type='''cosine''' ) elif beta_schedule == "exp": _A: int = betas_for_alpha_bar(lowerCAmelCase_ , alpha_transform_type='''exp''' ) else: raise NotImplementedError(F"""{beta_schedule} does is not implemented for {self.__class__}""" ) _A: Union[str, Any] = 1.0 - self.betas _A: Dict = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) _A: str = use_karras_sigmas def __magic_name__ ( self : List[str] , lowerCAmelCase_ : Any , lowerCAmelCase_ : Optional[int]=None ): """simple docstring""" if schedule_timesteps is None: _A: List[str] = self.timesteps _A: int = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: _A: Optional[int] = 1 if len(lowerCAmelCase_ ) > 1 else 0 else: _A: int = timestep.cpu().item() if torch.is_tensor(lowerCAmelCase_ ) else timestep _A: List[str] = self._index_counter[timestep_int] return indices[pos].item() @property def __magic_name__ ( self : int ): """simple docstring""" # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def __magic_name__ ( self : List[str] , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : Union[float, torch.FloatTensor] , ): """simple docstring""" _A: List[str] = self.index_for_timestep(lowerCAmelCase_ ) _A: str = self.sigmas[step_index] _A: str = sample / ((sigma**2 + 1) ** 0.5) return sample def __magic_name__ ( self : Optional[int] , lowerCAmelCase_ : int , lowerCAmelCase_ : Union[str, torch.device] = None , lowerCAmelCase_ : Optional[int] = None , ): """simple docstring""" _A: Union[str, Any] = num_inference_steps _A: str = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": _A: Optional[Any] = np.linspace(0 , num_train_timesteps - 1 , lowerCAmelCase_ , dtype=lowerCAmelCase_ )[::-1].copy() elif self.config.timestep_spacing == "leading": _A: List[Any] = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 _A: Dict = (np.arange(0 , lowerCAmelCase_ ) * step_ratio).round()[::-1].copy().astype(lowerCAmelCase_ ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": _A: Union[str, Any] = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 _A: List[Any] = (np.arange(lowerCAmelCase_ , 0 , -step_ratio )).round().copy().astype(lowerCAmelCase_ ) timesteps -= 1 else: raise ValueError( F"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.""" ) _A: Optional[int] = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) _A: str = np.log(lowerCAmelCase_ ) _A: int = np.interp(lowerCAmelCase_ , np.arange(0 , len(lowerCAmelCase_ ) ) , lowerCAmelCase_ ) if self.config.use_karras_sigmas: _A: Optional[int] = self._convert_to_karras(in_sigmas=lowerCAmelCase_ , num_inference_steps=self.num_inference_steps ) _A: List[str] = np.array([self._sigma_to_t(lowerCAmelCase_ , lowerCAmelCase_ ) for sigma in sigmas] ) _A: Optional[int] = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) _A: Optional[Any] = torch.from_numpy(lowerCAmelCase_ ).to(device=lowerCAmelCase_ ) _A: Tuple = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) _A: str = torch.from_numpy(lowerCAmelCase_ ) _A: str = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(lowerCAmelCase_ ).startswith('''mps''' ): # mps does not support float64 _A: List[Any] = timesteps.to(lowerCAmelCase_ , dtype=torch.floataa ) else: _A: Optional[int] = timesteps.to(device=lowerCAmelCase_ ) # empty dt and derivative _A: Dict = None _A: List[Any] = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter _A: Dict = defaultdict(lowerCAmelCase_ ) def __magic_name__ ( self : Dict , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Dict ): """simple docstring""" # get log sigma _A: Tuple = np.log(lowerCAmelCase_ ) # get distribution _A: List[str] = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range _A: Dict = np.cumsum((dists >= 0) , axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) _A: int = low_idx + 1 _A: Optional[int] = log_sigmas[low_idx] _A: Dict = log_sigmas[high_idx] # interpolate sigmas _A: Union[str, Any] = (low - log_sigma) / (low - high) _A: Optional[Any] = np.clip(lowerCAmelCase_ , 0 , 1 ) # transform interpolation to time range _A: Any = (1 - w) * low_idx + w * high_idx _A: List[Any] = t.reshape(sigma.shape ) return t def __magic_name__ ( self : Any , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" _A: float = in_sigmas[-1].item() _A: float = in_sigmas[0].item() _A: Union[str, Any] = 7.0 # 7.0 is the value used in the paper _A: Optional[Any] = np.linspace(0 , 1 , lowerCAmelCase_ ) _A: Tuple = sigma_min ** (1 / rho) _A: Optional[Any] = sigma_max ** (1 / rho) _A: List[str] = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def __magic_name__ ( self : Optional[Any] ): """simple docstring""" return self.dt is None def __magic_name__ ( self : Tuple , lowerCAmelCase_ : Union[torch.FloatTensor, np.ndarray] , lowerCAmelCase_ : Union[float, torch.FloatTensor] , lowerCAmelCase_ : Union[torch.FloatTensor, np.ndarray] , lowerCAmelCase_ : bool = True , ): """simple docstring""" _A: Optional[int] = self.index_for_timestep(lowerCAmelCase_ ) # advance index counter by 1 _A: Union[str, Any] = timestep.cpu().item() if torch.is_tensor(lowerCAmelCase_ ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: _A: Optional[int] = self.sigmas[step_index] _A: Union[str, Any] = self.sigmas[step_index + 1] else: # 2nd order / Heun's method _A: Union[str, Any] = self.sigmas[step_index - 1] _A: Optional[int] = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API _A: List[Any] = 0 _A: Tuple = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": _A: Union[str, Any] = sigma_hat if self.state_in_first_order else sigma_next _A: List[str] = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": _A: int = sigma_hat if self.state_in_first_order else sigma_next _A: List[str] = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": _A: Optional[int] = model_output else: raise ValueError( F"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`""" ) if self.config.clip_sample: _A: Tuple = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order _A: Optional[int] = (sample - pred_original_sample) / sigma_hat # 3. delta timestep _A: List[Any] = sigma_next - sigma_hat # store for 2nd order step _A: str = derivative _A: Any = dt _A: Dict = sample else: # 2. 2nd order / Heun's method _A: List[str] = (sample - pred_original_sample) / sigma_next _A: str = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample _A: Dict = self.dt _A: int = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" _A: int = None _A: int = None _A: Optional[Any] = None _A: Optional[Any] = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=lowerCAmelCase_ ) def __magic_name__ ( self : Any , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : torch.FloatTensor , ): """simple docstring""" # Make sure sigmas and timesteps have the same device and dtype as original_samples _A: str = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(lowerCAmelCase_ ): # mps does not support float64 _A: Optional[int] = self.timesteps.to(original_samples.device , dtype=torch.floataa ) _A: Any = timesteps.to(original_samples.device , dtype=torch.floataa ) else: _A: Union[str, Any] = self.timesteps.to(original_samples.device ) _A: int = timesteps.to(original_samples.device ) _A: str = [self.index_for_timestep(lowerCAmelCase_ , lowerCAmelCase_ ) for t in timesteps] _A: Optional[Any] = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): _A: List[str] = sigma.unsqueeze(-1 ) _A: Any = original_samples + noise * sigma return noisy_samples def __len__( self : Dict ): """simple docstring""" return self.config.num_train_timesteps
301
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 UpperCAmelCase__ : List[Any] = logging.get_logger(__name__) UpperCAmelCase__ : Tuple = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} UpperCAmelCase__ : Dict = { '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' ), }, } UpperCAmelCase__ : int = { 'google/realm-cc-news-pretrained-embedder': 512, 'google/realm-cc-news-pretrained-encoder': 512, 'google/realm-cc-news-pretrained-scorer': 512, 'google/realm-cc-news-pretrained-openqa': 512, 'google/realm-orqa-nq-openqa': 512, 'google/realm-orqa-nq-reader': 512, 'google/realm-orqa-wq-openqa': 512, 'google/realm-orqa-wq-reader': 512, } UpperCAmelCase__ : List[Any] = { '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 ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : List[str] = VOCAB_FILES_NAMES __UpperCamelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase : Optional[Any] = PRETRAINED_INIT_CONFIGURATION __UpperCamelCase : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase : Union[str, Any] = RealmTokenizer def __init__( self : int , lowerCAmelCase_ : Dict=None , lowerCAmelCase_ : Union[str, Any]=None , lowerCAmelCase_ : str=True , lowerCAmelCase_ : Tuple="[UNK]" , lowerCAmelCase_ : Optional[int]="[SEP]" , lowerCAmelCase_ : List[Any]="[PAD]" , lowerCAmelCase_ : int="[CLS]" , lowerCAmelCase_ : Any="[MASK]" , lowerCAmelCase_ : Dict=True , lowerCAmelCase_ : Tuple=None , **lowerCAmelCase_ : Optional[Any] , ): """simple docstring""" 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_ , ) _A: Union[str, 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 ): _A: Optional[Any] = getattr(lowerCAmelCase_ , normalizer_state.pop('''type''' ) ) _A: Tuple = do_lower_case _A: Union[str, Any] = strip_accents _A: Dict = tokenize_chinese_chars _A: Optional[Any] = normalizer_class(**lowerCAmelCase_ ) _A: Optional[Any] = do_lower_case def __magic_name__ ( self : List[Any] , lowerCAmelCase_ : int , **lowerCAmelCase_ : int ): """simple docstring""" _A: Dict = PaddingStrategy.MAX_LENGTH _A: Any = text _A: List[Any] = kwargs.pop('''text_pair''' , lowerCAmelCase_ ) _A: Optional[Any] = kwargs.pop('''return_tensors''' , lowerCAmelCase_ ) _A: List[str] = { '''input_ids''': [], '''attention_mask''': [], '''token_type_ids''': [], } for idx, candidate_text in enumerate(lowerCAmelCase_ ): if batch_text_pair is not None: _A: Any = batch_text_pair[idx] else: _A: List[str] = None _A: str = super().__call__(lowerCAmelCase_ , lowerCAmelCase_ , return_tensors=lowerCAmelCase_ , **lowerCAmelCase_ ) _A: int = encoded_candidates.get('''input_ids''' ) _A: Dict = encoded_candidates.get('''attention_mask''' ) _A: Optional[int] = 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_ ) _A: List[str] = {key: item for key, item in output_data.items() if len(lowerCAmelCase_ ) != 0} return BatchEncoding(lowerCAmelCase_ , tensor_type=lowerCAmelCase_ ) def __magic_name__ ( self : List[Any] , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : List[str]=None ): """simple docstring""" _A: Optional[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __magic_name__ ( self : List[Any] , lowerCAmelCase_ : List[int] , lowerCAmelCase_ : Optional[List[int]] = None ): """simple docstring""" _A: Tuple = [self.sep_token_id] _A: int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __magic_name__ ( self : List[Any] , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[str] = None ): """simple docstring""" _A: List[str] = self._tokenizer.model.save(lowerCAmelCase_ , name=lowerCAmelCase_ ) return tuple(lowerCAmelCase_ )
301
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=SCREAMING_SNAKE_CASE__ ) class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : str = field(default='''automatic-speech-recognition''' , metadata={'''include_in_asdict_even_if_is_default''': True} ) __UpperCamelCase : ClassVar[Features] = Features({'''audio''': Audio()} ) __UpperCamelCase : ClassVar[Features] = Features({'''transcription''': Value('''string''' )} ) __UpperCamelCase : str = "audio" __UpperCamelCase : str = "transcription" def __magic_name__ ( self : List[Any] , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" if self.audio_column not in features: raise ValueError(F"""Column {self.audio_column} is not present in features.""" ) if not isinstance(features[self.audio_column] , lowerCAmelCase_ ): raise ValueError(F"""Column {self.audio_column} is not an Audio type.""" ) _A: Optional[int] = copy.deepcopy(self ) _A: str = self.input_schema.copy() _A: List[str] = features[self.audio_column] _A: Dict = input_schema return task_template @property def __magic_name__ ( self : str ): """simple docstring""" return {self.audio_column: "audio", self.transcription_column: "transcription"}
301
1
from __future__ import annotations from bisect import bisect_left from functools import total_ordering from heapq import merge @total_ordering class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def __lt__( self : Dict , lowerCAmelCase_ : Optional[int] ): """simple docstring""" return self[-1] < other[-1] def __eq__( self : int , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" return self[-1] == other[-1] def lowerCamelCase__ ( a ) -> list: _A: list[Stack] = [] # sort into stacks for element in collection: _A: Any = Stack([element] ) _A: Optional[Any] = bisect_left(a , a ) if i != len(a ): stacks[i].append(a ) else: stacks.append(a ) # use a heap-based merge to merge stack efficiently _A: Tuple = merge(*(reversed(a ) for stack in stacks) ) return collection if __name__ == "__main__": UpperCAmelCase__ : Tuple = input('Enter numbers separated by a comma:\n').strip() UpperCAmelCase__ : Optional[Any] = [int(item) for item in user_input.split(',')] print(patience_sort(unsorted))
301
import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer UpperCAmelCase__ : Optional[int] = 'bart' UpperCAmelCase__ : Dict = True @st.cache(allow_output_mutation=a ) def lowerCamelCase__ ( ) -> Dict: if LOAD_DENSE_INDEX: _A: Optional[Any] = AutoTokenizer.from_pretrained('''yjernite/retribert-base-uncased''' ) _A: Any = AutoModel.from_pretrained('''yjernite/retribert-base-uncased''' ).to('''cuda:0''' ) _A: Any = qar_model.eval() else: _A , _A: Union[str, Any] = (None, None) if MODEL_TYPE == "bart": _A: Union[str, Any] = AutoTokenizer.from_pretrained('''yjernite/bart_eli5''' ) _A: Dict = AutoModelForSeqaSeqLM.from_pretrained('''yjernite/bart_eli5''' ).to('''cuda:0''' ) _A: Union[str, Any] = torch.load('''seq2seq_models/eli5_bart_model_blm_2.pth''' ) sas_model.load_state_dict(save_dict['''model'''] ) _A: int = sas_model.eval() else: _A , _A: Tuple = make_qa_sas_model( model_name='''t5-small''' , from_file='''seq2seq_models/eli5_t5_model_1024_4.pth''' , device='''cuda:0''' ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=a ) def lowerCamelCase__ ( ) -> Tuple: if LOAD_DENSE_INDEX: _A: List[Any] = faiss.StandardGpuResources() _A: int = datasets.load_dataset(path='''wiki_snippets''' , name='''wiki40b_en_100_0''' )['''train'''] _A: Dict = np.memmap( '''wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat''' , dtype='''float32''' , mode='''r''' , shape=(wikiaab_passages.num_rows, 1_28) , ) _A: str = faiss.IndexFlatIP(1_28 ) _A: Optional[int] = faiss.index_cpu_to_gpu(a , 1 , a ) wikiaab_gpu_index_flat.add(a ) # TODO fix for larger GPU else: _A , _A: str = (None, None) _A: Tuple = Elasticsearch([{'''host''': '''localhost''', '''port''': '''9200'''}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=a ) def lowerCamelCase__ ( ) -> str: _A: Dict = datasets.load_dataset('''eli5''' , name='''LFQA_reddit''' ) _A: Dict = elia['''train_eli5'''] _A: List[Any] = np.memmap( '''eli5_questions_reps.dat''' , dtype='''float32''' , mode='''r''' , shape=(elia_train.num_rows, 1_28) ) _A: Any = faiss.IndexFlatIP(1_28 ) eli5_train_q_index.add(a ) return (elia_train, eli5_train_q_index) UpperCAmelCase__ ,UpperCAmelCase__ ,UpperCAmelCase__ : int = load_indexes() UpperCAmelCase__ ,UpperCAmelCase__ ,UpperCAmelCase__ ,UpperCAmelCase__ : Any = load_models() UpperCAmelCase__ ,UpperCAmelCase__ : Tuple = load_train_data() def lowerCamelCase__ ( a , a=10 ) -> str: _A: Optional[int] = embed_questions_for_retrieval([question] , a , a ) _A , _A: List[str] = eli5_train_q_index.search(a , a ) _A: Dict = [elia_train[int(a )] for i in I[0]] return nn_examples def lowerCamelCase__ ( a , a="wiki40b" , a="dense" , a=10 ) -> str: if source == "none": _A , _A: Any = (''' <P> '''.join(['''''' for _ in range(11 )] ).strip(), []) else: if method == "dense": _A , _A: List[Any] = query_qa_dense_index( a , a , a , a , a , a ) else: _A , _A: Tuple = query_es_index( a , a , index_name='''english_wiki40b_snippets_100w''' , n_results=a , ) _A: Union[str, Any] = [ (res['''article_title'''], res['''section_title'''].strip(), res['''score'''], res['''passage_text''']) for res in hit_lst ] _A: str = '''question: {} context: {}'''.format(a , a ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda a : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda a : None), } ) def lowerCamelCase__ ( a , a , a , a=64 , a=2_56 , a=False , a=2 , a=0.95 , a=0.8 ) -> str: with torch.no_grad(): _A: Optional[int] = qa_sas_generate( a , a , a , num_answers=1 , num_beams=a , min_len=a , max_len=a , do_sample=a , temp=a , top_p=a , top_k=a , max_input_length=10_24 , device='''cuda:0''' , )[0] return (answer, support_list) st.title('Long Form Question Answering with ELI5') # Start sidebar UpperCAmelCase__ : List[Any] = '<img src=\'https://huggingface.co/front/assets/huggingface_logo.svg\'>' UpperCAmelCase__ : Optional[Any] = '\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class="img-container"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n' % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia UpperCAmelCase__ : str = '\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n' st.sidebar.markdown(description, unsafe_allow_html=True) UpperCAmelCase__ : str = [ 'Answer the question', 'View the retrieved document only', 'View the most similar ELI5 question and answer', 'Show me everything, please!', ] UpperCAmelCase__ : Optional[int] = st.sidebar.checkbox('Demo options') if demo_options: UpperCAmelCase__ : Any = st.sidebar.selectbox( '', action_list, index=3, ) UpperCAmelCase__ : List[str] = action_list.index(action_st) UpperCAmelCase__ : Optional[Any] = st.sidebar.selectbox( '', ['Show full text of passages', 'Show passage section titles'], index=0, ) UpperCAmelCase__ : List[Any] = show_type == 'Show full text of passages' else: UpperCAmelCase__ : Dict = 3 UpperCAmelCase__ : str = True UpperCAmelCase__ : Optional[Any] = st.sidebar.checkbox('Retrieval options') if retrieval_options: UpperCAmelCase__ : List[str] = '\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n ' st.sidebar.markdown(retriever_info) UpperCAmelCase__ : Optional[int] = st.sidebar.selectbox('Which Wikipedia format should the model use?', ['wiki40b', 'none']) UpperCAmelCase__ : int = st.sidebar.selectbox('Which Wikipedia indexer should the model use?', ['dense', 'sparse', 'mixed']) else: UpperCAmelCase__ : Tuple = 'wiki40b' UpperCAmelCase__ : List[Any] = 'dense' UpperCAmelCase__ : Tuple = 'beam' UpperCAmelCase__ : Any = 2 UpperCAmelCase__ : Dict = 64 UpperCAmelCase__ : Any = 256 UpperCAmelCase__ : int = None UpperCAmelCase__ : List[str] = None UpperCAmelCase__ : Optional[int] = st.sidebar.checkbox('Generation options') if generate_options: UpperCAmelCase__ : Any = '\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder\'s output probabilities.\n ' st.sidebar.markdown(generate_info) UpperCAmelCase__ : Optional[int] = st.sidebar.selectbox('Would you like to use beam search or sample an answer?', ['beam', 'sampled']) UpperCAmelCase__ : int = st.sidebar.slider( 'Minimum generation length', min_value=8, max_value=256, value=64, step=8, format=None, key=None ) UpperCAmelCase__ : str = st.sidebar.slider( 'Maximum generation length', min_value=64, max_value=512, value=256, step=16, format=None, key=None ) if sampled == "beam": UpperCAmelCase__ : Tuple = st.sidebar.slider('Beam size', min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: UpperCAmelCase__ : List[Any] = st.sidebar.slider( 'Nucleus sampling p', min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None ) UpperCAmelCase__ : Union[str, Any] = st.sidebar.slider( 'Temperature', min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None ) UpperCAmelCase__ : Optional[int] = None # start main text UpperCAmelCase__ : Any = [ '<MY QUESTION>', 'How do people make chocolate?', 'Why do we get a fever when we are sick?', 'How can different animals perceive different colors?', 'What is natural language processing?', 'What\'s the best way to treat a sunburn?', 'What exactly are vitamins ?', 'How does nuclear energy provide electricity?', 'What\'s the difference between viruses and bacteria?', 'Why are flutes classified as woodwinds when most of them are made out of metal ?', 'Why do people like drinking coffee even though it tastes so bad?', 'What happens when wine ages? How does it make the wine taste better?', 'If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?', 'How can we set a date to the beginning or end of an artistic period? Doesn\'t the change happen gradually?', 'How does New Zealand have so many large bird predators?', ] UpperCAmelCase__ : List[Any] = st.selectbox( 'What would you like to ask? ---- select <MY QUESTION> to enter a new query', questions_list, index=1, ) if question_s == "<MY QUESTION>": UpperCAmelCase__ : Any = st.text_input('Enter your question here:', '') else: UpperCAmelCase__ : int = question_s if st.button('Show me!'): if action in [0, 1, 3]: if index_type == "mixed": UpperCAmelCase__ ,UpperCAmelCase__ : Tuple = make_support(question, source=wiki_source, method='dense', n_results=10) UpperCAmelCase__ ,UpperCAmelCase__ : Optional[Any] = make_support(question, source=wiki_source, method='sparse', n_results=10) UpperCAmelCase__ : Dict = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] UpperCAmelCase__ : str = support_list[:10] UpperCAmelCase__ : str = '<P> ' + ' <P> '.join([res[-1] for res in support_list]) else: UpperCAmelCase__ ,UpperCAmelCase__ : List[Any] = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: UpperCAmelCase__ ,UpperCAmelCase__ : Optional[Any] = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == 'sampled'), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown('### The model generated answer is:') st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown('--- \n ### The model is drawing information from the following Wikipedia passages:') for i, res in enumerate(support_list): UpperCAmelCase__ : Any = 'https://en.wikipedia.org/wiki/{}'.format(res[0].replace(' ', '_')) UpperCAmelCase__ : Tuple = res[1].strip() if sec_titles == "": UpperCAmelCase__ : Optional[int] = '[{}]({})'.format(res[0], wiki_url) else: UpperCAmelCase__ : int = sec_titles.split(' & ') UpperCAmelCase__ : Union[str, Any] = ' & '.join( ['[{}]({}#{})'.format(sec.strip(), wiki_url, sec.strip().replace(' ', '_')) for sec in sec_list] ) st.markdown( '{0:02d} - **Article**: {1:<18} <br> _Section_: {2}'.format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( '> <span style="font-family:arial; font-size:10pt;">' + res[-1] + '</span>', unsafe_allow_html=True ) if action in [2, 3]: UpperCAmelCase__ : Union[str, Any] = find_nearest_training(question) UpperCAmelCase__ : int = nn_train_list[0] st.markdown( '--- \n ### The most similar question in the ELI5 training set was: \n\n {}'.format(train_exple['title']) ) UpperCAmelCase__ : Tuple = [ '{}. {}'.format(i + 1, ' \n'.join([line.strip() for line in ans.split('\n') if line.strip() != ''])) for i, (ans, sc) in enumerate(zip(train_exple['answers']['text'], train_exple['answers']['score'])) if i == 0 or sc > 2 ] st.markdown('##### Its answers were: \n\n {}'.format('\n'.join(answers_st))) UpperCAmelCase__ : Any = '\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n' st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
301
1
import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets UpperCAmelCase__ : List[str] = '\\n @inproceedings{kakwani2020indicnlpsuite,\n title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}},\n author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar},\n year={2020},\n booktitle={Findings of EMNLP},\n}\n' UpperCAmelCase__ : Dict = '\\n IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide\n variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te.\n' UpperCAmelCase__ : Dict = '\nCompute IndicGLUE evaluation metric associated to each IndicGLUE dataset.\nArgs:\n predictions: list of predictions to score (as int64),\n except for \'cvit-mkb-clsr\' where each prediction is a vector (of float32).\n references: list of ground truth labels corresponding to the predictions (as int64),\n except for \'cvit-mkb-clsr\' where each reference is a vector (of float32).\nReturns: depending on the IndicGLUE subset, one or several of:\n "accuracy": Accuracy\n "f1": F1 score\n "precision": Precision@10\nExamples:\n\n >>> indic_glue_metric = datasets.load_metric(\'indic_glue\', \'wnli\') # \'wnli\' or any of ["copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md"]\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric(\'indic_glue\', \'wiki-ner\')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0, \'f1\': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric(\'indic_glue\', \'cvit-mkb-clsr\')\n >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'precision@10\': 1.0}\n\n' def lowerCamelCase__ ( a , a ) -> Optional[int]: return float((preds == labels).mean() ) def lowerCamelCase__ ( a , a ) -> List[str]: _A: Any = simple_accuracy(a , a ) _A: Dict = float(fa_score(y_true=a , y_pred=a ) ) return { "accuracy": acc, "f1": fa, } def lowerCamelCase__ ( a , a ) -> Union[str, Any]: _A: Any = np.array(a ) _A: Optional[Any] = np.array(a ) _A: Optional[Any] = en_sentvecs.shape[0] # mean centering _A: List[Any] = en_sentvecs - np.mean(a , axis=0 ) _A: Optional[int] = in_sentvecs - np.mean(a , axis=0 ) _A: str = cdist(a , a , '''cosine''' ) _A: str = np.array(range(a ) ) _A: Optional[int] = sim.argsort(axis=1 )[:, :10] _A: Tuple = np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase ( datasets.Metric ): '''simple docstring''' def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( '''You should supply a configuration name selected in ''' '''["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ''' '''"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ''' '''"wiki-ner"]''' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''int64''' ) if self.config_name != '''cvit-mkb-clsr''' else datasets.Sequence(datasets.Value('''float32''' ) ), '''references''': datasets.Value('''int64''' ) if self.config_name != '''cvit-mkb-clsr''' else datasets.Sequence(datasets.Value('''float32''' ) ), } ) , codebase_urls=[] , reference_urls=[] , format='''numpy''' if self.config_name != '''cvit-mkb-clsr''' else None , ) def __magic_name__ ( self : Any , lowerCAmelCase_ : str , lowerCAmelCase_ : Dict ): """simple docstring""" if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(lowerCAmelCase_ , lowerCAmelCase_ )} elif self.config_name in ["wiki-ner"]: return acc_and_fa(lowerCAmelCase_ , lowerCAmelCase_ ) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ )} else: raise KeyError( '''You should supply a configuration name selected in ''' '''["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ''' '''"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ''' '''"wiki-ner"]''' )
301
from __future__ import annotations UpperCAmelCase__ : List[str] = list[list[int]] # assigning initial values to the grid UpperCAmelCase__ : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution UpperCAmelCase__ : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def lowerCamelCase__ ( a , a , a , a ) -> bool: for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def lowerCamelCase__ ( a ) -> tuple[int, int] | None: for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def lowerCamelCase__ ( a ) -> Matrix | None: if location := find_empty_location(a ): _A , _A: Optional[Any] = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(a , a , a , a ): _A: str = digit if sudoku(a ) is not None: return grid _A: Tuple = 0 return None def lowerCamelCase__ ( a ) -> None: for row in grid: for cell in row: print(a , end=''' ''' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('\nExample grid:\n' + '=' * 20) print_solution(example_grid) print('\nExample grid solution:') UpperCAmelCase__ : int = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('Cannot find a solution.')
301
1
import json import os import unittest from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase : List[str] = LEDTokenizer __UpperCamelCase : Optional[int] = LEDTokenizerFast __UpperCamelCase : List[Any] = True def __magic_name__ ( self : Optional[Any] ): """simple docstring""" super().setUp() _A: str = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''<unk>''', ] _A: Optional[Any] = dict(zip(lowerCAmelCase_ , range(len(lowerCAmelCase_ ) ) ) ) _A: List[Any] = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] _A: Optional[Any] = {'''unk_token''': '''<unk>'''} _A: Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) _A: Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(lowerCAmelCase_ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(lowerCAmelCase_ ) ) def __magic_name__ ( self : Union[str, Any] , **lowerCAmelCase_ : str ): """simple docstring""" kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **lowerCAmelCase_ ) def __magic_name__ ( self : Optional[Any] , **lowerCAmelCase_ : str ): """simple docstring""" kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **lowerCAmelCase_ ) def __magic_name__ ( self : Dict , lowerCAmelCase_ : List[str] ): """simple docstring""" return "lower newer", "lower newer" @cached_property def __magic_name__ ( self : Dict ): """simple docstring""" return LEDTokenizer.from_pretrained('''allenai/led-base-16384''' ) @cached_property def __magic_name__ ( self : Dict ): """simple docstring""" return LEDTokenizerFast.from_pretrained('''allenai/led-base-16384''' ) @require_torch def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" _A: Dict = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] _A: List[str] = [0, 2_5_0, 2_5_1, 1_7_8_1_8, 1_3, 3_9_1_8_6, 1_9_3_8, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _A: Tuple = tokenizer(lowerCAmelCase_ , max_length=len(lowerCAmelCase_ ) , padding=lowerCAmelCase_ , return_tensors='''pt''' ) self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) _A: Optional[int] = batch.input_ids.tolist()[0] self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) @require_torch def __magic_name__ ( self : str ): """simple docstring""" _A: Optional[Any] = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _A: List[Any] = tokenizer(lowerCAmelCase_ , padding=lowerCAmelCase_ , return_tensors='''pt''' ) self.assertIn('''input_ids''' , lowerCAmelCase_ ) self.assertIn('''attention_mask''' , lowerCAmelCase_ ) self.assertNotIn('''labels''' , lowerCAmelCase_ ) self.assertNotIn('''decoder_attention_mask''' , lowerCAmelCase_ ) @require_torch def __magic_name__ ( self : int ): """simple docstring""" _A: Union[str, Any] = [ '''Summary of the text.''', '''Another summary.''', ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _A: Dict = tokenizer(text_target=lowerCAmelCase_ , max_length=3_2 , padding='''max_length''' , return_tensors='''pt''' ) self.assertEqual(3_2 , targets['''input_ids'''].shape[1] ) @require_torch def __magic_name__ ( self : Tuple ): """simple docstring""" for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _A: Union[str, Any] = tokenizer( ['''I am a small frog''' * 1_0_2_4, '''I am a small frog'''] , padding=lowerCAmelCase_ , truncation=lowerCAmelCase_ , return_tensors='''pt''' ) self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertEqual(batch.input_ids.shape , (2, 5_1_2_2) ) @require_torch def __magic_name__ ( self : Any ): """simple docstring""" _A: List[Any] = ['''A long paragraph for summarization.'''] _A: int = [ '''Summary of the text.''', ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _A: Dict = tokenizer(lowerCAmelCase_ , return_tensors='''pt''' ) _A: Dict = tokenizer(text_target=lowerCAmelCase_ , return_tensors='''pt''' ) _A: Optional[int] = inputs['''input_ids'''] _A: List[Any] = targets['''input_ids'''] self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() ) self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() ) @require_torch def __magic_name__ ( self : str ): """simple docstring""" for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _A: Optional[int] = ['''Summary of the text.''', '''Another summary.'''] _A: Optional[Any] = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]] _A: List[Any] = tokenizer(lowerCAmelCase_ , padding=lowerCAmelCase_ ) _A: Optional[Any] = [[0] * len(lowerCAmelCase_ ) for x in encoded_output['''input_ids''']] _A: Optional[int] = tokenizer.pad(lowerCAmelCase_ ) self.assertSequenceEqual(outputs['''global_attention_mask'''] , lowerCAmelCase_ ) def __magic_name__ ( self : List[str] ): """simple docstring""" pass def __magic_name__ ( self : List[Any] ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): _A: int = self.rust_tokenizer_class.from_pretrained(lowerCAmelCase_ , **lowerCAmelCase_ ) _A: Union[str, Any] = self.tokenizer_class.from_pretrained(lowerCAmelCase_ , **lowerCAmelCase_ ) _A: Optional[int] = '''A, <mask> AllenNLP sentence.''' _A: List[Any] = tokenizer_r.encode_plus(lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ , return_token_type_ids=lowerCAmelCase_ ) _A: Union[str, Any] = tokenizer_p.encode_plus(lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ , return_token_type_ids=lowerCAmelCase_ ) self.assertEqual(sum(tokens_r['''token_type_ids'''] ) , sum(tokens_p['''token_type_ids'''] ) ) self.assertEqual( sum(tokens_r['''attention_mask'''] ) / len(tokens_r['''attention_mask'''] ) , sum(tokens_p['''attention_mask'''] ) / len(tokens_p['''attention_mask'''] ) , ) _A: Optional[Any] = tokenizer_r.convert_ids_to_tokens(tokens_r['''input_ids'''] ) _A: int = tokenizer_p.convert_ids_to_tokens(tokens_p['''input_ids'''] ) self.assertSequenceEqual(tokens_p['''input_ids'''] , [0, 2_5_0, 6, 5_0_2_6_4, 3_8_2_3, 4_8_7, 2_1_9_9_2, 3_6_4_5, 4, 2] ) self.assertSequenceEqual(tokens_r['''input_ids'''] , [0, 2_5_0, 6, 5_0_2_6_4, 3_8_2_3, 4_8_7, 2_1_9_9_2, 3_6_4_5, 4, 2] ) self.assertSequenceEqual( lowerCAmelCase_ , ['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>'''] ) self.assertSequenceEqual( lowerCAmelCase_ , ['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>'''] )
301
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests UpperCAmelCase__ : str = open # noqa: we just need to have a builtin inside this module to test it properly
301
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCAmelCase__ : int = { 'configuration_falcon': ['FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FalconConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : List[str] = [ '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 UpperCAmelCase__ : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
301
import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Optional[Any] , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : List[str]=3 , lowerCAmelCase_ : List[str]=3_2 , lowerCAmelCase_ : Union[str, Any]=3 , lowerCAmelCase_ : int=1_0 , lowerCAmelCase_ : Tuple=[1_0, 2_0, 3_0, 4_0] , lowerCAmelCase_ : Optional[Any]=[1, 1, 2, 1] , lowerCAmelCase_ : Optional[Any]=True , lowerCAmelCase_ : str=True , lowerCAmelCase_ : Optional[Any]="relu" , lowerCAmelCase_ : int=3 , lowerCAmelCase_ : List[Any]=None , ): """simple docstring""" _A: str = parent _A: List[Any] = batch_size _A: Optional[int] = image_size _A: Dict = num_channels _A: str = embeddings_size _A: Any = hidden_sizes _A: Dict = depths _A: Any = is_training _A: int = use_labels _A: Tuple = hidden_act _A: int = num_labels _A: int = scope _A: str = len(lowerCAmelCase_ ) def __magic_name__ ( self : Dict ): """simple docstring""" _A: Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _A: Union[str, Any] = self.get_config() return config, pixel_values def __magic_name__ ( self : str ): """simple docstring""" return RegNetConfig( 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 , image_size=self.image_size , ) def __magic_name__ ( self : str , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : str ): """simple docstring""" _A: str = FlaxRegNetModel(config=lowerCAmelCase_ ) _A: Optional[int] = model(lowerCAmelCase_ ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , ) def __magic_name__ ( self : str , lowerCAmelCase_ : str , lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Union[str, Any] = self.num_labels _A: Union[str, Any] = FlaxRegNetForImageClassification(config=lowerCAmelCase_ ) _A: str = model(lowerCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __magic_name__ ( self : List[Any] ): """simple docstring""" _A: str = self.prepare_config_and_inputs() _A , _A: Optional[int] = config_and_inputs _A: Union[str, Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_flax class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Tuple = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () __UpperCamelCase : Union[str, Any] = False __UpperCamelCase : List[Any] = False __UpperCamelCase : int = False def __magic_name__ ( self : int ): """simple docstring""" _A: int = FlaxRegNetModelTester(self ) _A: Union[str, Any] = ConfigTester(self , config_class=lowerCAmelCase_ , has_text_modality=lowerCAmelCase_ ) def __magic_name__ ( self : str ): """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __magic_name__ ( self : int ): """simple docstring""" return def __magic_name__ ( self : Tuple ): """simple docstring""" _A: int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase_ ) def __magic_name__ ( self : Tuple ): """simple docstring""" _A: Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_ ) @unittest.skip(reason='''RegNet does not use inputs_embeds''' ) def __magic_name__ ( self : str ): """simple docstring""" pass @unittest.skip(reason='''RegNet does not support input and output embeddings''' ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" pass def __magic_name__ ( self : List[Any] ): """simple docstring""" _A , _A: int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A: Union[str, Any] = model_class(lowerCAmelCase_ ) _A: Any = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _A: Any = [*signature.parameters.keys()] _A: Union[str, Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowerCAmelCase_ ) def __magic_name__ ( self : str ): """simple docstring""" def check_hidden_states_output(lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Tuple ): _A: int = model_class(lowerCAmelCase_ ) _A: List[str] = model(**self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ ) ) _A: str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _A: Tuple = self.model_tester.num_stages self.assertEqual(len(lowerCAmelCase_ ) , expected_num_stages + 1 ) _A , _A: List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A: Optional[Any] = True check_hidden_states_output(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _A: int = True check_hidden_states_output(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) def __magic_name__ ( self : Dict ): """simple docstring""" _A , _A: str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): _A: int = self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ ) _A: Union[str, Any] = model_class(lowerCAmelCase_ ) @jax.jit def model_jitted(lowerCAmelCase_ : Optional[Any] , **lowerCAmelCase_ : Optional[Any] ): return model(pixel_values=lowerCAmelCase_ , **lowerCAmelCase_ ) with self.subTest('''JIT Enabled''' ): _A: str = model_jitted(**lowerCAmelCase_ ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): _A: List[Any] = model_jitted(**lowerCAmelCase_ ).to_tuple() self.assertEqual(len(lowerCAmelCase_ ) , len(lowerCAmelCase_ ) ) for jitted_output, output in zip(lowerCAmelCase_ , lowerCAmelCase_ ): self.assertEqual(jitted_output.shape , output.shape ) def lowerCamelCase__ ( ) -> Tuple: _A: List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_flax class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" return AutoImageProcessor.from_pretrained('''facebook/regnet-y-040''' ) if is_vision_available() else None @slow def __magic_name__ ( self : List[str] ): """simple docstring""" _A: List[str] = FlaxRegNetForImageClassification.from_pretrained('''facebook/regnet-y-040''' ) _A: str = self.default_image_processor _A: int = prepare_img() _A: List[Any] = image_processor(images=lowerCAmelCase_ , return_tensors='''np''' ) _A: str = model(**lowerCAmelCase_ ) # verify the logits _A: str = (1, 1_0_0_0) self.assertEqual(outputs.logits.shape , lowerCAmelCase_ ) _A: Tuple = jnp.array([-0.4180, -1.5051, -3.4836] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] , lowerCAmelCase_ , atol=1e-4 ) )
301
1
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : Union[str, Any] = { 'google/mobilenet_v1_1.0_224': 'https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json', 'google/mobilenet_v1_0.75_192': 'https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 } class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Optional[int] = '''mobilenet_v1''' def __init__( self : Optional[int] , lowerCAmelCase_ : Any=3 , lowerCAmelCase_ : str=2_2_4 , lowerCAmelCase_ : List[str]=1.0 , lowerCAmelCase_ : Any=8 , lowerCAmelCase_ : Tuple="relu6" , lowerCAmelCase_ : List[Any]=True , lowerCAmelCase_ : Optional[int]=0.999 , lowerCAmelCase_ : List[str]=0.02 , lowerCAmelCase_ : List[Any]=0.001 , **lowerCAmelCase_ : Optional[Any] , ): """simple docstring""" super().__init__(**lowerCAmelCase_ ) if depth_multiplier <= 0: raise ValueError('''depth_multiplier must be greater than zero.''' ) _A: Any = num_channels _A: Optional[int] = image_size _A: Optional[Any] = depth_multiplier _A: Tuple = min_depth _A: Any = hidden_act _A: Dict = tf_padding _A: List[Any] = classifier_dropout_prob _A: Tuple = initializer_range _A: Tuple = layer_norm_eps class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Dict = version.parse('''1.11''' ) @property def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" return OrderedDict([('''pixel_values''', {0: '''batch'''})] ) @property def __magic_name__ ( self : Optional[Any] ): """simple docstring""" if self.task == "image-classification": return OrderedDict([('''logits''', {0: '''batch'''})] ) else: return OrderedDict([('''last_hidden_state''', {0: '''batch'''}), ('''pooler_output''', {0: '''batch'''})] ) @property def __magic_name__ ( self : Dict ): """simple docstring""" return 1e-4
301
from __future__ import annotations from bisect import bisect_left from functools import total_ordering from heapq import merge @total_ordering class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def __lt__( self : Dict , lowerCAmelCase_ : Optional[int] ): """simple docstring""" return self[-1] < other[-1] def __eq__( self : int , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" return self[-1] == other[-1] def lowerCamelCase__ ( a ) -> list: _A: list[Stack] = [] # sort into stacks for element in collection: _A: Any = Stack([element] ) _A: Optional[Any] = bisect_left(a , a ) if i != len(a ): stacks[i].append(a ) else: stacks.append(a ) # use a heap-based merge to merge stack efficiently _A: Tuple = merge(*(reversed(a ) for stack in stacks) ) return collection if __name__ == "__main__": UpperCAmelCase__ : Tuple = input('Enter numbers separated by a comma:\n').strip() UpperCAmelCase__ : Optional[Any] = [int(item) for item in user_input.split(',')] print(patience_sort(unsorted))
301
1
import random def lowerCamelCase__ ( a , a ) -> tuple: _A , _A , _A: int = [], [], [] for element in data: if element < pivot: less.append(a ) elif element > pivot: greater.append(a ) else: equal.append(a ) return less, equal, greater def lowerCamelCase__ ( a , a ) -> List[str]: # index = len(items) // 2 when trying to find the median # (value of index when items is sorted) # invalid input if index >= len(a ) or index < 0: return None _A: Any = items[random.randint(0 , len(a ) - 1 )] _A: List[str] = 0 _A , _A , _A: List[Any] = _partition(a , a ) _A: str = len(a ) _A: List[Any] = len(a ) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(a , a ) # must be in larger else: return quick_select(a , index - (m + count) )
301
import argparse import datetime import json import time import warnings from logging import getLogger from pathlib import Path from typing import Dict, List import torch from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils import calculate_bleu, calculate_rouge, chunks, parse_numeric_n_bool_cl_kwargs, use_task_specific_params UpperCAmelCase__ : Any = getLogger(__name__) UpperCAmelCase__ : Optional[Any] = 'cuda' if torch.cuda.is_available() else 'cpu' def lowerCamelCase__ ( a , a , a , a = 8 , a = DEFAULT_DEVICE , a=False , a="summarization" , a=None , **a , ) -> Dict: _A: str = Path(a ).open('''w''' , encoding='''utf-8''' ) _A: Optional[Any] = str(a ) _A: Union[str, Any] = AutoModelForSeqaSeqLM.from_pretrained(a ).to(a ) if fpaa: _A: Any = model.half() _A: Optional[int] = AutoTokenizer.from_pretrained(a ) logger.info(f"""Inferred tokenizer type: {tokenizer.__class__}""" ) # if this is wrong, check config.model_type. _A: Any = time.time() # update config with task specific params use_task_specific_params(a , a ) if prefix is None: _A: int = prefix or getattr(model.config , '''prefix''' , '''''' ) or '''''' for examples_chunk in tqdm(list(chunks(a , a ) ) ): _A: int = [prefix + text for text in examples_chunk] _A: str = tokenizer(a , return_tensors='''pt''' , truncation=a , padding='''longest''' ).to(a ) _A: str = model.generate( input_ids=batch.input_ids , attention_mask=batch.attention_mask , **a , ) _A: str = tokenizer.batch_decode(a , skip_special_tokens=a , clean_up_tokenization_spaces=a ) for hypothesis in dec: fout.write(hypothesis + '''\n''' ) fout.flush() fout.close() _A: Optional[int] = int(time.time() - start_time ) # seconds _A: Union[str, Any] = len(a ) return {"n_obs": n_obs, "runtime": runtime, "seconds_per_sample": round(runtime / n_obs , 4 )} def lowerCamelCase__ ( ) -> Tuple: return datetime.datetime.now().strftime('''%Y-%m-%d %H:%M:%S''' ) def lowerCamelCase__ ( a=True ) -> Optional[Any]: _A: str = argparse.ArgumentParser() parser.add_argument('''model_name''' , type=a , help='''like facebook/bart-large-cnn,t5-base, etc.''' ) parser.add_argument('''input_path''' , type=a , help='''like cnn_dm/test.source''' ) parser.add_argument('''save_path''' , type=a , help='''where to save summaries''' ) parser.add_argument('''--reference_path''' , type=a , required=a , help='''like cnn_dm/test.target''' ) parser.add_argument('''--score_path''' , type=a , required=a , default='''metrics.json''' , help='''where to save metrics''' ) parser.add_argument('''--device''' , type=a , required=a , default=a , help='''cuda, cuda:1, cpu etc.''' ) parser.add_argument( '''--prefix''' , type=a , required=a , default=a , help='''will be added to the begininng of src examples''' ) parser.add_argument('''--task''' , type=a , default='''summarization''' , help='''used for task_specific_params + metrics''' ) parser.add_argument('''--bs''' , type=a , default=8 , required=a , help='''batch size''' ) parser.add_argument( '''--n_obs''' , type=a , default=-1 , required=a , help='''How many observations. Defaults to all.''' ) parser.add_argument('''--fp16''' , action='''store_true''' ) parser.add_argument('''--dump-args''' , action='''store_true''' , help='''print the custom hparams with the results''' ) parser.add_argument( '''--info''' , nargs='''?''' , type=a , const=datetime_now() , help=( '''use in conjunction w/ --dump-args to print with the results whatever other info you\'d like, e.g.''' ''' lang=en-ru. If no value is passed, the current datetime string will be used.''' ) , ) # Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate _A , _A: Tuple = parser.parse_known_args() _A: List[str] = parse_numeric_n_bool_cl_kwargs(a ) if parsed_args and verbose: print(f"""parsed the following generate kwargs: {parsed_args}""" ) _A: int = [''' ''' + x.rstrip() if '''t5''' in args.model_name else x.rstrip() for x in open(args.input_path ).readlines()] if args.n_obs > 0: _A: List[str] = examples[: args.n_obs] Path(args.save_path ).parent.mkdir(exist_ok=a ) if args.reference_path is None and Path(args.score_path ).exists(): warnings.warn(f"""score_path {args.score_path} will be overwritten unless you type ctrl-c.""" ) if args.device == "cpu" and args.fpaa: # this mix leads to RuntimeError: "threshold_cpu" not implemented for 'Half' raise ValueError('''Can\'t mix --fp16 and --device cpu''' ) _A: Dict = generate_summaries_or_translations( a , args.save_path , args.model_name , batch_size=args.bs , device=args.device , fpaa=args.fpaa , task=args.task , prefix=args.prefix , **a , ) if args.reference_path is None: return {} # Compute scores _A: Dict = calculate_bleu if '''translation''' in args.task else calculate_rouge _A: List[Any] = [x.rstrip() for x in open(args.save_path ).readlines()] _A: Any = [x.rstrip() for x in open(args.reference_path ).readlines()][: len(a )] _A: dict = score_fn(a , a ) scores.update(a ) if args.dump_args: scores.update(a ) if args.info: _A: Optional[Any] = args.info if verbose: print(a ) if args.score_path is not None: json.dump(a , open(args.score_path , '''w''' ) ) return scores if __name__ == "__main__": # Usage for MT: # python run_eval.py MODEL_NAME $DATA_DIR/test.source $save_dir/test_translations.txt --reference_path $DATA_DIR/test.target --score_path $save_dir/test_bleu.json --task translation $@ run_generate(verbose=True)
301
1
import argparse from torch import nn # transformers_old should correspond to branch `save_old_prophetnet_model_structure` here # original prophetnet_checkpoints are saved under `patrickvonplaten/..._old` respectively from transformers_old.modeling_prophetnet import ( ProphetNetForConditionalGeneration as ProphetNetForConditionalGenerationOld, ) from transformers_old.modeling_xlm_prophetnet import ( XLMProphetNetForConditionalGeneration as XLMProphetNetForConditionalGenerationOld, ) from transformers import ProphetNetForConditionalGeneration, XLMProphetNetForConditionalGeneration, logging UpperCAmelCase__ : str = logging.get_logger(__name__) logging.set_verbosity_info() def lowerCamelCase__ ( a , a ) -> Optional[Any]: if "xprophetnet" in prophetnet_checkpoint_path: _A: str = XLMProphetNetForConditionalGenerationOld.from_pretrained(a ) _A , _A: int = XLMProphetNetForConditionalGeneration.from_pretrained( a , output_loading_info=a ) else: _A: Dict = ProphetNetForConditionalGenerationOld.from_pretrained(a ) _A , _A: Any = ProphetNetForConditionalGeneration.from_pretrained( a , output_loading_info=a ) _A: str = ['''key_proj''', '''value_proj''', '''query_proj'''] _A: List[Any] = { '''self_attn''': '''ngram_self_attn''', '''cross_attn''': '''encoder_attn''', '''cross_attn_layer_norm''': '''encoder_attn_layer_norm''', '''feed_forward_layer_norm''': '''final_layer_norm''', '''feed_forward''': '''''', '''intermediate''': '''fc1''', '''output''': '''fc2''', '''key_proj''': '''k_proj''', '''query_proj''': '''q_proj''', '''value_proj''': '''v_proj''', '''word_embeddings''': '''embed_tokens''', '''embeddings_layer_norm''': '''emb_layer_norm''', '''relative_pos_embeddings''': '''relative_linear''', '''ngram_embeddings''': '''ngram_input_embed''', '''position_embeddings''': '''embed_positions''', } for key in loading_info["missing_keys"]: _A: Tuple = key.split('''.''' ) if attributes[0] == "lm_head": _A: List[Any] = prophet _A: List[Any] = prophet_old else: _A: List[Any] = prophet.prophetnet _A: Dict = prophet_old.model _A: List[str] = False for attribute in attributes: if attribute in mapping: _A: Any = mapping[attribute] if not hasattr(a , a ) and len(a ) > 0: _A: Dict = attribute elif hasattr(a , a ): _A: List[Any] = attribute if attribute == "weight": assert old_model.weight.shape == model.weight.shape, "Shapes have to match!" _A: Tuple = old_model.weight logger.info(f"""{attribute} is initialized.""" ) _A: str = True break elif attribute == "bias": assert old_model.bias.shape == model.bias.shape, "Shapes have to match!" _A: Optional[int] = old_model.bias logger.info(f"""{attribute} is initialized""" ) _A: List[str] = True break elif attribute in special_keys and hasattr(a , '''in_proj_weight''' ): _A: int = old_model.in_proj_weight.shape[0] // 3 _A: Optional[int] = getattr(a , a ) param.weight.shape == old_model.in_proj_weight[:embed_dim, :].shape, "Shapes have to match" param.bias.shape == old_model.in_proj_bias[:embed_dim].shape, "Shapes have to match" if attribute == "query_proj": _A: Tuple = nn.Parameter(old_model.in_proj_weight[:embed_dim, :] ) _A: Tuple = nn.Parameter(old_model.in_proj_bias[:embed_dim] ) elif attribute == "key_proj": _A: Union[str, Any] = nn.Parameter(old_model.in_proj_weight[embed_dim : 2 * embed_dim, :] ) _A: Optional[int] = nn.Parameter(old_model.in_proj_bias[embed_dim : 2 * embed_dim] ) elif attribute == "value_proj": _A: Optional[int] = nn.Parameter(old_model.in_proj_weight[2 * embed_dim :, :] ) _A: Union[str, Any] = nn.Parameter(old_model.in_proj_bias[2 * embed_dim :] ) _A: List[Any] = True break elif attribute == "position_embeddings": assert ( model.position_embeddings.weight.shape[-1] == old_model.embed_positions.weight.shape[-1] ), "Hidden size has to match" assert model.position_embeddings.weight.shape[0] == 5_12, "We want 512 position_embeddings." _A: Optional[int] = nn.Parameter(old_model.embed_positions.weight[:5_12, :] ) _A: int = True break if attribute.isdigit(): _A: Optional[Any] = model[int(a )] _A: str = old_model[int(a )] else: _A: Tuple = getattr(a , a ) if old_attribute == "": _A: str = old_model else: if not hasattr(a , a ): raise ValueError(f"""{old_model} does not have {old_attribute}""" ) _A: str = getattr(a , a ) if not is_key_init: raise ValueError(f"""{key} was not correctly initialized!""" ) print(f"""Saving model to {pytorch_dump_folder_path}""" ) prophet.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase__ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--prophetnet_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) UpperCAmelCase__ : Dict = parser.parse_args() convert_prophetnet_checkpoint_to_pytorch(args.prophetnet_checkpoint_path, args.pytorch_dump_folder_path)
301
import math import random from typing import Any from .hill_climbing import SearchProblem def lowerCamelCase__ ( a , a = True , a = math.inf , a = -math.inf , a = math.inf , a = -math.inf , a = False , a = 1_00 , a = 0.01 , a = 1 , ) -> Any: _A: Optional[Any] = False _A: Dict = search_prob _A: str = start_temperate _A: Optional[int] = [] _A: int = 0 _A: Dict = None while not search_end: _A: Dict = current_state.score() if best_state is None or current_score > best_state.score(): _A: List[Any] = current_state scores.append(a ) iterations += 1 _A: List[str] = None _A: str = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to _A: Any = random.randint(0 , len(a ) - 1 ) # picking a random neighbor _A: Union[str, Any] = neighbors.pop(a ) _A: List[str] = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: _A: Optional[Any] = change * -1 # in case we are finding minimum if change > 0: # improves the solution _A: str = picked_neighbor else: _A: Tuple = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability _A: Optional[int] = picked_neighbor _A: Dict = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor _A: Any = True else: _A: List[Any] = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(a ) , a ) plt.xlabel('''Iterations''' ) plt.ylabel('''Function values''' ) plt.show() return best_state if __name__ == "__main__": def lowerCamelCase__ ( a , a ) -> Optional[Any]: return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) UpperCAmelCase__ : Optional[int] = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) UpperCAmelCase__ : Optional[Any] = simulated_annealing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( 'The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) # starting the problem with initial coordinates (12, 47) UpperCAmelCase__ : Optional[Any] = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) UpperCAmelCase__ : List[str] = simulated_annealing( prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( 'The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) def lowerCamelCase__ ( a , a ) -> Optional[Any]: return (3 * x**2) - (6 * y) UpperCAmelCase__ : Union[str, Any] = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) UpperCAmelCase__ : List[str] = simulated_annealing(prob, find_max=False, visualization=True) print( 'The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ' F"""{local_min.score()}""" ) UpperCAmelCase__ : Optional[Any] = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) UpperCAmelCase__ : List[Any] = simulated_annealing(prob, find_max=True, visualization=True) print( 'The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ' F"""{local_min.score()}""" )
301
1
import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets UpperCAmelCase__ : int = '\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n' UpperCAmelCase__ : Any = '\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n' UpperCAmelCase__ : int = '\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default \'gpt2-large\' Use one of [\'gpt2\', \'gpt2-medium\', \'gpt2-large\', \'gpt2-xl\'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: "c" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric(\'mauve\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase ( datasets.Metric ): '''simple docstring''' def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/krishnap25/mauve''' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , codebase_urls=['''https://github.com/krishnap25/mauve'''] , reference_urls=[ '''https://arxiv.org/abs/2102.01454''', '''https://github.com/krishnap25/mauve''', ] , ) def __magic_name__ ( self : Optional[Any] , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Any=None , lowerCAmelCase_ : List[str]=None , lowerCAmelCase_ : Tuple=None , lowerCAmelCase_ : str=None , lowerCAmelCase_ : str="auto" , lowerCAmelCase_ : Optional[Any]=-1 , lowerCAmelCase_ : int=0.9 , lowerCAmelCase_ : int=5 , lowerCAmelCase_ : Any=5_0_0 , lowerCAmelCase_ : Union[str, Any]="gpt2-large" , lowerCAmelCase_ : List[Any]=-1 , lowerCAmelCase_ : Tuple=1_0_2_4 , lowerCAmelCase_ : Optional[int]=2_5 , lowerCAmelCase_ : List[Any]=5 , lowerCAmelCase_ : Any=True , lowerCAmelCase_ : Union[str, Any]=2_5 , ): """simple docstring""" _A: str = compute_mauve( p_text=lowerCAmelCase_ , q_text=lowerCAmelCase_ , p_features=lowerCAmelCase_ , q_features=lowerCAmelCase_ , p_tokens=lowerCAmelCase_ , q_tokens=lowerCAmelCase_ , num_buckets=lowerCAmelCase_ , pca_max_data=lowerCAmelCase_ , kmeans_explained_var=lowerCAmelCase_ , kmeans_num_redo=lowerCAmelCase_ , kmeans_max_iter=lowerCAmelCase_ , featurize_model_name=lowerCAmelCase_ , device_id=lowerCAmelCase_ , max_text_length=lowerCAmelCase_ , divergence_curve_discretization_size=lowerCAmelCase_ , mauve_scaling_factor=lowerCAmelCase_ , verbose=lowerCAmelCase_ , seed=lowerCAmelCase_ , ) return out
301
import json import os from typing import Dict, List, Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase__ : List[Any] = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } UpperCAmelCase__ : Tuple = { '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__ : Optional[int] = {'facebook/blenderbot_small-90M': 512} def lowerCamelCase__ ( a ) -> Optional[Any]: _A: List[Any] = set() _A: List[Any] = word[0] for char in word[1:]: pairs.add((prev_char, char) ) _A: List[Any] = char _A: Union[str, Any] = set(a ) return pairs class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : str = VOCAB_FILES_NAMES __UpperCamelCase : List[Any] = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase : Union[str, Any] = ['''input_ids''', '''attention_mask'''] def __init__( self : int , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : List[str]="__start__" , lowerCAmelCase_ : Any="__end__" , lowerCAmelCase_ : Any="__unk__" , lowerCAmelCase_ : Any="__null__" , **lowerCAmelCase_ : int , ): """simple docstring""" super().__init__(unk_token=lowerCAmelCase_ , bos_token=lowerCAmelCase_ , eos_token=lowerCAmelCase_ , pad_token=lowerCAmelCase_ , **lowerCAmelCase_ ) with open(lowerCAmelCase_ , encoding='''utf-8''' ) as vocab_handle: _A: Optional[int] = json.load(lowerCAmelCase_ ) _A: int = {v: k for k, v in self.encoder.items()} with open(lowerCAmelCase_ , encoding='''utf-8''' ) as merges_handle: _A: Dict = merges_handle.read().split('''\n''' )[1:-1] _A: int = [tuple(merge.split() ) for merge in merges] _A: Dict = dict(zip(lowerCAmelCase_ , range(len(lowerCAmelCase_ ) ) ) ) _A: Union[str, Any] = {} @property def __magic_name__ ( self : Optional[int] ): """simple docstring""" return len(self.encoder ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def __magic_name__ ( self : str , lowerCAmelCase_ : str ): """simple docstring""" if token in self.cache: return self.cache[token] _A: List[Any] = re.sub('''([.,!?()])''' , R''' \1''' , lowerCAmelCase_ ) _A: List[Any] = re.sub('''(\')''' , R''' \1 ''' , lowerCAmelCase_ ) _A: List[Any] = re.sub(R'''\s{2,}''' , ''' ''' , lowerCAmelCase_ ) if "\n" in token: _A: Dict = token.replace('''\n''' , ''' __newln__''' ) _A: Any = token.split(''' ''' ) _A: Optional[Any] = [] for token in tokens: if not len(lowerCAmelCase_ ): continue _A: str = token.lower() _A: List[str] = tuple(lowerCAmelCase_ ) _A: str = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] ) _A: Dict = get_pairs(lowerCAmelCase_ ) if not pairs: words.append(lowerCAmelCase_ ) continue while True: _A: str = min(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : self.bpe_ranks.get(lowerCAmelCase_ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break _A , _A: Optional[int] = bigram _A: str = [] _A: Dict = 0 while i < len(lowerCAmelCase_ ): try: _A: List[Any] = word.index(lowerCAmelCase_ , lowerCAmelCase_ ) new_word.extend(word[i:j] ) _A: Optional[int] = j except ValueError: new_word.extend(word[i:] ) break if word[i] == first and i < len(lowerCAmelCase_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 _A: Union[str, Any] = tuple(lowerCAmelCase_ ) _A: Tuple = new_word if len(lowerCAmelCase_ ) == 1: break else: _A: Optional[int] = get_pairs(lowerCAmelCase_ ) _A: str = '''@@ '''.join(lowerCAmelCase_ ) _A: Tuple = word[:-4] _A: List[Any] = word words.append(lowerCAmelCase_ ) return " ".join(lowerCAmelCase_ ) def __magic_name__ ( self : str , lowerCAmelCase_ : str ): """simple docstring""" _A: List[Any] = [] _A: List[Any] = re.findall(R'''\S+\n?''' , lowerCAmelCase_ ) for token in words: split_tokens.extend(list(self.bpe(lowerCAmelCase_ ).split(''' ''' ) ) ) return split_tokens def __magic_name__ ( self : str , lowerCAmelCase_ : str ): """simple docstring""" _A: List[str] = token.lower() return self.encoder.get(lowerCAmelCase_ , self.encoder.get(self.unk_token ) ) def __magic_name__ ( self : int , lowerCAmelCase_ : int ): """simple docstring""" return self.decoder.get(lowerCAmelCase_ , self.unk_token ) def __magic_name__ ( self : List[str] , lowerCAmelCase_ : List[str] ): """simple docstring""" _A: List[str] = ''' '''.join(lowerCAmelCase_ ).replace('''@@ ''' , '''''' ).strip() return out_string def __magic_name__ ( self : List[Any] , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[str] = None ): """simple docstring""" if not os.path.isdir(lowerCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _A: Dict = os.path.join( lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) _A: Any = os.path.join( lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(lowerCAmelCase_ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=lowerCAmelCase_ , ensure_ascii=lowerCAmelCase_ ) + '''\n''' ) _A: List[str] = 0 with open(lowerCAmelCase_ , '''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 lowerCAmelCase_ : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" ''' Please check that the tokenizer is not corrupted!''' ) _A: Optional[int] = token_index writer.write(''' '''.join(lowerCAmelCase_ ) + '''\n''' ) index += 1 return vocab_file, merge_file
301
1
def lowerCamelCase__ ( a = 10 ) -> str: if not isinstance(a , a ) or n < 0: raise ValueError('''Invalid input''' ) _A: int = 10**n _A: List[Any] = 2_84_33 * (pow(2 , 7_83_04_57 , a )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(F"""{solution(10) = }""")
301
import os from pathlib import Path def lowerCamelCase__ ( ) -> Optional[Any]: from torch.utils.cpp_extension import load _A: str = Path(a ).resolve().parent.parent.parent / '''kernels''' / '''deformable_detr''' _A: Tuple = [ root / filename for filename in [ '''vision.cpp''', os.path.join('''cpu''' , '''ms_deform_attn_cpu.cpp''' ), os.path.join('''cuda''' , '''ms_deform_attn_cuda.cu''' ), ] ] load( '''MultiScaleDeformableAttention''' , a , with_cuda=a , extra_include_paths=[str(a )] , extra_cflags=['''-DWITH_CUDA=1'''] , extra_cuda_cflags=[ '''-DCUDA_HAS_FP16=1''', '''-D__CUDA_NO_HALF_OPERATORS__''', '''-D__CUDA_NO_HALF_CONVERSIONS__''', '''-D__CUDA_NO_HALF2_OPERATORS__''', ] , ) import MultiScaleDeformableAttention as MSDA return MSDA
301
1
def lowerCamelCase__ ( a , a ) -> int: return int((input_a, input_a).count(0 ) == 0 ) def lowerCamelCase__ ( ) -> None: assert and_gate(0 , 0 ) == 0 assert and_gate(0 , 1 ) == 0 assert and_gate(1 , 0 ) == 0 assert and_gate(1 , 1 ) == 1 if __name__ == "__main__": test_and_gate() print(and_gate(1, 0)) print(and_gate(0, 0)) print(and_gate(0, 1)) print(and_gate(1, 1))
301
from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Optional[int] = ['''image_processor''', '''tokenizer'''] __UpperCamelCase : Optional[Any] = '''BlipImageProcessor''' __UpperCamelCase : int = ('''BertTokenizer''', '''BertTokenizerFast''') def __init__( self : Optional[int] , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" _A: Optional[Any] = False super().__init__(lowerCAmelCase_ , lowerCAmelCase_ ) _A: List[Any] = self.image_processor def __call__( self : Optional[Any] , lowerCAmelCase_ : ImageInput = None , lowerCAmelCase_ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , lowerCAmelCase_ : bool = True , lowerCAmelCase_ : Union[bool, str, PaddingStrategy] = False , lowerCAmelCase_ : Union[bool, str, TruncationStrategy] = None , lowerCAmelCase_ : Optional[int] = None , lowerCAmelCase_ : int = 0 , lowerCAmelCase_ : Optional[int] = None , lowerCAmelCase_ : Optional[bool] = None , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = True , lowerCAmelCase_ : Optional[Union[str, TensorType]] = None , **lowerCAmelCase_ : Union[str, Any] , ): """simple docstring""" if images is None and text is None: raise ValueError('''You have to specify either images or text.''' ) # Get only text if images is None: _A: Tuple = self.tokenizer _A: Optional[int] = self.tokenizer( text=lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ , padding=lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ , stride=lowerCAmelCase_ , pad_to_multiple_of=lowerCAmelCase_ , return_attention_mask=lowerCAmelCase_ , return_overflowing_tokens=lowerCAmelCase_ , return_special_tokens_mask=lowerCAmelCase_ , return_offsets_mapping=lowerCAmelCase_ , return_token_type_ids=lowerCAmelCase_ , return_length=lowerCAmelCase_ , verbose=lowerCAmelCase_ , return_tensors=lowerCAmelCase_ , **lowerCAmelCase_ , ) return text_encoding # add pixel_values _A: List[Any] = self.image_processor(lowerCAmelCase_ , return_tensors=lowerCAmelCase_ ) if text is not None: _A: Tuple = self.tokenizer( text=lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ , padding=lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ , stride=lowerCAmelCase_ , pad_to_multiple_of=lowerCAmelCase_ , return_attention_mask=lowerCAmelCase_ , return_overflowing_tokens=lowerCAmelCase_ , return_special_tokens_mask=lowerCAmelCase_ , return_offsets_mapping=lowerCAmelCase_ , return_token_type_ids=lowerCAmelCase_ , return_length=lowerCAmelCase_ , verbose=lowerCAmelCase_ , return_tensors=lowerCAmelCase_ , **lowerCAmelCase_ , ) else: _A: str = None if text_encoding is not None: encoding_image_processor.update(lowerCAmelCase_ ) return encoding_image_processor def __magic_name__ ( self : Optional[Any] , *lowerCAmelCase_ : Union[str, Any] , **lowerCAmelCase_ : Tuple ): """simple docstring""" return self.tokenizer.batch_decode(*lowerCAmelCase_ , **lowerCAmelCase_ ) def __magic_name__ ( self : Union[str, Any] , *lowerCAmelCase_ : int , **lowerCAmelCase_ : Optional[int] ): """simple docstring""" return self.tokenizer.decode(*lowerCAmelCase_ , **lowerCAmelCase_ ) @property def __magic_name__ ( self : Dict ): """simple docstring""" _A: Dict = self.tokenizer.model_input_names _A: List[str] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
301
1
def lowerCamelCase__ ( a = 1_00_00_00 ) -> int: _A: Any = 1 _A: Dict = 1 _A: List[str] = {1: 1} for inputa in range(2 , a ): _A: Any = 0 _A: Any = inputa while True: if number in counters: counter += counters[number] break if number % 2 == 0: number //= 2 counter += 1 else: _A: int = (3 * number) + 1 counter += 1 if inputa not in counters: _A: Union[str, Any] = counter if counter > pre_counter: _A: Dict = inputa _A: Optional[Any] = counter return largest_number if __name__ == "__main__": print(solution(int(input().strip())))
301
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : Union[str, Any] = { 'google/mobilenet_v1_1.0_224': 'https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json', 'google/mobilenet_v1_0.75_192': 'https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 } class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Optional[int] = '''mobilenet_v1''' def __init__( self : Optional[int] , lowerCAmelCase_ : Any=3 , lowerCAmelCase_ : str=2_2_4 , lowerCAmelCase_ : List[str]=1.0 , lowerCAmelCase_ : Any=8 , lowerCAmelCase_ : Tuple="relu6" , lowerCAmelCase_ : List[Any]=True , lowerCAmelCase_ : Optional[int]=0.999 , lowerCAmelCase_ : List[str]=0.02 , lowerCAmelCase_ : List[Any]=0.001 , **lowerCAmelCase_ : Optional[Any] , ): """simple docstring""" super().__init__(**lowerCAmelCase_ ) if depth_multiplier <= 0: raise ValueError('''depth_multiplier must be greater than zero.''' ) _A: Any = num_channels _A: Optional[int] = image_size _A: Optional[Any] = depth_multiplier _A: Tuple = min_depth _A: Any = hidden_act _A: Dict = tf_padding _A: List[Any] = classifier_dropout_prob _A: Tuple = initializer_range _A: Tuple = layer_norm_eps class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Dict = version.parse('''1.11''' ) @property def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" return OrderedDict([('''pixel_values''', {0: '''batch'''})] ) @property def __magic_name__ ( self : Optional[Any] ): """simple docstring""" if self.task == "image-classification": return OrderedDict([('''logits''', {0: '''batch'''})] ) else: return OrderedDict([('''last_hidden_state''', {0: '''batch'''}), ('''pooler_output''', {0: '''batch'''})] ) @property def __magic_name__ ( self : Dict ): """simple docstring""" return 1e-4
301
1
from __future__ import annotations class UpperCAmelCase : '''simple docstring''' def __init__( self : Optional[Any] , lowerCAmelCase_ : int ): """simple docstring""" _A: List[str] = order # a_{0} ... a_{k} _A: Any = [1.0] + [0.0] * order # b_{0} ... b_{k} _A: Dict = [1.0] + [0.0] * order # x[n-1] ... x[n-k] _A: Optional[Any] = [0.0] * self.order # y[n-1] ... y[n-k] _A: Union[str, Any] = [0.0] * self.order def __magic_name__ ( self : List[Any] , lowerCAmelCase_ : list[float] , lowerCAmelCase_ : list[float] ): """simple docstring""" if len(lowerCAmelCase_ ) < self.order: _A: Any = [1.0, *a_coeffs] if len(lowerCAmelCase_ ) != self.order + 1: _A: Union[str, Any] = ( F"""Expected a_coeffs to have {self.order + 1} elements """ F"""for {self.order}-order filter, got {len(lowerCAmelCase_ )}""" ) raise ValueError(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) != self.order + 1: _A: Tuple = ( F"""Expected b_coeffs to have {self.order + 1} elements """ F"""for {self.order}-order filter, got {len(lowerCAmelCase_ )}""" ) raise ValueError(lowerCAmelCase_ ) _A: Dict = a_coeffs _A: Optional[Any] = b_coeffs def __magic_name__ ( self : Any , lowerCAmelCase_ : float ): """simple docstring""" _A: Dict = 0.0 # Start at index 1 and do index 0 at the end. for i in range(1 , self.order + 1 ): result += ( self.b_coeffs[i] * self.input_history[i - 1] - self.a_coeffs[i] * self.output_history[i - 1] ) _A: Any = (result + self.b_coeffs[0] * sample) / self.a_coeffs[0] _A: Tuple = self.input_history[:-1] _A: Optional[int] = self.output_history[:-1] _A: List[str] = sample _A: Optional[Any] = result return result
301
import argparse import json import os from tensorflow.core.protobuf.saved_model_pba import SavedModel # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py UpperCAmelCase__ : Any = '.' # Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model) UpperCAmelCase__ : Optional[Any] = [ 'Assert', 'AssignVariableOp', 'EmptyTensorList', 'MergeV2Checkpoints', 'ReadVariableOp', 'ResourceGather', 'RestoreV2', 'SaveV2', 'ShardedFilename', 'StatefulPartitionedCall', 'StaticRegexFullMatch', 'VarHandleOp', ] def lowerCamelCase__ ( a , a , a ) -> Union[str, Any]: _A: Optional[int] = SavedModel() _A: int = [] with open(os.path.join(a , '''utils''' , '''tf_ops''' , '''onnx.json''' ) ) as f: _A: List[Any] = json.load(a )['''opsets'''] for i in range(1 , opset + 1 ): onnx_ops.extend(onnx_opsets[str(a )] ) with open(a , '''rb''' ) as f: saved_model.ParseFromString(f.read() ) _A: Optional[Any] = set() # Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs) for meta_graph in saved_model.meta_graphs: # Add operations in the graph definition model_op_names.update(node.op for node in meta_graph.graph_def.node ) # Go through the functions in the graph definition for func in meta_graph.graph_def.library.function: # Add operations in each function model_op_names.update(node.op for node in func.node_def ) # Convert to list, sorted if you want _A: Optional[int] = sorted(a ) _A: Tuple = [] for op in model_op_names: if op not in onnx_ops and op not in INTERNAL_OPS: incompatible_ops.append(a ) if strict and len(a ) > 0: raise Exception(f"""Found the following incompatible ops for the opset {opset}:\n""" + incompatible_ops ) elif len(a ) > 0: print(f"""Found the following incompatible ops for the opset {opset}:""" ) print(*a , sep='''\n''' ) else: print(f"""The saved model {saved_model_path} can properly be converted with ONNX.""" ) if __name__ == "__main__": UpperCAmelCase__ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument('--saved_model_path', help='Path of the saved model to check (the .pb file).') parser.add_argument( '--opset', default=12, type=int, help='The ONNX opset against which the model has to be tested.' ) parser.add_argument( '--framework', choices=['onnx'], default='onnx', help='Frameworks against which to test the saved model.' ) parser.add_argument( '--strict', action='store_true', help='Whether make the checking strict (raise errors) or not (raise warnings)' ) UpperCAmelCase__ : int = parser.parse_args() if args.framework == "onnx": onnx_compliancy(args.saved_model_path, args.strict, args.opset)
301
1
from __future__ import annotations from cmath import sqrt def lowerCamelCase__ ( a , a , a ) -> tuple[complex, complex]: if a == 0: raise ValueError('''Coefficient \'a\' must not be zero.''' ) _A: int = b * b - 4 * a * c _A: Optional[int] = (-b + sqrt(a )) / (2 * a) _A: int = (-b - sqrt(a )) / (2 * a) return ( root_a.real if not root_a.imag else root_a, root_a.real if not root_a.imag else root_a, ) def lowerCamelCase__ ( ) -> Union[str, Any]: _A , _A: Tuple = quadratic_roots(a=5 , b=6 , c=1 ) print(f"""The solutions are: {solutiona} and {solutiona}""" ) if __name__ == "__main__": main()
301
import json import os from typing import Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ : int = logging.get_logger(__name__) UpperCAmelCase__ : Union[str, Any] = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', } UpperCAmelCase__ : str = { '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__ : Dict = { 'ctrl': 256, } UpperCAmelCase__ : Any = { 'Pregnancy': 168629, 'Christianity': 7675, 'Explain': 106423, 'Fitness': 63440, 'Saving': 63163, 'Ask': 27171, 'Ass': 95985, 'Joke': 163509, 'Questions': 45622, 'Thoughts': 49605, 'Retail': 52342, 'Feminism': 164338, 'Writing': 11992, 'Atheism': 192263, 'Netflix': 48616, 'Computing': 39639, 'Opinion': 43213, 'Alone': 44967, 'Funny': 58917, 'Gaming': 40358, 'Human': 4088, 'India': 1331, 'Joker': 77138, 'Diet': 36206, 'Legal': 11859, 'Norman': 4939, 'Tip': 72689, 'Weight': 52343, 'Movies': 46273, 'Running': 23425, 'Science': 2090, 'Horror': 37793, 'Confession': 60572, 'Finance': 12250, 'Politics': 16360, 'Scary': 191985, 'Support': 12654, 'Technologies': 32516, 'Teenage': 66160, 'Event': 32769, 'Learned': 67460, 'Notion': 182770, 'Wikipedia': 37583, 'Books': 6665, 'Extract': 76050, 'Confessions': 102701, 'Conspiracy': 75932, 'Links': 63674, 'Narcissus': 150425, 'Relationship': 54766, 'Relationships': 134796, 'Reviews': 41671, 'News': 4256, 'Translation': 26820, 'multilingual': 128406, } def lowerCamelCase__ ( a ) -> Optional[Any]: _A: Optional[int] = set() _A: Dict = word[0] for char in word[1:]: pairs.add((prev_char, char) ) _A: Any = char _A: Dict = set(a ) return pairs class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Any = VOCAB_FILES_NAMES __UpperCamelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase : Optional[int] = CONTROL_CODES def __init__( self : Dict , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[Any]="<unk>" , **lowerCAmelCase_ : Optional[int] ): """simple docstring""" super().__init__(unk_token=lowerCAmelCase_ , **lowerCAmelCase_ ) with open(lowerCAmelCase_ , encoding='''utf-8''' ) as vocab_handle: _A: str = json.load(lowerCAmelCase_ ) _A: List[Any] = {v: k for k, v in self.encoder.items()} with open(lowerCAmelCase_ , encoding='''utf-8''' ) as merges_handle: _A: int = merges_handle.read().split('''\n''' )[1:-1] _A: List[Any] = [tuple(merge.split() ) for merge in merges] _A: List[str] = dict(zip(lowerCAmelCase_ , range(len(lowerCAmelCase_ ) ) ) ) _A: Union[str, Any] = {} @property def __magic_name__ ( self : Any ): """simple docstring""" return len(self.encoder ) def __magic_name__ ( self : Dict ): """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def __magic_name__ ( self : List[str] , lowerCAmelCase_ : Tuple ): """simple docstring""" if token in self.cache: return self.cache[token] _A: List[Any] = tuple(lowerCAmelCase_ ) _A: Optional[Any] = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] ) _A: Optional[int] = get_pairs(lowerCAmelCase_ ) if not pairs: return token while True: _A: Optional[int] = min(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : self.bpe_ranks.get(lowerCAmelCase_ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break _A , _A: Any = bigram _A: int = [] _A: int = 0 while i < len(lowerCAmelCase_ ): try: _A: Any = word.index(lowerCAmelCase_ , lowerCAmelCase_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) _A: Optional[int] = j if word[i] == first and i < len(lowerCAmelCase_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 _A: Dict = tuple(lowerCAmelCase_ ) _A: Union[str, Any] = new_word if len(lowerCAmelCase_ ) == 1: break else: _A: Tuple = get_pairs(lowerCAmelCase_ ) _A: Optional[int] = '''@@ '''.join(lowerCAmelCase_ ) _A: List[str] = word[:-4] _A: Optional[Any] = word return word def __magic_name__ ( self : Optional[Any] , lowerCAmelCase_ : Union[str, Any] ): """simple docstring""" _A: List[Any] = [] _A: List[str] = re.findall(R'''\S+\n?''' , lowerCAmelCase_ ) for token in words: split_tokens.extend(list(self.bpe(lowerCAmelCase_ ).split(''' ''' ) ) ) return split_tokens def __magic_name__ ( self : Dict , lowerCAmelCase_ : Optional[int] ): """simple docstring""" return self.encoder.get(lowerCAmelCase_ , self.encoder.get(self.unk_token ) ) def __magic_name__ ( self : Dict , lowerCAmelCase_ : Tuple ): """simple docstring""" return self.decoder.get(lowerCAmelCase_ , self.unk_token ) def __magic_name__ ( self : Any , lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Any = ''' '''.join(lowerCAmelCase_ ).replace('''@@ ''' , '''''' ).strip() return out_string def __magic_name__ ( self : List[str] , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[str] = None ): """simple docstring""" if not os.path.isdir(lowerCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _A: List[str] = os.path.join( lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) _A: List[Any] = os.path.join( lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(lowerCAmelCase_ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=lowerCAmelCase_ , ensure_ascii=lowerCAmelCase_ ) + '''\n''' ) _A: str = 0 with open(lowerCAmelCase_ , '''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 lowerCAmelCase_ : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" ''' Please check that the tokenizer is not corrupted!''' ) _A: Tuple = token_index writer.write(''' '''.join(lowerCAmelCase_ ) + '''\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)
301
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) UpperCAmelCase__ : str = { 'configuration_speecht5': [ 'SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP', 'SpeechT5Config', 'SpeechT5HifiGanConfig', ], 'feature_extraction_speecht5': ['SpeechT5FeatureExtractor'], 'processing_speecht5': ['SpeechT5Processor'], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : str = ['SpeechT5Tokenizer'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Any = [ 'SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST', 'SpeechT5ForSpeechToText', 'SpeechT5ForSpeechToSpeech', 'SpeechT5ForTextToSpeech', 'SpeechT5Model', 'SpeechT5PreTrainedModel', 'SpeechT5HifiGan', ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys UpperCAmelCase__ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
301
def lowerCamelCase__ ( a = 10 ) -> str: if not isinstance(a , a ) or n < 0: raise ValueError('''Invalid input''' ) _A: int = 10**n _A: List[Any] = 2_84_33 * (pow(2 , 7_83_04_57 , a )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(F"""{solution(10) = }""")
301
1
UpperCAmelCase__ : Union[str, Any] = [ [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], ] def lowerCamelCase__ ( a , a , a , a ) -> str: # Return True if there is node that has not iterated. _A: Union[str, Any] = [False] * len(a ) _A: List[str] = [s] _A: Optional[Any] = True while queue: _A: Dict = queue.pop(0 ) for ind in range(len(graph[u] ) ): if visited[ind] is False and graph[u][ind] > 0: queue.append(a ) _A: Any = True _A: str = u return visited[t] def lowerCamelCase__ ( a , a , a ) -> Optional[int]: _A: Optional[Any] = [-1] * (len(a )) _A: int = 0 _A: Tuple = [] _A: Tuple = [i[:] for i in graph] # Record original cut, copy. while bfs(a , a , a , a ): _A: Tuple = float('''Inf''' ) _A: List[str] = sink while s != source: # Find the minimum value in select path _A: Dict = min(a , graph[parent[s]][s] ) _A: List[Any] = parent[s] max_flow += path_flow _A: Union[str, Any] = sink while v != source: _A: Optional[Any] = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow _A: List[Any] = parent[v] for i in range(len(a ) ): for j in range(len(graph[0] ) ): if graph[i][j] == 0 and temp[i][j] > 0: res.append((i, j) ) return res if __name__ == "__main__": print(mincut(test_graph, source=0, sink=5))
301
from __future__ import annotations import unittest from transformers import AutoTokenizer, MBartConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel @require_tf class UpperCAmelCase : '''simple docstring''' __UpperCamelCase : Any = MBartConfig __UpperCamelCase : Tuple = {} __UpperCamelCase : Dict = '''gelu''' def __init__( self : Dict , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : List[Any]=1_3 , lowerCAmelCase_ : Dict=7 , lowerCAmelCase_ : Optional[Any]=True , lowerCAmelCase_ : Optional[Any]=False , lowerCAmelCase_ : Union[str, Any]=9_9 , lowerCAmelCase_ : Dict=3_2 , lowerCAmelCase_ : str=2 , lowerCAmelCase_ : int=4 , lowerCAmelCase_ : Union[str, Any]=3_7 , lowerCAmelCase_ : Dict=0.1 , lowerCAmelCase_ : str=0.1 , lowerCAmelCase_ : List[str]=2_0 , lowerCAmelCase_ : str=2 , lowerCAmelCase_ : Optional[int]=1 , lowerCAmelCase_ : List[Any]=0 , ): """simple docstring""" _A: Union[str, Any] = parent _A: List[Any] = batch_size _A: Dict = seq_length _A: Dict = is_training _A: str = use_labels _A: int = vocab_size _A: str = hidden_size _A: Tuple = num_hidden_layers _A: Optional[Any] = num_attention_heads _A: Tuple = intermediate_size _A: int = hidden_dropout_prob _A: Tuple = attention_probs_dropout_prob _A: Tuple = max_position_embeddings _A: Dict = eos_token_id _A: int = pad_token_id _A: Any = bos_token_id def __magic_name__ ( self : Dict ): """simple docstring""" _A: Optional[int] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _A: Dict = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _A: List[Any] = tf.concat([input_ids, eos_tensor] , axis=1 ) _A: Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _A: int = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) _A: Any = prepare_mbart_inputs_dict(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return config, inputs_dict def __magic_name__ ( self : Union[str, Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : List[str] ): """simple docstring""" _A: Tuple = TFMBartModel(config=lowerCAmelCase_ ).get_decoder() _A: List[str] = inputs_dict['''input_ids'''] _A: Tuple = input_ids[:1, :] _A: List[Any] = inputs_dict['''attention_mask'''][:1, :] _A: str = inputs_dict['''head_mask'''] _A: Optional[Any] = 1 # first forward pass _A: Any = model(lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , head_mask=lowerCAmelCase_ , use_cache=lowerCAmelCase_ ) _A , _A: List[str] = outputs.to_tuple() _A: Dict = past_key_values[1] def lowerCamelCase__ ( a , a , a , a=None , a=None , a=None , a=None , a=None , ) -> Tuple: if attention_mask is None: _A: Union[str, Any] = tf.cast(tf.math.not_equal(a , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: _A: Optional[int] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: _A: Tuple = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _A: Union[str, Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: _A: Optional[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Union[str, Any] = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else () __UpperCamelCase : int = (TFMBartForConditionalGeneration,) if is_tf_available() else () __UpperCamelCase : Tuple = ( { '''conversational''': TFMBartForConditionalGeneration, '''feature-extraction''': TFMBartModel, '''summarization''': TFMBartForConditionalGeneration, '''text2text-generation''': TFMBartForConditionalGeneration, '''translation''': TFMBartForConditionalGeneration, } if is_tf_available() else {} ) __UpperCamelCase : List[Any] = True __UpperCamelCase : int = False __UpperCamelCase : Optional[Any] = False def __magic_name__ ( self : int , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : int , lowerCAmelCase_ : str , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : int ): """simple docstring""" if pipeline_test_casse_name != "FeatureExtractionPipelineTests": # Exception encountered when calling layer '...' return True return False def __magic_name__ ( self : Any ): """simple docstring""" _A: Dict = TFMBartModelTester(self ) _A: Tuple = ConfigTester(self , config_class=lowerCAmelCase_ ) def __magic_name__ ( self : List[str] ): """simple docstring""" self.config_tester.run_common_tests() def __magic_name__ ( self : Optional[Any] ): """simple docstring""" _A: str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*lowerCAmelCase_ ) @require_sentencepiece @require_tokenizers @require_tf class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Optional[int] = [ ''' UN Chief Says There Is No Military Solution in Syria''', ] __UpperCamelCase : List[str] = [ '''Şeful ONU declară că nu există o soluţie militară în Siria''', ] __UpperCamelCase : Union[str, Any] = '''facebook/mbart-large-en-ro''' @cached_property def __magic_name__ ( self : Tuple ): """simple docstring""" return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def __magic_name__ ( self : str ): """simple docstring""" _A: Union[str, Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def __magic_name__ ( self : Union[str, Any] , **lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Optional[Any] = self.translate_src_text(**lowerCAmelCase_ ) self.assertListEqual(self.expected_text , lowerCAmelCase_ ) def __magic_name__ ( self : Dict , **lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Any = self.tokenizer(self.src_text , **lowerCAmelCase_ , return_tensors='''tf''' ) _A: Any = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 ) _A: Optional[Any] = self.tokenizer.batch_decode(lowerCAmelCase_ , skip_special_tokens=lowerCAmelCase_ ) return generated_words @slow def __magic_name__ ( self : List[str] ): """simple docstring""" self._assert_generated_batch_equal_expected()
301
1
from math import isclose, sqrt def lowerCamelCase__ ( a , a , a ) -> tuple[float, float, float]: _A: List[str] = point_y / 4 / point_x _A: str = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) _A: Any = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) _A: Dict = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 _A: Tuple = outgoing_gradient**2 + 4 _A: Any = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) _A: Union[str, Any] = (point_y - outgoing_gradient * point_x) ** 2 - 1_00 _A: List[str] = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) _A: Optional[int] = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point _A: Union[str, Any] = x_minus if isclose(a , a ) else x_plus _A: Union[str, Any] = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def lowerCamelCase__ ( a = 1.4 , a = -9.6 ) -> int: _A: int = 0 _A: float = first_x_coord _A: float = first_y_coord _A: float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): _A , _A , _A: List[str] = next_point(a , a , a ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F"""{solution() = }""")
301
from typing import TYPE_CHECKING from ..utils import _LazyModule UpperCAmelCase__ : Tuple = { 'config': [ 'EXTERNAL_DATA_FORMAT_SIZE_LIMIT', 'OnnxConfig', 'OnnxConfigWithPast', 'OnnxSeq2SeqConfigWithPast', 'PatchingSpec', ], 'convert': ['export', 'validate_model_outputs'], 'features': ['FeaturesManager'], 'utils': ['ParameterFormat', 'compute_serialized_parameters_size'], } if TYPE_CHECKING: from .config import ( EXTERNAL_DATA_FORMAT_SIZE_LIMIT, OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast, PatchingSpec, ) from .convert import export, validate_model_outputs from .features import FeaturesManager from .utils import ParameterFormat, compute_serialized_parameters_size else: import sys UpperCAmelCase__ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
301
1
def lowerCamelCase__ ( a ) -> list: if n_term == "": return [] _A: list = [] for temp in range(int(a ) ): series.append(f"""1/{temp + 1}""" if series else '''1''' ) return series if __name__ == "__main__": UpperCAmelCase__ : Union[str, Any] = input('Enter the last number (nth term) of the Harmonic Series') print('Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n') print(harmonic_series(nth_term))
301
import torch from diffusers import DDPMParallelScheduler from .test_schedulers import SchedulerCommonTest class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Any = (DDPMParallelScheduler,) def __magic_name__ ( self : Optional[int] , **lowerCAmelCase_ : Any ): """simple docstring""" _A: Optional[int] = { '''num_train_timesteps''': 1_0_0_0, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''variance_type''': '''fixed_small''', '''clip_sample''': True, } config.update(**lowerCAmelCase_ ) return config def __magic_name__ ( self : int ): """simple docstring""" for timesteps in [1, 5, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=lowerCAmelCase_ ) def __magic_name__ ( self : Tuple ): """simple docstring""" for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=lowerCAmelCase_ , beta_end=lowerCAmelCase_ ) def __magic_name__ ( self : Optional[Any] ): """simple docstring""" for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=lowerCAmelCase_ ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=lowerCAmelCase_ ) def __magic_name__ ( self : Tuple ): """simple docstring""" for clip_sample in [True, False]: self.check_over_configs(clip_sample=lowerCAmelCase_ ) def __magic_name__ ( self : List[str] ): """simple docstring""" self.check_over_configs(thresholding=lowerCAmelCase_ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=lowerCAmelCase_ , prediction_type=lowerCAmelCase_ , sample_max_value=lowerCAmelCase_ , ) def __magic_name__ ( self : Dict ): """simple docstring""" for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=lowerCAmelCase_ ) def __magic_name__ ( self : int ): """simple docstring""" for t in [0, 5_0_0, 9_9_9]: self.check_over_forward(time_step=lowerCAmelCase_ ) def __magic_name__ ( self : Any ): """simple docstring""" _A: List[Any] = self.scheduler_classes[0] _A: Union[str, Any] = self.get_scheduler_config() _A: Optional[Any] = scheduler_class(**lowerCAmelCase_ ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_8_7 ) - 0.00979 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_9_9 ) - 0.02 ) ) < 1e-5 def __magic_name__ ( self : Optional[int] ): """simple docstring""" _A: Any = self.scheduler_classes[0] _A: List[str] = self.get_scheduler_config() _A: Union[str, Any] = scheduler_class(**lowerCAmelCase_ ) _A: List[Any] = len(lowerCAmelCase_ ) _A: Union[str, Any] = self.dummy_model() _A: Dict = self.dummy_sample_deter _A: Dict = self.dummy_sample_deter + 0.1 _A: str = self.dummy_sample_deter - 0.1 _A: str = samplea.shape[0] _A: Optional[Any] = torch.stack([samplea, samplea, samplea] , dim=0 ) _A: List[str] = torch.arange(lowerCAmelCase_ )[0:3, None].repeat(1 , lowerCAmelCase_ ) _A: List[Any] = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) _A: Optional[int] = scheduler.batch_step_no_noise(lowerCAmelCase_ , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) ) _A: Dict = torch.sum(torch.abs(lowerCAmelCase_ ) ) _A: List[str] = torch.mean(torch.abs(lowerCAmelCase_ ) ) assert abs(result_sum.item() - 1153.1833 ) < 1e-2 assert abs(result_mean.item() - 0.5005 ) < 1e-3 def __magic_name__ ( self : Tuple ): """simple docstring""" _A: Optional[Any] = self.scheduler_classes[0] _A: List[Any] = self.get_scheduler_config() _A: Any = scheduler_class(**lowerCAmelCase_ ) _A: Union[str, Any] = len(lowerCAmelCase_ ) _A: Any = self.dummy_model() _A: Optional[int] = self.dummy_sample_deter _A: List[str] = torch.manual_seed(0 ) for t in reversed(range(lowerCAmelCase_ ) ): # 1. predict noise residual _A: Optional[int] = model(lowerCAmelCase_ , lowerCAmelCase_ ) # 2. predict previous mean of sample x_t-1 _A: Optional[int] = scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , generator=lowerCAmelCase_ ).prev_sample _A: List[Any] = pred_prev_sample _A: Optional[int] = torch.sum(torch.abs(lowerCAmelCase_ ) ) _A: Any = torch.mean(torch.abs(lowerCAmelCase_ ) ) assert abs(result_sum.item() - 258.9606 ) < 1e-2 assert abs(result_mean.item() - 0.3372 ) < 1e-3 def __magic_name__ ( self : Tuple ): """simple docstring""" _A: Optional[int] = self.scheduler_classes[0] _A: Union[str, Any] = self.get_scheduler_config(prediction_type='''v_prediction''' ) _A: List[str] = scheduler_class(**lowerCAmelCase_ ) _A: Union[str, Any] = len(lowerCAmelCase_ ) _A: Any = self.dummy_model() _A: Any = self.dummy_sample_deter _A: str = torch.manual_seed(0 ) for t in reversed(range(lowerCAmelCase_ ) ): # 1. predict noise residual _A: Any = model(lowerCAmelCase_ , lowerCAmelCase_ ) # 2. predict previous mean of sample x_t-1 _A: int = scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , generator=lowerCAmelCase_ ).prev_sample _A: Tuple = pred_prev_sample _A: List[Any] = torch.sum(torch.abs(lowerCAmelCase_ ) ) _A: str = torch.mean(torch.abs(lowerCAmelCase_ ) ) assert abs(result_sum.item() - 202.0296 ) < 1e-2 assert abs(result_mean.item() - 0.2631 ) < 1e-3 def __magic_name__ ( self : Optional[int] ): """simple docstring""" _A: Optional[int] = self.scheduler_classes[0] _A: Optional[Any] = self.get_scheduler_config() _A: Dict = scheduler_class(**lowerCAmelCase_ ) _A: Any = [1_0_0, 8_7, 5_0, 1, 0] scheduler.set_timesteps(timesteps=lowerCAmelCase_ ) _A: Tuple = scheduler.timesteps for i, timestep in enumerate(lowerCAmelCase_ ): if i == len(lowerCAmelCase_ ) - 1: _A: Dict = -1 else: _A: int = timesteps[i + 1] _A: List[str] = scheduler.previous_timestep(lowerCAmelCase_ ) _A: str = prev_t.item() self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) def __magic_name__ ( self : Any ): """simple docstring""" _A: Tuple = self.scheduler_classes[0] _A: int = self.get_scheduler_config() _A: Any = scheduler_class(**lowerCAmelCase_ ) _A: Union[str, Any] = [1_0_0, 8_7, 5_0, 5_1, 0] with self.assertRaises(lowerCAmelCase_ , msg='''`custom_timesteps` must be in descending order.''' ): scheduler.set_timesteps(timesteps=lowerCAmelCase_ ) def __magic_name__ ( self : int ): """simple docstring""" _A: List[str] = self.scheduler_classes[0] _A: Optional[Any] = self.get_scheduler_config() _A: Union[str, Any] = scheduler_class(**lowerCAmelCase_ ) _A: Union[str, Any] = [1_0_0, 8_7, 5_0, 1, 0] _A: Dict = len(lowerCAmelCase_ ) with self.assertRaises(lowerCAmelCase_ , msg='''Can only pass one of `num_inference_steps` or `custom_timesteps`.''' ): scheduler.set_timesteps(num_inference_steps=lowerCAmelCase_ , timesteps=lowerCAmelCase_ ) def __magic_name__ ( self : Any ): """simple docstring""" _A: List[Any] = self.scheduler_classes[0] _A: int = self.get_scheduler_config() _A: str = scheduler_class(**lowerCAmelCase_ ) _A: Any = [scheduler.config.num_train_timesteps] with self.assertRaises( lowerCAmelCase_ , msg='''`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}''' , ): scheduler.set_timesteps(timesteps=lowerCAmelCase_ )
301
1
from __future__ import annotations UpperCAmelCase__ : List[Any] = 'Muhammad Umer Farooq' UpperCAmelCase__ : str = 'MIT' UpperCAmelCase__ : Optional[int] = '1.0.0' UpperCAmelCase__ : Any = 'Muhammad Umer Farooq' UpperCAmelCase__ : Optional[Any] = 'contact@muhammadumerfarooq.me' UpperCAmelCase__ : Union[str, Any] = 'Alpha' import re from html.parser import HTMLParser from urllib import parse import requests class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def __init__( self : Tuple , lowerCAmelCase_ : str ): """simple docstring""" super().__init__() _A: list[str] = [] _A: Optional[Any] = domain def __magic_name__ ( self : int , lowerCAmelCase_ : str , lowerCAmelCase_ : list[tuple[str, str | None]] ): """simple docstring""" # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: _A: int = parse.urljoin(self.domain , lowerCAmelCase_ ) self.urls.append(lowerCAmelCase_ ) def lowerCamelCase__ ( a ) -> str: return ".".join(get_sub_domain_name(a ).split('''.''' )[-2:] ) def lowerCamelCase__ ( a ) -> str: return parse.urlparse(a ).netloc def lowerCamelCase__ ( a = "https://github.com" ) -> list[str]: _A: List[Any] = get_domain_name(a ) # Initialize the parser _A: str = Parser(a ) try: # Open URL _A: Tuple = requests.get(a ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through _A: Optional[Any] = set() for link in parser.urls: # open URL. # read = requests.get(link) try: _A: List[str] = requests.get(a ) # Get the valid email. _A: List[str] = re.findall('''[a-zA-Z0-9]+@''' + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(a ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(a ) if __name__ == "__main__": UpperCAmelCase__ : Optional[Any] = emails_from_url('https://github.com') print(F"""{len(emails)} emails found:""") print('\n'.join(sorted(emails)))
301
import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Any = GPTSanJapaneseTokenizer __UpperCamelCase : Optional[int] = False __UpperCamelCase : str = {'''do_clean_text''': False, '''add_prefix_space''': False} def __magic_name__ ( self : Any ): """simple docstring""" super().setUp() # fmt: off _A: Union[str, Any] = ['''こん''', '''こんに''', '''にちは''', '''ばんは''', '''世界,㔺界''', '''、''', '''。''', '''<BR>''', '''<SP>''', '''<TAB>''', '''<URL>''', '''<EMAIL>''', '''<TEL>''', '''<DATE>''', '''<PRICE>''', '''<BLOCK>''', '''<KIGOU>''', '''<U2000U2BFF>''', '''<|emoji1|>''', '''<unk>''', '''<|bagoftoken|>''', '''<|endoftext|>'''] # fmt: on _A: Union[str, Any] = {'''emoji''': {'''\ud83d\ude00''': '''<|emoji1|>'''}, '''emoji_inv''': {'''<|emoji1|>''': '''\ud83d\ude00'''}} # 😀 _A: str = {'''unk_token''': '''<unk>'''} _A: Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) _A: Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''emoji_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) with open(self.emoji_file , '''w''' ) as emoji_writer: emoji_writer.write(json.dumps(lowerCAmelCase_ ) ) def __magic_name__ ( self : Optional[int] , **lowerCAmelCase_ : List[Any] ): """simple docstring""" kwargs.update(self.special_tokens_map ) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **lowerCAmelCase_ ) def __magic_name__ ( self : Optional[int] , lowerCAmelCase_ : List[str] ): """simple docstring""" _A: Optional[Any] = '''こんにちは、世界。 \nこんばんは、㔺界。😀''' _A: str = '''こんにちは、世界。 \nこんばんは、世界。😀''' return input_text, output_text def __magic_name__ ( self : List[str] , lowerCAmelCase_ : Optional[int] ): """simple docstring""" _A , _A: Optional[int] = self.get_input_output_texts(lowerCAmelCase_ ) _A: Union[str, Any] = tokenizer.encode(lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ ) _A: Tuple = tokenizer.decode(lowerCAmelCase_ , clean_up_tokenization_spaces=lowerCAmelCase_ ) return text, ids def __magic_name__ ( self : Tuple ): """simple docstring""" pass # TODO add if relevant def __magic_name__ ( self : List[str] ): """simple docstring""" pass # TODO add if relevant def __magic_name__ ( self : Dict ): """simple docstring""" pass # TODO add if relevant def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" _A: List[str] = self.get_tokenizer() # Testing tokenization _A: List[Any] = '''こんにちは、世界。 こんばんは、㔺界。''' _A: Dict = ['''こん''', '''にちは''', '''、''', '''世界''', '''。''', '''<SP>''', '''こん''', '''ばんは''', '''、''', '''㔺界''', '''。'''] _A: List[Any] = tokenizer.tokenize(lowerCAmelCase_ ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) # Testing conversion to ids without special tokens _A: Optional[int] = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] _A: Optional[int] = tokenizer.convert_tokens_to_ids(lowerCAmelCase_ ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) # Testing conversion to ids with special tokens _A: Dict = tokens + [tokenizer.unk_token] _A: str = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 1_9] _A: Optional[int] = tokenizer.convert_tokens_to_ids(lowerCAmelCase_ ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" _A: Dict = self.get_tokenizer() # Testing tokenization _A: Optional[int] = '''こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。''' _A: str = '''こんにちは、、、、世界。こんばんは、、、、世界。''' _A: Tuple = tokenizer.encode(lowerCAmelCase_ ) _A: List[str] = tokenizer.decode(lowerCAmelCase_ ) self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) @slow def __magic_name__ ( self : Any ): """simple docstring""" _A: List[Any] = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' ) # Testing tokenization _A: Union[str, Any] = '''こんにちは、世界。''' _A: Optional[int] = '''こんばんは、㔺界。😀''' _A: str = '''こんにちは、世界。こんばんは、世界。😀''' _A: List[Any] = tokenizer.encode(prefix_text + input_text ) _A: Optional[Any] = tokenizer.encode('''''' , prefix_text=prefix_text + input_text ) _A: List[Any] = tokenizer.encode(lowerCAmelCase_ , prefix_text=lowerCAmelCase_ ) _A: Union[str, Any] = tokenizer.decode(lowerCAmelCase_ ) _A: Any = tokenizer.decode(lowerCAmelCase_ ) _A: Dict = tokenizer.decode(lowerCAmelCase_ ) self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) @slow def __magic_name__ ( self : Optional[Any] ): """simple docstring""" _A: str = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' ) # Testing tokenization _A: Optional[int] = '''こんにちは、世界。''' _A: Optional[int] = '''こんばんは、㔺界。😀''' _A: Any = len(tokenizer.encode(lowerCAmelCase_ ) ) - 2 _A: int = len(tokenizer.encode(lowerCAmelCase_ ) ) - 2 _A: Optional[Any] = [1] + [0] * (len_prefix + len_text + 1) _A: Any = [1] * (len_prefix + len_text + 1) + [0] _A: Optional[int] = [1] + [1] * (len_prefix) + [0] * (len_text + 1) _A: Optional[Any] = tokenizer(prefix_text + input_text ).token_type_ids _A: List[str] = tokenizer('''''' , prefix_text=prefix_text + input_text ).token_type_ids _A: Dict = tokenizer(lowerCAmelCase_ , prefix_text=lowerCAmelCase_ ).token_type_ids self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) @slow def __magic_name__ ( self : Any ): """simple docstring""" _A: str = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' ) _A: List[Any] = tokenizer.encode('''あンいワ''' ) _A: Any = tokenizer.encode('''''' , prefix_text='''あンいワ''' ) _A: Union[str, Any] = tokenizer.encode('''いワ''' , prefix_text='''あン''' ) self.assertEqual(tokenizer.decode(lowerCAmelCase_ ) , tokenizer.decode(lowerCAmelCase_ ) ) self.assertEqual(tokenizer.decode(lowerCAmelCase_ ) , tokenizer.decode(lowerCAmelCase_ ) ) self.assertNotEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertNotEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token @slow def __magic_name__ ( self : List[Any] ): """simple docstring""" _A: Tuple = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' ) _A: Optional[Any] = [['''武田信玄''', '''は、'''], ['''織田信長''', '''の配下の、''']] _A: Optional[int] = tokenizer(lowerCAmelCase_ , padding=lowerCAmelCase_ ) _A: Optional[Any] = tokenizer.batch_encode_plus(lowerCAmelCase_ , padding=lowerCAmelCase_ ) # fmt: off _A: Tuple = [[3_5_9_9_3, 8_6_4_0, 2_5_9_4_8, 3_5_9_9_8, 3_0_6_4_7, 3_5_6_7_5, 3_5_9_9_9, 3_5_9_9_9], [3_5_9_9_3, 1_0_3_8_2, 9_8_6_8, 3_5_9_9_8, 3_0_6_4_6, 9_4_5_9, 3_0_6_4_6, 3_5_6_7_5]] _A: Optional[int] = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] _A: Dict = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids , lowerCAmelCase_ ) self.assertListEqual(x_token.token_type_ids , lowerCAmelCase_ ) self.assertListEqual(x_token.attention_mask , lowerCAmelCase_ ) self.assertListEqual(x_token_a.input_ids , lowerCAmelCase_ ) self.assertListEqual(x_token_a.token_type_ids , lowerCAmelCase_ ) self.assertListEqual(x_token_a.attention_mask , lowerCAmelCase_ ) def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" # Intentionally convert some words to accommodate character fluctuations unique to Japanese pass def __magic_name__ ( self : Tuple ): """simple docstring""" # tokenizer has no padding token pass
301
1
import torch def lowerCamelCase__ ( ) -> Tuple: if torch.cuda.is_available(): _A: Optional[int] = torch.cuda.device_count() else: _A: int = 0 print(f"""Successfully ran on {num_gpus} GPUs""" ) if __name__ == "__main__": main()
301
def lowerCamelCase__ ( a = 10**9 ) -> int: _A: Dict = 1 _A: Union[str, Any] = 2 _A: List[str] = 0 _A: List[Any] = 0 _A: int = 0 while perimeter <= max_perimeter: perimeters_sum += perimeter prev_value += 2 * value value += prev_value _A: List[Any] = 2 * value + 2 if i % 2 == 0 else 2 * value - 2 i += 1 return perimeters_sum if __name__ == "__main__": print(F"""{solution() = }""")
301
1
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionAttendAndExcitePipeline, UNetaDConditionModel, ) from diffusers.utils import load_numpy, skip_mps, slow from diffusers.utils.testing_utils import require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin UpperCAmelCase__ : List[str] = False @skip_mps class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase : str = StableDiffusionAttendAndExcitePipeline __UpperCamelCase : Dict = False __UpperCamelCase : List[str] = TEXT_TO_IMAGE_PARAMS __UpperCamelCase : Optional[int] = TEXT_TO_IMAGE_BATCH_PARAMS.union({'''token_indices'''} ) __UpperCamelCase : List[str] = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCamelCase : int = TEXT_TO_IMAGE_IMAGE_PARAMS @classmethod def __magic_name__ ( cls : Union[str, Any] ): """simple docstring""" super().setUpClass() torch.use_deterministic_algorithms(lowerCAmelCase_ ) @classmethod def __magic_name__ ( cls : Any ): """simple docstring""" super().tearDownClass() torch.use_deterministic_algorithms(lowerCAmelCase_ ) def __magic_name__ ( self : Any ): """simple docstring""" torch.manual_seed(0 ) _A: Dict = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=1 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=3_2 , attention_head_dim=(2, 4) , use_linear_projection=lowerCAmelCase_ , ) _A: Any = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , clip_sample=lowerCAmelCase_ , set_alpha_to_one=lowerCAmelCase_ , ) torch.manual_seed(0 ) _A: Any = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , sample_size=1_2_8 , ) torch.manual_seed(0 ) _A: str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act='''gelu''' , projection_dim=5_1_2 , ) _A: List[str] = CLIPTextModel(lowerCAmelCase_ ) _A: Any = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) _A: Tuple = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def __magic_name__ ( self : str , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[int]=0 ): """simple docstring""" if str(lowerCAmelCase_ ).startswith('''mps''' ): _A: Tuple = torch.manual_seed(lowerCAmelCase_ ) else: _A: Tuple = torch.Generator(device=lowerCAmelCase_ ).manual_seed(lowerCAmelCase_ ) _A: Union[str, Any] = { '''prompt''': '''a cat and a frog''', '''token_indices''': [2, 5], '''generator''': generator, '''num_inference_steps''': 1, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', '''max_iter_to_alter''': 2, '''thresholds''': {0: 0.7}, } return inputs def __magic_name__ ( self : Any ): """simple docstring""" _A: List[str] = '''cpu''' _A: int = self.get_dummy_components() _A: Optional[int] = self.pipeline_class(**lowerCAmelCase_ ) pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _A: Dict = self.get_dummy_inputs(lowerCAmelCase_ ) _A: Tuple = pipe(**lowerCAmelCase_ ).images _A: List[Any] = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 6_4, 6_4, 3) ) _A: Any = np.array( [0.63905364, 0.62897307, 0.48599017, 0.5133624, 0.5550048, 0.45769516, 0.50326973, 0.5023139, 0.45384496] ) _A: Tuple = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(lowerCAmelCase_ , 1e-3 ) def __magic_name__ ( self : Optional[Any] ): """simple docstring""" super().test_cpu_offload_forward_pass(expected_max_diff=5e-4 ) def __magic_name__ ( self : int ): """simple docstring""" # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" self._test_inference_batch_single_identical(batch_size=2 , expected_max_diff=7e-4 ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5e-4 ) def __magic_name__ ( self : str ): """simple docstring""" super().test_save_load_local(expected_max_difference=5e-4 ) def __magic_name__ ( self : Any ): """simple docstring""" super().test_save_load_optional_components(expected_max_difference=4e-4 ) @require_torch_gpu @slow class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @classmethod def __magic_name__ ( cls : Optional[int] ): """simple docstring""" super().setUpClass() torch.use_deterministic_algorithms(lowerCAmelCase_ ) @classmethod def __magic_name__ ( cls : Optional[int] ): """simple docstring""" super().tearDownClass() torch.use_deterministic_algorithms(lowerCAmelCase_ ) def __magic_name__ ( self : Optional[Any] ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" _A: Dict = torch.manual_seed(5_1 ) _A: int = StableDiffusionAttendAndExcitePipeline.from_pretrained( '''CompVis/stable-diffusion-v1-4''' , safety_checker=lowerCAmelCase_ , torch_dtype=torch.floataa ) pipe.to('''cuda''' ) _A: Any = '''a painting of an elephant with glasses''' _A: Optional[Any] = [5, 7] _A: Dict = pipe( prompt=lowerCAmelCase_ , token_indices=lowerCAmelCase_ , guidance_scale=7.5 , generator=lowerCAmelCase_ , num_inference_steps=5 , max_iter_to_alter=5 , output_type='''numpy''' , ).images[0] _A: Any = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy''' ) assert np.abs((expected_image - image).max() ) < 5e-1
301
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase__ : Union[str, Any] = { 'configuration_roc_bert': ['ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoCBertConfig'], 'tokenization_roc_bert': ['RoCBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: pass try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[Any] = [ 'ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'RoCBertForCausalLM', 'RoCBertForMaskedLM', 'RoCBertForMultipleChoice', 'RoCBertForPreTraining', 'RoCBertForQuestionAnswering', 'RoCBertForSequenceClassification', 'RoCBertForTokenClassification', 'RoCBertLayer', 'RoCBertModel', 'RoCBertPreTrainedModel', 'load_tf_weights_in_roc_bert', ] if TYPE_CHECKING: from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig from .tokenization_roc_bert import RoCBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: raise OptionalDependencyNotAvailable() try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) else: import sys UpperCAmelCase__ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
301
1
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision import transforms from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def lowerCamelCase__ ( a ) -> int: _A: Any = [2, 2, 6, 2] if '''tiny''' in model_name else [2, 2, 18, 2] _A: Dict = True if '''large''' in model_name or '''huge''' in model_name else False _A: Tuple = True if '''large''' in model_name or '''huge''' in model_name else False _A: Any = True if '''large''' in model_name or '''huge''' in model_name else False if "large" in model_name or "xlarge" in model_name or "huge" in model_name: if "fl3" in model_name: _A: Tuple = [3, 3, 3, 3] _A: List[Any] = [5, 5, 5, 5] elif "fl4" in model_name: _A: Tuple = [4, 4, 4, 4] _A: List[Any] = [3, 3, 3, 3] if "tiny" in model_name or "small" in model_name or "base" in model_name: _A: Union[str, Any] = [3, 3, 3, 3] if "lrf" in model_name: _A: List[str] = [3, 3, 3, 3] else: _A: List[str] = [2, 2, 2, 2] if "tiny" in model_name: _A: Optional[Any] = 96 elif "small" in model_name: _A: Optional[int] = 96 elif "base" in model_name: _A: int = 1_28 elif "large" in model_name: _A: List[Any] = 1_92 elif "xlarge" in model_name: _A: int = 2_56 elif "huge" in model_name: _A: Dict = 3_52 # set label information _A: str = '''huggingface/label-files''' if "large" in model_name or "huge" in model_name: _A: List[Any] = '''imagenet-22k-id2label.json''' else: _A: Any = '''imagenet-1k-id2label.json''' _A: List[Any] = json.load(open(hf_hub_download(a , a , repo_type='''dataset''' ) , '''r''' ) ) _A: int = {int(a ): v for k, v in idalabel.items()} _A: int = {v: k for k, v in idalabel.items()} _A: Dict = FocalNetConfig( embed_dim=a , depths=a , focal_levels=a , focal_windows=a , use_conv_embed=a , idalabel=a , labelaid=a , use_post_layernorm=a , use_layerscale=a , ) return config def lowerCamelCase__ ( a ) -> Optional[int]: if "patch_embed.proj" in name: _A: Union[str, Any] = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: _A: List[Any] = name.replace('''patch_embed.norm''' , '''embeddings.norm''' ) if "layers" in name: _A: Optional[int] = '''encoder.''' + name if "encoder.layers" in name: _A: Optional[Any] = name.replace('''encoder.layers''' , '''encoder.stages''' ) if "downsample.proj" in name: _A: Any = name.replace('''downsample.proj''' , '''downsample.projection''' ) if "blocks" in name: _A: Tuple = name.replace('''blocks''' , '''layers''' ) if "modulation.f.weight" in name or "modulation.f.bias" in name: _A: List[Any] = name.replace('''modulation.f''' , '''modulation.projection_in''' ) if "modulation.h.weight" in name or "modulation.h.bias" in name: _A: Dict = name.replace('''modulation.h''' , '''modulation.projection_context''' ) if "modulation.proj.weight" in name or "modulation.proj.bias" in name: _A: Union[str, Any] = name.replace('''modulation.proj''' , '''modulation.projection_out''' ) if name == "norm.weight": _A: Tuple = '''layernorm.weight''' if name == "norm.bias": _A: int = '''layernorm.bias''' if "head" in name: _A: Optional[int] = name.replace('''head''' , '''classifier''' ) else: _A: Optional[Any] = '''focalnet.''' + name return name def lowerCamelCase__ ( a , a , a=False ) -> str: # fmt: off _A: int = { '''focalnet-tiny''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_srf.pth''', '''focalnet-tiny-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_lrf.pth''', '''focalnet-small''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_srf.pth''', '''focalnet-small-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_lrf.pth''', '''focalnet-base''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_srf.pth''', '''focalnet-base-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_lrf.pth''', '''focalnet-large-lrf-fl3''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384.pth''', '''focalnet-large-lrf-fl4''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384_fl4.pth''', '''focalnet-xlarge-lrf-fl3''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384.pth''', '''focalnet-xlarge-lrf-fl4''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384_fl4.pth''', } # fmt: on _A: Union[str, Any] = model_name_to_url[model_name] print('''Checkpoint URL: ''' , a ) _A: Any = torch.hub.load_state_dict_from_url(a , map_location='''cpu''' )['''model'''] # rename keys for key in state_dict.copy().keys(): _A: int = state_dict.pop(a ) _A: Any = val _A: Any = get_focalnet_config(a ) _A: str = FocalNetForImageClassification(a ) model.eval() # load state dict model.load_state_dict(a ) # verify conversion _A: List[str] = '''http://images.cocodataset.org/val2017/000000039769.jpg''' _A: Any = BitImageProcessor( do_resize=a , size={'''shortest_edge''': 2_56} , resample=PILImageResampling.BILINEAR , do_center_crop=a , crop_size=2_24 , do_normalize=a , image_mean=a , image_std=a , ) _A: Union[str, Any] = Image.open(requests.get(a , stream=a ).raw ) _A: Optional[Any] = processor(images=a , return_tensors='''pt''' ) _A: Union[str, Any] = transforms.Compose( [ transforms.Resize(2_56 ), transforms.CenterCrop(2_24 ), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ), ] ) _A: Any = image_transforms(a ).unsqueeze(0 ) # verify pixel_values assert torch.allclose(inputs.pixel_values , a , atol=1E-4 ) _A: Tuple = model(**a ) _A: Optional[Any] = outputs.logits.argmax(-1 ).item() print('''Predicted class:''' , model.config.idalabel[predicted_class_idx] ) print('''First values of logits:''' , outputs.logits[0, :3] ) if model_name == "focalnet-tiny": _A: Union[str, Any] = torch.tensor([0.2166, -0.4368, 0.2191] ) elif model_name == "focalnet-tiny-lrf": _A: str = torch.tensor([1.1669, 0.0125, -0.1695] ) elif model_name == "focalnet-small": _A: Dict = torch.tensor([0.4917, -0.0430, 0.1341] ) elif model_name == "focalnet-small-lrf": _A: List[str] = torch.tensor([-0.2588, -0.5342, -0.2331] ) elif model_name == "focalnet-base": _A: Union[str, Any] = torch.tensor([-0.1655, -0.4090, -0.1730] ) elif model_name == "focalnet-base-lrf": _A: List[Any] = torch.tensor([0.5306, -0.0483, -0.3928] ) assert torch.allclose(outputs.logits[0, :3] , a , atol=1E-4 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: print(f"""Saving model and processor of {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(a ) processor.save_pretrained(a ) if push_to_hub: print(f"""Pushing model and processor of {model_name} to the hub...""" ) model.push_to_hub(f"""{model_name}""" ) processor.push_to_hub(f"""{model_name}""" ) if __name__ == "__main__": UpperCAmelCase__ : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='focalnet-tiny', type=str, help='Name of the FocalNet model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model and processor to the hub.', ) UpperCAmelCase__ : Dict = parser.parse_args() convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
301
import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def lowerCamelCase__ ( a , a=0.999 , a="cosine" , ) -> int: if alpha_transform_type == "cosine": def alpha_bar_fn(a ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(a ): return math.exp(t * -12.0 ) else: raise ValueError(f"""Unsupported alpha_tranform_type: {alpha_transform_type}""" ) _A: Dict = [] for i in range(a ): _A: Optional[int] = i / num_diffusion_timesteps _A: Optional[int] = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(a ) / alpha_bar_fn(a ) , a ) ) return torch.tensor(a , dtype=torch.floataa ) class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Optional[int] = [e.name for e in KarrasDiffusionSchedulers] __UpperCamelCase : Tuple = 2 @register_to_config def __init__( self : str , lowerCAmelCase_ : int = 1_0_0_0 , lowerCAmelCase_ : float = 0.00085 , lowerCAmelCase_ : float = 0.012 , lowerCAmelCase_ : str = "linear" , lowerCAmelCase_ : Optional[Union[np.ndarray, List[float]]] = None , lowerCAmelCase_ : str = "epsilon" , lowerCAmelCase_ : Optional[bool] = False , lowerCAmelCase_ : Optional[bool] = False , lowerCAmelCase_ : float = 1.0 , lowerCAmelCase_ : str = "linspace" , lowerCAmelCase_ : int = 0 , ): """simple docstring""" if trained_betas is not None: _A: Optional[Any] = torch.tensor(lowerCAmelCase_ , dtype=torch.floataa ) elif beta_schedule == "linear": _A: List[str] = torch.linspace(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. _A: Optional[Any] = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , lowerCAmelCase_ , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule _A: Tuple = betas_for_alpha_bar(lowerCAmelCase_ , alpha_transform_type='''cosine''' ) elif beta_schedule == "exp": _A: int = betas_for_alpha_bar(lowerCAmelCase_ , alpha_transform_type='''exp''' ) else: raise NotImplementedError(F"""{beta_schedule} does is not implemented for {self.__class__}""" ) _A: Union[str, Any] = 1.0 - self.betas _A: Dict = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) _A: str = use_karras_sigmas def __magic_name__ ( self : List[str] , lowerCAmelCase_ : Any , lowerCAmelCase_ : Optional[int]=None ): """simple docstring""" if schedule_timesteps is None: _A: List[str] = self.timesteps _A: int = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: _A: Optional[int] = 1 if len(lowerCAmelCase_ ) > 1 else 0 else: _A: int = timestep.cpu().item() if torch.is_tensor(lowerCAmelCase_ ) else timestep _A: List[str] = self._index_counter[timestep_int] return indices[pos].item() @property def __magic_name__ ( self : int ): """simple docstring""" # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def __magic_name__ ( self : List[str] , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : Union[float, torch.FloatTensor] , ): """simple docstring""" _A: List[str] = self.index_for_timestep(lowerCAmelCase_ ) _A: str = self.sigmas[step_index] _A: str = sample / ((sigma**2 + 1) ** 0.5) return sample def __magic_name__ ( self : Optional[int] , lowerCAmelCase_ : int , lowerCAmelCase_ : Union[str, torch.device] = None , lowerCAmelCase_ : Optional[int] = None , ): """simple docstring""" _A: Union[str, Any] = num_inference_steps _A: str = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": _A: Optional[Any] = np.linspace(0 , num_train_timesteps - 1 , lowerCAmelCase_ , dtype=lowerCAmelCase_ )[::-1].copy() elif self.config.timestep_spacing == "leading": _A: List[Any] = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 _A: Dict = (np.arange(0 , lowerCAmelCase_ ) * step_ratio).round()[::-1].copy().astype(lowerCAmelCase_ ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": _A: Union[str, Any] = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 _A: List[Any] = (np.arange(lowerCAmelCase_ , 0 , -step_ratio )).round().copy().astype(lowerCAmelCase_ ) timesteps -= 1 else: raise ValueError( F"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.""" ) _A: Optional[int] = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) _A: str = np.log(lowerCAmelCase_ ) _A: int = np.interp(lowerCAmelCase_ , np.arange(0 , len(lowerCAmelCase_ ) ) , lowerCAmelCase_ ) if self.config.use_karras_sigmas: _A: Optional[int] = self._convert_to_karras(in_sigmas=lowerCAmelCase_ , num_inference_steps=self.num_inference_steps ) _A: List[str] = np.array([self._sigma_to_t(lowerCAmelCase_ , lowerCAmelCase_ ) for sigma in sigmas] ) _A: Optional[int] = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) _A: Optional[Any] = torch.from_numpy(lowerCAmelCase_ ).to(device=lowerCAmelCase_ ) _A: Tuple = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) _A: str = torch.from_numpy(lowerCAmelCase_ ) _A: str = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(lowerCAmelCase_ ).startswith('''mps''' ): # mps does not support float64 _A: List[Any] = timesteps.to(lowerCAmelCase_ , dtype=torch.floataa ) else: _A: Optional[int] = timesteps.to(device=lowerCAmelCase_ ) # empty dt and derivative _A: Dict = None _A: List[Any] = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter _A: Dict = defaultdict(lowerCAmelCase_ ) def __magic_name__ ( self : Dict , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Dict ): """simple docstring""" # get log sigma _A: Tuple = np.log(lowerCAmelCase_ ) # get distribution _A: List[str] = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range _A: Dict = np.cumsum((dists >= 0) , axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) _A: int = low_idx + 1 _A: Optional[int] = log_sigmas[low_idx] _A: Dict = log_sigmas[high_idx] # interpolate sigmas _A: Union[str, Any] = (low - log_sigma) / (low - high) _A: Optional[Any] = np.clip(lowerCAmelCase_ , 0 , 1 ) # transform interpolation to time range _A: Any = (1 - w) * low_idx + w * high_idx _A: List[Any] = t.reshape(sigma.shape ) return t def __magic_name__ ( self : Any , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" _A: float = in_sigmas[-1].item() _A: float = in_sigmas[0].item() _A: Union[str, Any] = 7.0 # 7.0 is the value used in the paper _A: Optional[Any] = np.linspace(0 , 1 , lowerCAmelCase_ ) _A: Tuple = sigma_min ** (1 / rho) _A: Optional[Any] = sigma_max ** (1 / rho) _A: List[str] = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def __magic_name__ ( self : Optional[Any] ): """simple docstring""" return self.dt is None def __magic_name__ ( self : Tuple , lowerCAmelCase_ : Union[torch.FloatTensor, np.ndarray] , lowerCAmelCase_ : Union[float, torch.FloatTensor] , lowerCAmelCase_ : Union[torch.FloatTensor, np.ndarray] , lowerCAmelCase_ : bool = True , ): """simple docstring""" _A: Optional[int] = self.index_for_timestep(lowerCAmelCase_ ) # advance index counter by 1 _A: Union[str, Any] = timestep.cpu().item() if torch.is_tensor(lowerCAmelCase_ ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: _A: Optional[int] = self.sigmas[step_index] _A: Union[str, Any] = self.sigmas[step_index + 1] else: # 2nd order / Heun's method _A: Union[str, Any] = self.sigmas[step_index - 1] _A: Optional[int] = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API _A: List[Any] = 0 _A: Tuple = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": _A: Union[str, Any] = sigma_hat if self.state_in_first_order else sigma_next _A: List[str] = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": _A: int = sigma_hat if self.state_in_first_order else sigma_next _A: List[str] = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": _A: Optional[int] = model_output else: raise ValueError( F"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`""" ) if self.config.clip_sample: _A: Tuple = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order _A: Optional[int] = (sample - pred_original_sample) / sigma_hat # 3. delta timestep _A: List[Any] = sigma_next - sigma_hat # store for 2nd order step _A: str = derivative _A: Any = dt _A: Dict = sample else: # 2. 2nd order / Heun's method _A: List[str] = (sample - pred_original_sample) / sigma_next _A: str = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample _A: Dict = self.dt _A: int = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" _A: int = None _A: int = None _A: Optional[Any] = None _A: Optional[Any] = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=lowerCAmelCase_ ) def __magic_name__ ( self : Any , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : torch.FloatTensor , ): """simple docstring""" # Make sure sigmas and timesteps have the same device and dtype as original_samples _A: str = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(lowerCAmelCase_ ): # mps does not support float64 _A: Optional[int] = self.timesteps.to(original_samples.device , dtype=torch.floataa ) _A: Any = timesteps.to(original_samples.device , dtype=torch.floataa ) else: _A: Union[str, Any] = self.timesteps.to(original_samples.device ) _A: int = timesteps.to(original_samples.device ) _A: str = [self.index_for_timestep(lowerCAmelCase_ , lowerCAmelCase_ ) for t in timesteps] _A: Optional[Any] = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): _A: List[str] = sigma.unsqueeze(-1 ) _A: Any = original_samples + noise * sigma return noisy_samples def __len__( self : Dict ): """simple docstring""" return self.config.num_train_timesteps
301
1
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 UpperCAmelCase : '''simple docstring''' @staticmethod def __magic_name__ ( *lowerCAmelCase_ : Union[str, Any] , **lowerCAmelCase_ : int ): """simple docstring""" pass def lowerCamelCase__ ( a ) -> Optional[Any]: 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. UpperCAmelCase__ : Tuple = ( 'https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png' ) @is_pipeline_test @require_torch @require_vision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' __UpperCamelCase : List[Any] = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING @require_pytesseract @require_vision def __magic_name__ ( self : Any , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : str , lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Optional[int] = pipeline( '''document-question-answering''' , model=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ , image_processor=lowerCAmelCase_ ) _A: int = INVOICE_URL _A: Optional[Any] = list(zip(*apply_tesseract(load_image(lowerCAmelCase_ ) , lowerCAmelCase_ , '''''' ) ) ) _A: List[Any] = '''What is the placebo?''' _A: List[str] = [ { '''image''': load_image(lowerCAmelCase_ ), '''question''': question, }, { '''image''': image, '''question''': question, }, { '''image''': image, '''question''': question, '''word_boxes''': word_boxes, }, ] return dqa_pipeline, examples def __magic_name__ ( self : List[Any] , lowerCAmelCase_ : Dict , lowerCAmelCase_ : str ): """simple docstring""" _A: Optional[Any] = dqa_pipeline(lowerCAmelCase_ , top_k=2 ) self.assertEqual( lowerCAmelCase_ , [ [ {'''score''': ANY(lowerCAmelCase_ ), '''answer''': ANY(lowerCAmelCase_ ), '''start''': ANY(lowerCAmelCase_ ), '''end''': ANY(lowerCAmelCase_ )}, {'''score''': ANY(lowerCAmelCase_ ), '''answer''': ANY(lowerCAmelCase_ ), '''start''': ANY(lowerCAmelCase_ ), '''end''': ANY(lowerCAmelCase_ )}, ] ] * 3 , ) @require_torch @require_detectrona @require_pytesseract def __magic_name__ ( self : Optional[int] ): """simple docstring""" _A: int = pipeline('''document-question-answering''' , model='''hf-internal-testing/tiny-random-layoutlmv2''' ) _A: Optional[Any] = INVOICE_URL _A: Tuple = '''How many cats are there?''' _A: str = [ {'''score''': 0.0001, '''answer''': '''oy 2312/2019''', '''start''': 3_8, '''end''': 3_9}, {'''score''': 0.0001, '''answer''': '''oy 2312/2019 DUE''', '''start''': 3_8, '''end''': 4_0}, ] _A: List[Any] = dqa_pipeline(image=lowerCAmelCase_ , question=lowerCAmelCase_ , top_k=2 ) self.assertEqual(nested_simplify(lowerCAmelCase_ , decimals=4 ) , lowerCAmelCase_ ) _A: Union[str, Any] = dqa_pipeline({'''image''': image, '''question''': question} , top_k=2 ) self.assertEqual(nested_simplify(lowerCAmelCase_ , decimals=4 ) , lowerCAmelCase_ ) # This image does not detect ANY text in it, meaning layoutlmv2 should fail. # Empty answer probably _A: Any = '''./tests/fixtures/tests_samples/COCO/000000039769.png''' _A: List[str] = dqa_pipeline(image=lowerCAmelCase_ , question=lowerCAmelCase_ , top_k=2 ) self.assertEqual(lowerCAmelCase_ , [] ) # We can optionnally pass directly the words and bounding boxes _A: str = '''./tests/fixtures/tests_samples/COCO/000000039769.png''' _A: Optional[int] = [] _A: Tuple = [] _A: List[Any] = dqa_pipeline(image=lowerCAmelCase_ , question=lowerCAmelCase_ , words=lowerCAmelCase_ , boxes=lowerCAmelCase_ , top_k=2 ) self.assertEqual(lowerCAmelCase_ , [] ) @slow @require_torch @require_detectrona @require_pytesseract def __magic_name__ ( self : Optional[int] ): """simple docstring""" _A: List[Any] = pipeline( '''document-question-answering''' , model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa''' , revision='''9977165''' , ) _A: str = INVOICE_URL _A: Any = '''What is the invoice number?''' _A: List[str] = dqa_pipeline(image=lowerCAmelCase_ , question=lowerCAmelCase_ , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase_ , decimals=4 ) , [ {'''score''': 0.9944, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6}, {'''score''': 0.0009, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6}, ] , ) _A: List[Any] = dqa_pipeline({'''image''': image, '''question''': question} , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase_ , decimals=4 ) , [ {'''score''': 0.9944, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6}, {'''score''': 0.0009, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6}, ] , ) _A: Union[str, Any] = dqa_pipeline( [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}] , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase_ , decimals=4 ) , [ [ {'''score''': 0.9944, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6}, {'''score''': 0.0009, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6}, ], ] * 2 , ) @slow @require_torch @require_detectrona @require_pytesseract def __magic_name__ ( self : List[Any] ): """simple docstring""" _A: Optional[int] = pipeline( '''document-question-answering''' , model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa''' , revision='''9977165''' , max_seq_len=5_0 , ) _A: List[Any] = INVOICE_URL _A: Union[str, Any] = '''What is the invoice number?''' _A: Any = dqa_pipeline(image=lowerCAmelCase_ , question=lowerCAmelCase_ , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase_ , decimals=4 ) , [ {'''score''': 0.9974, '''answer''': '''1110212019''', '''start''': 2_3, '''end''': 2_3}, {'''score''': 0.9948, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6}, ] , ) _A: int = dqa_pipeline({'''image''': image, '''question''': question} , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase_ , decimals=4 ) , [ {'''score''': 0.9974, '''answer''': '''1110212019''', '''start''': 2_3, '''end''': 2_3}, {'''score''': 0.9948, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6}, ] , ) _A: int = dqa_pipeline( [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}] , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase_ , decimals=4 ) , [ [ {'''score''': 0.9974, '''answer''': '''1110212019''', '''start''': 2_3, '''end''': 2_3}, {'''score''': 0.9948, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6}, ] ] * 2 , ) @slow @require_torch @require_pytesseract @require_vision def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" _A: Any = AutoTokenizer.from_pretrained( '''impira/layoutlm-document-qa''' , revision='''3dc6de3''' , add_prefix_space=lowerCAmelCase_ ) _A: int = pipeline( '''document-question-answering''' , model='''impira/layoutlm-document-qa''' , tokenizer=lowerCAmelCase_ , revision='''3dc6de3''' , ) _A: Optional[Any] = INVOICE_URL _A: List[str] = '''What is the invoice number?''' _A: Optional[Any] = dqa_pipeline(image=lowerCAmelCase_ , question=lowerCAmelCase_ , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase_ , decimals=4 ) , [ {'''score''': 0.4251, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6}, {'''score''': 0.0819, '''answer''': '''1110212019''', '''start''': 2_3, '''end''': 2_3}, ] , ) _A: Optional[Any] = dqa_pipeline({'''image''': image, '''question''': question} , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase_ , decimals=4 ) , [ {'''score''': 0.4251, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6}, {'''score''': 0.0819, '''answer''': '''1110212019''', '''start''': 2_3, '''end''': 2_3}, ] , ) _A: Union[str, Any] = dqa_pipeline( [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}] , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase_ , decimals=4 ) , [ [ {'''score''': 0.4251, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6}, {'''score''': 0.0819, '''answer''': '''1110212019''', '''start''': 2_3, '''end''': 2_3}, ] ] * 2 , ) _A: Optional[Any] = list(zip(*apply_tesseract(load_image(lowerCAmelCase_ ) , lowerCAmelCase_ , '''''' ) ) ) # This model should also work if `image` is set to None _A: Any = dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question} , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase_ , decimals=4 ) , [ {'''score''': 0.4251, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6}, {'''score''': 0.0819, '''answer''': '''1110212019''', '''start''': 2_3, '''end''': 2_3}, ] , ) @slow @require_torch @require_pytesseract @require_vision def __magic_name__ ( self : Optional[int] ): """simple docstring""" _A: List[str] = AutoTokenizer.from_pretrained( '''impira/layoutlm-document-qa''' , revision='''3dc6de3''' , add_prefix_space=lowerCAmelCase_ ) _A: Dict = pipeline( '''document-question-answering''' , model='''impira/layoutlm-document-qa''' , tokenizer=lowerCAmelCase_ , revision='''3dc6de3''' , max_seq_len=5_0 , ) _A: List[str] = INVOICE_URL _A: Any = '''What is the invoice number?''' _A: int = dqa_pipeline(image=lowerCAmelCase_ , question=lowerCAmelCase_ , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase_ , decimals=4 ) , [ {'''score''': 0.9999, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6}, {'''score''': 0.9998, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6}, ] , ) _A: str = dqa_pipeline( [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}] , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase_ , decimals=4 ) , [ [ {'''score''': 0.9999, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6}, {'''score''': 0.9998, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6}, ] ] * 2 , ) _A: Dict = list(zip(*apply_tesseract(load_image(lowerCAmelCase_ ) , lowerCAmelCase_ , '''''' ) ) ) # This model should also work if `image` is set to None _A: Optional[Any] = dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question} , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase_ , decimals=4 ) , [ {'''score''': 0.9999, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6}, {'''score''': 0.9998, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6}, ] , ) @slow @require_torch def __magic_name__ ( self : Dict ): """simple docstring""" _A: Any = 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''' , ) _A: Tuple = INVOICE_URL _A: Tuple = '''What is the invoice number?''' _A: Optional[Any] = dqa_pipeline(image=lowerCAmelCase_ , question=lowerCAmelCase_ , top_k=2 ) self.assertEqual(nested_simplify(lowerCAmelCase_ , decimals=4 ) , [{'''answer''': '''us-001'''}] ) @require_tf @unittest.skip('''Document question answering not implemented in TF''' ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" pass
301
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=SCREAMING_SNAKE_CASE__ ) class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : str = field(default='''automatic-speech-recognition''' , metadata={'''include_in_asdict_even_if_is_default''': True} ) __UpperCamelCase : ClassVar[Features] = Features({'''audio''': Audio()} ) __UpperCamelCase : ClassVar[Features] = Features({'''transcription''': Value('''string''' )} ) __UpperCamelCase : str = "audio" __UpperCamelCase : str = "transcription" def __magic_name__ ( self : List[Any] , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" if self.audio_column not in features: raise ValueError(F"""Column {self.audio_column} is not present in features.""" ) if not isinstance(features[self.audio_column] , lowerCAmelCase_ ): raise ValueError(F"""Column {self.audio_column} is not an Audio type.""" ) _A: Optional[int] = copy.deepcopy(self ) _A: str = self.input_schema.copy() _A: List[str] = features[self.audio_column] _A: Dict = input_schema return task_template @property def __magic_name__ ( self : str ): """simple docstring""" return {self.audio_column: "audio", self.transcription_column: "transcription"}
301
1
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ : Dict = logging.get_logger(__name__) UpperCAmelCase__ : int = { 'microsoft/unispeech-sat-base-100h-libri-ft': ( 'https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft/resolve/main/config.json' ), # See all UniSpeechSat models at https://huggingface.co/models?filter=unispeech_sat } class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : str = '''unispeech-sat''' def __init__( self : Dict , lowerCAmelCase_ : Union[str, Any]=3_2 , lowerCAmelCase_ : str=7_6_8 , lowerCAmelCase_ : Dict=1_2 , lowerCAmelCase_ : Optional[Any]=1_2 , lowerCAmelCase_ : Union[str, Any]=3_0_7_2 , lowerCAmelCase_ : Tuple="gelu" , lowerCAmelCase_ : List[str]=0.1 , lowerCAmelCase_ : Union[str, Any]=0.1 , lowerCAmelCase_ : str=0.1 , lowerCAmelCase_ : int=0.0 , lowerCAmelCase_ : int=0.0 , lowerCAmelCase_ : Any=0.1 , lowerCAmelCase_ : int=0.1 , lowerCAmelCase_ : Optional[int]=0.02 , lowerCAmelCase_ : List[Any]=1e-5 , lowerCAmelCase_ : Optional[Any]="group" , lowerCAmelCase_ : Optional[Any]="gelu" , lowerCAmelCase_ : Union[str, Any]=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , lowerCAmelCase_ : str=(5, 2, 2, 2, 2, 2, 2) , lowerCAmelCase_ : Tuple=(1_0, 3, 3, 3, 3, 2, 2) , lowerCAmelCase_ : List[str]=False , lowerCAmelCase_ : List[Any]=1_2_8 , lowerCAmelCase_ : int=1_6 , lowerCAmelCase_ : Optional[Any]=False , lowerCAmelCase_ : str=True , lowerCAmelCase_ : Tuple=0.05 , lowerCAmelCase_ : Tuple=1_0 , lowerCAmelCase_ : Dict=2 , lowerCAmelCase_ : Dict=0.0 , lowerCAmelCase_ : str=1_0 , lowerCAmelCase_ : Any=0 , lowerCAmelCase_ : Optional[Any]=3_2_0 , lowerCAmelCase_ : Optional[int]=2 , lowerCAmelCase_ : int=0.1 , lowerCAmelCase_ : int=1_0_0 , lowerCAmelCase_ : int=2_5_6 , lowerCAmelCase_ : int=2_5_6 , lowerCAmelCase_ : Dict=0.1 , lowerCAmelCase_ : Any="mean" , lowerCAmelCase_ : Optional[int]=False , lowerCAmelCase_ : Optional[int]=False , lowerCAmelCase_ : Union[str, Any]=2_5_6 , lowerCAmelCase_ : Optional[int]=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 1_5_0_0) , lowerCAmelCase_ : Any=(5, 3, 3, 1, 1) , lowerCAmelCase_ : Union[str, Any]=(1, 2, 3, 1, 1) , lowerCAmelCase_ : str=5_1_2 , lowerCAmelCase_ : Any=0 , lowerCAmelCase_ : Dict=1 , lowerCAmelCase_ : Optional[int]=2 , lowerCAmelCase_ : Any=5_0_4 , **lowerCAmelCase_ : Union[str, Any] , ): """simple docstring""" super().__init__(**lowerCAmelCase_ , pad_token_id=lowerCAmelCase_ , bos_token_id=lowerCAmelCase_ , eos_token_id=lowerCAmelCase_ ) _A: List[str] = hidden_size _A: Tuple = feat_extract_norm _A: int = feat_extract_activation _A: Tuple = list(lowerCAmelCase_ ) _A: Tuple = list(lowerCAmelCase_ ) _A: List[Any] = list(lowerCAmelCase_ ) _A: List[Any] = conv_bias _A: Optional[Any] = num_conv_pos_embeddings _A: Optional[int] = num_conv_pos_embedding_groups _A: int = len(self.conv_dim ) _A: int = num_hidden_layers _A: int = intermediate_size _A: Union[str, Any] = hidden_act _A: int = num_attention_heads _A: Optional[int] = hidden_dropout _A: List[str] = attention_dropout _A: str = activation_dropout _A: Optional[int] = feat_proj_dropout _A: int = final_dropout _A: int = layerdrop _A: List[Any] = layer_norm_eps _A: List[Any] = initializer_range _A: List[str] = vocab_size _A: List[str] = num_clusters _A: Union[str, Any] = do_stable_layer_norm _A: Dict = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( '''Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==''' ''' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =''' F""" {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,""" F""" `len(config.conv_kernel) = {len(self.conv_kernel )}`.""" ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 _A: Union[str, Any] = apply_spec_augment _A: List[Any] = mask_time_prob _A: Dict = mask_time_length _A: str = mask_time_min_masks _A: Optional[int] = mask_feature_prob _A: Tuple = mask_feature_length _A: Tuple = mask_feature_min_masks # parameters for pretraining with codevector quantized representations _A: str = num_codevectors_per_group _A: int = num_codevector_groups _A: Any = contrastive_logits_temperature _A: Optional[Any] = feat_quantizer_dropout _A: List[Any] = num_negatives _A: List[Any] = codevector_dim _A: List[Any] = proj_codevector_dim _A: Union[str, Any] = diversity_loss_weight # ctc loss _A: Union[str, Any] = ctc_loss_reduction _A: List[Any] = ctc_zero_infinity # SequenceClassification-specific parameter. Feel free to ignore for other classes. _A: Optional[Any] = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. _A: Dict = list(lowerCAmelCase_ ) _A: Optional[int] = list(lowerCAmelCase_ ) _A: Optional[Any] = list(lowerCAmelCase_ ) _A: str = xvector_output_dim @property def __magic_name__ ( self : List[str] ): """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
301
import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer UpperCAmelCase__ : Optional[int] = 'bart' UpperCAmelCase__ : Dict = True @st.cache(allow_output_mutation=a ) def lowerCamelCase__ ( ) -> Dict: if LOAD_DENSE_INDEX: _A: Optional[Any] = AutoTokenizer.from_pretrained('''yjernite/retribert-base-uncased''' ) _A: Any = AutoModel.from_pretrained('''yjernite/retribert-base-uncased''' ).to('''cuda:0''' ) _A: Any = qar_model.eval() else: _A , _A: Union[str, Any] = (None, None) if MODEL_TYPE == "bart": _A: Union[str, Any] = AutoTokenizer.from_pretrained('''yjernite/bart_eli5''' ) _A: Dict = AutoModelForSeqaSeqLM.from_pretrained('''yjernite/bart_eli5''' ).to('''cuda:0''' ) _A: Union[str, Any] = torch.load('''seq2seq_models/eli5_bart_model_blm_2.pth''' ) sas_model.load_state_dict(save_dict['''model'''] ) _A: int = sas_model.eval() else: _A , _A: Tuple = make_qa_sas_model( model_name='''t5-small''' , from_file='''seq2seq_models/eli5_t5_model_1024_4.pth''' , device='''cuda:0''' ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=a ) def lowerCamelCase__ ( ) -> Tuple: if LOAD_DENSE_INDEX: _A: List[Any] = faiss.StandardGpuResources() _A: int = datasets.load_dataset(path='''wiki_snippets''' , name='''wiki40b_en_100_0''' )['''train'''] _A: Dict = np.memmap( '''wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat''' , dtype='''float32''' , mode='''r''' , shape=(wikiaab_passages.num_rows, 1_28) , ) _A: str = faiss.IndexFlatIP(1_28 ) _A: Optional[int] = faiss.index_cpu_to_gpu(a , 1 , a ) wikiaab_gpu_index_flat.add(a ) # TODO fix for larger GPU else: _A , _A: str = (None, None) _A: Tuple = Elasticsearch([{'''host''': '''localhost''', '''port''': '''9200'''}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=a ) def lowerCamelCase__ ( ) -> str: _A: Dict = datasets.load_dataset('''eli5''' , name='''LFQA_reddit''' ) _A: Dict = elia['''train_eli5'''] _A: List[Any] = np.memmap( '''eli5_questions_reps.dat''' , dtype='''float32''' , mode='''r''' , shape=(elia_train.num_rows, 1_28) ) _A: Any = faiss.IndexFlatIP(1_28 ) eli5_train_q_index.add(a ) return (elia_train, eli5_train_q_index) UpperCAmelCase__ ,UpperCAmelCase__ ,UpperCAmelCase__ : int = load_indexes() UpperCAmelCase__ ,UpperCAmelCase__ ,UpperCAmelCase__ ,UpperCAmelCase__ : Any = load_models() UpperCAmelCase__ ,UpperCAmelCase__ : Tuple = load_train_data() def lowerCamelCase__ ( a , a=10 ) -> str: _A: Optional[int] = embed_questions_for_retrieval([question] , a , a ) _A , _A: List[str] = eli5_train_q_index.search(a , a ) _A: Dict = [elia_train[int(a )] for i in I[0]] return nn_examples def lowerCamelCase__ ( a , a="wiki40b" , a="dense" , a=10 ) -> str: if source == "none": _A , _A: Any = (''' <P> '''.join(['''''' for _ in range(11 )] ).strip(), []) else: if method == "dense": _A , _A: List[Any] = query_qa_dense_index( a , a , a , a , a , a ) else: _A , _A: Tuple = query_es_index( a , a , index_name='''english_wiki40b_snippets_100w''' , n_results=a , ) _A: Union[str, Any] = [ (res['''article_title'''], res['''section_title'''].strip(), res['''score'''], res['''passage_text''']) for res in hit_lst ] _A: str = '''question: {} context: {}'''.format(a , a ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda a : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda a : None), } ) def lowerCamelCase__ ( a , a , a , a=64 , a=2_56 , a=False , a=2 , a=0.95 , a=0.8 ) -> str: with torch.no_grad(): _A: Optional[int] = qa_sas_generate( a , a , a , num_answers=1 , num_beams=a , min_len=a , max_len=a , do_sample=a , temp=a , top_p=a , top_k=a , max_input_length=10_24 , device='''cuda:0''' , )[0] return (answer, support_list) st.title('Long Form Question Answering with ELI5') # Start sidebar UpperCAmelCase__ : List[Any] = '<img src=\'https://huggingface.co/front/assets/huggingface_logo.svg\'>' UpperCAmelCase__ : Optional[Any] = '\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class="img-container"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n' % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia UpperCAmelCase__ : str = '\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n' st.sidebar.markdown(description, unsafe_allow_html=True) UpperCAmelCase__ : str = [ 'Answer the question', 'View the retrieved document only', 'View the most similar ELI5 question and answer', 'Show me everything, please!', ] UpperCAmelCase__ : Optional[int] = st.sidebar.checkbox('Demo options') if demo_options: UpperCAmelCase__ : Any = st.sidebar.selectbox( '', action_list, index=3, ) UpperCAmelCase__ : List[str] = action_list.index(action_st) UpperCAmelCase__ : Optional[Any] = st.sidebar.selectbox( '', ['Show full text of passages', 'Show passage section titles'], index=0, ) UpperCAmelCase__ : List[Any] = show_type == 'Show full text of passages' else: UpperCAmelCase__ : Dict = 3 UpperCAmelCase__ : str = True UpperCAmelCase__ : Optional[Any] = st.sidebar.checkbox('Retrieval options') if retrieval_options: UpperCAmelCase__ : List[str] = '\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n ' st.sidebar.markdown(retriever_info) UpperCAmelCase__ : Optional[int] = st.sidebar.selectbox('Which Wikipedia format should the model use?', ['wiki40b', 'none']) UpperCAmelCase__ : int = st.sidebar.selectbox('Which Wikipedia indexer should the model use?', ['dense', 'sparse', 'mixed']) else: UpperCAmelCase__ : Tuple = 'wiki40b' UpperCAmelCase__ : List[Any] = 'dense' UpperCAmelCase__ : Tuple = 'beam' UpperCAmelCase__ : Any = 2 UpperCAmelCase__ : Dict = 64 UpperCAmelCase__ : Any = 256 UpperCAmelCase__ : int = None UpperCAmelCase__ : List[str] = None UpperCAmelCase__ : Optional[int] = st.sidebar.checkbox('Generation options') if generate_options: UpperCAmelCase__ : Any = '\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder\'s output probabilities.\n ' st.sidebar.markdown(generate_info) UpperCAmelCase__ : Optional[int] = st.sidebar.selectbox('Would you like to use beam search or sample an answer?', ['beam', 'sampled']) UpperCAmelCase__ : int = st.sidebar.slider( 'Minimum generation length', min_value=8, max_value=256, value=64, step=8, format=None, key=None ) UpperCAmelCase__ : str = st.sidebar.slider( 'Maximum generation length', min_value=64, max_value=512, value=256, step=16, format=None, key=None ) if sampled == "beam": UpperCAmelCase__ : Tuple = st.sidebar.slider('Beam size', min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: UpperCAmelCase__ : List[Any] = st.sidebar.slider( 'Nucleus sampling p', min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None ) UpperCAmelCase__ : Union[str, Any] = st.sidebar.slider( 'Temperature', min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None ) UpperCAmelCase__ : Optional[int] = None # start main text UpperCAmelCase__ : Any = [ '<MY QUESTION>', 'How do people make chocolate?', 'Why do we get a fever when we are sick?', 'How can different animals perceive different colors?', 'What is natural language processing?', 'What\'s the best way to treat a sunburn?', 'What exactly are vitamins ?', 'How does nuclear energy provide electricity?', 'What\'s the difference between viruses and bacteria?', 'Why are flutes classified as woodwinds when most of them are made out of metal ?', 'Why do people like drinking coffee even though it tastes so bad?', 'What happens when wine ages? How does it make the wine taste better?', 'If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?', 'How can we set a date to the beginning or end of an artistic period? Doesn\'t the change happen gradually?', 'How does New Zealand have so many large bird predators?', ] UpperCAmelCase__ : List[Any] = st.selectbox( 'What would you like to ask? ---- select <MY QUESTION> to enter a new query', questions_list, index=1, ) if question_s == "<MY QUESTION>": UpperCAmelCase__ : Any = st.text_input('Enter your question here:', '') else: UpperCAmelCase__ : int = question_s if st.button('Show me!'): if action in [0, 1, 3]: if index_type == "mixed": UpperCAmelCase__ ,UpperCAmelCase__ : Tuple = make_support(question, source=wiki_source, method='dense', n_results=10) UpperCAmelCase__ ,UpperCAmelCase__ : Optional[Any] = make_support(question, source=wiki_source, method='sparse', n_results=10) UpperCAmelCase__ : Dict = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] UpperCAmelCase__ : str = support_list[:10] UpperCAmelCase__ : str = '<P> ' + ' <P> '.join([res[-1] for res in support_list]) else: UpperCAmelCase__ ,UpperCAmelCase__ : List[Any] = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: UpperCAmelCase__ ,UpperCAmelCase__ : Optional[Any] = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == 'sampled'), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown('### The model generated answer is:') st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown('--- \n ### The model is drawing information from the following Wikipedia passages:') for i, res in enumerate(support_list): UpperCAmelCase__ : Any = 'https://en.wikipedia.org/wiki/{}'.format(res[0].replace(' ', '_')) UpperCAmelCase__ : Tuple = res[1].strip() if sec_titles == "": UpperCAmelCase__ : Optional[int] = '[{}]({})'.format(res[0], wiki_url) else: UpperCAmelCase__ : int = sec_titles.split(' & ') UpperCAmelCase__ : Union[str, Any] = ' & '.join( ['[{}]({}#{})'.format(sec.strip(), wiki_url, sec.strip().replace(' ', '_')) for sec in sec_list] ) st.markdown( '{0:02d} - **Article**: {1:<18} <br> _Section_: {2}'.format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( '> <span style="font-family:arial; font-size:10pt;">' + res[-1] + '</span>', unsafe_allow_html=True ) if action in [2, 3]: UpperCAmelCase__ : Union[str, Any] = find_nearest_training(question) UpperCAmelCase__ : int = nn_train_list[0] st.markdown( '--- \n ### The most similar question in the ELI5 training set was: \n\n {}'.format(train_exple['title']) ) UpperCAmelCase__ : Tuple = [ '{}. {}'.format(i + 1, ' \n'.join([line.strip() for line in ans.split('\n') if line.strip() != ''])) for i, (ans, sc) in enumerate(zip(train_exple['answers']['text'], train_exple['answers']['score'])) if i == 0 or sc > 2 ] st.markdown('##### Its answers were: \n\n {}'.format('\n'.join(answers_st))) UpperCAmelCase__ : Any = '\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n' st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
301
1
import argparse from collections import defaultdict def lowerCamelCase__ ( a , a , a , a , a ) -> Union[str, Any]: _A: Union[str, Any] = f"""{file}_{class_name}_{test_name}""" done_test[_id] += 1 with open(a , '''r''' ) as f: _A: List[Any] = f.readlines() _A: Tuple = f"""class {class_name}(""" _A: Tuple = f"""{4 * ' '}def {test_name}(""" _A: Union[str, Any] = f"""{8 * ' '}{correct_line.split()[0]}""" _A: Any = f"""{16 * ' '}{correct_line.split()[0]}""" _A: List[Any] = False _A: int = False _A: List[str] = False _A: Dict = False _A: Union[str, Any] = 0 _A: Optional[Any] = 0 _A: Dict = [] for line in lines: if line.startswith(a ): _A: Union[str, Any] = True elif in_class and line.startswith(a ): _A: Any = True elif in_class and in_func and (line.startswith(a ) or line.startswith(a )): _A: int = len(line.split(correct_line.split()[0] )[0] ) count += 1 if count == done_test[_id]: _A: List[str] = True if in_class and in_func and in_line: if ")" not in line: continue else: _A: List[str] = True if in_class and in_func and in_line and insert_line: new_lines.append(f"""{spaces * ' '}{correct_line}""" ) _A: List[Any] = False else: new_lines.append(a ) with open(a , '''w''' ) as f: for line in new_lines: f.write(a ) def lowerCamelCase__ ( a , a=None ) -> int: if fail is not None: with open(a , '''r''' ) as f: _A: Dict = {l.strip() for l in f.readlines()} else: _A: Any = None with open(a , '''r''' ) as f: _A: Union[str, Any] = f.readlines() _A: str = defaultdict(a ) for line in correct_lines: _A , _A , _A , _A: Optional[int] = line.split(''';''' ) if test_failures is None or "::".join([file, class_name, test_name] ) in test_failures: overwrite_file(a , a , a , a , a ) if __name__ == "__main__": UpperCAmelCase__ : Optional[int] = argparse.ArgumentParser() parser.add_argument('--correct_filename', help='filename of tests with expected result') parser.add_argument('--fail_filename', help='filename of test failures', type=str, default=None) UpperCAmelCase__ : Optional[int] = parser.parse_args() main(args.correct_filename, args.fail_filename)
301
from __future__ import annotations UpperCAmelCase__ : List[str] = list[list[int]] # assigning initial values to the grid UpperCAmelCase__ : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution UpperCAmelCase__ : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def lowerCamelCase__ ( a , a , a , a ) -> bool: for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def lowerCamelCase__ ( a ) -> tuple[int, int] | None: for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def lowerCamelCase__ ( a ) -> Matrix | None: if location := find_empty_location(a ): _A , _A: Optional[Any] = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(a , a , a , a ): _A: str = digit if sudoku(a ) is not None: return grid _A: Tuple = 0 return None def lowerCamelCase__ ( a ) -> None: for row in grid: for cell in row: print(a , end=''' ''' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('\nExample grid:\n' + '=' * 20) print_solution(example_grid) print('\nExample grid solution:') UpperCAmelCase__ : int = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('Cannot find a solution.')
301
1
def lowerCamelCase__ ( a ) -> int: _A: list[list[int]] = [[0 for _ in range(a )] for _ in range(m + 1 )] for i in range(m + 1 ): _A: Optional[Any] = 1 for n in range(m + 1 ): for k in range(1 , a ): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: UpperCAmelCase__ : Any = int(input('Enter a number: ').strip()) print(partition(n)) except ValueError: print('Please enter a number.') else: try: UpperCAmelCase__ : Any = int(sys.argv[1]) print(partition(n)) except ValueError: print('Please pass a number.')
301
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests UpperCAmelCase__ : str = open # noqa: we just need to have a builtin inside this module to test it properly
301
1
import os def lowerCamelCase__ ( a = "matrix.txt" ) -> int: with open(os.path.join(os.path.dirname(a ) , a ) ) as in_file: _A: List[str] = in_file.read() _A: Dict = [[int(a ) for cell in row.split(''',''' )] for row in data.strip().splitlines()] _A: str = [[0 for cell in row] for row in grid] _A: Tuple = len(grid[0] ) _A: List[str] = [[0 for i in range(a )] for j in range(a )] _A: Union[str, Any] = grid[0][0] for i in range(1 , a ): _A: Any = grid[0][i] + dp[0][i - 1] for i in range(1 , a ): _A: Any = grid[i][0] + dp[i - 1][0] for i in range(1 , a ): for j in range(1 , a ): _A: List[Any] = grid[i][j] + min(dp[i - 1][j] , dp[i][j - 1] ) return dp[-1][-1] if __name__ == "__main__": print(F"""{solution() = }""")
301
import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Optional[Any] , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : List[str]=3 , lowerCAmelCase_ : List[str]=3_2 , lowerCAmelCase_ : Union[str, Any]=3 , lowerCAmelCase_ : int=1_0 , lowerCAmelCase_ : Tuple=[1_0, 2_0, 3_0, 4_0] , lowerCAmelCase_ : Optional[Any]=[1, 1, 2, 1] , lowerCAmelCase_ : Optional[Any]=True , lowerCAmelCase_ : str=True , lowerCAmelCase_ : Optional[Any]="relu" , lowerCAmelCase_ : int=3 , lowerCAmelCase_ : List[Any]=None , ): """simple docstring""" _A: str = parent _A: List[Any] = batch_size _A: Optional[int] = image_size _A: Dict = num_channels _A: str = embeddings_size _A: Any = hidden_sizes _A: Dict = depths _A: Any = is_training _A: int = use_labels _A: Tuple = hidden_act _A: int = num_labels _A: int = scope _A: str = len(lowerCAmelCase_ ) def __magic_name__ ( self : Dict ): """simple docstring""" _A: Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _A: Union[str, Any] = self.get_config() return config, pixel_values def __magic_name__ ( self : str ): """simple docstring""" return RegNetConfig( 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 , image_size=self.image_size , ) def __magic_name__ ( self : str , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : str ): """simple docstring""" _A: str = FlaxRegNetModel(config=lowerCAmelCase_ ) _A: Optional[int] = model(lowerCAmelCase_ ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , ) def __magic_name__ ( self : str , lowerCAmelCase_ : str , lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Union[str, Any] = self.num_labels _A: Union[str, Any] = FlaxRegNetForImageClassification(config=lowerCAmelCase_ ) _A: str = model(lowerCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __magic_name__ ( self : List[Any] ): """simple docstring""" _A: str = self.prepare_config_and_inputs() _A , _A: Optional[int] = config_and_inputs _A: Union[str, Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_flax class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Tuple = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () __UpperCamelCase : Union[str, Any] = False __UpperCamelCase : List[Any] = False __UpperCamelCase : int = False def __magic_name__ ( self : int ): """simple docstring""" _A: int = FlaxRegNetModelTester(self ) _A: Union[str, Any] = ConfigTester(self , config_class=lowerCAmelCase_ , has_text_modality=lowerCAmelCase_ ) def __magic_name__ ( self : str ): """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __magic_name__ ( self : int ): """simple docstring""" return def __magic_name__ ( self : Tuple ): """simple docstring""" _A: int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase_ ) def __magic_name__ ( self : Tuple ): """simple docstring""" _A: Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_ ) @unittest.skip(reason='''RegNet does not use inputs_embeds''' ) def __magic_name__ ( self : str ): """simple docstring""" pass @unittest.skip(reason='''RegNet does not support input and output embeddings''' ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" pass def __magic_name__ ( self : List[Any] ): """simple docstring""" _A , _A: int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A: Union[str, Any] = model_class(lowerCAmelCase_ ) _A: Any = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _A: Any = [*signature.parameters.keys()] _A: Union[str, Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowerCAmelCase_ ) def __magic_name__ ( self : str ): """simple docstring""" def check_hidden_states_output(lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Tuple ): _A: int = model_class(lowerCAmelCase_ ) _A: List[str] = model(**self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ ) ) _A: str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _A: Tuple = self.model_tester.num_stages self.assertEqual(len(lowerCAmelCase_ ) , expected_num_stages + 1 ) _A , _A: List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A: Optional[Any] = True check_hidden_states_output(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _A: int = True check_hidden_states_output(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) def __magic_name__ ( self : Dict ): """simple docstring""" _A , _A: str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): _A: int = self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ ) _A: Union[str, Any] = model_class(lowerCAmelCase_ ) @jax.jit def model_jitted(lowerCAmelCase_ : Optional[Any] , **lowerCAmelCase_ : Optional[Any] ): return model(pixel_values=lowerCAmelCase_ , **lowerCAmelCase_ ) with self.subTest('''JIT Enabled''' ): _A: str = model_jitted(**lowerCAmelCase_ ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): _A: List[Any] = model_jitted(**lowerCAmelCase_ ).to_tuple() self.assertEqual(len(lowerCAmelCase_ ) , len(lowerCAmelCase_ ) ) for jitted_output, output in zip(lowerCAmelCase_ , lowerCAmelCase_ ): self.assertEqual(jitted_output.shape , output.shape ) def lowerCamelCase__ ( ) -> Tuple: _A: List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_flax class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" return AutoImageProcessor.from_pretrained('''facebook/regnet-y-040''' ) if is_vision_available() else None @slow def __magic_name__ ( self : List[str] ): """simple docstring""" _A: List[str] = FlaxRegNetForImageClassification.from_pretrained('''facebook/regnet-y-040''' ) _A: str = self.default_image_processor _A: int = prepare_img() _A: List[Any] = image_processor(images=lowerCAmelCase_ , return_tensors='''np''' ) _A: str = model(**lowerCAmelCase_ ) # verify the logits _A: str = (1, 1_0_0_0) self.assertEqual(outputs.logits.shape , lowerCAmelCase_ ) _A: Tuple = jnp.array([-0.4180, -1.5051, -3.4836] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] , lowerCAmelCase_ , atol=1e-4 ) )
301
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCAmelCase__ : Union[str, Any] = { 'configuration_gpt_bigcode': ['GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GPTBigCodeConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : List[str] = [ 'GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST', 'GPTBigCodeForSequenceClassification', 'GPTBigCodeForTokenClassification', 'GPTBigCodeForCausalLM', 'GPTBigCodeModel', 'GPTBigCodePreTrainedModel', ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys UpperCAmelCase__ : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
301
from __future__ import annotations from bisect import bisect_left from functools import total_ordering from heapq import merge @total_ordering class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def __lt__( self : Dict , lowerCAmelCase_ : Optional[int] ): """simple docstring""" return self[-1] < other[-1] def __eq__( self : int , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" return self[-1] == other[-1] def lowerCamelCase__ ( a ) -> list: _A: list[Stack] = [] # sort into stacks for element in collection: _A: Any = Stack([element] ) _A: Optional[Any] = bisect_left(a , a ) if i != len(a ): stacks[i].append(a ) else: stacks.append(a ) # use a heap-based merge to merge stack efficiently _A: Tuple = merge(*(reversed(a ) for stack in stacks) ) return collection if __name__ == "__main__": UpperCAmelCase__ : Tuple = input('Enter numbers separated by a comma:\n').strip() UpperCAmelCase__ : Optional[Any] = [int(item) for item in user_input.split(',')] print(patience_sort(unsorted))
301
1
from dataclasses import dataclass from typing import Dict, Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .attention_processor import AttentionProcessor, AttnProcessor from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, DiagonalGaussianDistribution, Encoder @dataclass class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : "DiagonalGaussianDistribution" class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Tuple = True @register_to_config def __init__( self : int , lowerCAmelCase_ : int = 3 , lowerCAmelCase_ : int = 3 , lowerCAmelCase_ : Tuple[str] = ("DownEncoderBlock2D",) , lowerCAmelCase_ : Tuple[str] = ("UpDecoderBlock2D",) , lowerCAmelCase_ : Tuple[int] = (6_4,) , lowerCAmelCase_ : int = 1 , lowerCAmelCase_ : str = "silu" , lowerCAmelCase_ : int = 4 , lowerCAmelCase_ : int = 3_2 , lowerCAmelCase_ : int = 3_2 , lowerCAmelCase_ : float = 0.18215 , ): """simple docstring""" super().__init__() # pass init params to Encoder _A: Dict = Encoder( in_channels=lowerCAmelCase_ , out_channels=lowerCAmelCase_ , down_block_types=lowerCAmelCase_ , block_out_channels=lowerCAmelCase_ , layers_per_block=lowerCAmelCase_ , act_fn=lowerCAmelCase_ , norm_num_groups=lowerCAmelCase_ , double_z=lowerCAmelCase_ , ) # pass init params to Decoder _A: Tuple = Decoder( in_channels=lowerCAmelCase_ , out_channels=lowerCAmelCase_ , up_block_types=lowerCAmelCase_ , block_out_channels=lowerCAmelCase_ , layers_per_block=lowerCAmelCase_ , norm_num_groups=lowerCAmelCase_ , act_fn=lowerCAmelCase_ , ) _A: List[Any] = nn.Convad(2 * latent_channels , 2 * latent_channels , 1 ) _A: str = nn.Convad(lowerCAmelCase_ , lowerCAmelCase_ , 1 ) _A: List[Any] = False _A: Tuple = False # only relevant if vae tiling is enabled _A: Optional[Any] = self.config.sample_size _A: Any = ( self.config.sample_size[0] if isinstance(self.config.sample_size , (list, tuple) ) else self.config.sample_size ) _A: str = int(sample_size / (2 ** (len(self.config.block_out_channels ) - 1)) ) _A: Optional[int] = 0.25 def __magic_name__ ( self : List[Any] , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Dict=False ): """simple docstring""" if isinstance(lowerCAmelCase_ , (Encoder, Decoder) ): _A: Optional[int] = value def __magic_name__ ( self : List[str] , lowerCAmelCase_ : bool = True ): """simple docstring""" _A: List[Any] = use_tiling def __magic_name__ ( self : Dict ): """simple docstring""" self.enable_tiling(lowerCAmelCase_ ) def __magic_name__ ( self : str ): """simple docstring""" _A: List[str] = True def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" _A: Tuple = False @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def __magic_name__ ( self : int ): """simple docstring""" _A: Optional[int] = {} def fn_recursive_add_processors(lowerCAmelCase_ : str , lowerCAmelCase_ : torch.nn.Module , lowerCAmelCase_ : Dict[str, AttentionProcessor] ): if hasattr(lowerCAmelCase_ , '''set_processor''' ): _A: str = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(F"""{name}.{sub_name}""" , lowerCAmelCase_ , lowerCAmelCase_ ) return processors for name, module in self.named_children(): fn_recursive_add_processors(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return processors def __magic_name__ ( self : Tuple , lowerCAmelCase_ : Union[AttentionProcessor, Dict[str, AttentionProcessor]] ): """simple docstring""" _A: Optional[Any] = len(self.attn_processors.keys() ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and len(lowerCAmelCase_ ) != count: raise ValueError( F"""A dict of processors was passed, but the number of processors {len(lowerCAmelCase_ )} does not match the""" F""" number of attention layers: {count}. Please make sure to pass {count} processor classes.""" ) def fn_recursive_attn_processor(lowerCAmelCase_ : str , lowerCAmelCase_ : torch.nn.Module , lowerCAmelCase_ : Tuple ): if hasattr(lowerCAmelCase_ , '''set_processor''' ): if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): module.set_processor(lowerCAmelCase_ ) else: module.set_processor(processor.pop(F"""{name}.processor""" ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(F"""{name}.{sub_name}""" , lowerCAmelCase_ , lowerCAmelCase_ ) for name, module in self.named_children(): fn_recursive_attn_processor(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) def __magic_name__ ( self : List[str] ): """simple docstring""" self.set_attn_processor(AttnProcessor() ) @apply_forward_hook def __magic_name__ ( self : Dict , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : bool = True ): """simple docstring""" if self.use_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size): return self.tiled_encode(lowerCAmelCase_ , return_dict=lowerCAmelCase_ ) if self.use_slicing and x.shape[0] > 1: _A: Tuple = [self.encoder(lowerCAmelCase_ ) for x_slice in x.split(1 )] _A: List[str] = torch.cat(lowerCAmelCase_ ) else: _A: Optional[int] = self.encoder(lowerCAmelCase_ ) _A: Tuple = self.quant_conv(lowerCAmelCase_ ) _A: int = DiagonalGaussianDistribution(lowerCAmelCase_ ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=lowerCAmelCase_ ) def __magic_name__ ( self : Any , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : bool = True ): """simple docstring""" if self.use_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size): return self.tiled_decode(lowerCAmelCase_ , return_dict=lowerCAmelCase_ ) _A: int = self.post_quant_conv(lowerCAmelCase_ ) _A: int = self.decoder(lowerCAmelCase_ ) if not return_dict: return (dec,) return DecoderOutput(sample=lowerCAmelCase_ ) @apply_forward_hook def __magic_name__ ( self : Any , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : bool = True ): """simple docstring""" if self.use_slicing and z.shape[0] > 1: _A: Tuple = [self._decode(lowerCAmelCase_ ).sample for z_slice in z.split(1 )] _A: List[Any] = torch.cat(lowerCAmelCase_ ) else: _A: Optional[int] = self._decode(lowerCAmelCase_ ).sample if not return_dict: return (decoded,) return DecoderOutput(sample=lowerCAmelCase_ ) def __magic_name__ ( self : Optional[Any] , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Optional[int] ): """simple docstring""" _A: Dict = min(a.shape[2] , b.shape[2] , lowerCAmelCase_ ) for y in range(lowerCAmelCase_ ): _A: int = a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent) return b def __magic_name__ ( self : Optional[Any] , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : List[str] ): """simple docstring""" _A: Optional[int] = min(a.shape[3] , b.shape[3] , lowerCAmelCase_ ) for x in range(lowerCAmelCase_ ): _A: int = a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent) return b def __magic_name__ ( self : Any , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : bool = True ): """simple docstring""" _A: Optional[Any] = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor) ) _A: Dict = int(self.tile_latent_min_size * self.tile_overlap_factor ) _A: int = self.tile_latent_min_size - blend_extent # Split the image into 512x512 tiles and encode them separately. _A: List[Any] = [] for i in range(0 , x.shape[2] , lowerCAmelCase_ ): _A: str = [] for j in range(0 , x.shape[3] , lowerCAmelCase_ ): _A: List[str] = x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size] _A: List[Any] = self.encoder(lowerCAmelCase_ ) _A: Optional[Any] = self.quant_conv(lowerCAmelCase_ ) row.append(lowerCAmelCase_ ) rows.append(lowerCAmelCase_ ) _A: Any = [] for i, row in enumerate(lowerCAmelCase_ ): _A: str = [] for j, tile in enumerate(lowerCAmelCase_ ): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: _A: int = self.blend_v(rows[i - 1][j] , lowerCAmelCase_ , lowerCAmelCase_ ) if j > 0: _A: int = self.blend_h(row[j - 1] , lowerCAmelCase_ , lowerCAmelCase_ ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(lowerCAmelCase_ , dim=3 ) ) _A: Any = torch.cat(lowerCAmelCase_ , dim=2 ) _A: Union[str, Any] = DiagonalGaussianDistribution(lowerCAmelCase_ ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=lowerCAmelCase_ ) def __magic_name__ ( self : Union[str, Any] , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : bool = True ): """simple docstring""" _A: Optional[Any] = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor) ) _A: List[Any] = int(self.tile_sample_min_size * self.tile_overlap_factor ) _A: List[Any] = self.tile_sample_min_size - blend_extent # Split z into overlapping 64x64 tiles and decode them separately. # The tiles have an overlap to avoid seams between tiles. _A: List[Any] = [] for i in range(0 , z.shape[2] , lowerCAmelCase_ ): _A: str = [] for j in range(0 , z.shape[3] , lowerCAmelCase_ ): _A: str = z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size] _A: Dict = self.post_quant_conv(lowerCAmelCase_ ) _A: int = self.decoder(lowerCAmelCase_ ) row.append(lowerCAmelCase_ ) rows.append(lowerCAmelCase_ ) _A: Union[str, Any] = [] for i, row in enumerate(lowerCAmelCase_ ): _A: List[Any] = [] for j, tile in enumerate(lowerCAmelCase_ ): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: _A: Dict = self.blend_v(rows[i - 1][j] , lowerCAmelCase_ , lowerCAmelCase_ ) if j > 0: _A: Tuple = self.blend_h(row[j - 1] , lowerCAmelCase_ , lowerCAmelCase_ ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(lowerCAmelCase_ , dim=3 ) ) _A: Any = torch.cat(lowerCAmelCase_ , dim=2 ) if not return_dict: return (dec,) return DecoderOutput(sample=lowerCAmelCase_ ) def __magic_name__ ( self : Optional[Any] , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = True , lowerCAmelCase_ : Optional[torch.Generator] = None , ): """simple docstring""" _A: List[Any] = sample _A: Optional[int] = self.encode(lowerCAmelCase_ ).latent_dist if sample_posterior: _A: Optional[int] = posterior.sample(generator=lowerCAmelCase_ ) else: _A: Tuple = posterior.mode() _A: Dict = self.decode(lowerCAmelCase_ ).sample if not return_dict: return (dec,) return DecoderOutput(sample=lowerCAmelCase_ )
301
import argparse import datetime import json import time import warnings from logging import getLogger from pathlib import Path from typing import Dict, List import torch from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils import calculate_bleu, calculate_rouge, chunks, parse_numeric_n_bool_cl_kwargs, use_task_specific_params UpperCAmelCase__ : Any = getLogger(__name__) UpperCAmelCase__ : Optional[Any] = 'cuda' if torch.cuda.is_available() else 'cpu' def lowerCamelCase__ ( a , a , a , a = 8 , a = DEFAULT_DEVICE , a=False , a="summarization" , a=None , **a , ) -> Dict: _A: str = Path(a ).open('''w''' , encoding='''utf-8''' ) _A: Optional[Any] = str(a ) _A: Union[str, Any] = AutoModelForSeqaSeqLM.from_pretrained(a ).to(a ) if fpaa: _A: Any = model.half() _A: Optional[int] = AutoTokenizer.from_pretrained(a ) logger.info(f"""Inferred tokenizer type: {tokenizer.__class__}""" ) # if this is wrong, check config.model_type. _A: Any = time.time() # update config with task specific params use_task_specific_params(a , a ) if prefix is None: _A: int = prefix or getattr(model.config , '''prefix''' , '''''' ) or '''''' for examples_chunk in tqdm(list(chunks(a , a ) ) ): _A: int = [prefix + text for text in examples_chunk] _A: str = tokenizer(a , return_tensors='''pt''' , truncation=a , padding='''longest''' ).to(a ) _A: str = model.generate( input_ids=batch.input_ids , attention_mask=batch.attention_mask , **a , ) _A: str = tokenizer.batch_decode(a , skip_special_tokens=a , clean_up_tokenization_spaces=a ) for hypothesis in dec: fout.write(hypothesis + '''\n''' ) fout.flush() fout.close() _A: Optional[int] = int(time.time() - start_time ) # seconds _A: Union[str, Any] = len(a ) return {"n_obs": n_obs, "runtime": runtime, "seconds_per_sample": round(runtime / n_obs , 4 )} def lowerCamelCase__ ( ) -> Tuple: return datetime.datetime.now().strftime('''%Y-%m-%d %H:%M:%S''' ) def lowerCamelCase__ ( a=True ) -> Optional[Any]: _A: str = argparse.ArgumentParser() parser.add_argument('''model_name''' , type=a , help='''like facebook/bart-large-cnn,t5-base, etc.''' ) parser.add_argument('''input_path''' , type=a , help='''like cnn_dm/test.source''' ) parser.add_argument('''save_path''' , type=a , help='''where to save summaries''' ) parser.add_argument('''--reference_path''' , type=a , required=a , help='''like cnn_dm/test.target''' ) parser.add_argument('''--score_path''' , type=a , required=a , default='''metrics.json''' , help='''where to save metrics''' ) parser.add_argument('''--device''' , type=a , required=a , default=a , help='''cuda, cuda:1, cpu etc.''' ) parser.add_argument( '''--prefix''' , type=a , required=a , default=a , help='''will be added to the begininng of src examples''' ) parser.add_argument('''--task''' , type=a , default='''summarization''' , help='''used for task_specific_params + metrics''' ) parser.add_argument('''--bs''' , type=a , default=8 , required=a , help='''batch size''' ) parser.add_argument( '''--n_obs''' , type=a , default=-1 , required=a , help='''How many observations. Defaults to all.''' ) parser.add_argument('''--fp16''' , action='''store_true''' ) parser.add_argument('''--dump-args''' , action='''store_true''' , help='''print the custom hparams with the results''' ) parser.add_argument( '''--info''' , nargs='''?''' , type=a , const=datetime_now() , help=( '''use in conjunction w/ --dump-args to print with the results whatever other info you\'d like, e.g.''' ''' lang=en-ru. If no value is passed, the current datetime string will be used.''' ) , ) # Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate _A , _A: Tuple = parser.parse_known_args() _A: List[str] = parse_numeric_n_bool_cl_kwargs(a ) if parsed_args and verbose: print(f"""parsed the following generate kwargs: {parsed_args}""" ) _A: int = [''' ''' + x.rstrip() if '''t5''' in args.model_name else x.rstrip() for x in open(args.input_path ).readlines()] if args.n_obs > 0: _A: List[str] = examples[: args.n_obs] Path(args.save_path ).parent.mkdir(exist_ok=a ) if args.reference_path is None and Path(args.score_path ).exists(): warnings.warn(f"""score_path {args.score_path} will be overwritten unless you type ctrl-c.""" ) if args.device == "cpu" and args.fpaa: # this mix leads to RuntimeError: "threshold_cpu" not implemented for 'Half' raise ValueError('''Can\'t mix --fp16 and --device cpu''' ) _A: Dict = generate_summaries_or_translations( a , args.save_path , args.model_name , batch_size=args.bs , device=args.device , fpaa=args.fpaa , task=args.task , prefix=args.prefix , **a , ) if args.reference_path is None: return {} # Compute scores _A: Dict = calculate_bleu if '''translation''' in args.task else calculate_rouge _A: List[Any] = [x.rstrip() for x in open(args.save_path ).readlines()] _A: Any = [x.rstrip() for x in open(args.reference_path ).readlines()][: len(a )] _A: dict = score_fn(a , a ) scores.update(a ) if args.dump_args: scores.update(a ) if args.info: _A: Optional[Any] = args.info if verbose: print(a ) if args.score_path is not None: json.dump(a , open(args.score_path , '''w''' ) ) return scores if __name__ == "__main__": # Usage for MT: # python run_eval.py MODEL_NAME $DATA_DIR/test.source $save_dir/test_translations.txt --reference_path $DATA_DIR/test.target --score_path $save_dir/test_bleu.json --task translation $@ run_generate(verbose=True)
301
1
import os def lowerCamelCase__ ( a ) -> List[str]: _A: Dict = len(grid[0] ) _A: Union[str, Any] = len(a ) _A: int = 0 _A: int = 0 _A: Dict = 0 # Check vertically, horizontally, diagonally at the same time (only works # for nxn grid) for i in range(a ): for j in range(n_rows - 3 ): _A: Dict = grid[j][i] * grid[j + 1][i] * grid[j + 2][i] * grid[j + 3][i] _A: str = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3] # Left-to-right diagonal (\) product if i < n_columns - 3: _A: Tuple = ( grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3] ) # Right-to-left diagonal(/) product if i > 2: _A: Optional[int] = ( grid[i][j] * grid[i - 1][j + 1] * grid[i - 2][j + 2] * grid[i - 3][j + 3] ) _A: Optional[Any] = max( a , a , a , a ) if max_product > largest: _A: str = max_product return largest def lowerCamelCase__ ( ) -> Optional[Any]: _A: Optional[Any] = [] with open(os.path.dirname(a ) + '''/grid.txt''' ) as file: for line in file: grid.append(line.strip('''\n''' ).split(''' ''' ) ) _A: Any = [[int(a ) for i in grid[j]] for j in range(len(a ) )] return largest_product(a ) if __name__ == "__main__": print(solution())
301
import math import random from typing import Any from .hill_climbing import SearchProblem def lowerCamelCase__ ( a , a = True , a = math.inf , a = -math.inf , a = math.inf , a = -math.inf , a = False , a = 1_00 , a = 0.01 , a = 1 , ) -> Any: _A: Optional[Any] = False _A: Dict = search_prob _A: str = start_temperate _A: Optional[int] = [] _A: int = 0 _A: Dict = None while not search_end: _A: Dict = current_state.score() if best_state is None or current_score > best_state.score(): _A: List[Any] = current_state scores.append(a ) iterations += 1 _A: List[str] = None _A: str = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to _A: Any = random.randint(0 , len(a ) - 1 ) # picking a random neighbor _A: Union[str, Any] = neighbors.pop(a ) _A: List[str] = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: _A: Optional[Any] = change * -1 # in case we are finding minimum if change > 0: # improves the solution _A: str = picked_neighbor else: _A: Tuple = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability _A: Optional[int] = picked_neighbor _A: Dict = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor _A: Any = True else: _A: List[Any] = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(a ) , a ) plt.xlabel('''Iterations''' ) plt.ylabel('''Function values''' ) plt.show() return best_state if __name__ == "__main__": def lowerCamelCase__ ( a , a ) -> Optional[Any]: return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) UpperCAmelCase__ : Optional[int] = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) UpperCAmelCase__ : Optional[Any] = simulated_annealing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( 'The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) # starting the problem with initial coordinates (12, 47) UpperCAmelCase__ : Optional[Any] = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) UpperCAmelCase__ : List[str] = simulated_annealing( prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( 'The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) def lowerCamelCase__ ( a , a ) -> Optional[Any]: return (3 * x**2) - (6 * y) UpperCAmelCase__ : Union[str, Any] = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) UpperCAmelCase__ : List[str] = simulated_annealing(prob, find_max=False, visualization=True) print( 'The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ' F"""{local_min.score()}""" ) UpperCAmelCase__ : Optional[Any] = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) UpperCAmelCase__ : List[Any] = simulated_annealing(prob, find_max=True, visualization=True) print( 'The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ' F"""{local_min.score()}""" )
301
1
from typing import TYPE_CHECKING from ...utils import _LazyModule UpperCAmelCase__ : int = {'tokenization_byt5': ['ByT5Tokenizer']} if TYPE_CHECKING: from .tokenization_byta import ByTaTokenizer else: import sys UpperCAmelCase__ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
301
import json import os from typing import Dict, List, Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase__ : List[Any] = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } UpperCAmelCase__ : Tuple = { '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__ : Optional[int] = {'facebook/blenderbot_small-90M': 512} def lowerCamelCase__ ( a ) -> Optional[Any]: _A: List[Any] = set() _A: List[Any] = word[0] for char in word[1:]: pairs.add((prev_char, char) ) _A: List[Any] = char _A: Union[str, Any] = set(a ) return pairs class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : str = VOCAB_FILES_NAMES __UpperCamelCase : List[Any] = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase : Union[str, Any] = ['''input_ids''', '''attention_mask'''] def __init__( self : int , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : List[str]="__start__" , lowerCAmelCase_ : Any="__end__" , lowerCAmelCase_ : Any="__unk__" , lowerCAmelCase_ : Any="__null__" , **lowerCAmelCase_ : int , ): """simple docstring""" super().__init__(unk_token=lowerCAmelCase_ , bos_token=lowerCAmelCase_ , eos_token=lowerCAmelCase_ , pad_token=lowerCAmelCase_ , **lowerCAmelCase_ ) with open(lowerCAmelCase_ , encoding='''utf-8''' ) as vocab_handle: _A: Optional[int] = json.load(lowerCAmelCase_ ) _A: int = {v: k for k, v in self.encoder.items()} with open(lowerCAmelCase_ , encoding='''utf-8''' ) as merges_handle: _A: Dict = merges_handle.read().split('''\n''' )[1:-1] _A: int = [tuple(merge.split() ) for merge in merges] _A: Dict = dict(zip(lowerCAmelCase_ , range(len(lowerCAmelCase_ ) ) ) ) _A: Union[str, Any] = {} @property def __magic_name__ ( self : Optional[int] ): """simple docstring""" return len(self.encoder ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def __magic_name__ ( self : str , lowerCAmelCase_ : str ): """simple docstring""" if token in self.cache: return self.cache[token] _A: List[Any] = re.sub('''([.,!?()])''' , R''' \1''' , lowerCAmelCase_ ) _A: List[Any] = re.sub('''(\')''' , R''' \1 ''' , lowerCAmelCase_ ) _A: List[Any] = re.sub(R'''\s{2,}''' , ''' ''' , lowerCAmelCase_ ) if "\n" in token: _A: Dict = token.replace('''\n''' , ''' __newln__''' ) _A: Any = token.split(''' ''' ) _A: Optional[Any] = [] for token in tokens: if not len(lowerCAmelCase_ ): continue _A: str = token.lower() _A: List[str] = tuple(lowerCAmelCase_ ) _A: str = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] ) _A: Dict = get_pairs(lowerCAmelCase_ ) if not pairs: words.append(lowerCAmelCase_ ) continue while True: _A: str = min(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : self.bpe_ranks.get(lowerCAmelCase_ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break _A , _A: Optional[int] = bigram _A: str = [] _A: Dict = 0 while i < len(lowerCAmelCase_ ): try: _A: List[Any] = word.index(lowerCAmelCase_ , lowerCAmelCase_ ) new_word.extend(word[i:j] ) _A: Optional[int] = j except ValueError: new_word.extend(word[i:] ) break if word[i] == first and i < len(lowerCAmelCase_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 _A: Union[str, Any] = tuple(lowerCAmelCase_ ) _A: Tuple = new_word if len(lowerCAmelCase_ ) == 1: break else: _A: Optional[int] = get_pairs(lowerCAmelCase_ ) _A: str = '''@@ '''.join(lowerCAmelCase_ ) _A: Tuple = word[:-4] _A: List[Any] = word words.append(lowerCAmelCase_ ) return " ".join(lowerCAmelCase_ ) def __magic_name__ ( self : str , lowerCAmelCase_ : str ): """simple docstring""" _A: List[Any] = [] _A: List[Any] = re.findall(R'''\S+\n?''' , lowerCAmelCase_ ) for token in words: split_tokens.extend(list(self.bpe(lowerCAmelCase_ ).split(''' ''' ) ) ) return split_tokens def __magic_name__ ( self : str , lowerCAmelCase_ : str ): """simple docstring""" _A: List[str] = token.lower() return self.encoder.get(lowerCAmelCase_ , self.encoder.get(self.unk_token ) ) def __magic_name__ ( self : int , lowerCAmelCase_ : int ): """simple docstring""" return self.decoder.get(lowerCAmelCase_ , self.unk_token ) def __magic_name__ ( self : List[str] , lowerCAmelCase_ : List[str] ): """simple docstring""" _A: List[str] = ''' '''.join(lowerCAmelCase_ ).replace('''@@ ''' , '''''' ).strip() return out_string def __magic_name__ ( self : List[Any] , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[str] = None ): """simple docstring""" if not os.path.isdir(lowerCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _A: Dict = os.path.join( lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) _A: Any = os.path.join( lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(lowerCAmelCase_ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=lowerCAmelCase_ , ensure_ascii=lowerCAmelCase_ ) + '''\n''' ) _A: List[str] = 0 with open(lowerCAmelCase_ , '''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 lowerCAmelCase_ : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" ''' Please check that the tokenizer is not corrupted!''' ) _A: Optional[int] = token_index writer.write(''' '''.join(lowerCAmelCase_ ) + '''\n''' ) index += 1 return vocab_file, merge_file
301
1
import math def lowerCamelCase__ ( a , a ) -> float: if initial_intensity < 0: raise ValueError('''The value of intensity cannot be negative''' ) # handling of negative values of initial intensity if angle < 0 or angle > 3_60: raise ValueError('''In Malus Law, the angle is in the range 0-360 degrees''' ) # handling of values out of allowed range return initial_intensity * (math.cos(math.radians(a ) ) ** 2) if __name__ == "__main__": import doctest doctest.testmod(name='malus_law')
301
import os from pathlib import Path def lowerCamelCase__ ( ) -> Optional[Any]: from torch.utils.cpp_extension import load _A: str = Path(a ).resolve().parent.parent.parent / '''kernels''' / '''deformable_detr''' _A: Tuple = [ root / filename for filename in [ '''vision.cpp''', os.path.join('''cpu''' , '''ms_deform_attn_cpu.cpp''' ), os.path.join('''cuda''' , '''ms_deform_attn_cuda.cu''' ), ] ] load( '''MultiScaleDeformableAttention''' , a , with_cuda=a , extra_include_paths=[str(a )] , extra_cflags=['''-DWITH_CUDA=1'''] , extra_cuda_cflags=[ '''-DCUDA_HAS_FP16=1''', '''-D__CUDA_NO_HALF_OPERATORS__''', '''-D__CUDA_NO_HALF_CONVERSIONS__''', '''-D__CUDA_NO_HALF2_OPERATORS__''', ] , ) import MultiScaleDeformableAttention as MSDA return MSDA
301
1
def lowerCamelCase__ ( a = 2_00 ) -> int: _A: Any = [1, 2, 5, 10, 20, 50, 1_00, 2_00] _A: str = [0] * (pence + 1) _A: List[Any] = 1 # base case: 1 way to make 0 pence for coin in coins: for i in range(a , pence + 1 , 1 ): number_of_ways[i] += number_of_ways[i - coin] return number_of_ways[pence] if __name__ == "__main__": assert solution(200) == 73682
301
from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Optional[int] = ['''image_processor''', '''tokenizer'''] __UpperCamelCase : Optional[Any] = '''BlipImageProcessor''' __UpperCamelCase : int = ('''BertTokenizer''', '''BertTokenizerFast''') def __init__( self : Optional[int] , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" _A: Optional[Any] = False super().__init__(lowerCAmelCase_ , lowerCAmelCase_ ) _A: List[Any] = self.image_processor def __call__( self : Optional[Any] , lowerCAmelCase_ : ImageInput = None , lowerCAmelCase_ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , lowerCAmelCase_ : bool = True , lowerCAmelCase_ : Union[bool, str, PaddingStrategy] = False , lowerCAmelCase_ : Union[bool, str, TruncationStrategy] = None , lowerCAmelCase_ : Optional[int] = None , lowerCAmelCase_ : int = 0 , lowerCAmelCase_ : Optional[int] = None , lowerCAmelCase_ : Optional[bool] = None , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = True , lowerCAmelCase_ : Optional[Union[str, TensorType]] = None , **lowerCAmelCase_ : Union[str, Any] , ): """simple docstring""" if images is None and text is None: raise ValueError('''You have to specify either images or text.''' ) # Get only text if images is None: _A: Tuple = self.tokenizer _A: Optional[int] = self.tokenizer( text=lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ , padding=lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ , stride=lowerCAmelCase_ , pad_to_multiple_of=lowerCAmelCase_ , return_attention_mask=lowerCAmelCase_ , return_overflowing_tokens=lowerCAmelCase_ , return_special_tokens_mask=lowerCAmelCase_ , return_offsets_mapping=lowerCAmelCase_ , return_token_type_ids=lowerCAmelCase_ , return_length=lowerCAmelCase_ , verbose=lowerCAmelCase_ , return_tensors=lowerCAmelCase_ , **lowerCAmelCase_ , ) return text_encoding # add pixel_values _A: List[Any] = self.image_processor(lowerCAmelCase_ , return_tensors=lowerCAmelCase_ ) if text is not None: _A: Tuple = self.tokenizer( text=lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ , padding=lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ , stride=lowerCAmelCase_ , pad_to_multiple_of=lowerCAmelCase_ , return_attention_mask=lowerCAmelCase_ , return_overflowing_tokens=lowerCAmelCase_ , return_special_tokens_mask=lowerCAmelCase_ , return_offsets_mapping=lowerCAmelCase_ , return_token_type_ids=lowerCAmelCase_ , return_length=lowerCAmelCase_ , verbose=lowerCAmelCase_ , return_tensors=lowerCAmelCase_ , **lowerCAmelCase_ , ) else: _A: str = None if text_encoding is not None: encoding_image_processor.update(lowerCAmelCase_ ) return encoding_image_processor def __magic_name__ ( self : Optional[Any] , *lowerCAmelCase_ : Union[str, Any] , **lowerCAmelCase_ : Tuple ): """simple docstring""" return self.tokenizer.batch_decode(*lowerCAmelCase_ , **lowerCAmelCase_ ) def __magic_name__ ( self : Union[str, Any] , *lowerCAmelCase_ : int , **lowerCAmelCase_ : Optional[int] ): """simple docstring""" return self.tokenizer.decode(*lowerCAmelCase_ , **lowerCAmelCase_ ) @property def __magic_name__ ( self : Dict ): """simple docstring""" _A: Dict = self.tokenizer.model_input_names _A: List[str] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
301
1
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() UpperCAmelCase__ : List[Any] = logging.get_logger(__name__) UpperCAmelCase__ : Union[str, Any] = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.linear_k': 'encoder.layers.*.self_attn.linear_k', 'self_attn.linear_v': 'encoder.layers.*.self_attn.linear_v', 'self_attn.linear_q': 'encoder.layers.*.self_attn.linear_q', 'self_attn.pos_bias_u': 'encoder.layers.*.self_attn.pos_bias_u', 'self_attn.pos_bias_v': 'encoder.layers.*.self_attn.pos_bias_v', 'self_attn.linear_out': 'encoder.layers.*.self_attn.linear_out', 'self_attn.linear_pos': 'encoder.layers.*.self_attn.linear_pos', 'self_attn.rotary_emb': 'encoder.embed_positions', 'self_attn_layer_norm': 'encoder.layers.*.self_attn_layer_norm', 'conv_module.pointwise_conv1': 'encoder.layers.*.conv_module.pointwise_conv1', 'conv_module.pointwise_conv2': 'encoder.layers.*.conv_module.pointwise_conv2', 'conv_module.depthwise_conv': 'encoder.layers.*.conv_module.depthwise_conv', 'conv_module.batch_norm': 'encoder.layers.*.conv_module.batch_norm', 'conv_module.layer_norm': 'encoder.layers.*.conv_module.layer_norm', 'ffn1.w_1': 'encoder.layers.*.ffn1.intermediate_dense', 'ffn1.w_2': 'encoder.layers.*.ffn1.output_dense', 'ffn1.layer_norm': 'encoder.layers.*.ffn1_layer_norm', 'ffn2.w_1': 'encoder.layers.*.ffn2.intermediate_dense', 'ffn2.w_2': 'encoder.layers.*.ffn2.output_dense', 'ffn2.layer_norm': 'encoder.layers.*.ffn2_layer_norm', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', } UpperCAmelCase__ : Any = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', ] def lowerCamelCase__ ( a , a , a , a , a ) -> Optional[int]: for attribute in key.split('''.''' ): _A: Optional[Any] = getattr(a , a ) if weight_type is not None: _A: List[Any] = getattr(a , a ).shape else: _A: Dict = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": _A: List[Any] = value elif weight_type == "weight_g": _A: List[Any] = value elif weight_type == "weight_v": _A: Optional[Any] = value elif weight_type == "bias": _A: Optional[Any] = value elif weight_type == "running_mean": _A: Tuple = value elif weight_type == "running_var": _A: List[Any] = value elif weight_type == "num_batches_tracked": _A: List[str] = value elif weight_type == "inv_freq": _A: Any = value else: _A: str = value logger.info(f"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" ) def lowerCamelCase__ ( a , a , a ) -> int: _A: Any = [] _A: Optional[int] = fairseq_model.state_dict() _A: Tuple = hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): _A: Dict = False if "conv_layers" in name: load_conv_layer( a , a , a , a , hf_model.config.feat_extract_norm == '''group''' , ) _A: str = True else: for key, mapped_key in MAPPING.items(): _A: int = '''wav2vec2_conformer.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: _A: int = True if "*" in mapped_key: _A: List[Any] = name.split(a )[0].split('''.''' )[-2] _A: List[Any] = mapped_key.replace('''*''' , a ) if "pos_bias_u" in name: _A: Dict = None elif "pos_bias_v" in name: _A: Tuple = None elif "weight_g" in name: _A: str = '''weight_g''' elif "weight_v" in name: _A: Union[str, Any] = '''weight_v''' elif "bias" in name: _A: int = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj _A: Optional[int] = '''weight''' elif "running_mean" in name: _A: int = '''running_mean''' elif "inv_freq" in name: _A: Optional[int] = '''inv_freq''' elif "running_var" in name: _A: Dict = '''running_var''' elif "num_batches_tracked" in name: _A: Any = '''num_batches_tracked''' else: _A: List[str] = None set_recursively(a , a , a , a , a ) continue if not is_used: unused_weights.append(a ) logger.warning(f"""Unused weights: {unused_weights}""" ) def lowerCamelCase__ ( a , a , a , a , a ) -> List[str]: _A: Optional[Any] = full_name.split('''conv_layers.''' )[-1] _A: Tuple = name.split('''.''' ) _A: Dict = int(items[0] ) _A: int = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) _A: List[Any] = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) _A: str = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" ) _A: Tuple = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" ) _A: int = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(a ) @torch.no_grad() def lowerCamelCase__ ( a , a , a=None , a=None , a=True ) -> Any: if config_path is not None: _A: Union[str, Any] = WavaVecaConformerConfig.from_pretrained(a , hidden_act='''swish''' ) else: _A: Any = WavaVecaConformerConfig() if "rope" in checkpoint_path: _A: List[str] = '''rotary''' if is_finetuned: if dict_path: _A: Optional[int] = Dictionary.load(a ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq _A: Optional[Any] = target_dict.pad_index _A: List[str] = target_dict.bos_index _A: str = target_dict.eos_index _A: Any = len(target_dict.symbols ) _A: Optional[int] = os.path.join(a , '''vocab.json''' ) if not os.path.isdir(a ): logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(a ) ) return os.makedirs(a , exist_ok=a ) _A: Optional[Any] = target_dict.indices # fairseq has the <pad> and <s> switched _A: Optional[Any] = 0 _A: Dict = 1 with open(a , '''w''' , encoding='''utf-8''' ) as vocab_handle: json.dump(a , a ) _A: List[Any] = WavaVecaCTCTokenizer( a , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='''|''' , do_lower_case=a , ) _A: List[str] = True if config.feat_extract_norm == '''layer''' else False _A: Optional[int] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=a , return_attention_mask=a , ) _A: Dict = WavaVecaProcessor(feature_extractor=a , tokenizer=a ) processor.save_pretrained(a ) _A: int = WavaVecaConformerForCTC(a ) else: _A: Optional[Any] = WavaVecaConformerForPreTraining(a ) if is_finetuned: _A , _A , _A: Optional[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) else: _A: List[Any] = argparse.Namespace(task='''audio_pretraining''' ) _A: Tuple = fairseq.tasks.setup_task(a ) _A , _A , _A: Optional[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=a ) _A: Dict = model[0].eval() recursively_load_weights(a , a , not is_finetuned ) hf_wavavec.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase__ : int = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) UpperCAmelCase__ : Optional[Any] = parser.parse_args() convert_wavaveca_conformer_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
301
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : Union[str, Any] = { 'google/mobilenet_v1_1.0_224': 'https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json', 'google/mobilenet_v1_0.75_192': 'https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 } class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Optional[int] = '''mobilenet_v1''' def __init__( self : Optional[int] , lowerCAmelCase_ : Any=3 , lowerCAmelCase_ : str=2_2_4 , lowerCAmelCase_ : List[str]=1.0 , lowerCAmelCase_ : Any=8 , lowerCAmelCase_ : Tuple="relu6" , lowerCAmelCase_ : List[Any]=True , lowerCAmelCase_ : Optional[int]=0.999 , lowerCAmelCase_ : List[str]=0.02 , lowerCAmelCase_ : List[Any]=0.001 , **lowerCAmelCase_ : Optional[Any] , ): """simple docstring""" super().__init__(**lowerCAmelCase_ ) if depth_multiplier <= 0: raise ValueError('''depth_multiplier must be greater than zero.''' ) _A: Any = num_channels _A: Optional[int] = image_size _A: Optional[Any] = depth_multiplier _A: Tuple = min_depth _A: Any = hidden_act _A: Dict = tf_padding _A: List[Any] = classifier_dropout_prob _A: Tuple = initializer_range _A: Tuple = layer_norm_eps class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Dict = version.parse('''1.11''' ) @property def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" return OrderedDict([('''pixel_values''', {0: '''batch'''})] ) @property def __magic_name__ ( self : Optional[Any] ): """simple docstring""" if self.task == "image-classification": return OrderedDict([('''logits''', {0: '''batch'''})] ) else: return OrderedDict([('''last_hidden_state''', {0: '''batch'''}), ('''pooler_output''', {0: '''batch'''})] ) @property def __magic_name__ ( self : Dict ): """simple docstring""" return 1e-4
301
1
def lowerCamelCase__ ( a ) -> str: if number > 0: raise ValueError('''input must be a negative integer''' ) _A: str = len(bin(a )[3:] ) _A: str = bin(abs(a ) - (1 << binary_number_length) )[3:] _A: List[Any] = ( ( '''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()
301
import argparse import json import os from tensorflow.core.protobuf.saved_model_pba import SavedModel # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py UpperCAmelCase__ : Any = '.' # Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model) UpperCAmelCase__ : Optional[Any] = [ 'Assert', 'AssignVariableOp', 'EmptyTensorList', 'MergeV2Checkpoints', 'ReadVariableOp', 'ResourceGather', 'RestoreV2', 'SaveV2', 'ShardedFilename', 'StatefulPartitionedCall', 'StaticRegexFullMatch', 'VarHandleOp', ] def lowerCamelCase__ ( a , a , a ) -> Union[str, Any]: _A: Optional[int] = SavedModel() _A: int = [] with open(os.path.join(a , '''utils''' , '''tf_ops''' , '''onnx.json''' ) ) as f: _A: List[Any] = json.load(a )['''opsets'''] for i in range(1 , opset + 1 ): onnx_ops.extend(onnx_opsets[str(a )] ) with open(a , '''rb''' ) as f: saved_model.ParseFromString(f.read() ) _A: Optional[Any] = set() # Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs) for meta_graph in saved_model.meta_graphs: # Add operations in the graph definition model_op_names.update(node.op for node in meta_graph.graph_def.node ) # Go through the functions in the graph definition for func in meta_graph.graph_def.library.function: # Add operations in each function model_op_names.update(node.op for node in func.node_def ) # Convert to list, sorted if you want _A: Optional[int] = sorted(a ) _A: Tuple = [] for op in model_op_names: if op not in onnx_ops and op not in INTERNAL_OPS: incompatible_ops.append(a ) if strict and len(a ) > 0: raise Exception(f"""Found the following incompatible ops for the opset {opset}:\n""" + incompatible_ops ) elif len(a ) > 0: print(f"""Found the following incompatible ops for the opset {opset}:""" ) print(*a , sep='''\n''' ) else: print(f"""The saved model {saved_model_path} can properly be converted with ONNX.""" ) if __name__ == "__main__": UpperCAmelCase__ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument('--saved_model_path', help='Path of the saved model to check (the .pb file).') parser.add_argument( '--opset', default=12, type=int, help='The ONNX opset against which the model has to be tested.' ) parser.add_argument( '--framework', choices=['onnx'], default='onnx', help='Frameworks against which to test the saved model.' ) parser.add_argument( '--strict', action='store_true', help='Whether make the checking strict (raise errors) or not (raise warnings)' ) UpperCAmelCase__ : int = parser.parse_args() if args.framework == "onnx": onnx_compliancy(args.saved_model_path, args.strict, args.opset)
301
1
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : List[str] = { 'BridgeTower/bridgetower-base': 'https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json', 'BridgeTower/bridgetower-base-itm-mlm': ( 'https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json' ), } class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Dict = '''bridgetower_vision_model''' def __init__( self : Optional[int] , lowerCAmelCase_ : Tuple=7_6_8 , lowerCAmelCase_ : int=1_2 , lowerCAmelCase_ : List[str]=3 , lowerCAmelCase_ : List[Any]=1_6 , lowerCAmelCase_ : str=2_8_8 , lowerCAmelCase_ : List[Any]=1 , lowerCAmelCase_ : int=1e-05 , lowerCAmelCase_ : Any=False , lowerCAmelCase_ : Union[str, Any]=True , lowerCAmelCase_ : List[Any]=False , **lowerCAmelCase_ : Dict , ): """simple docstring""" super().__init__(**lowerCAmelCase_ ) _A: Union[str, Any] = hidden_size _A: Dict = num_hidden_layers _A: Optional[Any] = num_channels _A: Optional[Any] = patch_size _A: List[Any] = image_size _A: Tuple = initializer_factor _A: Optional[Any] = layer_norm_eps _A: List[Any] = stop_gradient _A: Optional[Any] = share_layernorm _A: Union[str, Any] = remove_last_layer @classmethod def __magic_name__ ( cls : int , lowerCAmelCase_ : Union[str, os.PathLike] , **lowerCAmelCase_ : List[str] ): """simple docstring""" _A , _A: Optional[Any] = cls.get_config_dict(lowerCAmelCase_ , **lowerCAmelCase_ ) if config_dict.get('''model_type''' ) == "bridgetower": _A: Tuple = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(lowerCAmelCase_ , **lowerCAmelCase_ ) class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : List[Any] = '''bridgetower_text_model''' def __init__( self : Optional[Any] , lowerCAmelCase_ : Tuple=5_0_2_6_5 , lowerCAmelCase_ : List[Any]=7_6_8 , lowerCAmelCase_ : Optional[int]=1_2 , lowerCAmelCase_ : Optional[int]=1_2 , lowerCAmelCase_ : Union[str, Any]=1 , lowerCAmelCase_ : Any=3_0_7_2 , lowerCAmelCase_ : Tuple="gelu" , lowerCAmelCase_ : Any=0.1 , lowerCAmelCase_ : List[str]=0.1 , lowerCAmelCase_ : Optional[Any]=5_1_4 , lowerCAmelCase_ : Any=1 , lowerCAmelCase_ : Optional[int]=1e-05 , lowerCAmelCase_ : Dict=1 , lowerCAmelCase_ : Any=0 , lowerCAmelCase_ : Optional[int]=2 , lowerCAmelCase_ : str="absolute" , lowerCAmelCase_ : str=True , **lowerCAmelCase_ : Union[str, Any] , ): """simple docstring""" super().__init__(**lowerCAmelCase_ ) _A: Optional[int] = vocab_size _A: Optional[Any] = hidden_size _A: List[Any] = num_hidden_layers _A: Optional[int] = num_attention_heads _A: Any = hidden_act _A: Optional[Any] = initializer_factor _A: Union[str, Any] = intermediate_size _A: List[Any] = hidden_dropout_prob _A: Union[str, Any] = attention_probs_dropout_prob _A: Dict = max_position_embeddings _A: Union[str, Any] = type_vocab_size _A: str = layer_norm_eps _A: Union[str, Any] = position_embedding_type _A: str = use_cache _A: Union[str, Any] = pad_token_id _A: Dict = bos_token_id _A: Union[str, Any] = eos_token_id @classmethod def __magic_name__ ( cls : Tuple , lowerCAmelCase_ : Union[str, os.PathLike] , **lowerCAmelCase_ : Tuple ): """simple docstring""" _A , _A: Dict = cls.get_config_dict(lowerCAmelCase_ , **lowerCAmelCase_ ) if config_dict.get('''model_type''' ) == "bridgetower": _A: str = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(lowerCAmelCase_ , **lowerCAmelCase_ ) class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Tuple = '''bridgetower''' def __init__( self : Dict , lowerCAmelCase_ : List[Any]=True , lowerCAmelCase_ : Union[str, Any]="gelu" , lowerCAmelCase_ : int=7_6_8 , lowerCAmelCase_ : int=1 , lowerCAmelCase_ : Dict=1e-05 , lowerCAmelCase_ : str=False , lowerCAmelCase_ : List[str]="add" , lowerCAmelCase_ : Tuple=1_2 , lowerCAmelCase_ : Tuple=6 , lowerCAmelCase_ : Union[str, Any]=False , lowerCAmelCase_ : Optional[int]=False , lowerCAmelCase_ : List[str]=None , lowerCAmelCase_ : Tuple=None , **lowerCAmelCase_ : Any , ): """simple docstring""" # TODO: remove this once the Hub files are updated. _A: List[Any] = kwargs.pop('''text_config_dict''' , lowerCAmelCase_ ) _A: str = kwargs.pop('''vision_config_dict''' , lowerCAmelCase_ ) super().__init__(**lowerCAmelCase_ ) _A: str = share_cross_modal_transformer_layers _A: str = hidden_act _A: int = hidden_size _A: Optional[int] = initializer_factor _A: str = layer_norm_eps _A: int = share_link_tower_layers _A: List[Any] = link_tower_type _A: List[str] = num_attention_heads _A: str = num_hidden_layers _A: Any = tie_word_embeddings _A: str = init_layernorm_from_vision_encoder if text_config is None: _A: int = {} logger.info('''`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values.''' ) if vision_config is None: _A: Tuple = {} logger.info('''`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values.''' ) _A: Tuple = BridgeTowerTextConfig(**lowerCAmelCase_ ) _A: Optional[Any] = BridgeTowerVisionConfig(**lowerCAmelCase_ ) @classmethod def __magic_name__ ( cls : List[Any] , lowerCAmelCase_ : BridgeTowerTextConfig , lowerCAmelCase_ : BridgeTowerVisionConfig , **lowerCAmelCase_ : List[str] ): """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **lowerCAmelCase_ ) def __magic_name__ ( self : Dict ): """simple docstring""" _A: Union[str, Any] = copy.deepcopy(self.__dict__ ) _A: Any = self.text_config.to_dict() _A: List[Any] = self.vision_config.to_dict() _A: Any = self.__class__.model_type return output
301
import json import os from typing import Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ : int = logging.get_logger(__name__) UpperCAmelCase__ : Union[str, Any] = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', } UpperCAmelCase__ : str = { '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__ : Dict = { 'ctrl': 256, } UpperCAmelCase__ : Any = { 'Pregnancy': 168629, 'Christianity': 7675, 'Explain': 106423, 'Fitness': 63440, 'Saving': 63163, 'Ask': 27171, 'Ass': 95985, 'Joke': 163509, 'Questions': 45622, 'Thoughts': 49605, 'Retail': 52342, 'Feminism': 164338, 'Writing': 11992, 'Atheism': 192263, 'Netflix': 48616, 'Computing': 39639, 'Opinion': 43213, 'Alone': 44967, 'Funny': 58917, 'Gaming': 40358, 'Human': 4088, 'India': 1331, 'Joker': 77138, 'Diet': 36206, 'Legal': 11859, 'Norman': 4939, 'Tip': 72689, 'Weight': 52343, 'Movies': 46273, 'Running': 23425, 'Science': 2090, 'Horror': 37793, 'Confession': 60572, 'Finance': 12250, 'Politics': 16360, 'Scary': 191985, 'Support': 12654, 'Technologies': 32516, 'Teenage': 66160, 'Event': 32769, 'Learned': 67460, 'Notion': 182770, 'Wikipedia': 37583, 'Books': 6665, 'Extract': 76050, 'Confessions': 102701, 'Conspiracy': 75932, 'Links': 63674, 'Narcissus': 150425, 'Relationship': 54766, 'Relationships': 134796, 'Reviews': 41671, 'News': 4256, 'Translation': 26820, 'multilingual': 128406, } def lowerCamelCase__ ( a ) -> Optional[Any]: _A: Optional[int] = set() _A: Dict = word[0] for char in word[1:]: pairs.add((prev_char, char) ) _A: Any = char _A: Dict = set(a ) return pairs class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Any = VOCAB_FILES_NAMES __UpperCamelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase : Optional[int] = CONTROL_CODES def __init__( self : Dict , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[Any]="<unk>" , **lowerCAmelCase_ : Optional[int] ): """simple docstring""" super().__init__(unk_token=lowerCAmelCase_ , **lowerCAmelCase_ ) with open(lowerCAmelCase_ , encoding='''utf-8''' ) as vocab_handle: _A: str = json.load(lowerCAmelCase_ ) _A: List[Any] = {v: k for k, v in self.encoder.items()} with open(lowerCAmelCase_ , encoding='''utf-8''' ) as merges_handle: _A: int = merges_handle.read().split('''\n''' )[1:-1] _A: List[Any] = [tuple(merge.split() ) for merge in merges] _A: List[str] = dict(zip(lowerCAmelCase_ , range(len(lowerCAmelCase_ ) ) ) ) _A: Union[str, Any] = {} @property def __magic_name__ ( self : Any ): """simple docstring""" return len(self.encoder ) def __magic_name__ ( self : Dict ): """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def __magic_name__ ( self : List[str] , lowerCAmelCase_ : Tuple ): """simple docstring""" if token in self.cache: return self.cache[token] _A: List[Any] = tuple(lowerCAmelCase_ ) _A: Optional[Any] = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] ) _A: Optional[int] = get_pairs(lowerCAmelCase_ ) if not pairs: return token while True: _A: Optional[int] = min(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : self.bpe_ranks.get(lowerCAmelCase_ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break _A , _A: Any = bigram _A: int = [] _A: int = 0 while i < len(lowerCAmelCase_ ): try: _A: Any = word.index(lowerCAmelCase_ , lowerCAmelCase_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) _A: Optional[int] = j if word[i] == first and i < len(lowerCAmelCase_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 _A: Dict = tuple(lowerCAmelCase_ ) _A: Union[str, Any] = new_word if len(lowerCAmelCase_ ) == 1: break else: _A: Tuple = get_pairs(lowerCAmelCase_ ) _A: Optional[int] = '''@@ '''.join(lowerCAmelCase_ ) _A: List[str] = word[:-4] _A: Optional[Any] = word return word def __magic_name__ ( self : Optional[Any] , lowerCAmelCase_ : Union[str, Any] ): """simple docstring""" _A: List[Any] = [] _A: List[str] = re.findall(R'''\S+\n?''' , lowerCAmelCase_ ) for token in words: split_tokens.extend(list(self.bpe(lowerCAmelCase_ ).split(''' ''' ) ) ) return split_tokens def __magic_name__ ( self : Dict , lowerCAmelCase_ : Optional[int] ): """simple docstring""" return self.encoder.get(lowerCAmelCase_ , self.encoder.get(self.unk_token ) ) def __magic_name__ ( self : Dict , lowerCAmelCase_ : Tuple ): """simple docstring""" return self.decoder.get(lowerCAmelCase_ , self.unk_token ) def __magic_name__ ( self : Any , lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Any = ''' '''.join(lowerCAmelCase_ ).replace('''@@ ''' , '''''' ).strip() return out_string def __magic_name__ ( self : List[str] , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[str] = None ): """simple docstring""" if not os.path.isdir(lowerCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _A: List[str] = os.path.join( lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) _A: List[Any] = os.path.join( lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(lowerCAmelCase_ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=lowerCAmelCase_ , ensure_ascii=lowerCAmelCase_ ) + '''\n''' ) _A: str = 0 with open(lowerCAmelCase_ , '''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 lowerCAmelCase_ : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" ''' Please check that the tokenizer is not corrupted!''' ) _A: Tuple = token_index writer.write(''' '''.join(lowerCAmelCase_ ) + '''\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)
301
1
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 UpperCAmelCase__ : int = 8 def lowerCamelCase__ ( a , a=BITS ) -> Any: _A: Dict = x.device _A: Optional[Any] = (x * 2_55).int().clamp(0 , 2_55 ) _A: Tuple = 2 ** torch.arange(bits - 1 , -1 , -1 , device=a ) _A: Tuple = rearrange(a , '''d -> d 1 1''' ) _A: Dict = rearrange(a , '''b c h w -> b c 1 h w''' ) _A: Tuple = ((x & mask) != 0).float() _A: Union[str, Any] = rearrange(a , '''b c d h w -> b (c d) h w''' ) _A: Union[str, Any] = bits * 2 - 1 return bits def lowerCamelCase__ ( a , a=BITS ) -> Any: _A: str = x.device _A: List[str] = (x > 0).int() _A: Any = 2 ** torch.arange(bits - 1 , -1 , -1 , device=a , dtype=torch.intaa ) _A: List[Any] = rearrange(a , '''d -> d 1 1''' ) _A: int = rearrange(a , '''b (c d) h w -> b c d h w''' , d=8 ) _A: Any = reduce(x * mask , '''b c d h w -> b c h w''' , '''sum''' ) return (dec / 2_55).clamp(0.0 , 1.0 ) def lowerCamelCase__ ( self , a , a , a , a = 0.0 , a = True , a=None , a = 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) _A: List[Any] = timestep - self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas _A: int = self.alphas_cumprod[timestep] _A: Optional[int] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod _A: List[str] = 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 _A: Dict = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 # 4. Clip "predicted x_0" _A: Tuple = self.bit_scale if self.config.clip_sample: _A: str = torch.clamp(a , -scale , a ) # 5. compute variance: "sigma_t(η)" -> see formula (16) # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) _A: str = self._get_variance(a , a ) _A: Union[str, Any] = eta * variance ** 0.5 if use_clipped_model_output: # the model_output is always re-derived from the clipped x_0 in Glide _A: Tuple = (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 _A: Any = (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 _A: 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 _A: Union[str, Any] = model_output.device if torch.is_tensor(a ) else '''cpu''' _A: Dict = torch.randn(model_output.shape , dtype=model_output.dtype , generator=a ).to(a ) _A: Tuple = self._get_variance(a , a ) ** 0.5 * eta * noise _A: Union[str, Any] = prev_sample + variance if not return_dict: return (prev_sample,) return DDIMSchedulerOutput(prev_sample=a , pred_original_sample=a ) def lowerCamelCase__ ( self , a , a , a , a="epsilon" , a=None , a = True , ) -> Union[DDPMSchedulerOutput, Tuple]: _A: int = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]: _A , _A: int = torch.split(a , sample.shape[1] , dim=1 ) else: _A: int = None # 1. compute alphas, betas _A: Any = self.alphas_cumprod[t] _A: List[str] = self.alphas_cumprod[t - 1] if t > 0 else self.one _A: Union[str, Any] = 1 - alpha_prod_t _A: Optional[int] = 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": _A: List[Any] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif prediction_type == "sample": _A: Union[str, Any] = model_output else: raise ValueError(f"""Unsupported prediction_type {prediction_type}.""" ) # 3. Clip "predicted x_0" _A: Tuple = self.bit_scale if self.config.clip_sample: _A: Union[str, Any] = torch.clamp(a , -scale , a ) # 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 _A: Union[str, Any] = (alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t _A: Any = 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 _A: List[str] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise _A: List[str] = 0 if t > 0: _A: Optional[int] = torch.randn( model_output.size() , dtype=model_output.dtype , layout=model_output.layout , generator=a ).to(model_output.device ) _A: Any = (self._get_variance(a , predicted_variance=a ) ** 0.5) * noise _A: Any = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return DDPMSchedulerOutput(prev_sample=a , pred_original_sample=a ) class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def __init__( self : Optional[Any] , lowerCAmelCase_ : UNetaDConditionModel , lowerCAmelCase_ : Union[DDIMScheduler, DDPMScheduler] , lowerCAmelCase_ : Optional[float] = 1.0 , ): """simple docstring""" super().__init__() _A: Tuple = bit_scale _A: Any = ( 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 : Dict , lowerCAmelCase_ : Optional[int] = 2_5_6 , lowerCAmelCase_ : Optional[int] = 2_5_6 , lowerCAmelCase_ : Optional[int] = 5_0 , lowerCAmelCase_ : Optional[torch.Generator] = None , lowerCAmelCase_ : Optional[int] = 1 , lowerCAmelCase_ : Optional[str] = "pil" , lowerCAmelCase_ : bool = True , **lowerCAmelCase_ : Union[str, Any] , ): """simple docstring""" _A: Any = torch.randn( (batch_size, self.unet.config.in_channels, height, width) , generator=lowerCAmelCase_ , ) _A: List[Any] = decimal_to_bits(lowerCAmelCase_ ) * self.bit_scale _A: Any = latents.to(self.device ) self.scheduler.set_timesteps(lowerCAmelCase_ ) for t in self.progress_bar(self.scheduler.timesteps ): # predict the noise residual _A: Dict = self.unet(lowerCAmelCase_ , lowerCAmelCase_ ).sample # compute the previous noisy sample x_t -> x_t-1 _A: Optional[Any] = self.scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ).prev_sample _A: int = bits_to_decimal(lowerCAmelCase_ ) if output_type == "pil": _A: List[str] = self.numpy_to_pil(lowerCAmelCase_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCAmelCase_ )
301
def lowerCamelCase__ ( a = 10 ) -> str: if not isinstance(a , a ) or n < 0: raise ValueError('''Invalid input''' ) _A: int = 10**n _A: List[Any] = 2_84_33 * (pow(2 , 7_83_04_57 , a )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(F"""{solution(10) = }""")
301
1
def lowerCamelCase__ ( a ) -> int: _A: List[str] = hex_num.strip() if not hex_num: raise ValueError('''No value was passed to the function''' ) _A: Any = hex_num[0] == '''-''' if is_negative: _A: Tuple = hex_num[1:] try: _A: Union[str, Any] = int(a , 16 ) except ValueError: raise ValueError('''Invalid value was passed to the function''' ) _A: Optional[int] = '''''' while int_num > 0: _A: str = str(int_num % 2 ) + bin_str int_num >>= 1 return int(('''-''' + bin_str) if is_negative else bin_str ) if __name__ == "__main__": import doctest doctest.testmod()
301
from __future__ import annotations import unittest from transformers import AutoTokenizer, MBartConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel @require_tf class UpperCAmelCase : '''simple docstring''' __UpperCamelCase : Any = MBartConfig __UpperCamelCase : Tuple = {} __UpperCamelCase : Dict = '''gelu''' def __init__( self : Dict , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : List[Any]=1_3 , lowerCAmelCase_ : Dict=7 , lowerCAmelCase_ : Optional[Any]=True , lowerCAmelCase_ : Optional[Any]=False , lowerCAmelCase_ : Union[str, Any]=9_9 , lowerCAmelCase_ : Dict=3_2 , lowerCAmelCase_ : str=2 , lowerCAmelCase_ : int=4 , lowerCAmelCase_ : Union[str, Any]=3_7 , lowerCAmelCase_ : Dict=0.1 , lowerCAmelCase_ : str=0.1 , lowerCAmelCase_ : List[str]=2_0 , lowerCAmelCase_ : str=2 , lowerCAmelCase_ : Optional[int]=1 , lowerCAmelCase_ : List[Any]=0 , ): """simple docstring""" _A: Union[str, Any] = parent _A: List[Any] = batch_size _A: Dict = seq_length _A: Dict = is_training _A: str = use_labels _A: int = vocab_size _A: str = hidden_size _A: Tuple = num_hidden_layers _A: Optional[Any] = num_attention_heads _A: Tuple = intermediate_size _A: int = hidden_dropout_prob _A: Tuple = attention_probs_dropout_prob _A: Tuple = max_position_embeddings _A: Dict = eos_token_id _A: int = pad_token_id _A: Any = bos_token_id def __magic_name__ ( self : Dict ): """simple docstring""" _A: Optional[int] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _A: Dict = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _A: List[Any] = tf.concat([input_ids, eos_tensor] , axis=1 ) _A: Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _A: int = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) _A: Any = prepare_mbart_inputs_dict(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return config, inputs_dict def __magic_name__ ( self : Union[str, Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : List[str] ): """simple docstring""" _A: Tuple = TFMBartModel(config=lowerCAmelCase_ ).get_decoder() _A: List[str] = inputs_dict['''input_ids'''] _A: Tuple = input_ids[:1, :] _A: List[Any] = inputs_dict['''attention_mask'''][:1, :] _A: str = inputs_dict['''head_mask'''] _A: Optional[Any] = 1 # first forward pass _A: Any = model(lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , head_mask=lowerCAmelCase_ , use_cache=lowerCAmelCase_ ) _A , _A: List[str] = outputs.to_tuple() _A: Dict = past_key_values[1] def lowerCamelCase__ ( a , a , a , a=None , a=None , a=None , a=None , a=None , ) -> Tuple: if attention_mask is None: _A: Union[str, Any] = tf.cast(tf.math.not_equal(a , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: _A: Optional[int] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: _A: Tuple = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _A: Union[str, Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: _A: Optional[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Union[str, Any] = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else () __UpperCamelCase : int = (TFMBartForConditionalGeneration,) if is_tf_available() else () __UpperCamelCase : Tuple = ( { '''conversational''': TFMBartForConditionalGeneration, '''feature-extraction''': TFMBartModel, '''summarization''': TFMBartForConditionalGeneration, '''text2text-generation''': TFMBartForConditionalGeneration, '''translation''': TFMBartForConditionalGeneration, } if is_tf_available() else {} ) __UpperCamelCase : List[Any] = True __UpperCamelCase : int = False __UpperCamelCase : Optional[Any] = False def __magic_name__ ( self : int , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : int , lowerCAmelCase_ : str , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : int ): """simple docstring""" if pipeline_test_casse_name != "FeatureExtractionPipelineTests": # Exception encountered when calling layer '...' return True return False def __magic_name__ ( self : Any ): """simple docstring""" _A: Dict = TFMBartModelTester(self ) _A: Tuple = ConfigTester(self , config_class=lowerCAmelCase_ ) def __magic_name__ ( self : List[str] ): """simple docstring""" self.config_tester.run_common_tests() def __magic_name__ ( self : Optional[Any] ): """simple docstring""" _A: str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*lowerCAmelCase_ ) @require_sentencepiece @require_tokenizers @require_tf class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Optional[int] = [ ''' UN Chief Says There Is No Military Solution in Syria''', ] __UpperCamelCase : List[str] = [ '''Şeful ONU declară că nu există o soluţie militară în Siria''', ] __UpperCamelCase : Union[str, Any] = '''facebook/mbart-large-en-ro''' @cached_property def __magic_name__ ( self : Tuple ): """simple docstring""" return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def __magic_name__ ( self : str ): """simple docstring""" _A: Union[str, Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def __magic_name__ ( self : Union[str, Any] , **lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Optional[Any] = self.translate_src_text(**lowerCAmelCase_ ) self.assertListEqual(self.expected_text , lowerCAmelCase_ ) def __magic_name__ ( self : Dict , **lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Any = self.tokenizer(self.src_text , **lowerCAmelCase_ , return_tensors='''tf''' ) _A: Any = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 ) _A: Optional[Any] = self.tokenizer.batch_decode(lowerCAmelCase_ , skip_special_tokens=lowerCAmelCase_ ) return generated_words @slow def __magic_name__ ( self : List[str] ): """simple docstring""" self._assert_generated_batch_equal_expected()
301
1
import argparse import os from pathlib import Path import torch from bark.generation import _load_model as _bark_load_model from huggingface_hub import hf_hub_download from transformers import EncodecConfig, EncodecModel, set_seed from transformers.models.bark.configuration_bark import ( BarkCoarseConfig, BarkConfig, BarkFineConfig, BarkSemanticConfig, ) from transformers.models.bark.generation_configuration_bark import ( BarkCoarseGenerationConfig, BarkFineGenerationConfig, BarkGenerationConfig, BarkSemanticGenerationConfig, ) from transformers.models.bark.modeling_bark import BarkCoarseModel, BarkFineModel, BarkModel, BarkSemanticModel from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase__ : Any = logging.get_logger(__name__) set_seed(770) UpperCAmelCase__ : List[Any] = { 'c_attn': 'att_proj', 'c_proj': 'out_proj', 'c_fc': 'in_proj', 'transformer.': '', 'h.': 'layers.', 'ln_1': 'layernorm_1', 'ln_2': 'layernorm_2', 'ln_f': 'layernorm_final', 'wpe': 'position_embeds_layer', 'wte': 'input_embeds_layer', } UpperCAmelCase__ : Tuple = { 'text_small': { 'repo_id': 'suno/bark', 'file_name': 'text.pt', }, 'coarse_small': { 'repo_id': 'suno/bark', 'file_name': 'coarse.pt', }, 'fine_small': { 'repo_id': 'suno/bark', 'file_name': 'fine.pt', }, 'text': { 'repo_id': 'suno/bark', 'file_name': 'text_2.pt', }, 'coarse': { 'repo_id': 'suno/bark', 'file_name': 'coarse_2.pt', }, 'fine': { 'repo_id': 'suno/bark', 'file_name': 'fine_2.pt', }, } UpperCAmelCase__ : Tuple = os.path.dirname(os.path.abspath(__file__)) UpperCAmelCase__ : Tuple = os.path.join(os.path.expanduser('~'), '.cache') UpperCAmelCase__ : List[str] = os.path.join(os.getenv('XDG_CACHE_HOME', default_cache_dir), 'suno', 'bark_v0') def lowerCamelCase__ ( a , a=False ) -> Union[str, Any]: _A: Tuple = model_type if use_small: key += "_small" return os.path.join(a , REMOTE_MODEL_PATHS[key]['''file_name'''] ) def lowerCamelCase__ ( a , a ) -> Any: os.makedirs(a , exist_ok=a ) hf_hub_download(repo_id=a , filename=a , local_dir=a ) def lowerCamelCase__ ( a , a , a=False , a="text" ) -> Any: if model_type == "text": _A: List[str] = BarkSemanticModel _A: Optional[Any] = BarkSemanticConfig _A: Dict = BarkSemanticGenerationConfig elif model_type == "coarse": _A: int = BarkCoarseModel _A: List[Any] = BarkCoarseConfig _A: str = BarkCoarseGenerationConfig elif model_type == "fine": _A: List[Any] = BarkFineModel _A: Any = BarkFineConfig _A: Optional[int] = BarkFineGenerationConfig else: raise NotImplementedError() _A: Optional[int] = f"""{model_type}_small""" if use_small else model_type _A: Optional[Any] = REMOTE_MODEL_PATHS[model_key] if not os.path.exists(a ): logger.info(f"""{model_type} model not found, downloading into `{CACHE_DIR}`.""" ) _download(model_info['''repo_id'''] , model_info['''file_name'''] ) _A: Union[str, Any] = torch.load(a , map_location=a ) # this is a hack _A: int = checkpoint['''model_args'''] if "input_vocab_size" not in model_args: _A: int = model_args['''vocab_size'''] _A: List[str] = model_args['''vocab_size'''] del model_args["vocab_size"] # convert Bark model arguments to HF Bark model arguments _A: Tuple = model_args.pop('''n_head''' ) _A: Tuple = model_args.pop('''n_embd''' ) _A: int = model_args.pop('''n_layer''' ) _A: List[Any] = ConfigClass(**checkpoint['''model_args'''] ) _A: int = ModelClass(config=a ) _A: Tuple = GenerationConfigClass() _A: Any = model_generation_config _A: Union[str, Any] = checkpoint['''model'''] # fixup checkpoint _A: Optional[Any] = '''_orig_mod.''' for k, v in list(state_dict.items() ): if k.startswith(a ): # replace part of the key with corresponding layer name in HF implementation _A: str = k[len(a ) :] for old_layer_name in new_layer_name_dict: _A: Optional[Any] = new_k.replace(a , new_layer_name_dict[old_layer_name] ) _A: str = state_dict.pop(a ) _A: Dict = set(state_dict.keys() ) - set(model.state_dict().keys() ) _A: Any = {k for k in extra_keys if not k.endswith('''.attn.bias''' )} _A: str = set(model.state_dict().keys() ) - set(state_dict.keys() ) _A: Dict = {k for k in missing_keys if not k.endswith('''.attn.bias''' )} if len(a ) != 0: raise ValueError(f"""extra keys found: {extra_keys}""" ) if len(a ) != 0: raise ValueError(f"""missing keys: {missing_keys}""" ) model.load_state_dict(a , strict=a ) _A: List[Any] = model.num_parameters(exclude_embeddings=a ) _A: Optional[int] = checkpoint['''best_val_loss'''].item() logger.info(f"""model loaded: {round(n_params/1E6 , 1 )}M params, {round(a , 3 )} loss""" ) model.eval() model.to(a ) del checkpoint, state_dict return model def lowerCamelCase__ ( a , a=False , a="text" ) -> List[Any]: if model_type not in ("text", "coarse", "fine"): raise NotImplementedError() _A: List[Any] = '''cpu''' # do conversion on cpu _A: List[str] = _get_ckpt_path(a , use_small=a ) _A: List[Any] = _load_model(a , a , model_type=a , use_small=a ) # load bark initial model _A: Optional[int] = _bark_load_model(a , '''cpu''' , model_type=a , use_small=a ) if model_type == "text": _A: int = bark_model['''model'''] if model.num_parameters(exclude_embeddings=a ) != bark_model.get_num_params(): raise ValueError('''initial and new models don\'t have the same number of parameters''' ) # check if same output as the bark model _A: Tuple = 5 _A: Dict = 10 if model_type in ["text", "coarse"]: _A: Optional[Any] = torch.randint(2_56 , (batch_size, sequence_length) , dtype=torch.int ) _A: Any = bark_model(a )[0] _A: Any = model(a ) # take last logits _A: List[Any] = output_new_model_total.logits[:, [-1], :] else: _A: Any = 3 _A: str = 8 _A: Dict = torch.randint(2_56 , (batch_size, sequence_length, n_codes_total) , dtype=torch.int ) _A: int = model(a , a ) _A: Union[str, Any] = bark_model(a , a ) _A: Optional[int] = output_new_model_total.logits # output difference should come from the difference of self-attention implementation design if output_new_model.shape != output_old_model.shape: raise ValueError('''initial and new outputs don\'t have the same shape''' ) if (output_new_model - output_old_model).abs().max().item() > 1E-3: raise ValueError('''initial and new outputs are not equal''' ) Path(a ).mkdir(exist_ok=a ) model.save_pretrained(a ) def lowerCamelCase__ ( a , a , a , a , a , a , ) -> Dict: _A: str = os.path.join(a , a ) _A: Any = BarkSemanticConfig.from_pretrained(os.path.join(a , '''config.json''' ) ) _A: Dict = BarkCoarseConfig.from_pretrained(os.path.join(a , '''config.json''' ) ) _A: Any = BarkFineConfig.from_pretrained(os.path.join(a , '''config.json''' ) ) _A: str = EncodecConfig.from_pretrained('''facebook/encodec_24khz''' ) _A: Optional[int] = BarkSemanticModel.from_pretrained(a ) _A: str = BarkCoarseModel.from_pretrained(a ) _A: Optional[Any] = BarkFineModel.from_pretrained(a ) _A: Tuple = EncodecModel.from_pretrained('''facebook/encodec_24khz''' ) _A: List[str] = BarkConfig.from_sub_model_configs( a , a , a , a ) _A: Optional[Any] = BarkGenerationConfig.from_sub_model_configs( semantic.generation_config , coarseAcoustic.generation_config , fineAcoustic.generation_config ) _A: Dict = BarkModel(a ) _A: Tuple = semantic _A: Dict = coarseAcoustic _A: List[Any] = fineAcoustic _A: Union[str, Any] = codec _A: Optional[int] = bark_generation_config Path(a ).mkdir(exist_ok=a ) bark.save_pretrained(a , repo_id=a , push_to_hub=a ) if __name__ == "__main__": UpperCAmelCase__ : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument('model_type', type=str, help='text, coarse or fine.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--is_small', action='store_true', help='convert the small version instead of the large.') UpperCAmelCase__ : Tuple = parser.parse_args() load_model(args.pytorch_dump_folder_path, model_type=args.model_type, use_small=args.is_small)
301
from typing import TYPE_CHECKING from ..utils import _LazyModule UpperCAmelCase__ : Tuple = { 'config': [ 'EXTERNAL_DATA_FORMAT_SIZE_LIMIT', 'OnnxConfig', 'OnnxConfigWithPast', 'OnnxSeq2SeqConfigWithPast', 'PatchingSpec', ], 'convert': ['export', 'validate_model_outputs'], 'features': ['FeaturesManager'], 'utils': ['ParameterFormat', 'compute_serialized_parameters_size'], } if TYPE_CHECKING: from .config import ( EXTERNAL_DATA_FORMAT_SIZE_LIMIT, OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast, PatchingSpec, ) from .convert import export, validate_model_outputs from .features import FeaturesManager from .utils import ParameterFormat, compute_serialized_parameters_size else: import sys UpperCAmelCase__ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
301
1
import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @property def __magic_name__ ( self : Dict ): """simple docstring""" return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def __magic_name__ ( self : Optional[Any] ): """simple docstring""" _A: Tuple = ort.SessionOptions() _A: Tuple = False return options def __magic_name__ ( self : Tuple ): """simple docstring""" _A: Dict = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/in_paint/overture-creations-5sI6fQgYIuo.png''' ) _A: Optional[Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/in_paint/overture-creations-5sI6fQgYIuo_mask.png''' ) _A: str = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy''' ) # using the PNDM scheduler by default _A: List[Any] = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( '''CompVis/stable-diffusion-v1-4''' , revision='''onnx''' , safety_checker=lowerCAmelCase_ , feature_extractor=lowerCAmelCase_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _A: List[Any] = '''A red cat sitting on a park bench''' _A: Any = np.random.RandomState(0 ) _A: Tuple = pipe( prompt=lowerCAmelCase_ , image=lowerCAmelCase_ , mask_image=lowerCAmelCase_ , strength=0.75 , guidance_scale=7.5 , num_inference_steps=1_5 , generator=lowerCAmelCase_ , output_type='''np''' , ) _A: Optional[int] = output.images[0] assert image.shape == (5_1_2, 5_1_2, 3) assert np.abs(expected_image - image ).max() < 1e-2
301
import torch from diffusers import DDPMParallelScheduler from .test_schedulers import SchedulerCommonTest class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Any = (DDPMParallelScheduler,) def __magic_name__ ( self : Optional[int] , **lowerCAmelCase_ : Any ): """simple docstring""" _A: Optional[int] = { '''num_train_timesteps''': 1_0_0_0, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''variance_type''': '''fixed_small''', '''clip_sample''': True, } config.update(**lowerCAmelCase_ ) return config def __magic_name__ ( self : int ): """simple docstring""" for timesteps in [1, 5, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=lowerCAmelCase_ ) def __magic_name__ ( self : Tuple ): """simple docstring""" for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=lowerCAmelCase_ , beta_end=lowerCAmelCase_ ) def __magic_name__ ( self : Optional[Any] ): """simple docstring""" for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=lowerCAmelCase_ ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=lowerCAmelCase_ ) def __magic_name__ ( self : Tuple ): """simple docstring""" for clip_sample in [True, False]: self.check_over_configs(clip_sample=lowerCAmelCase_ ) def __magic_name__ ( self : List[str] ): """simple docstring""" self.check_over_configs(thresholding=lowerCAmelCase_ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=lowerCAmelCase_ , prediction_type=lowerCAmelCase_ , sample_max_value=lowerCAmelCase_ , ) def __magic_name__ ( self : Dict ): """simple docstring""" for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=lowerCAmelCase_ ) def __magic_name__ ( self : int ): """simple docstring""" for t in [0, 5_0_0, 9_9_9]: self.check_over_forward(time_step=lowerCAmelCase_ ) def __magic_name__ ( self : Any ): """simple docstring""" _A: List[Any] = self.scheduler_classes[0] _A: Union[str, Any] = self.get_scheduler_config() _A: Optional[Any] = scheduler_class(**lowerCAmelCase_ ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_8_7 ) - 0.00979 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_9_9 ) - 0.02 ) ) < 1e-5 def __magic_name__ ( self : Optional[int] ): """simple docstring""" _A: Any = self.scheduler_classes[0] _A: List[str] = self.get_scheduler_config() _A: Union[str, Any] = scheduler_class(**lowerCAmelCase_ ) _A: List[Any] = len(lowerCAmelCase_ ) _A: Union[str, Any] = self.dummy_model() _A: Dict = self.dummy_sample_deter _A: Dict = self.dummy_sample_deter + 0.1 _A: str = self.dummy_sample_deter - 0.1 _A: str = samplea.shape[0] _A: Optional[Any] = torch.stack([samplea, samplea, samplea] , dim=0 ) _A: List[str] = torch.arange(lowerCAmelCase_ )[0:3, None].repeat(1 , lowerCAmelCase_ ) _A: List[Any] = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) _A: Optional[int] = scheduler.batch_step_no_noise(lowerCAmelCase_ , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) ) _A: Dict = torch.sum(torch.abs(lowerCAmelCase_ ) ) _A: List[str] = torch.mean(torch.abs(lowerCAmelCase_ ) ) assert abs(result_sum.item() - 1153.1833 ) < 1e-2 assert abs(result_mean.item() - 0.5005 ) < 1e-3 def __magic_name__ ( self : Tuple ): """simple docstring""" _A: Optional[Any] = self.scheduler_classes[0] _A: List[Any] = self.get_scheduler_config() _A: Any = scheduler_class(**lowerCAmelCase_ ) _A: Union[str, Any] = len(lowerCAmelCase_ ) _A: Any = self.dummy_model() _A: Optional[int] = self.dummy_sample_deter _A: List[str] = torch.manual_seed(0 ) for t in reversed(range(lowerCAmelCase_ ) ): # 1. predict noise residual _A: Optional[int] = model(lowerCAmelCase_ , lowerCAmelCase_ ) # 2. predict previous mean of sample x_t-1 _A: Optional[int] = scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , generator=lowerCAmelCase_ ).prev_sample _A: List[Any] = pred_prev_sample _A: Optional[int] = torch.sum(torch.abs(lowerCAmelCase_ ) ) _A: Any = torch.mean(torch.abs(lowerCAmelCase_ ) ) assert abs(result_sum.item() - 258.9606 ) < 1e-2 assert abs(result_mean.item() - 0.3372 ) < 1e-3 def __magic_name__ ( self : Tuple ): """simple docstring""" _A: Optional[int] = self.scheduler_classes[0] _A: Union[str, Any] = self.get_scheduler_config(prediction_type='''v_prediction''' ) _A: List[str] = scheduler_class(**lowerCAmelCase_ ) _A: Union[str, Any] = len(lowerCAmelCase_ ) _A: Any = self.dummy_model() _A: Any = self.dummy_sample_deter _A: str = torch.manual_seed(0 ) for t in reversed(range(lowerCAmelCase_ ) ): # 1. predict noise residual _A: Any = model(lowerCAmelCase_ , lowerCAmelCase_ ) # 2. predict previous mean of sample x_t-1 _A: int = scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , generator=lowerCAmelCase_ ).prev_sample _A: Tuple = pred_prev_sample _A: List[Any] = torch.sum(torch.abs(lowerCAmelCase_ ) ) _A: str = torch.mean(torch.abs(lowerCAmelCase_ ) ) assert abs(result_sum.item() - 202.0296 ) < 1e-2 assert abs(result_mean.item() - 0.2631 ) < 1e-3 def __magic_name__ ( self : Optional[int] ): """simple docstring""" _A: Optional[int] = self.scheduler_classes[0] _A: Optional[Any] = self.get_scheduler_config() _A: Dict = scheduler_class(**lowerCAmelCase_ ) _A: Any = [1_0_0, 8_7, 5_0, 1, 0] scheduler.set_timesteps(timesteps=lowerCAmelCase_ ) _A: Tuple = scheduler.timesteps for i, timestep in enumerate(lowerCAmelCase_ ): if i == len(lowerCAmelCase_ ) - 1: _A: Dict = -1 else: _A: int = timesteps[i + 1] _A: List[str] = scheduler.previous_timestep(lowerCAmelCase_ ) _A: str = prev_t.item() self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) def __magic_name__ ( self : Any ): """simple docstring""" _A: Tuple = self.scheduler_classes[0] _A: int = self.get_scheduler_config() _A: Any = scheduler_class(**lowerCAmelCase_ ) _A: Union[str, Any] = [1_0_0, 8_7, 5_0, 5_1, 0] with self.assertRaises(lowerCAmelCase_ , msg='''`custom_timesteps` must be in descending order.''' ): scheduler.set_timesteps(timesteps=lowerCAmelCase_ ) def __magic_name__ ( self : int ): """simple docstring""" _A: List[str] = self.scheduler_classes[0] _A: Optional[Any] = self.get_scheduler_config() _A: Union[str, Any] = scheduler_class(**lowerCAmelCase_ ) _A: Union[str, Any] = [1_0_0, 8_7, 5_0, 1, 0] _A: Dict = len(lowerCAmelCase_ ) with self.assertRaises(lowerCAmelCase_ , msg='''Can only pass one of `num_inference_steps` or `custom_timesteps`.''' ): scheduler.set_timesteps(num_inference_steps=lowerCAmelCase_ , timesteps=lowerCAmelCase_ ) def __magic_name__ ( self : Any ): """simple docstring""" _A: List[Any] = self.scheduler_classes[0] _A: int = self.get_scheduler_config() _A: str = scheduler_class(**lowerCAmelCase_ ) _A: Any = [scheduler.config.num_train_timesteps] with self.assertRaises( lowerCAmelCase_ , msg='''`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}''' , ): scheduler.set_timesteps(timesteps=lowerCAmelCase_ )
301
1
import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mvp import MvpTokenizer UpperCAmelCase__ : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase__ : str = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} # See all MVP models at https://huggingface.co/models?filter=mvp UpperCAmelCase__ : Union[str, Any] = { 'vocab_file': { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/vocab.json', }, 'added_tokens.json': { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/added_tokens.json', }, 'merges_file': { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/merges.txt', }, 'tokenizer_file': { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/tokenizer.json', }, } UpperCAmelCase__ : Any = { 'RUCAIBox/mvp': 1024, } class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Union[str, Any] = VOCAB_FILES_NAMES __UpperCamelCase : Tuple = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase : int = ['''input_ids''', '''attention_mask'''] __UpperCamelCase : int = MvpTokenizer def __init__( self : Optional[Any] , lowerCAmelCase_ : Any=None , lowerCAmelCase_ : int=None , lowerCAmelCase_ : int=None , lowerCAmelCase_ : Union[str, Any]="replace" , lowerCAmelCase_ : Optional[int]="<s>" , lowerCAmelCase_ : Union[str, Any]="</s>" , lowerCAmelCase_ : int="</s>" , lowerCAmelCase_ : Dict="<s>" , lowerCAmelCase_ : Optional[int]="<unk>" , lowerCAmelCase_ : Any="<pad>" , lowerCAmelCase_ : List[str]="<mask>" , lowerCAmelCase_ : Optional[Any]=False , lowerCAmelCase_ : Optional[int]=True , **lowerCAmelCase_ : Any , ): """simple docstring""" super().__init__( lowerCAmelCase_ , lowerCAmelCase_ , tokenizer_file=lowerCAmelCase_ , errors=lowerCAmelCase_ , bos_token=lowerCAmelCase_ , eos_token=lowerCAmelCase_ , sep_token=lowerCAmelCase_ , cls_token=lowerCAmelCase_ , unk_token=lowerCAmelCase_ , pad_token=lowerCAmelCase_ , mask_token=lowerCAmelCase_ , add_prefix_space=lowerCAmelCase_ , trim_offsets=lowerCAmelCase_ , **lowerCAmelCase_ , ) _A: Optional[int] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , lowerCAmelCase_ ) != add_prefix_space: _A: str = getattr(lowerCAmelCase_ , pre_tok_state.pop('''type''' ) ) _A: List[str] = add_prefix_space _A: Optional[int] = pre_tok_class(**lowerCAmelCase_ ) _A: List[Any] = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` _A: Union[str, Any] = '''post_processor''' _A: Tuple = getattr(self.backend_tokenizer , lowerCAmelCase_ , lowerCAmelCase_ ) if tokenizer_component_instance: _A: str = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: _A: int = tuple(state['''sep'''] ) if "cls" in state: _A: Any = tuple(state['''cls'''] ) _A: Union[str, Any] = False if state.get('''add_prefix_space''' , lowerCAmelCase_ ) != add_prefix_space: _A: Optional[Any] = add_prefix_space _A: str = True if state.get('''trim_offsets''' , lowerCAmelCase_ ) != trim_offsets: _A: str = trim_offsets _A: int = True if changes_to_apply: _A: Optional[int] = getattr(lowerCAmelCase_ , state.pop('''type''' ) ) _A: Union[str, Any] = component_class(**lowerCAmelCase_ ) setattr(self.backend_tokenizer , lowerCAmelCase_ , lowerCAmelCase_ ) @property def __magic_name__ ( self : Dict ): """simple docstring""" if self._mask_token is None: if self.verbose: logger.error('''Using mask_token, but it is not set yet.''' ) return None return str(self._mask_token ) @mask_token.setter def __magic_name__ ( self : Dict , lowerCAmelCase_ : int ): """simple docstring""" _A: Dict = AddedToken(lowerCAmelCase_ , lstrip=lowerCAmelCase_ , rstrip=lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else value _A: Optional[int] = value def __magic_name__ ( self : List[str] , *lowerCAmelCase_ : Any , **lowerCAmelCase_ : List[str] ): """simple docstring""" _A: List[str] = kwargs.get('''is_split_into_words''' , lowerCAmelCase_ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ '''to use it with pretokenized inputs.''' ) return super()._batch_encode_plus(*lowerCAmelCase_ , **lowerCAmelCase_ ) def __magic_name__ ( self : int , *lowerCAmelCase_ : Dict , **lowerCAmelCase_ : List[str] ): """simple docstring""" _A: Union[str, Any] = kwargs.get('''is_split_into_words''' , lowerCAmelCase_ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ '''to use it with pretokenized inputs.''' ) return super()._encode_plus(*lowerCAmelCase_ , **lowerCAmelCase_ ) def __magic_name__ ( self : Any , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[str] = None ): """simple docstring""" _A: List[str] = self._tokenizer.model.save(lowerCAmelCase_ , name=lowerCAmelCase_ ) return tuple(lowerCAmelCase_ ) def __magic_name__ ( self : List[Any] , lowerCAmelCase_ : str , lowerCAmelCase_ : int=None ): """simple docstring""" _A: Optional[int] = [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 __magic_name__ ( self : str , lowerCAmelCase_ : List[int] , lowerCAmelCase_ : Optional[List[int]] = None ): """simple docstring""" _A: Optional[int] = [self.sep_token_id] _A: List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
301
import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Any = GPTSanJapaneseTokenizer __UpperCamelCase : Optional[int] = False __UpperCamelCase : str = {'''do_clean_text''': False, '''add_prefix_space''': False} def __magic_name__ ( self : Any ): """simple docstring""" super().setUp() # fmt: off _A: Union[str, Any] = ['''こん''', '''こんに''', '''にちは''', '''ばんは''', '''世界,㔺界''', '''、''', '''。''', '''<BR>''', '''<SP>''', '''<TAB>''', '''<URL>''', '''<EMAIL>''', '''<TEL>''', '''<DATE>''', '''<PRICE>''', '''<BLOCK>''', '''<KIGOU>''', '''<U2000U2BFF>''', '''<|emoji1|>''', '''<unk>''', '''<|bagoftoken|>''', '''<|endoftext|>'''] # fmt: on _A: Union[str, Any] = {'''emoji''': {'''\ud83d\ude00''': '''<|emoji1|>'''}, '''emoji_inv''': {'''<|emoji1|>''': '''\ud83d\ude00'''}} # 😀 _A: str = {'''unk_token''': '''<unk>'''} _A: Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) _A: Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''emoji_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) with open(self.emoji_file , '''w''' ) as emoji_writer: emoji_writer.write(json.dumps(lowerCAmelCase_ ) ) def __magic_name__ ( self : Optional[int] , **lowerCAmelCase_ : List[Any] ): """simple docstring""" kwargs.update(self.special_tokens_map ) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **lowerCAmelCase_ ) def __magic_name__ ( self : Optional[int] , lowerCAmelCase_ : List[str] ): """simple docstring""" _A: Optional[Any] = '''こんにちは、世界。 \nこんばんは、㔺界。😀''' _A: str = '''こんにちは、世界。 \nこんばんは、世界。😀''' return input_text, output_text def __magic_name__ ( self : List[str] , lowerCAmelCase_ : Optional[int] ): """simple docstring""" _A , _A: Optional[int] = self.get_input_output_texts(lowerCAmelCase_ ) _A: Union[str, Any] = tokenizer.encode(lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ ) _A: Tuple = tokenizer.decode(lowerCAmelCase_ , clean_up_tokenization_spaces=lowerCAmelCase_ ) return text, ids def __magic_name__ ( self : Tuple ): """simple docstring""" pass # TODO add if relevant def __magic_name__ ( self : List[str] ): """simple docstring""" pass # TODO add if relevant def __magic_name__ ( self : Dict ): """simple docstring""" pass # TODO add if relevant def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" _A: List[str] = self.get_tokenizer() # Testing tokenization _A: List[Any] = '''こんにちは、世界。 こんばんは、㔺界。''' _A: Dict = ['''こん''', '''にちは''', '''、''', '''世界''', '''。''', '''<SP>''', '''こん''', '''ばんは''', '''、''', '''㔺界''', '''。'''] _A: List[Any] = tokenizer.tokenize(lowerCAmelCase_ ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) # Testing conversion to ids without special tokens _A: Optional[int] = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] _A: Optional[int] = tokenizer.convert_tokens_to_ids(lowerCAmelCase_ ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) # Testing conversion to ids with special tokens _A: Dict = tokens + [tokenizer.unk_token] _A: str = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 1_9] _A: Optional[int] = tokenizer.convert_tokens_to_ids(lowerCAmelCase_ ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" _A: Dict = self.get_tokenizer() # Testing tokenization _A: Optional[int] = '''こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。''' _A: str = '''こんにちは、、、、世界。こんばんは、、、、世界。''' _A: Tuple = tokenizer.encode(lowerCAmelCase_ ) _A: List[str] = tokenizer.decode(lowerCAmelCase_ ) self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) @slow def __magic_name__ ( self : Any ): """simple docstring""" _A: List[Any] = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' ) # Testing tokenization _A: Union[str, Any] = '''こんにちは、世界。''' _A: Optional[int] = '''こんばんは、㔺界。😀''' _A: str = '''こんにちは、世界。こんばんは、世界。😀''' _A: List[Any] = tokenizer.encode(prefix_text + input_text ) _A: Optional[Any] = tokenizer.encode('''''' , prefix_text=prefix_text + input_text ) _A: List[Any] = tokenizer.encode(lowerCAmelCase_ , prefix_text=lowerCAmelCase_ ) _A: Union[str, Any] = tokenizer.decode(lowerCAmelCase_ ) _A: Any = tokenizer.decode(lowerCAmelCase_ ) _A: Dict = tokenizer.decode(lowerCAmelCase_ ) self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) @slow def __magic_name__ ( self : Optional[Any] ): """simple docstring""" _A: str = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' ) # Testing tokenization _A: Optional[int] = '''こんにちは、世界。''' _A: Optional[int] = '''こんばんは、㔺界。😀''' _A: Any = len(tokenizer.encode(lowerCAmelCase_ ) ) - 2 _A: int = len(tokenizer.encode(lowerCAmelCase_ ) ) - 2 _A: Optional[Any] = [1] + [0] * (len_prefix + len_text + 1) _A: Any = [1] * (len_prefix + len_text + 1) + [0] _A: Optional[int] = [1] + [1] * (len_prefix) + [0] * (len_text + 1) _A: Optional[Any] = tokenizer(prefix_text + input_text ).token_type_ids _A: List[str] = tokenizer('''''' , prefix_text=prefix_text + input_text ).token_type_ids _A: Dict = tokenizer(lowerCAmelCase_ , prefix_text=lowerCAmelCase_ ).token_type_ids self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) @slow def __magic_name__ ( self : Any ): """simple docstring""" _A: str = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' ) _A: List[Any] = tokenizer.encode('''あンいワ''' ) _A: Any = tokenizer.encode('''''' , prefix_text='''あンいワ''' ) _A: Union[str, Any] = tokenizer.encode('''いワ''' , prefix_text='''あン''' ) self.assertEqual(tokenizer.decode(lowerCAmelCase_ ) , tokenizer.decode(lowerCAmelCase_ ) ) self.assertEqual(tokenizer.decode(lowerCAmelCase_ ) , tokenizer.decode(lowerCAmelCase_ ) ) self.assertNotEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertNotEqual(lowerCAmelCase_ , lowerCAmelCase_ ) self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token @slow def __magic_name__ ( self : List[Any] ): """simple docstring""" _A: Tuple = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' ) _A: Optional[Any] = [['''武田信玄''', '''は、'''], ['''織田信長''', '''の配下の、''']] _A: Optional[int] = tokenizer(lowerCAmelCase_ , padding=lowerCAmelCase_ ) _A: Optional[Any] = tokenizer.batch_encode_plus(lowerCAmelCase_ , padding=lowerCAmelCase_ ) # fmt: off _A: Tuple = [[3_5_9_9_3, 8_6_4_0, 2_5_9_4_8, 3_5_9_9_8, 3_0_6_4_7, 3_5_6_7_5, 3_5_9_9_9, 3_5_9_9_9], [3_5_9_9_3, 1_0_3_8_2, 9_8_6_8, 3_5_9_9_8, 3_0_6_4_6, 9_4_5_9, 3_0_6_4_6, 3_5_6_7_5]] _A: Optional[int] = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] _A: Dict = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids , lowerCAmelCase_ ) self.assertListEqual(x_token.token_type_ids , lowerCAmelCase_ ) self.assertListEqual(x_token.attention_mask , lowerCAmelCase_ ) self.assertListEqual(x_token_a.input_ids , lowerCAmelCase_ ) self.assertListEqual(x_token_a.token_type_ids , lowerCAmelCase_ ) self.assertListEqual(x_token_a.attention_mask , lowerCAmelCase_ ) def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" # Intentionally convert some words to accommodate character fluctuations unique to Japanese pass def __magic_name__ ( self : Tuple ): """simple docstring""" # tokenizer has no padding token pass
301
1
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=SCREAMING_SNAKE_CASE__ ) class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : str = field(default='''automatic-speech-recognition''' , metadata={'''include_in_asdict_even_if_is_default''': True} ) __UpperCamelCase : ClassVar[Features] = Features({'''audio''': Audio()} ) __UpperCamelCase : ClassVar[Features] = Features({'''transcription''': Value('''string''' )} ) __UpperCamelCase : str = "audio" __UpperCamelCase : str = "transcription" def __magic_name__ ( self : List[Any] , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" if self.audio_column not in features: raise ValueError(F"""Column {self.audio_column} is not present in features.""" ) if not isinstance(features[self.audio_column] , lowerCAmelCase_ ): raise ValueError(F"""Column {self.audio_column} is not an Audio type.""" ) _A: Optional[int] = copy.deepcopy(self ) _A: str = self.input_schema.copy() _A: List[str] = features[self.audio_column] _A: Dict = input_schema return task_template @property def __magic_name__ ( self : str ): """simple docstring""" return {self.audio_column: "audio", self.transcription_column: "transcription"}
301
def lowerCamelCase__ ( a = 10**9 ) -> int: _A: Dict = 1 _A: Union[str, Any] = 2 _A: List[str] = 0 _A: List[Any] = 0 _A: int = 0 while perimeter <= max_perimeter: perimeters_sum += perimeter prev_value += 2 * value value += prev_value _A: List[Any] = 2 * value + 2 if i % 2 == 0 else 2 * value - 2 i += 1 return perimeters_sum if __name__ == "__main__": print(F"""{solution() = }""")
301
1
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ : List[str] = logging.get_logger(__name__) UpperCAmelCase__ : str = { 'microsoft/wavlm-base': 'https://huggingface.co/microsoft/wavlm-base/resolve/main/config.json', # See all WavLM models at https://huggingface.co/models?filter=wavlm } class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Any = '''wavlm''' def __init__( self : Tuple , lowerCAmelCase_ : Tuple=3_2 , lowerCAmelCase_ : Any=7_6_8 , lowerCAmelCase_ : str=1_2 , lowerCAmelCase_ : Any=1_2 , lowerCAmelCase_ : Optional[int]=3_0_7_2 , lowerCAmelCase_ : Optional[Any]="gelu" , lowerCAmelCase_ : Tuple=0.1 , lowerCAmelCase_ : Any=0.1 , lowerCAmelCase_ : Tuple=0.1 , lowerCAmelCase_ : Any=0.0 , lowerCAmelCase_ : Optional[int]=0.1 , lowerCAmelCase_ : Dict=0.1 , lowerCAmelCase_ : int=0.02 , lowerCAmelCase_ : int=1e-5 , lowerCAmelCase_ : str="group" , lowerCAmelCase_ : Optional[int]="gelu" , lowerCAmelCase_ : Optional[Any]=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , lowerCAmelCase_ : Dict=(5, 2, 2, 2, 2, 2, 2) , lowerCAmelCase_ : List[Any]=(1_0, 3, 3, 3, 3, 2, 2) , lowerCAmelCase_ : Dict=False , lowerCAmelCase_ : str=1_2_8 , lowerCAmelCase_ : List[str]=1_6 , lowerCAmelCase_ : Tuple=3_2_0 , lowerCAmelCase_ : Union[str, Any]=8_0_0 , lowerCAmelCase_ : List[Any]=False , lowerCAmelCase_ : List[Any]=True , lowerCAmelCase_ : Any=0.05 , lowerCAmelCase_ : Tuple=1_0 , lowerCAmelCase_ : str=2 , lowerCAmelCase_ : List[str]=0.0 , lowerCAmelCase_ : Tuple=1_0 , lowerCAmelCase_ : Tuple=3_2_0 , lowerCAmelCase_ : int=2 , lowerCAmelCase_ : List[Any]=0.1 , lowerCAmelCase_ : Union[str, Any]=1_0_0 , lowerCAmelCase_ : Dict=2_5_6 , lowerCAmelCase_ : str=2_5_6 , lowerCAmelCase_ : Optional[int]=0.1 , lowerCAmelCase_ : List[Any]="mean" , lowerCAmelCase_ : List[str]=False , lowerCAmelCase_ : Tuple=False , lowerCAmelCase_ : Dict=2_5_6 , lowerCAmelCase_ : Optional[Any]=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 1_5_0_0) , lowerCAmelCase_ : List[str]=(5, 3, 3, 1, 1) , lowerCAmelCase_ : Union[str, Any]=(1, 2, 3, 1, 1) , lowerCAmelCase_ : Optional[int]=5_1_2 , lowerCAmelCase_ : str=8_0 , lowerCAmelCase_ : Optional[int]=0 , lowerCAmelCase_ : Optional[int]=1 , lowerCAmelCase_ : List[Any]=2 , lowerCAmelCase_ : str=False , lowerCAmelCase_ : str=3 , lowerCAmelCase_ : int=2 , lowerCAmelCase_ : List[Any]=3 , lowerCAmelCase_ : Union[str, Any]=None , **lowerCAmelCase_ : Tuple , ): """simple docstring""" super().__init__(**lowerCAmelCase_ , pad_token_id=lowerCAmelCase_ , bos_token_id=lowerCAmelCase_ , eos_token_id=lowerCAmelCase_ ) _A: str = hidden_size _A: str = feat_extract_norm _A: Optional[Any] = feat_extract_activation _A: Optional[Any] = list(lowerCAmelCase_ ) _A: Optional[int] = list(lowerCAmelCase_ ) _A: str = list(lowerCAmelCase_ ) _A: int = conv_bias _A: Optional[Any] = num_buckets _A: Dict = max_bucket_distance _A: Optional[int] = num_conv_pos_embeddings _A: str = num_conv_pos_embedding_groups _A: Dict = len(self.conv_dim ) _A: Dict = num_hidden_layers _A: List[str] = intermediate_size _A: List[str] = hidden_act _A: Tuple = num_attention_heads _A: str = hidden_dropout _A: Any = attention_dropout _A: List[Any] = activation_dropout _A: int = feat_proj_dropout _A: List[str] = final_dropout _A: Optional[Any] = layerdrop _A: Any = layer_norm_eps _A: Optional[int] = initializer_range _A: Union[str, Any] = num_ctc_classes _A: Optional[int] = vocab_size _A: Any = do_stable_layer_norm _A: Dict = use_weighted_layer_sum _A: int = classifier_proj_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( '''Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==''' ''' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =''' F""" {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,""" F""" `len(config.conv_kernel) = {len(self.conv_kernel )}`.""" ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 _A: Dict = apply_spec_augment _A: Union[str, Any] = mask_time_prob _A: Optional[Any] = mask_time_length _A: List[Any] = mask_time_min_masks _A: Optional[Any] = mask_feature_prob _A: Any = mask_feature_length # parameters for pretraining with codevector quantized representations _A: Optional[Any] = num_codevectors_per_group _A: Tuple = num_codevector_groups _A: Any = contrastive_logits_temperature _A: List[Any] = num_negatives _A: Union[str, Any] = codevector_dim _A: List[str] = proj_codevector_dim _A: List[Any] = diversity_loss_weight # ctc loss _A: Optional[Any] = ctc_loss_reduction _A: str = ctc_zero_infinity # adapter _A: str = add_adapter _A: Optional[int] = adapter_kernel_size _A: str = adapter_stride _A: Dict = num_adapter_layers _A: Optional[int] = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. _A: Dict = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. _A: Optional[Any] = list(lowerCAmelCase_ ) _A: Optional[Any] = list(lowerCAmelCase_ ) _A: Dict = list(lowerCAmelCase_ ) _A: Optional[int] = xvector_output_dim @property def __magic_name__ ( self : Dict ): """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
301
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase__ : Union[str, Any] = { 'configuration_roc_bert': ['ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoCBertConfig'], 'tokenization_roc_bert': ['RoCBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: pass try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[Any] = [ 'ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'RoCBertForCausalLM', 'RoCBertForMaskedLM', 'RoCBertForMultipleChoice', 'RoCBertForPreTraining', 'RoCBertForQuestionAnswering', 'RoCBertForSequenceClassification', 'RoCBertForTokenClassification', 'RoCBertLayer', 'RoCBertModel', 'RoCBertPreTrainedModel', 'load_tf_weights_in_roc_bert', ] if TYPE_CHECKING: from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig from .tokenization_roc_bert import RoCBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: raise OptionalDependencyNotAvailable() try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) else: import sys UpperCAmelCase__ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
301
1
def lowerCamelCase__ ( a = 10_00 ) -> int: _A: Tuple = 3 _A: List[str] = 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() = }""")
301
import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def lowerCamelCase__ ( a , a=0.999 , a="cosine" , ) -> int: if alpha_transform_type == "cosine": def alpha_bar_fn(a ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(a ): return math.exp(t * -12.0 ) else: raise ValueError(f"""Unsupported alpha_tranform_type: {alpha_transform_type}""" ) _A: Dict = [] for i in range(a ): _A: Optional[int] = i / num_diffusion_timesteps _A: Optional[int] = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(a ) / alpha_bar_fn(a ) , a ) ) return torch.tensor(a , dtype=torch.floataa ) class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Optional[int] = [e.name for e in KarrasDiffusionSchedulers] __UpperCamelCase : Tuple = 2 @register_to_config def __init__( self : str , lowerCAmelCase_ : int = 1_0_0_0 , lowerCAmelCase_ : float = 0.00085 , lowerCAmelCase_ : float = 0.012 , lowerCAmelCase_ : str = "linear" , lowerCAmelCase_ : Optional[Union[np.ndarray, List[float]]] = None , lowerCAmelCase_ : str = "epsilon" , lowerCAmelCase_ : Optional[bool] = False , lowerCAmelCase_ : Optional[bool] = False , lowerCAmelCase_ : float = 1.0 , lowerCAmelCase_ : str = "linspace" , lowerCAmelCase_ : int = 0 , ): """simple docstring""" if trained_betas is not None: _A: Optional[Any] = torch.tensor(lowerCAmelCase_ , dtype=torch.floataa ) elif beta_schedule == "linear": _A: List[str] = torch.linspace(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. _A: Optional[Any] = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , lowerCAmelCase_ , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule _A: Tuple = betas_for_alpha_bar(lowerCAmelCase_ , alpha_transform_type='''cosine''' ) elif beta_schedule == "exp": _A: int = betas_for_alpha_bar(lowerCAmelCase_ , alpha_transform_type='''exp''' ) else: raise NotImplementedError(F"""{beta_schedule} does is not implemented for {self.__class__}""" ) _A: Union[str, Any] = 1.0 - self.betas _A: Dict = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) _A: str = use_karras_sigmas def __magic_name__ ( self : List[str] , lowerCAmelCase_ : Any , lowerCAmelCase_ : Optional[int]=None ): """simple docstring""" if schedule_timesteps is None: _A: List[str] = self.timesteps _A: int = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: _A: Optional[int] = 1 if len(lowerCAmelCase_ ) > 1 else 0 else: _A: int = timestep.cpu().item() if torch.is_tensor(lowerCAmelCase_ ) else timestep _A: List[str] = self._index_counter[timestep_int] return indices[pos].item() @property def __magic_name__ ( self : int ): """simple docstring""" # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def __magic_name__ ( self : List[str] , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : Union[float, torch.FloatTensor] , ): """simple docstring""" _A: List[str] = self.index_for_timestep(lowerCAmelCase_ ) _A: str = self.sigmas[step_index] _A: str = sample / ((sigma**2 + 1) ** 0.5) return sample def __magic_name__ ( self : Optional[int] , lowerCAmelCase_ : int , lowerCAmelCase_ : Union[str, torch.device] = None , lowerCAmelCase_ : Optional[int] = None , ): """simple docstring""" _A: Union[str, Any] = num_inference_steps _A: str = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": _A: Optional[Any] = np.linspace(0 , num_train_timesteps - 1 , lowerCAmelCase_ , dtype=lowerCAmelCase_ )[::-1].copy() elif self.config.timestep_spacing == "leading": _A: List[Any] = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 _A: Dict = (np.arange(0 , lowerCAmelCase_ ) * step_ratio).round()[::-1].copy().astype(lowerCAmelCase_ ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": _A: Union[str, Any] = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 _A: List[Any] = (np.arange(lowerCAmelCase_ , 0 , -step_ratio )).round().copy().astype(lowerCAmelCase_ ) timesteps -= 1 else: raise ValueError( F"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.""" ) _A: Optional[int] = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) _A: str = np.log(lowerCAmelCase_ ) _A: int = np.interp(lowerCAmelCase_ , np.arange(0 , len(lowerCAmelCase_ ) ) , lowerCAmelCase_ ) if self.config.use_karras_sigmas: _A: Optional[int] = self._convert_to_karras(in_sigmas=lowerCAmelCase_ , num_inference_steps=self.num_inference_steps ) _A: List[str] = np.array([self._sigma_to_t(lowerCAmelCase_ , lowerCAmelCase_ ) for sigma in sigmas] ) _A: Optional[int] = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) _A: Optional[Any] = torch.from_numpy(lowerCAmelCase_ ).to(device=lowerCAmelCase_ ) _A: Tuple = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) _A: str = torch.from_numpy(lowerCAmelCase_ ) _A: str = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(lowerCAmelCase_ ).startswith('''mps''' ): # mps does not support float64 _A: List[Any] = timesteps.to(lowerCAmelCase_ , dtype=torch.floataa ) else: _A: Optional[int] = timesteps.to(device=lowerCAmelCase_ ) # empty dt and derivative _A: Dict = None _A: List[Any] = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter _A: Dict = defaultdict(lowerCAmelCase_ ) def __magic_name__ ( self : Dict , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Dict ): """simple docstring""" # get log sigma _A: Tuple = np.log(lowerCAmelCase_ ) # get distribution _A: List[str] = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range _A: Dict = np.cumsum((dists >= 0) , axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) _A: int = low_idx + 1 _A: Optional[int] = log_sigmas[low_idx] _A: Dict = log_sigmas[high_idx] # interpolate sigmas _A: Union[str, Any] = (low - log_sigma) / (low - high) _A: Optional[Any] = np.clip(lowerCAmelCase_ , 0 , 1 ) # transform interpolation to time range _A: Any = (1 - w) * low_idx + w * high_idx _A: List[Any] = t.reshape(sigma.shape ) return t def __magic_name__ ( self : Any , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" _A: float = in_sigmas[-1].item() _A: float = in_sigmas[0].item() _A: Union[str, Any] = 7.0 # 7.0 is the value used in the paper _A: Optional[Any] = np.linspace(0 , 1 , lowerCAmelCase_ ) _A: Tuple = sigma_min ** (1 / rho) _A: Optional[Any] = sigma_max ** (1 / rho) _A: List[str] = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def __magic_name__ ( self : Optional[Any] ): """simple docstring""" return self.dt is None def __magic_name__ ( self : Tuple , lowerCAmelCase_ : Union[torch.FloatTensor, np.ndarray] , lowerCAmelCase_ : Union[float, torch.FloatTensor] , lowerCAmelCase_ : Union[torch.FloatTensor, np.ndarray] , lowerCAmelCase_ : bool = True , ): """simple docstring""" _A: Optional[int] = self.index_for_timestep(lowerCAmelCase_ ) # advance index counter by 1 _A: Union[str, Any] = timestep.cpu().item() if torch.is_tensor(lowerCAmelCase_ ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: _A: Optional[int] = self.sigmas[step_index] _A: Union[str, Any] = self.sigmas[step_index + 1] else: # 2nd order / Heun's method _A: Union[str, Any] = self.sigmas[step_index - 1] _A: Optional[int] = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API _A: List[Any] = 0 _A: Tuple = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": _A: Union[str, Any] = sigma_hat if self.state_in_first_order else sigma_next _A: List[str] = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": _A: int = sigma_hat if self.state_in_first_order else sigma_next _A: List[str] = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": _A: Optional[int] = model_output else: raise ValueError( F"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`""" ) if self.config.clip_sample: _A: Tuple = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order _A: Optional[int] = (sample - pred_original_sample) / sigma_hat # 3. delta timestep _A: List[Any] = sigma_next - sigma_hat # store for 2nd order step _A: str = derivative _A: Any = dt _A: Dict = sample else: # 2. 2nd order / Heun's method _A: List[str] = (sample - pred_original_sample) / sigma_next _A: str = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample _A: Dict = self.dt _A: int = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" _A: int = None _A: int = None _A: Optional[Any] = None _A: Optional[Any] = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=lowerCAmelCase_ ) def __magic_name__ ( self : Any , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : torch.FloatTensor , lowerCAmelCase_ : torch.FloatTensor , ): """simple docstring""" # Make sure sigmas and timesteps have the same device and dtype as original_samples _A: str = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(lowerCAmelCase_ ): # mps does not support float64 _A: Optional[int] = self.timesteps.to(original_samples.device , dtype=torch.floataa ) _A: Any = timesteps.to(original_samples.device , dtype=torch.floataa ) else: _A: Union[str, Any] = self.timesteps.to(original_samples.device ) _A: int = timesteps.to(original_samples.device ) _A: str = [self.index_for_timestep(lowerCAmelCase_ , lowerCAmelCase_ ) for t in timesteps] _A: Optional[Any] = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): _A: List[str] = sigma.unsqueeze(-1 ) _A: Any = original_samples + noise * sigma return noisy_samples def __len__( self : Dict ): """simple docstring""" return self.config.num_train_timesteps
301
1
import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase__ : Optional[int] = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt'} UpperCAmelCase__ : Union[str, Any] = { 'vocab_file': { 'allenai/longformer-base-4096': 'https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json', 'allenai/longformer-large-4096': ( 'https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json' ), 'allenai/longformer-large-4096-finetuned-triviaqa': ( 'https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json' ), 'allenai/longformer-base-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json' ), 'allenai/longformer-large-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json' ), }, 'merges_file': { 'allenai/longformer-base-4096': 'https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt', 'allenai/longformer-large-4096': ( 'https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt' ), 'allenai/longformer-large-4096-finetuned-triviaqa': ( 'https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt' ), 'allenai/longformer-base-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt' ), 'allenai/longformer-large-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt' ), }, } UpperCAmelCase__ : List[Any] = { 'allenai/longformer-base-4096': 4096, 'allenai/longformer-large-4096': 4096, 'allenai/longformer-large-4096-finetuned-triviaqa': 4096, 'allenai/longformer-base-4096-extra.pos.embd.only': 4096, 'allenai/longformer-large-4096-extra.pos.embd.only': 4096, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def lowerCamelCase__ ( ) -> Any: _A: Tuple = ( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) _A: List[str] = bs[:] _A: Optional[Any] = 0 for b in range(2**8 ): if b not in bs: bs.append(a ) cs.append(2**8 + n ) n += 1 _A: Optional[Any] = [chr(a ) for n in cs] return dict(zip(a , a ) ) def lowerCamelCase__ ( a ) -> Tuple: _A: Dict = set() _A: Union[str, Any] = word[0] for char in word[1:]: pairs.add((prev_char, char) ) _A: Optional[int] = char return pairs class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : int = VOCAB_FILES_NAMES __UpperCamelCase : List[Any] = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase : Union[str, Any] = ['''input_ids''', '''attention_mask'''] def __init__( self : List[Any] , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[int]="replace" , lowerCAmelCase_ : Union[str, Any]="<s>" , lowerCAmelCase_ : Optional[Any]="</s>" , lowerCAmelCase_ : List[Any]="</s>" , lowerCAmelCase_ : Optional[Any]="<s>" , lowerCAmelCase_ : List[Any]="<unk>" , lowerCAmelCase_ : Union[str, Any]="<pad>" , lowerCAmelCase_ : int="<mask>" , lowerCAmelCase_ : Any=False , **lowerCAmelCase_ : List[Any] , ): """simple docstring""" _A: Any = AddedToken(lowerCAmelCase_ , lstrip=lowerCAmelCase_ , rstrip=lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else bos_token _A: Optional[Any] = AddedToken(lowerCAmelCase_ , lstrip=lowerCAmelCase_ , rstrip=lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else eos_token _A: List[str] = AddedToken(lowerCAmelCase_ , lstrip=lowerCAmelCase_ , rstrip=lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else sep_token _A: List[str] = AddedToken(lowerCAmelCase_ , lstrip=lowerCAmelCase_ , rstrip=lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else cls_token _A: Union[str, Any] = AddedToken(lowerCAmelCase_ , lstrip=lowerCAmelCase_ , rstrip=lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else unk_token _A: Dict = AddedToken(lowerCAmelCase_ , lstrip=lowerCAmelCase_ , rstrip=lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it _A: List[str] = AddedToken(lowerCAmelCase_ , lstrip=lowerCAmelCase_ , rstrip=lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else mask_token super().__init__( errors=lowerCAmelCase_ , bos_token=lowerCAmelCase_ , eos_token=lowerCAmelCase_ , unk_token=lowerCAmelCase_ , sep_token=lowerCAmelCase_ , cls_token=lowerCAmelCase_ , pad_token=lowerCAmelCase_ , mask_token=lowerCAmelCase_ , add_prefix_space=lowerCAmelCase_ , **lowerCAmelCase_ , ) with open(lowerCAmelCase_ , encoding='''utf-8''' ) as vocab_handle: _A: List[str] = json.load(lowerCAmelCase_ ) _A: Tuple = {v: k for k, v in self.encoder.items()} _A: Any = errors # how to handle errors in decoding _A: Dict = bytes_to_unicode() _A: Optional[int] = {v: k for k, v in self.byte_encoder.items()} with open(lowerCAmelCase_ , encoding='''utf-8''' ) as merges_handle: _A: Optional[Any] = merges_handle.read().split('''\n''' )[1:-1] _A: Any = [tuple(merge.split() ) for merge in bpe_merges] _A: Dict = dict(zip(lowerCAmelCase_ , range(len(lowerCAmelCase_ ) ) ) ) _A: Optional[int] = {} _A: Any = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions _A: List[str] = re.compile(R'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' ) @property def __magic_name__ ( self : Optional[int] ): """simple docstring""" return len(self.encoder ) def __magic_name__ ( self : Optional[Any] ): """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def __magic_name__ ( self : Optional[Any] , lowerCAmelCase_ : int ): """simple docstring""" if token in self.cache: return self.cache[token] _A: Optional[int] = tuple(lowerCAmelCase_ ) _A: int = get_pairs(lowerCAmelCase_ ) if not pairs: return token while True: _A: Dict = min(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : self.bpe_ranks.get(lowerCAmelCase_ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break _A , _A: List[str] = bigram _A: Optional[int] = [] _A: Optional[Any] = 0 while i < len(lowerCAmelCase_ ): try: _A: Dict = word.index(lowerCAmelCase_ , lowerCAmelCase_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) _A: List[Any] = j if word[i] == first and i < len(lowerCAmelCase_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 _A: List[str] = tuple(lowerCAmelCase_ ) _A: str = new_word if len(lowerCAmelCase_ ) == 1: break else: _A: int = get_pairs(lowerCAmelCase_ ) _A: Optional[int] = ''' '''.join(lowerCAmelCase_ ) _A: Optional[int] = word return word def __magic_name__ ( self : List[Any] , lowerCAmelCase_ : Any ): """simple docstring""" _A: Dict = [] for token in re.findall(self.pat , lowerCAmelCase_ ): _A: Optional[Any] = ''''''.join( self.byte_encoder[b] for b in token.encode('''utf-8''' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(lowerCAmelCase_ ).split(''' ''' ) ) return bpe_tokens def __magic_name__ ( self : Any , lowerCAmelCase_ : Tuple ): """simple docstring""" return self.encoder.get(lowerCAmelCase_ , self.encoder.get(self.unk_token ) ) def __magic_name__ ( self : str , lowerCAmelCase_ : Union[str, Any] ): """simple docstring""" return self.decoder.get(lowerCAmelCase_ ) def __magic_name__ ( self : Dict , lowerCAmelCase_ : Dict ): """simple docstring""" _A: Dict = ''''''.join(lowerCAmelCase_ ) _A: List[str] = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''' , errors=self.errors ) return text def __magic_name__ ( self : Any , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[str] = None ): """simple docstring""" if not os.path.isdir(lowerCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _A: int = os.path.join( lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) _A: str = os.path.join( lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(lowerCAmelCase_ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=lowerCAmelCase_ , ensure_ascii=lowerCAmelCase_ ) + '''\n''' ) _A: Any = 0 with open(lowerCAmelCase_ , '''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 lowerCAmelCase_ : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" ''' Please check that the tokenizer is not corrupted!''' ) _A: Optional[int] = token_index writer.write(''' '''.join(lowerCAmelCase_ ) + '''\n''' ) index += 1 return vocab_file, merge_file def __magic_name__ ( self : str , lowerCAmelCase_ : List[int] , lowerCAmelCase_ : Optional[List[int]] = None ): """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _A: Tuple = [self.cls_token_id] _A: List[str] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __magic_name__ ( self : Dict , lowerCAmelCase_ : List[int] , lowerCAmelCase_ : Optional[List[int]] = None , lowerCAmelCase_ : bool = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowerCAmelCase_ , token_ids_a=lowerCAmelCase_ , already_has_special_tokens=lowerCAmelCase_ ) if token_ids_a is None: return [1] + ([0] * len(lowerCAmelCase_ )) + [1] return [1] + ([0] * len(lowerCAmelCase_ )) + [1, 1] + ([0] * len(lowerCAmelCase_ )) + [1] def __magic_name__ ( self : int , lowerCAmelCase_ : List[int] , lowerCAmelCase_ : Optional[List[int]] = None ): """simple docstring""" _A: Optional[int] = [self.sep_token_id] _A: List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __magic_name__ ( self : str , lowerCAmelCase_ : int , lowerCAmelCase_ : Any=False , **lowerCAmelCase_ : int ): """simple docstring""" _A: Any = kwargs.pop('''add_prefix_space''' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(lowerCAmelCase_ ) > 0 and not text[0].isspace()): _A: str = ''' ''' + text return (text, kwargs)
301
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=SCREAMING_SNAKE_CASE__ ) class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : str = field(default='''automatic-speech-recognition''' , metadata={'''include_in_asdict_even_if_is_default''': True} ) __UpperCamelCase : ClassVar[Features] = Features({'''audio''': Audio()} ) __UpperCamelCase : ClassVar[Features] = Features({'''transcription''': Value('''string''' )} ) __UpperCamelCase : str = "audio" __UpperCamelCase : str = "transcription" def __magic_name__ ( self : List[Any] , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" if self.audio_column not in features: raise ValueError(F"""Column {self.audio_column} is not present in features.""" ) if not isinstance(features[self.audio_column] , lowerCAmelCase_ ): raise ValueError(F"""Column {self.audio_column} is not an Audio type.""" ) _A: Optional[int] = copy.deepcopy(self ) _A: str = self.input_schema.copy() _A: List[str] = features[self.audio_column] _A: Dict = input_schema return task_template @property def __magic_name__ ( self : str ): """simple docstring""" return {self.audio_column: "audio", self.transcription_column: "transcription"}
301
1
# Author: OMKAR PATHAK, Nwachukwu Chidiebere # Use a Python dictionary to construct the graph. from __future__ import annotations from pprint import pformat from typing import Generic, TypeVar UpperCAmelCase__ : int = TypeVar('T') class UpperCAmelCase ( Generic[T] ): '''simple docstring''' def __init__( self : List[str] , lowerCAmelCase_ : bool = True ): """simple docstring""" _A: dict[T, list[T]] = {} # dictionary of lists _A: List[str] = directed def __magic_name__ ( self : Any , lowerCAmelCase_ : T , lowerCAmelCase_ : T ): """simple docstring""" if not self.directed: # For undirected graphs # if both source vertex and destination vertex are both present in the # adjacency list, add destination vertex to source vertex list of adjacent # vertices and add source vertex to destination vertex list of adjacent # vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(lowerCAmelCase_ ) self.adj_list[destination_vertex].append(lowerCAmelCase_ ) # if only source vertex is present in adjacency list, add destination vertex # to source vertex list of adjacent vertices, then create a new vertex with # destination vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(lowerCAmelCase_ ) _A: List[Any] = [source_vertex] # if only destination vertex is present in adjacency list, add source vertex # to destination vertex list of adjacent vertices, then create a new vertex # with source vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif destination_vertex in self.adj_list: self.adj_list[destination_vertex].append(lowerCAmelCase_ ) _A: Optional[int] = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and assign a list # containing the destination vertex as it's first adjacent vertex also # create a new vertex with destination vertex as key and assign a list # containing the source vertex as it's first adjacent vertex. else: _A: Union[str, Any] = [destination_vertex] _A: Dict = [source_vertex] else: # For directed graphs # if both source vertex and destination vertex are present in adjacency # list, add destination vertex to source vertex list of adjacent vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(lowerCAmelCase_ ) # if only source vertex is present in adjacency list, add destination # vertex to source vertex list of adjacent vertices and create a new vertex # with destination vertex as key, which has no adjacent vertex elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(lowerCAmelCase_ ) _A: int = [] # if only destination vertex is present in adjacency list, create a new # vertex with source vertex as key and assign a list containing destination # vertex as first adjacent vertex elif destination_vertex in self.adj_list: _A: str = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and a list containing # destination vertex as it's first adjacent vertex. Then create a new vertex # with destination vertex as key, which has no adjacent vertex else: _A: Tuple = [destination_vertex] _A: str = [] return self def __repr__( self : Tuple ): """simple docstring""" return pformat(self.adj_list )
301
import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer UpperCAmelCase__ : Optional[int] = 'bart' UpperCAmelCase__ : Dict = True @st.cache(allow_output_mutation=a ) def lowerCamelCase__ ( ) -> Dict: if LOAD_DENSE_INDEX: _A: Optional[Any] = AutoTokenizer.from_pretrained('''yjernite/retribert-base-uncased''' ) _A: Any = AutoModel.from_pretrained('''yjernite/retribert-base-uncased''' ).to('''cuda:0''' ) _A: Any = qar_model.eval() else: _A , _A: Union[str, Any] = (None, None) if MODEL_TYPE == "bart": _A: Union[str, Any] = AutoTokenizer.from_pretrained('''yjernite/bart_eli5''' ) _A: Dict = AutoModelForSeqaSeqLM.from_pretrained('''yjernite/bart_eli5''' ).to('''cuda:0''' ) _A: Union[str, Any] = torch.load('''seq2seq_models/eli5_bart_model_blm_2.pth''' ) sas_model.load_state_dict(save_dict['''model'''] ) _A: int = sas_model.eval() else: _A , _A: Tuple = make_qa_sas_model( model_name='''t5-small''' , from_file='''seq2seq_models/eli5_t5_model_1024_4.pth''' , device='''cuda:0''' ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=a ) def lowerCamelCase__ ( ) -> Tuple: if LOAD_DENSE_INDEX: _A: List[Any] = faiss.StandardGpuResources() _A: int = datasets.load_dataset(path='''wiki_snippets''' , name='''wiki40b_en_100_0''' )['''train'''] _A: Dict = np.memmap( '''wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat''' , dtype='''float32''' , mode='''r''' , shape=(wikiaab_passages.num_rows, 1_28) , ) _A: str = faiss.IndexFlatIP(1_28 ) _A: Optional[int] = faiss.index_cpu_to_gpu(a , 1 , a ) wikiaab_gpu_index_flat.add(a ) # TODO fix for larger GPU else: _A , _A: str = (None, None) _A: Tuple = Elasticsearch([{'''host''': '''localhost''', '''port''': '''9200'''}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=a ) def lowerCamelCase__ ( ) -> str: _A: Dict = datasets.load_dataset('''eli5''' , name='''LFQA_reddit''' ) _A: Dict = elia['''train_eli5'''] _A: List[Any] = np.memmap( '''eli5_questions_reps.dat''' , dtype='''float32''' , mode='''r''' , shape=(elia_train.num_rows, 1_28) ) _A: Any = faiss.IndexFlatIP(1_28 ) eli5_train_q_index.add(a ) return (elia_train, eli5_train_q_index) UpperCAmelCase__ ,UpperCAmelCase__ ,UpperCAmelCase__ : int = load_indexes() UpperCAmelCase__ ,UpperCAmelCase__ ,UpperCAmelCase__ ,UpperCAmelCase__ : Any = load_models() UpperCAmelCase__ ,UpperCAmelCase__ : Tuple = load_train_data() def lowerCamelCase__ ( a , a=10 ) -> str: _A: Optional[int] = embed_questions_for_retrieval([question] , a , a ) _A , _A: List[str] = eli5_train_q_index.search(a , a ) _A: Dict = [elia_train[int(a )] for i in I[0]] return nn_examples def lowerCamelCase__ ( a , a="wiki40b" , a="dense" , a=10 ) -> str: if source == "none": _A , _A: Any = (''' <P> '''.join(['''''' for _ in range(11 )] ).strip(), []) else: if method == "dense": _A , _A: List[Any] = query_qa_dense_index( a , a , a , a , a , a ) else: _A , _A: Tuple = query_es_index( a , a , index_name='''english_wiki40b_snippets_100w''' , n_results=a , ) _A: Union[str, Any] = [ (res['''article_title'''], res['''section_title'''].strip(), res['''score'''], res['''passage_text''']) for res in hit_lst ] _A: str = '''question: {} context: {}'''.format(a , a ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda a : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda a : None), } ) def lowerCamelCase__ ( a , a , a , a=64 , a=2_56 , a=False , a=2 , a=0.95 , a=0.8 ) -> str: with torch.no_grad(): _A: Optional[int] = qa_sas_generate( a , a , a , num_answers=1 , num_beams=a , min_len=a , max_len=a , do_sample=a , temp=a , top_p=a , top_k=a , max_input_length=10_24 , device='''cuda:0''' , )[0] return (answer, support_list) st.title('Long Form Question Answering with ELI5') # Start sidebar UpperCAmelCase__ : List[Any] = '<img src=\'https://huggingface.co/front/assets/huggingface_logo.svg\'>' UpperCAmelCase__ : Optional[Any] = '\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class="img-container"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n' % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia UpperCAmelCase__ : str = '\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n' st.sidebar.markdown(description, unsafe_allow_html=True) UpperCAmelCase__ : str = [ 'Answer the question', 'View the retrieved document only', 'View the most similar ELI5 question and answer', 'Show me everything, please!', ] UpperCAmelCase__ : Optional[int] = st.sidebar.checkbox('Demo options') if demo_options: UpperCAmelCase__ : Any = st.sidebar.selectbox( '', action_list, index=3, ) UpperCAmelCase__ : List[str] = action_list.index(action_st) UpperCAmelCase__ : Optional[Any] = st.sidebar.selectbox( '', ['Show full text of passages', 'Show passage section titles'], index=0, ) UpperCAmelCase__ : List[Any] = show_type == 'Show full text of passages' else: UpperCAmelCase__ : Dict = 3 UpperCAmelCase__ : str = True UpperCAmelCase__ : Optional[Any] = st.sidebar.checkbox('Retrieval options') if retrieval_options: UpperCAmelCase__ : List[str] = '\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n ' st.sidebar.markdown(retriever_info) UpperCAmelCase__ : Optional[int] = st.sidebar.selectbox('Which Wikipedia format should the model use?', ['wiki40b', 'none']) UpperCAmelCase__ : int = st.sidebar.selectbox('Which Wikipedia indexer should the model use?', ['dense', 'sparse', 'mixed']) else: UpperCAmelCase__ : Tuple = 'wiki40b' UpperCAmelCase__ : List[Any] = 'dense' UpperCAmelCase__ : Tuple = 'beam' UpperCAmelCase__ : Any = 2 UpperCAmelCase__ : Dict = 64 UpperCAmelCase__ : Any = 256 UpperCAmelCase__ : int = None UpperCAmelCase__ : List[str] = None UpperCAmelCase__ : Optional[int] = st.sidebar.checkbox('Generation options') if generate_options: UpperCAmelCase__ : Any = '\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder\'s output probabilities.\n ' st.sidebar.markdown(generate_info) UpperCAmelCase__ : Optional[int] = st.sidebar.selectbox('Would you like to use beam search or sample an answer?', ['beam', 'sampled']) UpperCAmelCase__ : int = st.sidebar.slider( 'Minimum generation length', min_value=8, max_value=256, value=64, step=8, format=None, key=None ) UpperCAmelCase__ : str = st.sidebar.slider( 'Maximum generation length', min_value=64, max_value=512, value=256, step=16, format=None, key=None ) if sampled == "beam": UpperCAmelCase__ : Tuple = st.sidebar.slider('Beam size', min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: UpperCAmelCase__ : List[Any] = st.sidebar.slider( 'Nucleus sampling p', min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None ) UpperCAmelCase__ : Union[str, Any] = st.sidebar.slider( 'Temperature', min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None ) UpperCAmelCase__ : Optional[int] = None # start main text UpperCAmelCase__ : Any = [ '<MY QUESTION>', 'How do people make chocolate?', 'Why do we get a fever when we are sick?', 'How can different animals perceive different colors?', 'What is natural language processing?', 'What\'s the best way to treat a sunburn?', 'What exactly are vitamins ?', 'How does nuclear energy provide electricity?', 'What\'s the difference between viruses and bacteria?', 'Why are flutes classified as woodwinds when most of them are made out of metal ?', 'Why do people like drinking coffee even though it tastes so bad?', 'What happens when wine ages? How does it make the wine taste better?', 'If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?', 'How can we set a date to the beginning or end of an artistic period? Doesn\'t the change happen gradually?', 'How does New Zealand have so many large bird predators?', ] UpperCAmelCase__ : List[Any] = st.selectbox( 'What would you like to ask? ---- select <MY QUESTION> to enter a new query', questions_list, index=1, ) if question_s == "<MY QUESTION>": UpperCAmelCase__ : Any = st.text_input('Enter your question here:', '') else: UpperCAmelCase__ : int = question_s if st.button('Show me!'): if action in [0, 1, 3]: if index_type == "mixed": UpperCAmelCase__ ,UpperCAmelCase__ : Tuple = make_support(question, source=wiki_source, method='dense', n_results=10) UpperCAmelCase__ ,UpperCAmelCase__ : Optional[Any] = make_support(question, source=wiki_source, method='sparse', n_results=10) UpperCAmelCase__ : Dict = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] UpperCAmelCase__ : str = support_list[:10] UpperCAmelCase__ : str = '<P> ' + ' <P> '.join([res[-1] for res in support_list]) else: UpperCAmelCase__ ,UpperCAmelCase__ : List[Any] = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: UpperCAmelCase__ ,UpperCAmelCase__ : Optional[Any] = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == 'sampled'), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown('### The model generated answer is:') st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown('--- \n ### The model is drawing information from the following Wikipedia passages:') for i, res in enumerate(support_list): UpperCAmelCase__ : Any = 'https://en.wikipedia.org/wiki/{}'.format(res[0].replace(' ', '_')) UpperCAmelCase__ : Tuple = res[1].strip() if sec_titles == "": UpperCAmelCase__ : Optional[int] = '[{}]({})'.format(res[0], wiki_url) else: UpperCAmelCase__ : int = sec_titles.split(' & ') UpperCAmelCase__ : Union[str, Any] = ' & '.join( ['[{}]({}#{})'.format(sec.strip(), wiki_url, sec.strip().replace(' ', '_')) for sec in sec_list] ) st.markdown( '{0:02d} - **Article**: {1:<18} <br> _Section_: {2}'.format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( '> <span style="font-family:arial; font-size:10pt;">' + res[-1] + '</span>', unsafe_allow_html=True ) if action in [2, 3]: UpperCAmelCase__ : Union[str, Any] = find_nearest_training(question) UpperCAmelCase__ : int = nn_train_list[0] st.markdown( '--- \n ### The most similar question in the ELI5 training set was: \n\n {}'.format(train_exple['title']) ) UpperCAmelCase__ : Tuple = [ '{}. {}'.format(i + 1, ' \n'.join([line.strip() for line in ans.split('\n') if line.strip() != ''])) for i, (ans, sc) in enumerate(zip(train_exple['answers']['text'], train_exple['answers']['score'])) if i == 0 or sc > 2 ] st.markdown('##### Its answers were: \n\n {}'.format('\n'.join(answers_st))) UpperCAmelCase__ : Any = '\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n' st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
301
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ : List[str] = logging.get_logger(__name__) UpperCAmelCase__ : Optional[Any] = { 'MIT/ast-finetuned-audioset-10-10-0.4593': ( 'https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json' ), } class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Dict = '''audio-spectrogram-transformer''' def __init__( self : Union[str, Any] , lowerCAmelCase_ : Dict=7_6_8 , lowerCAmelCase_ : Optional[int]=1_2 , lowerCAmelCase_ : Any=1_2 , lowerCAmelCase_ : Any=3_0_7_2 , lowerCAmelCase_ : str="gelu" , lowerCAmelCase_ : Tuple=0.0 , lowerCAmelCase_ : Dict=0.0 , lowerCAmelCase_ : List[str]=0.02 , lowerCAmelCase_ : Optional[Any]=1e-12 , lowerCAmelCase_ : Optional[Any]=1_6 , lowerCAmelCase_ : Union[str, Any]=True , lowerCAmelCase_ : Optional[Any]=1_0 , lowerCAmelCase_ : Tuple=1_0 , lowerCAmelCase_ : Dict=1_0_2_4 , lowerCAmelCase_ : Tuple=1_2_8 , **lowerCAmelCase_ : Optional[int] , ): """simple docstring""" super().__init__(**lowerCAmelCase_ ) _A: str = hidden_size _A: int = num_hidden_layers _A: Optional[int] = num_attention_heads _A: Any = intermediate_size _A: Dict = hidden_act _A: List[Any] = hidden_dropout_prob _A: Optional[Any] = attention_probs_dropout_prob _A: Union[str, Any] = initializer_range _A: Dict = layer_norm_eps _A: str = patch_size _A: Optional[Any] = qkv_bias _A: Union[str, Any] = frequency_stride _A: List[Any] = time_stride _A: Union[str, Any] = max_length _A: List[Any] = num_mel_bins
301
from __future__ import annotations UpperCAmelCase__ : List[str] = list[list[int]] # assigning initial values to the grid UpperCAmelCase__ : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution UpperCAmelCase__ : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def lowerCamelCase__ ( a , a , a , a ) -> bool: for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def lowerCamelCase__ ( a ) -> tuple[int, int] | None: for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def lowerCamelCase__ ( a ) -> Matrix | None: if location := find_empty_location(a ): _A , _A: Optional[Any] = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(a , a , a , a ): _A: str = digit if sudoku(a ) is not None: return grid _A: Tuple = 0 return None def lowerCamelCase__ ( a ) -> None: for row in grid: for cell in row: print(a , end=''' ''' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('\nExample grid:\n' + '=' * 20) print_solution(example_grid) print('\nExample grid solution:') UpperCAmelCase__ : int = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('Cannot find a solution.')
301
1
import copy from ...configuration_utils import PretrainedConfig from ...utils import add_start_docstrings UpperCAmelCase__ : Tuple = R'\n [`RagConfig`] stores the configuration of a *RagModel*. Configuration objects inherit from [`PretrainedConfig`] and\n can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.\n\n Args:\n title_sep (`str`, *optional*, defaults to `" / "`):\n Separator inserted between the title and the text of the retrieved document when calling [`RagRetriever`].\n doc_sep (`str`, *optional*, defaults to `" // "`):\n Separator inserted between the text of the retrieved document and the original input when calling\n [`RagRetriever`].\n n_docs (`int`, *optional*, defaults to 5):\n Number of documents to retrieve.\n max_combined_length (`int`, *optional*, defaults to 300):\n Max length of contextualized input returned by [`~RagRetriever.__call__`].\n retrieval_vector_size (`int`, *optional*, defaults to 768):\n Dimensionality of the document embeddings indexed by [`RagRetriever`].\n retrieval_batch_size (`int`, *optional*, defaults to 8):\n Retrieval batch size, defined as the number of queries issues concurrently to the faiss index encapsulated\n [`RagRetriever`].\n dataset (`str`, *optional*, defaults to `"wiki_dpr"`):\n A dataset identifier of the indexed dataset in HuggingFace Datasets (list all available datasets and ids\n using `datasets.list_datasets()`).\n dataset_split (`str`, *optional*, defaults to `"train"`)\n Which split of the `dataset` to load.\n index_name (`str`, *optional*, defaults to `"compressed"`)\n The index name of the index associated with the `dataset`. One can choose between `"legacy"`, `"exact"` and\n `"compressed"`.\n index_path (`str`, *optional*)\n The path to the serialized faiss index on disk.\n passages_path (`str`, *optional*):\n A path to text passages compatible with the faiss index. Required if using\n [`~models.rag.retrieval_rag.LegacyIndex`]\n use_dummy_dataset (`bool`, *optional*, defaults to `False`)\n Whether to load a "dummy" variant of the dataset specified by `dataset`.\n label_smoothing (`float`, *optional*, defaults to 0.0):\n Only relevant if `return_loss` is set to `True`. Controls the `epsilon` parameter value for label smoothing\n in the loss calculation. If set to 0, no label smoothing is performed.\n do_marginalize (`bool`, *optional*, defaults to `False`):\n If `True`, the logits are marginalized over all documents by making use of\n `torch.nn.functional.log_softmax`.\n reduce_loss (`bool`, *optional*, defaults to `False`):\n Whether or not to reduce the NLL loss using the `torch.Tensor.sum` operation.\n do_deduplication (`bool`, *optional*, defaults to `True`):\n Whether or not to deduplicate the generations from different context documents for a given input. Has to be\n set to `False` if used while training with distributed backend.\n exclude_bos_score (`bool`, *optional*, defaults to `False`):\n Whether or not to disregard the BOS token when computing the loss.\n output_retrieved(`bool`, *optional*, defaults to `False`):\n If set to `True`, `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and\n `context_attention_mask` are returned. See returned tensors for more detail.\n use_cache (`bool`, *optional*, defaults to `True`):\n Whether or not the model should return the last key/values attentions (not used by all models).\n forced_eos_token_id (`int`, *optional*):\n The id of the token to force as the last generated token when `max_length` is reached. Usually set to\n `eos_token_id`.\n' @add_start_docstrings(SCREAMING_SNAKE_CASE__ ) class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : int = '''rag''' __UpperCamelCase : List[Any] = True def __init__( self : List[str] , lowerCAmelCase_ : Optional[Any]=None , lowerCAmelCase_ : List[Any]=True , lowerCAmelCase_ : Union[str, Any]=None , lowerCAmelCase_ : Dict=None , lowerCAmelCase_ : List[Any]=None , lowerCAmelCase_ : Any=None , lowerCAmelCase_ : Any=None , lowerCAmelCase_ : List[str]=" / " , lowerCAmelCase_ : int=" // " , lowerCAmelCase_ : List[str]=5 , lowerCAmelCase_ : Union[str, Any]=3_0_0 , lowerCAmelCase_ : Union[str, Any]=7_6_8 , lowerCAmelCase_ : int=8 , lowerCAmelCase_ : Optional[int]="wiki_dpr" , lowerCAmelCase_ : int="train" , lowerCAmelCase_ : Optional[Any]="compressed" , lowerCAmelCase_ : List[str]=None , lowerCAmelCase_ : str=None , lowerCAmelCase_ : List[Any]=False , lowerCAmelCase_ : int=False , lowerCAmelCase_ : Optional[int]=0.0 , lowerCAmelCase_ : int=True , lowerCAmelCase_ : Optional[int]=False , lowerCAmelCase_ : List[Any]=False , lowerCAmelCase_ : Tuple=False , lowerCAmelCase_ : Any=True , lowerCAmelCase_ : str=None , **lowerCAmelCase_ : Optional[int] , ): """simple docstring""" super().__init__( bos_token_id=lowerCAmelCase_ , pad_token_id=lowerCAmelCase_ , eos_token_id=lowerCAmelCase_ , decoder_start_token_id=lowerCAmelCase_ , forced_eos_token_id=lowerCAmelCase_ , is_encoder_decoder=lowerCAmelCase_ , prefix=lowerCAmelCase_ , vocab_size=lowerCAmelCase_ , **lowerCAmelCase_ , ) assert ( "question_encoder" in kwargs and "generator" in kwargs ), "Config has to be initialized with question_encoder and generator config" _A: Optional[Any] = kwargs.pop('''question_encoder''' ) _A: Optional[int] = question_encoder_config.pop('''model_type''' ) _A: Tuple = kwargs.pop('''generator''' ) _A: int = decoder_config.pop('''model_type''' ) from ..auto.configuration_auto import AutoConfig _A: List[Any] = AutoConfig.for_model(lowerCAmelCase_ , **lowerCAmelCase_ ) _A: Tuple = AutoConfig.for_model(lowerCAmelCase_ , **lowerCAmelCase_ ) _A: List[str] = reduce_loss _A: Tuple = label_smoothing _A: Optional[Any] = exclude_bos_score _A: List[str] = do_marginalize _A: Dict = title_sep _A: List[Any] = doc_sep _A: Any = n_docs _A: Any = max_combined_length _A: Dict = dataset _A: int = dataset_split _A: int = index_name _A: Optional[Any] = retrieval_vector_size _A: Union[str, Any] = retrieval_batch_size _A: List[Any] = passages_path _A: List[str] = index_path _A: Dict = use_dummy_dataset _A: int = output_retrieved _A: Any = do_deduplication _A: str = use_cache if self.forced_eos_token_id is None: _A: List[str] = getattr(self.generator , '''forced_eos_token_id''' , lowerCAmelCase_ ) @classmethod def __magic_name__ ( cls : str , lowerCAmelCase_ : PretrainedConfig , lowerCAmelCase_ : PretrainedConfig , **lowerCAmelCase_ : Union[str, Any] ): """simple docstring""" return cls(question_encoder=question_encoder_config.to_dict() , generator=generator_config.to_dict() , **lowerCAmelCase_ ) def __magic_name__ ( self : Dict ): """simple docstring""" _A: Optional[int] = copy.deepcopy(self.__dict__ ) _A: Tuple = self.question_encoder.to_dict() _A: Any = self.generator.to_dict() _A: Optional[int] = self.__class__.model_type return output
301
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests UpperCAmelCase__ : str = open # noqa: we just need to have a builtin inside this module to test it properly
301
1
import json import os from datetime import date from pathlib import Path from tabulate import DataRow, TableFormat, tabulate UpperCAmelCase__ : Optional[Any] = TableFormat( lineabove=None, linebelowheader=None, linebetweenrows=None, linebelow=None, headerrow=DataRow('', '|', '|'), datarow=DataRow('', '|', '|'), padding=1, with_header_hide=None, ) UpperCAmelCase__ : Dict = [] UpperCAmelCase__ : Optional[Any] = [] UpperCAmelCase__ : List[Any] = {'type': 'section', 'text': {'type': 'plain_text', 'text': 'No failed tests! 🤗', 'emoji': True}} UpperCAmelCase__ : Tuple = [ { 'type': 'header', 'text': { 'type': 'plain_text', 'text': F"""🤗 Accelerate nightly {os.environ.get("TEST_TYPE", "")} test results""", 'emoji': True, }, } ] UpperCAmelCase__ : Optional[Any] = 0 for log in Path().glob('*.log'): UpperCAmelCase__ : List[str] = 0 with open(log, 'r') as f: for line in f: UpperCAmelCase__ : List[Any] = json.loads(line) if line.get('nodeid', '') != "": UpperCAmelCase__ : Optional[Any] = line['nodeid'] if line.get('duration', None) is not None: UpperCAmelCase__ : Dict = F"""{line["duration"]:.4f}""" if line.get('outcome', '') == "failed": section_num_failed += 1 failed.append([test, duration, log.name.split('_')[0]]) total_num_failed += 1 group_info.append([str(log), section_num_failed, failed]) UpperCAmelCase__ : Tuple = [] log.unlink() UpperCAmelCase__ : List[Any] = '' UpperCAmelCase__ : Dict = [] if total_num_failed > 0: for name, num_failed, failed_tests in group_info: if num_failed > 0: if num_failed == 1: message += F"*{name[1:]}: {num_failed} failed test*\n" else: message += F"*{name[1:]}: {num_failed} failed tests*\n" UpperCAmelCase__ : Dict = [] UpperCAmelCase__ : Tuple = {} for test in failed_tests: UpperCAmelCase__ : int = test[0].split('::') UpperCAmelCase__ : Optional[int] = data[0].split('/')[-1] if data[0] not in filesafailed: UpperCAmelCase__ : Any = [data[1:]] else: filesafailed[data[0]] += [data[1:]] failed_table.append(data) UpperCAmelCase__ : Any = [test[0] for test in failed_table] UpperCAmelCase__ : str = list(set(files)) # Count number of instances in failed_tests UpperCAmelCase__ : Tuple = [] for file in individual_files: table.append([file, len(filesafailed[file])]) UpperCAmelCase__ : List[Any] = tabulate( table, headers=['Test Location', 'Num Failed'], tablefmt=hf_table_format, stralign='right', ) message += F"\n```\n{failed_table}\n```" all_filesafailed.append(filesafailed) if len(message) > 3000: UpperCAmelCase__ : List[str] = 'Too many failed tests, please see the full report in the Action results.' UpperCAmelCase__ : Optional[Any] = len(err) + 10 UpperCAmelCase__ : List[Any] = message[: 3000 - offset] + F"""\n...\n```\n{err}""" print(F"""### {message}""") else: UpperCAmelCase__ : Optional[Any] = 'No failed tests! 🤗' print(F"""## {message}""") payload.append(no_error_payload) if os.environ.get('TEST_TYPE', '') != "": from slack_sdk import WebClient UpperCAmelCase__ : List[str] = WebClient(token=os.environ['SLACK_API_TOKEN']) if message != "No failed tests! 🤗": UpperCAmelCase__ : Dict = { 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': message, }, } payload.append(md_report) UpperCAmelCase__ : Union[str, Any] = { 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': '*For more details:*', }, 'accessory': { 'type': 'button', 'text': { 'type': 'plain_text', 'text': 'Check Action results', 'emoji': True, }, 'url': F"""https://github.com/{os.environ["GITHUB_REPOSITORY"]}/actions/runs/{os.environ["GITHUB_RUN_ID"]}""", }, } payload.append(action_button) UpperCAmelCase__ : List[Any] = { 'type': 'context', 'elements': [ { 'type': 'plain_text', 'text': F"""Nightly {os.environ.get("TEST_TYPE")} test results for {date.today()}""", } ], } payload.append(date_report) UpperCAmelCase__ : List[Any] = client.chat_postMessage(channel='#accelerate-ci-daily', text=message, blocks=payload) UpperCAmelCase__ : List[str] = response.data['ts'] for failed_file in all_filesafailed: for test_location, test_failures in failed_file.items(): # Keep only the first instance of the test name UpperCAmelCase__ : Optional[int] = '' for i, row in enumerate(test_failures): if row[0] != test_class: UpperCAmelCase__ : Optional[int] = row[0] else: UpperCAmelCase__ : int = '' UpperCAmelCase__ : Optional[int] = { 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': F"""Test location: {test_location}\n```\n{tabulate(test_failures, headers=["Class", "Test"], tablefmt=hf_table_format, stralign="right")}\n```""", }, } client.chat_postMessage( channel='#accelerate-ci-daily', thread_ts=ts, blocks=[payload], )
301
import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Optional[Any] , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : List[str]=3 , lowerCAmelCase_ : List[str]=3_2 , lowerCAmelCase_ : Union[str, Any]=3 , lowerCAmelCase_ : int=1_0 , lowerCAmelCase_ : Tuple=[1_0, 2_0, 3_0, 4_0] , lowerCAmelCase_ : Optional[Any]=[1, 1, 2, 1] , lowerCAmelCase_ : Optional[Any]=True , lowerCAmelCase_ : str=True , lowerCAmelCase_ : Optional[Any]="relu" , lowerCAmelCase_ : int=3 , lowerCAmelCase_ : List[Any]=None , ): """simple docstring""" _A: str = parent _A: List[Any] = batch_size _A: Optional[int] = image_size _A: Dict = num_channels _A: str = embeddings_size _A: Any = hidden_sizes _A: Dict = depths _A: Any = is_training _A: int = use_labels _A: Tuple = hidden_act _A: int = num_labels _A: int = scope _A: str = len(lowerCAmelCase_ ) def __magic_name__ ( self : Dict ): """simple docstring""" _A: Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _A: Union[str, Any] = self.get_config() return config, pixel_values def __magic_name__ ( self : str ): """simple docstring""" return RegNetConfig( 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 , image_size=self.image_size , ) def __magic_name__ ( self : str , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : str ): """simple docstring""" _A: str = FlaxRegNetModel(config=lowerCAmelCase_ ) _A: Optional[int] = model(lowerCAmelCase_ ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , ) def __magic_name__ ( self : str , lowerCAmelCase_ : str , lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Union[str, Any] = self.num_labels _A: Union[str, Any] = FlaxRegNetForImageClassification(config=lowerCAmelCase_ ) _A: str = model(lowerCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __magic_name__ ( self : List[Any] ): """simple docstring""" _A: str = self.prepare_config_and_inputs() _A , _A: Optional[int] = config_and_inputs _A: Union[str, Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_flax class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Tuple = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () __UpperCamelCase : Union[str, Any] = False __UpperCamelCase : List[Any] = False __UpperCamelCase : int = False def __magic_name__ ( self : int ): """simple docstring""" _A: int = FlaxRegNetModelTester(self ) _A: Union[str, Any] = ConfigTester(self , config_class=lowerCAmelCase_ , has_text_modality=lowerCAmelCase_ ) def __magic_name__ ( self : str ): """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __magic_name__ ( self : int ): """simple docstring""" return def __magic_name__ ( self : Tuple ): """simple docstring""" _A: int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase_ ) def __magic_name__ ( self : Tuple ): """simple docstring""" _A: Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_ ) @unittest.skip(reason='''RegNet does not use inputs_embeds''' ) def __magic_name__ ( self : str ): """simple docstring""" pass @unittest.skip(reason='''RegNet does not support input and output embeddings''' ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" pass def __magic_name__ ( self : List[Any] ): """simple docstring""" _A , _A: int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A: Union[str, Any] = model_class(lowerCAmelCase_ ) _A: Any = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _A: Any = [*signature.parameters.keys()] _A: Union[str, Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowerCAmelCase_ ) def __magic_name__ ( self : str ): """simple docstring""" def check_hidden_states_output(lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Tuple ): _A: int = model_class(lowerCAmelCase_ ) _A: List[str] = model(**self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ ) ) _A: str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _A: Tuple = self.model_tester.num_stages self.assertEqual(len(lowerCAmelCase_ ) , expected_num_stages + 1 ) _A , _A: List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A: Optional[Any] = True check_hidden_states_output(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _A: int = True check_hidden_states_output(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) def __magic_name__ ( self : Dict ): """simple docstring""" _A , _A: str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): _A: int = self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ ) _A: Union[str, Any] = model_class(lowerCAmelCase_ ) @jax.jit def model_jitted(lowerCAmelCase_ : Optional[Any] , **lowerCAmelCase_ : Optional[Any] ): return model(pixel_values=lowerCAmelCase_ , **lowerCAmelCase_ ) with self.subTest('''JIT Enabled''' ): _A: str = model_jitted(**lowerCAmelCase_ ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): _A: List[Any] = model_jitted(**lowerCAmelCase_ ).to_tuple() self.assertEqual(len(lowerCAmelCase_ ) , len(lowerCAmelCase_ ) ) for jitted_output, output in zip(lowerCAmelCase_ , lowerCAmelCase_ ): self.assertEqual(jitted_output.shape , output.shape ) def lowerCamelCase__ ( ) -> Tuple: _A: List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_flax class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" return AutoImageProcessor.from_pretrained('''facebook/regnet-y-040''' ) if is_vision_available() else None @slow def __magic_name__ ( self : List[str] ): """simple docstring""" _A: List[str] = FlaxRegNetForImageClassification.from_pretrained('''facebook/regnet-y-040''' ) _A: str = self.default_image_processor _A: int = prepare_img() _A: List[Any] = image_processor(images=lowerCAmelCase_ , return_tensors='''np''' ) _A: str = model(**lowerCAmelCase_ ) # verify the logits _A: str = (1, 1_0_0_0) self.assertEqual(outputs.logits.shape , lowerCAmelCase_ ) _A: Tuple = jnp.array([-0.4180, -1.5051, -3.4836] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] , lowerCAmelCase_ , atol=1e-4 ) )
301
1
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 UpperCAmelCase__ : Tuple = 'src/transformers' # This is to make sure the transformers module imported is the one in the repo. UpperCAmelCase__ : Optional[Any] = direct_transformers_import(PATH_TO_TRANSFORMERS) UpperCAmelCase__ : str = transformers.models.auto.configuration_auto.CONFIG_MAPPING UpperCAmelCase__ : Tuple = { # 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__ ( a , a , a , a ) -> int: _A: Optional[Any] = 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 ): _A: int = 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 ): _A: Dict = 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: _A: Tuple = True if attribute_used: break if attribute_used: break # common and important attributes, even if they do not always appear in the modeling files _A: Union[str, Any] = [ '''bos_index''', '''eos_index''', '''pad_index''', '''unk_index''', '''mask_index''', '''image_size''', '''use_cache''', '''out_features''', '''out_indices''', ] _A: Any = ['''encoder_no_repeat_ngram_size'''] # Special cases to be allowed _A: List[str] = True if not attribute_used: _A: int = 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: _A: Optional[int] = True elif attribute in ["tie_word_embeddings"] and default_value is False: _A: Union[str, Any] = True # Allow cases without checking the default value in the configuration class elif attribute in attributes_to_allow + attributes_used_in_generation: _A: List[str] = True elif attribute.endswith('''_token_id''' ): _A: Optional[Any] = True # configuration class specific cases if not case_allowed: _A: List[str] = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__ , [] ) _A: Optional[int] = allowed_cases is True or attribute in allowed_cases return attribute_used or case_allowed def lowerCamelCase__ ( a ) -> Optional[int]: _A: str = dict(inspect.signature(config_class.__init__ ).parameters ) _A: Tuple = [x for x in list(signature.keys() ) if x not in ['''self''', '''kwargs''']] _A: Dict = [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 _A: str = {} if len(config_class.attribute_map ) > 0: _A: str = {v: k for k, v in config_class.attribute_map.items()} # Get the path to modeling source files _A: Optional[Any] = inspect.getsourcefile(a ) _A: Dict = os.path.dirname(a ) # Let's check against all frameworks: as long as one framework uses an attribute, we are good. _A: int = [os.path.join(a , a ) for fn in os.listdir(a ) if fn.startswith('''modeling_''' )] # Get the source code strings _A: Tuple = [] for path in modeling_paths: if os.path.isfile(a ): with open(a ) as fp: modeling_sources.append(fp.read() ) _A: Tuple = [] for config_param, default_value in zip(a , a ): # `attributes` here is all the variant names for `config_param` _A: Optional[int] = [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__ ( ) -> Union[str, Any]: _A: Dict = {} 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.) _A: Tuple = [ cls for name, cls in inspect.getmembers( inspect.getmodule(_config_class ) , lambda a : inspect.isclass(a ) and issubclass(a , a ) and inspect.getmodule(a ) == inspect.getmodule(_config_class ) , ) ] for config_class in config_classes_in_module: _A: Optional[int] = check_config_attributes_being_used(a ) if len(a ) > 0: _A: Optional[Any] = unused_attributes if len(a ) > 0: _A: Union[str, Any] = '''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()
301
from __future__ import annotations from bisect import bisect_left from functools import total_ordering from heapq import merge @total_ordering class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def __lt__( self : Dict , lowerCAmelCase_ : Optional[int] ): """simple docstring""" return self[-1] < other[-1] def __eq__( self : int , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" return self[-1] == other[-1] def lowerCamelCase__ ( a ) -> list: _A: list[Stack] = [] # sort into stacks for element in collection: _A: Any = Stack([element] ) _A: Optional[Any] = bisect_left(a , a ) if i != len(a ): stacks[i].append(a ) else: stacks.append(a ) # use a heap-based merge to merge stack efficiently _A: Tuple = merge(*(reversed(a ) for stack in stacks) ) return collection if __name__ == "__main__": UpperCAmelCase__ : Tuple = input('Enter numbers separated by a comma:\n').strip() UpperCAmelCase__ : Optional[Any] = [int(item) for item in user_input.split(',')] print(patience_sort(unsorted))
301
1
import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast UpperCAmelCase__ : List[Any] = datasets.utils.logging.get_logger(__name__) @dataclass class UpperCAmelCase ( datasets.BuilderConfig ): '''simple docstring''' __UpperCamelCase : int = 1_0000 __UpperCamelCase : Optional[List[str]] = None __UpperCamelCase : Optional[datasets.Features] = None class UpperCAmelCase ( datasets.ArrowBasedBuilder ): '''simple docstring''' __UpperCamelCase : Dict = ParquetConfig def __magic_name__ ( self : Any ): """simple docstring""" return datasets.DatasetInfo(features=self.config.features ) def __magic_name__ ( self : List[str] , lowerCAmelCase_ : str ): """simple docstring""" if not self.config.data_files: raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) _A: Optional[Any] = dl_manager.download_and_extract(self.config.data_files ) if isinstance(lowerCAmelCase_ , (str, list, tuple) ): _A: Any = data_files if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): _A: Union[str, Any] = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive _A: Optional[Any] = [dl_manager.iter_files(lowerCAmelCase_ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] _A: int = [] for split_name, files in data_files.items(): if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): _A: Dict = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive _A: List[str] = [dl_manager.iter_files(lowerCAmelCase_ ) for file in files] # Infer features is they are stoed in the arrow schema if self.info.features is None: for file in itertools.chain.from_iterable(lowerCAmelCase_ ): with open(lowerCAmelCase_ , '''rb''' ) as f: _A: int = datasets.Features.from_arrow_schema(pq.read_schema(lowerCAmelCase_ ) ) break splits.append(datasets.SplitGenerator(name=lowerCAmelCase_ , gen_kwargs={'''files''': files} ) ) return splits def __magic_name__ ( self : Optional[int] , lowerCAmelCase_ : pa.Table ): """simple docstring""" if self.info.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example _A: Any = table_cast(lowerCAmelCase_ , self.info.features.arrow_schema ) return pa_table def __magic_name__ ( self : Optional[int] , lowerCAmelCase_ : Any ): """simple docstring""" _A: List[Any] = self.info.features.arrow_schema if self.info.features is not None else None if self.info.features is not None and self.config.columns is not None: if sorted(field.name for field in schema ) != sorted(self.config.columns ): raise ValueError( F"""Tried to load parquet data with columns '{self.config.columns}' with mismatching features '{self.info.features}'""" ) for file_idx, file in enumerate(itertools.chain.from_iterable(lowerCAmelCase_ ) ): with open(lowerCAmelCase_ , '''rb''' ) as f: _A: Optional[Any] = pq.ParquetFile(lowerCAmelCase_ ) try: for batch_idx, record_batch in enumerate( parquet_file.iter_batches(batch_size=self.config.batch_size , columns=self.config.columns ) ): _A: str = pa.Table.from_batches([record_batch] ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield F"""{file_idx}_{batch_idx}""", self._cast_table(lowerCAmelCase_ ) except ValueError as e: logger.error(F"""Failed to read file '{file}' with error {type(lowerCAmelCase_ )}: {e}""" ) raise
301
import argparse import datetime import json import time import warnings from logging import getLogger from pathlib import Path from typing import Dict, List import torch from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils import calculate_bleu, calculate_rouge, chunks, parse_numeric_n_bool_cl_kwargs, use_task_specific_params UpperCAmelCase__ : Any = getLogger(__name__) UpperCAmelCase__ : Optional[Any] = 'cuda' if torch.cuda.is_available() else 'cpu' def lowerCamelCase__ ( a , a , a , a = 8 , a = DEFAULT_DEVICE , a=False , a="summarization" , a=None , **a , ) -> Dict: _A: str = Path(a ).open('''w''' , encoding='''utf-8''' ) _A: Optional[Any] = str(a ) _A: Union[str, Any] = AutoModelForSeqaSeqLM.from_pretrained(a ).to(a ) if fpaa: _A: Any = model.half() _A: Optional[int] = AutoTokenizer.from_pretrained(a ) logger.info(f"""Inferred tokenizer type: {tokenizer.__class__}""" ) # if this is wrong, check config.model_type. _A: Any = time.time() # update config with task specific params use_task_specific_params(a , a ) if prefix is None: _A: int = prefix or getattr(model.config , '''prefix''' , '''''' ) or '''''' for examples_chunk in tqdm(list(chunks(a , a ) ) ): _A: int = [prefix + text for text in examples_chunk] _A: str = tokenizer(a , return_tensors='''pt''' , truncation=a , padding='''longest''' ).to(a ) _A: str = model.generate( input_ids=batch.input_ids , attention_mask=batch.attention_mask , **a , ) _A: str = tokenizer.batch_decode(a , skip_special_tokens=a , clean_up_tokenization_spaces=a ) for hypothesis in dec: fout.write(hypothesis + '''\n''' ) fout.flush() fout.close() _A: Optional[int] = int(time.time() - start_time ) # seconds _A: Union[str, Any] = len(a ) return {"n_obs": n_obs, "runtime": runtime, "seconds_per_sample": round(runtime / n_obs , 4 )} def lowerCamelCase__ ( ) -> Tuple: return datetime.datetime.now().strftime('''%Y-%m-%d %H:%M:%S''' ) def lowerCamelCase__ ( a=True ) -> Optional[Any]: _A: str = argparse.ArgumentParser() parser.add_argument('''model_name''' , type=a , help='''like facebook/bart-large-cnn,t5-base, etc.''' ) parser.add_argument('''input_path''' , type=a , help='''like cnn_dm/test.source''' ) parser.add_argument('''save_path''' , type=a , help='''where to save summaries''' ) parser.add_argument('''--reference_path''' , type=a , required=a , help='''like cnn_dm/test.target''' ) parser.add_argument('''--score_path''' , type=a , required=a , default='''metrics.json''' , help='''where to save metrics''' ) parser.add_argument('''--device''' , type=a , required=a , default=a , help='''cuda, cuda:1, cpu etc.''' ) parser.add_argument( '''--prefix''' , type=a , required=a , default=a , help='''will be added to the begininng of src examples''' ) parser.add_argument('''--task''' , type=a , default='''summarization''' , help='''used for task_specific_params + metrics''' ) parser.add_argument('''--bs''' , type=a , default=8 , required=a , help='''batch size''' ) parser.add_argument( '''--n_obs''' , type=a , default=-1 , required=a , help='''How many observations. Defaults to all.''' ) parser.add_argument('''--fp16''' , action='''store_true''' ) parser.add_argument('''--dump-args''' , action='''store_true''' , help='''print the custom hparams with the results''' ) parser.add_argument( '''--info''' , nargs='''?''' , type=a , const=datetime_now() , help=( '''use in conjunction w/ --dump-args to print with the results whatever other info you\'d like, e.g.''' ''' lang=en-ru. If no value is passed, the current datetime string will be used.''' ) , ) # Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate _A , _A: Tuple = parser.parse_known_args() _A: List[str] = parse_numeric_n_bool_cl_kwargs(a ) if parsed_args and verbose: print(f"""parsed the following generate kwargs: {parsed_args}""" ) _A: int = [''' ''' + x.rstrip() if '''t5''' in args.model_name else x.rstrip() for x in open(args.input_path ).readlines()] if args.n_obs > 0: _A: List[str] = examples[: args.n_obs] Path(args.save_path ).parent.mkdir(exist_ok=a ) if args.reference_path is None and Path(args.score_path ).exists(): warnings.warn(f"""score_path {args.score_path} will be overwritten unless you type ctrl-c.""" ) if args.device == "cpu" and args.fpaa: # this mix leads to RuntimeError: "threshold_cpu" not implemented for 'Half' raise ValueError('''Can\'t mix --fp16 and --device cpu''' ) _A: Dict = generate_summaries_or_translations( a , args.save_path , args.model_name , batch_size=args.bs , device=args.device , fpaa=args.fpaa , task=args.task , prefix=args.prefix , **a , ) if args.reference_path is None: return {} # Compute scores _A: Dict = calculate_bleu if '''translation''' in args.task else calculate_rouge _A: List[Any] = [x.rstrip() for x in open(args.save_path ).readlines()] _A: Any = [x.rstrip() for x in open(args.reference_path ).readlines()][: len(a )] _A: dict = score_fn(a , a ) scores.update(a ) if args.dump_args: scores.update(a ) if args.info: _A: Optional[Any] = args.info if verbose: print(a ) if args.score_path is not None: json.dump(a , open(args.score_path , '''w''' ) ) return scores if __name__ == "__main__": # Usage for MT: # python run_eval.py MODEL_NAME $DATA_DIR/test.source $save_dir/test_translations.txt --reference_path $DATA_DIR/test.target --score_path $save_dir/test_bleu.json --task translation $@ run_generate(verbose=True)
301
1
import itertools import random import unittest import numpy as np from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaConfig, WavaVecaFeatureExtractor from transformers.testing_utils import require_torch, slow from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin UpperCAmelCase__ : Union[str, Any] = random.Random() def lowerCamelCase__ ( a , a=1.0 , a=None , a=None ) -> Optional[Any]: if rng is None: _A: Tuple = global_rng _A: Union[str, Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[Any] , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Any=7 , lowerCAmelCase_ : Dict=4_0_0 , lowerCAmelCase_ : Dict=2_0_0_0 , lowerCAmelCase_ : str=1 , lowerCAmelCase_ : Union[str, Any]=0.0 , lowerCAmelCase_ : Dict=1_6_0_0_0 , lowerCAmelCase_ : Optional[Any]=True , lowerCAmelCase_ : Dict=True , ): """simple docstring""" _A: Any = parent _A: int = batch_size _A: Any = min_seq_length _A: Optional[int] = max_seq_length _A: Any = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) _A: str = feature_size _A: Union[str, Any] = padding_value _A: Optional[int] = sampling_rate _A: List[Any] = return_attention_mask _A: Optional[int] = do_normalize def __magic_name__ ( self : Optional[int] ): """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def __magic_name__ ( self : Optional[int] , lowerCAmelCase_ : Optional[Any]=False , lowerCAmelCase_ : Any=False ): """simple docstring""" def _flatten(lowerCAmelCase_ : int ): return list(itertools.chain(*lowerCAmelCase_ ) ) if equal_length: _A: List[Any] = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size _A: List[Any] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: _A: int = [np.asarray(lowerCAmelCase_ ) for x in speech_inputs] return speech_inputs class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Dict = WavaVecaFeatureExtractor def __magic_name__ ( self : str ): """simple docstring""" _A: Union[str, Any] = WavaVecaFeatureExtractionTester(self ) def __magic_name__ ( self : List[Any] , lowerCAmelCase_ : Optional[int] ): """simple docstring""" self.assertTrue(np.all(np.mean(lowerCAmelCase_ , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(lowerCAmelCase_ , axis=0 ) - 1 ) < 1e-3 ) ) def __magic_name__ ( self : Dict ): """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus _A: Any = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 _A: Union[str, Any] = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] _A: Dict = [np.asarray(lowerCAmelCase_ ) for speech_input in speech_inputs] # Test not batched input _A: Tuple = feat_extract(speech_inputs[0] , return_tensors='''np''' ).input_values _A: Dict = feat_extract(np_speech_inputs[0] , return_tensors='''np''' ).input_values self.assertTrue(np.allclose(lowerCAmelCase_ , lowerCAmelCase_ , atol=1e-3 ) ) # Test batched _A: Union[str, Any] = feat_extract(lowerCAmelCase_ , return_tensors='''np''' ).input_values _A: Any = feat_extract(lowerCAmelCase_ , return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(lowerCAmelCase_ , lowerCAmelCase_ ): self.assertTrue(np.allclose(lowerCAmelCase_ , lowerCAmelCase_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. _A: List[Any] = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] _A: Optional[int] = np.asarray(lowerCAmelCase_ ) _A: Any = feat_extract(lowerCAmelCase_ , return_tensors='''np''' ).input_values _A: str = feat_extract(lowerCAmelCase_ , return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(lowerCAmelCase_ , lowerCAmelCase_ ): self.assertTrue(np.allclose(lowerCAmelCase_ , lowerCAmelCase_ , atol=1e-3 ) ) def __magic_name__ ( self : Any ): """simple docstring""" _A: Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _A: List[Any] = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] _A: List[Any] = ['''longest''', '''max_length''', '''do_not_pad'''] _A: Any = [None, 1_6_0_0, None] for max_length, padding in zip(lowerCAmelCase_ , lowerCAmelCase_ ): _A: Optional[Any] = feat_extract(lowerCAmelCase_ , padding=lowerCAmelCase_ , max_length=lowerCAmelCase_ , return_tensors='''np''' ) _A: Union[str, Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:8_0_0] ) self.assertTrue(input_values[0][8_0_0:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0] ) self.assertTrue(input_values[0][1_0_0_0:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0] ) def __magic_name__ ( self : str ): """simple docstring""" _A: Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _A: Optional[Any] = range(8_0_0 , 1_4_0_0 , 2_0_0 ) _A: List[Any] = [floats_list((1, x) )[0] for x in lengths] _A: Optional[int] = ['''longest''', '''max_length''', '''do_not_pad'''] _A: List[str] = [None, 1_6_0_0, None] for max_length, padding in zip(lowerCAmelCase_ , lowerCAmelCase_ ): _A: List[Any] = feat_extract(lowerCAmelCase_ , max_length=lowerCAmelCase_ , padding=lowerCAmelCase_ ) _A: Any = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:8_0_0] ) self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0] ) self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0] ) def __magic_name__ ( self : Dict ): """simple docstring""" _A: List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _A: str = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] _A: str = feat_extract( lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=1_0_0_0 , padding='''max_length''' , return_tensors='''np''' ) _A: int = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def __magic_name__ ( self : List[str] ): """simple docstring""" _A: List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _A: Optional[Any] = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] _A: Any = feat_extract( lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=1_0_0_0 , padding='''longest''' , return_tensors='''np''' ) _A: List[str] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1_0_0_0) ) _A: Optional[int] = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] _A: Union[str, Any] = feat_extract( lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=2_0_0_0 , padding='''longest''' , return_tensors='''np''' ) _A: Optional[Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :8_0_0] ) self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1_2_0_0) ) @require_torch def __magic_name__ ( self : List[Any] ): """simple docstring""" import torch _A: Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _A: List[Any] = np.random.rand(1_0_0 ).astype(np.floataa ) _A: Tuple = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: _A: Union[str, Any] = feature_extractor.pad([{'''input_values''': inputs}] , return_tensors='''np''' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) _A: Dict = feature_extractor.pad([{'''input_values''': inputs}] , return_tensors='''pt''' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) @slow @require_torch def __magic_name__ ( self : List[Any] ): """simple docstring""" # this test makes sure that models that are using # group norm don't have their feature extractor return the # attention_mask for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST: _A: Optional[int] = WavaVecaConfig.from_pretrained(lowerCAmelCase_ ) _A: Optional[int] = WavaVecaFeatureExtractor.from_pretrained(lowerCAmelCase_ ) # only "layer" feature extraction norm should make use of # attention_mask self.assertEqual(feat_extract.return_attention_mask , config.feat_extract_norm == '''layer''' )
301
import math import random from typing import Any from .hill_climbing import SearchProblem def lowerCamelCase__ ( a , a = True , a = math.inf , a = -math.inf , a = math.inf , a = -math.inf , a = False , a = 1_00 , a = 0.01 , a = 1 , ) -> Any: _A: Optional[Any] = False _A: Dict = search_prob _A: str = start_temperate _A: Optional[int] = [] _A: int = 0 _A: Dict = None while not search_end: _A: Dict = current_state.score() if best_state is None or current_score > best_state.score(): _A: List[Any] = current_state scores.append(a ) iterations += 1 _A: List[str] = None _A: str = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to _A: Any = random.randint(0 , len(a ) - 1 ) # picking a random neighbor _A: Union[str, Any] = neighbors.pop(a ) _A: List[str] = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: _A: Optional[Any] = change * -1 # in case we are finding minimum if change > 0: # improves the solution _A: str = picked_neighbor else: _A: Tuple = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability _A: Optional[int] = picked_neighbor _A: Dict = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor _A: Any = True else: _A: List[Any] = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(a ) , a ) plt.xlabel('''Iterations''' ) plt.ylabel('''Function values''' ) plt.show() return best_state if __name__ == "__main__": def lowerCamelCase__ ( a , a ) -> Optional[Any]: return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) UpperCAmelCase__ : Optional[int] = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) UpperCAmelCase__ : Optional[Any] = simulated_annealing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( 'The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) # starting the problem with initial coordinates (12, 47) UpperCAmelCase__ : Optional[Any] = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) UpperCAmelCase__ : List[str] = simulated_annealing( prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( 'The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) def lowerCamelCase__ ( a , a ) -> Optional[Any]: return (3 * x**2) - (6 * y) UpperCAmelCase__ : Union[str, Any] = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) UpperCAmelCase__ : List[str] = simulated_annealing(prob, find_max=False, visualization=True) print( 'The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ' F"""{local_min.score()}""" ) UpperCAmelCase__ : Optional[Any] = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) UpperCAmelCase__ : List[Any] = simulated_annealing(prob, find_max=True, visualization=True) print( 'The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ' F"""{local_min.score()}""" )
301
1
from __future__ import annotations def lowerCamelCase__ ( a ) -> list[int]: if len(a ) == 0: return array _A , _A: List[str] = min(a ), max(a ) # Compute the variables _A: Optional[int] = _max - _min + 1 _A , _A: List[str] = [0] * holes_range, [0] * holes_range # Make the sorting. for i in array: _A: Any = i - _min _A: List[str] = i holes_repeat[index] += 1 # Makes the array back by replacing the numbers. _A: Optional[int] = 0 for i in range(a ): while holes_repeat[i] > 0: _A: List[Any] = holes[i] index += 1 holes_repeat[i] -= 1 # Returns the sorted array. return array if __name__ == "__main__": import doctest doctest.testmod() UpperCAmelCase__ : List[Any] = input('Enter numbers separated by comma:\n') UpperCAmelCase__ : Tuple = [int(x) for x in user_input.split(',')] print(pigeon_sort(unsorted))
301
import json import os from typing import Dict, List, Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase__ : List[Any] = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } UpperCAmelCase__ : Tuple = { '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__ : Optional[int] = {'facebook/blenderbot_small-90M': 512} def lowerCamelCase__ ( a ) -> Optional[Any]: _A: List[Any] = set() _A: List[Any] = word[0] for char in word[1:]: pairs.add((prev_char, char) ) _A: List[Any] = char _A: Union[str, Any] = set(a ) return pairs class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : str = VOCAB_FILES_NAMES __UpperCamelCase : List[Any] = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase : Union[str, Any] = ['''input_ids''', '''attention_mask'''] def __init__( self : int , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : List[str]="__start__" , lowerCAmelCase_ : Any="__end__" , lowerCAmelCase_ : Any="__unk__" , lowerCAmelCase_ : Any="__null__" , **lowerCAmelCase_ : int , ): """simple docstring""" super().__init__(unk_token=lowerCAmelCase_ , bos_token=lowerCAmelCase_ , eos_token=lowerCAmelCase_ , pad_token=lowerCAmelCase_ , **lowerCAmelCase_ ) with open(lowerCAmelCase_ , encoding='''utf-8''' ) as vocab_handle: _A: Optional[int] = json.load(lowerCAmelCase_ ) _A: int = {v: k for k, v in self.encoder.items()} with open(lowerCAmelCase_ , encoding='''utf-8''' ) as merges_handle: _A: Dict = merges_handle.read().split('''\n''' )[1:-1] _A: int = [tuple(merge.split() ) for merge in merges] _A: Dict = dict(zip(lowerCAmelCase_ , range(len(lowerCAmelCase_ ) ) ) ) _A: Union[str, Any] = {} @property def __magic_name__ ( self : Optional[int] ): """simple docstring""" return len(self.encoder ) def __magic_name__ ( self : Optional[int] ): """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def __magic_name__ ( self : str , lowerCAmelCase_ : str ): """simple docstring""" if token in self.cache: return self.cache[token] _A: List[Any] = re.sub('''([.,!?()])''' , R''' \1''' , lowerCAmelCase_ ) _A: List[Any] = re.sub('''(\')''' , R''' \1 ''' , lowerCAmelCase_ ) _A: List[Any] = re.sub(R'''\s{2,}''' , ''' ''' , lowerCAmelCase_ ) if "\n" in token: _A: Dict = token.replace('''\n''' , ''' __newln__''' ) _A: Any = token.split(''' ''' ) _A: Optional[Any] = [] for token in tokens: if not len(lowerCAmelCase_ ): continue _A: str = token.lower() _A: List[str] = tuple(lowerCAmelCase_ ) _A: str = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] ) _A: Dict = get_pairs(lowerCAmelCase_ ) if not pairs: words.append(lowerCAmelCase_ ) continue while True: _A: str = min(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : self.bpe_ranks.get(lowerCAmelCase_ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break _A , _A: Optional[int] = bigram _A: str = [] _A: Dict = 0 while i < len(lowerCAmelCase_ ): try: _A: List[Any] = word.index(lowerCAmelCase_ , lowerCAmelCase_ ) new_word.extend(word[i:j] ) _A: Optional[int] = j except ValueError: new_word.extend(word[i:] ) break if word[i] == first and i < len(lowerCAmelCase_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 _A: Union[str, Any] = tuple(lowerCAmelCase_ ) _A: Tuple = new_word if len(lowerCAmelCase_ ) == 1: break else: _A: Optional[int] = get_pairs(lowerCAmelCase_ ) _A: str = '''@@ '''.join(lowerCAmelCase_ ) _A: Tuple = word[:-4] _A: List[Any] = word words.append(lowerCAmelCase_ ) return " ".join(lowerCAmelCase_ ) def __magic_name__ ( self : str , lowerCAmelCase_ : str ): """simple docstring""" _A: List[Any] = [] _A: List[Any] = re.findall(R'''\S+\n?''' , lowerCAmelCase_ ) for token in words: split_tokens.extend(list(self.bpe(lowerCAmelCase_ ).split(''' ''' ) ) ) return split_tokens def __magic_name__ ( self : str , lowerCAmelCase_ : str ): """simple docstring""" _A: List[str] = token.lower() return self.encoder.get(lowerCAmelCase_ , self.encoder.get(self.unk_token ) ) def __magic_name__ ( self : int , lowerCAmelCase_ : int ): """simple docstring""" return self.decoder.get(lowerCAmelCase_ , self.unk_token ) def __magic_name__ ( self : List[str] , lowerCAmelCase_ : List[str] ): """simple docstring""" _A: List[str] = ''' '''.join(lowerCAmelCase_ ).replace('''@@ ''' , '''''' ).strip() return out_string def __magic_name__ ( self : List[Any] , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[str] = None ): """simple docstring""" if not os.path.isdir(lowerCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _A: Dict = os.path.join( lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) _A: Any = os.path.join( lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(lowerCAmelCase_ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=lowerCAmelCase_ , ensure_ascii=lowerCAmelCase_ ) + '''\n''' ) _A: List[str] = 0 with open(lowerCAmelCase_ , '''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 lowerCAmelCase_ : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" ''' Please check that the tokenizer is not corrupted!''' ) _A: Optional[int] = token_index writer.write(''' '''.join(lowerCAmelCase_ ) + '''\n''' ) index += 1 return vocab_file, merge_file
301
1
from __future__ import annotations import unittest from transformers import AutoTokenizer, MBartConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel @require_tf class UpperCAmelCase : '''simple docstring''' __UpperCamelCase : Any = MBartConfig __UpperCamelCase : Tuple = {} __UpperCamelCase : Dict = '''gelu''' def __init__( self : Dict , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : List[Any]=1_3 , lowerCAmelCase_ : Dict=7 , lowerCAmelCase_ : Optional[Any]=True , lowerCAmelCase_ : Optional[Any]=False , lowerCAmelCase_ : Union[str, Any]=9_9 , lowerCAmelCase_ : Dict=3_2 , lowerCAmelCase_ : str=2 , lowerCAmelCase_ : int=4 , lowerCAmelCase_ : Union[str, Any]=3_7 , lowerCAmelCase_ : Dict=0.1 , lowerCAmelCase_ : str=0.1 , lowerCAmelCase_ : List[str]=2_0 , lowerCAmelCase_ : str=2 , lowerCAmelCase_ : Optional[int]=1 , lowerCAmelCase_ : List[Any]=0 , ): """simple docstring""" _A: Union[str, Any] = parent _A: List[Any] = batch_size _A: Dict = seq_length _A: Dict = is_training _A: str = use_labels _A: int = vocab_size _A: str = hidden_size _A: Tuple = num_hidden_layers _A: Optional[Any] = num_attention_heads _A: Tuple = intermediate_size _A: int = hidden_dropout_prob _A: Tuple = attention_probs_dropout_prob _A: Tuple = max_position_embeddings _A: Dict = eos_token_id _A: int = pad_token_id _A: Any = bos_token_id def __magic_name__ ( self : Dict ): """simple docstring""" _A: Optional[int] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _A: Dict = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _A: List[Any] = tf.concat([input_ids, eos_tensor] , axis=1 ) _A: Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _A: int = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) _A: Any = prepare_mbart_inputs_dict(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return config, inputs_dict def __magic_name__ ( self : Union[str, Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : List[str] ): """simple docstring""" _A: Tuple = TFMBartModel(config=lowerCAmelCase_ ).get_decoder() _A: List[str] = inputs_dict['''input_ids'''] _A: Tuple = input_ids[:1, :] _A: List[Any] = inputs_dict['''attention_mask'''][:1, :] _A: str = inputs_dict['''head_mask'''] _A: Optional[Any] = 1 # first forward pass _A: Any = model(lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , head_mask=lowerCAmelCase_ , use_cache=lowerCAmelCase_ ) _A , _A: List[str] = outputs.to_tuple() _A: Dict = past_key_values[1] def lowerCamelCase__ ( a , a , a , a=None , a=None , a=None , a=None , a=None , ) -> Tuple: if attention_mask is None: _A: Union[str, Any] = tf.cast(tf.math.not_equal(a , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: _A: Optional[int] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: _A: Tuple = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _A: Union[str, Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: _A: Optional[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Union[str, Any] = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else () __UpperCamelCase : int = (TFMBartForConditionalGeneration,) if is_tf_available() else () __UpperCamelCase : Tuple = ( { '''conversational''': TFMBartForConditionalGeneration, '''feature-extraction''': TFMBartModel, '''summarization''': TFMBartForConditionalGeneration, '''text2text-generation''': TFMBartForConditionalGeneration, '''translation''': TFMBartForConditionalGeneration, } if is_tf_available() else {} ) __UpperCamelCase : List[Any] = True __UpperCamelCase : int = False __UpperCamelCase : Optional[Any] = False def __magic_name__ ( self : int , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : int , lowerCAmelCase_ : str , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : int ): """simple docstring""" if pipeline_test_casse_name != "FeatureExtractionPipelineTests": # Exception encountered when calling layer '...' return True return False def __magic_name__ ( self : Any ): """simple docstring""" _A: Dict = TFMBartModelTester(self ) _A: Tuple = ConfigTester(self , config_class=lowerCAmelCase_ ) def __magic_name__ ( self : List[str] ): """simple docstring""" self.config_tester.run_common_tests() def __magic_name__ ( self : Optional[Any] ): """simple docstring""" _A: str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*lowerCAmelCase_ ) @require_sentencepiece @require_tokenizers @require_tf class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' __UpperCamelCase : Optional[int] = [ ''' UN Chief Says There Is No Military Solution in Syria''', ] __UpperCamelCase : List[str] = [ '''Şeful ONU declară că nu există o soluţie militară în Siria''', ] __UpperCamelCase : Union[str, Any] = '''facebook/mbart-large-en-ro''' @cached_property def __magic_name__ ( self : Tuple ): """simple docstring""" return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def __magic_name__ ( self : str ): """simple docstring""" _A: Union[str, Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def __magic_name__ ( self : Union[str, Any] , **lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Optional[Any] = self.translate_src_text(**lowerCAmelCase_ ) self.assertListEqual(self.expected_text , lowerCAmelCase_ ) def __magic_name__ ( self : Dict , **lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Any = self.tokenizer(self.src_text , **lowerCAmelCase_ , return_tensors='''tf''' ) _A: Any = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 ) _A: Optional[Any] = self.tokenizer.batch_decode(lowerCAmelCase_ , skip_special_tokens=lowerCAmelCase_ ) return generated_words @slow def __magic_name__ ( self : List[str] ): """simple docstring""" self._assert_generated_batch_equal_expected()
301
import os from pathlib import Path def lowerCamelCase__ ( ) -> Optional[Any]: from torch.utils.cpp_extension import load _A: str = Path(a ).resolve().parent.parent.parent / '''kernels''' / '''deformable_detr''' _A: Tuple = [ root / filename for filename in [ '''vision.cpp''', os.path.join('''cpu''' , '''ms_deform_attn_cpu.cpp''' ), os.path.join('''cuda''' , '''ms_deform_attn_cuda.cu''' ), ] ] load( '''MultiScaleDeformableAttention''' , a , with_cuda=a , extra_include_paths=[str(a )] , extra_cflags=['''-DWITH_CUDA=1'''] , extra_cuda_cflags=[ '''-DCUDA_HAS_FP16=1''', '''-D__CUDA_NO_HALF_OPERATORS__''', '''-D__CUDA_NO_HALF_CONVERSIONS__''', '''-D__CUDA_NO_HALF2_OPERATORS__''', ] , ) import MultiScaleDeformableAttention as MSDA return MSDA
301
1
from cva import destroyAllWindows, imread, imshow, waitKey def lowerCamelCase__ ( a ) -> Optional[int]: # getting number of pixels in the image _A , _A: Any = img.shape[0], img.shape[1] # converting each pixel's color to its negative for i in range(a ): for j in range(a ): _A: int = [2_55, 2_55, 2_55] - img[i][j] return img if __name__ == "__main__": # read original image UpperCAmelCase__ : Union[str, Any] = imread('image_data/lena.jpg', 1) # convert to its negative UpperCAmelCase__ : str = convert_to_negative(img) # show result image imshow('negative of original image', img) waitKey(0) destroyAllWindows()
301
from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Optional[int] = ['''image_processor''', '''tokenizer'''] __UpperCamelCase : Optional[Any] = '''BlipImageProcessor''' __UpperCamelCase : int = ('''BertTokenizer''', '''BertTokenizerFast''') def __init__( self : Optional[int] , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" _A: Optional[Any] = False super().__init__(lowerCAmelCase_ , lowerCAmelCase_ ) _A: List[Any] = self.image_processor def __call__( self : Optional[Any] , lowerCAmelCase_ : ImageInput = None , lowerCAmelCase_ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , lowerCAmelCase_ : bool = True , lowerCAmelCase_ : Union[bool, str, PaddingStrategy] = False , lowerCAmelCase_ : Union[bool, str, TruncationStrategy] = None , lowerCAmelCase_ : Optional[int] = None , lowerCAmelCase_ : int = 0 , lowerCAmelCase_ : Optional[int] = None , lowerCAmelCase_ : Optional[bool] = None , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = True , lowerCAmelCase_ : Optional[Union[str, TensorType]] = None , **lowerCAmelCase_ : Union[str, Any] , ): """simple docstring""" if images is None and text is None: raise ValueError('''You have to specify either images or text.''' ) # Get only text if images is None: _A: Tuple = self.tokenizer _A: Optional[int] = self.tokenizer( text=lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ , padding=lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ , stride=lowerCAmelCase_ , pad_to_multiple_of=lowerCAmelCase_ , return_attention_mask=lowerCAmelCase_ , return_overflowing_tokens=lowerCAmelCase_ , return_special_tokens_mask=lowerCAmelCase_ , return_offsets_mapping=lowerCAmelCase_ , return_token_type_ids=lowerCAmelCase_ , return_length=lowerCAmelCase_ , verbose=lowerCAmelCase_ , return_tensors=lowerCAmelCase_ , **lowerCAmelCase_ , ) return text_encoding # add pixel_values _A: List[Any] = self.image_processor(lowerCAmelCase_ , return_tensors=lowerCAmelCase_ ) if text is not None: _A: Tuple = self.tokenizer( text=lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ , padding=lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ , stride=lowerCAmelCase_ , pad_to_multiple_of=lowerCAmelCase_ , return_attention_mask=lowerCAmelCase_ , return_overflowing_tokens=lowerCAmelCase_ , return_special_tokens_mask=lowerCAmelCase_ , return_offsets_mapping=lowerCAmelCase_ , return_token_type_ids=lowerCAmelCase_ , return_length=lowerCAmelCase_ , verbose=lowerCAmelCase_ , return_tensors=lowerCAmelCase_ , **lowerCAmelCase_ , ) else: _A: str = None if text_encoding is not None: encoding_image_processor.update(lowerCAmelCase_ ) return encoding_image_processor def __magic_name__ ( self : Optional[Any] , *lowerCAmelCase_ : Union[str, Any] , **lowerCAmelCase_ : Tuple ): """simple docstring""" return self.tokenizer.batch_decode(*lowerCAmelCase_ , **lowerCAmelCase_ ) def __magic_name__ ( self : Union[str, Any] , *lowerCAmelCase_ : int , **lowerCAmelCase_ : Optional[int] ): """simple docstring""" return self.tokenizer.decode(*lowerCAmelCase_ , **lowerCAmelCase_ ) @property def __magic_name__ ( self : Dict ): """simple docstring""" _A: Dict = self.tokenizer.model_input_names _A: List[str] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
301
1
import unittest import numpy as np from transformers import MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING, TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING from transformers.pipelines import AudioClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_torchaudio, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' __UpperCamelCase : List[str] = MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING __UpperCamelCase : Any = TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING def __magic_name__ ( self : str , lowerCAmelCase_ : int , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Dict ): """simple docstring""" _A: Union[str, Any] = AudioClassificationPipeline(model=lowerCAmelCase_ , feature_extractor=lowerCAmelCase_ ) # test with a raw waveform _A: Optional[Any] = np.zeros((3_4_0_0_0,) ) _A: int = np.zeros((1_4_0_0_0,) ) return audio_classifier, [audioa, audio] def __magic_name__ ( self : int , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Any ): """simple docstring""" _A , _A: Any = examples _A: List[str] = audio_classifier(lowerCAmelCase_ ) # by default a model is initialized with num_labels=2 self.assertEqual( lowerCAmelCase_ , [ {'''score''': ANY(lowerCAmelCase_ ), '''label''': ANY(lowerCAmelCase_ )}, {'''score''': ANY(lowerCAmelCase_ ), '''label''': ANY(lowerCAmelCase_ )}, ] , ) _A: Optional[Any] = audio_classifier(lowerCAmelCase_ , top_k=1 ) self.assertEqual( lowerCAmelCase_ , [ {'''score''': ANY(lowerCAmelCase_ ), '''label''': ANY(lowerCAmelCase_ )}, ] , ) self.run_torchaudio(lowerCAmelCase_ ) @require_torchaudio def __magic_name__ ( self : Any , lowerCAmelCase_ : Optional[int] ): """simple docstring""" import datasets # test with a local file _A: List[str] = datasets.load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) _A: Any = dataset[0]['''audio''']['''array'''] _A: Optional[int] = audio_classifier(lowerCAmelCase_ ) self.assertEqual( lowerCAmelCase_ , [ {'''score''': ANY(lowerCAmelCase_ ), '''label''': ANY(lowerCAmelCase_ )}, {'''score''': ANY(lowerCAmelCase_ ), '''label''': ANY(lowerCAmelCase_ )}, ] , ) @require_torch def __magic_name__ ( self : List[Any] ): """simple docstring""" _A: Optional[Any] = '''anton-l/wav2vec2-random-tiny-classifier''' _A: Dict = pipeline('''audio-classification''' , model=lowerCAmelCase_ ) _A: List[str] = np.ones((8_0_0_0,) ) _A: str = audio_classifier(lowerCAmelCase_ , top_k=4 ) _A: Tuple = [ {'''score''': 0.0842, '''label''': '''no'''}, {'''score''': 0.0838, '''label''': '''up'''}, {'''score''': 0.0837, '''label''': '''go'''}, {'''score''': 0.0834, '''label''': '''right'''}, ] _A: str = [ {'''score''': 0.0845, '''label''': '''stop'''}, {'''score''': 0.0844, '''label''': '''on'''}, {'''score''': 0.0841, '''label''': '''right'''}, {'''score''': 0.0834, '''label''': '''left'''}, ] self.assertIn(nested_simplify(lowerCAmelCase_ , decimals=4 ) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2] ) _A: Optional[int] = {'''array''': np.ones((8_0_0_0,) ), '''sampling_rate''': audio_classifier.feature_extractor.sampling_rate} _A: List[str] = audio_classifier(lowerCAmelCase_ , top_k=4 ) self.assertIn(nested_simplify(lowerCAmelCase_ , decimals=4 ) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2] ) @require_torch @slow def __magic_name__ ( self : str ): """simple docstring""" import datasets _A: Union[str, Any] = '''superb/wav2vec2-base-superb-ks''' _A: int = pipeline('''audio-classification''' , model=lowerCAmelCase_ ) _A: Union[str, Any] = datasets.load_dataset('''anton-l/superb_dummy''' , '''ks''' , split='''test''' ) _A: Optional[Any] = np.array(dataset[3]['''speech'''] , dtype=np.floataa ) _A: Tuple = audio_classifier(lowerCAmelCase_ , top_k=4 ) self.assertEqual( nested_simplify(lowerCAmelCase_ , decimals=3 ) , [ {'''score''': 0.981, '''label''': '''go'''}, {'''score''': 0.007, '''label''': '''up'''}, {'''score''': 0.006, '''label''': '''_unknown_'''}, {'''score''': 0.001, '''label''': '''down'''}, ] , ) @require_tf @unittest.skip('''Audio classification is not implemented for TF''' ) def __magic_name__ ( self : List[Any] ): """simple docstring""" pass
301
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : Union[str, Any] = { 'google/mobilenet_v1_1.0_224': 'https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json', 'google/mobilenet_v1_0.75_192': 'https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 } class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Optional[int] = '''mobilenet_v1''' def __init__( self : Optional[int] , lowerCAmelCase_ : Any=3 , lowerCAmelCase_ : str=2_2_4 , lowerCAmelCase_ : List[str]=1.0 , lowerCAmelCase_ : Any=8 , lowerCAmelCase_ : Tuple="relu6" , lowerCAmelCase_ : List[Any]=True , lowerCAmelCase_ : Optional[int]=0.999 , lowerCAmelCase_ : List[str]=0.02 , lowerCAmelCase_ : List[Any]=0.001 , **lowerCAmelCase_ : Optional[Any] , ): """simple docstring""" super().__init__(**lowerCAmelCase_ ) if depth_multiplier <= 0: raise ValueError('''depth_multiplier must be greater than zero.''' ) _A: Any = num_channels _A: Optional[int] = image_size _A: Optional[Any] = depth_multiplier _A: Tuple = min_depth _A: Any = hidden_act _A: Dict = tf_padding _A: List[Any] = classifier_dropout_prob _A: Tuple = initializer_range _A: Tuple = layer_norm_eps class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Dict = version.parse('''1.11''' ) @property def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" return OrderedDict([('''pixel_values''', {0: '''batch'''})] ) @property def __magic_name__ ( self : Optional[Any] ): """simple docstring""" if self.task == "image-classification": return OrderedDict([('''logits''', {0: '''batch'''})] ) else: return OrderedDict([('''last_hidden_state''', {0: '''batch'''}), ('''pooler_output''', {0: '''batch'''})] ) @property def __magic_name__ ( self : Dict ): """simple docstring""" return 1e-4
301
1
from manim import * class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def __magic_name__ ( self : Union[str, Any] ): """simple docstring""" _A: Optional[Any] = Rectangle(height=0.5 , width=0.5 ) _A: int = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) _A: List[str] = [mem.copy() for i in range(6 )] _A: Optional[Any] = [mem.copy() for i in range(6 )] _A: Any = VGroup(*lowerCAmelCase_ ).arrange(lowerCAmelCase_ , buff=0 ) _A: Union[str, Any] = VGroup(*lowerCAmelCase_ ).arrange(lowerCAmelCase_ , buff=0 ) _A: Union[str, Any] = VGroup(lowerCAmelCase_ , lowerCAmelCase_ ).arrange(lowerCAmelCase_ , buff=0 ) _A: Union[str, Any] = Text('''CPU''' , font_size=2_4 ) _A: Union[str, Any] = Group(lowerCAmelCase_ , lowerCAmelCase_ ).arrange(lowerCAmelCase_ , buff=0.5 , aligned_edge=lowerCAmelCase_ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(lowerCAmelCase_ ) _A: str = [mem.copy() for i in range(1 )] _A: List[str] = VGroup(*lowerCAmelCase_ ).arrange(lowerCAmelCase_ , buff=0 ) _A: Dict = Text('''GPU''' , font_size=2_4 ) _A: str = Group(lowerCAmelCase_ , lowerCAmelCase_ ).arrange(lowerCAmelCase_ , buff=0.5 , aligned_edge=lowerCAmelCase_ ) gpu.align_to(lowerCAmelCase_ , lowerCAmelCase_ ) gpu.set_x(gpu.get_x() - 1 ) self.add(lowerCAmelCase_ ) _A: Optional[Any] = [mem.copy() for i in range(6 )] _A: str = VGroup(*lowerCAmelCase_ ).arrange(lowerCAmelCase_ , buff=0 ) _A: Union[str, Any] = Text('''Model''' , font_size=2_4 ) _A: Optional[Any] = Group(lowerCAmelCase_ , lowerCAmelCase_ ).arrange(lowerCAmelCase_ , buff=0.5 , aligned_edge=lowerCAmelCase_ ) model.move_to([3, -1.0, 0] ) self.play( Create(lowerCAmelCase_ , run_time=1 ) , Create(lowerCAmelCase_ , run_time=1 ) , Create(lowerCAmelCase_ , run_time=1 ) , ) _A: Optional[Any] = MarkupText( F"""First, an empty model skeleton is loaded\ninto <span fgcolor='{YELLOW}'>memory</span> without using much RAM.""" , font_size=2_4 , ) _A: int = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) _A: Dict = 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] ) step_a.move_to([2, 2, 0] ) self.play(Write(lowerCAmelCase_ , run_time=2.5 ) , Write(lowerCAmelCase_ ) , Write(lowerCAmelCase_ ) ) self.add(lowerCAmelCase_ ) _A: List[Any] = [] _A: Union[str, Any] = [] _A: List[str] = [] for i, rect in enumerate(lowerCAmelCase_ ): _A: Optional[Any] = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0.0 ).set_fill(lowerCAmelCase_ , opacity=0.7 ) cpu_target.move_to(lowerCAmelCase_ ) cpu_target.generate_target() _A: Optional[int] = 0.46 / 4 _A: Any = 0.46 / 3 if i == 0: cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=lowerCAmelCase_ ) cpu_target.target.set_x(cpu_target.target.get_x() + 0.1 ) elif i == 3: cpu_target.target.next_to(cpu_targs[0].target , direction=lowerCAmelCase_ , buff=0.0 ) else: cpu_target.target.next_to(cpu_targs[i - 1].target , direction=lowerCAmelCase_ , buff=0.0 ) cpu_targs.append(lowerCAmelCase_ ) first_animations.append(rect.animate(run_time=0.5 ).set_stroke(lowerCAmelCase_ ) ) second_animations.append(MoveToTarget(lowerCAmelCase_ , run_time=1.5 ) ) self.play(*lowerCAmelCase_ ) self.play(*lowerCAmelCase_ ) self.wait()
301
import argparse import json import os from tensorflow.core.protobuf.saved_model_pba import SavedModel # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py UpperCAmelCase__ : Any = '.' # Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model) UpperCAmelCase__ : Optional[Any] = [ 'Assert', 'AssignVariableOp', 'EmptyTensorList', 'MergeV2Checkpoints', 'ReadVariableOp', 'ResourceGather', 'RestoreV2', 'SaveV2', 'ShardedFilename', 'StatefulPartitionedCall', 'StaticRegexFullMatch', 'VarHandleOp', ] def lowerCamelCase__ ( a , a , a ) -> Union[str, Any]: _A: Optional[int] = SavedModel() _A: int = [] with open(os.path.join(a , '''utils''' , '''tf_ops''' , '''onnx.json''' ) ) as f: _A: List[Any] = json.load(a )['''opsets'''] for i in range(1 , opset + 1 ): onnx_ops.extend(onnx_opsets[str(a )] ) with open(a , '''rb''' ) as f: saved_model.ParseFromString(f.read() ) _A: Optional[Any] = set() # Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs) for meta_graph in saved_model.meta_graphs: # Add operations in the graph definition model_op_names.update(node.op for node in meta_graph.graph_def.node ) # Go through the functions in the graph definition for func in meta_graph.graph_def.library.function: # Add operations in each function model_op_names.update(node.op for node in func.node_def ) # Convert to list, sorted if you want _A: Optional[int] = sorted(a ) _A: Tuple = [] for op in model_op_names: if op not in onnx_ops and op not in INTERNAL_OPS: incompatible_ops.append(a ) if strict and len(a ) > 0: raise Exception(f"""Found the following incompatible ops for the opset {opset}:\n""" + incompatible_ops ) elif len(a ) > 0: print(f"""Found the following incompatible ops for the opset {opset}:""" ) print(*a , sep='''\n''' ) else: print(f"""The saved model {saved_model_path} can properly be converted with ONNX.""" ) if __name__ == "__main__": UpperCAmelCase__ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument('--saved_model_path', help='Path of the saved model to check (the .pb file).') parser.add_argument( '--opset', default=12, type=int, help='The ONNX opset against which the model has to be tested.' ) parser.add_argument( '--framework', choices=['onnx'], default='onnx', help='Frameworks against which to test the saved model.' ) parser.add_argument( '--strict', action='store_true', help='Whether make the checking strict (raise errors) or not (raise warnings)' ) UpperCAmelCase__ : int = parser.parse_args() if args.framework == "onnx": onnx_compliancy(args.saved_model_path, args.strict, args.opset)
301
1
import argparse import importlib from pathlib import Path # Test all the extensions added in the setup UpperCAmelCase__ : Optional[int] = [ 'kernels/rwkv/wkv_cuda.cu', 'kernels/rwkv/wkv_op.cpp', 'kernels/deformable_detr/ms_deform_attn.h', 'kernels/deformable_detr/cuda/ms_deform_im2col_cuda.cuh', 'models/graphormer/algos_graphormer.pyx', ] def lowerCamelCase__ ( a ) -> str: # Test all the extensions added in the setup for file in FILES_TO_FIND: if not (transformers_path / file).exists(): return False return True if __name__ == "__main__": UpperCAmelCase__ : int = argparse.ArgumentParser() parser.add_argument('--check_lib', action='store_true', help='Whether to check the build or the actual package.') UpperCAmelCase__ : Dict = parser.parse_args() if args.check_lib: UpperCAmelCase__ : Any = importlib.import_module('transformers') UpperCAmelCase__ : Tuple = Path(transformers_module.__file__).parent else: UpperCAmelCase__ : List[Any] = Path.cwd() / 'build/lib/transformers' if not test_custom_files_are_present(transformers_path): raise ValueError('The built release does not contain the custom files. Fix this before going further!')
301
import json import os from typing import Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ : int = logging.get_logger(__name__) UpperCAmelCase__ : Union[str, Any] = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', } UpperCAmelCase__ : str = { '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__ : Dict = { 'ctrl': 256, } UpperCAmelCase__ : Any = { 'Pregnancy': 168629, 'Christianity': 7675, 'Explain': 106423, 'Fitness': 63440, 'Saving': 63163, 'Ask': 27171, 'Ass': 95985, 'Joke': 163509, 'Questions': 45622, 'Thoughts': 49605, 'Retail': 52342, 'Feminism': 164338, 'Writing': 11992, 'Atheism': 192263, 'Netflix': 48616, 'Computing': 39639, 'Opinion': 43213, 'Alone': 44967, 'Funny': 58917, 'Gaming': 40358, 'Human': 4088, 'India': 1331, 'Joker': 77138, 'Diet': 36206, 'Legal': 11859, 'Norman': 4939, 'Tip': 72689, 'Weight': 52343, 'Movies': 46273, 'Running': 23425, 'Science': 2090, 'Horror': 37793, 'Confession': 60572, 'Finance': 12250, 'Politics': 16360, 'Scary': 191985, 'Support': 12654, 'Technologies': 32516, 'Teenage': 66160, 'Event': 32769, 'Learned': 67460, 'Notion': 182770, 'Wikipedia': 37583, 'Books': 6665, 'Extract': 76050, 'Confessions': 102701, 'Conspiracy': 75932, 'Links': 63674, 'Narcissus': 150425, 'Relationship': 54766, 'Relationships': 134796, 'Reviews': 41671, 'News': 4256, 'Translation': 26820, 'multilingual': 128406, } def lowerCamelCase__ ( a ) -> Optional[Any]: _A: Optional[int] = set() _A: Dict = word[0] for char in word[1:]: pairs.add((prev_char, char) ) _A: Any = char _A: Dict = set(a ) return pairs class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __UpperCamelCase : Any = VOCAB_FILES_NAMES __UpperCamelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase : Optional[int] = CONTROL_CODES def __init__( self : Dict , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[Any]="<unk>" , **lowerCAmelCase_ : Optional[int] ): """simple docstring""" super().__init__(unk_token=lowerCAmelCase_ , **lowerCAmelCase_ ) with open(lowerCAmelCase_ , encoding='''utf-8''' ) as vocab_handle: _A: str = json.load(lowerCAmelCase_ ) _A: List[Any] = {v: k for k, v in self.encoder.items()} with open(lowerCAmelCase_ , encoding='''utf-8''' ) as merges_handle: _A: int = merges_handle.read().split('''\n''' )[1:-1] _A: List[Any] = [tuple(merge.split() ) for merge in merges] _A: List[str] = dict(zip(lowerCAmelCase_ , range(len(lowerCAmelCase_ ) ) ) ) _A: Union[str, Any] = {} @property def __magic_name__ ( self : Any ): """simple docstring""" return len(self.encoder ) def __magic_name__ ( self : Dict ): """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def __magic_name__ ( self : List[str] , lowerCAmelCase_ : Tuple ): """simple docstring""" if token in self.cache: return self.cache[token] _A: List[Any] = tuple(lowerCAmelCase_ ) _A: Optional[Any] = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] ) _A: Optional[int] = get_pairs(lowerCAmelCase_ ) if not pairs: return token while True: _A: Optional[int] = min(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : self.bpe_ranks.get(lowerCAmelCase_ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break _A , _A: Any = bigram _A: int = [] _A: int = 0 while i < len(lowerCAmelCase_ ): try: _A: Any = word.index(lowerCAmelCase_ , lowerCAmelCase_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) _A: Optional[int] = j if word[i] == first and i < len(lowerCAmelCase_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 _A: Dict = tuple(lowerCAmelCase_ ) _A: Union[str, Any] = new_word if len(lowerCAmelCase_ ) == 1: break else: _A: Tuple = get_pairs(lowerCAmelCase_ ) _A: Optional[int] = '''@@ '''.join(lowerCAmelCase_ ) _A: List[str] = word[:-4] _A: Optional[Any] = word return word def __magic_name__ ( self : Optional[Any] , lowerCAmelCase_ : Union[str, Any] ): """simple docstring""" _A: List[Any] = [] _A: List[str] = re.findall(R'''\S+\n?''' , lowerCAmelCase_ ) for token in words: split_tokens.extend(list(self.bpe(lowerCAmelCase_ ).split(''' ''' ) ) ) return split_tokens def __magic_name__ ( self : Dict , lowerCAmelCase_ : Optional[int] ): """simple docstring""" return self.encoder.get(lowerCAmelCase_ , self.encoder.get(self.unk_token ) ) def __magic_name__ ( self : Dict , lowerCAmelCase_ : Tuple ): """simple docstring""" return self.decoder.get(lowerCAmelCase_ , self.unk_token ) def __magic_name__ ( self : Any , lowerCAmelCase_ : Tuple ): """simple docstring""" _A: Any = ''' '''.join(lowerCAmelCase_ ).replace('''@@ ''' , '''''' ).strip() return out_string def __magic_name__ ( self : List[str] , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[str] = None ): """simple docstring""" if not os.path.isdir(lowerCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _A: List[str] = os.path.join( lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) _A: List[Any] = os.path.join( lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(lowerCAmelCase_ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=lowerCAmelCase_ , ensure_ascii=lowerCAmelCase_ ) + '''\n''' ) _A: str = 0 with open(lowerCAmelCase_ , '''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 lowerCAmelCase_ : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" ''' Please check that the tokenizer is not corrupted!''' ) _A: Tuple = token_index writer.write(''' '''.join(lowerCAmelCase_ ) + '''\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)
301
1