code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ :str = logging.get_logger(__name__) lowercase__ :Tuple = { # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert } class lowercase ( SCREAMING_SNAKE_CASE__ ): lowercase_ : str ='''megatron-bert''' def __init__( self ,A__=2_9_0_5_6 ,A__=1_0_2_4 ,A__=2_4 ,A__=1_6 ,A__=4_0_9_6 ,A__="gelu" ,A__=0.1 ,A__=0.1 ,A__=5_1_2 ,A__=2 ,A__=0.02 ,A__=1E-12 ,A__=0 ,A__="absolute" ,A__=True ,**A__ ,): super().__init__(pad_token_id=A__ ,**A__) lowercase = vocab_size lowercase = hidden_size lowercase = num_hidden_layers lowercase = num_attention_heads lowercase = hidden_act lowercase = intermediate_size lowercase = hidden_dropout_prob lowercase = attention_probs_dropout_prob lowercase = max_position_embeddings lowercase = type_vocab_size lowercase = initializer_range lowercase = layer_norm_eps lowercase = position_embedding_type lowercase = use_cache
101
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch UpperCAmelCase : int = random.Random() def a__ ( a__ , a__=1.0 , a__=None , a__=None ): """simple docstring""" if rng is None: __SCREAMING_SNAKE_CASE = global_rng __SCREAMING_SNAKE_CASE = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : str=7 , __SCREAMING_SNAKE_CASE : List[str]=400 , __SCREAMING_SNAKE_CASE : Any=2_000 , __SCREAMING_SNAKE_CASE : List[str]=10 , __SCREAMING_SNAKE_CASE : Optional[int]=160 , __SCREAMING_SNAKE_CASE : List[str]=8 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.0 , __SCREAMING_SNAKE_CASE : Dict=4_000 , __SCREAMING_SNAKE_CASE : Optional[int]=False , __SCREAMING_SNAKE_CASE : List[Any]=True , ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = min_seq_length __SCREAMING_SNAKE_CASE = max_seq_length __SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = return_attention_mask __SCREAMING_SNAKE_CASE = do_normalize __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = chunk_length __SCREAMING_SNAKE_CASE = hop_length def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring""" return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Union[str, Any]: """simple docstring""" def _flatten(__SCREAMING_SNAKE_CASE : Dict ): return list(itertools.chain(*__SCREAMING_SNAKE_CASE ) ) if equal_length: __SCREAMING_SNAKE_CASE = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size __SCREAMING_SNAKE_CASE = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = WhisperFeatureExtractor if is_speech_available() else None def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = WhisperFeatureExtractionTester(self ) def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = os.path.join(__SCREAMING_SNAKE_CASE , """feat_extract.json""" ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] # Test feature size __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , padding="""max_length""" , return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input __SCREAMING_SNAKE_CASE = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test batched __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in (800, 800, 800)] __SCREAMING_SNAKE_CASE = np.asarray(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test truncation required __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] __SCREAMING_SNAKE_CASE = [x[: feature_extractor.n_samples] for x in speech_inputs] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs_truncated] __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" import torch __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = np.random.rand(100 , 32 ).astype(np.floataa ) __SCREAMING_SNAKE_CASE = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Tuple ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech __SCREAMING_SNAKE_CASE = ds.sort("""id""" ).select(range(__SCREAMING_SNAKE_CASE ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def UpperCAmelCase__ ( self : Tuple ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on __SCREAMING_SNAKE_CASE = self._load_datasamples(1 ) __SCREAMING_SNAKE_CASE = WhisperFeatureExtractor() __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).input_features self.assertEqual(input_features.shape , (1, 80, 3_000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) ) def UpperCAmelCase__ ( self : List[Any] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = self._load_datasamples(1 )[0] __SCREAMING_SNAKE_CASE = ((audio - audio.min()) / (audio.max() - audio.min())) * 65_535 # Rescale to [0, 65535] to show issue __SCREAMING_SNAKE_CASE = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(np.all(np.mean(__SCREAMING_SNAKE_CASE ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(__SCREAMING_SNAKE_CASE ) - 1 ) < 1E-3 ) )
267
0
"""simple docstring""" def lowercase ( _snake_case : list ) ->int: """simple docstring""" if not grid or not grid[0]: raise TypeError('''The grid does not contain the appropriate information''' ) for cell_n in range(1 , len(grid[0] ) ): grid[0][cell_n] += grid[0][cell_n - 1] __snake_case : Optional[Any] = grid[0] for row_n in range(1 , len(_snake_case ) ): __snake_case : Any = grid[row_n] __snake_case : List[Any] = fill_row(_snake_case , _snake_case ) __snake_case : Optional[int] = grid[row_n] return grid[-1][-1] def lowercase ( _snake_case : list , _snake_case : list ) ->list: """simple docstring""" current_row[0] += row_above[0] for cell_n in range(1 , len(_snake_case ) ): current_row[cell_n] += min(current_row[cell_n - 1] , row_above[cell_n] ) return current_row if __name__ == "__main__": import doctest doctest.testmod()
102
'''simple docstring''' from __future__ import annotations def a__ ( a__ , a__ , a__ ): """simple docstring""" if len(a__ ) == 0: raise ValueError("""find_max() arg is an empty sequence""" ) if ( left >= len(a__ ) or left < -len(a__ ) or right >= len(a__ ) or right < -len(a__ ) ): raise IndexError("""list index out of range""" ) if left == right: return nums[left] __SCREAMING_SNAKE_CASE = (left + right) >> 1 # the middle __SCREAMING_SNAKE_CASE = find_max(a__ , a__ , a__ ) # find max in range[left, mid] __SCREAMING_SNAKE_CASE = find_max(a__ , mid + 1 , a__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
267
0
def UpperCamelCase( __UpperCamelCase : list[list[float]] ): lowerCAmelCase_ : list[list[float]] = [] for data in source_data: for i, el in enumerate(__UpperCamelCase ): if len(__UpperCamelCase ) < i + 1: data_lists.append([] ) data_lists[i].append(float(__UpperCamelCase ) ) return data_lists def UpperCamelCase( __UpperCamelCase : list[list[float]] ,__UpperCamelCase : list[int] ): lowerCAmelCase_ : list[list[float]] = [] for dlist, weight in zip(__UpperCamelCase ,__UpperCamelCase ): lowerCAmelCase_ : int = min(__UpperCamelCase ) lowerCAmelCase_ : Optional[Any] = max(__UpperCamelCase ) lowerCAmelCase_ : list[float] = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind)) ) except ZeroDivisionError: score.append(1 ) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind) ) except ZeroDivisionError: score.append(0 ) # weight not 0 or 1 else: lowerCAmelCase_ : str = f"""Invalid weight of {weight:f} provided""" raise ValueError(__UpperCamelCase ) score_lists.append(__UpperCamelCase ) return score_lists def UpperCamelCase( __UpperCamelCase : list[list[float]] ): lowerCAmelCase_ : list[float] = [0 for i in range(len(score_lists[0] ) )] for slist in score_lists: for j, ele in enumerate(__UpperCamelCase ): lowerCAmelCase_ : List[str] = final_scores[j] + ele return final_scores def UpperCamelCase( __UpperCamelCase : list[list[float]] ,__UpperCamelCase : list[int] ): lowerCAmelCase_ : Optional[Any] = get_data(__UpperCamelCase ) lowerCAmelCase_ : Tuple = calculate_each_score(__UpperCamelCase ,__UpperCamelCase ) lowerCAmelCase_ : Union[str, Any] = generate_final_scores(__UpperCamelCase ) # append scores to source data for i, ele in enumerate(__UpperCamelCase ): source_data[i].append(__UpperCamelCase ) return source_data
103
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) # Initialize Result __SCREAMING_SNAKE_CASE = [] # Traverse through all denomination for denomination in reversed(a__ ): # Find denominations while int(a__ ) >= int(a__ ): total_value -= int(a__ ) answer.append(a__ ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase : Dict = [] UpperCAmelCase : List[str] = '0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): UpperCAmelCase : List[str] = int(input('Enter the number of denominations you want to add: ').strip()) for i in range(0, n): denominations.append(int(input(f"""Denomination {i}: """).strip())) UpperCAmelCase : str = input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter UpperCAmelCase : int = [1, 2, 5, 1_0, 2_0, 5_0, 1_0_0, 5_0_0, 2_0_0_0] UpperCAmelCase : Any = input('Enter the change you want to make: ').strip() if int(value) == 0 or int(value) < 0: print('The total value cannot be zero or negative.') else: print(f"""Following is minimal change for {value}: """) UpperCAmelCase : Any = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
267
0
'''simple docstring''' 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() lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''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''', } lowerCAmelCase__ = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def _A ( A__ , A__ , A__ , A__ , A__ ): """simple docstring""" for attribute in key.split('''.''' ): __lowercase = getattr(A__ , A__ ) if weight_type is not None: __lowercase = getattr(A__ , A__ ).shape else: __lowercase = 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": __lowercase = value elif weight_type == "weight_g": __lowercase = value elif weight_type == "weight_v": __lowercase = value elif weight_type == "bias": __lowercase = value elif weight_type == "running_mean": __lowercase = value elif weight_type == "running_var": __lowercase = value elif weight_type == "num_batches_tracked": __lowercase = value elif weight_type == "inv_freq": __lowercase = value else: __lowercase = value logger.info(F"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def _A ( A__ , A__ , A__ ): """simple docstring""" __lowercase = [] __lowercase = fairseq_model.state_dict() __lowercase = hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): __lowercase = False if "conv_layers" in name: load_conv_layer( A__ , A__ , A__ , A__ , hf_model.config.feat_extract_norm == '''group''' , ) __lowercase = True else: for key, mapped_key in MAPPING.items(): __lowercase = '''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]: __lowercase = True if "*" in mapped_key: __lowercase = name.split(A__ )[0].split('''.''' )[-2] __lowercase = mapped_key.replace('''*''' , A__ ) if "pos_bias_u" in name: __lowercase = None elif "pos_bias_v" in name: __lowercase = None elif "weight_g" in name: __lowercase = '''weight_g''' elif "weight_v" in name: __lowercase = '''weight_v''' elif "bias" in name: __lowercase = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj __lowercase = '''weight''' elif "running_mean" in name: __lowercase = '''running_mean''' elif "inv_freq" in name: __lowercase = '''inv_freq''' elif "running_var" in name: __lowercase = '''running_var''' elif "num_batches_tracked" in name: __lowercase = '''num_batches_tracked''' else: __lowercase = 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 _A ( A__ , A__ , A__ , A__ , A__ ): """simple docstring""" __lowercase = full_name.split('''conv_layers.''' )[-1] __lowercase = name.split('''.''' ) __lowercase = int(items[0] ) __lowercase = 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." ) __lowercase = 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." ) __lowercase = 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." ) __lowercase = 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." ) __lowercase = 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 _A ( A__ , A__ , A__=None , A__=None , A__=True ): """simple docstring""" if config_path is not None: __lowercase = WavaVecaConformerConfig.from_pretrained(A__ , hidden_act='''swish''' ) else: __lowercase = WavaVecaConformerConfig() if "rope" in checkpoint_path: __lowercase = '''rotary''' if is_finetuned: if dict_path: __lowercase = Dictionary.load(A__ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __lowercase = target_dict.pad_index __lowercase = target_dict.bos_index __lowercase = target_dict.eos_index __lowercase = len(target_dict.symbols ) __lowercase = 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__ ) __lowercase = target_dict.indices # fairseq has the <pad> and <s> switched __lowercase = 0 __lowercase = 1 with open(A__ , '''w''' , encoding='''utf-8''' ) as vocab_handle: json.dump(A__ , A__ ) __lowercase = 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__ , ) __lowercase = True if config.feat_extract_norm == '''layer''' else False __lowercase = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=A__ , return_attention_mask=A__ , ) __lowercase = WavaVecaProcessor(feature_extractor=A__ , tokenizer=A__ ) processor.save_pretrained(A__ ) __lowercase = WavaVecaConformerForCTC(A__ ) else: __lowercase = WavaVecaConformerForPreTraining(A__ ) if is_finetuned: __lowercase , __lowercase , __lowercase = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) else: __lowercase = argparse.Namespace(task='''audio_pretraining''' ) __lowercase = fairseq.tasks.setup_task(A__ ) __lowercase , __lowercase , __lowercase = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=A__ ) __lowercase = model[0].eval() recursively_load_weights(A__ , A__ , not is_finetuned ) hf_wavavec.save_pretrained(A__ ) if __name__ == "__main__": lowerCAmelCase__ = 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''' ) lowerCAmelCase__ = 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 )
104
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu UpperCAmelCase : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def a__ ( a__ , a__=None , a__=None , a__=None ): """simple docstring""" __SCREAMING_SNAKE_CASE = True while ask_again: __SCREAMING_SNAKE_CASE = input(a__ ) try: if default is not None and len(a__ ) == 0: return default return convert_value(a__ ) if convert_value is not None else result except Exception: if error_message is not None: print(a__ ) def a__ ( a__ , a__=[] , a__=None , a__=0 ): """simple docstring""" __SCREAMING_SNAKE_CASE = BulletMenu(a__ , a__ ) __SCREAMING_SNAKE_CASE = menu.run(default_choice=a__ ) return convert_value(a__ ) if convert_value is not None else result def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value] ) def a__ ( a__ ): """simple docstring""" return {"yes": True, "no": False}[value.lower()] class lowerCAmelCase__ ( argparse.RawDescriptionHelpFormatter ): """simple docstring""" def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = super()._format_usage(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = usage.replace("""<command> [<args>] """ , """""" ) return usage
267
0
"""simple docstring""" from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class __UpperCamelCase ( a__ ): lowerCamelCase : List[str] =DistilBertTokenizer lowerCamelCase : Optional[Any] =DistilBertTokenizerFast lowerCamelCase : List[Any] =True @slow def __a ( self ) -> Any: a : Dict = DistilBertTokenizer.from_pretrained("distilbert-base-uncased" ) a : List[str] = tokenizer.encode("sequence builders" , add_special_tokens=lowerCAmelCase__ ) a : Optional[Any] = tokenizer.encode("multi-sequence build" , add_special_tokens=lowerCAmelCase__ ) a : Optional[Any] = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase__ ) a : Tuple = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase__ , lowerCAmelCase__ ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ]
105
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) if n == 0: return 0 __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + naive_cut_rod_recursive(n - i , a__ ) ) return max_revue def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ ): """simple docstring""" if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , a__ , a__ ) , ) __SCREAMING_SNAKE_CASE = max_revenue return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] __SCREAMING_SNAKE_CASE = 0 for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max_rev[i] for j in range(1 , i + 1 ): __SCREAMING_SNAKE_CASE = max(a__ , prices[j - 1] + max_rev[i - j] ) __SCREAMING_SNAKE_CASE = max_revenue_i return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" if n < 0: __SCREAMING_SNAKE_CASE = F'n must be greater than or equal to 0. Got n = {n}' raise ValueError(a__ ) if n > len(a__ ): __SCREAMING_SNAKE_CASE = ( """Each integral piece of rod must have a corresponding price. """ F'Got n = {n} but length of prices = {len(a__ )}' ) raise ValueError(a__ ) def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = [6, 10, 12, 15, 20, 23] __SCREAMING_SNAKE_CASE = len(a__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __SCREAMING_SNAKE_CASE = 36 __SCREAMING_SNAKE_CASE = top_down_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = bottom_up_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = naive_cut_rod_recursive(a__ , a__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
267
0
"""simple docstring""" __UpperCamelCase : Any = [ [0, 1_6, 1_3, 0, 0, 0], [0, 0, 1_0, 1_2, 0, 0], [0, 4, 0, 0, 1_4, 0], [0, 0, 9, 0, 0, 2_0], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] def __SCREAMING_SNAKE_CASE ( A_ , A_ , A_ , A_ ): # Return True if there is node that has not iterated. lowerCAmelCase__ : Union[str, Any] = [False] * len(A_ ) lowerCAmelCase__ : Union[str, Any] = [s] lowerCAmelCase__ : Union[str, Any] = True while queue: lowerCAmelCase__ : List[Any] = queue.pop(0 ) for ind in range(len(graph[u] ) ): if visited[ind] is False and graph[u][ind] > 0: queue.append(A_ ) lowerCAmelCase__ : Union[str, Any] = True lowerCAmelCase__ : str = u return visited[t] def __SCREAMING_SNAKE_CASE ( A_ , A_ , A_ ): lowerCAmelCase__ : List[Any] = [-1] * (len(A_ )) lowerCAmelCase__ : Any = 0 lowerCAmelCase__ : Any = [] lowerCAmelCase__ : Dict = [i[:] for i in graph] # Record original cut, copy. while bfs(A_ , A_ , A_ , A_ ): lowerCAmelCase__ : Optional[Any] = float('''Inf''' ) lowerCAmelCase__ : List[Any] = sink while s != source: # Find the minimum value in select path lowerCAmelCase__ : Optional[Any] = min(A_ , graph[parent[s]][s] ) lowerCAmelCase__ : Dict = parent[s] max_flow += path_flow lowerCAmelCase__ : str = sink while v != source: lowerCAmelCase__ : List[Any] = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow lowerCAmelCase__ : 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))
106
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : Union[str, Any] = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ 'SEW_PRETRAINED_MODEL_ARCHIVE_LIST', 'SEWForCTC', 'SEWForSequenceClassification', 'SEWModel', 'SEWPreTrainedModel', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys UpperCAmelCase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
267
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase : int = logging.get_logger(__name__) __lowerCAmelCase : Tuple = { 'weiweishi/roc-bert-base-zh': 'https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json', } class snake_case__ (_UpperCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = """roc_bert""" def __init__( self : Dict , __lowerCamelCase : List[Any]=3_05_22 , __lowerCamelCase : Dict=7_68 , __lowerCamelCase : Any=12 , __lowerCamelCase : Optional[Any]=12 , __lowerCamelCase : Optional[Any]=30_72 , __lowerCamelCase : Any="gelu" , __lowerCamelCase : Optional[Any]=0.1 , __lowerCamelCase : Optional[Any]=0.1 , __lowerCamelCase : List[Any]=5_12 , __lowerCamelCase : Optional[int]=2 , __lowerCamelCase : List[Any]=0.02 , __lowerCamelCase : Dict=1e-12 , __lowerCamelCase : Dict=True , __lowerCamelCase : Tuple=0 , __lowerCamelCase : Tuple="absolute" , __lowerCamelCase : Any=None , __lowerCamelCase : str=True , __lowerCamelCase : Tuple=True , __lowerCamelCase : str=7_68 , __lowerCamelCase : Optional[int]=9_10 , __lowerCamelCase : str=5_12 , __lowerCamelCase : Union[str, Any]=2_48_58 , __lowerCamelCase : Optional[int]=True , **__lowerCamelCase : str , ) -> List[Any]: a = vocab_size a = max_position_embeddings a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = initializer_range a = type_vocab_size a = layer_norm_eps a = use_cache a = enable_pronunciation a = enable_shape a = pronunciation_embed_dim a = pronunciation_vocab_size a = shape_embed_dim a = shape_vocab_size a = concat_input a = position_embedding_type a = classifier_dropout super().__init__(pad_token_id=__lowerCamelCase , **__lowerCamelCase )
107
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = name __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = weight def __repr__( self : str ) -> Union[str, Any]: """simple docstring""" return f'{self.__class__.__name__}({self.name}, {self.value}, {self.weight})' def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" return self.value def UpperCAmelCase__ ( self : Any ) -> str: """simple docstring""" return self.name def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.weight def UpperCAmelCase__ ( self : int ) -> Tuple: """simple docstring""" return self.value / self.weight def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = [] for i in range(len(a__ ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = sorted(a__ , key=a__ , reverse=a__ ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 0.0, 0.0 for i in range(len(a__ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def a__ ( ): """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
267
0
"""simple docstring""" import datasets from .evaluate import evaluate lowerCAmelCase__ = '''\ @article{hendrycks2021cuad, title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review}, author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball}, journal={arXiv preprint arXiv:2103.06268}, year={2021} } ''' lowerCAmelCase__ = ''' This metric wrap the official scoring script for version 1 of the Contract Understanding Atticus Dataset (CUAD). Contract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510 commercial legal contracts that have been manually labeled to identify 41 categories of important clauses that lawyers look for when reviewing contracts in connection with corporate transactions. ''' lowerCAmelCase__ = ''' Computes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall). Args: predictions: List of question-answers dictionaries with the following key-values: - \'id\': id of the question-answer pair as given in the references (see below) - \'prediction_text\': list of possible texts for the answer, as a list of strings depending on a threshold on the confidence probability of each prediction. references: List of question-answers dictionaries with the following key-values: - \'id\': id of the question-answer pair (see above), - \'answers\': a Dict in the CUAD dataset format { \'text\': list of possible texts for the answer, as a list of strings \'answer_start\': list of start positions for the answer, as a list of ints } Note that answer_start values are not taken into account to compute the metric. Returns: \'exact_match\': Exact match (the normalized answer exactly match the gold answer) \'f1\': The F-score of predicted tokens versus the gold answer \'aupr\': Area Under the Precision-Recall curve \'prec_at_80_recall\': Precision at 80% recall \'prec_at_90_recall\': Precision at 90% recall Examples: >>> predictions = [{\'prediction_text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\'], \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}] >>> references = [{\'answers\': {\'answer_start\': [143, 49], \'text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\']}, \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}] >>> cuad_metric = datasets.load_metric("cuad") >>> results = cuad_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 100.0, \'f1\': 100.0, \'aupr\': 0.0, \'prec_at_80_recall\': 1.0, \'prec_at_90_recall\': 1.0} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE__ ( datasets.Metric ): """simple docstring""" def lowercase__ ( self ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": { "id": datasets.Value("string" ), "prediction_text": datasets.features.Sequence(datasets.Value("string" ) ), }, "references": { "id": datasets.Value("string" ), "answers": datasets.features.Sequence( { "text": datasets.Value("string" ), "answer_start": datasets.Value("int32" ), } ), }, } ) , codebase_urls=["https://www.atticusprojectai.org/cuad"] , reference_urls=["https://www.atticusprojectai.org/cuad"] , ) def lowercase__ ( self , snake_case__ , snake_case__ ): """simple docstring""" lowerCAmelCase : Optional[int] = {prediction["id"]: prediction["prediction_text"] for prediction in predictions} lowerCAmelCase : List[Any] = [ { "paragraphs": [ { "qas": [ { "answers": [{"text": answer_text} for answer_text in ref["answers"]["text"]], "id": ref["id"], } for ref in references ] } ] } ] lowerCAmelCase : Any = evaluate(dataset=snake_case__ , predictions=snake_case__ ) return score
108
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE = ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on __SCREAMING_SNAKE_CASE = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) __SCREAMING_SNAKE_CASE = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] __SCREAMING_SNAKE_CASE = {"""unk_token""": """<unk>"""} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__SCREAMING_SNAKE_CASE ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48145466, 0.4578275, 0.40821073], """image_std""": [0.26862954, 0.26130258, 0.27577711], } __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , __SCREAMING_SNAKE_CASE ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> str: """simple docstring""" return CLIPTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple , **__SCREAMING_SNAKE_CASE : Any ) -> int: """simple docstring""" return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> List[str]: """simple docstring""" return CLIPImageProcessor.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(__SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_slow.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_fast.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) __SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = image_processor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) __SCREAMING_SNAKE_CASE = processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer(__SCREAMING_SNAKE_CASE ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase__ ( self : Dict ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(__SCREAMING_SNAKE_CASE ): processor() def UpperCAmelCase__ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE = processor.batch_decode(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
267
0
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaPriorEmbaEmbPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase__ , unittest.TestCase ): __lowerCAmelCase : int = KandinskyVaaControlnetImgaImgPipeline __lowerCAmelCase : Dict = ['image_embeds', 'negative_image_embeds', 'image', 'hint'] __lowerCAmelCase : Any = ['image_embeds', 'negative_image_embeds', 'image', 'hint'] __lowerCAmelCase : Optional[int] = [ 'generator', 'height', 'width', 'strength', 'guidance_scale', 'num_inference_steps', 'return_dict', 'guidance_scale', 'num_images_per_prompt', 'output_type', 'return_dict', ] __lowerCAmelCase : List[Any] = False @property def SCREAMING_SNAKE_CASE ( self ) -> int: '''simple docstring''' return 32 @property def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: '''simple docstring''' return 32 @property def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: '''simple docstring''' return self.time_input_dim @property def SCREAMING_SNAKE_CASE ( self ) -> Tuple: '''simple docstring''' return self.time_input_dim * 4 @property def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: '''simple docstring''' return 100 @property def SCREAMING_SNAKE_CASE ( self ) -> Any: '''simple docstring''' torch.manual_seed(0 ) UpperCAmelCase : List[str] = { """in_channels""": 8, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """image_hint""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } UpperCAmelCase : int = UNetaDConditionModel(**_SCREAMING_SNAKE_CASE ) return model @property def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: '''simple docstring''' return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def SCREAMING_SNAKE_CASE ( self ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) UpperCAmelCase : Dict = VQModel(**self.dummy_movq_kwargs ) return model def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase : List[Any] = self.dummy_unet UpperCAmelCase : Dict = self.dummy_movq UpperCAmelCase : List[str] = { """num_train_timesteps""": 1000, """beta_schedule""": """linear""", """beta_start""": 0.0_0085, """beta_end""": 0.012, """clip_sample""": False, """set_alpha_to_one""": False, """steps_offset""": 0, """prediction_type""": """epsilon""", """thresholding""": False, } UpperCAmelCase : Optional[Any] = DDIMScheduler(**_SCREAMING_SNAKE_CASE ) UpperCAmelCase : List[Any] = { """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def SCREAMING_SNAKE_CASE ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=0 ) -> Any: '''simple docstring''' UpperCAmelCase : Optional[int] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE ) UpperCAmelCase : Union[str, Any] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( _SCREAMING_SNAKE_CASE ) # create init_image UpperCAmelCase : List[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE ) UpperCAmelCase : List[str] = image.cpu().permute(0 , 2 , 3 , 1 )[0] UpperCAmelCase : Optional[Any] = Image.fromarray(np.uinta(_SCREAMING_SNAKE_CASE ) ).convert("""RGB""" ).resize((256, 256) ) # create hint UpperCAmelCase : str = floats_tensor((1, 3, 64, 64) , rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE ) if str(_SCREAMING_SNAKE_CASE ).startswith("""mps""" ): UpperCAmelCase : List[Any] = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: UpperCAmelCase : Tuple = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) UpperCAmelCase : str = { """image""": init_image, """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """hint""": hint, """generator""": generator, """height""": 64, """width""": 64, """num_inference_steps""": 10, """guidance_scale""": 7.0, """strength""": 0.2, """output_type""": """np""", } return inputs def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase : List[str] = """cpu""" UpperCAmelCase : Optional[Any] = self.get_dummy_components() UpperCAmelCase : Optional[Any] = self.pipeline_class(**_SCREAMING_SNAKE_CASE ) UpperCAmelCase : Optional[Any] = pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) UpperCAmelCase : Optional[int] = pipe(**self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) ) UpperCAmelCase : int = output.images UpperCAmelCase : Optional[Any] = pipe( **self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) , return_dict=_SCREAMING_SNAKE_CASE , )[0] UpperCAmelCase : Tuple = image[0, -3:, -3:, -1] UpperCAmelCase : Tuple = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCAmelCase : Any = np.array( [0.5498_5034, 0.5550_9365, 0.5256_1504, 0.557_0494, 0.559_3818, 0.526_3979, 0.5028_5643, 0.506_9846, 0.5119_6736] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), F" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self ) -> int: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE ( self ) -> str: '''simple docstring''' UpperCAmelCase : List[str] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/kandinskyv22_controlnet_img2img_robotcat_fp16.npy""" ) UpperCAmelCase : List[str] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" ) UpperCAmelCase : Tuple = init_image.resize((512, 512) ) UpperCAmelCase : List[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/hint_image_cat.png""" ) UpperCAmelCase : Optional[int] = torch.from_numpy(np.array(_SCREAMING_SNAKE_CASE ) ).float() / 255.0 UpperCAmelCase : Optional[int] = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) UpperCAmelCase : Any = """A robot, 4k photo""" UpperCAmelCase : Dict = KandinskyVaaPriorEmbaEmbPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(_SCREAMING_SNAKE_CASE ) UpperCAmelCase : List[Any] = KandinskyVaaControlnetImgaImgPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-controlnet-depth""" , torch_dtype=torch.floataa ) UpperCAmelCase : Optional[Any] = pipeline.to(_SCREAMING_SNAKE_CASE ) pipeline.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) UpperCAmelCase : Optional[int] = torch.Generator(device="""cpu""" ).manual_seed(0 ) UpperCAmelCase , UpperCAmelCase : int = pipe_prior( _SCREAMING_SNAKE_CASE , image=_SCREAMING_SNAKE_CASE , strength=0.85 , generator=_SCREAMING_SNAKE_CASE , negative_prompt="""""" , ).to_tuple() UpperCAmelCase : Union[str, Any] = pipeline( image=_SCREAMING_SNAKE_CASE , image_embeds=_SCREAMING_SNAKE_CASE , negative_image_embeds=_SCREAMING_SNAKE_CASE , hint=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=100 , height=512 , width=512 , strength=0.5 , output_type="""np""" , ) UpperCAmelCase : List[Any] = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
109
'''simple docstring''' import numpy as np def a__ ( a__ , a__ , a__ = 1E-1_2 , a__ = 1_00 , ): """simple docstring""" assert np.shape(a__ )[0] == np.shape(a__ )[1] # Ensure proper dimensionality. assert np.shape(a__ )[0] == np.shape(a__ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(a__ ) == np.iscomplexobj(a__ ) __SCREAMING_SNAKE_CASE = np.iscomplexobj(a__ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(a__ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 1E1_2 while not convergence: # Multiple matrix by the vector. __SCREAMING_SNAKE_CASE = np.dot(a__ , a__ ) # Normalize the resulting output vector. __SCREAMING_SNAKE_CASE = w / np.linalg.norm(a__ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __SCREAMING_SNAKE_CASE = vector.conj().T if is_complex else vector.T __SCREAMING_SNAKE_CASE = np.dot(a__ , np.dot(a__ , a__ ) ) # Check convergence. __SCREAMING_SNAKE_CASE = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = lambda_ if is_complex: __SCREAMING_SNAKE_CASE = np.real(lambda_ ) return lambda_, vector def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ) __SCREAMING_SNAKE_CASE = real_input_matrix.astype(np.complexaaa ) __SCREAMING_SNAKE_CASE = np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __SCREAMING_SNAKE_CASE = real_input_matrix __SCREAMING_SNAKE_CASE = real_vector elif problem_type == "complex": __SCREAMING_SNAKE_CASE = complex_input_matrix __SCREAMING_SNAKE_CASE = complex_vector # Our implementation. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = power_iteration(a__ , a__ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = np.linalg.eigh(a__ ) # Last eigenvalue is the maximum one. __SCREAMING_SNAKE_CASE = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __SCREAMING_SNAKE_CASE = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(a__ ) - np.abs(a__ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
267
0
'''simple docstring''' import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Optional[Any] = logging.get_logger(__name__) a__ : Optional[Any] = { '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__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = '''wavlm''' def __init__( self , lowercase=3_2 , lowercase=7_6_8 , lowercase=1_2 , lowercase=1_2 , lowercase=3_0_7_2 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=0.1 , lowercase=0.0 , lowercase=0.1 , lowercase=0.1 , lowercase=0.02 , lowercase=1E-5 , lowercase="group" , lowercase="gelu" , lowercase=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , lowercase=(5, 2, 2, 2, 2, 2, 2) , lowercase=(1_0, 3, 3, 3, 3, 2, 2) , lowercase=False , lowercase=1_2_8 , lowercase=1_6 , lowercase=3_2_0 , lowercase=8_0_0 , lowercase=False , lowercase=True , lowercase=0.05 , lowercase=1_0 , lowercase=2 , lowercase=0.0 , lowercase=1_0 , lowercase=3_2_0 , lowercase=2 , lowercase=0.1 , lowercase=1_0_0 , lowercase=2_5_6 , lowercase=2_5_6 , lowercase=0.1 , lowercase="mean" , lowercase=False , lowercase=False , lowercase=2_5_6 , lowercase=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 1_5_0_0) , lowercase=(5, 3, 3, 1, 1) , lowercase=(1, 2, 3, 1, 1) , lowercase=5_1_2 , lowercase=8_0 , lowercase=0 , lowercase=1 , lowercase=2 , lowercase=False , lowercase=3 , lowercase=2 , lowercase=3 , lowercase=None , **lowercase , ) -> Optional[Any]: super().__init__(**__SCREAMING_SNAKE_CASE , pad_token_id=__SCREAMING_SNAKE_CASE , bos_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE ) __UpperCamelCase = hidden_size __UpperCamelCase = feat_extract_norm __UpperCamelCase = feat_extract_activation __UpperCamelCase = list(__SCREAMING_SNAKE_CASE ) __UpperCamelCase = list(__SCREAMING_SNAKE_CASE ) __UpperCamelCase = list(__SCREAMING_SNAKE_CASE ) __UpperCamelCase = conv_bias __UpperCamelCase = num_buckets __UpperCamelCase = max_bucket_distance __UpperCamelCase = num_conv_pos_embeddings __UpperCamelCase = num_conv_pos_embedding_groups __UpperCamelCase = len(self.conv_dim ) __UpperCamelCase = num_hidden_layers __UpperCamelCase = intermediate_size __UpperCamelCase = hidden_act __UpperCamelCase = num_attention_heads __UpperCamelCase = hidden_dropout __UpperCamelCase = attention_dropout __UpperCamelCase = activation_dropout __UpperCamelCase = feat_proj_dropout __UpperCamelCase = final_dropout __UpperCamelCase = layerdrop __UpperCamelCase = layer_norm_eps __UpperCamelCase = initializer_range __UpperCamelCase = num_ctc_classes __UpperCamelCase = vocab_size __UpperCamelCase = do_stable_layer_norm __UpperCamelCase = use_weighted_layer_sum __UpperCamelCase = classifier_proj_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==""" """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =""" f" {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`," f" `len(config.conv_kernel) = {len(self.conv_kernel )}`." ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __UpperCamelCase = apply_spec_augment __UpperCamelCase = mask_time_prob __UpperCamelCase = mask_time_length __UpperCamelCase = mask_time_min_masks __UpperCamelCase = mask_feature_prob __UpperCamelCase = mask_feature_length # parameters for pretraining with codevector quantized representations __UpperCamelCase = num_codevectors_per_group __UpperCamelCase = num_codevector_groups __UpperCamelCase = contrastive_logits_temperature __UpperCamelCase = num_negatives __UpperCamelCase = codevector_dim __UpperCamelCase = proj_codevector_dim __UpperCamelCase = diversity_loss_weight # ctc loss __UpperCamelCase = ctc_loss_reduction __UpperCamelCase = ctc_zero_infinity # adapter __UpperCamelCase = add_adapter __UpperCamelCase = adapter_kernel_size __UpperCamelCase = adapter_stride __UpperCamelCase = num_adapter_layers __UpperCamelCase = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. __UpperCamelCase = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. __UpperCamelCase = list(__SCREAMING_SNAKE_CASE ) __UpperCamelCase = list(__SCREAMING_SNAKE_CASE ) __UpperCamelCase = list(__SCREAMING_SNAKE_CASE ) __UpperCamelCase = xvector_output_dim @property def __lowerCamelCase ( self ) -> List[Any]: return functools.reduce(operator.mul , self.conv_stride , 1 )
349
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( a , a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = StableDiffusionInpaintPipeline lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowerCAmelCase__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowerCAmelCase__ = frozenset([] ) def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = PNDMScheduler(skip_prk_steps=__SCREAMING_SNAKE_CASE ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) __SCREAMING_SNAKE_CASE = CLIPTextModel(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __SCREAMING_SNAKE_CASE = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any]=0 ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 )[0] __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE ) ).convert("""RGB""" ).resize((64, 64) ) __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): __SCREAMING_SNAKE_CASE = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = """cpu""" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe.to(__SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe(**__SCREAMING_SNAKE_CASE ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __SCREAMING_SNAKE_CASE = np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : List[str] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained(__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def UpperCAmelCase__ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , safety_checker=__SCREAMING_SNAKE_CASE , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def UpperCAmelCase__ ( self : Tuple ) -> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = PNDMScheduler.from_pretrained(__SCREAMING_SNAKE_CASE , subfolder="""scheduler""" ) __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
267
0
import hashlib import unittest from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available from transformers.pipelines import DepthEstimationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_torch_available(): import torch if is_vision_available(): from PIL import Image else: class A_ : @staticmethod def _lowercase ( *_A , **_A ): '''simple docstring''' pass def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase = hashlib.mda(image.tobytes() ) return m.hexdigest() @is_pipeline_test @require_vision @require_timm @require_torch class A_ (unittest.TestCase ): UpperCAmelCase__ = MODEL_FOR_DEPTH_ESTIMATION_MAPPING def _lowercase ( self , _A , _A , _A ): '''simple docstring''' UpperCAmelCase = DepthEstimationPipeline(model=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) return depth_estimator, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def _lowercase ( self , _A , _A ): '''simple docstring''' UpperCAmelCase = depth_estimator('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) self.assertEqual({'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )} , __SCREAMING_SNAKE_CASE ) import datasets UpperCAmelCase = datasets.load_dataset('''hf-internal-testing/fixtures_image_utils''' , '''image''' , split='''test''' ) UpperCAmelCase = depth_estimator( [ Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ), '''http://images.cocodataset.org/val2017/000000039769.jpg''', # RGBA dataset[0]['''file'''], # LA dataset[1]['''file'''], # L dataset[2]['''file'''], ] ) self.assertEqual( [ {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, ] , __SCREAMING_SNAKE_CASE , ) @require_tf @unittest.skip('''Depth estimation is not implemented in TF''' ) def _lowercase ( self ): '''simple docstring''' pass @slow @require_torch def _lowercase ( self ): '''simple docstring''' UpperCAmelCase = '''Intel/dpt-large''' UpperCAmelCase = pipeline('''depth-estimation''' , model=__SCREAMING_SNAKE_CASE ) UpperCAmelCase = depth_estimator('''http://images.cocodataset.org/val2017/000000039769.jpg''' ) UpperCAmelCase = hashimage(outputs['''depth'''] ) # This seems flaky. # self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977") self.assertEqual(nested_simplify(outputs['''predicted_depth'''].max().item() ) , 29.3_04 ) self.assertEqual(nested_simplify(outputs['''predicted_depth'''].min().item() ) , 2.6_62 ) @require_torch def _lowercase ( self ): '''simple docstring''' self.skipTest('''There is not hf-internal-testing tiny model for either GLPN nor DPT''' )
273
'''simple docstring''' from itertools import count def a__ ( a__ = 50 ): """simple docstring""" __SCREAMING_SNAKE_CASE = [1] * min_block_length for n in count(a__ ): fill_count_functions.append(1 ) for block_length in range(a__ , n + 1 ): for block_start in range(n - block_length ): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_00_00_00: break return n if __name__ == "__main__": print(f"""{solution() = }""")
267
0
import random def __UpperCAmelCase ( a_): snake_case_ = num - 1 snake_case_ = 0 while s % 2 == 0: snake_case_ = s // 2 t += 1 for _ in range(5): snake_case_ = random.randrange(2 , num - 1) snake_case_ = pow(a__ , a__ , a__) if v != 1: snake_case_ = 0 while v != (num - 1): if i == t - 1: return False else: snake_case_ = i + 1 snake_case_ = (v**2) % num return True def __UpperCAmelCase ( a_): if num < 2: return False snake_case_ = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 1_01, 1_03, 1_07, 1_09, 1_13, 1_27, 1_31, 1_37, 1_39, 1_49, 1_51, 1_57, 1_63, 1_67, 1_73, 1_79, 1_81, 1_91, 1_93, 1_97, 1_99, 2_11, 2_23, 2_27, 2_29, 2_33, 2_39, 2_41, 2_51, 2_57, 2_63, 2_69, 2_71, 2_77, 2_81, 2_83, 2_93, 3_07, 3_11, 3_13, 3_17, 3_31, 3_37, 3_47, 3_49, 3_53, 3_59, 3_67, 3_73, 3_79, 3_83, 3_89, 3_97, 4_01, 4_09, 4_19, 4_21, 4_31, 4_33, 4_39, 4_43, 4_49, 4_57, 4_61, 4_63, 4_67, 4_79, 4_87, 4_91, 4_99, 5_03, 5_09, 5_21, 5_23, 5_41, 5_47, 5_57, 5_63, 5_69, 5_71, 5_77, 5_87, 5_93, 5_99, 6_01, 6_07, 6_13, 6_17, 6_19, 6_31, 6_41, 6_43, 6_47, 6_53, 6_59, 6_61, 6_73, 6_77, 6_83, 6_91, 7_01, 7_09, 7_19, 7_27, 7_33, 7_39, 7_43, 7_51, 7_57, 7_61, 7_69, 7_73, 7_87, 7_97, 8_09, 8_11, 8_21, 8_23, 8_27, 8_29, 8_39, 8_53, 8_57, 8_59, 8_63, 8_77, 8_81, 8_83, 8_87, 9_07, 9_11, 9_19, 9_29, 9_37, 9_41, 9_47, 9_53, 9_67, 9_71, 9_77, 9_83, 9_91, 9_97, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(a__) def __UpperCAmelCase ( a_ = 10_24): while True: snake_case_ = random.randrange(2 ** (keysize - 1) , 2 ** (keysize)) if is_prime_low_num(a__): return num if __name__ == "__main__": lowercase = generate_large_prime() print(("Prime number:", num)) print(("is_prime_low_num:", is_prime_low_num(num)))
178
'''simple docstring''' import logging import os import threading import time try: import warnings except ImportError: UpperCAmelCase : Optional[Any] = None try: import msvcrt except ImportError: UpperCAmelCase : List[Any] = None try: import fcntl except ImportError: UpperCAmelCase : int = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: UpperCAmelCase : Union[str, Any] = OSError # Data # ------------------------------------------------ UpperCAmelCase : List[Any] = [ 'Timeout', 'BaseFileLock', 'WindowsFileLock', 'UnixFileLock', 'SoftFileLock', 'FileLock', ] UpperCAmelCase : Tuple = '3.0.12' UpperCAmelCase : str = None def a__ ( ): """simple docstring""" global _logger __SCREAMING_SNAKE_CASE = _logger or logging.getLogger(__name__ ) return _logger class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock_file return None def __str__( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = f'The file lock \'{self.lock_file}\' could not be acquired.' return temp class lowerCAmelCase__ : """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock return None def __enter__( self : List[str] ) -> List[Any]: """simple docstring""" return self.lock def __exit__( self : Tuple , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[str]: """simple docstring""" self.lock.release() return None class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = max_filename_length if max_filename_length is not None else 255 # Hash the filename if it's too long __SCREAMING_SNAKE_CASE = self.hash_filename_if_too_long(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # The path to the lock file. __SCREAMING_SNAKE_CASE = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. __SCREAMING_SNAKE_CASE = None # The default timeout value. __SCREAMING_SNAKE_CASE = timeout # We use this lock primarily for the lock counter. __SCREAMING_SNAKE_CASE = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. __SCREAMING_SNAKE_CASE = 0 return None @property def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" return self._lock_file @property def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" return self._timeout @timeout.setter def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = float(__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" raise NotImplementedError() def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" raise NotImplementedError() @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" return self._lock_file_fd is not None def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=None , __SCREAMING_SNAKE_CASE : Optional[int]=0.05 ) -> Optional[Any]: """simple docstring""" if timeout is None: __SCREAMING_SNAKE_CASE = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file __SCREAMING_SNAKE_CASE = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(f'Attempting to acquire lock {lock_id} on {lock_filename}' ) self._acquire() if self.is_locked: logger().debug(f'Lock {lock_id} acquired on {lock_filename}' ) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(f'Timeout on acquiring lock {lock_id} on {lock_filename}' ) raise Timeout(self._lock_file ) else: logger().debug( f'Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...' ) time.sleep(__SCREAMING_SNAKE_CASE ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: __SCREAMING_SNAKE_CASE = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Dict: """simple docstring""" with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file logger().debug(f'Attempting to release lock {lock_id} on {lock_filename}' ) self._release() __SCREAMING_SNAKE_CASE = 0 logger().debug(f'Lock {lock_id} released on {lock_filename}' ) return None def __enter__( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" self.acquire() return self def __exit__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" self.release() return None def __del__( self : str ) -> Union[str, Any]: """simple docstring""" self.release(force=__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = os.path.basename(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > max_length and max_length > 0: __SCREAMING_SNAKE_CASE = os.path.dirname(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = str(hash(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = filename[: max_length - len(__SCREAMING_SNAKE_CASE ) - 8] + """...""" + hashed_filename + """.lock""" return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: return path class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Dict=-1 , __SCREAMING_SNAKE_CASE : Dict=None ) -> List[Any]: """simple docstring""" from .file_utils import relative_to_absolute_path super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """\\\\?\\""" + relative_to_absolute_path(self.lock_file ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: try: msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_UNLCK , 1 ) os.close(__SCREAMING_SNAKE_CASE ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any]=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = os.statvfs(os.path.dirname(__SCREAMING_SNAKE_CASE ) ).f_namemax super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) try: fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_UN ) os.close(__SCREAMING_SNAKE_CASE ) return None class lowerCAmelCase__ ( a ): """simple docstring""" def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : int ) -> Optional[int]: """simple docstring""" os.close(self._lock_file_fd ) __SCREAMING_SNAKE_CASE = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None UpperCAmelCase : Dict = None if msvcrt: UpperCAmelCase : Optional[int] = WindowsFileLock elif fcntl: UpperCAmelCase : Optional[Any] = UnixFileLock else: UpperCAmelCase : int = SoftFileLock if warnings is not None: warnings.warn('only soft file lock is available')
267
0
def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : Dict = 1000000 ) -> Optional[Any]: __lowercase = set(range(3 , a__ , 2 ) ) primes.add(2 ) for p in range(3 , a__ , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , a__ , a__ ) ) ) __lowercase = [float(a__ ) for n in range(limit + 1 )] for p in primes: for n in range(a__ , limit + 1 , a__ ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(F'''{solution() = }''')
325
'''simple docstring''' import shutil import tempfile import unittest from transformers import ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, NllbTokenizer, NllbTokenizerFast, is_torch_available, ) from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right UpperCAmelCase : Optional[int] = 2_5_6_0_4_7 UpperCAmelCase : Union[str, Any] = 2_5_6_1_4_5 @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = NllbTokenizer lowerCAmelCase__ = NllbTokenizerFast lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = {} def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__SCREAMING_SNAKE_CASE , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-nllb""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) __SCREAMING_SNAKE_CASE = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=True __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=False __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : List[Any] ) -> Any: """simple docstring""" if not self.test_seqaseq: return __SCREAMING_SNAKE_CASE = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Longer text that will definitely require truncation. __SCREAMING_SNAKE_CASE = [ """ UN Chief Says There Is No Military Solution in Syria""", """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for""" """ Syria is that 'there is no military solution' to the nearly five-year conflict and more weapons""" """ will only worsen the violence and misery for millions of people.""", ] __SCREAMING_SNAKE_CASE = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", """Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al""" """ Rusiei pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi""" """ că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""", ] try: __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" , ) except NotImplementedError: return self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 10 ) # max_target_length will default to max_length if not specified __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( __SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 3 ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" ) self.assertEqual(batch_encoder_only.input_ids.shape[1] , 3 ) self.assertEqual(batch_encoder_only.attention_mask.shape[1] , 3 ) self.assertNotIn("""decoder_input_ids""" , __SCREAMING_SNAKE_CASE ) @unittest.skip("""Unfortunately way too slow to build a BPE with SentencePiece.""" ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" pass def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = [AddedToken("""<special>""" , lstrip=__SCREAMING_SNAKE_CASE )] __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""<special>""" , add_special_tokens=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(special_token_id in r_output ) if self.test_slow_tokenizer: __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_cr.encode("""Hey this is a <special> token""" ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertTrue(special_token_id in p_output ) self.assertTrue(special_token_id in cr_output ) @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = "facebook/nllb-200-distilled-600M" lowerCAmelCase__ = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] lowerCAmelCase__ = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] lowerCAmelCase__ = [ 256047, 16297, 134408, 8165, 248066, 14734, 950, 1135, 105721, 3573, 83, 27352, 108, 49486, 2, ] @classmethod def UpperCAmelCase__ ( cls : List[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" ) __SCREAMING_SNAKE_CASE = 1 return cls def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[str]: """simple docstring""" self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Arab"""] , 256_001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Latn"""] , 256_002 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""fra_Latn"""] , 256_057 ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" self.assertIn(__SCREAMING_SNAKE_CASE , self.tokenizer.all_special_ids ) # fmt: off __SCREAMING_SNAKE_CASE = [RO_CODE, 4_254, 98_068, 112_923, 39_072, 3_909, 713, 102_767, 26, 17_314, 35_642, 14_683, 33_118, 2_022, 66_987, 2, 256_047] # fmt: on __SCREAMING_SNAKE_CASE = self.tokenizer.decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertNotIn(self.tokenizer.eos_token , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = ["""this is gunna be a long sentence """ * 20] assert isinstance(src_text[0] , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = 10 __SCREAMING_SNAKE_CASE = self.tokenizer(__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ).input_ids[0] self.assertEqual(ids[-1] , 2 ) self.assertEqual(ids[0] , __SCREAMING_SNAKE_CASE ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> List[Any]: """simple docstring""" self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [256_203, 3] ) def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) __SCREAMING_SNAKE_CASE = shift_tokens_right( batch["""labels"""] , self.tokenizer.pad_token_id , self.tokenizer.lang_code_to_id["""ron_Latn"""] ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual((2, 15) , batch.input_ids.shape ) self.assertEqual((2, 15) , batch.attention_mask.shape ) __SCREAMING_SNAKE_CASE = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , batch.decoder_input_ids[0, 0] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = self.tokenizer( text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=10 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = targets["""input_ids"""] __SCREAMING_SNAKE_CASE = shift_tokens_right( __SCREAMING_SNAKE_CASE , self.tokenizer.pad_token_id , decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] , ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , { # A, test, EOS, en_XX """input_ids""": [[256_047, 70, 7_356, 2]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 256_057, } , ) @require_torch def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2, 256_047] ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [256_047, 16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2] )
267
0
'''simple docstring''' import fire from utils import calculate_rouge, save_json def a ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None , **lowerCamelCase__ ): '''simple docstring''' A_ : Optional[Any] = [x.strip() for x in open(a__ ).readlines()] A_ : str = [x.strip() for x in open(a__ ).readlines()][: len(a__ )] A_ : Any = calculate_rouge(a__ , a__ , **a__ ) if save_path is not None: save_json(a__ , a__ , indent=a__ ) return metrics # these print nicely if __name__ == "__main__": fire.Fire(calculate_rouge_path)
206
'''simple docstring''' import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging UpperCAmelCase : str = logging.get_logger(__name__) class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "linear" lowerCAmelCase__ = "cosine" lowerCAmelCase__ = "cosine_with_restarts" lowerCAmelCase__ = "polynomial" lowerCAmelCase__ = "constant" lowerCAmelCase__ = "constant_with_warmup" lowerCAmelCase__ = "piecewise_constant" def a__ ( a__ , a__ = -1 ): """simple docstring""" return LambdaLR(a__ , lambda a__ : 1 , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1.0 , a__ ) ) return 1.0 return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = step_rules.split(""",""" ) for rule_str in rule_list[:-1]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = rule_str.split(""":""" ) __SCREAMING_SNAKE_CASE = int(a__ ) __SCREAMING_SNAKE_CASE = float(a__ ) __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = float(rule_list[-1] ) def create_rules_function(a__ , a__ ): def rule_func(a__ ) -> float: __SCREAMING_SNAKE_CASE = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(a__ ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func __SCREAMING_SNAKE_CASE = create_rules_function(a__ , a__ ) return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ , a__=-1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 0.5 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(a__ ) * 2.0 * progress )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 1 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(a__ ) * progress) % 1.0) )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__=1E-7 , a__=1.0 , a__=-1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = optimizer.defaults["""lr"""] if not (lr_init > lr_end): raise ValueError(F'lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})' ) def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: __SCREAMING_SNAKE_CASE = lr_init - lr_end __SCREAMING_SNAKE_CASE = num_training_steps - num_warmup_steps __SCREAMING_SNAKE_CASE = 1 - (current_step - num_warmup_steps) / decay_steps __SCREAMING_SNAKE_CASE = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(a__ , a__ , a__ ) UpperCAmelCase : Optional[Any] = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def a__ ( a__ , a__ , a__ = None , a__ = None , a__ = None , a__ = 1 , a__ = 1.0 , a__ = -1 , ): """simple docstring""" __SCREAMING_SNAKE_CASE = SchedulerType(a__ ) __SCREAMING_SNAKE_CASE = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(a__ , last_epoch=a__ ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(a__ , step_rules=a__ , last_epoch=a__ ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(F'{name} requires `num_warmup_steps`, please provide that argument.' ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(a__ , num_warmup_steps=a__ , last_epoch=a__ ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(F'{name} requires `num_training_steps`, please provide that argument.' ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , num_cycles=a__ , last_epoch=a__ , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , power=a__ , last_epoch=a__ , ) return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , last_epoch=a__ )
267
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class A ( __snake_case , __snake_case , __snake_case , unittest.TestCase ): __magic_name__ = StableDiffusionInpaintPipeline __magic_name__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS __magic_name__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS __magic_name__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess __magic_name__ = frozenset([] ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) A : List[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__SCREAMING_SNAKE_CASE , ) A : List[str] = PNDMScheduler(skip_prk_steps=__SCREAMING_SNAKE_CASE ) torch.manual_seed(0 ) A : Tuple = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) A : List[str] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='''gelu''' , projection_dim=512 , ) A : List[str] = CLIPTextModel(__SCREAMING_SNAKE_CASE ) A : Optional[int] = 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 __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=0 ) -> int: """simple docstring""" A : int = floats_tensor((1, 3, 32, 32) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) A : Tuple = image.cpu().permute(0 , 2 , 3 , 1 )[0] A : Dict = Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE ) ).convert('''RGB''' ).resize((64, 64) ) A : List[Any] = Image.fromarray(np.uinta(image + 4 ) ).convert('''RGB''' ).resize((64, 64) ) if str(__SCREAMING_SNAKE_CASE ).startswith('''mps''' ): A : Tuple = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: A : Dict = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) A : Dict = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': init_image, '''mask_image''': mask_image, '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : Dict = '''cpu''' # ensure determinism for the device-dependent torch.Generator A : Optional[Any] = self.get_dummy_components() A : int = StableDiffusionInpaintPipeline(**__SCREAMING_SNAKE_CASE ) A : Any = sd_pipe.to(__SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) A : Any = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) A : Optional[Any] = sd_pipe(**__SCREAMING_SNAKE_CASE ).images A : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) A : Tuple = np.array([0.4_727, 0.5_735, 0.3_941, 0.5_446, 0.5_926, 0.4_394, 0.5_062, 0.4_654, 0.4_476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self ) -> str: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class A ( unittest.TestCase ): def __lowerCAmelCase ( self ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : Any = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''' ) A : Dict = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' ) A : List[str] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint''' '''/yellow_cat_sitting_on_a_park_bench.npy''' ) A : List[str] = '''stabilityai/stable-diffusion-2-inpainting''' A : int = StableDiffusionInpaintPipeline.from_pretrained(__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() A : Union[str, Any] = '''Face of a yellow cat, high resolution, sitting on a park bench''' A : Optional[Any] = torch.manual_seed(0 ) A : str = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type='''np''' , ) A : Optional[Any] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9e-3 def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : List[str] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''' ) A : Dict = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' ) A : int = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint''' '''/yellow_cat_sitting_on_a_park_bench_fp16.npy''' ) A : Any = '''stabilityai/stable-diffusion-2-inpainting''' A : List[Any] = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , safety_checker=__SCREAMING_SNAKE_CASE , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() A : Any = '''Face of a yellow cat, high resolution, sitting on a park bench''' A : Any = torch.manual_seed(0 ) A : Optional[int] = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type='''np''' , ) A : Optional[int] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5e-1 def __lowerCAmelCase ( self ) -> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() A : str = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''' ) A : List[str] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' ) A : Dict = '''stabilityai/stable-diffusion-2-inpainting''' A : List[Any] = PNDMScheduler.from_pretrained(__SCREAMING_SNAKE_CASE , subfolder='''scheduler''' ) A : Dict = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() A : Dict = '''Face of a yellow cat, high resolution, sitting on a park bench''' A : Optional[Any] = torch.manual_seed(0 ) A : Optional[Any] = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type='''np''' , ) A : List[str] = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
3
'''simple docstring''' import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() UpperCAmelCase : Tuple = { 'bart': ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'bert': ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-base-cased-finetuned-mrpc': ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'dpr': ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'gpt2': ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlnet': ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm': ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm-roberta': ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'transfo-xl': ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'openai-gpt': ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'roberta': ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'layoutlm': ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'roberta-large-mnli': ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'camembert': ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'flaubert': ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert': ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert-base-distilled-squad': ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert': ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert-visual-feature-encoder': ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'ctrl': ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'albert': ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 't5': ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'electra': ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'wav2vec2': ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def a__ ( a__ , a__ , a__ , a__ , a__=False , a__=True ): """simple docstring""" if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) __SCREAMING_SNAKE_CASE = config_class.from_json_file(a__ ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True print(F'Building TensorFlow model from configuration: {config}' ) __SCREAMING_SNAKE_CASE = model_class(a__ ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): __SCREAMING_SNAKE_CASE = cached_file( a__ , a__ , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: __SCREAMING_SNAKE_CASE = load_pytorch_checkpoint_in_tfa_model(a__ , a__ ) if compare_with_pt_model: __SCREAMING_SNAKE_CASE = tf_model(tf_model.dummy_inputs , training=a__ ) # build the network __SCREAMING_SNAKE_CASE = torch.load(a__ , map_location="""cpu""" ) __SCREAMING_SNAKE_CASE = pt_model_class.from_pretrained( pretrained_model_name_or_path=a__ , config=a__ , state_dict=a__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = pt_model(**pt_model.dummy_inputs ) __SCREAMING_SNAKE_CASE = pto[0].numpy() __SCREAMING_SNAKE_CASE = tfo[0].numpy() __SCREAMING_SNAKE_CASE = np.amax(np.abs(np_pt - np_tf ) ) print(F'Max absolute difference between models outputs {diff}' ) assert diff <= 2E-2, F'Error, model absolute difference is >2e-2: {diff}' # Save pytorch-model print(F'Save TensorFlow model to {tf_dump_path}' ) tf_model.save_weights(a__ , save_format="""h5""" ) def a__ ( a__ , a__ , a__=None , a__=None , a__=False , a__=False , a__=False , a__=False , ): """simple docstring""" if args_model_type is None: __SCREAMING_SNAKE_CASE = list(MODEL_CLASSES.keys() ) else: __SCREAMING_SNAKE_CASE = [args_model_type] for j, model_type in enumerate(a__ , start=1 ): print("""=""" * 1_00 ) print(F' Converting model type {j}/{len(a__ )}: {model_type}' ) print("""=""" * 1_00 ) if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(a__ , a__ ) , start=1 ): print("""-""" * 1_00 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(F' Skipping finetuned checkpoint {model_shortcut_name}' ) continue __SCREAMING_SNAKE_CASE = model_shortcut_name elif only_convert_finetuned_models: print(F' Skipping not finetuned checkpoint {model_shortcut_name}' ) continue print( F' Converting checkpoint {i}/{len(a__ )}: {model_shortcut_name} - model_type {model_type}' ) print("""-""" * 1_00 ) if config_shortcut_name in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = config_shortcut_name if model_shortcut_name in aws_model_maps: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = model_shortcut_name if os.path.isfile(a__ ): __SCREAMING_SNAKE_CASE = """converted_model""" convert_pt_checkpoint_to_tf( model_type=a__ , pytorch_checkpoint_path=a__ , config_file=a__ , tf_dump_path=os.path.join(a__ , model_shortcut_name + """-tf_model.h5""" ) , compare_with_pt_model=a__ , ) if remove_cached_files: os.remove(a__ ) os.remove(a__ ) if __name__ == "__main__": UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_dump_path', default=None, type=str, required=True, help='Path to the output Tensorflow dump file.' ) parser.add_argument( '--model_type', default=None, type=str, help=( f"""Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and """ 'convert all the models from AWS.' ), ) parser.add_argument( '--pytorch_checkpoint_path', default=None, type=str, help=( 'Path to the PyTorch checkpoint path or shortcut name to download from AWS. ' 'If not given, will download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--config_file', default=None, type=str, help=( 'The config json file corresponding to the pre-trained model. \n' 'This specifies the model architecture. If not given and ' '--pytorch_checkpoint_path is not given or is a shortcut name ' 'use the configuration associated to the shortcut name on the AWS' ), ) parser.add_argument( '--compare_with_pt_model', action='store_true', help='Compare Tensorflow and PyTorch model predictions.' ) parser.add_argument( '--use_cached_models', action='store_true', help='Use cached models if possible instead of updating to latest checkpoint versions.', ) parser.add_argument( '--remove_cached_files', action='store_true', help='Remove pytorch models after conversion (save memory when converting in batches).', ) parser.add_argument('--only_convert_finetuned_models', action='store_true', help='Only convert finetuned models.') UpperCAmelCase : List[Any] = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
267
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available A : Dict = { 'configuration_graphormer': ['GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GraphormerConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : int = [ 'GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'GraphormerForGraphClassification', 'GraphormerModel', 'GraphormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_graphormer import GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, GraphormerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_graphormer import ( GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST, GraphormerForGraphClassification, GraphormerModel, GraphormerPreTrainedModel, ) else: import sys A : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
6
'''simple docstring''' def a__ ( a__ ): """simple docstring""" if isinstance(a__ , a__ ): raise TypeError("""'float' object cannot be interpreted as an integer""" ) if isinstance(a__ , a__ ): raise TypeError("""'str' object cannot be interpreted as an integer""" ) if num == 0: return "0b0" __SCREAMING_SNAKE_CASE = False if num < 0: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = -num __SCREAMING_SNAKE_CASE = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(a__ ) for e in binary ) return "0b" + "".join(str(a__ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
267
0
"""simple docstring""" import os def SCREAMING_SNAKE_CASE__ ( ) -> int: lowercase__: str = os.path.join(os.path.dirname(a__ ) , '''num.txt''' ) with open(a__ ) as file_hand: return str(sum(int(a__ ) for line in file_hand ) )[:1_0] if __name__ == "__main__": print(solution())
177
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : Optional[int] = logging.get_logger(__name__) UpperCAmelCase : str = { 'facebook/convnextv2-tiny-1k-224': 'https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json', } class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "convnextv2" def __init__( self : Any , __SCREAMING_SNAKE_CASE : int=3 , __SCREAMING_SNAKE_CASE : Dict=4 , __SCREAMING_SNAKE_CASE : List[Any]=4 , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Optional[int]="gelu" , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.02 , __SCREAMING_SNAKE_CASE : Dict=1E-12 , __SCREAMING_SNAKE_CASE : List[str]=0.0 , __SCREAMING_SNAKE_CASE : Optional[Any]=224 , __SCREAMING_SNAKE_CASE : Tuple=None , __SCREAMING_SNAKE_CASE : List[str]=None , **__SCREAMING_SNAKE_CASE : Union[str, Any] , ) -> Union[str, Any]: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_stages __SCREAMING_SNAKE_CASE = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes __SCREAMING_SNAKE_CASE = [3, 3, 9, 3] if depths is None else depths __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(self.depths ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
0
from __future__ import annotations import unittest from transformers import EsmConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers.models.esm.modeling_tf_esm import ( TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, TFEsmModel, ) class snake_case : '''simple docstring''' def __init__( self : Any , lowerCAmelCase : str , ) -> Tuple: """simple docstring""" _snake_case : List[Any] = parent _snake_case : Any = 13 _snake_case : Union[str, Any] = 7 _snake_case : Union[str, Any] = True _snake_case : List[str] = True _snake_case : List[str] = True _snake_case : Tuple = 99 _snake_case : Any = 32 _snake_case : Optional[int] = 2 _snake_case : List[str] = 4 _snake_case : Union[str, Any] = 37 _snake_case : Any = """gelu""" _snake_case : Dict = 0.1 _snake_case : Tuple = 0.1 _snake_case : Optional[Any] = 512 _snake_case : Optional[Any] = 16 _snake_case : Dict = 2 _snake_case : str = 0.02 _snake_case : List[Any] = 3 _snake_case : int = 4 _snake_case : Tuple = None def UpperCamelCase_ ( self : Optional[Any]) -> str: """simple docstring""" _snake_case : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) _snake_case : List[Any] = None if self.use_input_mask: _snake_case : Optional[int] = random_attention_mask([self.batch_size, self.seq_length]) _snake_case : Optional[int] = None _snake_case : Optional[int] = None _snake_case : Optional[Any] = None if self.use_labels: _snake_case : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size) _snake_case : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) _snake_case : Optional[int] = ids_tensor([self.batch_size] , self.num_choices) _snake_case : Dict = EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , pad_token_id=1 , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase_ ( self : Union[str, Any]) -> Union[str, Any]: """simple docstring""" ( ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ) : str = self.prepare_config_and_inputs() _snake_case : List[Any] = True _snake_case : Union[str, Any] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) _snake_case : int = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) return ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def UpperCamelCase_ ( self : List[Any] , lowerCAmelCase : Tuple , lowerCAmelCase : str , lowerCAmelCase : str , lowerCAmelCase : Tuple , lowerCAmelCase : Tuple , lowerCAmelCase : int) -> List[Any]: """simple docstring""" _snake_case : List[Any] = TFEsmModel(config=__SCREAMING_SNAKE_CASE) _snake_case : Tuple = {"""input_ids""": input_ids, """attention_mask""": input_mask} _snake_case : str = model(__SCREAMING_SNAKE_CASE) _snake_case : Optional[int] = [input_ids, input_mask] _snake_case : str = model(__SCREAMING_SNAKE_CASE) _snake_case : Optional[Any] = model(__SCREAMING_SNAKE_CASE) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def UpperCamelCase_ ( self : Union[str, Any] , lowerCAmelCase : Any , lowerCAmelCase : List[Any] , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Dict , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : List[Any] , lowerCAmelCase : Optional[Any] , ) -> int: """simple docstring""" _snake_case : List[Any] = True _snake_case : int = TFEsmModel(config=__SCREAMING_SNAKE_CASE) _snake_case : Optional[Any] = { """input_ids""": input_ids, """attention_mask""": input_mask, """encoder_hidden_states""": encoder_hidden_states, """encoder_attention_mask""": encoder_attention_mask, } _snake_case : List[str] = model(__SCREAMING_SNAKE_CASE) _snake_case : Optional[Any] = [input_ids, input_mask] _snake_case : str = model(__SCREAMING_SNAKE_CASE , encoder_hidden_states=__SCREAMING_SNAKE_CASE) # Also check the case where encoder outputs are not passed _snake_case : int = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def UpperCamelCase_ ( self : Optional[int] , lowerCAmelCase : str , lowerCAmelCase : Optional[Any] , lowerCAmelCase : int , lowerCAmelCase : Optional[Any] , lowerCAmelCase : int , lowerCAmelCase : List[Any]) -> int: """simple docstring""" _snake_case : Optional[Any] = TFEsmForMaskedLM(config=__SCREAMING_SNAKE_CASE) _snake_case : str = model([input_ids, input_mask]) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def UpperCamelCase_ ( self : Optional[Any] , lowerCAmelCase : Any , lowerCAmelCase : Optional[int] , lowerCAmelCase : Dict , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : List[str] , lowerCAmelCase : int) -> List[str]: """simple docstring""" _snake_case : List[Any] = self.num_labels _snake_case : str = TFEsmForTokenClassification(config=__SCREAMING_SNAKE_CASE) _snake_case : str = {"""input_ids""": input_ids, """attention_mask""": input_mask} _snake_case : Any = model(__SCREAMING_SNAKE_CASE) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def UpperCamelCase_ ( self : List[Any]) -> int: """simple docstring""" _snake_case : Optional[int] = self.prepare_config_and_inputs() ( ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ) : Optional[int] = config_and_inputs _snake_case : List[Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class snake_case ( SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,unittest.TestCase ): '''simple docstring''' snake_case_ : Tuple = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) snake_case_ : Any = ( { """feature-extraction""": TFEsmModel, """fill-mask""": TFEsmForMaskedLM, """text-classification""": TFEsmForSequenceClassification, """token-classification""": TFEsmForTokenClassification, """zero-shot""": TFEsmForSequenceClassification, } if is_tf_available() else {} ) snake_case_ : List[Any] = False snake_case_ : Tuple = False def UpperCamelCase_ ( self : Dict) -> Any: """simple docstring""" _snake_case : Optional[Any] = TFEsmModelTester(self) _snake_case : str = ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , hidden_size=37) def UpperCamelCase_ ( self : Optional[Any]) -> Any: """simple docstring""" self.config_tester.run_common_tests() def UpperCamelCase_ ( self : List[str]) -> List[str]: """simple docstring""" _snake_case : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self : Any) -> Optional[Any]: """simple docstring""" _snake_case : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*__SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self : Optional[Any]) -> int: """simple docstring""" _snake_case : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self : Union[str, Any]) -> Tuple: """simple docstring""" _snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self : str) -> int: """simple docstring""" for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _snake_case : int = TFEsmModel.from_pretrained(__SCREAMING_SNAKE_CASE) self.assertIsNotNone(__SCREAMING_SNAKE_CASE) @unittest.skip("""Protein models do not support embedding resizing.""") def UpperCamelCase_ ( self : Optional[Any]) -> Tuple: """simple docstring""" pass @unittest.skip("""Protein models do not support embedding resizing.""") def UpperCamelCase_ ( self : List[Any]) -> Tuple: """simple docstring""" pass def UpperCamelCase_ ( self : str) -> Tuple: """simple docstring""" _snake_case , _snake_case : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _snake_case : Optional[int] = model_class(__SCREAMING_SNAKE_CASE) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer) if model_class is TFEsmForMaskedLM: # Output embedding test differs from the main test because they're a matrix, not a layer _snake_case : Dict = model.get_bias() assert isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) for k, v in name.items(): assert isinstance(__SCREAMING_SNAKE_CASE , tf.Variable) else: _snake_case : str = model.get_output_embeddings() assert x is None _snake_case : str = model.get_bias() assert name is None @require_tf class snake_case ( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase_ ( self : Tuple) -> Any: """simple docstring""" _snake_case : str = TFEsmForMaskedLM.from_pretrained("""facebook/esm2_t6_8M_UR50D""") _snake_case : List[str] = tf.constant([[0, 1, 2, 3, 4, 5]]) _snake_case : Union[str, Any] = model(__SCREAMING_SNAKE_CASE)[0] _snake_case : Union[str, Any] = [1, 6, 33] self.assertEqual(list(output.numpy().shape) , __SCREAMING_SNAKE_CASE) # compare the actual values for a slice. _snake_case : List[str] = tf.constant( [ [ [8.921_518, -10.589_814, -6.4_671_307], [-6.3_967_156, -13.911_377, -1.1_211_915], [-7.781_247, -13.951_557, -3.740_592], ] ]) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-2)) @slow def UpperCamelCase_ ( self : Optional[Any]) -> str: """simple docstring""" _snake_case : int = TFEsmModel.from_pretrained("""facebook/esm2_t6_8M_UR50D""") _snake_case : Optional[Any] = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]]) _snake_case : Optional[Any] = model(__SCREAMING_SNAKE_CASE)[0] # compare the actual values for a slice. _snake_case : List[Any] = tf.constant( [ [ [0.14_443_092, 0.54_125_327, 0.3_247_739], [0.30_340_484, 0.00_526_676, 0.31_077_722], [0.32_278_043, -0.24_987_096, 0.3_414_628], ] ]) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4))
317
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : List[str] = logging.get_logger(__name__) class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "maskformer-swin" lowerCAmelCase__ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : str , __SCREAMING_SNAKE_CASE : Tuple=224 , __SCREAMING_SNAKE_CASE : str=4 , __SCREAMING_SNAKE_CASE : Union[str, Any]=3 , __SCREAMING_SNAKE_CASE : Optional[Any]=96 , __SCREAMING_SNAKE_CASE : Optional[Any]=[2, 2, 6, 2] , __SCREAMING_SNAKE_CASE : Any=[3, 6, 12, 24] , __SCREAMING_SNAKE_CASE : Dict=7 , __SCREAMING_SNAKE_CASE : Dict=4.0 , __SCREAMING_SNAKE_CASE : Dict=True , __SCREAMING_SNAKE_CASE : str=0.0 , __SCREAMING_SNAKE_CASE : int=0.0 , __SCREAMING_SNAKE_CASE : str=0.1 , __SCREAMING_SNAKE_CASE : List[Any]="gelu" , __SCREAMING_SNAKE_CASE : str=False , __SCREAMING_SNAKE_CASE : Optional[int]=0.02 , __SCREAMING_SNAKE_CASE : Optional[int]=1E-5 , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Dict=None , **__SCREAMING_SNAKE_CASE : Tuple , ) -> Tuple: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = embed_dim __SCREAMING_SNAKE_CASE = depths __SCREAMING_SNAKE_CASE = len(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_heads __SCREAMING_SNAKE_CASE = window_size __SCREAMING_SNAKE_CASE = mlp_ratio __SCREAMING_SNAKE_CASE = qkv_bias __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = use_absolute_embeddings __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __SCREAMING_SNAKE_CASE = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) ) __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
0
"""simple docstring""" import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available lowerCAmelCase_ = logging.getLogger(__name__) @dataclass class __A : '''simple docstring''' lowerCAmelCase : int = 4_2 lowerCAmelCase : int = 4_2 lowerCAmelCase : int = 4_2 @dataclass class __A : '''simple docstring''' lowerCAmelCase : Any = 4_2 lowerCAmelCase : Tuple = 4_2 lowerCAmelCase : Union[str, Any] = None lowerCAmelCase : int = None class __A ( A_ ): '''simple docstring''' lowerCAmelCase : Optional[Any] = "train" lowerCAmelCase : List[str] = "dev" lowerCAmelCase : List[str] = "test" class __A : '''simple docstring''' @staticmethod def UpperCAmelCase ( _snake_case : Optional[int] ,_snake_case : Union[Split, str] ) -> List[InputExample]: """simple docstring""" raise NotImplementedError @staticmethod def UpperCAmelCase ( _snake_case : str ) -> List[str]: """simple docstring""" raise NotImplementedError @staticmethod def UpperCAmelCase ( _snake_case : List[InputExample] ,_snake_case : List[str] ,_snake_case : int ,_snake_case : PreTrainedTokenizer ,_snake_case : Optional[int]=False ,_snake_case : int="[CLS]" ,_snake_case : Optional[int]=1 ,_snake_case : Optional[int]="[SEP]" ,_snake_case : int=False ,_snake_case : Optional[Any]=False ,_snake_case : Dict=0 ,_snake_case : List[str]=0 ,_snake_case : Optional[int]=-100 ,_snake_case : Union[str, Any]=0 ,_snake_case : Union[str, Any]=True ,) -> List[InputFeatures]: """simple docstring""" lowercase__ : Union[str, Any] = {label: i for i, label in enumerate(__SCREAMING_SNAKE_CASE )} lowercase__ : Optional[Any] = [] for ex_index, example in enumerate(__SCREAMING_SNAKE_CASE ): if ex_index % 10_000 == 0: logger.info('''Writing example %d of %d''' ,__SCREAMING_SNAKE_CASE ,len(__SCREAMING_SNAKE_CASE ) ) lowercase__ : List[Any] = [] lowercase__ : List[Any] = [] for word, label in zip(example.words ,example.labels ): lowercase__ : Union[str, Any] = tokenizer.tokenize(__SCREAMING_SNAKE_CASE ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(__SCREAMING_SNAKE_CASE ) > 0: tokens.extend(__SCREAMING_SNAKE_CASE ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(__SCREAMING_SNAKE_CASE ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. lowercase__ : int = tokenizer.num_special_tokens_to_add() if len(__SCREAMING_SNAKE_CASE ) > max_seq_length - special_tokens_count: lowercase__ : Union[str, Any] = tokens[: (max_seq_length - special_tokens_count)] lowercase__ : List[Any] = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] lowercase__ : Dict = [sequence_a_segment_id] * len(__SCREAMING_SNAKE_CASE ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: lowercase__ : Tuple = [cls_token] + tokens lowercase__ : Optional[int] = [pad_token_label_id] + label_ids lowercase__ : str = [cls_token_segment_id] + segment_ids lowercase__ : Any = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. lowercase__ : Optional[Any] = [1 if mask_padding_with_zero else 0] * len(__SCREAMING_SNAKE_CASE ) # Zero-pad up to the sequence length. lowercase__ : str = max_seq_length - len(__SCREAMING_SNAKE_CASE ) if pad_on_left: lowercase__ : Optional[int] = ([pad_token] * padding_length) + input_ids lowercase__ : Union[str, Any] = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask lowercase__ : int = ([pad_token_segment_id] * padding_length) + segment_ids lowercase__ : Any = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(__SCREAMING_SNAKE_CASE ) == max_seq_length assert len(__SCREAMING_SNAKE_CASE ) == max_seq_length assert len(__SCREAMING_SNAKE_CASE ) == max_seq_length assert len(__SCREAMING_SNAKE_CASE ) == max_seq_length if ex_index < 5: logger.info('''*** Example ***''' ) logger.info('''guid: %s''' ,example.guid ) logger.info('''tokens: %s''' ,''' '''.join([str(__SCREAMING_SNAKE_CASE ) for x in tokens] ) ) logger.info('''input_ids: %s''' ,''' '''.join([str(__SCREAMING_SNAKE_CASE ) for x in input_ids] ) ) logger.info('''input_mask: %s''' ,''' '''.join([str(__SCREAMING_SNAKE_CASE ) for x in input_mask] ) ) logger.info('''segment_ids: %s''' ,''' '''.join([str(__SCREAMING_SNAKE_CASE ) for x in segment_ids] ) ) logger.info('''label_ids: %s''' ,''' '''.join([str(__SCREAMING_SNAKE_CASE ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: lowercase__ : str = None features.append( InputFeatures( input_ids=__SCREAMING_SNAKE_CASE ,attention_mask=__SCREAMING_SNAKE_CASE ,token_type_ids=__SCREAMING_SNAKE_CASE ,label_ids=__SCREAMING_SNAKE_CASE ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class __A ( A_ ): '''simple docstring''' lowerCAmelCase : List[Any] = 4_2 lowerCAmelCase : Union[str, Any] = nn.CrossEntropyLoss().ignore_index def __init__( self : List[Any] ,_snake_case : TokenClassificationTask ,_snake_case : str ,_snake_case : PreTrainedTokenizer ,_snake_case : List[str] ,_snake_case : str ,_snake_case : Optional[int] = None ,_snake_case : List[Any]=False ,_snake_case : Split = Split.train ,) -> Union[str, Any]: """simple docstring""" lowercase__ : List[Any] = os.path.join( __SCREAMING_SNAKE_CASE ,'''cached_{}_{}_{}'''.format(mode.value ,tokenizer.__class__.__name__ ,str(__SCREAMING_SNAKE_CASE ) ) ,) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. lowercase__ : Union[str, Any] = cached_features_file + '''.lock''' with FileLock(__SCREAMING_SNAKE_CASE ): if os.path.exists(__SCREAMING_SNAKE_CASE ) and not overwrite_cache: logger.info(f"""Loading features from cached file {cached_features_file}""" ) lowercase__ : List[str] = torch.load(__SCREAMING_SNAKE_CASE ) else: logger.info(f"""Creating features from dataset file at {data_dir}""" ) lowercase__ : List[Any] = token_classification_task.read_examples_from_file(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers lowercase__ : Optional[Any] = token_classification_task.convert_examples_to_features( __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,cls_token_at_end=bool(model_type in ['''xlnet'''] ) ,cls_token=tokenizer.cls_token ,cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 ,sep_token=tokenizer.sep_token ,sep_token_extra=__SCREAMING_SNAKE_CASE ,pad_on_left=bool(tokenizer.padding_side == '''left''' ) ,pad_token=tokenizer.pad_token_id ,pad_token_segment_id=tokenizer.pad_token_type_id ,pad_token_label_id=self.pad_token_label_id ,) logger.info(f"""Saving features into cached file {cached_features_file}""" ) torch.save(self.features ,__SCREAMING_SNAKE_CASE ) def __len__( self : Tuple ) -> str: """simple docstring""" return len(self.features ) def __getitem__( self : Union[str, Any] ,_snake_case : Union[str, Any] ) -> InputFeatures: """simple docstring""" return self.features[i] if is_tf_available(): import tensorflow as tf class __A : '''simple docstring''' lowerCAmelCase : Any = 4_2 lowerCAmelCase : Tuple = -1_0_0 def __init__( self : Any ,_snake_case : TokenClassificationTask ,_snake_case : str ,_snake_case : PreTrainedTokenizer ,_snake_case : List[str] ,_snake_case : str ,_snake_case : Optional[int] = None ,_snake_case : Tuple=False ,_snake_case : Split = Split.train ,) -> Optional[Any]: """simple docstring""" lowercase__ : Any = token_classification_task.read_examples_from_file(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers lowercase__ : Any = token_classification_task.convert_examples_to_features( __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,cls_token_at_end=bool(model_type in ['''xlnet'''] ) ,cls_token=tokenizer.cls_token ,cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 ,sep_token=tokenizer.sep_token ,sep_token_extra=__SCREAMING_SNAKE_CASE ,pad_on_left=bool(tokenizer.padding_side == '''left''' ) ,pad_token=tokenizer.pad_token_id ,pad_token_segment_id=tokenizer.pad_token_type_id ,pad_token_label_id=self.pad_token_label_id ,) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: lowercase__ : Any = tf.data.Dataset.from_generator( __SCREAMING_SNAKE_CASE ,({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa}, tf.intaa) ,( {'''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] )}, tf.TensorShape([None] ), ) ,) else: lowercase__ : Optional[int] = tf.data.Dataset.from_generator( __SCREAMING_SNAKE_CASE ,({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa}, tf.intaa) ,( { '''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] ), '''token_type_ids''': tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) ,) def UpperCAmelCase ( self : Union[str, Any] ) -> Tuple: """simple docstring""" lowercase__ : List[str] = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self : List[Any] ) -> Union[str, Any]: """simple docstring""" return len(self.features ) def __getitem__( self : Union[str, Any] ,_snake_case : Optional[int] ) -> InputFeatures: """simple docstring""" return self.features[i]
16
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = n __SCREAMING_SNAKE_CASE = [None] * self.n __SCREAMING_SNAKE_CASE = 0 # index of the first element __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 def __len__( self : Tuple ) -> int: """simple docstring""" return self.size def UpperCAmelCase__ ( self : Optional[Any] ) -> bool: """simple docstring""" return self.size == 0 def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" return False if self.is_empty() else self.array[self.front] def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Dict: """simple docstring""" if self.size >= self.n: raise Exception("""QUEUE IS FULL""" ) __SCREAMING_SNAKE_CASE = data __SCREAMING_SNAKE_CASE = (self.rear + 1) % self.n self.size += 1 return self def UpperCAmelCase__ ( self : List[str] ) -> Optional[Any]: """simple docstring""" if self.size == 0: raise Exception("""UNDERFLOW""" ) __SCREAMING_SNAKE_CASE = self.array[self.front] __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = (self.front + 1) % self.n self.size -= 1 return temp
267
0
from __future__ import annotations _UpperCAmelCase : Dict = 'Muhammad Umer Farooq' _UpperCAmelCase : Any = 'MIT' _UpperCAmelCase : Tuple = '1.0.0' _UpperCAmelCase : Optional[Any] = 'Muhammad Umer Farooq' _UpperCAmelCase : Union[str, Any] = 'contact@muhammadumerfarooq.me' _UpperCAmelCase : Dict = 'Alpha' import re from html.parser import HTMLParser from urllib import parse import requests class __lowerCAmelCase ( lowerCAmelCase): def __init__( self: List[Any] , _lowerCAmelCase: str ): super().__init__() lowercase :int = [] lowercase :str = domain def SCREAMING_SNAKE_CASE ( self: Union[str, Any] , _lowerCAmelCase: str , _lowerCAmelCase: list[tuple[str, str | None]] ): 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: lowercase :Dict = parse.urljoin(self.domain , __SCREAMING_SNAKE_CASE ) self.urls.append(__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( lowerCamelCase ): return ".".join(get_sub_domain_name(a__ ).split("." )[-2:] ) def UpperCAmelCase__ ( lowerCamelCase ): return parse.urlparse(a__ ).netloc def UpperCAmelCase__ ( lowerCamelCase = "https://github.com" ): lowercase :str = get_domain_name(a__ ) # Initialize the parser lowercase :int = Parser(a__ ) try: # Open URL lowercase :int = requests.get(a__ ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through lowercase :Any = set() for link in parser.urls: # open URL. # read = requests.get(link) try: lowercase :List[Any] = requests.get(a__ ) # Get the valid email. lowercase :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 : int = emails_from_url("https://github.com") print(f'''{len(emails)} emails found:''') print("\n".join(sorted(emails)))
236
'''simple docstring''' import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @property def UpperCAmelCase__ ( self : List[str] ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("""DownBlock2D""", """AttnDownBlock2D""") , up_block_types=("""AttnUpBlock2D""", """UpBlock2D""") , ) return model def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.dummy_uncond_unet __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" , return_dict=__SCREAMING_SNAKE_CASE )[0] __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """google/ddpm-cifar10-32""" __SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array([0.1564, 0.14645, 0.1406, 0.14715, 0.12425, 0.14045, 0.13115, 0.12175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
267
0
'''simple docstring''' from ...utils import deprecate from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401 deprecate( 'stable diffusion controlnet', '0.22.0', 'Importing `FlaxStableDiffusionControlNetPipeline` from diffusers.pipelines.stable_diffusion.flax_pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import FlaxStableDiffusionControlNetPipeline` instead.', standard_warn=False, stacklevel=3, )
349
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : """simple docstring""" @staticmethod def UpperCAmelCase__ ( *__SCREAMING_SNAKE_CASE : Tuple , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: """simple docstring""" pass @is_pipeline_test @require_vision @require_timm @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = MODEL_FOR_OBJECT_DETECTION_MAPPING def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Tuple ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = object_detector("""./tests/fixtures/tests_samples/COCO/000000039769.png""" , threshold=0.0 ) self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) import datasets __SCREAMING_SNAKE_CASE = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) __SCREAMING_SNAKE_CASE = [ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ] __SCREAMING_SNAKE_CASE = object_detector(__SCREAMING_SNAKE_CASE , threshold=0.0 ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(__SCREAMING_SNAKE_CASE ) ) for outputs in batch_outputs: self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) @require_tf @unittest.skip("""Object detection not implemented in TF""" ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" pass @require_torch def UpperCAmelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """hf-internal-testing/tiny-detr-mobilenetsv3""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=0.0 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Dict ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = 0.9985 __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=__SCREAMING_SNAKE_CASE ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) @require_torch @require_pytesseract @slow def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """Narsil/layoutlmv3-finetuned-funsd""" __SCREAMING_SNAKE_CASE = 0.9993 __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE , threshold=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector( """https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, ] , )
267
0
import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class A_ (a_ , unittest.TestCase ): UpperCAmelCase__ = FlaxAutoencoderKL @property def _lowercase ( self ): '''simple docstring''' UpperCAmelCase = 4 UpperCAmelCase = 3 UpperCAmelCase = (3_2, 3_2) UpperCAmelCase = jax.random.PRNGKey(0 ) UpperCAmelCase = jax.random.uniform(__SCREAMING_SNAKE_CASE , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def _lowercase ( self ): '''simple docstring''' UpperCAmelCase = { '''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, } UpperCAmelCase = self.dummy_input return init_dict, inputs_dict
273
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = FlaxAutoencoderKL @property def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (32, 32) __SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0 ) __SCREAMING_SNAKE_CASE = jax.random.uniform(__SCREAMING_SNAKE_CASE , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 4, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict
267
0
import warnings from ...utils import logging from .image_processing_chinese_clip import ChineseCLIPImageProcessor lowercase = logging.get_logger(__name__) class UpperCamelCase_ ( snake_case_ ): '''simple docstring''' def __init__( self , *a , **a ) -> None: warnings.warn( 'The class ChineseCLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use ChineseCLIPImageProcessor instead.' , __SCREAMING_SNAKE_CASE , ) super().__init__(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE )
178
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch UpperCAmelCase : int = random.Random() def a__ ( a__ , a__=1.0 , a__=None , a__=None ): """simple docstring""" if rng is None: __SCREAMING_SNAKE_CASE = global_rng __SCREAMING_SNAKE_CASE = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : str=7 , __SCREAMING_SNAKE_CASE : List[str]=400 , __SCREAMING_SNAKE_CASE : Any=2_000 , __SCREAMING_SNAKE_CASE : List[str]=10 , __SCREAMING_SNAKE_CASE : Optional[int]=160 , __SCREAMING_SNAKE_CASE : List[str]=8 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.0 , __SCREAMING_SNAKE_CASE : Dict=4_000 , __SCREAMING_SNAKE_CASE : Optional[int]=False , __SCREAMING_SNAKE_CASE : List[Any]=True , ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = min_seq_length __SCREAMING_SNAKE_CASE = max_seq_length __SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = return_attention_mask __SCREAMING_SNAKE_CASE = do_normalize __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = chunk_length __SCREAMING_SNAKE_CASE = hop_length def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring""" return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Union[str, Any]: """simple docstring""" def _flatten(__SCREAMING_SNAKE_CASE : Dict ): return list(itertools.chain(*__SCREAMING_SNAKE_CASE ) ) if equal_length: __SCREAMING_SNAKE_CASE = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size __SCREAMING_SNAKE_CASE = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = WhisperFeatureExtractor if is_speech_available() else None def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = WhisperFeatureExtractionTester(self ) def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = os.path.join(__SCREAMING_SNAKE_CASE , """feat_extract.json""" ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] # Test feature size __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , padding="""max_length""" , return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input __SCREAMING_SNAKE_CASE = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test batched __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in (800, 800, 800)] __SCREAMING_SNAKE_CASE = np.asarray(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test truncation required __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] __SCREAMING_SNAKE_CASE = [x[: feature_extractor.n_samples] for x in speech_inputs] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs_truncated] __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" import torch __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = np.random.rand(100 , 32 ).astype(np.floataa ) __SCREAMING_SNAKE_CASE = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Tuple ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech __SCREAMING_SNAKE_CASE = ds.sort("""id""" ).select(range(__SCREAMING_SNAKE_CASE ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def UpperCAmelCase__ ( self : Tuple ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on __SCREAMING_SNAKE_CASE = self._load_datasamples(1 ) __SCREAMING_SNAKE_CASE = WhisperFeatureExtractor() __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).input_features self.assertEqual(input_features.shape , (1, 80, 3_000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) ) def UpperCAmelCase__ ( self : List[Any] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = self._load_datasamples(1 )[0] __SCREAMING_SNAKE_CASE = ((audio - audio.min()) / (audio.max() - audio.min())) * 65_535 # Rescale to [0, 65535] to show issue __SCREAMING_SNAKE_CASE = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(np.all(np.mean(__SCREAMING_SNAKE_CASE ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(__SCREAMING_SNAKE_CASE ) - 1 ) < 1E-3 ) )
267
0
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) class A__ ( lowerCAmelCase__ ): lowerCAmelCase__ : Optional[Any] = "encoder-decoder" lowerCAmelCase__ : Optional[Any] = True def __init__( self : str , **_UpperCAmelCase : Any ) -> int: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) assert ( "encoder" in kwargs and "decoder" in kwargs ), "Config has to be initialized with encoder and decoder config" __lowercase = kwargs.pop('encoder' ) __lowercase = encoder_config.pop('model_type' ) __lowercase = kwargs.pop('decoder' ) __lowercase = decoder_config.pop('model_type' ) from ..auto.configuration_auto import AutoConfig __lowercase = AutoConfig.for_model(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __lowercase = AutoConfig.for_model(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __lowercase = True @classmethod def a__ ( cls : str , _UpperCAmelCase : PretrainedConfig , _UpperCAmelCase : PretrainedConfig , **_UpperCAmelCase : str ) -> PretrainedConfig: """simple docstring""" logger.info('Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config' ) __lowercase = True __lowercase = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **__SCREAMING_SNAKE_CASE ) def a__ ( self : List[str] ) -> Optional[int]: """simple docstring""" __lowercase = copy.deepcopy(self.__dict__ ) __lowercase = self.encoder.to_dict() __lowercase = self.decoder.to_dict() __lowercase = self.__class__.model_type return output
325
'''simple docstring''' from __future__ import annotations def a__ ( a__ , a__ , a__ ): """simple docstring""" if len(a__ ) == 0: raise ValueError("""find_max() arg is an empty sequence""" ) if ( left >= len(a__ ) or left < -len(a__ ) or right >= len(a__ ) or right < -len(a__ ) ): raise IndexError("""list index out of range""" ) if left == right: return nums[left] __SCREAMING_SNAKE_CASE = (left + right) >> 1 # the middle __SCREAMING_SNAKE_CASE = find_max(a__ , a__ , a__ ) # find max in range[left, mid] __SCREAMING_SNAKE_CASE = find_max(a__ , mid + 1 , a__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
267
0
'''simple docstring''' import os import string import sys lowerCamelCase :Union[str, Any] = 1 << 8 lowerCamelCase :Any = { 'tab': ord('''\t'''), 'newline': ord('''\r'''), 'esc': 2_7, 'up': 6_5 + ARROW_KEY_FLAG, 'down': 6_6 + ARROW_KEY_FLAG, 'right': 6_7 + ARROW_KEY_FLAG, 'left': 6_8 + ARROW_KEY_FLAG, 'mod_int': 9_1, 'undefined': sys.maxsize, 'interrupt': 3, 'insert': 5_0, 'delete': 5_1, 'pg_up': 5_3, 'pg_down': 5_4, } lowerCamelCase :Optional[Any] = KEYMAP['up'] lowerCamelCase :Optional[int] = KEYMAP['left'] if sys.platform == "win32": lowerCamelCase :Union[str, Any] = [] lowerCamelCase :Dict = { b'\xe0H': KEYMAP['up'] - ARROW_KEY_FLAG, b'\x00H': KEYMAP['up'] - ARROW_KEY_FLAG, b'\xe0P': KEYMAP['down'] - ARROW_KEY_FLAG, b'\x00P': KEYMAP['down'] - ARROW_KEY_FLAG, b'\xe0M': KEYMAP['right'] - ARROW_KEY_FLAG, b'\x00M': KEYMAP['right'] - ARROW_KEY_FLAG, b'\xe0K': KEYMAP['left'] - ARROW_KEY_FLAG, b'\x00K': KEYMAP['left'] - ARROW_KEY_FLAG, } for i in range(1_0): lowerCamelCase :Tuple = ord(str(i)) def a ( ): '''simple docstring''' if os.name == "nt": import msvcrt A_ : Optional[Any] = """mbcs""" # Flush the keyboard buffer while msvcrt.kbhit(): msvcrt.getch() if len(a__ ) == 0: # Read the keystroke A_ : Union[str, Any] = msvcrt.getch() # If it is a prefix char, get second part if ch in (b"\x00", b"\xe0"): A_ : str = ch + msvcrt.getch() # Translate actual Win chars to bullet char types try: A_ : int = chr(WIN_KEYMAP[cha] ) WIN_CH_BUFFER.append(chr(KEYMAP["""mod_int"""] ) ) WIN_CH_BUFFER.append(a__ ) if ord(a__ ) in ( KEYMAP["insert"] - 1 << 9, KEYMAP["delete"] - 1 << 9, KEYMAP["pg_up"] - 1 << 9, KEYMAP["pg_down"] - 1 << 9, ): WIN_CH_BUFFER.append(chr(1_26 ) ) A_ : List[str] = chr(KEYMAP["""esc"""] ) except KeyError: A_ : Optional[int] = cha[1] else: A_ : List[Any] = ch.decode(a__ ) else: A_ : Tuple = WIN_CH_BUFFER.pop(0 ) elif os.name == "posix": import termios import tty A_ : int = sys.stdin.fileno() A_ : List[Any] = termios.tcgetattr(a__ ) try: tty.setraw(a__ ) A_ : Union[str, Any] = sys.stdin.read(1 ) finally: termios.tcsetattr(a__ , termios.TCSADRAIN , a__ ) return ch def a ( ): '''simple docstring''' A_ : Any = get_raw_chars() if ord(a__ ) in [KEYMAP["interrupt"], KEYMAP["newline"]]: return char elif ord(a__ ) == KEYMAP["esc"]: A_ : int = get_raw_chars() if ord(a__ ) == KEYMAP["mod_int"]: A_ : List[Any] = get_raw_chars() if ord(a__ ) >= KEYMAP["arrow_begin"] - ARROW_KEY_FLAG and ord(a__ ) <= KEYMAP["arrow_end"] - ARROW_KEY_FLAG: return chr(ord(a__ ) + ARROW_KEY_FLAG ) else: return KEYMAP["undefined"] else: return get_raw_chars() else: if char in string.printable: return char else: return KEYMAP["undefined"]
206
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) # Initialize Result __SCREAMING_SNAKE_CASE = [] # Traverse through all denomination for denomination in reversed(a__ ): # Find denominations while int(a__ ) >= int(a__ ): total_value -= int(a__ ) answer.append(a__ ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase : Dict = [] UpperCAmelCase : List[str] = '0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): UpperCAmelCase : List[str] = int(input('Enter the number of denominations you want to add: ').strip()) for i in range(0, n): denominations.append(int(input(f"""Denomination {i}: """).strip())) UpperCAmelCase : str = input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter UpperCAmelCase : int = [1, 2, 5, 1_0, 2_0, 5_0, 1_0_0, 5_0_0, 2_0_0_0] UpperCAmelCase : Any = input('Enter the change you want to make: ').strip() if int(value) == 0 or int(value) < 0: print('The total value cannot be zero or negative.') else: print(f"""Following is minimal change for {value}: """) UpperCAmelCase : Any = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
267
0
'''simple docstring''' import pytest lowercase : Tuple = '__dummy_dataset1__' lowercase : int = '\nimport json\nimport os\n\nimport datasets\n\n\nREPO_URL = "https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/"\nURLS = {"train": REPO_URL + "wikiann-bn-train.jsonl", "validation": REPO_URL + "wikiann-bn-validation.jsonl"}\n\n\nclass __DummyDataset1__(datasets.GeneratorBasedBuilder):\n\n def _info(self):\n features = datasets.Features(\n {\n "tokens": datasets.Sequence(datasets.Value("string")),\n "ner_tags": datasets.Sequence(\n datasets.features.ClassLabel(\n names=[\n "O",\n "B-PER",\n "I-PER",\n "B-ORG",\n "I-ORG",\n "B-LOC",\n "I-LOC",\n ]\n )\n ),\n "langs": datasets.Sequence(datasets.Value("string")),\n "spans": datasets.Sequence(datasets.Value("string")),\n }\n )\n return datasets.DatasetInfo(features=features)\n\n def _split_generators(self, dl_manager):\n dl_path = dl_manager.download(URLS)\n return [\n datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={"filepath": dl_path["train"]}),\n datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={"filepath": dl_path["validation"]}),\n ]\n\n def _generate_examples(self, filepath):\n with open(filepath, "r", encoding="utf-8") as f:\n for i, line in enumerate(f):\n yield i, json.loads(line)\n' @pytest.fixture def lowerCAmelCase_ ( ): '''simple docstring''' return DATASET_LOADING_SCRIPT_NAME @pytest.fixture def lowerCAmelCase_ ( ): '''simple docstring''' return DATASET_LOADING_SCRIPT_CODE @pytest.fixture def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' A : Optional[int] = dataset_loading_script_name A : Any = tmp_path / '''datasets''' / script_name script_dir.mkdir(parents=a__ ) A : Dict = script_dir / F'{script_name}.py' with open(a__ , '''w''' ) as f: f.write(a__ ) return str(a__ )
3
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu UpperCAmelCase : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def a__ ( a__ , a__=None , a__=None , a__=None ): """simple docstring""" __SCREAMING_SNAKE_CASE = True while ask_again: __SCREAMING_SNAKE_CASE = input(a__ ) try: if default is not None and len(a__ ) == 0: return default return convert_value(a__ ) if convert_value is not None else result except Exception: if error_message is not None: print(a__ ) def a__ ( a__ , a__=[] , a__=None , a__=0 ): """simple docstring""" __SCREAMING_SNAKE_CASE = BulletMenu(a__ , a__ ) __SCREAMING_SNAKE_CASE = menu.run(default_choice=a__ ) return convert_value(a__ ) if convert_value is not None else result def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value] ) def a__ ( a__ ): """simple docstring""" return {"yes": True, "no": False}[value.lower()] class lowerCAmelCase__ ( argparse.RawDescriptionHelpFormatter ): """simple docstring""" def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = super()._format_usage(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = usage.replace("""<command> [<args>] """ , """""" ) return usage
267
0
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging A : Optional[Any] = logging.get_logger(__name__) A : Dict = { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json', } class __A( a ): snake_case_ = '''mvp''' snake_case_ = ['''past_key_values'''] snake_case_ = {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''} def __init__( self , _snake_case=50_267 , _snake_case=1_024 , _snake_case=12 , _snake_case=4_096 , _snake_case=16 , _snake_case=12 , _snake_case=4_096 , _snake_case=16 , _snake_case=0.0 , _snake_case=0.0 , _snake_case="gelu" , _snake_case=1_024 , _snake_case=0.1 , _snake_case=0.0 , _snake_case=0.0 , _snake_case=0.02 , _snake_case=0.0 , _snake_case=False , _snake_case=True , _snake_case=1 , _snake_case=0 , _snake_case=2 , _snake_case=True , _snake_case=2 , _snake_case=2 , _snake_case=False , _snake_case=100 , _snake_case=800 , **_snake_case , ) -> Union[str, Any]: '''simple docstring''' __a = vocab_size __a = max_position_embeddings __a = d_model __a = encoder_ffn_dim __a = encoder_layers __a = encoder_attention_heads __a = decoder_ffn_dim __a = decoder_layers __a = decoder_attention_heads __a = dropout __a = attention_dropout __a = activation_dropout __a = activation_function __a = init_std __a = encoder_layerdrop __a = decoder_layerdrop __a = classifier_dropout __a = use_cache __a = encoder_layers __a = scale_embedding # scale factor will be sqrt(d_model) if True __a = use_prompt __a = prompt_length __a = prompt_mid_dim super().__init__( pad_token_id=__SCREAMING_SNAKE_CASE , bos_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , is_encoder_decoder=__SCREAMING_SNAKE_CASE , decoder_start_token_id=__SCREAMING_SNAKE_CASE , forced_eos_token_id=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) if self.forced_bos_token_id is None and kwargs.get('''force_bos_token_to_be_generated''' , __SCREAMING_SNAKE_CASE ): __a = self.bos_token_id warnings.warn( F"""Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. """ '''The config can simply be saved and uploaded again to be fixed.''' )
6
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) if n == 0: return 0 __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + naive_cut_rod_recursive(n - i , a__ ) ) return max_revue def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ ): """simple docstring""" if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , a__ , a__ ) , ) __SCREAMING_SNAKE_CASE = max_revenue return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] __SCREAMING_SNAKE_CASE = 0 for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max_rev[i] for j in range(1 , i + 1 ): __SCREAMING_SNAKE_CASE = max(a__ , prices[j - 1] + max_rev[i - j] ) __SCREAMING_SNAKE_CASE = max_revenue_i return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" if n < 0: __SCREAMING_SNAKE_CASE = F'n must be greater than or equal to 0. Got n = {n}' raise ValueError(a__ ) if n > len(a__ ): __SCREAMING_SNAKE_CASE = ( """Each integral piece of rod must have a corresponding price. """ F'Got n = {n} but length of prices = {len(a__ )}' ) raise ValueError(a__ ) def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = [6, 10, 12, 15, 20, 23] __SCREAMING_SNAKE_CASE = len(a__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __SCREAMING_SNAKE_CASE = 36 __SCREAMING_SNAKE_CASE = top_down_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = bottom_up_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = naive_cut_rod_recursive(a__ , a__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
267
0
"""simple docstring""" def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase ) -> List[Any]: if not isinstance(a__ , a__ ): lowercase__: Union[str, Any] = F"""Input value of [number={number}] must be an integer""" raise TypeError(a__ ) if number < 1: lowercase__: str = F"""Input value of [number={number}] must be > 0""" raise ValueError(a__ ) lowercase__: Optional[int] = 1 for i in range(1 , a__ ): current_number *= 4 * i - 2 current_number //= i + 1 return current_number if __name__ == "__main__": import doctest doctest.testmod()
177
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : Union[str, Any] = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ 'SEW_PRETRAINED_MODEL_ARCHIVE_LIST', 'SEWForCTC', 'SEWForSequenceClassification', 'SEWModel', 'SEWPreTrainedModel', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys UpperCAmelCase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
267
0
import argparse import os import re a__ = 'src/transformers/models/auto' # re pattern that matches mapping introductions: # SUPER_MODEL_MAPPING_NAMES = OrderedDict or SUPER_MODEL_MAPPING = OrderedDict a__ = re.compile(R"""[A-Z_]+_MAPPING(\s+|_[A-Z_]+\s+)=\s+OrderedDict""") # re pattern that matches identifiers in mappings a__ = re.compile(R"""\s*\(\s*\"(\S[^\"]+)\"""") def lowercase ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] = False ) -> str: with open(a__ , """r""" , encoding="""utf-8""" ) as f: _snake_case : Union[str, Any] = f.read() _snake_case : List[Any] = content.split("""\n""" ) _snake_case : Any = [] _snake_case : Union[str, Any] = 0 while line_idx < len(a__ ): if _re_intro_mapping.search(lines[line_idx] ) is not None: _snake_case : Any = len(re.search(R"""^(\s*)\S""" , lines[line_idx] ).groups()[0] ) + 8 # Start of a new mapping! while not lines[line_idx].startswith(""" """ * indent + """(""" ): new_lines.append(lines[line_idx] ) line_idx += 1 _snake_case : str = [] while lines[line_idx].strip() != "]": # Blocks either fit in one line or not if lines[line_idx].strip() == "(": _snake_case : Optional[Any] = line_idx while not lines[line_idx].startswith(""" """ * indent + """)""" ): line_idx += 1 blocks.append("""\n""".join(lines[start_idx : line_idx + 1] ) ) else: blocks.append(lines[line_idx] ) line_idx += 1 # Sort blocks by their identifiers _snake_case : List[Any] = sorted(a__ , key=lambda SCREAMING_SNAKE_CASE__ : _re_identifier.search(a__ ).groups()[0] ) new_lines += blocks else: new_lines.append(lines[line_idx] ) line_idx += 1 if overwrite: with open(a__ , """w""" , encoding="""utf-8""" ) as f: f.write("""\n""".join(a__ ) ) elif "\n".join(a__ ) != content: return True def lowercase ( SCREAMING_SNAKE_CASE__ : Dict = False ) -> Optional[int]: _snake_case : int = [os.path.join(a__ , a__ ) for f in os.listdir(a__ ) if f.endswith(""".py""" )] _snake_case : List[Any] = [sort_auto_mapping(a__ , overwrite=a__ ) for fname in fnames] if not overwrite and any(a__ ): _snake_case : Optional[int] = [f for f, d in zip(a__ , a__ ) if d] raise ValueError( F'''The following files have auto mappings that need sorting: {', '.join(a__ )}. Run `make style` to fix''' """ this.""" ) if __name__ == "__main__": a__ = argparse.ArgumentParser() parser.add_argument("""--check_only""", action="""store_true""", help="""Whether to only check or fix style.""") a__ = parser.parse_args() sort_all_auto_mappings(not args.check_only)
317
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = name __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = weight def __repr__( self : str ) -> Union[str, Any]: """simple docstring""" return f'{self.__class__.__name__}({self.name}, {self.value}, {self.weight})' def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" return self.value def UpperCAmelCase__ ( self : Any ) -> str: """simple docstring""" return self.name def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.weight def UpperCAmelCase__ ( self : int ) -> Tuple: """simple docstring""" return self.value / self.weight def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = [] for i in range(len(a__ ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = sorted(a__ , key=a__ , reverse=a__ ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 0.0, 0.0 for i in range(len(a__ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def a__ ( ): """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
267
0
"""simple docstring""" import sys import webbrowser import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print('Googling.....') lowerCAmelCase_ = 'https://www.google.com/search?q=' + ' '.join(sys.argv[1:]) lowerCAmelCase_ = requests.get(url, headers={'UserAgent': UserAgent().random}) # res.raise_for_status() with open('project1a.html', 'wb') as out_file: # only for knowing the class for data in res.iter_content(10_000): out_file.write(data) lowerCAmelCase_ = BeautifulSoup(res.text, 'html.parser') lowerCAmelCase_ = list(soup.select('.eZt8xd'))[:5] print(len(links)) for link in links: if link.text == "Maps": webbrowser.open(link.get('href')) else: webbrowser.open(F'''https://google.com{link.get("href")}''')
16
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE = ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on __SCREAMING_SNAKE_CASE = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) __SCREAMING_SNAKE_CASE = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] __SCREAMING_SNAKE_CASE = {"""unk_token""": """<unk>"""} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__SCREAMING_SNAKE_CASE ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48145466, 0.4578275, 0.40821073], """image_std""": [0.26862954, 0.26130258, 0.27577711], } __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , __SCREAMING_SNAKE_CASE ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> str: """simple docstring""" return CLIPTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple , **__SCREAMING_SNAKE_CASE : Any ) -> int: """simple docstring""" return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> List[str]: """simple docstring""" return CLIPImageProcessor.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(__SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_slow.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_fast.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) __SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = image_processor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) __SCREAMING_SNAKE_CASE = processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer(__SCREAMING_SNAKE_CASE ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase__ ( self : Dict ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(__SCREAMING_SNAKE_CASE ): processor() def UpperCAmelCase__ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE = processor.batch_decode(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
267
0
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionTextToImagePipeline from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device _UpperCAmelCase : str = False class __lowerCAmelCase ( unittest.TestCase): pass @nightly @require_torch_gpu class __lowerCAmelCase ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self: Union[str, Any] ): super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE ( self: Any ): lowercase :Dict = VersatileDiffusionTextToImagePipeline.from_pretrained("shi-labs/versatile-diffusion" ) # remove text_unet pipe.remove_unused_weights() pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) lowercase :Union[str, Any] = "A painting of a squirrel eating a burger " lowercase :Optional[int] = torch.manual_seed(0 ) lowercase :Optional[int] = pipe( prompt=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , guidance_scale=7.5 , num_inference_steps=2 , output_type="numpy" ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(__SCREAMING_SNAKE_CASE ) lowercase :Dict = VersatileDiffusionTextToImagePipeline.from_pretrained(__SCREAMING_SNAKE_CASE ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) lowercase :Optional[Any] = generator.manual_seed(0 ) lowercase :int = pipe( prompt=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , guidance_scale=7.5 , num_inference_steps=2 , output_type="numpy" ).images assert np.abs(image - new_image ).sum() < 1e-5, "Models don't have the same forward pass" def SCREAMING_SNAKE_CASE ( self: Tuple ): lowercase :Dict = VersatileDiffusionTextToImagePipeline.from_pretrained( "shi-labs/versatile-diffusion" , torch_dtype=torch.floataa ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) lowercase :Dict = "A painting of a squirrel eating a burger " lowercase :Any = torch.manual_seed(0 ) lowercase :int = pipe( prompt=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , guidance_scale=7.5 , num_inference_steps=50 , output_type="numpy" ).images lowercase :List[str] = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) lowercase :Any = np.array([0.33_67, 0.31_69, 0.26_56, 0.38_70, 0.47_90, 0.37_96, 0.40_09, 0.48_78, 0.47_78] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
236
'''simple docstring''' import numpy as np def a__ ( a__ , a__ , a__ = 1E-1_2 , a__ = 1_00 , ): """simple docstring""" assert np.shape(a__ )[0] == np.shape(a__ )[1] # Ensure proper dimensionality. assert np.shape(a__ )[0] == np.shape(a__ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(a__ ) == np.iscomplexobj(a__ ) __SCREAMING_SNAKE_CASE = np.iscomplexobj(a__ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(a__ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 1E1_2 while not convergence: # Multiple matrix by the vector. __SCREAMING_SNAKE_CASE = np.dot(a__ , a__ ) # Normalize the resulting output vector. __SCREAMING_SNAKE_CASE = w / np.linalg.norm(a__ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __SCREAMING_SNAKE_CASE = vector.conj().T if is_complex else vector.T __SCREAMING_SNAKE_CASE = np.dot(a__ , np.dot(a__ , a__ ) ) # Check convergence. __SCREAMING_SNAKE_CASE = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = lambda_ if is_complex: __SCREAMING_SNAKE_CASE = np.real(lambda_ ) return lambda_, vector def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ) __SCREAMING_SNAKE_CASE = real_input_matrix.astype(np.complexaaa ) __SCREAMING_SNAKE_CASE = np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __SCREAMING_SNAKE_CASE = real_input_matrix __SCREAMING_SNAKE_CASE = real_vector elif problem_type == "complex": __SCREAMING_SNAKE_CASE = complex_input_matrix __SCREAMING_SNAKE_CASE = complex_vector # Our implementation. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = power_iteration(a__ , a__ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = np.linalg.eigh(a__ ) # Last eigenvalue is the maximum one. __SCREAMING_SNAKE_CASE = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __SCREAMING_SNAKE_CASE = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(a__ ) - np.abs(a__ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
267
0
'''simple docstring''' import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEmbeddings, BertLayer, BertPooler, BertPreTrainedModel, ) def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = torch.exp(a__ ) __UpperCamelCase = torch.sum(a__ ,dim=1 ) # sum of exp(x_i) __UpperCamelCase = torch.sum(x * exp_x ,dim=1 ) # sum of x_i * exp(x_i) return torch.log(a__ ) - B / A class UpperCAmelCase__ ( nn.Module): def __init__( self , lowercase ) -> Optional[int]: super().__init__() __UpperCamelCase = config.output_attentions __UpperCamelCase = config.output_hidden_states __UpperCamelCase = nn.ModuleList([BertLayer(__SCREAMING_SNAKE_CASE ) for _ in range(config.num_hidden_layers )] ) __UpperCamelCase = nn.ModuleList([BertHighway(__SCREAMING_SNAKE_CASE ) for _ in range(config.num_hidden_layers )] ) __UpperCamelCase = [-1 for _ in range(config.num_hidden_layers )] def __lowerCamelCase ( self , lowercase ) -> int: if (type(__SCREAMING_SNAKE_CASE ) is float) or (type(__SCREAMING_SNAKE_CASE ) is int): for i in range(len(self.early_exit_entropy ) ): __UpperCamelCase = x else: __UpperCamelCase = x def __lowerCamelCase ( self , lowercase ) -> Dict: __UpperCamelCase = pooler.state_dict() for highway in self.highway: for name, param in highway.pooler.state_dict().items(): param.copy_(loaded_model[name] ) def __lowerCamelCase ( self , lowercase , lowercase=None , lowercase=None , lowercase=None , lowercase=None , ) -> Optional[int]: __UpperCamelCase = () __UpperCamelCase = () __UpperCamelCase = () for i, layer_module in enumerate(self.layer ): if self.output_hidden_states: __UpperCamelCase = all_hidden_states + (hidden_states,) __UpperCamelCase = layer_module( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , head_mask[i] , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __UpperCamelCase = layer_outputs[0] if self.output_attentions: __UpperCamelCase = all_attentions + (layer_outputs[1],) __UpperCamelCase = (hidden_states,) if self.output_hidden_states: __UpperCamelCase = current_outputs + (all_hidden_states,) if self.output_attentions: __UpperCamelCase = current_outputs + (all_attentions,) __UpperCamelCase = self.highway[i](__SCREAMING_SNAKE_CASE ) # logits, pooled_output if not self.training: __UpperCamelCase = highway_exit[0] __UpperCamelCase = entropy(__SCREAMING_SNAKE_CASE ) __UpperCamelCase = highway_exit + (highway_entropy,) # logits, hidden_states(?), entropy __UpperCamelCase = all_highway_exits + (highway_exit,) if highway_entropy < self.early_exit_entropy[i]: __UpperCamelCase = (highway_logits,) + current_outputs[1:] + (all_highway_exits,) raise HighwayException(__SCREAMING_SNAKE_CASE , i + 1 ) else: __UpperCamelCase = all_highway_exits + (highway_exit,) # Add last layer if self.output_hidden_states: __UpperCamelCase = all_hidden_states + (hidden_states,) __UpperCamelCase = (hidden_states,) if self.output_hidden_states: __UpperCamelCase = outputs + (all_hidden_states,) if self.output_attentions: __UpperCamelCase = outputs + (all_attentions,) __UpperCamelCase = outputs + (all_highway_exits,) return outputs # last-layer hidden state, (all hidden states), (all attentions), all highway exits @add_start_docstrings( '''The Bert Model transformer with early exiting (DeeBERT). ''' , UpperCAmelCase_ , ) class UpperCAmelCase__ ( UpperCAmelCase_): def __init__( self , lowercase ) -> Optional[int]: super().__init__(__SCREAMING_SNAKE_CASE ) __UpperCamelCase = config __UpperCamelCase = BertEmbeddings(__SCREAMING_SNAKE_CASE ) __UpperCamelCase = DeeBertEncoder(__SCREAMING_SNAKE_CASE ) __UpperCamelCase = BertPooler(__SCREAMING_SNAKE_CASE ) self.init_weights() def __lowerCamelCase ( self ) -> Optional[int]: self.encoder.init_highway_pooler(self.pooler ) def __lowerCamelCase ( self ) -> str: return self.embeddings.word_embeddings def __lowerCamelCase ( self , lowercase ) -> List[str]: __UpperCamelCase = value def __lowerCamelCase ( self , lowercase ) -> Optional[int]: for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(__SCREAMING_SNAKE_CASE ) @add_start_docstrings_to_model_forward(__SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self , lowercase=None , lowercase=None , lowercase=None , lowercase=None , lowercase=None , lowercase=None , lowercase=None , lowercase=None , ) -> Optional[Any]: if input_ids is not None and inputs_embeds is not None: raise ValueError("""You cannot specify both input_ids and inputs_embeds at the same time""" ) elif input_ids is not None: __UpperCamelCase = input_ids.size() elif inputs_embeds is not None: __UpperCamelCase = inputs_embeds.size()[:-1] else: raise ValueError("""You have to specify either input_ids or inputs_embeds""" ) __UpperCamelCase = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: __UpperCamelCase = torch.ones(__SCREAMING_SNAKE_CASE , device=__SCREAMING_SNAKE_CASE ) if encoder_attention_mask is None: __UpperCamelCase = torch.ones(__SCREAMING_SNAKE_CASE , device=__SCREAMING_SNAKE_CASE ) if token_type_ids is None: __UpperCamelCase = torch.zeros(__SCREAMING_SNAKE_CASE , dtype=torch.long , device=__SCREAMING_SNAKE_CASE ) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. __UpperCamelCase = self.get_extended_attention_mask(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if encoder_attention_mask.dim() == 3: __UpperCamelCase = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.dim() == 2: __UpperCamelCase = encoder_attention_mask[:, None, None, :] __UpperCamelCase = encoder_extended_attention_mask.to( dtype=next(self.parameters() ).dtype ) # fp16 compatibility __UpperCamelCase = (1.0 - encoder_extended_attention_mask) * -10_000.0 # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] __UpperCamelCase = self.get_head_mask(__SCREAMING_SNAKE_CASE , self.config.num_hidden_layers ) __UpperCamelCase = self.embeddings( input_ids=__SCREAMING_SNAKE_CASE , position_ids=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , inputs_embeds=__SCREAMING_SNAKE_CASE ) __UpperCamelCase = self.encoder( __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , head_mask=__SCREAMING_SNAKE_CASE , encoder_hidden_states=__SCREAMING_SNAKE_CASE , encoder_attention_mask=__SCREAMING_SNAKE_CASE , ) __UpperCamelCase = encoder_outputs[0] __UpperCamelCase = self.pooler(__SCREAMING_SNAKE_CASE ) __UpperCamelCase = ( sequence_output, pooled_output, ) + encoder_outputs[ 1: ] # add hidden_states and attentions if they are here return outputs # sequence_output, pooled_output, (hidden_states), (attentions), highway exits class UpperCAmelCase__ ( UpperCAmelCase_): def __init__( self , lowercase , lowercase ) -> Optional[int]: __UpperCamelCase = message __UpperCamelCase = exit_layer # start from 1! class UpperCAmelCase__ ( nn.Module): def __init__( self , lowercase ) -> str: super().__init__() __UpperCamelCase = BertPooler(__SCREAMING_SNAKE_CASE ) __UpperCamelCase = nn.Dropout(config.hidden_dropout_prob ) __UpperCamelCase = nn.Linear(config.hidden_size , config.num_labels ) def __lowerCamelCase ( self , lowercase ) -> Optional[int]: __UpperCamelCase = encoder_outputs[0] __UpperCamelCase = self.pooler(__SCREAMING_SNAKE_CASE ) # "return" pooler_output # BertModel __UpperCamelCase = (pooler_input, pooler_output) + encoder_outputs[1:] # "return" bmodel_output # Dropout and classification __UpperCamelCase = bmodel_output[1] __UpperCamelCase = self.dropout(__SCREAMING_SNAKE_CASE ) __UpperCamelCase = self.classifier(__SCREAMING_SNAKE_CASE ) return logits, pooled_output @add_start_docstrings( '''Bert Model (with early exiting - DeeBERT) with a classifier on top,\n also takes care of multi-layer training. ''' , UpperCAmelCase_ , ) class UpperCAmelCase__ ( UpperCAmelCase_): def __init__( self , lowercase ) -> Optional[Any]: super().__init__(__SCREAMING_SNAKE_CASE ) __UpperCamelCase = config.num_labels __UpperCamelCase = config.num_hidden_layers __UpperCamelCase = DeeBertModel(__SCREAMING_SNAKE_CASE ) __UpperCamelCase = nn.Dropout(config.hidden_dropout_prob ) __UpperCamelCase = nn.Linear(config.hidden_size , self.config.num_labels ) self.init_weights() @add_start_docstrings_to_model_forward(__SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self , lowercase=None , lowercase=None , lowercase=None , lowercase=None , lowercase=None , lowercase=None , lowercase=None , lowercase=-1 , lowercase=False , ) -> Any: __UpperCamelCase = self.num_layers try: __UpperCamelCase = self.bert( __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , position_ids=__SCREAMING_SNAKE_CASE , head_mask=__SCREAMING_SNAKE_CASE , inputs_embeds=__SCREAMING_SNAKE_CASE , ) # sequence_output, pooled_output, (hidden_states), (attentions), highway exits __UpperCamelCase = outputs[1] __UpperCamelCase = self.dropout(__SCREAMING_SNAKE_CASE ) __UpperCamelCase = self.classifier(__SCREAMING_SNAKE_CASE ) __UpperCamelCase = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: __UpperCamelCase = e.message __UpperCamelCase = e.exit_layer __UpperCamelCase = outputs[0] if not self.training: __UpperCamelCase = entropy(__SCREAMING_SNAKE_CASE ) __UpperCamelCase = [] __UpperCamelCase = [] if labels is not None: if self.num_labels == 1: # We are doing regression __UpperCamelCase = MSELoss() __UpperCamelCase = loss_fct(logits.view(-1 ) , labels.view(-1 ) ) else: __UpperCamelCase = CrossEntropyLoss() __UpperCamelCase = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) # work with highway exits __UpperCamelCase = [] for highway_exit in outputs[-1]: __UpperCamelCase = highway_exit[0] if not self.training: highway_logits_all.append(__SCREAMING_SNAKE_CASE ) highway_entropy.append(highway_exit[2] ) if self.num_labels == 1: # We are doing regression __UpperCamelCase = MSELoss() __UpperCamelCase = loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) ) else: __UpperCamelCase = CrossEntropyLoss() __UpperCamelCase = loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) highway_losses.append(__SCREAMING_SNAKE_CASE ) if train_highway: __UpperCamelCase = (sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: __UpperCamelCase = (loss,) + outputs if not self.training: __UpperCamelCase = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: __UpperCamelCase = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), (highway_exits)
349
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( a , a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = StableDiffusionInpaintPipeline lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowerCAmelCase__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowerCAmelCase__ = frozenset([] ) def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = PNDMScheduler(skip_prk_steps=__SCREAMING_SNAKE_CASE ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) __SCREAMING_SNAKE_CASE = CLIPTextModel(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __SCREAMING_SNAKE_CASE = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any]=0 ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 )[0] __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE ) ).convert("""RGB""" ).resize((64, 64) ) __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): __SCREAMING_SNAKE_CASE = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = """cpu""" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe.to(__SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe(**__SCREAMING_SNAKE_CASE ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __SCREAMING_SNAKE_CASE = np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : List[str] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained(__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def UpperCAmelCase__ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , safety_checker=__SCREAMING_SNAKE_CASE , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def UpperCAmelCase__ ( self : Tuple ) -> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = PNDMScheduler.from_pretrained(__SCREAMING_SNAKE_CASE , subfolder="""scheduler""" ) __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
267
0
import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class A_ (unittest.TestCase ): def _lowercase ( self ): '''simple docstring''' UpperCAmelCase = ['''a''', '''b''', '''c'''] # Defaults to last layer if both are None UpperCAmelCase , UpperCAmelCase = get_aligned_output_features_output_indices(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , ['''c'''] ) self.assertEqual(__SCREAMING_SNAKE_CASE , [2] ) # Out indices set to match out features UpperCAmelCase , UpperCAmelCase = get_aligned_output_features_output_indices(['''a''', '''c'''] , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , ['''a''', '''c'''] ) self.assertEqual(__SCREAMING_SNAKE_CASE , [0, 2] ) # Out features set to match out indices UpperCAmelCase , UpperCAmelCase = get_aligned_output_features_output_indices(__SCREAMING_SNAKE_CASE , [0, 2] , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , ['''a''', '''c'''] ) self.assertEqual(__SCREAMING_SNAKE_CASE , [0, 2] ) # Out features selected from negative indices UpperCAmelCase , UpperCAmelCase = get_aligned_output_features_output_indices(__SCREAMING_SNAKE_CASE , [-3, -1] , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , ['''a''', '''c'''] ) self.assertEqual(__SCREAMING_SNAKE_CASE , [-3, -1] ) def _lowercase ( self ): '''simple docstring''' with self.assertRaises(__SCREAMING_SNAKE_CASE ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , __SCREAMING_SNAKE_CASE ) # Out features must be a list with self.assertRaises(__SCREAMING_SNAKE_CASE ): verify_out_features_out_indices(('''a''', '''b''') , (0, 1) , ['''a''', '''b'''] ) # Out features must be a subset of stage names with self.assertRaises(__SCREAMING_SNAKE_CASE ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , ['''a'''] ) # Out indices must be a list or tuple with self.assertRaises(__SCREAMING_SNAKE_CASE ): verify_out_features_out_indices(__SCREAMING_SNAKE_CASE , 0 , ['''a''', '''b'''] ) # Out indices must be a subset of stage names with self.assertRaises(__SCREAMING_SNAKE_CASE ): verify_out_features_out_indices(__SCREAMING_SNAKE_CASE , (0, 1) , ['''a'''] ) # Out features and out indices must be the same length with self.assertRaises(__SCREAMING_SNAKE_CASE ): verify_out_features_out_indices(['''a''', '''b'''] , (0,) , ['''a''', '''b''', '''c'''] ) # Out features should match out indices with self.assertRaises(__SCREAMING_SNAKE_CASE ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 2) , ['''a''', '''b''', '''c'''] ) # Out features and out indices should be in order with self.assertRaises(__SCREAMING_SNAKE_CASE ): verify_out_features_out_indices(['''b''', '''a'''] , (0, 1) , ['''a''', '''b'''] ) # Check passes with valid inputs verify_out_features_out_indices(['''a''', '''b''', '''d'''] , (0, 1, -1) , ['''a''', '''b''', '''c''', '''d'''] ) def _lowercase ( self ): '''simple docstring''' UpperCAmelCase = BackboneMixin() UpperCAmelCase = ['''a''', '''b''', '''c'''] UpperCAmelCase = ['''a''', '''c'''] UpperCAmelCase = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly UpperCAmelCase = ['''a''', '''b'''] self.assertEqual(backbone.out_features , ['''a''', '''b'''] ) self.assertEqual(backbone.out_indices , [0, 1] ) UpperCAmelCase = [-3, -1] self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [-3, -1] )
273
'''simple docstring''' from itertools import count def a__ ( a__ = 50 ): """simple docstring""" __SCREAMING_SNAKE_CASE = [1] * min_block_length for n in count(a__ ): fill_count_functions.append(1 ) for block_length in range(a__ , n + 1 ): for block_start in range(n - block_length ): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_00_00_00: break return n if __name__ == "__main__": print(f"""{solution() = }""")
267
0
import math from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase = logging.get_logger(__name__) lowercase = { 'facebook/data2vec-base-960h': 'https://huggingface.co/facebook/data2vec-audio-base-960h/resolve/main/config.json', # See all Data2VecAudio models at https://huggingface.co/models?filter=data2vec-audio } class UpperCamelCase_ ( snake_case_ ): '''simple docstring''' lowerCAmelCase = '''data2vec-audio''' def __init__( self , a=32 , a=7_68 , a=12 , a=12 , a=30_72 , a="gelu" , a=0.1 , a=0.1 , a=0.1 , a=0.0 , a=0.1 , a=0.1 , a=0.02 , a=1E-5 , a="gelu" , a=(5_12, 5_12, 5_12, 5_12, 5_12, 5_12, 5_12) , a=(5, 2, 2, 2, 2, 2, 2) , a=(10, 3, 3, 3, 3, 2, 2) , a=False , a=16 , a=19 , a=5 , a=0.05 , a=10 , a=2 , a=0.0 , a=10 , a=0 , a="sum" , a=False , a=False , a=2_56 , a=(5_12, 5_12, 5_12, 5_12, 15_00) , a=(5, 3, 3, 1, 1) , a=(1, 2, 3, 1, 1) , a=5_12 , a=0 , a=1 , a=2 , a=False , a=3 , a=2 , a=3 , a=None , **a , ) -> str: super().__init__(**__SCREAMING_SNAKE_CASE , pad_token_id=__SCREAMING_SNAKE_CASE , bos_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE ) snake_case_ = hidden_size snake_case_ = feat_extract_activation snake_case_ = list(__SCREAMING_SNAKE_CASE ) snake_case_ = list(__SCREAMING_SNAKE_CASE ) snake_case_ = list(__SCREAMING_SNAKE_CASE ) snake_case_ = conv_bias snake_case_ = num_conv_pos_embeddings snake_case_ = num_conv_pos_embedding_groups snake_case_ = conv_pos_kernel_size snake_case_ = len(self.conv_dim ) snake_case_ = num_hidden_layers snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = num_attention_heads snake_case_ = hidden_dropout snake_case_ = attention_dropout snake_case_ = activation_dropout snake_case_ = feat_proj_dropout snake_case_ = final_dropout snake_case_ = layerdrop snake_case_ = layer_norm_eps snake_case_ = initializer_range snake_case_ = vocab_size snake_case_ = 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 snake_case_ = mask_time_prob snake_case_ = mask_time_length snake_case_ = mask_time_min_masks snake_case_ = mask_feature_prob snake_case_ = mask_feature_length snake_case_ = mask_feature_min_masks # ctc loss snake_case_ = ctc_loss_reduction snake_case_ = ctc_zero_infinity # adapter snake_case_ = add_adapter snake_case_ = adapter_kernel_size snake_case_ = adapter_stride snake_case_ = num_adapter_layers snake_case_ = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. snake_case_ = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. snake_case_ = list(__SCREAMING_SNAKE_CASE ) snake_case_ = list(__SCREAMING_SNAKE_CASE ) snake_case_ = list(__SCREAMING_SNAKE_CASE ) snake_case_ = xvector_output_dim @property def _UpperCamelCase ( self ) -> Any: return math.prod(self.conv_stride )
178
'''simple docstring''' import logging import os import threading import time try: import warnings except ImportError: UpperCAmelCase : Optional[Any] = None try: import msvcrt except ImportError: UpperCAmelCase : List[Any] = None try: import fcntl except ImportError: UpperCAmelCase : int = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: UpperCAmelCase : Union[str, Any] = OSError # Data # ------------------------------------------------ UpperCAmelCase : List[Any] = [ 'Timeout', 'BaseFileLock', 'WindowsFileLock', 'UnixFileLock', 'SoftFileLock', 'FileLock', ] UpperCAmelCase : Tuple = '3.0.12' UpperCAmelCase : str = None def a__ ( ): """simple docstring""" global _logger __SCREAMING_SNAKE_CASE = _logger or logging.getLogger(__name__ ) return _logger class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock_file return None def __str__( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = f'The file lock \'{self.lock_file}\' could not be acquired.' return temp class lowerCAmelCase__ : """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock return None def __enter__( self : List[str] ) -> List[Any]: """simple docstring""" return self.lock def __exit__( self : Tuple , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[str]: """simple docstring""" self.lock.release() return None class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = max_filename_length if max_filename_length is not None else 255 # Hash the filename if it's too long __SCREAMING_SNAKE_CASE = self.hash_filename_if_too_long(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # The path to the lock file. __SCREAMING_SNAKE_CASE = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. __SCREAMING_SNAKE_CASE = None # The default timeout value. __SCREAMING_SNAKE_CASE = timeout # We use this lock primarily for the lock counter. __SCREAMING_SNAKE_CASE = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. __SCREAMING_SNAKE_CASE = 0 return None @property def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" return self._lock_file @property def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" return self._timeout @timeout.setter def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = float(__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" raise NotImplementedError() def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" raise NotImplementedError() @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" return self._lock_file_fd is not None def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=None , __SCREAMING_SNAKE_CASE : Optional[int]=0.05 ) -> Optional[Any]: """simple docstring""" if timeout is None: __SCREAMING_SNAKE_CASE = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file __SCREAMING_SNAKE_CASE = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(f'Attempting to acquire lock {lock_id} on {lock_filename}' ) self._acquire() if self.is_locked: logger().debug(f'Lock {lock_id} acquired on {lock_filename}' ) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(f'Timeout on acquiring lock {lock_id} on {lock_filename}' ) raise Timeout(self._lock_file ) else: logger().debug( f'Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...' ) time.sleep(__SCREAMING_SNAKE_CASE ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: __SCREAMING_SNAKE_CASE = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Dict: """simple docstring""" with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file logger().debug(f'Attempting to release lock {lock_id} on {lock_filename}' ) self._release() __SCREAMING_SNAKE_CASE = 0 logger().debug(f'Lock {lock_id} released on {lock_filename}' ) return None def __enter__( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" self.acquire() return self def __exit__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" self.release() return None def __del__( self : str ) -> Union[str, Any]: """simple docstring""" self.release(force=__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = os.path.basename(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > max_length and max_length > 0: __SCREAMING_SNAKE_CASE = os.path.dirname(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = str(hash(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = filename[: max_length - len(__SCREAMING_SNAKE_CASE ) - 8] + """...""" + hashed_filename + """.lock""" return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: return path class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Dict=-1 , __SCREAMING_SNAKE_CASE : Dict=None ) -> List[Any]: """simple docstring""" from .file_utils import relative_to_absolute_path super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """\\\\?\\""" + relative_to_absolute_path(self.lock_file ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: try: msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_UNLCK , 1 ) os.close(__SCREAMING_SNAKE_CASE ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any]=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = os.statvfs(os.path.dirname(__SCREAMING_SNAKE_CASE ) ).f_namemax super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) try: fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_UN ) os.close(__SCREAMING_SNAKE_CASE ) return None class lowerCAmelCase__ ( a ): """simple docstring""" def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : int ) -> Optional[int]: """simple docstring""" os.close(self._lock_file_fd ) __SCREAMING_SNAKE_CASE = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None UpperCAmelCase : Dict = None if msvcrt: UpperCAmelCase : Optional[int] = WindowsFileLock elif fcntl: UpperCAmelCase : Optional[Any] = UnixFileLock else: UpperCAmelCase : int = SoftFileLock if warnings is not None: warnings.warn('only soft file lock is available')
267
0
def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : int ) -> Tuple: # noqa: E741 __lowercase = len(a__ ) __lowercase = 0 __lowercase = [0] * n __lowercase = [False] * n __lowercase = [False] * n def dfs(SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : int ): if parent == root: out_edge_count += 1 __lowercase = True __lowercase = at for to in l[at]: if to == parent: pass elif not visited[to]: __lowercase = dfs(a__ , a__ , a__ , a__ ) __lowercase = min(low[at] , low[to] ) # AP found via bridge if at < low[to]: __lowercase = True # AP found via cycle if at == low[to]: __lowercase = True else: __lowercase = min(low[at] , a__ ) return out_edge_count for i in range(a__ ): if not visited[i]: __lowercase = 0 __lowercase = dfs(a__ , a__ , -1 , a__ ) __lowercase = out_edge_count > 1 for x in range(len(a__ ) ): if is_art[x] is True: print(a__ ) # Adjacency list of graph SCREAMING_SNAKE_CASE__ = { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], } compute_ap(data)
325
'''simple docstring''' import shutil import tempfile import unittest from transformers import ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, NllbTokenizer, NllbTokenizerFast, is_torch_available, ) from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right UpperCAmelCase : Optional[int] = 2_5_6_0_4_7 UpperCAmelCase : Union[str, Any] = 2_5_6_1_4_5 @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = NllbTokenizer lowerCAmelCase__ = NllbTokenizerFast lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = {} def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__SCREAMING_SNAKE_CASE , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-nllb""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) __SCREAMING_SNAKE_CASE = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=True __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=False __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : List[Any] ) -> Any: """simple docstring""" if not self.test_seqaseq: return __SCREAMING_SNAKE_CASE = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Longer text that will definitely require truncation. __SCREAMING_SNAKE_CASE = [ """ UN Chief Says There Is No Military Solution in Syria""", """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for""" """ Syria is that 'there is no military solution' to the nearly five-year conflict and more weapons""" """ will only worsen the violence and misery for millions of people.""", ] __SCREAMING_SNAKE_CASE = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", """Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al""" """ Rusiei pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi""" """ că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""", ] try: __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" , ) except NotImplementedError: return self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 10 ) # max_target_length will default to max_length if not specified __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( __SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 3 ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" ) self.assertEqual(batch_encoder_only.input_ids.shape[1] , 3 ) self.assertEqual(batch_encoder_only.attention_mask.shape[1] , 3 ) self.assertNotIn("""decoder_input_ids""" , __SCREAMING_SNAKE_CASE ) @unittest.skip("""Unfortunately way too slow to build a BPE with SentencePiece.""" ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" pass def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = [AddedToken("""<special>""" , lstrip=__SCREAMING_SNAKE_CASE )] __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""<special>""" , add_special_tokens=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(special_token_id in r_output ) if self.test_slow_tokenizer: __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_cr.encode("""Hey this is a <special> token""" ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertTrue(special_token_id in p_output ) self.assertTrue(special_token_id in cr_output ) @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = "facebook/nllb-200-distilled-600M" lowerCAmelCase__ = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] lowerCAmelCase__ = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] lowerCAmelCase__ = [ 256047, 16297, 134408, 8165, 248066, 14734, 950, 1135, 105721, 3573, 83, 27352, 108, 49486, 2, ] @classmethod def UpperCAmelCase__ ( cls : List[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" ) __SCREAMING_SNAKE_CASE = 1 return cls def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[str]: """simple docstring""" self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Arab"""] , 256_001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Latn"""] , 256_002 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""fra_Latn"""] , 256_057 ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" self.assertIn(__SCREAMING_SNAKE_CASE , self.tokenizer.all_special_ids ) # fmt: off __SCREAMING_SNAKE_CASE = [RO_CODE, 4_254, 98_068, 112_923, 39_072, 3_909, 713, 102_767, 26, 17_314, 35_642, 14_683, 33_118, 2_022, 66_987, 2, 256_047] # fmt: on __SCREAMING_SNAKE_CASE = self.tokenizer.decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertNotIn(self.tokenizer.eos_token , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = ["""this is gunna be a long sentence """ * 20] assert isinstance(src_text[0] , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = 10 __SCREAMING_SNAKE_CASE = self.tokenizer(__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ).input_ids[0] self.assertEqual(ids[-1] , 2 ) self.assertEqual(ids[0] , __SCREAMING_SNAKE_CASE ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> List[Any]: """simple docstring""" self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [256_203, 3] ) def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) __SCREAMING_SNAKE_CASE = shift_tokens_right( batch["""labels"""] , self.tokenizer.pad_token_id , self.tokenizer.lang_code_to_id["""ron_Latn"""] ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual((2, 15) , batch.input_ids.shape ) self.assertEqual((2, 15) , batch.attention_mask.shape ) __SCREAMING_SNAKE_CASE = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , batch.decoder_input_ids[0, 0] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = self.tokenizer( text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=10 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = targets["""input_ids"""] __SCREAMING_SNAKE_CASE = shift_tokens_right( __SCREAMING_SNAKE_CASE , self.tokenizer.pad_token_id , decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] , ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , { # A, test, EOS, en_XX """input_ids""": [[256_047, 70, 7_356, 2]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 256_057, } , ) @require_torch def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2, 256_047] ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [256_047, 16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2] )
267
0
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCamelCase :str = logging.get_logger(__name__) lowerCamelCase :Union[str, Any] = '▁' lowerCamelCase :Dict = {'vocab_file': 'sentencepiece.bpe.model'} lowerCamelCase :List[Any] = { 'vocab_file': { 'facebook/xglm-564M': 'https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model', } } lowerCamelCase :Dict = { 'facebook/xglm-564M': 2_0_4_8, } class _lowerCAmelCase ( __UpperCAmelCase ): __SCREAMING_SNAKE_CASE : Tuple = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : str = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : Dict = ['input_ids', 'attention_mask'] def __init__(self , lowercase , lowercase="<s>" , lowercase="</s>" , lowercase="</s>" , lowercase="<s>" , lowercase="<unk>" , lowercase="<pad>" , lowercase = None , **lowercase , ): A_ : Tuple = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer A_ : List[Any] = 7 A_ : int = [F'<madeupword{i}>' for i in range(self.num_madeup_words )] A_ : int = kwargs.get("""additional_special_tokens""" , [] ) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , cls_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **__SCREAMING_SNAKE_CASE , ) A_ : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__SCREAMING_SNAKE_CASE ) ) A_ : Dict = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab A_ : Optional[Any] = 1 # Mimic fairseq token-to-id alignment for the first 4 token A_ : Tuple = {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3} A_ : Optional[int] = len(self.sp_model ) A_ : Dict = {F'<madeupword{i}>': sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words )} self.fairseq_tokens_to_ids.update(__SCREAMING_SNAKE_CASE ) A_ : Union[str, Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__(self ): A_ : Tuple = self.__dict__.copy() A_ : int = None A_ : Any = self.sp_model.serialized_model_proto() return state def __setstate__(self , lowercase ): A_ : List[str] = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): A_ : Union[str, Any] = {} A_ : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def _a (self , lowercase , lowercase = None ): if token_ids_a is None: return [self.sep_token_id] + token_ids_a A_ : Optional[int] = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def _a (self , lowercase , lowercase = None , lowercase = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__SCREAMING_SNAKE_CASE , token_ids_a=__SCREAMING_SNAKE_CASE , already_has_special_tokens=__SCREAMING_SNAKE_CASE ) if token_ids_a is None: return [1] + ([0] * len(__SCREAMING_SNAKE_CASE )) return [1] + ([0] * len(__SCREAMING_SNAKE_CASE )) + [1, 1] + ([0] * len(__SCREAMING_SNAKE_CASE )) def _a (self , lowercase , lowercase = None ): A_ : List[str] = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a ) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a ) * [0] @property def _a (self ): return len(self.sp_model ) + self.fairseq_offset + self.num_madeup_words def _a (self ): A_ : Any = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _a (self , lowercase ): return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _a (self , lowercase ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] A_ : List[str] = self.sp_model.PieceToId(__SCREAMING_SNAKE_CASE ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _a (self , lowercase ): if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _a (self , lowercase ): A_ : str = """""".join(__SCREAMING_SNAKE_CASE ).replace(__SCREAMING_SNAKE_CASE , """ """ ).strip() return out_string def _a (self , lowercase , lowercase = None ): if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return A_ : List[str] = os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(__SCREAMING_SNAKE_CASE , """wb""" ) as fi: A_ : Optional[int] = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
206
'''simple docstring''' import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging UpperCAmelCase : str = logging.get_logger(__name__) class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "linear" lowerCAmelCase__ = "cosine" lowerCAmelCase__ = "cosine_with_restarts" lowerCAmelCase__ = "polynomial" lowerCAmelCase__ = "constant" lowerCAmelCase__ = "constant_with_warmup" lowerCAmelCase__ = "piecewise_constant" def a__ ( a__ , a__ = -1 ): """simple docstring""" return LambdaLR(a__ , lambda a__ : 1 , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1.0 , a__ ) ) return 1.0 return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = step_rules.split(""",""" ) for rule_str in rule_list[:-1]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = rule_str.split(""":""" ) __SCREAMING_SNAKE_CASE = int(a__ ) __SCREAMING_SNAKE_CASE = float(a__ ) __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = float(rule_list[-1] ) def create_rules_function(a__ , a__ ): def rule_func(a__ ) -> float: __SCREAMING_SNAKE_CASE = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(a__ ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func __SCREAMING_SNAKE_CASE = create_rules_function(a__ , a__ ) return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ , a__=-1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 0.5 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(a__ ) * 2.0 * progress )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 1 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(a__ ) * progress) % 1.0) )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__=1E-7 , a__=1.0 , a__=-1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = optimizer.defaults["""lr"""] if not (lr_init > lr_end): raise ValueError(F'lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})' ) def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: __SCREAMING_SNAKE_CASE = lr_init - lr_end __SCREAMING_SNAKE_CASE = num_training_steps - num_warmup_steps __SCREAMING_SNAKE_CASE = 1 - (current_step - num_warmup_steps) / decay_steps __SCREAMING_SNAKE_CASE = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(a__ , a__ , a__ ) UpperCAmelCase : Optional[Any] = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def a__ ( a__ , a__ , a__ = None , a__ = None , a__ = None , a__ = 1 , a__ = 1.0 , a__ = -1 , ): """simple docstring""" __SCREAMING_SNAKE_CASE = SchedulerType(a__ ) __SCREAMING_SNAKE_CASE = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(a__ , last_epoch=a__ ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(a__ , step_rules=a__ , last_epoch=a__ ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(F'{name} requires `num_warmup_steps`, please provide that argument.' ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(a__ , num_warmup_steps=a__ , last_epoch=a__ ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(F'{name} requires `num_training_steps`, please provide that argument.' ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , num_cycles=a__ , last_epoch=a__ , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , power=a__ , last_epoch=a__ , ) return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , last_epoch=a__ )
267
0
'''simple docstring''' import argparse import torch from torch import nn from transformers import SpeechaTextConfig, SpeechaTextForConditionalGeneration def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : int = [ '''encoder.version''', '''decoder.version''', '''model.encoder.version''', '''model.decoder.version''', '''decoder.output_projection.weight''', '''_float_tensor''', '''encoder.embed_positions._float_tensor''', '''decoder.embed_positions._float_tensor''', ] for k in ignore_keys: state_dict.pop(a__ , a__ ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : int = list(s_dict.keys() ) for key in keys: if "transformer_layers" in key: A : Optional[Any] = s_dict.pop(a__ ) elif "subsample" in key: A : Optional[Any] = s_dict.pop(a__ ) def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A, A : List[Any] = emb.weight.shape A : str = nn.Linear(a__ , a__ , bias=a__ ) A : Union[str, Any] = emb.weight.data return lin_layer def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A : Tuple = torch.load(a__ , map_location='''cpu''' ) A : Dict = mam_aaa['''args'''] A : List[str] = mam_aaa['''model'''] A : Optional[int] = state_dict['''decoder.output_projection.weight'''] remove_ignore_keys_(a__ ) rename_keys(a__ ) A : Any = state_dict['''decoder.embed_tokens.weight'''].shape[0] A : str = args.share_decoder_input_output_embed A : List[str] = [int(a__ ) for i in args.conv_kernel_sizes.split(''',''' )] A : Union[str, Any] = SpeechaTextConfig( vocab_size=a__ , max_source_positions=args.max_source_positions , max_target_positions=args.max_target_positions , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='''relu''' , num_conv_layers=len(a__ ) , conv_channels=args.conv_channels , conv_kernel_sizes=a__ , input_feat_per_channel=args.input_feat_per_channel , input_channels=args.input_channels , tie_word_embeddings=a__ , num_beams=5 , max_length=200 , use_cache=a__ , decoder_start_token_id=2 , early_stopping=a__ , ) A : Optional[int] = SpeechaTextForConditionalGeneration(a__ ) A, A : Tuple = model.model.load_state_dict(a__ , strict=a__ ) if len(a__ ) > 0 and not set(a__ ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( '''Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,''' F' but all the following weights are missing {missing}' ) if tie_embeds: A : Tuple = make_linear_from_emb(model.model.decoder.embed_tokens ) else: A : int = lm_head_weights model.save_pretrained(a__ ) if __name__ == "__main__": lowercase : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument('--fairseq_path', type=str, help='Path to the fairseq model (.pt) file.') parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') lowercase : List[str] = parser.parse_args() convert_fairseq_sat_checkpoint_to_tfms(args.fairseq_path, args.pytorch_dump_folder_path)
3
'''simple docstring''' import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() UpperCAmelCase : Tuple = { 'bart': ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'bert': ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-base-cased-finetuned-mrpc': ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'dpr': ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'gpt2': ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlnet': ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm': ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm-roberta': ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'transfo-xl': ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'openai-gpt': ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'roberta': ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'layoutlm': ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'roberta-large-mnli': ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'camembert': ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'flaubert': ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert': ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert-base-distilled-squad': ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert': ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert-visual-feature-encoder': ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'ctrl': ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'albert': ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 't5': ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'electra': ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'wav2vec2': ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def a__ ( a__ , a__ , a__ , a__ , a__=False , a__=True ): """simple docstring""" if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) __SCREAMING_SNAKE_CASE = config_class.from_json_file(a__ ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True print(F'Building TensorFlow model from configuration: {config}' ) __SCREAMING_SNAKE_CASE = model_class(a__ ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): __SCREAMING_SNAKE_CASE = cached_file( a__ , a__ , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: __SCREAMING_SNAKE_CASE = load_pytorch_checkpoint_in_tfa_model(a__ , a__ ) if compare_with_pt_model: __SCREAMING_SNAKE_CASE = tf_model(tf_model.dummy_inputs , training=a__ ) # build the network __SCREAMING_SNAKE_CASE = torch.load(a__ , map_location="""cpu""" ) __SCREAMING_SNAKE_CASE = pt_model_class.from_pretrained( pretrained_model_name_or_path=a__ , config=a__ , state_dict=a__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = pt_model(**pt_model.dummy_inputs ) __SCREAMING_SNAKE_CASE = pto[0].numpy() __SCREAMING_SNAKE_CASE = tfo[0].numpy() __SCREAMING_SNAKE_CASE = np.amax(np.abs(np_pt - np_tf ) ) print(F'Max absolute difference between models outputs {diff}' ) assert diff <= 2E-2, F'Error, model absolute difference is >2e-2: {diff}' # Save pytorch-model print(F'Save TensorFlow model to {tf_dump_path}' ) tf_model.save_weights(a__ , save_format="""h5""" ) def a__ ( a__ , a__ , a__=None , a__=None , a__=False , a__=False , a__=False , a__=False , ): """simple docstring""" if args_model_type is None: __SCREAMING_SNAKE_CASE = list(MODEL_CLASSES.keys() ) else: __SCREAMING_SNAKE_CASE = [args_model_type] for j, model_type in enumerate(a__ , start=1 ): print("""=""" * 1_00 ) print(F' Converting model type {j}/{len(a__ )}: {model_type}' ) print("""=""" * 1_00 ) if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(a__ , a__ ) , start=1 ): print("""-""" * 1_00 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(F' Skipping finetuned checkpoint {model_shortcut_name}' ) continue __SCREAMING_SNAKE_CASE = model_shortcut_name elif only_convert_finetuned_models: print(F' Skipping not finetuned checkpoint {model_shortcut_name}' ) continue print( F' Converting checkpoint {i}/{len(a__ )}: {model_shortcut_name} - model_type {model_type}' ) print("""-""" * 1_00 ) if config_shortcut_name in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = config_shortcut_name if model_shortcut_name in aws_model_maps: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = model_shortcut_name if os.path.isfile(a__ ): __SCREAMING_SNAKE_CASE = """converted_model""" convert_pt_checkpoint_to_tf( model_type=a__ , pytorch_checkpoint_path=a__ , config_file=a__ , tf_dump_path=os.path.join(a__ , model_shortcut_name + """-tf_model.h5""" ) , compare_with_pt_model=a__ , ) if remove_cached_files: os.remove(a__ ) os.remove(a__ ) if __name__ == "__main__": UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_dump_path', default=None, type=str, required=True, help='Path to the output Tensorflow dump file.' ) parser.add_argument( '--model_type', default=None, type=str, help=( f"""Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and """ 'convert all the models from AWS.' ), ) parser.add_argument( '--pytorch_checkpoint_path', default=None, type=str, help=( 'Path to the PyTorch checkpoint path or shortcut name to download from AWS. ' 'If not given, will download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--config_file', default=None, type=str, help=( 'The config json file corresponding to the pre-trained model. \n' 'This specifies the model architecture. If not given and ' '--pytorch_checkpoint_path is not given or is a shortcut name ' 'use the configuration associated to the shortcut name on the AWS' ), ) parser.add_argument( '--compare_with_pt_model', action='store_true', help='Compare Tensorflow and PyTorch model predictions.' ) parser.add_argument( '--use_cached_models', action='store_true', help='Use cached models if possible instead of updating to latest checkpoint versions.', ) parser.add_argument( '--remove_cached_files', action='store_true', help='Remove pytorch models after conversion (save memory when converting in batches).', ) parser.add_argument('--only_convert_finetuned_models', action='store_true', help='Only convert finetuned models.') UpperCAmelCase : List[Any] = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
267
0
def __lowerCAmelCase ( a__ , a__ ) -> int: return x if y == 0 else greatest_common_divisor(a__ , x % y ) def __lowerCAmelCase ( a__ , a__ ) -> str: return (x * y) // greatest_common_divisor(a__ , a__ ) def __lowerCAmelCase ( a__ = 20 ) -> Union[str, Any]: __a = 1 for i in range(1 , n + 1 ): __a = lcm(a__ , a__ ) return g if __name__ == "__main__": print(F"{solution() = }")
6
'''simple docstring''' def a__ ( a__ ): """simple docstring""" if isinstance(a__ , a__ ): raise TypeError("""'float' object cannot be interpreted as an integer""" ) if isinstance(a__ , a__ ): raise TypeError("""'str' object cannot be interpreted as an integer""" ) if num == 0: return "0b0" __SCREAMING_SNAKE_CASE = False if num < 0: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = -num __SCREAMING_SNAKE_CASE = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(a__ ) for e in binary ) return "0b" + "".join(str(a__ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
267
0
"""simple docstring""" import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin __A = get_tests_dir("fixtures/test_sentencepiece_bpe_char.model") @require_sentencepiece @require_tokenizers class UpperCAmelCase (_UpperCAmelCase ,unittest.TestCase ): """simple docstring""" _UpperCAmelCase :Union[str, Any] = SpeechTaTokenizer _UpperCAmelCase :int = False _UpperCAmelCase :Optional[Any] = True def _snake_case ( self ): super().setUp() # We have a SentencePiece fixture for testing lowercase__: Optional[int] = SpeechTaTokenizer(__SCREAMING_SNAKE_CASE ) lowercase__: Any = AddedToken('''<mask>''' , lstrip=__SCREAMING_SNAKE_CASE , rstrip=__SCREAMING_SNAKE_CASE ) lowercase__: Optional[int] = mask_token tokenizer.add_special_tokens({'''mask_token''': mask_token} ) tokenizer.add_tokens(['''<ctc_blank>'''] ) tokenizer.save_pretrained(self.tmpdirname ) def _snake_case ( self , _UpperCAmelCase ): lowercase__: str = '''this is a test''' lowercase__: List[str] = '''this is a test''' return input_text, output_text def _snake_case ( self , _UpperCAmelCase , _UpperCAmelCase=False , _UpperCAmelCase=20 , _UpperCAmelCase=5 ): lowercase__, lowercase__: str = self.get_input_output_texts(__SCREAMING_SNAKE_CASE ) lowercase__: str = tokenizer.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) lowercase__: str = tokenizer.decode(__SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=__SCREAMING_SNAKE_CASE ) return text, ids def _snake_case ( self ): lowercase__: Any = '''<pad>''' lowercase__: Tuple = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def _snake_case ( self ): lowercase__: List[str] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-4] , '''œ''' ) self.assertEqual(vocab_keys[-2] , '''<mask>''' ) self.assertEqual(vocab_keys[-1] , '''<ctc_blank>''' ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , 81 ) def _snake_case ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def _snake_case ( self ): lowercase__: Optional[Any] = self.get_tokenizers(do_lower_case=__SCREAMING_SNAKE_CASE ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): lowercase__: List[str] = tokenizer.vocab_size lowercase__: List[str] = len(__SCREAMING_SNAKE_CASE ) self.assertNotEqual(__SCREAMING_SNAKE_CASE , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) lowercase__: Dict = ['''aaaaa bbbbbb''', '''cccccccccdddddddd'''] lowercase__: str = tokenizer.add_tokens(__SCREAMING_SNAKE_CASE ) lowercase__: List[Any] = tokenizer.vocab_size lowercase__: Optional[Any] = len(__SCREAMING_SNAKE_CASE ) self.assertNotEqual(__SCREAMING_SNAKE_CASE , 0 ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , len(__SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , all_size + len(__SCREAMING_SNAKE_CASE ) ) lowercase__: Any = tokenizer.encode('''aaaaa bbbbbb low cccccccccdddddddd l''' , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(len(__SCREAMING_SNAKE_CASE ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) lowercase__: Dict = {'''eos_token''': '''>>>>|||<||<<|<<''', '''pad_token''': '''<<<<<|||>|>>>>|>'''} lowercase__: Optional[int] = tokenizer.add_special_tokens(__SCREAMING_SNAKE_CASE ) lowercase__: Tuple = tokenizer.vocab_size lowercase__: Any = len(__SCREAMING_SNAKE_CASE ) self.assertNotEqual(__SCREAMING_SNAKE_CASE , 0 ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , len(__SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , all_size_a + len(__SCREAMING_SNAKE_CASE ) ) lowercase__: Tuple = tokenizer.encode( '''>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l''' , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(len(__SCREAMING_SNAKE_CASE ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def _snake_case ( self ): pass def _snake_case ( self ): pass def _snake_case ( self ): lowercase__: Union[str, Any] = self.get_tokenizer() lowercase__: Tuple = tokenizer.tokenize('''This is a test''' ) # fmt: off self.assertListEqual(__SCREAMING_SNAKE_CASE , [SPIECE_UNDERLINE, '''T''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''a''', SPIECE_UNDERLINE, '''t''', '''e''', '''s''', '''t'''] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) lowercase__: int = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''92000''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) lowercase__: Any = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) # fmt: off self.assertListEqual(__SCREAMING_SNAKE_CASE , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on lowercase__: List[str] = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''<unk>''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) @slow def _snake_case ( self ): lowercase__: Optional[Any] = [ '''Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides ''' '''general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural ''' '''Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained ''' '''models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.''', '''BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly ''' '''conditioning on both left and right context in all layers.''', '''The quick brown fox jumps over the lazy dog.''', ] # fmt: off lowercase__: Any = { '''input_ids''': [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=__SCREAMING_SNAKE_CASE , model_name='''microsoft/speecht5_asr''' , revision='''c5ef64c71905caeccde0e4462ef3f9077224c524''' , sequences=__SCREAMING_SNAKE_CASE , )
177
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : Optional[int] = logging.get_logger(__name__) UpperCAmelCase : str = { 'facebook/convnextv2-tiny-1k-224': 'https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json', } class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "convnextv2" def __init__( self : Any , __SCREAMING_SNAKE_CASE : int=3 , __SCREAMING_SNAKE_CASE : Dict=4 , __SCREAMING_SNAKE_CASE : List[Any]=4 , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Optional[int]="gelu" , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.02 , __SCREAMING_SNAKE_CASE : Dict=1E-12 , __SCREAMING_SNAKE_CASE : List[str]=0.0 , __SCREAMING_SNAKE_CASE : Optional[Any]=224 , __SCREAMING_SNAKE_CASE : Tuple=None , __SCREAMING_SNAKE_CASE : List[str]=None , **__SCREAMING_SNAKE_CASE : Union[str, Any] , ) -> Union[str, Any]: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_stages __SCREAMING_SNAKE_CASE = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes __SCREAMING_SNAKE_CASE = [3, 3, 9, 3] if depths is None else depths __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(self.depths ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
0
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class snake_case ( SCREAMING_SNAKE_CASE_ ,unittest.TestCase ): '''simple docstring''' snake_case_ : List[Any] = FunnelTokenizer snake_case_ : Tuple = FunnelTokenizerFast snake_case_ : List[str] = True snake_case_ : Optional[Any] = True def UpperCamelCase_ ( self : Any) -> Dict: """simple docstring""" super().setUp() _snake_case : Union[str, Any] = [ """<unk>""", """<cls>""", """<sep>""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] _snake_case : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""]) with open(self.vocab_file , """w""" , encoding="""utf-8""") as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens])) def UpperCamelCase_ ( self : List[str] , **lowerCAmelCase : Tuple) -> int: """simple docstring""" return FunnelTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self : Union[str, Any] , **lowerCAmelCase : Union[str, Any]) -> Optional[int]: """simple docstring""" return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self : Optional[Any] , lowerCAmelCase : Optional[Any]) -> Optional[int]: """simple docstring""" _snake_case : List[Any] = """UNwant\u00E9d,running""" _snake_case : int = """unwanted, running""" return input_text, output_text def UpperCamelCase_ ( self : Optional[Any]) -> Union[str, Any]: """simple docstring""" _snake_case : Tuple = self.tokenizer_class(self.vocab_file) _snake_case : Union[str, Any] = tokenizer.tokenize("""UNwant\u00E9d,running""") self.assertListEqual(__SCREAMING_SNAKE_CASE , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""]) self.assertListEqual(tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE) , [7, 4, 5, 10, 8, 9]) def UpperCamelCase_ ( self : str) -> Tuple: """simple docstring""" _snake_case : Tuple = self.get_tokenizers(do_lower_case=__SCREAMING_SNAKE_CASE) for tokenizer in tokenizers: _snake_case : List[str] = tokenizer("""UNwant\u00E9d,running""") _snake_case : Optional[int] = len(inputs["""input_ids"""]) - 1 self.assertListEqual(inputs["""token_type_ids"""] , [2] + [0] * sentence_len) _snake_case : str = tokenizer("""UNwant\u00E9d,running""" , """UNwant\u00E9d,running""") self.assertListEqual(inputs["""token_type_ids"""] , [2] + [0] * sentence_len + [1] * sentence_len)
317
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : List[str] = logging.get_logger(__name__) class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "maskformer-swin" lowerCAmelCase__ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : str , __SCREAMING_SNAKE_CASE : Tuple=224 , __SCREAMING_SNAKE_CASE : str=4 , __SCREAMING_SNAKE_CASE : Union[str, Any]=3 , __SCREAMING_SNAKE_CASE : Optional[Any]=96 , __SCREAMING_SNAKE_CASE : Optional[Any]=[2, 2, 6, 2] , __SCREAMING_SNAKE_CASE : Any=[3, 6, 12, 24] , __SCREAMING_SNAKE_CASE : Dict=7 , __SCREAMING_SNAKE_CASE : Dict=4.0 , __SCREAMING_SNAKE_CASE : Dict=True , __SCREAMING_SNAKE_CASE : str=0.0 , __SCREAMING_SNAKE_CASE : int=0.0 , __SCREAMING_SNAKE_CASE : str=0.1 , __SCREAMING_SNAKE_CASE : List[Any]="gelu" , __SCREAMING_SNAKE_CASE : str=False , __SCREAMING_SNAKE_CASE : Optional[int]=0.02 , __SCREAMING_SNAKE_CASE : Optional[int]=1E-5 , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Dict=None , **__SCREAMING_SNAKE_CASE : Tuple , ) -> Tuple: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = embed_dim __SCREAMING_SNAKE_CASE = depths __SCREAMING_SNAKE_CASE = len(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_heads __SCREAMING_SNAKE_CASE = window_size __SCREAMING_SNAKE_CASE = mlp_ratio __SCREAMING_SNAKE_CASE = qkv_bias __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = use_absolute_embeddings __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __SCREAMING_SNAKE_CASE = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) ) __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
0
"""simple docstring""" import logging from dataclasses import dataclass, field from pathlib import Path from typing import Optional, Union from .generation.configuration_utils import GenerationConfig from .training_args import TrainingArguments from .utils import add_start_docstrings lowerCAmelCase_ = logging.getLogger(__name__) @dataclass @add_start_docstrings(TrainingArguments.__doc__ ) class __A ( A_ ): '''simple docstring''' lowerCAmelCase : Optional[Any] = field(default=A_ ,metadata={"help": "Whether to use SortishSampler or not."} ) lowerCAmelCase : Tuple = field( default=A_ ,metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) lowerCAmelCase : int = field( default=A_ ,metadata={ "help": ( "The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default " "to the `max_length` value of the model configuration." ) } ,) lowerCAmelCase : List[Any] = field( default=A_ ,metadata={ "help": ( "The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default " "to the `num_beams` value of the model configuration." ) } ,) lowerCAmelCase : Union[str, Any] = field( default=A_ ,metadata={ "help": "Model id, file path or url pointing to a GenerationConfig json file, to use during prediction." } ,) def UpperCAmelCase ( self : int ) -> List[Any]: """simple docstring""" lowercase__ : Union[str, Any] = super().to_dict() for k, v in d.items(): if isinstance(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ): lowercase__ : Optional[Any] = v.to_dict() return d
16
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = n __SCREAMING_SNAKE_CASE = [None] * self.n __SCREAMING_SNAKE_CASE = 0 # index of the first element __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 def __len__( self : Tuple ) -> int: """simple docstring""" return self.size def UpperCAmelCase__ ( self : Optional[Any] ) -> bool: """simple docstring""" return self.size == 0 def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" return False if self.is_empty() else self.array[self.front] def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Dict: """simple docstring""" if self.size >= self.n: raise Exception("""QUEUE IS FULL""" ) __SCREAMING_SNAKE_CASE = data __SCREAMING_SNAKE_CASE = (self.rear + 1) % self.n self.size += 1 return self def UpperCAmelCase__ ( self : List[str] ) -> Optional[Any]: """simple docstring""" if self.size == 0: raise Exception("""UNDERFLOW""" ) __SCREAMING_SNAKE_CASE = self.array[self.front] __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = (self.front + 1) % self.n self.size -= 1 return temp
267
0
def UpperCAmelCase__ ( lowerCamelCase ): lowercase :Tuple = len(a__ ) for i in range(a__ ): for j in range(i + 1, a__ ): if numbers[j] < numbers[i]: lowercase , lowercase :Optional[Any] = numbers[j], numbers[i] return numbers if __name__ == "__main__": _UpperCAmelCase : Union[str, Any] = input("Enter numbers separated by a comma:\n").strip() _UpperCAmelCase : int = [int(item) for item in user_input.split(",")] print(exchange_sort(unsorted))
236
'''simple docstring''' import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @property def UpperCAmelCase__ ( self : List[str] ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("""DownBlock2D""", """AttnDownBlock2D""") , up_block_types=("""AttnUpBlock2D""", """UpBlock2D""") , ) return model def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.dummy_uncond_unet __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" , return_dict=__SCREAMING_SNAKE_CASE )[0] __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """google/ddpm-cifar10-32""" __SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array([0.1564, 0.14645, 0.1406, 0.14715, 0.12425, 0.14045, 0.13115, 0.12175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
267
0
'''simple docstring''' from ....configuration_utils import PretrainedConfig from ....utils import logging a__ : Optional[Any] = logging.get_logger(__name__) # TODO: upload to AWS a__ : Optional[Any] = { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/config.json' ), } class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = '''retribert''' def __init__( self , lowercase=3_0_5_2_2 , lowercase=7_6_8 , lowercase=8 , lowercase=1_2 , lowercase=3_0_7_2 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=5_1_2 , lowercase=2 , lowercase=0.02 , lowercase=1E-12 , lowercase=True , lowercase=1_2_8 , lowercase=0 , **lowercase , ) -> Any: super().__init__(pad_token_id=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __UpperCamelCase = vocab_size __UpperCamelCase = hidden_size __UpperCamelCase = num_hidden_layers __UpperCamelCase = num_attention_heads __UpperCamelCase = hidden_act __UpperCamelCase = intermediate_size __UpperCamelCase = hidden_dropout_prob __UpperCamelCase = attention_probs_dropout_prob __UpperCamelCase = max_position_embeddings __UpperCamelCase = type_vocab_size __UpperCamelCase = initializer_range __UpperCamelCase = layer_norm_eps __UpperCamelCase = share_encoders __UpperCamelCase = projection_dim
349
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : """simple docstring""" @staticmethod def UpperCAmelCase__ ( *__SCREAMING_SNAKE_CASE : Tuple , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: """simple docstring""" pass @is_pipeline_test @require_vision @require_timm @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = MODEL_FOR_OBJECT_DETECTION_MAPPING def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Tuple ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = object_detector("""./tests/fixtures/tests_samples/COCO/000000039769.png""" , threshold=0.0 ) self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) import datasets __SCREAMING_SNAKE_CASE = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) __SCREAMING_SNAKE_CASE = [ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ] __SCREAMING_SNAKE_CASE = object_detector(__SCREAMING_SNAKE_CASE , threshold=0.0 ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(__SCREAMING_SNAKE_CASE ) ) for outputs in batch_outputs: self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) @require_tf @unittest.skip("""Object detection not implemented in TF""" ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" pass @require_torch def UpperCAmelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """hf-internal-testing/tiny-detr-mobilenetsv3""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=0.0 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Dict ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = 0.9985 __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=__SCREAMING_SNAKE_CASE ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) @require_torch @require_pytesseract @slow def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """Narsil/layoutlmv3-finetuned-funsd""" __SCREAMING_SNAKE_CASE = 0.9993 __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE , threshold=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector( """https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, ] , )
267
0
from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
273
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = FlaxAutoencoderKL @property def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (32, 32) __SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0 ) __SCREAMING_SNAKE_CASE = jax.random.uniform(__SCREAMING_SNAKE_CASE , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 4, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict
267
0
from typing import List, Optional, Union import numpy as np import tensorflow as tf from .utils import logging lowercase = logging.get_logger(__name__) def __UpperCAmelCase ( a_): if isinstance(a__ , np.ndarray): return list(tensor.shape) snake_case_ = tf.shape(a__) if tensor.shape == tf.TensorShape(a__): return dynamic snake_case_ = tensor.shape.as_list() return [dynamic[i] if s is None else s for i, s in enumerate(a__)] def __UpperCAmelCase ( a_ , a_ = None , a_ = None): return tf.nn.softmax(logits=logits + 1E-9 , axis=a__ , name=a__) def __UpperCAmelCase ( a_ , a_ , a_ , a_=1E-5 , a_=-1): if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(a__ , a__): raise NotImplementedError('Only 1D weight and bias tensors are supported for now, with only a single axis.') # Get mean and variance on the axis to be normalized snake_case_ , snake_case_ = tf.nn.moments(a__ , axes=[axis] , keepdims=a__) if axis != -1: # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions # on every dimension except axis snake_case_ = [1] * inputs.shape.rank snake_case_ = shape_list(a__)[axis] snake_case_ = tf.reshape(a__ , a__) snake_case_ = tf.reshape(a__ , a__) # Compute layer normalization using the batch_normalization # function. snake_case_ = tf.nn.batch_normalization( a__ , a__ , a__ , offset=a__ , scale=a__ , variance_epsilon=a__ , ) return outputs def __UpperCAmelCase ( a_ , a_=0 , a_=-1): if end_dim < 0: end_dim += input.shape.rank if start_dim < 0: start_dim += input.shape.rank if start_dim == end_dim: return input snake_case_ = tf.shape(a__) snake_case_ = tf.math.reduce_prod(in_shape[start_dim : end_dim + 1]) snake_case_ = tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]] , axis=0) return tf.reshape(a__ , a__) def __UpperCAmelCase ( a_): if not isinstance(a__ , tf.Tensor): snake_case_ = tf.convert_to_tensor(a__) # Catches stray NumPy inputs if encoder_attention_mask.shape.rank == 3: snake_case_ = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.shape.rank == 2: snake_case_ = encoder_attention_mask[:, None, None, :] # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow # /transformer/transformer_layers.py#L270 # encoder_extended_attention_mask = (encoder_extended_attention_mask == # encoder_extended_attention_mask.transpose(-1, -2)) snake_case_ = ( tf.cast(1 , encoder_attention_mask.dtype) - encoder_extended_attention_mask ) * encoder_extended_attention_mask.dtype.min return encoder_extended_attention_mask def __UpperCAmelCase ( a_ , a_ , a_ = "input_ids"): tf.debugging.assert_less( a__ , tf.cast(a__ , dtype=tensor.dtype) , message=( f'''The maximum value of {tensor_name} ({tf.math.reduce_max(a__)}) must be smaller than the embedding ''' f'''layer\'s input dimension ({embed_dim}). The likely cause is some problem at tokenization time.''' ) , ) def __UpperCAmelCase ( a_ , a_ , a_): snake_case_ = 6_45_12 # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT` # because in that case even chunking the array would not make the saving # possible. snake_case_ = [x for x in data if len(a__) > HDF5_OBJECT_HEADER_LIMIT] # Expecting this to never be true. if bad_attributes: raise RuntimeError( 'The following attributes cannot be saved to HDF5 file because ' f'''they are larger than {HDF5_OBJECT_HEADER_LIMIT} ''' f'''bytes: {bad_attributes}''') snake_case_ = np.asarray(a__) snake_case_ = 1 snake_case_ = np.array_split(a__ , a__) # This will never loop forever thanks to the test above. while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data): num_chunks += 1 snake_case_ = np.array_split(a__ , a__) if num_chunks > 1: for chunk_id, chunk_data in enumerate(a__): snake_case_ = chunk_data else: snake_case_ = data def __UpperCAmelCase ( a_ , a_): if name in group.attrs: snake_case_ = [n.decode('utf8') if hasattr(a__ , 'decode') else n for n in group.attrs[name]] else: snake_case_ = [] snake_case_ = 0 while "%s%d" % (name, chunk_id) in group.attrs: data.extend( [n.decode('utf8') if hasattr(a__ , 'decode') else n for n in group.attrs['%s%d' % (name, chunk_id)]]) chunk_id += 1 return data def __UpperCAmelCase ( a_): def _expand_single_ad_tensor(a_): if isinstance(a__ , tf.Tensor) and t.shape.rank == 1: return tf.expand_dims(a__ , axis=-1) return t return tf.nest.map_structure(_expand_single_ad_tensor , a__)
178
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch UpperCAmelCase : int = random.Random() def a__ ( a__ , a__=1.0 , a__=None , a__=None ): """simple docstring""" if rng is None: __SCREAMING_SNAKE_CASE = global_rng __SCREAMING_SNAKE_CASE = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : str=7 , __SCREAMING_SNAKE_CASE : List[str]=400 , __SCREAMING_SNAKE_CASE : Any=2_000 , __SCREAMING_SNAKE_CASE : List[str]=10 , __SCREAMING_SNAKE_CASE : Optional[int]=160 , __SCREAMING_SNAKE_CASE : List[str]=8 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.0 , __SCREAMING_SNAKE_CASE : Dict=4_000 , __SCREAMING_SNAKE_CASE : Optional[int]=False , __SCREAMING_SNAKE_CASE : List[Any]=True , ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = min_seq_length __SCREAMING_SNAKE_CASE = max_seq_length __SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = return_attention_mask __SCREAMING_SNAKE_CASE = do_normalize __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = chunk_length __SCREAMING_SNAKE_CASE = hop_length def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring""" return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Union[str, Any]: """simple docstring""" def _flatten(__SCREAMING_SNAKE_CASE : Dict ): return list(itertools.chain(*__SCREAMING_SNAKE_CASE ) ) if equal_length: __SCREAMING_SNAKE_CASE = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size __SCREAMING_SNAKE_CASE = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = WhisperFeatureExtractor if is_speech_available() else None def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = WhisperFeatureExtractionTester(self ) def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = os.path.join(__SCREAMING_SNAKE_CASE , """feat_extract.json""" ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] # Test feature size __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , padding="""max_length""" , return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input __SCREAMING_SNAKE_CASE = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test batched __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in (800, 800, 800)] __SCREAMING_SNAKE_CASE = np.asarray(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test truncation required __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] __SCREAMING_SNAKE_CASE = [x[: feature_extractor.n_samples] for x in speech_inputs] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs_truncated] __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" import torch __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = np.random.rand(100 , 32 ).astype(np.floataa ) __SCREAMING_SNAKE_CASE = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Tuple ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech __SCREAMING_SNAKE_CASE = ds.sort("""id""" ).select(range(__SCREAMING_SNAKE_CASE ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def UpperCAmelCase__ ( self : Tuple ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on __SCREAMING_SNAKE_CASE = self._load_datasamples(1 ) __SCREAMING_SNAKE_CASE = WhisperFeatureExtractor() __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).input_features self.assertEqual(input_features.shape , (1, 80, 3_000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) ) def UpperCAmelCase__ ( self : List[Any] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = self._load_datasamples(1 )[0] __SCREAMING_SNAKE_CASE = ((audio - audio.min()) / (audio.max() - audio.min())) * 65_535 # Rescale to [0, 65535] to show issue __SCREAMING_SNAKE_CASE = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(np.all(np.mean(__SCREAMING_SNAKE_CASE ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(__SCREAMING_SNAKE_CASE ) - 1 ) < 1E-3 ) )
267
0
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class A__ ( lowerCAmelCase__ ): lowerCAmelCase__ : Any = ["image_processor", "tokenizer"] lowerCAmelCase__ : int = "CLIPImageProcessor" lowerCAmelCase__ : Tuple = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast") def __init__( self : str , _UpperCAmelCase : int=None , _UpperCAmelCase : List[Any]=None , **_UpperCAmelCase : Optional[int] ) -> List[str]: """simple docstring""" __lowercase = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , __SCREAMING_SNAKE_CASE , ) __lowercase = kwargs.pop('feature_extractor' ) __lowercase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __call__( self : List[str] , _UpperCAmelCase : int=None , _UpperCAmelCase : str=None , _UpperCAmelCase : List[Any]=None , **_UpperCAmelCase : List[Any] ) -> str: """simple docstring""" if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: __lowercase = self.tokenizer(__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if images is not None: __lowercase = self.image_processor(__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if text is not None and images is not None: __lowercase = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__SCREAMING_SNAKE_CASE ) , tensor_type=__SCREAMING_SNAKE_CASE ) def a__ ( self : List[str] , *_UpperCAmelCase : Dict , **_UpperCAmelCase : int ) -> Optional[Any]: """simple docstring""" return self.tokenizer.batch_decode(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def a__ ( self : int , *_UpperCAmelCase : Optional[Any] , **_UpperCAmelCase : Any ) -> Union[str, Any]: """simple docstring""" return self.tokenizer.decode(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) @property def a__ ( self : Union[str, Any] ) -> str: """simple docstring""" __lowercase = self.tokenizer.model_input_names __lowercase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
325
'''simple docstring''' from __future__ import annotations def a__ ( a__ , a__ , a__ ): """simple docstring""" if len(a__ ) == 0: raise ValueError("""find_max() arg is an empty sequence""" ) if ( left >= len(a__ ) or left < -len(a__ ) or right >= len(a__ ) or right < -len(a__ ) ): raise IndexError("""list index out of range""" ) if left == right: return nums[left] __SCREAMING_SNAKE_CASE = (left + right) >> 1 # the middle __SCREAMING_SNAKE_CASE = find_max(a__ , a__ , a__ ) # find max in range[left, mid] __SCREAMING_SNAKE_CASE = find_max(a__ , mid + 1 , a__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
267
0
'''simple docstring''' from argparse import ArgumentParser from .env import EnvironmentCommand def a ( ): '''simple docstring''' A_ : Optional[Any] = ArgumentParser("""Diffusers CLI tool""" , usage="""diffusers-cli <command> [<args>]""" ) A_ : Any = parser.add_subparsers(help="""diffusers-cli command helpers""" ) # Register commands EnvironmentCommand.register_subcommand(a__ ) # Let's go A_ : str = parser.parse_args() if not hasattr(a__ , """func""" ): parser.print_help() exit(1 ) # Run A_ : str = args.func(a__ ) service.run() if __name__ == "__main__": main()
206
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) # Initialize Result __SCREAMING_SNAKE_CASE = [] # Traverse through all denomination for denomination in reversed(a__ ): # Find denominations while int(a__ ) >= int(a__ ): total_value -= int(a__ ) answer.append(a__ ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase : Dict = [] UpperCAmelCase : List[str] = '0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): UpperCAmelCase : List[str] = int(input('Enter the number of denominations you want to add: ').strip()) for i in range(0, n): denominations.append(int(input(f"""Denomination {i}: """).strip())) UpperCAmelCase : str = input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter UpperCAmelCase : int = [1, 2, 5, 1_0, 2_0, 5_0, 1_0_0, 5_0_0, 2_0_0_0] UpperCAmelCase : Any = input('Enter the change you want to make: ').strip() if int(value) == 0 or int(value) < 0: print('The total value cannot be zero or negative.') else: print(f"""Following is minimal change for {value}: """) UpperCAmelCase : Any = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
267
0
'''simple docstring''' import os import unittest from transformers import LxmertTokenizer, LxmertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class A ( __snake_case , unittest.TestCase ): __magic_name__ = LxmertTokenizer __magic_name__ = LxmertTokenizerFast __magic_name__ = True __magic_name__ = True def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" super().setUp() A : Optional[int] = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] A : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" A : List[Any] = '''UNwant\u00E9d,running''' A : Any = '''unwanted, running''' return input_text, output_text def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : List[Any] = self.tokenizer_class(self.vocab_file ) A : Tuple = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(__SCREAMING_SNAKE_CASE , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [7, 4, 5, 10, 8, 9] ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" if not self.test_rust_tokenizer: return A : List[Any] = self.get_tokenizer() A : Union[str, Any] = self.get_rust_tokenizer() A : List[str] = '''I was born in 92000, and this is falsé.''' A : Optional[Any] = tokenizer.tokenize(__SCREAMING_SNAKE_CASE ) A : Optional[Any] = rust_tokenizer.tokenize(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) A : Dict = tokenizer.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) A : str = rust_tokenizer.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) A : Any = self.get_rust_tokenizer() A : Optional[int] = tokenizer.encode(__SCREAMING_SNAKE_CASE ) A : List[Any] = rust_tokenizer.encode(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
3
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu UpperCAmelCase : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def a__ ( a__ , a__=None , a__=None , a__=None ): """simple docstring""" __SCREAMING_SNAKE_CASE = True while ask_again: __SCREAMING_SNAKE_CASE = input(a__ ) try: if default is not None and len(a__ ) == 0: return default return convert_value(a__ ) if convert_value is not None else result except Exception: if error_message is not None: print(a__ ) def a__ ( a__ , a__=[] , a__=None , a__=0 ): """simple docstring""" __SCREAMING_SNAKE_CASE = BulletMenu(a__ , a__ ) __SCREAMING_SNAKE_CASE = menu.run(default_choice=a__ ) return convert_value(a__ ) if convert_value is not None else result def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value] ) def a__ ( a__ ): """simple docstring""" return {"yes": True, "no": False}[value.lower()] class lowerCAmelCase__ ( argparse.RawDescriptionHelpFormatter ): """simple docstring""" def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = super()._format_usage(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = usage.replace("""<command> [<args>] """ , """""" ) return usage
267
0
import requests from bsa import BeautifulSoup def __lowerCAmelCase ( a__ , a__ ) -> int: __a = BeautifulSoup(requests.get(a__ , params=a__ ).content , '''html.parser''' ) __a = soup.find('''div''' , attrs={'''class''': '''gs_ri'''} ) __a = div.find('''div''' , attrs={'''class''': '''gs_fl'''} ).find_all('''a''' ) return anchors[2].get_text() if __name__ == "__main__": A : int = { 'title': ( 'Precisely geometry controlled microsupercapacitors for ultrahigh areal ' 'capacitance, volumetric capacitance, and energy density' ), 'journal': 'Chem. Mater.', 'volume': 3_0, 'pages': '3979-3990', 'year': 2_0_1_8, 'hl': 'en', } print(get_citation('https://scholar.google.com/scholar_lookup', params=params))
6
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) if n == 0: return 0 __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + naive_cut_rod_recursive(n - i , a__ ) ) return max_revue def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ ): """simple docstring""" if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , a__ , a__ ) , ) __SCREAMING_SNAKE_CASE = max_revenue return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] __SCREAMING_SNAKE_CASE = 0 for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max_rev[i] for j in range(1 , i + 1 ): __SCREAMING_SNAKE_CASE = max(a__ , prices[j - 1] + max_rev[i - j] ) __SCREAMING_SNAKE_CASE = max_revenue_i return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" if n < 0: __SCREAMING_SNAKE_CASE = F'n must be greater than or equal to 0. Got n = {n}' raise ValueError(a__ ) if n > len(a__ ): __SCREAMING_SNAKE_CASE = ( """Each integral piece of rod must have a corresponding price. """ F'Got n = {n} but length of prices = {len(a__ )}' ) raise ValueError(a__ ) def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = [6, 10, 12, 15, 20, 23] __SCREAMING_SNAKE_CASE = len(a__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __SCREAMING_SNAKE_CASE = 36 __SCREAMING_SNAKE_CASE = top_down_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = bottom_up_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = naive_cut_rod_recursive(a__ , a__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
267
0
"""simple docstring""" import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () __A = np.linspace(start=0, stop=7_5, num=7_5, endpoint=True, retstep=False) # Create two fuzzy sets by defining any membership function # (trapmf(), gbellmf(), gaussmf(), etc). __A = [0, 2_5, 5_0] __A = [2_5, 5_0, 7_5] __A = fuzz.membership.trimf(X, abca) __A = fuzz.membership.trimf(X, abca) # Compute the different operations using inbuilt functions. __A = np.ones(7_5) __A = np.zeros((7_5,)) # 1. Union = max(µA(x), µB(x)) __A = fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) __A = fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) __A = fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) __A = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] __A = young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) __A = young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] __A = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] __A = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1] # max-min composition # max-product composition # Plot each set A, set B and each operation result using plot() and subplot(). from matplotlib import pyplot as plt plt.figure() plt.subplot(4, 3, 1) plt.plot(X, young) plt.title("Young") plt.grid(True) plt.subplot(4, 3, 2) plt.plot(X, middle_aged) plt.title("Middle aged") plt.grid(True) plt.subplot(4, 3, 3) plt.plot(X, union) plt.title("union") plt.grid(True) plt.subplot(4, 3, 4) plt.plot(X, intersection) plt.title("intersection") plt.grid(True) plt.subplot(4, 3, 5) plt.plot(X, complement_a) plt.title("complement_a") plt.grid(True) plt.subplot(4, 3, 6) plt.plot(X, difference) plt.title("difference a/b") plt.grid(True) plt.subplot(4, 3, 7) plt.plot(X, alg_sum) plt.title("alg_sum") plt.grid(True) plt.subplot(4, 3, 8) plt.plot(X, alg_product) plt.title("alg_product") plt.grid(True) plt.subplot(4, 3, 9) plt.plot(X, bdd_sum) plt.title("bdd_sum") plt.grid(True) plt.subplot(4, 3, 1_0) plt.plot(X, bdd_difference) plt.title("bdd_difference") plt.grid(True) plt.subplots_adjust(hspace=0.5) plt.show()
177
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : Union[str, Any] = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ 'SEW_PRETRAINED_MODEL_ARCHIVE_LIST', 'SEWForCTC', 'SEWForSequenceClassification', 'SEWModel', 'SEWPreTrainedModel', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys UpperCAmelCase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
267
0
import argparse import collections import numpy as np import torch from flax import traverse_util from tax import checkpoints from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def lowercase ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Any: return params[F'''{prefix}/{prefix}/relpos_bias/rel_embedding'''][:, i, :] def lowercase ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str]="attention" ) -> List[str]: _snake_case : List[Any] = np.ascontiguousarray(params[F'''{prefix}/{prefix}/{layer_name}/key/kernel'''][:, i, :, :] ) _snake_case : List[str] = k_tmp.reshape(k_tmp.shape[0] , k_tmp.shape[1] * k_tmp.shape[2] ) _snake_case : List[str] = np.ascontiguousarray(params[F'''{prefix}/{prefix}/{layer_name}/out/kernel'''][:, i, :, :] ) _snake_case : Tuple = o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1] , o_tmp.shape[2] ) _snake_case : List[str] = np.ascontiguousarray(params[F'''{prefix}/{prefix}/{layer_name}/query/kernel'''][:, i, :, :] ) _snake_case : List[Any] = q_tmp.reshape(q_tmp.shape[0] , q_tmp.shape[1] * q_tmp.shape[2] ) _snake_case : int = np.ascontiguousarray(params[F'''{prefix}/{prefix}/{layer_name}/value/kernel'''][:, i, :, :] ) _snake_case : Any = v_tmp.reshape(v_tmp.shape[0] , v_tmp.shape[1] * v_tmp.shape[2] ) return k, o, q, v def lowercase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int]=False ) -> str: if split_mlp_wi: _snake_case : Tuple = params[F'''{prefix}/{prefix}/mlp/wi_0/kernel'''][:, i, :] _snake_case : List[Any] = params[F'''{prefix}/{prefix}/mlp/wi_1/kernel'''][:, i, :] _snake_case : int = (wi_a, wi_a) else: _snake_case : Optional[Any] = params[F'''{prefix}/{prefix}/mlp/wi/kernel'''][:, i, :] _snake_case : Tuple = params[F'''{prefix}/{prefix}/mlp/wo/kernel'''][:, i, :] return wi, wo def lowercase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> str: return params[F'''{prefix}/{prefix}/{layer_name}/scale'''][:, i] def lowercase ( SCREAMING_SNAKE_CASE__ : Tuple , *, SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] = False ) -> Dict: _snake_case : Dict = traverse_util.flatten_dict(variables["""target"""] ) _snake_case : Optional[Any] = {"""/""".join(a__ ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi _snake_case : Any = """encoder/encoder/mlp/wi_0/kernel""" in old print("""Split MLP:""" , a__ ) _snake_case : List[Any] = collections.OrderedDict() # Shared embeddings. _snake_case : Dict = old["""token_embedder/embedding"""] # Encoder. for i in range(a__ ): # Block i, layer 0 (Self Attention). _snake_case : List[Any] = tax_layer_norm_lookup(a__ , a__ , """encoder""" , """pre_attention_layer_norm""" ) _snake_case , _snake_case , _snake_case , _snake_case : Optional[int] = tax_attention_lookup(a__ , a__ , """encoder""" , """attention""" ) _snake_case : str = layer_norm _snake_case : List[str] = k.T _snake_case : Optional[int] = o.T _snake_case : int = q.T _snake_case : Dict = v.T # Block i, layer 1 (MLP). _snake_case : List[Any] = tax_layer_norm_lookup(a__ , a__ , """encoder""" , """pre_mlp_layer_norm""" ) _snake_case , _snake_case : List[Any] = tax_mlp_lookup(a__ , a__ , """encoder""" , a__ ) _snake_case : Optional[Any] = layer_norm if split_mlp_wi: _snake_case : Tuple = wi[0].T _snake_case : List[str] = wi[1].T else: _snake_case : Any = wi.T _snake_case : List[Any] = wo.T if scalable_attention: # convert the rel_embedding of each layer _snake_case : List[Any] = tax_relpos_bias_lookup( a__ , a__ , """encoder""" ).T _snake_case : Any = old["""encoder/encoder_norm/scale"""] if not scalable_attention: _snake_case : Optional[Any] = tax_relpos_bias_lookup( a__ , 0 , """encoder""" ).T _snake_case : str = tax_relpos_bias_lookup( a__ , 0 , """decoder""" ).T if not is_encoder_only: # Decoder. for i in range(a__ ): # Block i, layer 0 (Self Attention). _snake_case : Union[str, Any] = tax_layer_norm_lookup(a__ , a__ , """decoder""" , """pre_self_attention_layer_norm""" ) _snake_case , _snake_case , _snake_case , _snake_case : str = tax_attention_lookup(a__ , a__ , """decoder""" , """self_attention""" ) _snake_case : Union[str, Any] = layer_norm _snake_case : List[Any] = k.T _snake_case : int = o.T _snake_case : str = q.T _snake_case : Optional[int] = v.T # Block i, layer 1 (Cross Attention). _snake_case : Any = tax_layer_norm_lookup(a__ , a__ , """decoder""" , """pre_cross_attention_layer_norm""" ) _snake_case , _snake_case , _snake_case , _snake_case : Dict = tax_attention_lookup(a__ , a__ , """decoder""" , """encoder_decoder_attention""" ) _snake_case : Optional[int] = layer_norm _snake_case : Tuple = k.T _snake_case : Any = o.T _snake_case : str = q.T _snake_case : List[Any] = v.T # Block i, layer 2 (MLP). _snake_case : Optional[Any] = tax_layer_norm_lookup(a__ , a__ , """decoder""" , """pre_mlp_layer_norm""" ) _snake_case , _snake_case : Dict = tax_mlp_lookup(a__ , a__ , """decoder""" , a__ ) _snake_case : Optional[int] = layer_norm if split_mlp_wi: _snake_case : Tuple = wi[0].T _snake_case : Any = wi[1].T else: _snake_case : Tuple = wi.T _snake_case : str = wo.T if scalable_attention: # convert the rel_embedding of each layer _snake_case : int = tax_relpos_bias_lookup(a__ , a__ , """decoder""" ).T _snake_case : List[str] = old["""decoder/decoder_norm/scale"""] # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: _snake_case : Optional[Any] = old["""decoder/logits_dense/kernel"""].T return new def lowercase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple ) -> Dict: _snake_case : Tuple = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: _snake_case : Optional[Any] = state_dict["""shared.weight"""] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: _snake_case : Dict = state_dict["""shared.weight"""] if "lm_head.weight" not in state_dict: # For old 1.0 models. print("""Using shared word embeddings as lm_head.""" ) _snake_case : Any = state_dict["""shared.weight"""] return state_dict def lowercase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict ) -> Tuple: _snake_case : Optional[Any] = checkpoints.load_tax_checkpoint(a__ ) _snake_case : List[Any] = convert_tax_to_pytorch( a__ , num_layers=config.num_layers , is_encoder_only=a__ , scalable_attention=a__ ) _snake_case : int = make_state_dict(a__ , a__ ) model.load_state_dict(a__ , strict=a__ ) def lowercase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] = False , SCREAMING_SNAKE_CASE__ : Any = False , ) -> Union[str, Any]: _snake_case : Optional[int] = MTaConfig.from_json_file(a__ ) print(F'''Building PyTorch model from configuration: {config}''' ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: _snake_case : Tuple = UMTaEncoderModel(a__ ) else: _snake_case : List[str] = UMTaForConditionalGeneration(a__ ) # Load weights from tf checkpoint load_tax_weights_in_ta(a__ , a__ , a__ , a__ , a__ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(a__ ) # Verify that we can load the checkpoint. model.from_pretrained(a__ ) print("""Done""" ) if __name__ == "__main__": a__ = argparse.ArgumentParser(description="""Converts a native T5X checkpoint into a PyTorch checkpoint.""") # Required parameters parser.add_argument( """--t5x_checkpoint_path""", default=None, type=str, required=True, help="""Path to the T5X checkpoint.""" ) parser.add_argument( """--config_file""", default=None, type=str, required=True, help="""The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.""", ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--is_encoder_only""", action="""store_true""", help="""Check if the model is encoder-decoder model""", default=False ) parser.add_argument( """--scalable_attention""", action="""store_true""", help="""Whether the model uses scaled attention (umt5 model)""", default=False, ) a__ = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only, args.scalable_attention, )
317
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = name __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = weight def __repr__( self : str ) -> Union[str, Any]: """simple docstring""" return f'{self.__class__.__name__}({self.name}, {self.value}, {self.weight})' def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" return self.value def UpperCAmelCase__ ( self : Any ) -> str: """simple docstring""" return self.name def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.weight def UpperCAmelCase__ ( self : int ) -> Tuple: """simple docstring""" return self.value / self.weight def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = [] for i in range(len(a__ ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = sorted(a__ , key=a__ , reverse=a__ ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 0.0, 0.0 for i in range(len(a__ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def a__ ( ): """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
267
0
"""simple docstring""" import os # Precomputes a list of the 100 first triangular numbers lowerCAmelCase_ = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def __UpperCAmelCase ( ) -> Any: lowercase__ : Union[str, Any] = os.path.dirname(os.path.realpath(a__ ) ) lowercase__ : Tuple = os.path.join(a__ , '''words.txt''' ) lowercase__ : List[Any] = '''''' with open(a__ ) as f: lowercase__ : int = f.readline() lowercase__ : List[Any] = [word.strip('''\"''' ) for word in words.strip('''\r\n''' ).split(''',''' )] lowercase__ : List[Any] = [ word for word in [sum(ord(a__ ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(a__ ) if __name__ == "__main__": print(solution())
16
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE = ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on __SCREAMING_SNAKE_CASE = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) __SCREAMING_SNAKE_CASE = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] __SCREAMING_SNAKE_CASE = {"""unk_token""": """<unk>"""} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__SCREAMING_SNAKE_CASE ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48145466, 0.4578275, 0.40821073], """image_std""": [0.26862954, 0.26130258, 0.27577711], } __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , __SCREAMING_SNAKE_CASE ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> str: """simple docstring""" return CLIPTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple , **__SCREAMING_SNAKE_CASE : Any ) -> int: """simple docstring""" return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> List[str]: """simple docstring""" return CLIPImageProcessor.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(__SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_slow.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_fast.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) __SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = image_processor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) __SCREAMING_SNAKE_CASE = processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer(__SCREAMING_SNAKE_CASE ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase__ ( self : Dict ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(__SCREAMING_SNAKE_CASE ): processor() def UpperCAmelCase__ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE = processor.batch_decode(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
267
0
import importlib.util import os import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import ( is_accelerate_available, is_flax_available, is_safetensors_available, is_tf_available, is_torch_available, ) from . import BaseTransformersCLICommand def UpperCAmelCase__ ( lowerCamelCase ): return EnvironmentCommand() def UpperCAmelCase__ ( lowerCamelCase ): return EnvironmentCommand(args.accelerate_config_file ) class __lowerCAmelCase ( lowerCAmelCase): @staticmethod def SCREAMING_SNAKE_CASE ( _lowerCAmelCase: ArgumentParser ): lowercase :List[str] = parser.add_parser("env" ) download_parser.set_defaults(func=__SCREAMING_SNAKE_CASE ) download_parser.add_argument( "--accelerate-config_file" , default=__SCREAMING_SNAKE_CASE , help="The accelerate config file to use for the default values in the launching script." , ) download_parser.set_defaults(func=__SCREAMING_SNAKE_CASE ) def __init__( self: List[str] , _lowerCAmelCase: Tuple , *_lowerCAmelCase: int ): lowercase :List[str] = accelerate_config_file def SCREAMING_SNAKE_CASE ( self: Optional[Any] ): lowercase :Any = "not installed" if is_safetensors_available(): import safetensors lowercase :int = safetensors.__version__ elif importlib.util.find_spec("safetensors" ) is not None: import safetensors lowercase :Optional[Any] = F"{safetensors.__version__} but is ignored because of PyTorch version too old." lowercase :str = "not installed" lowercase :Tuple = "not found" if is_accelerate_available(): import accelerate from accelerate.commands.config import default_config_file, load_config_from_file lowercase :Tuple = accelerate.__version__ # Get the default from the config file. if self._accelerate_config_file is not None or os.path.isfile(__SCREAMING_SNAKE_CASE ): lowercase :List[Any] = load_config_from_file(self._accelerate_config_file ).to_dict() lowercase :Optional[int] = ( "\n".join([F"\t- {prop}: {val}" for prop, val in accelerate_config.items()] ) if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else F"\t{accelerate_config}" ) lowercase :List[str] = "not installed" lowercase :str = "NA" if is_torch_available(): import torch lowercase :Optional[int] = torch.__version__ lowercase :List[str] = torch.cuda.is_available() lowercase :Any = "not installed" lowercase :int = "NA" if is_tf_available(): import tensorflow as tf lowercase :List[Any] = tf.__version__ try: # deprecated in v2.1 lowercase :Dict = tf.test.is_gpu_available() except AttributeError: # returns list of devices, convert to bool lowercase :Dict = bool(tf.config.list_physical_devices("GPU" ) ) lowercase :Tuple = "not installed" lowercase :int = "not installed" lowercase :int = "not installed" lowercase :Any = "NA" if is_flax_available(): import flax import jax import jaxlib lowercase :Optional[Any] = flax.__version__ lowercase :str = jax.__version__ lowercase :List[Any] = jaxlib.__version__ lowercase :Tuple = jax.lib.xla_bridge.get_backend().platform lowercase :Tuple = { "`transformers` version": version, "Platform": platform.platform(), "Python version": platform.python_version(), "Huggingface_hub version": huggingface_hub.__version__, "Safetensors version": F"{safetensors_version}", "Accelerate version": F"{accelerate_version}", "Accelerate config": F"{accelerate_config_str}", "PyTorch version (GPU?)": F"{pt_version} ({pt_cuda_available})", "Tensorflow version (GPU?)": F"{tf_version} ({tf_cuda_available})", "Flax version (CPU?/GPU?/TPU?)": F"{flax_version} ({jax_backend})", "Jax version": F"{jax_version}", "JaxLib version": F"{jaxlib_version}", "Using GPU in script?": "<fill in>", "Using distributed or parallel set-up in script?": "<fill in>", } print("\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n" ) print(self.format_dict(__SCREAMING_SNAKE_CASE ) ) return info @staticmethod def SCREAMING_SNAKE_CASE ( _lowerCAmelCase: Any ): return "\n".join([F"- {prop}: {val}" for prop, val in d.items()] ) + "\n"
236
'''simple docstring''' import numpy as np def a__ ( a__ , a__ , a__ = 1E-1_2 , a__ = 1_00 , ): """simple docstring""" assert np.shape(a__ )[0] == np.shape(a__ )[1] # Ensure proper dimensionality. assert np.shape(a__ )[0] == np.shape(a__ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(a__ ) == np.iscomplexobj(a__ ) __SCREAMING_SNAKE_CASE = np.iscomplexobj(a__ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(a__ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 1E1_2 while not convergence: # Multiple matrix by the vector. __SCREAMING_SNAKE_CASE = np.dot(a__ , a__ ) # Normalize the resulting output vector. __SCREAMING_SNAKE_CASE = w / np.linalg.norm(a__ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __SCREAMING_SNAKE_CASE = vector.conj().T if is_complex else vector.T __SCREAMING_SNAKE_CASE = np.dot(a__ , np.dot(a__ , a__ ) ) # Check convergence. __SCREAMING_SNAKE_CASE = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = lambda_ if is_complex: __SCREAMING_SNAKE_CASE = np.real(lambda_ ) return lambda_, vector def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ) __SCREAMING_SNAKE_CASE = real_input_matrix.astype(np.complexaaa ) __SCREAMING_SNAKE_CASE = np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __SCREAMING_SNAKE_CASE = real_input_matrix __SCREAMING_SNAKE_CASE = real_vector elif problem_type == "complex": __SCREAMING_SNAKE_CASE = complex_input_matrix __SCREAMING_SNAKE_CASE = complex_vector # Our implementation. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = power_iteration(a__ , a__ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = np.linalg.eigh(a__ ) # Last eigenvalue is the maximum one. __SCREAMING_SNAKE_CASE = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __SCREAMING_SNAKE_CASE = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(a__ ) - np.abs(a__ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
267
0
'''simple docstring''' from __future__ import annotations def _lowercase ( __A ,__A ,__A ): '''simple docstring''' if len(a__ ) == 0: raise ValueError("""find_max() arg is an empty sequence""" ) if ( left >= len(a__ ) or left < -len(a__ ) or right >= len(a__ ) or right < -len(a__ ) ): raise IndexError("""list index out of range""" ) if left == right: return nums[left] __UpperCamelCase = (left + right) >> 1 # the middle __UpperCamelCase = find_max(a__ ,a__ ,a__ ) # find max in range[left, mid] __UpperCamelCase = find_max(a__ ,mid + 1 ,a__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
349
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( a , a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = StableDiffusionInpaintPipeline lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowerCAmelCase__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowerCAmelCase__ = frozenset([] ) def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = PNDMScheduler(skip_prk_steps=__SCREAMING_SNAKE_CASE ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) __SCREAMING_SNAKE_CASE = CLIPTextModel(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __SCREAMING_SNAKE_CASE = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any]=0 ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 )[0] __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE ) ).convert("""RGB""" ).resize((64, 64) ) __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): __SCREAMING_SNAKE_CASE = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = """cpu""" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe.to(__SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe(**__SCREAMING_SNAKE_CASE ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __SCREAMING_SNAKE_CASE = np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : List[str] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained(__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def UpperCAmelCase__ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , safety_checker=__SCREAMING_SNAKE_CASE , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def UpperCAmelCase__ ( self : Tuple ) -> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = PNDMScheduler.from_pretrained(__SCREAMING_SNAKE_CASE , subfolder="""scheduler""" ) __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
267
0
import itertools import random import unittest import numpy as np from transformers import is_speech_available from transformers.testing_utils import require_torch, require_torchaudio from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import SpeechaTextFeatureExtractor __A : Dict = random.Random() def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__=1.0 , UpperCamelCase__=None , UpperCamelCase__=None ) -> Any: '''simple docstring''' if rng is None: UpperCAmelCase = global_rng UpperCAmelCase = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class A_ (unittest.TestCase ): def __init__( self , _A , _A=7 , _A=4_0_0 , _A=2_0_0_0 , _A=2_4 , _A=2_4 , _A=0.0 , _A=1_6_0_0_0 , _A=True , _A=True , ): '''simple docstring''' UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = min_seq_length UpperCAmelCase = max_seq_length UpperCAmelCase = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) UpperCAmelCase = feature_size UpperCAmelCase = num_mel_bins UpperCAmelCase = padding_value UpperCAmelCase = sampling_rate UpperCAmelCase = return_attention_mask UpperCAmelCase = do_normalize def _lowercase ( self ): '''simple docstring''' return { "feature_size": self.feature_size, "num_mel_bins": self.num_mel_bins, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _lowercase ( self , _A=False , _A=False ): '''simple docstring''' def _flatten(_A ): return list(itertools.chain(*__SCREAMING_SNAKE_CASE ) ) if equal_length: UpperCAmelCase = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size UpperCAmelCase = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: UpperCAmelCase = [np.asarray(__SCREAMING_SNAKE_CASE ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class A_ (a_ , unittest.TestCase ): UpperCAmelCase__ = SpeechaTextFeatureExtractor if is_speech_available() else None def _lowercase ( self ): '''simple docstring''' UpperCAmelCase = SpeechaTextFeatureExtractionTester(self ) def _lowercase ( self , _A ): '''simple docstring''' self.assertTrue(np.all(np.mean(__SCREAMING_SNAKE_CASE , axis=0 ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(__SCREAMING_SNAKE_CASE , axis=0 ) - 1 ) < 1E-3 ) ) def _lowercase ( self ): '''simple docstring''' UpperCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 UpperCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] UpperCAmelCase = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] # Test feature size UpperCAmelCase = feature_extractor(__SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE , return_tensors='''np''' ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size ) # Test not batched input UpperCAmelCase = feature_extractor(speech_inputs[0] , return_tensors='''np''' ).input_features UpperCAmelCase = feature_extractor(np_speech_inputs[0] , return_tensors='''np''' ).input_features self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test batched UpperCAmelCase = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors='''np''' ).input_features UpperCAmelCase = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. UpperCAmelCase = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] UpperCAmelCase = np.asarray(__SCREAMING_SNAKE_CASE ) UpperCAmelCase = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors='''np''' ).input_features UpperCAmelCase = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) def _lowercase ( self ): '''simple docstring''' UpperCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] UpperCAmelCase = ['''longest''', '''max_length''', '''do_not_pad'''] UpperCAmelCase = [None, 1_6, None] for max_length, padding in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): UpperCAmelCase = feature_extractor( __SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , return_attention_mask=__SCREAMING_SNAKE_CASE ) UpperCAmelCase = inputs.input_features UpperCAmelCase = inputs.attention_mask UpperCAmelCase = [np.sum(__SCREAMING_SNAKE_CASE ) for x in attention_mask] self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]] ) def _lowercase ( self ): '''simple docstring''' UpperCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] UpperCAmelCase = ['''longest''', '''max_length''', '''do_not_pad'''] UpperCAmelCase = [None, 1_6, None] for max_length, padding in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): UpperCAmelCase = feature_extractor( __SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE , return_tensors='''np''' , return_attention_mask=__SCREAMING_SNAKE_CASE ) UpperCAmelCase = inputs.input_features UpperCAmelCase = inputs.attention_mask UpperCAmelCase = [np.sum(__SCREAMING_SNAKE_CASE ) for x in attention_mask] self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]] ) self.assertTrue(input_features[0][fbank_feat_lengths[0] :].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]] ) self.assertTrue(input_features[0][fbank_feat_lengths[1] :].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]] ) def _lowercase ( self ): '''simple docstring''' UpperCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] UpperCAmelCase = feature_extractor( __SCREAMING_SNAKE_CASE , padding='''max_length''' , max_length=4 , truncation=__SCREAMING_SNAKE_CASE , return_tensors='''np''' , return_attention_mask=__SCREAMING_SNAKE_CASE , ) UpperCAmelCase = inputs.input_features UpperCAmelCase = inputs.attention_mask UpperCAmelCase = np.sum(attention_mask == 1 , axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1] ) self._check_zero_mean_unit_variance(input_features[2] ) def _lowercase ( self ): '''simple docstring''' UpperCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] UpperCAmelCase = feature_extractor( __SCREAMING_SNAKE_CASE , padding='''longest''' , max_length=4 , truncation=__SCREAMING_SNAKE_CASE , return_tensors='''np''' , return_attention_mask=__SCREAMING_SNAKE_CASE , ) UpperCAmelCase = inputs.input_features UpperCAmelCase = inputs.attention_mask UpperCAmelCase = np.sum(attention_mask == 1 , axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertEqual(input_features.shape , (3, 4, 2_4) ) UpperCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] UpperCAmelCase = feature_extractor( __SCREAMING_SNAKE_CASE , padding='''longest''' , max_length=1_6 , truncation=__SCREAMING_SNAKE_CASE , return_tensors='''np''' , return_attention_mask=__SCREAMING_SNAKE_CASE , ) UpperCAmelCase = inputs.input_features UpperCAmelCase = inputs.attention_mask UpperCAmelCase = np.sum(attention_mask == 1 , axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertEqual(input_features.shape , (3, 6, 2_4) ) def _lowercase ( self ): '''simple docstring''' import torch UpperCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCAmelCase = np.random.rand(1_0_0 , 3_2 ).astype(np.floataa ) UpperCAmelCase = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: UpperCAmelCase = feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''np''' ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) UpperCAmelCase = feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''pt''' ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def _lowercase ( self , _A ): '''simple docstring''' from datasets import load_dataset UpperCAmelCase = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech UpperCAmelCase = ds.sort('''id''' ).select(range(__SCREAMING_SNAKE_CASE ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] def _lowercase ( self ): '''simple docstring''' UpperCAmelCase = np.array([ -1.57_45, -1.77_13, -1.70_20, -1.60_69, -1.22_50, -1.11_05, -0.90_72, -0.82_41, -1.23_10, -0.80_98, -0.33_20, -0.41_01, -0.79_85, -0.49_96, -0.82_13, -0.91_28, -1.04_20, -1.12_86, -1.04_40, -0.79_99, -0.84_05, -1.22_75, -1.54_43, -1.46_25, ] ) # fmt: on UpperCAmelCase = self._load_datasamples(1 ) UpperCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCAmelCase = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).input_features self.assertEquals(input_features.shape , (1, 5_8_4, 2_4) ) self.assertTrue(np.allclose(input_features[0, 0, :3_0] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) )
273
'''simple docstring''' from itertools import count def a__ ( a__ = 50 ): """simple docstring""" __SCREAMING_SNAKE_CASE = [1] * min_block_length for n in count(a__ ): fill_count_functions.append(1 ) for block_length in range(a__ , n + 1 ): for block_start in range(n - block_length ): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_00_00_00: break return n if __name__ == "__main__": print(f"""{solution() = }""")
267
0
import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, AutoConfig, AutoFeatureExtractor, WavaVecaConfig, WavaVecaFeatureExtractor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 lowercase = get_tests_dir("fixtures") lowercase = get_tests_dir("fixtures/dummy_feature_extractor_config.json") lowercase = get_tests_dir("fixtures/dummy-config.json") class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ) -> Union[str, Any]: snake_case_ = 0 def _UpperCamelCase ( self ) -> Optional[int]: snake_case_ = AutoFeatureExtractor.from_pretrained('facebook/wav2vec2-base-960h' ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _UpperCamelCase ( self ) -> Optional[Any]: snake_case_ = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _UpperCamelCase ( self ) -> Tuple: with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ = WavaVecaConfig() # remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally snake_case_ = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ).to_dict() config_dict.pop('feature_extractor_type' ) snake_case_ = WavaVecaFeatureExtractor(**__SCREAMING_SNAKE_CASE ) # save in new folder model_config.save_pretrained(__SCREAMING_SNAKE_CASE ) config.save_pretrained(__SCREAMING_SNAKE_CASE ) snake_case_ = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) # make sure private variable is not incorrectly saved snake_case_ = json.loads(config.to_json_string() ) self.assertTrue('_processor_class' not in dict_as_saved ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _UpperCamelCase ( self ) -> Any: snake_case_ = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _UpperCamelCase ( self ) -> List[Any]: with self.assertRaisesRegex( __SCREAMING_SNAKE_CASE , 'bert-base is not a local folder and is not a valid model identifier' ): snake_case_ = AutoFeatureExtractor.from_pretrained('bert-base' ) def _UpperCamelCase ( self ) -> List[Any]: with self.assertRaisesRegex( __SCREAMING_SNAKE_CASE , R'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)' ): snake_case_ = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE , revision='aaaaaa' ) def _UpperCamelCase ( self ) -> int: with self.assertRaisesRegex( __SCREAMING_SNAKE_CASE , 'hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.' , ): snake_case_ = AutoFeatureExtractor.from_pretrained('hf-internal-testing/config-no-model' ) def _UpperCamelCase ( self ) -> List[str]: with self.assertRaises(__SCREAMING_SNAKE_CASE ): snake_case_ = AutoFeatureExtractor.from_pretrained( 'hf-internal-testing/test_dynamic_feature_extractor' ) # If remote code is disabled, we can't load this config. with self.assertRaises(__SCREAMING_SNAKE_CASE ): snake_case_ = AutoFeatureExtractor.from_pretrained( 'hf-internal-testing/test_dynamic_feature_extractor' , trust_remote_code=__SCREAMING_SNAKE_CASE ) snake_case_ = AutoFeatureExtractor.from_pretrained( 'hf-internal-testing/test_dynamic_feature_extractor' , trust_remote_code=__SCREAMING_SNAKE_CASE ) self.assertEqual(feature_extractor.__class__.__name__ , 'NewFeatureExtractor' ) # Test feature extractor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained(__SCREAMING_SNAKE_CASE ) snake_case_ = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE , trust_remote_code=__SCREAMING_SNAKE_CASE ) self.assertEqual(reloaded_feature_extractor.__class__.__name__ , 'NewFeatureExtractor' ) def _UpperCamelCase ( self ) -> int: try: AutoConfig.register('custom' , __SCREAMING_SNAKE_CASE ) AutoFeatureExtractor.register(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(__SCREAMING_SNAKE_CASE ): AutoFeatureExtractor.register(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Now that the config is registered, it can be used as any other config with the auto-API snake_case_ = CustomFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained(__SCREAMING_SNAKE_CASE ) snake_case_ = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] def _UpperCamelCase ( self ) -> str: class UpperCamelCase_ ( snake_case_ ): '''simple docstring''' lowerCAmelCase = True try: AutoConfig.register('custom' , __SCREAMING_SNAKE_CASE ) AutoFeatureExtractor.register(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # If remote code is not set, the default is to use local snake_case_ = AutoFeatureExtractor.from_pretrained( 'hf-internal-testing/test_dynamic_feature_extractor' ) self.assertEqual(feature_extractor.__class__.__name__ , 'NewFeatureExtractor' ) self.assertTrue(feature_extractor.is_local ) # If remote code is disabled, we load the local one. snake_case_ = AutoFeatureExtractor.from_pretrained( 'hf-internal-testing/test_dynamic_feature_extractor' , trust_remote_code=__SCREAMING_SNAKE_CASE ) self.assertEqual(feature_extractor.__class__.__name__ , 'NewFeatureExtractor' ) self.assertTrue(feature_extractor.is_local ) # If remote is enabled, we load from the Hub snake_case_ = AutoFeatureExtractor.from_pretrained( 'hf-internal-testing/test_dynamic_feature_extractor' , trust_remote_code=__SCREAMING_SNAKE_CASE ) self.assertEqual(feature_extractor.__class__.__name__ , 'NewFeatureExtractor' ) self.assertTrue(not hasattr(__SCREAMING_SNAKE_CASE , 'is_local' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
178
'''simple docstring''' import logging import os import threading import time try: import warnings except ImportError: UpperCAmelCase : Optional[Any] = None try: import msvcrt except ImportError: UpperCAmelCase : List[Any] = None try: import fcntl except ImportError: UpperCAmelCase : int = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: UpperCAmelCase : Union[str, Any] = OSError # Data # ------------------------------------------------ UpperCAmelCase : List[Any] = [ 'Timeout', 'BaseFileLock', 'WindowsFileLock', 'UnixFileLock', 'SoftFileLock', 'FileLock', ] UpperCAmelCase : Tuple = '3.0.12' UpperCAmelCase : str = None def a__ ( ): """simple docstring""" global _logger __SCREAMING_SNAKE_CASE = _logger or logging.getLogger(__name__ ) return _logger class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock_file return None def __str__( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = f'The file lock \'{self.lock_file}\' could not be acquired.' return temp class lowerCAmelCase__ : """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock return None def __enter__( self : List[str] ) -> List[Any]: """simple docstring""" return self.lock def __exit__( self : Tuple , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[str]: """simple docstring""" self.lock.release() return None class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = max_filename_length if max_filename_length is not None else 255 # Hash the filename if it's too long __SCREAMING_SNAKE_CASE = self.hash_filename_if_too_long(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # The path to the lock file. __SCREAMING_SNAKE_CASE = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. __SCREAMING_SNAKE_CASE = None # The default timeout value. __SCREAMING_SNAKE_CASE = timeout # We use this lock primarily for the lock counter. __SCREAMING_SNAKE_CASE = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. __SCREAMING_SNAKE_CASE = 0 return None @property def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" return self._lock_file @property def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" return self._timeout @timeout.setter def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = float(__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" raise NotImplementedError() def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" raise NotImplementedError() @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" return self._lock_file_fd is not None def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=None , __SCREAMING_SNAKE_CASE : Optional[int]=0.05 ) -> Optional[Any]: """simple docstring""" if timeout is None: __SCREAMING_SNAKE_CASE = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file __SCREAMING_SNAKE_CASE = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(f'Attempting to acquire lock {lock_id} on {lock_filename}' ) self._acquire() if self.is_locked: logger().debug(f'Lock {lock_id} acquired on {lock_filename}' ) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(f'Timeout on acquiring lock {lock_id} on {lock_filename}' ) raise Timeout(self._lock_file ) else: logger().debug( f'Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...' ) time.sleep(__SCREAMING_SNAKE_CASE ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: __SCREAMING_SNAKE_CASE = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Dict: """simple docstring""" with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file logger().debug(f'Attempting to release lock {lock_id} on {lock_filename}' ) self._release() __SCREAMING_SNAKE_CASE = 0 logger().debug(f'Lock {lock_id} released on {lock_filename}' ) return None def __enter__( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" self.acquire() return self def __exit__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" self.release() return None def __del__( self : str ) -> Union[str, Any]: """simple docstring""" self.release(force=__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = os.path.basename(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > max_length and max_length > 0: __SCREAMING_SNAKE_CASE = os.path.dirname(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = str(hash(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = filename[: max_length - len(__SCREAMING_SNAKE_CASE ) - 8] + """...""" + hashed_filename + """.lock""" return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: return path class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Dict=-1 , __SCREAMING_SNAKE_CASE : Dict=None ) -> List[Any]: """simple docstring""" from .file_utils import relative_to_absolute_path super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """\\\\?\\""" + relative_to_absolute_path(self.lock_file ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: try: msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_UNLCK , 1 ) os.close(__SCREAMING_SNAKE_CASE ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any]=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = os.statvfs(os.path.dirname(__SCREAMING_SNAKE_CASE ) ).f_namemax super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) try: fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_UN ) os.close(__SCREAMING_SNAKE_CASE ) return None class lowerCAmelCase__ ( a ): """simple docstring""" def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : int ) -> Optional[int]: """simple docstring""" os.close(self._lock_file_fd ) __SCREAMING_SNAKE_CASE = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None UpperCAmelCase : Dict = None if msvcrt: UpperCAmelCase : Optional[int] = WindowsFileLock elif fcntl: UpperCAmelCase : Optional[Any] = UnixFileLock else: UpperCAmelCase : int = SoftFileLock if warnings is not None: warnings.warn('only soft file lock is available')
267
0
import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu SCREAMING_SNAKE_CASE__ = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Tuple=None , SCREAMING_SNAKE_CASE : Any=None , SCREAMING_SNAKE_CASE : Union[str, Any]=None ) -> int: __lowercase = True while ask_again: __lowercase = input(a__ ) try: if default is not None and len(a__ ) == 0: return default return convert_value(a__ ) if convert_value is not None else result except Exception: if error_message is not None: print(a__ ) def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : List[Any]=[] , SCREAMING_SNAKE_CASE : Tuple=None , SCREAMING_SNAKE_CASE : Dict=0 ) -> Optional[int]: __lowercase = BulletMenu(a__ , a__ ) __lowercase = menu.run(default_choice=a__ ) return convert_value(a__ ) if convert_value is not None else result def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : Tuple ) -> List[Any]: __lowercase = int(a__ ) return ComputeEnvironment(['LOCAL_MACHINE', 'AMAZON_SAGEMAKER'][value] ) def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : Optional[int] ) -> List[str]: __lowercase = int(a__ ) return DistributedType(['NO', 'MULTI_CPU', 'MULTI_XPU', 'MULTI_GPU', 'MULTI_NPU', 'TPU'][value] ) def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : Tuple ) -> int: __lowercase = int(a__ ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : Dict ) -> int: __lowercase = int(a__ ) return PrecisionType(['no', 'fp16', 'bf16', 'fp8'][value] ) def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : int ) -> Dict: __lowercase = int(a__ ) return SageMakerDistributedType(['NO', 'DATA_PARALLEL', 'MODEL_PARALLEL'][value] ) def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : int ) -> Union[str, Any]: return {"yes": True, "no": False}[value.lower()] class A__ ( argparse.RawDescriptionHelpFormatter ): def a__ ( self : str , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Dict , _UpperCAmelCase : Optional[int] , _UpperCAmelCase : List[Any] ) -> Dict: """simple docstring""" __lowercase = super()._format_usage(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __lowercase = usage.replace('<command> [<args>] ' , '' ) return usage
325
'''simple docstring''' import shutil import tempfile import unittest from transformers import ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, NllbTokenizer, NllbTokenizerFast, is_torch_available, ) from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right UpperCAmelCase : Optional[int] = 2_5_6_0_4_7 UpperCAmelCase : Union[str, Any] = 2_5_6_1_4_5 @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = NllbTokenizer lowerCAmelCase__ = NllbTokenizerFast lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = {} def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__SCREAMING_SNAKE_CASE , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-nllb""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) __SCREAMING_SNAKE_CASE = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=True __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=False __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : List[Any] ) -> Any: """simple docstring""" if not self.test_seqaseq: return __SCREAMING_SNAKE_CASE = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Longer text that will definitely require truncation. __SCREAMING_SNAKE_CASE = [ """ UN Chief Says There Is No Military Solution in Syria""", """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for""" """ Syria is that 'there is no military solution' to the nearly five-year conflict and more weapons""" """ will only worsen the violence and misery for millions of people.""", ] __SCREAMING_SNAKE_CASE = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", """Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al""" """ Rusiei pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi""" """ că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""", ] try: __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" , ) except NotImplementedError: return self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 10 ) # max_target_length will default to max_length if not specified __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( __SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 3 ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" ) self.assertEqual(batch_encoder_only.input_ids.shape[1] , 3 ) self.assertEqual(batch_encoder_only.attention_mask.shape[1] , 3 ) self.assertNotIn("""decoder_input_ids""" , __SCREAMING_SNAKE_CASE ) @unittest.skip("""Unfortunately way too slow to build a BPE with SentencePiece.""" ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" pass def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = [AddedToken("""<special>""" , lstrip=__SCREAMING_SNAKE_CASE )] __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""<special>""" , add_special_tokens=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(special_token_id in r_output ) if self.test_slow_tokenizer: __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_cr.encode("""Hey this is a <special> token""" ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertTrue(special_token_id in p_output ) self.assertTrue(special_token_id in cr_output ) @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = "facebook/nllb-200-distilled-600M" lowerCAmelCase__ = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] lowerCAmelCase__ = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] lowerCAmelCase__ = [ 256047, 16297, 134408, 8165, 248066, 14734, 950, 1135, 105721, 3573, 83, 27352, 108, 49486, 2, ] @classmethod def UpperCAmelCase__ ( cls : List[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" ) __SCREAMING_SNAKE_CASE = 1 return cls def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[str]: """simple docstring""" self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Arab"""] , 256_001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Latn"""] , 256_002 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""fra_Latn"""] , 256_057 ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" self.assertIn(__SCREAMING_SNAKE_CASE , self.tokenizer.all_special_ids ) # fmt: off __SCREAMING_SNAKE_CASE = [RO_CODE, 4_254, 98_068, 112_923, 39_072, 3_909, 713, 102_767, 26, 17_314, 35_642, 14_683, 33_118, 2_022, 66_987, 2, 256_047] # fmt: on __SCREAMING_SNAKE_CASE = self.tokenizer.decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertNotIn(self.tokenizer.eos_token , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = ["""this is gunna be a long sentence """ * 20] assert isinstance(src_text[0] , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = 10 __SCREAMING_SNAKE_CASE = self.tokenizer(__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ).input_ids[0] self.assertEqual(ids[-1] , 2 ) self.assertEqual(ids[0] , __SCREAMING_SNAKE_CASE ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> List[Any]: """simple docstring""" self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [256_203, 3] ) def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) __SCREAMING_SNAKE_CASE = shift_tokens_right( batch["""labels"""] , self.tokenizer.pad_token_id , self.tokenizer.lang_code_to_id["""ron_Latn"""] ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual((2, 15) , batch.input_ids.shape ) self.assertEqual((2, 15) , batch.attention_mask.shape ) __SCREAMING_SNAKE_CASE = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , batch.decoder_input_ids[0, 0] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = self.tokenizer( text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=10 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = targets["""input_ids"""] __SCREAMING_SNAKE_CASE = shift_tokens_right( __SCREAMING_SNAKE_CASE , self.tokenizer.pad_token_id , decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] , ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , { # A, test, EOS, en_XX """input_ids""": [[256_047, 70, 7_356, 2]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 256_057, } , ) @require_torch def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2, 256_047] ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [256_047, 16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2] )
267
0
'''simple docstring''' import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class _lowerCAmelCase ( __UpperCAmelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = None __SCREAMING_SNAKE_CASE : int = None @property def _a (self ): return self.feat_extract_tester.prepare_feat_extract_dict() def _a (self ): A_ : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """feature_size""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """sampling_rate""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """padding_value""" ) ) def _a (self ): A_ : Any = self.feat_extract_tester.prepare_inputs_for_common() A_ : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_dict ) A_ : List[str] = feat_extract.model_input_names[0] A_ : List[str] = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(__SCREAMING_SNAKE_CASE ) == len(__SCREAMING_SNAKE_CASE ) for x, y in zip(__SCREAMING_SNAKE_CASE , processed_features[input_name] ) ) ) A_ : Union[str, Any] = self.feat_extract_tester.prepare_inputs_for_common(equal_length=__SCREAMING_SNAKE_CASE ) A_ : List[str] = BatchFeature({input_name: speech_inputs} , tensor_type="""np""" ) A_ : Dict = processed_features[input_name] if len(batch_features_input.shape ) < 3: A_ : Any = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_torch def _a (self ): A_ : Union[str, Any] = self.feat_extract_tester.prepare_inputs_for_common(equal_length=__SCREAMING_SNAKE_CASE ) A_ : Tuple = self.feature_extraction_class(**self.feat_extract_dict ) A_ : Tuple = feat_extract.model_input_names[0] A_ : Union[str, Any] = BatchFeature({input_name: speech_inputs} , tensor_type="""pt""" ) A_ : List[Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: A_ : Tuple = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_tf def _a (self ): A_ : Union[str, Any] = self.feat_extract_tester.prepare_inputs_for_common(equal_length=__SCREAMING_SNAKE_CASE ) A_ : Any = self.feature_extraction_class(**self.feat_extract_dict ) A_ : Optional[int] = feat_extract.model_input_names[0] A_ : Dict = BatchFeature({input_name: speech_inputs} , tensor_type="""tf""" ) A_ : Any = processed_features[input_name] if len(batch_features_input.shape ) < 3: A_ : List[str] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) def _a (self , lowercase=False ): def _inputs_have_equal_length(lowercase ): A_ : Optional[Any] = len(input[0] ) for input_slice in input[1:]: if len(__SCREAMING_SNAKE_CASE ) != length: return False return True def _inputs_are_equal(lowercase , lowercase ): if len(__SCREAMING_SNAKE_CASE ) != len(__SCREAMING_SNAKE_CASE ): return False for input_slice_a, input_slice_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): if not np.allclose(np.asarray(__SCREAMING_SNAKE_CASE ) , np.asarray(__SCREAMING_SNAKE_CASE ) , atol=1E-3 ): return False return True A_ : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) A_ : Optional[int] = self.feat_extract_tester.prepare_inputs_for_common(numpify=__SCREAMING_SNAKE_CASE ) A_ : Tuple = feat_extract.model_input_names[0] A_ : List[Any] = BatchFeature({input_name: speech_inputs} ) A_ : Union[str, Any] = self.feat_extract_tester.seq_length_diff A_ : Union[str, Any] = self.feat_extract_tester.max_seq_length + pad_diff A_ : Optional[Any] = self.feat_extract_tester.min_seq_length A_ : Dict = self.feat_extract_tester.batch_size A_ : int = self.feat_extract_tester.feature_size # test padding for List[int] + numpy A_ : Dict = feat_extract.pad(__SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE ) A_ : Optional[int] = input_a[input_name] A_ : Any = feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""longest""" ) A_ : Union[str, Any] = input_a[input_name] A_ : Union[str, Any] = feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=len(speech_inputs[-1] ) ) A_ : Dict = input_a[input_name] A_ : Any = feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""longest""" , return_tensors="""np""" ) A_ : Dict = input_a[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(__SCREAMING_SNAKE_CASE ): feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""max_length""" )[input_name] A_ : Union[str, Any] = feat_extract.pad( __SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) A_ : Optional[int] = input_a[input_name] self.assertFalse(_inputs_have_equal_length(__SCREAMING_SNAKE_CASE ) ) self.assertTrue(_inputs_have_equal_length(__SCREAMING_SNAKE_CASE ) ) self.assertTrue(_inputs_have_equal_length(__SCREAMING_SNAKE_CASE ) ) self.assertTrue(_inputs_are_equal(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertTrue(len(input_a[0] ) == pad_min_length ) self.assertTrue(len(input_a[1] ) == pad_min_length + pad_diff ) self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0] )) ) self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size ) # test padding for `pad_to_multiple_of` for List[int] + numpy A_ : List[Any] = feat_extract.pad(__SCREAMING_SNAKE_CASE , pad_to_multiple_of=10 ) A_ : List[Any] = input_a[input_name] A_ : Tuple = feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""longest""" , pad_to_multiple_of=10 ) A_ : str = input_a[input_name] A_ : Dict = feat_extract.pad( __SCREAMING_SNAKE_CASE , padding="""max_length""" , pad_to_multiple_of=10 , max_length=__SCREAMING_SNAKE_CASE ) A_ : int = input_a[input_name] A_ : Optional[Any] = feat_extract.pad( __SCREAMING_SNAKE_CASE , padding="""max_length""" , pad_to_multiple_of=10 , max_length=__SCREAMING_SNAKE_CASE , return_tensors="""np""" , ) A_ : Tuple = input_a[input_name] self.assertTrue(all(len(__SCREAMING_SNAKE_CASE ) % 10 == 0 for x in input_a ) ) self.assertTrue(_inputs_are_equal(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) A_ : List[Any] = pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 self.assertTrue(all(len(__SCREAMING_SNAKE_CASE ) == expected_mult_pad_length for x in input_a ) ) self.assertEqual(input_a.shape[:2] , (batch_size, expected_mult_pad_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == feature_size ) # Check padding value is correct A_ : Tuple = (np.ones(self.feat_extract_tester.feature_size ) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_a[0] )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1E-3 ) self.assertTrue( abs( np.asarray(input_a[1] )[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1E-3 ) self.assertTrue( abs( np.asarray(input_a[2] )[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1E-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1E-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length) ) < 1E-3 ) def _a (self , lowercase=False ): def _inputs_have_equal_length(lowercase ): A_ : str = len(input[0] ) for input_slice in input[1:]: if len(__SCREAMING_SNAKE_CASE ) != length: return False return True def _inputs_are_equal(lowercase , lowercase ): if len(__SCREAMING_SNAKE_CASE ) != len(__SCREAMING_SNAKE_CASE ): return False for input_slice_a, input_slice_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): if not np.allclose(np.asarray(__SCREAMING_SNAKE_CASE ) , np.asarray(__SCREAMING_SNAKE_CASE ) , atol=1E-3 ): return False return True A_ : Optional[Any] = self.feature_extraction_class(**self.feat_extract_dict ) A_ : Optional[int] = self.feat_extract_tester.prepare_inputs_for_common(numpify=__SCREAMING_SNAKE_CASE ) A_ : Tuple = feat_extract.model_input_names[0] A_ : Union[str, Any] = BatchFeature({input_name: speech_inputs} ) # truncate to smallest A_ : Optional[int] = feat_extract.pad( __SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=len(speech_inputs[0] ) , truncation=__SCREAMING_SNAKE_CASE ) A_ : Optional[int] = input_a[input_name] A_ : Tuple = feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=len(speech_inputs[0] ) ) A_ : int = input_a[input_name] self.assertTrue(_inputs_have_equal_length(__SCREAMING_SNAKE_CASE ) ) self.assertFalse(_inputs_have_equal_length(__SCREAMING_SNAKE_CASE ) ) # truncate to smallest with np A_ : Optional[int] = feat_extract.pad( __SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=len(speech_inputs[0] ) , return_tensors="""np""" , truncation=__SCREAMING_SNAKE_CASE , ) A_ : int = input_a[input_name] A_ : Dict = feat_extract.pad( __SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=len(speech_inputs[0] ) , return_tensors="""np""" ) A_ : Dict = input_a[input_name] self.assertTrue(_inputs_have_equal_length(__SCREAMING_SNAKE_CASE ) ) self.assertTrue(input_a.shape[1] == len(speech_inputs[0] ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(__SCREAMING_SNAKE_CASE ) ) # truncate to middle A_ : Tuple = feat_extract.pad( __SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=len(speech_inputs[1] ) , truncation=__SCREAMING_SNAKE_CASE , return_tensors="""np""" , ) A_ : Tuple = input_a[input_name] A_ : str = feat_extract.pad( __SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=len(speech_inputs[1] ) , truncation=__SCREAMING_SNAKE_CASE ) A_ : Union[str, Any] = input_a[input_name] A_ : Optional[Any] = feat_extract.pad( __SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=len(speech_inputs[1] ) , return_tensors="""np""" ) A_ : Any = input_a[input_name] self.assertTrue(input_a.shape[1] == len(speech_inputs[1] ) ) self.assertTrue(_inputs_have_equal_length(__SCREAMING_SNAKE_CASE ) ) self.assertTrue(_inputs_have_equal_length(__SCREAMING_SNAKE_CASE ) ) self.assertTrue(_inputs_are_equal(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(__SCREAMING_SNAKE_CASE ) ) self.assertTrue(len(input_a[-1] ) == len(speech_inputs[-1] ) ) # padding has to be max_length when setting `truncation=True` with self.assertRaises(__SCREAMING_SNAKE_CASE ): feat_extract.pad(__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(__SCREAMING_SNAKE_CASE ): feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""longest""" , truncation=__SCREAMING_SNAKE_CASE )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(__SCREAMING_SNAKE_CASE ): feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""longest""" , truncation=__SCREAMING_SNAKE_CASE )[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(__SCREAMING_SNAKE_CASE ): feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""max_length""" , truncation=__SCREAMING_SNAKE_CASE )[input_name] # test truncation for `pad_to_multiple_of` for List[int] + numpy A_ : Optional[int] = 12 A_ : Optional[int] = feat_extract.pad( __SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=len(speech_inputs[0] ) , pad_to_multiple_of=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , ) A_ : Tuple = input_a[input_name] A_ : Optional[int] = feat_extract.pad( __SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=len(speech_inputs[0] ) , pad_to_multiple_of=__SCREAMING_SNAKE_CASE , ) A_ : Tuple = input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of A_ : str = len(speech_inputs[0] ) if expected_length % pad_to_multiple_of != 0: A_ : List[Any] = ((len(speech_inputs[0] ) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_a[0] ) == expected_length ) self.assertTrue(_inputs_have_equal_length(__SCREAMING_SNAKE_CASE ) ) self.assertFalse(_inputs_have_equal_length(__SCREAMING_SNAKE_CASE ) ) def _a (self ): self._check_padding(numpify=__SCREAMING_SNAKE_CASE ) def _a (self ): self._check_padding(numpify=__SCREAMING_SNAKE_CASE ) def _a (self ): self._check_truncation(numpify=__SCREAMING_SNAKE_CASE ) def _a (self ): self._check_truncation(numpify=__SCREAMING_SNAKE_CASE ) @require_torch def _a (self ): A_ : Any = self.feature_extraction_class(**self.feat_extract_dict ) A_ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_common() A_ : Any = feat_extract.model_input_names[0] A_ : Any = BatchFeature({input_name: speech_inputs} ) A_ : List[str] = feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""longest""" , return_tensors="""np""" )[input_name] A_ : Any = feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""longest""" , return_tensors="""pt""" )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1E-2 ) @require_tf def _a (self ): A_ : List[str] = self.feature_extraction_class(**self.feat_extract_dict ) A_ : Tuple = self.feat_extract_tester.prepare_inputs_for_common() A_ : str = feat_extract.model_input_names[0] A_ : Optional[int] = BatchFeature({input_name: speech_inputs} ) A_ : Optional[int] = feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""longest""" , return_tensors="""np""" )[input_name] A_ : Tuple = feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""longest""" , return_tensors="""tf""" )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_tf.numpy().astype(np.floataa ).sum() ) < 1E-2 ) def _a (self ): A_ : Optional[Any] = self.feat_extract_dict A_ : Optional[Any] = True A_ : str = self.feature_extraction_class(**__SCREAMING_SNAKE_CASE ) A_ : Any = self.feat_extract_tester.prepare_inputs_for_common() A_ : Tuple = [len(__SCREAMING_SNAKE_CASE ) for x in speech_inputs] A_ : Union[str, Any] = feat_extract.model_input_names[0] A_ : List[Any] = BatchFeature({input_name: speech_inputs} ) A_ : Any = feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""longest""" , return_tensors="""np""" ) self.assertIn("""attention_mask""" , __SCREAMING_SNAKE_CASE ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , __SCREAMING_SNAKE_CASE ) def _a (self ): A_ : int = self.feat_extract_dict A_ : Any = True A_ : str = self.feature_extraction_class(**__SCREAMING_SNAKE_CASE ) A_ : List[Any] = self.feat_extract_tester.prepare_inputs_for_common() A_ : Tuple = [len(__SCREAMING_SNAKE_CASE ) for x in speech_inputs] A_ : List[Any] = feat_extract.model_input_names[0] A_ : str = BatchFeature({input_name: speech_inputs} ) A_ : List[Any] = min(__SCREAMING_SNAKE_CASE ) A_ : Optional[Any] = feat_extract.pad( __SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) self.assertIn("""attention_mask""" , __SCREAMING_SNAKE_CASE ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] )
206
'''simple docstring''' import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging UpperCAmelCase : str = logging.get_logger(__name__) class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "linear" lowerCAmelCase__ = "cosine" lowerCAmelCase__ = "cosine_with_restarts" lowerCAmelCase__ = "polynomial" lowerCAmelCase__ = "constant" lowerCAmelCase__ = "constant_with_warmup" lowerCAmelCase__ = "piecewise_constant" def a__ ( a__ , a__ = -1 ): """simple docstring""" return LambdaLR(a__ , lambda a__ : 1 , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1.0 , a__ ) ) return 1.0 return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = step_rules.split(""",""" ) for rule_str in rule_list[:-1]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = rule_str.split(""":""" ) __SCREAMING_SNAKE_CASE = int(a__ ) __SCREAMING_SNAKE_CASE = float(a__ ) __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = float(rule_list[-1] ) def create_rules_function(a__ , a__ ): def rule_func(a__ ) -> float: __SCREAMING_SNAKE_CASE = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(a__ ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func __SCREAMING_SNAKE_CASE = create_rules_function(a__ , a__ ) return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ , a__=-1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 0.5 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(a__ ) * 2.0 * progress )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 1 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(a__ ) * progress) % 1.0) )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__=1E-7 , a__=1.0 , a__=-1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = optimizer.defaults["""lr"""] if not (lr_init > lr_end): raise ValueError(F'lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})' ) def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: __SCREAMING_SNAKE_CASE = lr_init - lr_end __SCREAMING_SNAKE_CASE = num_training_steps - num_warmup_steps __SCREAMING_SNAKE_CASE = 1 - (current_step - num_warmup_steps) / decay_steps __SCREAMING_SNAKE_CASE = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(a__ , a__ , a__ ) UpperCAmelCase : Optional[Any] = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def a__ ( a__ , a__ , a__ = None , a__ = None , a__ = None , a__ = 1 , a__ = 1.0 , a__ = -1 , ): """simple docstring""" __SCREAMING_SNAKE_CASE = SchedulerType(a__ ) __SCREAMING_SNAKE_CASE = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(a__ , last_epoch=a__ ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(a__ , step_rules=a__ , last_epoch=a__ ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(F'{name} requires `num_warmup_steps`, please provide that argument.' ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(a__ , num_warmup_steps=a__ , last_epoch=a__ ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(F'{name} requires `num_training_steps`, please provide that argument.' ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , num_cycles=a__ , last_epoch=a__ , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , power=a__ , last_epoch=a__ , ) return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , last_epoch=a__ )
267
0
'''simple docstring''' import os import re import shutil import sys import tempfile import unittest import black lowercase : Dict = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, 'utils')) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated. lowercase : Optional[Any] = ' def __init__(self, config):\n super().__init__()\n self.transform = BertPredictionHeadTransform(config)\n\n # The output weights are the same as the input embeddings, but there is\n # an output-only bias for each token.\n self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)\n\n self.bias = nn.Parameter(torch.zeros(config.vocab_size))\n\n # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`\n self.decoder.bias = self.bias\n\n def forward(self, hidden_states):\n hidden_states = self.transform(hidden_states)\n hidden_states = self.decoder(hidden_states)\n return hidden_states\n' class A ( unittest.TestCase ): def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Any = tempfile.mkdtemp() os.makedirs(os.path.join(self.transformer_dir , '''models/bert/''' ) ) A : Optional[Any] = self.transformer_dir shutil.copy( os.path.join(__SCREAMING_SNAKE_CASE , '''src/transformers/models/bert/modeling_bert.py''' ) , os.path.join(self.transformer_dir , '''models/bert/modeling_bert.py''' ) , ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" A : List[Any] = '''src/transformers''' shutil.rmtree(self.transformer_dir ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=None ) -> Dict: """simple docstring""" A : Any = comment + F'\nclass {class_name}(nn.Module):\n' + class_code if overwrite_result is not None: A : Union[str, Any] = comment + F'\nclass {class_name}(nn.Module):\n' + overwrite_result A : Dict = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 ) A : Tuple = black.format_str(__SCREAMING_SNAKE_CASE , mode=__SCREAMING_SNAKE_CASE ) A : Optional[Any] = os.path.join(self.transformer_dir , '''new_code.py''' ) with open(__SCREAMING_SNAKE_CASE , '''w''' , newline='''\n''' ) as f: f.write(__SCREAMING_SNAKE_CASE ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(__SCREAMING_SNAKE_CASE ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=__SCREAMING_SNAKE_CASE ) with open(__SCREAMING_SNAKE_CASE , '''r''' ) as f: self.assertTrue(f.read() , __SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : Optional[Any] = check_copies.find_code_in_transformers('''models.bert.modeling_bert.BertLMPredictionHead''' ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" self.check_copy_consistency( '''# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead''' , '''BertLMPredictionHead''' , REFERENCE_CODE + '''\n''' , ) # With no empty line at the end self.check_copy_consistency( '''# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead''' , '''BertLMPredictionHead''' , __SCREAMING_SNAKE_CASE , ) # Copy consistency with rename self.check_copy_consistency( '''# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel''' , '''TestModelLMPredictionHead''' , re.sub('''Bert''' , '''TestModel''' , __SCREAMING_SNAKE_CASE ) , ) # Copy consistency with a really long name A : Any = '''TestModelWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason''' self.check_copy_consistency( F'# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->{long_class_name}' , F'{long_class_name}LMPredictionHead' , re.sub('''Bert''' , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , ) # Copy consistency with overwrite self.check_copy_consistency( '''# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel''' , '''TestModelLMPredictionHead''' , __SCREAMING_SNAKE_CASE , overwrite_result=re.sub('''Bert''' , '''TestModel''' , __SCREAMING_SNAKE_CASE ) , ) def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : Union[str, Any] = check_copies.LOCALIZED_READMES['''README_zh-hans.md'''] A : int = ( '''1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the''' ''' Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for''' ''' Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong''' ''' Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1.''' ''' **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace),''' ''' released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and''' ''' lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same''' ''' method has been applied to compress GPT2 into''' ''' [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into''' ''' [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),''' ''' Multilingual BERT into''' ''' [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German''' ''' version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**''' ''' (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders''' ''' as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang''' ''' Luong, Quoc V. Le, Christopher D. Manning.''' ) A : str = ( '''1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the''' ''' Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of''' ''' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian''' ''' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n''' ) A : Any = ( '''1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the''' ''' Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of''' ''' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian''' ''' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1.''' ''' **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文''' ''' [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and''' ''' lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same''' ''' method has been applied to compress GPT2 into''' ''' [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into''' ''' [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),''' ''' Multilingual BERT into''' ''' [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German''' ''' version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自''' ''' Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather''' ''' than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le,''' ''' Christopher D. Manning 发布。\n''' ) A, A : Any = check_copies.convert_to_localized_md( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , localized_readme['''format_model_list'''] ) self.assertFalse(__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) A, A : List[Any] = check_copies.convert_to_localized_md( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , localized_readme['''format_model_list'''] ) # Check whether the number of models is equal to README.md after conversion. self.assertTrue(__SCREAMING_SNAKE_CASE ) A : Union[str, Any] = ( '''1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the''' ''' Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for''' ''' Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong''' ''' Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.''' ) A : Dict = ( '''1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and''' ''' the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of''' ''' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian''' ''' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n''' ) A : List[str] = ( '''1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the''' ''' Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of''' ''' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian''' ''' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n''' ) A, A : Any = check_copies.convert_to_localized_md( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , localized_readme['''format_model_list'''] ) # Check if the model link is synchronized. self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
3
'''simple docstring''' import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() UpperCAmelCase : Tuple = { 'bart': ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'bert': ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-base-cased-finetuned-mrpc': ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'dpr': ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'gpt2': ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlnet': ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm': ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm-roberta': ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'transfo-xl': ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'openai-gpt': ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'roberta': ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'layoutlm': ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'roberta-large-mnli': ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'camembert': ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'flaubert': ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert': ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert-base-distilled-squad': ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert': ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert-visual-feature-encoder': ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'ctrl': ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'albert': ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 't5': ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'electra': ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'wav2vec2': ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def a__ ( a__ , a__ , a__ , a__ , a__=False , a__=True ): """simple docstring""" if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) __SCREAMING_SNAKE_CASE = config_class.from_json_file(a__ ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True print(F'Building TensorFlow model from configuration: {config}' ) __SCREAMING_SNAKE_CASE = model_class(a__ ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): __SCREAMING_SNAKE_CASE = cached_file( a__ , a__ , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: __SCREAMING_SNAKE_CASE = load_pytorch_checkpoint_in_tfa_model(a__ , a__ ) if compare_with_pt_model: __SCREAMING_SNAKE_CASE = tf_model(tf_model.dummy_inputs , training=a__ ) # build the network __SCREAMING_SNAKE_CASE = torch.load(a__ , map_location="""cpu""" ) __SCREAMING_SNAKE_CASE = pt_model_class.from_pretrained( pretrained_model_name_or_path=a__ , config=a__ , state_dict=a__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = pt_model(**pt_model.dummy_inputs ) __SCREAMING_SNAKE_CASE = pto[0].numpy() __SCREAMING_SNAKE_CASE = tfo[0].numpy() __SCREAMING_SNAKE_CASE = np.amax(np.abs(np_pt - np_tf ) ) print(F'Max absolute difference between models outputs {diff}' ) assert diff <= 2E-2, F'Error, model absolute difference is >2e-2: {diff}' # Save pytorch-model print(F'Save TensorFlow model to {tf_dump_path}' ) tf_model.save_weights(a__ , save_format="""h5""" ) def a__ ( a__ , a__ , a__=None , a__=None , a__=False , a__=False , a__=False , a__=False , ): """simple docstring""" if args_model_type is None: __SCREAMING_SNAKE_CASE = list(MODEL_CLASSES.keys() ) else: __SCREAMING_SNAKE_CASE = [args_model_type] for j, model_type in enumerate(a__ , start=1 ): print("""=""" * 1_00 ) print(F' Converting model type {j}/{len(a__ )}: {model_type}' ) print("""=""" * 1_00 ) if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(a__ , a__ ) , start=1 ): print("""-""" * 1_00 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(F' Skipping finetuned checkpoint {model_shortcut_name}' ) continue __SCREAMING_SNAKE_CASE = model_shortcut_name elif only_convert_finetuned_models: print(F' Skipping not finetuned checkpoint {model_shortcut_name}' ) continue print( F' Converting checkpoint {i}/{len(a__ )}: {model_shortcut_name} - model_type {model_type}' ) print("""-""" * 1_00 ) if config_shortcut_name in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = config_shortcut_name if model_shortcut_name in aws_model_maps: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = model_shortcut_name if os.path.isfile(a__ ): __SCREAMING_SNAKE_CASE = """converted_model""" convert_pt_checkpoint_to_tf( model_type=a__ , pytorch_checkpoint_path=a__ , config_file=a__ , tf_dump_path=os.path.join(a__ , model_shortcut_name + """-tf_model.h5""" ) , compare_with_pt_model=a__ , ) if remove_cached_files: os.remove(a__ ) os.remove(a__ ) if __name__ == "__main__": UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_dump_path', default=None, type=str, required=True, help='Path to the output Tensorflow dump file.' ) parser.add_argument( '--model_type', default=None, type=str, help=( f"""Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and """ 'convert all the models from AWS.' ), ) parser.add_argument( '--pytorch_checkpoint_path', default=None, type=str, help=( 'Path to the PyTorch checkpoint path or shortcut name to download from AWS. ' 'If not given, will download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--config_file', default=None, type=str, help=( 'The config json file corresponding to the pre-trained model. \n' 'This specifies the model architecture. If not given and ' '--pytorch_checkpoint_path is not given or is a shortcut name ' 'use the configuration associated to the shortcut name on the AWS' ), ) parser.add_argument( '--compare_with_pt_model', action='store_true', help='Compare Tensorflow and PyTorch model predictions.' ) parser.add_argument( '--use_cached_models', action='store_true', help='Use cached models if possible instead of updating to latest checkpoint versions.', ) parser.add_argument( '--remove_cached_files', action='store_true', help='Remove pytorch models after conversion (save memory when converting in batches).', ) parser.add_argument('--only_convert_finetuned_models', action='store_true', help='Only convert finetuned models.') UpperCAmelCase : List[Any] = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
267
0
import random from typing import Any def __lowerCAmelCase ( a__ ) -> Any: for _ in range(len(a__ ) ): __a = random.randint(0 , len(a__ ) - 1 ) __a = random.randint(0 , len(a__ ) - 1 ) __a , __a = data[b], data[a] return data if __name__ == "__main__": A : List[Any] = [0, 1, 2, 3, 4, 5, 6, 7] A : str = ['python', 'says', 'hello', '!'] print('Fisher-Yates Shuffle:') print('List', integers, strings) print('FY Shuffle', fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
6
'''simple docstring''' def a__ ( a__ ): """simple docstring""" if isinstance(a__ , a__ ): raise TypeError("""'float' object cannot be interpreted as an integer""" ) if isinstance(a__ , a__ ): raise TypeError("""'str' object cannot be interpreted as an integer""" ) if num == 0: return "0b0" __SCREAMING_SNAKE_CASE = False if num < 0: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = -num __SCREAMING_SNAKE_CASE = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(a__ ) for e in binary ) return "0b" + "".join(str(a__ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
267
0
"""simple docstring""" import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets __A = '\\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' __A = '\\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' __A = '\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 SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase , __UpperCAmelCase ) -> str: return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase , __UpperCAmelCase ) -> Optional[Any]: lowercase__: str = simple_accuracy(a__ , a__ ) lowercase__: Any = float(fa_score(y_true=a__ , y_pred=a__ ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]: lowercase__: str = np.array(a__ ) lowercase__: List[str] = np.array(a__ ) lowercase__: Optional[int] = en_sentvecs.shape[0] # mean centering lowercase__: Optional[int] = en_sentvecs - np.mean(a__ , axis=0 ) lowercase__: Union[str, Any] = in_sentvecs - np.mean(a__ , axis=0 ) lowercase__: str = cdist(a__ , a__ , '''cosine''' ) lowercase__: Tuple = np.array(range(a__ ) ) lowercase__: int = sim.argsort(axis=1 )[:, :1_0] lowercase__: Dict = 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 _snake_case ( self ): 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 _snake_case ( self , _UpperCAmelCase , _UpperCAmelCase ): if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )} elif self.config_name in ["wiki-ner"]: return acc_and_fa(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )} 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\"]''' )
177
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : Optional[int] = logging.get_logger(__name__) UpperCAmelCase : str = { 'facebook/convnextv2-tiny-1k-224': 'https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json', } class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "convnextv2" def __init__( self : Any , __SCREAMING_SNAKE_CASE : int=3 , __SCREAMING_SNAKE_CASE : Dict=4 , __SCREAMING_SNAKE_CASE : List[Any]=4 , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Optional[int]="gelu" , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.02 , __SCREAMING_SNAKE_CASE : Dict=1E-12 , __SCREAMING_SNAKE_CASE : List[str]=0.0 , __SCREAMING_SNAKE_CASE : Optional[Any]=224 , __SCREAMING_SNAKE_CASE : Tuple=None , __SCREAMING_SNAKE_CASE : List[str]=None , **__SCREAMING_SNAKE_CASE : Union[str, Any] , ) -> Union[str, Any]: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_stages __SCREAMING_SNAKE_CASE = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes __SCREAMING_SNAKE_CASE = [3, 3, 9, 3] if depths is None else depths __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(self.depths ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
0
import math def lowercase ( ) -> Optional[int]: _snake_case : Optional[Any] = input("""Enter message: """ ) _snake_case : List[Any] = int(input(F'''Enter key [2-{len(a__ ) - 1}]: ''' ) ) _snake_case : Dict = input("""Encryption/Decryption [e/d]: """ ) if mode.lower().startswith("""e""" ): _snake_case : Dict = encrypt_message(a__ , a__ ) elif mode.lower().startswith("""d""" ): _snake_case : Union[str, Any] = decrypt_message(a__ , a__ ) # Append pipe symbol (vertical bar) to identify spaces at the end. print(F'''Output:\n{text + '|'}''' ) def lowercase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple ) -> Optional[int]: _snake_case : List[Any] = [""""""] * key for col in range(a__ ): _snake_case : List[str] = col while pointer < len(a__ ): cipher_text[col] += message[pointer] pointer += key return "".join(a__ ) def lowercase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Optional[Any]: _snake_case : Optional[Any] = math.ceil(len(a__ ) / key ) _snake_case : Optional[int] = key _snake_case : int = (num_cols * num_rows) - len(a__ ) _snake_case : List[str] = [""""""] * num_cols _snake_case : Optional[Any] = 0 _snake_case : Optional[int] = 0 for symbol in message: plain_text[col] += symbol col += 1 if ( (col == num_cols) or (col == num_cols - 1) and (row >= num_rows - num_shaded_boxes) ): _snake_case : Tuple = 0 row += 1 return "".join(a__ ) if __name__ == "__main__": import doctest doctest.testmod() main()
317
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : List[str] = logging.get_logger(__name__) class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "maskformer-swin" lowerCAmelCase__ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : str , __SCREAMING_SNAKE_CASE : Tuple=224 , __SCREAMING_SNAKE_CASE : str=4 , __SCREAMING_SNAKE_CASE : Union[str, Any]=3 , __SCREAMING_SNAKE_CASE : Optional[Any]=96 , __SCREAMING_SNAKE_CASE : Optional[Any]=[2, 2, 6, 2] , __SCREAMING_SNAKE_CASE : Any=[3, 6, 12, 24] , __SCREAMING_SNAKE_CASE : Dict=7 , __SCREAMING_SNAKE_CASE : Dict=4.0 , __SCREAMING_SNAKE_CASE : Dict=True , __SCREAMING_SNAKE_CASE : str=0.0 , __SCREAMING_SNAKE_CASE : int=0.0 , __SCREAMING_SNAKE_CASE : str=0.1 , __SCREAMING_SNAKE_CASE : List[Any]="gelu" , __SCREAMING_SNAKE_CASE : str=False , __SCREAMING_SNAKE_CASE : Optional[int]=0.02 , __SCREAMING_SNAKE_CASE : Optional[int]=1E-5 , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Dict=None , **__SCREAMING_SNAKE_CASE : Tuple , ) -> Tuple: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = embed_dim __SCREAMING_SNAKE_CASE = depths __SCREAMING_SNAKE_CASE = len(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_heads __SCREAMING_SNAKE_CASE = window_size __SCREAMING_SNAKE_CASE = mlp_ratio __SCREAMING_SNAKE_CASE = qkv_bias __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = use_absolute_embeddings __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __SCREAMING_SNAKE_CASE = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) ) __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
0
"""simple docstring""" import math from typing import Callable, List, Optional, Union import numpy as np import PIL import torch from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=[] ) -> List[Any]: lowercase__ : Any = size[0] - overlap_pixels * 2 lowercase__ : Union[str, Any] = size[1] - overlap_pixels * 2 for letter in ["l", "r"]: if letter in remove_borders: size_x += overlap_pixels for letter in ["t", "b"]: if letter in remove_borders: size_y += overlap_pixels lowercase__ : List[str] = np.ones((size_y, size_x) , dtype=np.uinta ) * 2_55 lowercase__ : str = np.pad(a__ , mode='''linear_ramp''' , pad_width=a__ , end_values=0 ) if "l" in remove_borders: lowercase__ : Any = mask[:, overlap_pixels : mask.shape[1]] if "r" in remove_borders: lowercase__ : Tuple = mask[:, 0 : mask.shape[1] - overlap_pixels] if "t" in remove_borders: lowercase__ : Optional[int] = mask[overlap_pixels : mask.shape[0], :] if "b" in remove_borders: lowercase__ : int = mask[0 : mask.shape[0] - overlap_pixels, :] return mask def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> int: return max(a__ , min(a__ , a__ ) ) def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: return ( clamp(rect[0] , min[0] , max[0] ), clamp(rect[1] , min[1] , max[1] ), clamp(rect[2] , min[0] , max[0] ), clamp(rect[3] , min[1] , max[1] ), ) def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]: lowercase__ : int = list(a__ ) rect[0] -= overlap rect[1] -= overlap rect[2] += overlap rect[3] += overlap lowercase__ : Optional[int] = clamp_rect(a__ , [0, 0] , [image_size[0], image_size[1]] ) return rect def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> int: lowercase__ : Optional[Any] = Image.new('''RGB''' , (tile.size[0] + original_slice, tile.size[1]) ) result.paste( original_image.resize((tile.size[0], tile.size[1]) , Image.BICUBIC ).crop( (slice_x, 0, slice_x + original_slice, tile.size[1]) ) , (0, 0) , ) result.paste(a__ , (original_slice, 0) ) return result def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase ) -> List[str]: lowercase__ : Optional[int] = (original_image_slice * 4, 0, tile.size[0], tile.size[1]) lowercase__ : Dict = tile.crop(a__ ) return tile def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase ) -> List[str]: lowercase__ : Optional[Any] = n % d return n - divisor class __A ( A_ ): '''simple docstring''' def __init__( self : List[Any] ,_snake_case : AutoencoderKL ,_snake_case : CLIPTextModel ,_snake_case : CLIPTokenizer ,_snake_case : UNetaDConditionModel ,_snake_case : DDPMScheduler ,_snake_case : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] ,_snake_case : int = 350 ,) -> int: """simple docstring""" super().__init__( vae=__SCREAMING_SNAKE_CASE ,text_encoder=__SCREAMING_SNAKE_CASE ,tokenizer=__SCREAMING_SNAKE_CASE ,unet=__SCREAMING_SNAKE_CASE ,low_res_scheduler=__SCREAMING_SNAKE_CASE ,scheduler=__SCREAMING_SNAKE_CASE ,max_noise_level=__SCREAMING_SNAKE_CASE ,) def UpperCAmelCase ( self : List[Any] ,_snake_case : str ,_snake_case : Tuple ,_snake_case : Optional[int] ,_snake_case : Optional[Any] ,_snake_case : Tuple ,_snake_case : List[Any] ,_snake_case : int ,**_snake_case : str ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) lowercase__ : int = ( min(image.size[0] - (tile_size + original_image_slice) ,x * tile_size ), min(image.size[1] - (tile_size + original_image_slice) ,y * tile_size ), min(image.size[0] ,(x + 1) * tile_size ), min(image.size[1] ,(y + 1) * tile_size ), ) lowercase__ : Union[str, Any] = add_overlap_rect(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,image.size ) lowercase__ : Union[str, Any] = image.crop(__SCREAMING_SNAKE_CASE ) lowercase__ : Any = ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0] lowercase__ : Dict = translated_slice_x - (original_image_slice / 2) lowercase__ : Any = max(0 ,__SCREAMING_SNAKE_CASE ) lowercase__ : Tuple = squeeze_tile(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ) lowercase__ : int = to_input.size lowercase__ : Tuple = to_input.resize((tile_size, tile_size) ,Image.BICUBIC ) lowercase__ : Optional[int] = super(__SCREAMING_SNAKE_CASE ,self ).__call__(image=__SCREAMING_SNAKE_CASE ,**__SCREAMING_SNAKE_CASE ).images[0] lowercase__ : List[Any] = upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4) ,Image.BICUBIC ) lowercase__ : Tuple = unsqueeze_tile(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ) lowercase__ : Optional[int] = upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4) ,Image.BICUBIC ) lowercase__ : Optional[int] = [] if x == 0: remove_borders.append('''l''' ) elif crop_rect[2] == image.size[0]: remove_borders.append('''r''' ) if y == 0: remove_borders.append('''t''' ) elif crop_rect[3] == image.size[1]: remove_borders.append('''b''' ) lowercase__ : Optional[int] = Image.fromarray( make_transparency_mask( (upscaled_tile.size[0], upscaled_tile.size[1]) ,tile_border * 4 ,remove_borders=__SCREAMING_SNAKE_CASE ) ,mode='''L''' ,) final_image.paste( __SCREAMING_SNAKE_CASE ,(crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4) ,__SCREAMING_SNAKE_CASE ) @torch.no_grad() def __call__( self : List[str] ,_snake_case : Union[str, List[str]] ,_snake_case : Union[PIL.Image.Image, List[PIL.Image.Image]] ,_snake_case : int = 75 ,_snake_case : float = 9.0 ,_snake_case : int = 50 ,_snake_case : Optional[Union[str, List[str]]] = None ,_snake_case : Optional[int] = 1 ,_snake_case : float = 0.0 ,_snake_case : Optional[torch.Generator] = None ,_snake_case : Optional[torch.FloatTensor] = None ,_snake_case : Optional[Callable[[int, int, torch.FloatTensor], None]] = None ,_snake_case : int = 1 ,_snake_case : int = 128 ,_snake_case : int = 32 ,_snake_case : int = 32 ,) -> str: """simple docstring""" lowercase__ : Dict = Image.new('''RGB''' ,(image.size[0] * 4, image.size[1] * 4) ) lowercase__ : Any = math.ceil(image.size[0] / tile_size ) lowercase__ : str = math.ceil(image.size[1] / tile_size ) lowercase__ : Tuple = tcx * tcy lowercase__ : List[Any] = 0 for y in range(__SCREAMING_SNAKE_CASE ): for x in range(__SCREAMING_SNAKE_CASE ): self._process_tile( __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,prompt=__SCREAMING_SNAKE_CASE ,num_inference_steps=__SCREAMING_SNAKE_CASE ,guidance_scale=__SCREAMING_SNAKE_CASE ,noise_level=__SCREAMING_SNAKE_CASE ,negative_prompt=__SCREAMING_SNAKE_CASE ,num_images_per_prompt=__SCREAMING_SNAKE_CASE ,eta=__SCREAMING_SNAKE_CASE ,generator=__SCREAMING_SNAKE_CASE ,latents=__SCREAMING_SNAKE_CASE ,) current_count += 1 if callback is not None: callback({'''progress''': current_count / total_tile_count, '''image''': final_image} ) return final_image def __UpperCAmelCase ( ) -> Optional[Any]: lowercase__ : Union[str, Any] = '''stabilityai/stable-diffusion-x4-upscaler''' lowercase__ : Union[str, Any] = StableDiffusionTiledUpscalePipeline.from_pretrained(a__ , revision='''fp16''' , torch_dtype=torch.floataa ) lowercase__ : int = pipe.to('''cuda''' ) lowercase__ : List[str] = Image.open('''../../docs/source/imgs/diffusers_library.jpg''' ) def callback(__lowerCamelCase ): print(f"""progress: {obj["progress"]:.4f}""" ) obj["image"].save('''diffusers_library_progress.jpg''' ) lowercase__ : Dict = pipe(image=a__ , prompt='''Black font, white background, vector''' , noise_level=40 , callback=a__ ) final_image.save('''diffusers_library.jpg''' ) if __name__ == "__main__": main()
16
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = n __SCREAMING_SNAKE_CASE = [None] * self.n __SCREAMING_SNAKE_CASE = 0 # index of the first element __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 def __len__( self : Tuple ) -> int: """simple docstring""" return self.size def UpperCAmelCase__ ( self : Optional[Any] ) -> bool: """simple docstring""" return self.size == 0 def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" return False if self.is_empty() else self.array[self.front] def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Dict: """simple docstring""" if self.size >= self.n: raise Exception("""QUEUE IS FULL""" ) __SCREAMING_SNAKE_CASE = data __SCREAMING_SNAKE_CASE = (self.rear + 1) % self.n self.size += 1 return self def UpperCAmelCase__ ( self : List[str] ) -> Optional[Any]: """simple docstring""" if self.size == 0: raise Exception("""UNDERFLOW""" ) __SCREAMING_SNAKE_CASE = self.array[self.front] __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = (self.front + 1) % self.n self.size -= 1 return temp
267
0
def UpperCAmelCase__ ( lowerCamelCase = 1000000 ): lowercase :List[str] = 1 lowercase :Any = 1 lowercase :Tuple = {1: 1} for inputa in range(2, a__ ): lowercase :Optional[int] = 0 lowercase :int = inputa while True: if number in counters: counter += counters[number] break if number % 2 == 0: number //= 2 counter += 1 else: lowercase :Union[str, Any] = (3 * number) + 1 counter += 1 if inputa not in counters: lowercase :Union[str, Any] = counter if counter > pre_counter: lowercase :Dict = inputa lowercase :Optional[Any] = counter return largest_number if __name__ == "__main__": print(solution(int(input().strip())))
236
'''simple docstring''' import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @property def UpperCAmelCase__ ( self : List[str] ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("""DownBlock2D""", """AttnDownBlock2D""") , up_block_types=("""AttnUpBlock2D""", """UpBlock2D""") , ) return model def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.dummy_uncond_unet __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" , return_dict=__SCREAMING_SNAKE_CASE )[0] __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """google/ddpm-cifar10-32""" __SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array([0.1564, 0.14645, 0.1406, 0.14715, 0.12425, 0.14045, 0.13115, 0.12175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
267
0
'''simple docstring''' import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def _lowercase ( __A ,__A ,__A ,__A ,__A ,__A ): '''simple docstring''' if (ksize % 2) == 0: __UpperCamelCase = ksize + 1 __UpperCamelCase = np.zeros((ksize, ksize) ,dtype=np.floataa ) # each value for y in range(a__ ): for x in range(a__ ): # distance from center __UpperCamelCase = x - ksize // 2 __UpperCamelCase = y - ksize // 2 # degree to radiant __UpperCamelCase = theta / 180 * np.pi __UpperCamelCase = np.cos(_theta ) __UpperCamelCase = np.sin(_theta ) # get kernel x __UpperCamelCase = cos_theta * px + sin_theta * py # get kernel y __UpperCamelCase = -sin_theta * px + cos_theta * py # fill kernel __UpperCamelCase = np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi ) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image a__ : Optional[Any] = imread('../image_data/lena.jpg') # turn image in gray scale value a__ : List[Any] = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges a__ : int = np.zeros(gray.shape[:2]) for theta in [0, 3_0, 6_0, 9_0, 1_2_0, 1_5_0]: a__ : str = gabor_filter_kernel(1_0, 8, theta, 1_0, 0, 0) out += filteraD(gray, CV_8UC3, kernel_aa) a__ : str = out / out.max() * 2_5_5 a__ : List[str] = out.astype(np.uinta) imshow('Original', gray) imshow('Gabor filter with 20x20 mask and 6 directions', out) waitKey(0)
349
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : """simple docstring""" @staticmethod def UpperCAmelCase__ ( *__SCREAMING_SNAKE_CASE : Tuple , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: """simple docstring""" pass @is_pipeline_test @require_vision @require_timm @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = MODEL_FOR_OBJECT_DETECTION_MAPPING def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Tuple ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = object_detector("""./tests/fixtures/tests_samples/COCO/000000039769.png""" , threshold=0.0 ) self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) import datasets __SCREAMING_SNAKE_CASE = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) __SCREAMING_SNAKE_CASE = [ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ] __SCREAMING_SNAKE_CASE = object_detector(__SCREAMING_SNAKE_CASE , threshold=0.0 ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(__SCREAMING_SNAKE_CASE ) ) for outputs in batch_outputs: self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) @require_tf @unittest.skip("""Object detection not implemented in TF""" ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" pass @require_torch def UpperCAmelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """hf-internal-testing/tiny-detr-mobilenetsv3""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=0.0 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Dict ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = 0.9985 __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=__SCREAMING_SNAKE_CASE ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) @require_torch @require_pytesseract @slow def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """Narsil/layoutlmv3-finetuned-funsd""" __SCREAMING_SNAKE_CASE = 0.9993 __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE , threshold=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector( """https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, ] , )
267
0
from string import ascii_uppercase __A : Dict = {str(ord(c) - 55): c for c in ascii_uppercase} def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__ ) -> Union[str, Any]: '''simple docstring''' if isinstance(a__ , a__ ): raise TypeError('''int() can\'t convert non-string with explicit base''' ) if num < 0: raise ValueError('''parameter must be positive int''' ) if isinstance(a__ , a__ ): raise TypeError('''\'str\' object cannot be interpreted as an integer''' ) if isinstance(a__ , a__ ): raise TypeError('''\'float\' object cannot be interpreted as an integer''' ) if base in (0, 1): raise ValueError('''base must be >= 2''' ) if base > 36: raise ValueError('''base must be <= 36''' ) UpperCAmelCase = '''''' UpperCAmelCase = 0 UpperCAmelCase = 0 while div != 1: UpperCAmelCase , UpperCAmelCase = divmod(a__ , a__ ) if base >= 11 and 9 < mod < 36: UpperCAmelCase = ALPHABET_VALUES[str(a__ )] else: UpperCAmelCase = str(a__ ) new_value += actual_value UpperCAmelCase = num // base UpperCAmelCase = div if div == 0: return str(new_value[::-1] ) elif div == 1: new_value += str(a__ ) return str(new_value[::-1] ) return new_value[::-1] if __name__ == "__main__": import doctest doctest.testmod() for base in range(2, 37): for num in range(1_000): assert int(decimal_to_any(num, base), base) == num, ( num, base, decimal_to_any(num, base), int(decimal_to_any(num, base), base), )
273
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = FlaxAutoencoderKL @property def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (32, 32) __SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0 ) __SCREAMING_SNAKE_CASE = jax.random.uniform(__SCREAMING_SNAKE_CASE , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 4, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict
267
0
import unittest from transformers import is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class UpperCamelCase_ : '''simple docstring''' @staticmethod def _UpperCamelCase ( *a , **a ) -> Optional[int]: pass @is_pipeline_test @require_vision class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' @require_torch def _UpperCamelCase ( self ) -> Optional[int]: snake_case_ = pipeline( model='hf-internal-testing/tiny-random-clip-zero-shot-image-classification' , ) snake_case_ = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) snake_case_ = image_classifier(__SCREAMING_SNAKE_CASE , candidate_labels=['a', 'b', 'c'] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(__SCREAMING_SNAKE_CASE ) , [ [{'score': 0.333, 'label': 'a'}, {'score': 0.333, 'label': 'b'}, {'score': 0.333, 'label': 'c'}], [{'score': 0.333, 'label': 'a'}, {'score': 0.333, 'label': 'c'}, {'score': 0.333, 'label': 'b'}], ] , ) snake_case_ = image_classifier([image] * 5 , candidate_labels=['A', 'B', 'C'] , batch_size=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , [ [ {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, ], [ {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, ], [ {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, ], [ {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, ], [ {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, ], ] , ) @require_tf def _UpperCamelCase ( self ) -> Tuple: snake_case_ = pipeline( model='hf-internal-testing/tiny-random-clip-zero-shot-image-classification' , framework='tf' ) snake_case_ = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) snake_case_ = image_classifier(__SCREAMING_SNAKE_CASE , candidate_labels=['a', 'b', 'c'] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , [{'score': 0.333, 'label': 'a'}, {'score': 0.333, 'label': 'b'}, {'score': 0.333, 'label': 'c'}] , ) snake_case_ = image_classifier([image] * 5 , candidate_labels=['A', 'B', 'C'] , batch_size=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , [ [ {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, ], [ {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, ], [ {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, ], [ {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, ], [ {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, {'score': 0.333, 'label': ANY(__SCREAMING_SNAKE_CASE )}, ], ] , ) @slow @require_torch def _UpperCamelCase ( self ) -> Any: snake_case_ = pipeline( task='zero-shot-image-classification' , model='openai/clip-vit-base-patch32' , ) # This is an image of 2 cats with remotes and no planes snake_case_ = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) snake_case_ = image_classifier(__SCREAMING_SNAKE_CASE , candidate_labels=['cat', 'plane', 'remote'] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , [ {'score': 0.511, 'label': 'remote'}, {'score': 0.485, 'label': 'cat'}, {'score': 0.004, 'label': 'plane'}, ] , ) snake_case_ = image_classifier([image] * 5 , candidate_labels=['cat', 'plane', 'remote'] , batch_size=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , [ [ {'score': 0.511, 'label': 'remote'}, {'score': 0.485, 'label': 'cat'}, {'score': 0.004, 'label': 'plane'}, ], ] * 5 , ) @slow @require_tf def _UpperCamelCase ( self ) -> Optional[Any]: snake_case_ = pipeline( task='zero-shot-image-classification' , model='openai/clip-vit-base-patch32' , framework='tf' ) # This is an image of 2 cats with remotes and no planes snake_case_ = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) snake_case_ = image_classifier(__SCREAMING_SNAKE_CASE , candidate_labels=['cat', 'plane', 'remote'] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , [ {'score': 0.511, 'label': 'remote'}, {'score': 0.485, 'label': 'cat'}, {'score': 0.004, 'label': 'plane'}, ] , ) snake_case_ = image_classifier([image] * 5 , candidate_labels=['cat', 'plane', 'remote'] , batch_size=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , [ [ {'score': 0.511, 'label': 'remote'}, {'score': 0.485, 'label': 'cat'}, {'score': 0.004, 'label': 'plane'}, ], ] * 5 , )
178
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch UpperCAmelCase : int = random.Random() def a__ ( a__ , a__=1.0 , a__=None , a__=None ): """simple docstring""" if rng is None: __SCREAMING_SNAKE_CASE = global_rng __SCREAMING_SNAKE_CASE = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : str=7 , __SCREAMING_SNAKE_CASE : List[str]=400 , __SCREAMING_SNAKE_CASE : Any=2_000 , __SCREAMING_SNAKE_CASE : List[str]=10 , __SCREAMING_SNAKE_CASE : Optional[int]=160 , __SCREAMING_SNAKE_CASE : List[str]=8 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.0 , __SCREAMING_SNAKE_CASE : Dict=4_000 , __SCREAMING_SNAKE_CASE : Optional[int]=False , __SCREAMING_SNAKE_CASE : List[Any]=True , ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = min_seq_length __SCREAMING_SNAKE_CASE = max_seq_length __SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = return_attention_mask __SCREAMING_SNAKE_CASE = do_normalize __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = chunk_length __SCREAMING_SNAKE_CASE = hop_length def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring""" return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Union[str, Any]: """simple docstring""" def _flatten(__SCREAMING_SNAKE_CASE : Dict ): return list(itertools.chain(*__SCREAMING_SNAKE_CASE ) ) if equal_length: __SCREAMING_SNAKE_CASE = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size __SCREAMING_SNAKE_CASE = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = WhisperFeatureExtractor if is_speech_available() else None def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = WhisperFeatureExtractionTester(self ) def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = os.path.join(__SCREAMING_SNAKE_CASE , """feat_extract.json""" ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] # Test feature size __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , padding="""max_length""" , return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input __SCREAMING_SNAKE_CASE = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test batched __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in (800, 800, 800)] __SCREAMING_SNAKE_CASE = np.asarray(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test truncation required __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] __SCREAMING_SNAKE_CASE = [x[: feature_extractor.n_samples] for x in speech_inputs] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs_truncated] __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" import torch __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = np.random.rand(100 , 32 ).astype(np.floataa ) __SCREAMING_SNAKE_CASE = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Tuple ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech __SCREAMING_SNAKE_CASE = ds.sort("""id""" ).select(range(__SCREAMING_SNAKE_CASE ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def UpperCAmelCase__ ( self : Tuple ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on __SCREAMING_SNAKE_CASE = self._load_datasamples(1 ) __SCREAMING_SNAKE_CASE = WhisperFeatureExtractor() __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).input_features self.assertEqual(input_features.shape , (1, 80, 3_000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) ) def UpperCAmelCase__ ( self : List[Any] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = self._load_datasamples(1 )[0] __SCREAMING_SNAKE_CASE = ((audio - audio.min()) / (audio.max() - audio.min())) * 65_535 # Rescale to [0, 65535] to show issue __SCREAMING_SNAKE_CASE = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(np.all(np.mean(__SCREAMING_SNAKE_CASE ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(__SCREAMING_SNAKE_CASE ) - 1 ) < 1E-3 ) )
267
0
from math import ceil def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : List[Any] = 1001 ) -> int: __lowercase = 1 for i in range(1 , int(ceil(n / 2.0 ) ) ): __lowercase = 2 * i + 1 __lowercase = 2 * i __lowercase = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: SCREAMING_SNAKE_CASE__ = int(sys.argv[1]) print(solution(n)) except ValueError: print("""Invalid entry - please enter a number""")
325
'''simple docstring''' from __future__ import annotations def a__ ( a__ , a__ , a__ ): """simple docstring""" if len(a__ ) == 0: raise ValueError("""find_max() arg is an empty sequence""" ) if ( left >= len(a__ ) or left < -len(a__ ) or right >= len(a__ ) or right < -len(a__ ) ): raise IndexError("""list index out of range""" ) if left == right: return nums[left] __SCREAMING_SNAKE_CASE = (left + right) >> 1 # the middle __SCREAMING_SNAKE_CASE = find_max(a__ , a__ , a__ ) # find max in range[left, mid] __SCREAMING_SNAKE_CASE = find_max(a__ , mid + 1 , a__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
267
0
'''simple docstring''' from itertools import count def a ( lowerCamelCase__ = 50 ): '''simple docstring''' A_ : str = [1] * min_block_length for n in count(a__ ): fill_count_functions.append(1 ) for block_length in range(a__ , n + 1 ): for block_start in range(n - block_length ): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_00_00_00: break return n if __name__ == "__main__": print(F"{solution() = }")
206
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) # Initialize Result __SCREAMING_SNAKE_CASE = [] # Traverse through all denomination for denomination in reversed(a__ ): # Find denominations while int(a__ ) >= int(a__ ): total_value -= int(a__ ) answer.append(a__ ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase : Dict = [] UpperCAmelCase : List[str] = '0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): UpperCAmelCase : List[str] = int(input('Enter the number of denominations you want to add: ').strip()) for i in range(0, n): denominations.append(int(input(f"""Denomination {i}: """).strip())) UpperCAmelCase : str = input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter UpperCAmelCase : int = [1, 2, 5, 1_0, 2_0, 5_0, 1_0_0, 5_0_0, 2_0_0_0] UpperCAmelCase : Any = input('Enter the change you want to make: ').strip() if int(value) == 0 or int(value) < 0: print('The total value cannot be zero or negative.') else: print(f"""Following is minimal change for {value}: """) UpperCAmelCase : Any = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
267
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase : Tuple = logging.get_logger(__name__) lowercase : Tuple = { 'junnyu/roformer_chinese_small': 'https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json', 'junnyu/roformer_chinese_base': 'https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json', 'junnyu/roformer_chinese_char_small': ( 'https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json' ), 'junnyu/roformer_chinese_char_base': ( 'https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json' ), 'junnyu/roformer_small_discriminator': ( 'https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json' ), 'junnyu/roformer_small_generator': ( 'https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json' ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class A ( __snake_case ): __magic_name__ = '''roformer''' def __init__( self , SCREAMING_SNAKE_CASE=50000 , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3072 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=1536 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-12 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=True , **SCREAMING_SNAKE_CASE , ) -> Optional[Any]: """simple docstring""" super().__init__(pad_token_id=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) A : Optional[int] = vocab_size A : str = hidden_size if embedding_size is None else embedding_size A : List[str] = hidden_size A : int = num_hidden_layers A : List[Any] = num_attention_heads A : int = hidden_act A : Tuple = intermediate_size A : List[Any] = hidden_dropout_prob A : Any = attention_probs_dropout_prob A : Dict = max_position_embeddings A : Optional[Any] = type_vocab_size A : List[str] = initializer_range A : Dict = layer_norm_eps A : List[str] = rotary_value A : int = use_cache class A ( __snake_case ): @property def __lowerCAmelCase ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": A : List[Any] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: A : Tuple = {0: '''batch''', 1: '''sequence'''} A : Any = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
3
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu UpperCAmelCase : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def a__ ( a__ , a__=None , a__=None , a__=None ): """simple docstring""" __SCREAMING_SNAKE_CASE = True while ask_again: __SCREAMING_SNAKE_CASE = input(a__ ) try: if default is not None and len(a__ ) == 0: return default return convert_value(a__ ) if convert_value is not None else result except Exception: if error_message is not None: print(a__ ) def a__ ( a__ , a__=[] , a__=None , a__=0 ): """simple docstring""" __SCREAMING_SNAKE_CASE = BulletMenu(a__ , a__ ) __SCREAMING_SNAKE_CASE = menu.run(default_choice=a__ ) return convert_value(a__ ) if convert_value is not None else result def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value] ) def a__ ( a__ ): """simple docstring""" return {"yes": True, "no": False}[value.lower()] class lowerCAmelCase__ ( argparse.RawDescriptionHelpFormatter ): """simple docstring""" def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = super()._format_usage(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = usage.replace("""<command> [<args>] """ , """""" ) return usage
267
0
class __A: def __init__( self , _snake_case , _snake_case , _snake_case ) -> Tuple: '''simple docstring''' __a = name __a = value __a = weight def __repr__( self ) -> Union[str, Any]: '''simple docstring''' return F"""{self.__class__.__name__}({self.name}, {self.value}, {self.weight})""" def SCREAMING_SNAKE_CASE_ ( self ) -> List[Any]: '''simple docstring''' return self.value def SCREAMING_SNAKE_CASE_ ( self ) -> str: '''simple docstring''' return self.name def SCREAMING_SNAKE_CASE_ ( self ) -> Union[str, Any]: '''simple docstring''' return self.weight def SCREAMING_SNAKE_CASE_ ( self ) -> Tuple: '''simple docstring''' return self.value / self.weight def __lowerCAmelCase ( a__ , a__ , a__ ) -> Any: __a = [] for i in range(len(a__ ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def __lowerCAmelCase ( a__ , a__ , a__ ) -> int: __a = sorted(a__ , key=a__ , reverse=a__ ) __a = [] __a , __a = 0.0, 0.0 for i in range(len(a__ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def __lowerCAmelCase ( ) -> Any: pass if __name__ == "__main__": import doctest doctest.testmod()
6
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) if n == 0: return 0 __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + naive_cut_rod_recursive(n - i , a__ ) ) return max_revue def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ ): """simple docstring""" if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , a__ , a__ ) , ) __SCREAMING_SNAKE_CASE = max_revenue return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] __SCREAMING_SNAKE_CASE = 0 for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max_rev[i] for j in range(1 , i + 1 ): __SCREAMING_SNAKE_CASE = max(a__ , prices[j - 1] + max_rev[i - j] ) __SCREAMING_SNAKE_CASE = max_revenue_i return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" if n < 0: __SCREAMING_SNAKE_CASE = F'n must be greater than or equal to 0. Got n = {n}' raise ValueError(a__ ) if n > len(a__ ): __SCREAMING_SNAKE_CASE = ( """Each integral piece of rod must have a corresponding price. """ F'Got n = {n} but length of prices = {len(a__ )}' ) raise ValueError(a__ ) def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = [6, 10, 12, 15, 20, 23] __SCREAMING_SNAKE_CASE = len(a__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __SCREAMING_SNAKE_CASE = 36 __SCREAMING_SNAKE_CASE = top_down_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = bottom_up_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = naive_cut_rod_recursive(a__ , a__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
267
0
"""simple docstring""" import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging __A = logging.get_logger(__name__) class UpperCAmelCase (_UpperCAmelCase ): """simple docstring""" _UpperCAmelCase :List[str] = "linear" _UpperCAmelCase :Dict = "cosine" _UpperCAmelCase :int = "cosine_with_restarts" _UpperCAmelCase :int = "polynomial" _UpperCAmelCase :Optional[Any] = "constant" _UpperCAmelCase :Optional[Any] = "constant_with_warmup" _UpperCAmelCase :Union[str, Any] = "piecewise_constant" def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase , __UpperCAmelCase = -1 ) -> Dict: return LambdaLR(a__ , lambda __UpperCAmelCase : 1 , last_epoch=a__ ) def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = -1 ) -> Any: def lr_lambda(__UpperCAmelCase ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1.0 , a__ ) ) return 1.0 return LambdaLR(a__ , a__ , last_epoch=a__ ) def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = -1 ) -> Optional[Any]: lowercase__: List[str] = {} lowercase__: str = step_rules.split(''',''' ) for rule_str in rule_list[:-1]: lowercase__, lowercase__: str = rule_str.split(''':''' ) lowercase__: List[str] = int(a__ ) lowercase__: int = float(a__ ) lowercase__: Optional[int] = value lowercase__: Optional[int] = float(rule_list[-1] ) def create_rules_function(__UpperCAmelCase , __UpperCAmelCase ): def rule_func(__UpperCAmelCase ) -> float: lowercase__: Optional[int] = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(a__ ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func lowercase__: List[str] = create_rules_function(a__ , a__ ) return LambdaLR(a__ , a__ , last_epoch=a__ ) def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase=-1 ) -> Union[str, Any]: def lr_lambda(__UpperCAmelCase ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(a__ , a__ , a__ ) def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = 0.5 , __UpperCAmelCase = -1 ) -> Optional[Any]: def lr_lambda(__UpperCAmelCase ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) lowercase__: List[Any] = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(a__ ) * 2.0 * progress )) ) return LambdaLR(a__ , a__ , a__ ) def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = 1 , __UpperCAmelCase = -1 ) -> Optional[int]: def lr_lambda(__UpperCAmelCase ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) lowercase__: Dict = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(a__ ) * progress) % 1.0) )) ) return LambdaLR(a__ , a__ , a__ ) def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase=1e-7 , __UpperCAmelCase=1.0 , __UpperCAmelCase=-1 ) -> Any: lowercase__: Optional[int] = optimizer.defaults['''lr'''] if not (lr_init > lr_end): raise ValueError(F"""lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})""" ) def lr_lambda(__UpperCAmelCase ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: lowercase__: List[str] = lr_init - lr_end lowercase__: Optional[Any] = num_training_steps - num_warmup_steps lowercase__: Union[str, Any] = 1 - (current_step - num_warmup_steps) / decay_steps lowercase__: List[str] = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(a__ , a__ , a__ ) __A = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = 1 , __UpperCAmelCase = 1.0 , __UpperCAmelCase = -1 , ) -> List[str]: lowercase__: Optional[int] = SchedulerType(a__ ) lowercase__: int = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(a__ , last_epoch=a__ ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(a__ , step_rules=a__ , last_epoch=a__ ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(F"""{name} requires `num_warmup_steps`, please provide that argument.""" ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(a__ , num_warmup_steps=a__ , last_epoch=a__ ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(F"""{name} requires `num_training_steps`, please provide that argument.""" ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , num_cycles=a__ , last_epoch=a__ , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , power=a__ , last_epoch=a__ , ) return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , last_epoch=a__ )
177
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : Union[str, Any] = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ 'SEW_PRETRAINED_MODEL_ARCHIVE_LIST', 'SEWForCTC', 'SEWForSequenceClassification', 'SEWModel', 'SEWPreTrainedModel', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys UpperCAmelCase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
267
0
import math import sys def lowercase ( SCREAMING_SNAKE_CASE__ : List[Any] ) -> Tuple: if number != int(a__ ): raise ValueError("""the value of input must be a natural number""" ) if number < 0: raise ValueError("""the value of input must not be a negative number""" ) if number == 0: return 1 _snake_case : str = [-1] * (number + 1) _snake_case : List[Any] = 0 for i in range(1 , number + 1 ): _snake_case : Optional[Any] = sys.maxsize _snake_case : Any = int(math.sqrt(a__ ) ) for j in range(1 , root + 1 ): _snake_case : Dict = 1 + answers[i - (j**2)] _snake_case : List[Any] = min(a__ , a__ ) _snake_case : List[Any] = answer return answers[number] if __name__ == "__main__": import doctest doctest.testmod()
317
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = name __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = weight def __repr__( self : str ) -> Union[str, Any]: """simple docstring""" return f'{self.__class__.__name__}({self.name}, {self.value}, {self.weight})' def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" return self.value def UpperCAmelCase__ ( self : Any ) -> str: """simple docstring""" return self.name def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.weight def UpperCAmelCase__ ( self : int ) -> Tuple: """simple docstring""" return self.value / self.weight def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = [] for i in range(len(a__ ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = sorted(a__ , key=a__ , reverse=a__ ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 0.0, 0.0 for i in range(len(a__ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def a__ ( ): """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
267
0
"""simple docstring""" import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss lowerCAmelCase_ = pytest.mark.integration @require_faiss class __A ( A_ ): '''simple docstring''' def UpperCAmelCase ( self : List[str] ) -> str: """simple docstring""" lowercase__ : Optional[int] = Dataset.from_dict({'''filename''': ['''my_name-train''' + '''_''' + str(__SCREAMING_SNAKE_CASE ) for x in np.arange(30 ).tolist()]} ) return dset def UpperCAmelCase ( self : str ) -> Optional[int]: """simple docstring""" import faiss lowercase__ : Optional[int] = self._create_dummy_dataset() lowercase__ : int = dset.map( lambda _snake_case ,_snake_case : {"vecs": i * np.ones(5 ,dtype=np.floataa )} ,with_indices=__SCREAMING_SNAKE_CASE ,keep_in_memory=__SCREAMING_SNAKE_CASE ) lowercase__ : str = dset.add_faiss_index('''vecs''' ,batch_size=100 ,metric_type=faiss.METRIC_INNER_PRODUCT ) lowercase__ , lowercase__ : Any = dset.get_nearest_examples('''vecs''' ,np.ones(5 ,dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] ,'''my_name-train_29''' ) dset.drop_index('''vecs''' ) def UpperCAmelCase ( self : List[str] ) -> Tuple: """simple docstring""" import faiss lowercase__ : List[Any] = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 ,1 ) ,index_name='''vecs''' ,batch_size=100 ,metric_type=faiss.METRIC_INNER_PRODUCT ,) lowercase__ , lowercase__ : Optional[int] = dset.get_nearest_examples('''vecs''' ,np.ones(5 ,dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] ,'''my_name-train_29''' ) def UpperCAmelCase ( self : int ) -> List[str]: """simple docstring""" import faiss lowercase__ : List[Any] = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 ,1 ) ,index_name='''vecs''' ,metric_type=faiss.METRIC_INNER_PRODUCT ,) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__SCREAMING_SNAKE_CASE ) as tmp_file: dset.save_faiss_index('''vecs''' ,tmp_file.name ) dset.load_faiss_index('''vecs2''' ,tmp_file.name ) os.unlink(tmp_file.name ) lowercase__ , lowercase__ : List[str] = dset.get_nearest_examples('''vecs2''' ,np.ones(5 ,dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] ,'''my_name-train_29''' ) def UpperCAmelCase ( self : Dict ) -> Union[str, Any]: """simple docstring""" lowercase__ : Tuple = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 ,1 ) ,index_name='''vecs''' ) dset.drop_index('''vecs''' ) self.assertRaises(__SCREAMING_SNAKE_CASE ,partial(dset.get_nearest_examples ,'''vecs2''' ,np.ones(5 ,dtype=np.floataa ) ) ) def UpperCAmelCase ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" from elasticsearch import Elasticsearch lowercase__ : List[Any] = self._create_dummy_dataset() with patch('''elasticsearch.Elasticsearch.search''' ) as mocked_search, patch( '''elasticsearch.client.IndicesClient.create''' ) as mocked_index_create, patch('''elasticsearch.helpers.streaming_bulk''' ) as mocked_bulk: lowercase__ : Tuple = {'''acknowledged''': True} mocked_bulk.return_value([(True, None)] * 30 ) lowercase__ : Any = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 29}]}} lowercase__ : Tuple = Elasticsearch() dset.add_elasticsearch_index('''filename''' ,es_client=__SCREAMING_SNAKE_CASE ) lowercase__ , lowercase__ : Any = dset.get_nearest_examples('''filename''' ,'''my_name-train_29''' ) self.assertEqual(examples['''filename'''][0] ,'''my_name-train_29''' ) @require_faiss class __A ( A_ ): '''simple docstring''' def UpperCAmelCase ( self : List[Any] ) -> int: """simple docstring""" import faiss lowercase__ : Tuple = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal ,5 ) index.add_vectors(np.zeros((5, 5) ,dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal ,10 ) # single query lowercase__ : str = np.zeros(5 ,dtype=np.floataa ) lowercase__ : Dict = 1 lowercase__ , lowercase__ : Tuple = index.search(__SCREAMING_SNAKE_CASE ) self.assertRaises(__SCREAMING_SNAKE_CASE ,index.search ,query.reshape(-1 ,1 ) ) self.assertGreater(scores[0] ,0 ) self.assertEqual(indices[0] ,1 ) # batched queries lowercase__ : Optional[int] = np.eye(5 ,dtype=np.floataa )[::-1] lowercase__ , lowercase__ : List[Any] = index.search_batch(__SCREAMING_SNAKE_CASE ) self.assertRaises(__SCREAMING_SNAKE_CASE ,index.search_batch ,queries[0] ) lowercase__ : Union[str, Any] = [scores[0] for scores in total_scores] lowercase__ : List[Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(__SCREAMING_SNAKE_CASE ) ,0 ) self.assertListEqual([4, 3, 2, 1, 0] ,__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self : List[Any] ) -> List[Any]: """simple docstring""" import faiss lowercase__ : Tuple = FaissIndex(string_factory='''Flat''' ) index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index ,faiss.IndexFlat ) lowercase__ : Any = FaissIndex(string_factory='''LSH''' ) index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index ,faiss.IndexLSH ) with self.assertRaises(__SCREAMING_SNAKE_CASE ): lowercase__ : Optional[int] = FaissIndex(string_factory='''Flat''' ,custom_index=faiss.IndexFlat(5 ) ) def UpperCAmelCase ( self : Optional[int] ) -> List[Any]: """simple docstring""" import faiss lowercase__ : Any = faiss.IndexFlat(5 ) lowercase__ : Tuple = FaissIndex(custom_index=__SCREAMING_SNAKE_CASE ) index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index ,faiss.IndexFlat ) def UpperCAmelCase ( self : Optional[Any] ) -> int: """simple docstring""" import faiss lowercase__ : Optional[Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__SCREAMING_SNAKE_CASE ) as tmp_file: index.save(tmp_file.name ) lowercase__ : List[Any] = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) lowercase__ : Optional[Any] = np.zeros(5 ,dtype=np.floataa ) lowercase__ : Union[str, Any] = 1 lowercase__ , lowercase__ : Optional[Any] = index.search(__SCREAMING_SNAKE_CASE ) self.assertGreater(scores[0] ,0 ) self.assertEqual(indices[0] ,1 ) @require_faiss def __UpperCAmelCase ( __lowerCamelCase ) -> int: import faiss lowercase__ : str = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) lowercase__ : Optional[Any] = '''index.faiss''' lowercase__ : Optional[Any] = f"""mock://{index_name}""" index.save(a__ , storage_options=mockfs.storage_options ) lowercase__ : Optional[Any] = FaissIndex.load(a__ , storage_options=mockfs.storage_options ) lowercase__ : List[Any] = np.zeros(5 , dtype=np.floataa ) lowercase__ : Dict = 1 lowercase__ , lowercase__ : Any = index.search(a__ ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class __A ( A_ ): '''simple docstring''' def UpperCAmelCase ( self : int ) -> int: """simple docstring""" from elasticsearch import Elasticsearch with patch('''elasticsearch.Elasticsearch.search''' ) as mocked_search, patch( '''elasticsearch.client.IndicesClient.create''' ) as mocked_index_create, patch('''elasticsearch.helpers.streaming_bulk''' ) as mocked_bulk: lowercase__ : Union[str, Any] = Elasticsearch() lowercase__ : int = {'''acknowledged''': True} lowercase__ : Dict = ElasticSearchIndex(es_client=__SCREAMING_SNAKE_CASE ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['''foo''', '''bar''', '''foobar'''] ) # single query lowercase__ : Union[str, Any] = '''foo''' lowercase__ : Optional[int] = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} lowercase__ , lowercase__ : Union[str, Any] = index.search(__SCREAMING_SNAKE_CASE ) self.assertEqual(scores[0] ,1 ) self.assertEqual(indices[0] ,0 ) # single query with timeout lowercase__ : Optional[int] = '''foo''' lowercase__ : Dict = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} lowercase__ , lowercase__ : List[str] = index.search(__SCREAMING_SNAKE_CASE ,request_timeout=30 ) self.assertEqual(scores[0] ,1 ) self.assertEqual(indices[0] ,0 ) # batched queries lowercase__ : int = ['''foo''', '''bar''', '''foobar'''] lowercase__ : List[str] = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} lowercase__ , lowercase__ : List[str] = index.search_batch(__SCREAMING_SNAKE_CASE ) lowercase__ : Optional[int] = [scores[0] for scores in total_scores] lowercase__ : int = [indices[0] for indices in total_indices] self.assertGreater(np.min(__SCREAMING_SNAKE_CASE ) ,0 ) self.assertListEqual([1, 1, 1] ,__SCREAMING_SNAKE_CASE ) # batched queries with timeout lowercase__ : List[str] = ['''foo''', '''bar''', '''foobar'''] lowercase__ : Union[str, Any] = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} lowercase__ , lowercase__ : str = index.search_batch(__SCREAMING_SNAKE_CASE ,request_timeout=30 ) lowercase__ : Union[str, Any] = [scores[0] for scores in total_scores] lowercase__ : Optional[int] = [indices[0] for indices in total_indices] self.assertGreater(np.min(__SCREAMING_SNAKE_CASE ) ,0 ) self.assertListEqual([1, 1, 1] ,__SCREAMING_SNAKE_CASE )
16
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE = ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on __SCREAMING_SNAKE_CASE = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) __SCREAMING_SNAKE_CASE = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] __SCREAMING_SNAKE_CASE = {"""unk_token""": """<unk>"""} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__SCREAMING_SNAKE_CASE ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48145466, 0.4578275, 0.40821073], """image_std""": [0.26862954, 0.26130258, 0.27577711], } __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , __SCREAMING_SNAKE_CASE ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> str: """simple docstring""" return CLIPTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple , **__SCREAMING_SNAKE_CASE : Any ) -> int: """simple docstring""" return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> List[str]: """simple docstring""" return CLIPImageProcessor.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(__SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_slow.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_fast.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) __SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = image_processor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) __SCREAMING_SNAKE_CASE = processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer(__SCREAMING_SNAKE_CASE ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase__ ( self : Dict ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(__SCREAMING_SNAKE_CASE ): processor() def UpperCAmelCase__ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE = processor.batch_decode(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
267
0
import inspect import re from hashlib import shaaaa from typing import Dict, List from .arrow import arrow from .audiofolder import audiofolder from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parquet import parquet from .sql import sql # noqa F401 from .text import text def UpperCAmelCase__ ( lowerCamelCase ): lowercase :Optional[Any] = [] for line in lines: lowercase :List[Any] = re.sub(r"#.*", "", a__ ) # remove comments if line: filtered_lines.append(a__ ) lowercase :int = "\n".join(a__ ) # Make a hash from all this code lowercase :Tuple = full_str.encode("utf-8" ) return shaaaa(a__ ).hexdigest() # get importable module names and hash for caching _UpperCAmelCase : Dict = { 'csv': (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())), 'json': (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())), 'pandas': (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())), 'parquet': (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())), 'arrow': (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())), 'text': (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())), 'imagefolder': (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())), 'audiofolder': (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())), } # Used to infer the module to use based on the data files extensions _UpperCAmelCase : str = { '.csv': ('csv', {}), '.tsv': ('csv', {'sep': '\t'}), '.json': ('json', {}), '.jsonl': ('json', {}), '.parquet': ('parquet', {}), '.arrow': ('arrow', {}), '.txt': ('text', {}), } _EXTENSION_TO_MODULE.update({ext: ("imagefolder", {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ("imagefolder", {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext: ("audiofolder", {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ("audiofolder", {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) _UpperCAmelCase : List[Any] = {'imagefolder', 'audiofolder'} # Used to filter data files based on extensions given a module name _UpperCAmelCase : Dict[str, List[str]] = {} for _ext, (_module, _) in _EXTENSION_TO_MODULE.items(): _MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext) _MODULE_TO_EXTENSIONS["imagefolder"].append(".zip") _MODULE_TO_EXTENSIONS["audiofolder"].append(".zip")
236
'''simple docstring''' import numpy as np def a__ ( a__ , a__ , a__ = 1E-1_2 , a__ = 1_00 , ): """simple docstring""" assert np.shape(a__ )[0] == np.shape(a__ )[1] # Ensure proper dimensionality. assert np.shape(a__ )[0] == np.shape(a__ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(a__ ) == np.iscomplexobj(a__ ) __SCREAMING_SNAKE_CASE = np.iscomplexobj(a__ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(a__ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 1E1_2 while not convergence: # Multiple matrix by the vector. __SCREAMING_SNAKE_CASE = np.dot(a__ , a__ ) # Normalize the resulting output vector. __SCREAMING_SNAKE_CASE = w / np.linalg.norm(a__ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __SCREAMING_SNAKE_CASE = vector.conj().T if is_complex else vector.T __SCREAMING_SNAKE_CASE = np.dot(a__ , np.dot(a__ , a__ ) ) # Check convergence. __SCREAMING_SNAKE_CASE = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = lambda_ if is_complex: __SCREAMING_SNAKE_CASE = np.real(lambda_ ) return lambda_, vector def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ) __SCREAMING_SNAKE_CASE = real_input_matrix.astype(np.complexaaa ) __SCREAMING_SNAKE_CASE = np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __SCREAMING_SNAKE_CASE = real_input_matrix __SCREAMING_SNAKE_CASE = real_vector elif problem_type == "complex": __SCREAMING_SNAKE_CASE = complex_input_matrix __SCREAMING_SNAKE_CASE = complex_vector # Our implementation. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = power_iteration(a__ , a__ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = np.linalg.eigh(a__ ) # Last eigenvalue is the maximum one. __SCREAMING_SNAKE_CASE = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __SCREAMING_SNAKE_CASE = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(a__ ) - np.abs(a__ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
267
0
'''simple docstring''' from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable a__ : str = { 'configuration_gpt_neox_japanese': ['GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GPTNeoXJapaneseConfig'], 'tokenization_gpt_neox_japanese': ['GPTNeoXJapaneseTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Dict = [ 'GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST', 'GPTNeoXJapaneseForCausalLM', 'GPTNeoXJapaneseLayer', 'GPTNeoXJapaneseModel', 'GPTNeoXJapanesePreTrainedModel', ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys a__ : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
349
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( a , a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = StableDiffusionInpaintPipeline lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowerCAmelCase__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowerCAmelCase__ = frozenset([] ) def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = PNDMScheduler(skip_prk_steps=__SCREAMING_SNAKE_CASE ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) __SCREAMING_SNAKE_CASE = CLIPTextModel(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __SCREAMING_SNAKE_CASE = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any]=0 ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 )[0] __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE ) ).convert("""RGB""" ).resize((64, 64) ) __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): __SCREAMING_SNAKE_CASE = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = """cpu""" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe.to(__SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe(**__SCREAMING_SNAKE_CASE ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __SCREAMING_SNAKE_CASE = np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : List[str] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained(__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def UpperCAmelCase__ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , safety_checker=__SCREAMING_SNAKE_CASE , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def UpperCAmelCase__ ( self : Tuple ) -> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = PNDMScheduler.from_pretrained(__SCREAMING_SNAKE_CASE , subfolder="""scheduler""" ) __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
267
0
def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ ) -> int: '''simple docstring''' if not isinstance(a__ , a__ ): raise TypeError('''only integers accepted as input''' ) else: UpperCAmelCase = str(abs(a__ ) ) UpperCAmelCase = [list(a__ ) for char in range(len(a__ ) )] for index in range(len(a__ ) ): num_transpositions[index].pop(a__ ) return max( int(''''''.join(list(a__ ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__("doctest").testmod()
273
'''simple docstring''' from itertools import count def a__ ( a__ = 50 ): """simple docstring""" __SCREAMING_SNAKE_CASE = [1] * min_block_length for n in count(a__ ): fill_count_functions.append(1 ) for block_length in range(a__ , n + 1 ): for block_start in range(n - block_length ): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_00_00_00: break return n if __name__ == "__main__": print(f"""{solution() = }""")
267
0
import numpy as np import pandas as pd from sklearn.preprocessing import Normalizer from sklearn.svm import SVR from statsmodels.tsa.statespace.sarimax import SARIMAX def __UpperCAmelCase ( a_ , a_ , a_ , a_ , a_): snake_case_ = np.array([[1, item, train_mtch[i]] for i, item in enumerate(a__)]) snake_case_ = np.array(a__) snake_case_ = np.dot(np.dot(np.linalg.inv(np.dot(x.transpose() , a__)) , x.transpose()) , a__) return abs(beta[0] + test_dt[0] * beta[1] + test_mtch[0] + beta[2]) def __UpperCAmelCase ( a_ , a_ , a_): snake_case_ = (1, 2, 1) snake_case_ = (1, 1, 0, 7) snake_case_ = SARIMAX( a__ , exog=a__ , order=a__ , seasonal_order=a__) snake_case_ = model.fit(disp=a__ , maxiter=6_00 , method='nm') snake_case_ = model_fit.predict(1 , len(a__) , exog=[test_match]) return result[0] def __UpperCAmelCase ( a_ , a_ , a_): snake_case_ = SVR(kernel='rbf' , C=1 , gamma=0.1 , epsilon=0.1) regressor.fit(a__ , a__) snake_case_ = regressor.predict(a__) return y_pred[0] def __UpperCAmelCase ( a_): train_user.sort() snake_case_ = np.percentile(a__ , 25) snake_case_ = np.percentile(a__ , 75) snake_case_ = qa - qa snake_case_ = qa - (iqr * 0.1) return low_lim def __UpperCAmelCase ( a_ , a_): snake_case_ = 0 snake_case_ = 0 for i in list_vote: if i > actual_result: snake_case_ = not_safe + 1 else: if abs(abs(a__) - abs(a__)) <= 0.1: safe += 1 else: not_safe += 1 return safe > not_safe if __name__ == "__main__": # data_input_df = pd.read_csv("ex_data.csv", header=None) lowercase = [[18231, 0.0, 1], [22621, 1.0, 2], [15675, 0.0, 3], [23583, 1.0, 4]] lowercase = pd.DataFrame( data_input, columns=["total_user", "total_even", "days"] ) lowercase = Normalizer().fit_transform(data_input_df.values) # split data lowercase = normalize_df[:, 2].tolist() lowercase = normalize_df[:, 0].tolist() lowercase = normalize_df[:, 1].tolist() # for svr (input variable = total date and total match) lowercase = normalize_df[:, [1, 2]].tolist() lowercase = x[: len(x) - 1] lowercase = x[len(x) - 1 :] # for linear regression & sarimax lowercase = total_date[: len(total_date) - 1] lowercase = total_user[: len(total_user) - 1] lowercase = total_match[: len(total_match) - 1] lowercase = total_date[len(total_date) - 1 :] lowercase = total_user[len(total_user) - 1 :] lowercase = total_match[len(total_match) - 1 :] # voting system with forecasting lowercase = [ linear_regression_prediction( trn_date, trn_user, trn_match, tst_date, tst_match ), sarimax_predictor(trn_user, trn_match, tst_match), support_vector_regressor(x_train, x_test, trn_user), ] # check the safety of today's data lowercase = '' if data_safety_checker(res_vote, tst_user) else 'not ' print("Today\'s data is {not_str}safe.")
178
'''simple docstring''' import logging import os import threading import time try: import warnings except ImportError: UpperCAmelCase : Optional[Any] = None try: import msvcrt except ImportError: UpperCAmelCase : List[Any] = None try: import fcntl except ImportError: UpperCAmelCase : int = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: UpperCAmelCase : Union[str, Any] = OSError # Data # ------------------------------------------------ UpperCAmelCase : List[Any] = [ 'Timeout', 'BaseFileLock', 'WindowsFileLock', 'UnixFileLock', 'SoftFileLock', 'FileLock', ] UpperCAmelCase : Tuple = '3.0.12' UpperCAmelCase : str = None def a__ ( ): """simple docstring""" global _logger __SCREAMING_SNAKE_CASE = _logger or logging.getLogger(__name__ ) return _logger class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock_file return None def __str__( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = f'The file lock \'{self.lock_file}\' could not be acquired.' return temp class lowerCAmelCase__ : """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock return None def __enter__( self : List[str] ) -> List[Any]: """simple docstring""" return self.lock def __exit__( self : Tuple , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[str]: """simple docstring""" self.lock.release() return None class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = max_filename_length if max_filename_length is not None else 255 # Hash the filename if it's too long __SCREAMING_SNAKE_CASE = self.hash_filename_if_too_long(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # The path to the lock file. __SCREAMING_SNAKE_CASE = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. __SCREAMING_SNAKE_CASE = None # The default timeout value. __SCREAMING_SNAKE_CASE = timeout # We use this lock primarily for the lock counter. __SCREAMING_SNAKE_CASE = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. __SCREAMING_SNAKE_CASE = 0 return None @property def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" return self._lock_file @property def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" return self._timeout @timeout.setter def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = float(__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" raise NotImplementedError() def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" raise NotImplementedError() @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" return self._lock_file_fd is not None def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=None , __SCREAMING_SNAKE_CASE : Optional[int]=0.05 ) -> Optional[Any]: """simple docstring""" if timeout is None: __SCREAMING_SNAKE_CASE = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file __SCREAMING_SNAKE_CASE = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(f'Attempting to acquire lock {lock_id} on {lock_filename}' ) self._acquire() if self.is_locked: logger().debug(f'Lock {lock_id} acquired on {lock_filename}' ) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(f'Timeout on acquiring lock {lock_id} on {lock_filename}' ) raise Timeout(self._lock_file ) else: logger().debug( f'Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...' ) time.sleep(__SCREAMING_SNAKE_CASE ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: __SCREAMING_SNAKE_CASE = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Dict: """simple docstring""" with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file logger().debug(f'Attempting to release lock {lock_id} on {lock_filename}' ) self._release() __SCREAMING_SNAKE_CASE = 0 logger().debug(f'Lock {lock_id} released on {lock_filename}' ) return None def __enter__( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" self.acquire() return self def __exit__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" self.release() return None def __del__( self : str ) -> Union[str, Any]: """simple docstring""" self.release(force=__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = os.path.basename(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > max_length and max_length > 0: __SCREAMING_SNAKE_CASE = os.path.dirname(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = str(hash(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = filename[: max_length - len(__SCREAMING_SNAKE_CASE ) - 8] + """...""" + hashed_filename + """.lock""" return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: return path class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Dict=-1 , __SCREAMING_SNAKE_CASE : Dict=None ) -> List[Any]: """simple docstring""" from .file_utils import relative_to_absolute_path super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """\\\\?\\""" + relative_to_absolute_path(self.lock_file ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: try: msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_UNLCK , 1 ) os.close(__SCREAMING_SNAKE_CASE ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any]=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = os.statvfs(os.path.dirname(__SCREAMING_SNAKE_CASE ) ).f_namemax super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) try: fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_UN ) os.close(__SCREAMING_SNAKE_CASE ) return None class lowerCAmelCase__ ( a ): """simple docstring""" def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : int ) -> Optional[int]: """simple docstring""" os.close(self._lock_file_fd ) __SCREAMING_SNAKE_CASE = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None UpperCAmelCase : Dict = None if msvcrt: UpperCAmelCase : Optional[int] = WindowsFileLock elif fcntl: UpperCAmelCase : Optional[Any] = UnixFileLock else: UpperCAmelCase : int = SoftFileLock if warnings is not None: warnings.warn('only soft file lock is available')
267
0
import shutil import tempfile import unittest from transformers import ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, NllbTokenizer, NllbTokenizerFast, is_torch_available, ) from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ = get_tests_dir("""fixtures/test_sentencepiece.model""") if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right SCREAMING_SNAKE_CASE__ = 25_6047 SCREAMING_SNAKE_CASE__ = 25_6145 @require_sentencepiece @require_tokenizers class A__ ( lowerCAmelCase__ , unittest.TestCase ): lowerCAmelCase__ : Any = NllbTokenizer lowerCAmelCase__ : Tuple = NllbTokenizerFast lowerCAmelCase__ : str = True lowerCAmelCase__ : str = True lowerCAmelCase__ : Optional[Any] = {} def a__ ( self : List[Any] ) -> int: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __lowercase = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def a__ ( self : Dict ) -> Any: """simple docstring""" __lowercase = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) __lowercase = tokenizer.tokenize('This is a test' ) self.assertListEqual(__SCREAMING_SNAKE_CASE , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) __lowercase = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) __lowercase = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) __lowercase = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) def a__ ( self : Dict ) -> Any: """simple docstring""" __lowercase = (self.rust_tokenizer_class, 'hf-internal-testing/tiny-random-nllb', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __lowercase = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __lowercase = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __lowercase = tempfile.mkdtemp() __lowercase = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE ) __lowercase = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) __lowercase = tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __lowercase = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __lowercase = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=True __lowercase = tempfile.mkdtemp() __lowercase = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __lowercase = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __lowercase = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __lowercase = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=False __lowercase = tempfile.mkdtemp() __lowercase = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __lowercase = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __lowercase = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __lowercase = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) @require_torch def a__ ( self : List[Any] ) -> Any: """simple docstring""" if not self.test_seqaseq: return __lowercase = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f"""{tokenizer.__class__.__name__}""" ): # Longer text that will definitely require truncation. __lowercase = [ ' UN Chief Says There Is No Military Solution in Syria', ' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for' ' Syria is that \'there is no military solution\' to the nearly five-year conflict and more weapons' ' will only worsen the violence and misery for millions of people.', ] __lowercase = [ 'Şeful ONU declară că nu există o soluţie militară în Siria', 'Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al' ' Rusiei pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi' ' că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.', ] try: __lowercase = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors='pt' , src_lang='eng_Latn' , tgt_lang='ron_Latn' , ) except NotImplementedError: return self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 10 ) # max_target_length will default to max_length if not specified __lowercase = tokenizer.prepare_seqaseq_batch( __SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors='pt' ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 3 ) __lowercase = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors='pt' ) self.assertEqual(batch_encoder_only.input_ids.shape[1] , 3 ) self.assertEqual(batch_encoder_only.attention_mask.shape[1] , 3 ) self.assertNotIn('decoder_input_ids' , __SCREAMING_SNAKE_CASE ) @unittest.skip('Unfortunately way too slow to build a BPE with SentencePiece.' ) def a__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" pass def a__ ( self : List[str] ) -> Dict: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __lowercase = [AddedToken('<special>' , lstrip=__SCREAMING_SNAKE_CASE )] __lowercase = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __lowercase = tokenizer_r.encode('Hey this is a <special> token' ) __lowercase = tokenizer_r.encode('<special>' , add_special_tokens=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(special_token_id in r_output ) if self.test_slow_tokenizer: __lowercase = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) __lowercase = self.tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __lowercase = tokenizer_p.encode('Hey this is a <special> token' ) __lowercase = tokenizer_cr.encode('Hey this is a <special> token' ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertTrue(special_token_id in p_output ) self.assertTrue(special_token_id in cr_output ) @require_torch @require_sentencepiece @require_tokenizers class A__ ( unittest.TestCase ): lowerCAmelCase__ : List[str] = "facebook/nllb-200-distilled-600M" lowerCAmelCase__ : Optional[Any] = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] lowerCAmelCase__ : Union[str, Any] = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] lowerCAmelCase__ : Optional[int] = [ 256047, 16297, 134408, 8165, 248066, 14734, 950, 1135, 105721, 3573, 83, 27352, 108, 49486, 2, ] @classmethod def a__ ( cls : List[Any] ) -> Any: """simple docstring""" __lowercase = NllbTokenizer.from_pretrained( cls.checkpoint_name , src_lang='eng_Latn' , tgt_lang='ron_Latn' ) __lowercase = 1 return cls def a__ ( self : Union[str, Any] ) -> List[str]: """simple docstring""" self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ace_Arab'] , 25_60_01 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ace_Latn'] , 25_60_02 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['fra_Latn'] , 25_60_57 ) def a__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" __lowercase = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) def a__ ( self : Any ) -> int: """simple docstring""" self.assertIn(__SCREAMING_SNAKE_CASE , self.tokenizer.all_special_ids ) # fmt: off __lowercase = [RO_CODE, 42_54, 9_80_68, 11_29_23, 3_90_72, 39_09, 7_13, 10_27_67, 26, 1_73_14, 3_56_42, 1_46_83, 3_31_18, 20_22, 6_69_87, 2, 25_60_47] # fmt: on __lowercase = self.tokenizer.decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) __lowercase = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertNotIn(self.tokenizer.eos_token , __SCREAMING_SNAKE_CASE ) def a__ ( self : Optional[Any] ) -> Any: """simple docstring""" __lowercase = ['this is gunna be a long sentence ' * 20] assert isinstance(src_text[0] , __SCREAMING_SNAKE_CASE ) __lowercase = 10 __lowercase = self.tokenizer(__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ).input_ids[0] self.assertEqual(ids[-1] , 2 ) self.assertEqual(ids[0] , __SCREAMING_SNAKE_CASE ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def a__ ( self : int ) -> List[Any]: """simple docstring""" self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['<mask>', 'ar_AR'] ) , [25_62_03, 3] ) def a__ ( self : str ) -> Optional[int]: """simple docstring""" __lowercase = tempfile.mkdtemp() __lowercase = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) __lowercase = NllbTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __SCREAMING_SNAKE_CASE ) @require_torch def a__ ( self : str ) -> List[Any]: """simple docstring""" __lowercase = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=len(self.expected_src_tokens ) , return_tensors='pt' , ) __lowercase = shift_tokens_right( batch['labels'] , self.tokenizer.pad_token_id , self.tokenizer.lang_code_to_id['ron_Latn'] ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual((2, 15) , batch.input_ids.shape ) self.assertEqual((2, 15) , batch.attention_mask.shape ) __lowercase = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , batch.decoder_input_ids[0, 0] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def a__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __lowercase = self.tokenizer(self.src_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors='pt' ) __lowercase = self.tokenizer( text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=10 , return_tensors='pt' ) __lowercase = targets['input_ids'] __lowercase = shift_tokens_right( __SCREAMING_SNAKE_CASE , self.tokenizer.pad_token_id , decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] , ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def a__ ( self : int ) -> str: """simple docstring""" __lowercase = self.tokenizer._build_translation_inputs( 'A test' , return_tensors='pt' , src_lang='eng_Latn' , tgt_lang='fra_Latn' ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , { # A, test, EOS, en_XX 'input_ids': [[25_60_47, 70, 73_56, 2]], 'attention_mask': [[1, 1, 1, 1]], # ar_AR 'forced_bos_token_id': 25_60_57, } , ) @require_torch def a__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" __lowercase = True __lowercase = self.tokenizer( 'UN Chief says there is no military solution in Syria' , src_lang='eng_Latn' , tgt_lang='fra_Latn' ) self.assertEqual( inputs.input_ids , [1_62_97, 13_44_08, 2_56_53, 63_70, 2_48, 2_54, 10_39_29, 9_49_95, 1_08, 4_94_86, 2, 25_60_47] ) __lowercase = False __lowercase = self.tokenizer( 'UN Chief says there is no military solution in Syria' , src_lang='eng_Latn' , tgt_lang='fra_Latn' ) self.assertEqual( inputs.input_ids , [25_60_47, 1_62_97, 13_44_08, 2_56_53, 63_70, 2_48, 2_54, 10_39_29, 9_49_95, 1_08, 4_94_86, 2] )
325
'''simple docstring''' import shutil import tempfile import unittest from transformers import ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, NllbTokenizer, NllbTokenizerFast, is_torch_available, ) from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right UpperCAmelCase : Optional[int] = 2_5_6_0_4_7 UpperCAmelCase : Union[str, Any] = 2_5_6_1_4_5 @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = NllbTokenizer lowerCAmelCase__ = NllbTokenizerFast lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = {} def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__SCREAMING_SNAKE_CASE , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-nllb""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) __SCREAMING_SNAKE_CASE = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=True __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=False __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : List[Any] ) -> Any: """simple docstring""" if not self.test_seqaseq: return __SCREAMING_SNAKE_CASE = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Longer text that will definitely require truncation. __SCREAMING_SNAKE_CASE = [ """ UN Chief Says There Is No Military Solution in Syria""", """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for""" """ Syria is that 'there is no military solution' to the nearly five-year conflict and more weapons""" """ will only worsen the violence and misery for millions of people.""", ] __SCREAMING_SNAKE_CASE = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", """Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al""" """ Rusiei pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi""" """ că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""", ] try: __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" , ) except NotImplementedError: return self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 10 ) # max_target_length will default to max_length if not specified __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( __SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 3 ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" ) self.assertEqual(batch_encoder_only.input_ids.shape[1] , 3 ) self.assertEqual(batch_encoder_only.attention_mask.shape[1] , 3 ) self.assertNotIn("""decoder_input_ids""" , __SCREAMING_SNAKE_CASE ) @unittest.skip("""Unfortunately way too slow to build a BPE with SentencePiece.""" ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" pass def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = [AddedToken("""<special>""" , lstrip=__SCREAMING_SNAKE_CASE )] __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""<special>""" , add_special_tokens=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(special_token_id in r_output ) if self.test_slow_tokenizer: __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_cr.encode("""Hey this is a <special> token""" ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertTrue(special_token_id in p_output ) self.assertTrue(special_token_id in cr_output ) @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = "facebook/nllb-200-distilled-600M" lowerCAmelCase__ = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] lowerCAmelCase__ = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] lowerCAmelCase__ = [ 256047, 16297, 134408, 8165, 248066, 14734, 950, 1135, 105721, 3573, 83, 27352, 108, 49486, 2, ] @classmethod def UpperCAmelCase__ ( cls : List[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" ) __SCREAMING_SNAKE_CASE = 1 return cls def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[str]: """simple docstring""" self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Arab"""] , 256_001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Latn"""] , 256_002 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""fra_Latn"""] , 256_057 ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" self.assertIn(__SCREAMING_SNAKE_CASE , self.tokenizer.all_special_ids ) # fmt: off __SCREAMING_SNAKE_CASE = [RO_CODE, 4_254, 98_068, 112_923, 39_072, 3_909, 713, 102_767, 26, 17_314, 35_642, 14_683, 33_118, 2_022, 66_987, 2, 256_047] # fmt: on __SCREAMING_SNAKE_CASE = self.tokenizer.decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertNotIn(self.tokenizer.eos_token , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = ["""this is gunna be a long sentence """ * 20] assert isinstance(src_text[0] , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = 10 __SCREAMING_SNAKE_CASE = self.tokenizer(__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ).input_ids[0] self.assertEqual(ids[-1] , 2 ) self.assertEqual(ids[0] , __SCREAMING_SNAKE_CASE ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> List[Any]: """simple docstring""" self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [256_203, 3] ) def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) __SCREAMING_SNAKE_CASE = shift_tokens_right( batch["""labels"""] , self.tokenizer.pad_token_id , self.tokenizer.lang_code_to_id["""ron_Latn"""] ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual((2, 15) , batch.input_ids.shape ) self.assertEqual((2, 15) , batch.attention_mask.shape ) __SCREAMING_SNAKE_CASE = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , batch.decoder_input_ids[0, 0] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = self.tokenizer( text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=10 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = targets["""input_ids"""] __SCREAMING_SNAKE_CASE = shift_tokens_right( __SCREAMING_SNAKE_CASE , self.tokenizer.pad_token_id , decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] , ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , { # A, test, EOS, en_XX """input_ids""": [[256_047, 70, 7_356, 2]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 256_057, } , ) @require_torch def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2, 256_047] ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [256_047, 16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2] )
267
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import ( DiffusionPipeline, UnCLIPImageVariationPipeline, UnCLIPScheduler, UNetaDConditionModel, UNetaDModel, ) from diffusers.pipelines.unclip.text_proj import UnCLIPTextProjModel from diffusers.utils import floats_tensor, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, load_image, require_torch_gpu, skip_mps from ..pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class _lowerCAmelCase ( __UpperCAmelCase , unittest.TestCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = UnCLIPImageVariationPipeline __SCREAMING_SNAKE_CASE : Optional[int] = IMAGE_VARIATION_PARAMS - {'height', 'width', 'guidance_scale'} __SCREAMING_SNAKE_CASE : Optional[int] = IMAGE_VARIATION_BATCH_PARAMS __SCREAMING_SNAKE_CASE : Optional[Any] = [ 'generator', 'return_dict', 'decoder_num_inference_steps', 'super_res_num_inference_steps', ] __SCREAMING_SNAKE_CASE : Optional[int] = False @property def _a (self ): return 32 @property def _a (self ): return 32 @property def _a (self ): return self.time_input_dim @property def _a (self ): return self.time_input_dim * 4 @property def _a (self ): return 100 @property def _a (self ): A_ : List[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) return tokenizer @property def _a (self ): torch.manual_seed(0 ) A_ : Any = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__SCREAMING_SNAKE_CASE ) @property def _a (self ): torch.manual_seed(0 ) A_ : Any = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) return CLIPVisionModelWithProjection(__SCREAMING_SNAKE_CASE ) @property def _a (self ): torch.manual_seed(0 ) A_ : Optional[int] = { """clip_embeddings_dim""": self.text_embedder_hidden_size, """time_embed_dim""": self.time_embed_dim, """cross_attention_dim""": self.cross_attention_dim, } A_ : Any = UnCLIPTextProjModel(**__SCREAMING_SNAKE_CASE ) return model @property def _a (self ): torch.manual_seed(0 ) A_ : str = { """sample_size""": 32, # RGB in channels """in_channels""": 3, # Out channels is double in channels because predicts mean and variance """out_channels""": 6, """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": """identity""", } A_ : Tuple = UNetaDConditionModel(**__SCREAMING_SNAKE_CASE ) return model @property def _a (self ): return { "sample_size": 64, "layers_per_block": 1, "down_block_types": ("ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D"), "up_block_types": ("ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D"), "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "in_channels": 6, "out_channels": 3, } @property def _a (self ): torch.manual_seed(0 ) A_ : int = UNetaDModel(**self.dummy_super_res_kwargs ) return model @property def _a (self ): torch.manual_seed(1 ) A_ : Tuple = UNetaDModel(**self.dummy_super_res_kwargs ) return model def _a (self ): A_ : List[Any] = self.dummy_decoder A_ : Optional[Any] = self.dummy_text_proj A_ : int = self.dummy_text_encoder A_ : List[str] = self.dummy_tokenizer A_ : int = self.dummy_super_res_first A_ : List[str] = self.dummy_super_res_last A_ : int = UnCLIPScheduler( variance_type="""learned_range""" , prediction_type="""epsilon""" , num_train_timesteps=1000 , ) A_ : Dict = UnCLIPScheduler( variance_type="""fixed_small_log""" , prediction_type="""epsilon""" , num_train_timesteps=1000 , ) A_ : Tuple = CLIPImageProcessor(crop_size=32 , size=32 ) A_ : List[Any] = self.dummy_image_encoder return { "decoder": decoder, "text_encoder": text_encoder, "tokenizer": tokenizer, "text_proj": text_proj, "feature_extractor": feature_extractor, "image_encoder": image_encoder, "super_res_first": super_res_first, "super_res_last": super_res_last, "decoder_scheduler": decoder_scheduler, "super_res_scheduler": super_res_scheduler, } def _a (self , lowercase , lowercase=0 , lowercase=True ): A_ : Optional[int] = floats_tensor((1, 3, 32, 32) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): A_ : List[Any] = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: A_ : int = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) if pil_image: A_ : List[str] = input_image * 0.5 + 0.5 A_ : Optional[Any] = input_image.clamp(0 , 1 ) A_ : str = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() A_ : Optional[Any] = DiffusionPipeline.numpy_to_pil(__SCREAMING_SNAKE_CASE )[0] return { "image": input_image, "generator": generator, "decoder_num_inference_steps": 2, "super_res_num_inference_steps": 2, "output_type": "np", } def _a (self ): A_ : str = """cpu""" A_ : Any = self.get_dummy_components() A_ : Union[str, Any] = self.pipeline_class(**__SCREAMING_SNAKE_CASE ) A_ : Optional[Any] = pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) A_ : str = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE , pil_image=__SCREAMING_SNAKE_CASE ) A_ : Union[str, Any] = pipe(**__SCREAMING_SNAKE_CASE ) A_ : Union[str, Any] = output.images A_ : Optional[int] = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE , pil_image=__SCREAMING_SNAKE_CASE ) A_ : Dict = pipe( **__SCREAMING_SNAKE_CASE , return_dict=__SCREAMING_SNAKE_CASE , )[0] A_ : int = image[0, -3:, -3:, -1] A_ : str = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) A_ : int = np.array( [ 0.99_97, 0.00_02, 0.99_97, 0.99_97, 0.99_69, 0.00_23, 0.99_97, 0.99_69, 0.99_70, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def _a (self ): A_ : str = """cpu""" A_ : Optional[Any] = self.get_dummy_components() A_ : str = self.pipeline_class(**__SCREAMING_SNAKE_CASE ) A_ : Dict = pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) A_ : Union[str, Any] = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE , pil_image=__SCREAMING_SNAKE_CASE ) A_ : Any = pipe(**__SCREAMING_SNAKE_CASE ) A_ : List[str] = output.images A_ : List[str] = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE , pil_image=__SCREAMING_SNAKE_CASE ) A_ : Dict = pipe( **__SCREAMING_SNAKE_CASE , return_dict=__SCREAMING_SNAKE_CASE , )[0] A_ : Union[str, Any] = image[0, -3:, -3:, -1] A_ : List[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) A_ : Union[str, Any] = np.array([0.99_97, 0.00_03, 0.99_97, 0.99_97, 0.99_70, 0.00_24, 0.99_97, 0.99_71, 0.99_71] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def _a (self ): A_ : List[Any] = """cpu""" A_ : Optional[Any] = self.get_dummy_components() A_ : List[str] = self.pipeline_class(**__SCREAMING_SNAKE_CASE ) A_ : int = pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) A_ : Union[str, Any] = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE , pil_image=__SCREAMING_SNAKE_CASE ) A_ : int = [ pipeline_inputs["""image"""], pipeline_inputs["""image"""], ] A_ : List[str] = pipe(**__SCREAMING_SNAKE_CASE ) A_ : Union[str, Any] = output.images A_ : Optional[int] = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE , pil_image=__SCREAMING_SNAKE_CASE ) A_ : int = [ tuple_pipeline_inputs["""image"""], tuple_pipeline_inputs["""image"""], ] A_ : List[Any] = pipe( **__SCREAMING_SNAKE_CASE , return_dict=__SCREAMING_SNAKE_CASE , )[0] A_ : List[Any] = image[0, -3:, -3:, -1] A_ : int = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (2, 64, 64, 3) A_ : str = np.array( [ 0.99_97, 0.99_89, 0.00_08, 0.00_21, 0.99_60, 0.00_18, 0.00_14, 0.00_02, 0.99_33, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def _a (self ): A_ : Dict = torch.device("""cpu""" ) class _lowerCAmelCase : __SCREAMING_SNAKE_CASE : Optional[Any] = 1 A_ : Tuple = self.get_dummy_components() A_ : Optional[Any] = self.pipeline_class(**__SCREAMING_SNAKE_CASE ) A_ : Union[str, Any] = pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) A_ : Optional[Any] = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(0 ) A_ : Tuple = pipe.decoder.dtype A_ : Any = 1 A_ : List[str] = ( batch_size, pipe.decoder.config.in_channels, pipe.decoder.config.sample_size, pipe.decoder.config.sample_size, ) A_ : List[Any] = pipe.prepare_latents( __SCREAMING_SNAKE_CASE , dtype=__SCREAMING_SNAKE_CASE , device=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , latents=__SCREAMING_SNAKE_CASE , scheduler=DummyScheduler() ) A_ : Tuple = ( batch_size, pipe.super_res_first.config.in_channels // 2, pipe.super_res_first.config.sample_size, pipe.super_res_first.config.sample_size, ) A_ : str = pipe.prepare_latents( __SCREAMING_SNAKE_CASE , dtype=__SCREAMING_SNAKE_CASE , device=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , latents=__SCREAMING_SNAKE_CASE , scheduler=DummyScheduler() ) A_ : Optional[Any] = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE , pil_image=__SCREAMING_SNAKE_CASE ) A_ : Tuple = pipe( **__SCREAMING_SNAKE_CASE , decoder_latents=__SCREAMING_SNAKE_CASE , super_res_latents=__SCREAMING_SNAKE_CASE ).images A_ : Optional[int] = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE , pil_image=__SCREAMING_SNAKE_CASE ) # Don't pass image, instead pass embedding A_ : List[str] = pipeline_inputs.pop("""image""" ) A_ : Tuple = pipe.image_encoder(__SCREAMING_SNAKE_CASE ).image_embeds A_ : Optional[Any] = pipe( **__SCREAMING_SNAKE_CASE , decoder_latents=__SCREAMING_SNAKE_CASE , super_res_latents=__SCREAMING_SNAKE_CASE , image_embeddings=__SCREAMING_SNAKE_CASE , ).images # make sure passing text embeddings manually is identical assert np.abs(img_out_a - img_out_a ).max() < 1E-4 @skip_mps def _a (self ): A_ : Tuple = torch_device == """cpu""" # Check is relaxed because there is not a torch 2.0 sliced attention added kv processor A_ : str = 1E-2 self._test_attention_slicing_forward_pass( test_max_difference=__SCREAMING_SNAKE_CASE , expected_max_diff=__SCREAMING_SNAKE_CASE ) @skip_mps def _a (self ): A_ : Union[str, Any] = torch_device == """cpu""" A_ : List[str] = True A_ : Optional[Any] = [ """decoder_num_inference_steps""", """super_res_num_inference_steps""", ] self._test_inference_batch_single_identical( test_max_difference=__SCREAMING_SNAKE_CASE , relax_max_difference=__SCREAMING_SNAKE_CASE , additional_params_copy_to_batched_inputs=__SCREAMING_SNAKE_CASE , ) def _a (self ): A_ : str = [ """decoder_num_inference_steps""", """super_res_num_inference_steps""", ] if torch_device == "mps": # TODO: MPS errors with larger batch sizes A_ : List[Any] = [2, 3] self._test_inference_batch_consistent( batch_sizes=__SCREAMING_SNAKE_CASE , additional_params_copy_to_batched_inputs=__SCREAMING_SNAKE_CASE , ) else: self._test_inference_batch_consistent( additional_params_copy_to_batched_inputs=__SCREAMING_SNAKE_CASE ) @skip_mps def _a (self ): return super().test_dict_tuple_outputs_equivalent() @skip_mps def _a (self ): return super().test_save_load_local() @skip_mps def _a (self ): return super().test_save_load_optional_components() @slow @require_torch_gpu class _lowerCAmelCase ( unittest.TestCase ): def _a (self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _a (self ): A_ : Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unclip/cat.png""" ) A_ : Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/unclip/karlo_v1_alpha_cat_variation_fp16.npy""" ) A_ : int = UnCLIPImageVariationPipeline.from_pretrained( """kakaobrain/karlo-v1-alpha-image-variations""" , torch_dtype=torch.floataa ) A_ : Any = pipeline.to(__SCREAMING_SNAKE_CASE ) pipeline.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) A_ : Tuple = torch.Generator(device="""cpu""" ).manual_seed(0 ) A_ : Any = pipeline( __SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) A_ : Optional[int] = output.images[0] assert image.shape == (256, 256, 3) assert_mean_pixel_difference(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , 15 )
206
'''simple docstring''' import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging UpperCAmelCase : str = logging.get_logger(__name__) class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "linear" lowerCAmelCase__ = "cosine" lowerCAmelCase__ = "cosine_with_restarts" lowerCAmelCase__ = "polynomial" lowerCAmelCase__ = "constant" lowerCAmelCase__ = "constant_with_warmup" lowerCAmelCase__ = "piecewise_constant" def a__ ( a__ , a__ = -1 ): """simple docstring""" return LambdaLR(a__ , lambda a__ : 1 , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1.0 , a__ ) ) return 1.0 return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = step_rules.split(""",""" ) for rule_str in rule_list[:-1]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = rule_str.split(""":""" ) __SCREAMING_SNAKE_CASE = int(a__ ) __SCREAMING_SNAKE_CASE = float(a__ ) __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = float(rule_list[-1] ) def create_rules_function(a__ , a__ ): def rule_func(a__ ) -> float: __SCREAMING_SNAKE_CASE = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(a__ ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func __SCREAMING_SNAKE_CASE = create_rules_function(a__ , a__ ) return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ , a__=-1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 0.5 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(a__ ) * 2.0 * progress )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 1 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(a__ ) * progress) % 1.0) )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__=1E-7 , a__=1.0 , a__=-1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = optimizer.defaults["""lr"""] if not (lr_init > lr_end): raise ValueError(F'lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})' ) def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: __SCREAMING_SNAKE_CASE = lr_init - lr_end __SCREAMING_SNAKE_CASE = num_training_steps - num_warmup_steps __SCREAMING_SNAKE_CASE = 1 - (current_step - num_warmup_steps) / decay_steps __SCREAMING_SNAKE_CASE = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(a__ , a__ , a__ ) UpperCAmelCase : Optional[Any] = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def a__ ( a__ , a__ , a__ = None , a__ = None , a__ = None , a__ = 1 , a__ = 1.0 , a__ = -1 , ): """simple docstring""" __SCREAMING_SNAKE_CASE = SchedulerType(a__ ) __SCREAMING_SNAKE_CASE = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(a__ , last_epoch=a__ ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(a__ , step_rules=a__ , last_epoch=a__ ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(F'{name} requires `num_warmup_steps`, please provide that argument.' ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(a__ , num_warmup_steps=a__ , last_epoch=a__ ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(F'{name} requires `num_training_steps`, please provide that argument.' ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , num_cycles=a__ , last_epoch=a__ , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , power=a__ , last_epoch=a__ , ) return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , last_epoch=a__ )
267
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase : Dict = {'configuration_xglm': ['XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XGLMConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Tuple = ['XGLMTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Optional[Any] = ['XGLMTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Dict = [ 'XGLM_PRETRAINED_MODEL_ARCHIVE_LIST', 'XGLMForCausalLM', 'XGLMModel', 'XGLMPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : List[str] = [ 'FlaxXGLMForCausalLM', 'FlaxXGLMModel', 'FlaxXGLMPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Union[str, Any] = [ 'TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFXGLMForCausalLM', 'TFXGLMModel', 'TFXGLMPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys lowercase : int = _LazyModule(__name__, globals()['__file__'], _import_structure)
3
'''simple docstring''' import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() UpperCAmelCase : Tuple = { 'bart': ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'bert': ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-base-cased-finetuned-mrpc': ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'dpr': ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'gpt2': ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlnet': ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm': ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm-roberta': ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'transfo-xl': ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'openai-gpt': ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'roberta': ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'layoutlm': ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'roberta-large-mnli': ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'camembert': ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'flaubert': ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert': ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert-base-distilled-squad': ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert': ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert-visual-feature-encoder': ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'ctrl': ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'albert': ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 't5': ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'electra': ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'wav2vec2': ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def a__ ( a__ , a__ , a__ , a__ , a__=False , a__=True ): """simple docstring""" if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) __SCREAMING_SNAKE_CASE = config_class.from_json_file(a__ ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True print(F'Building TensorFlow model from configuration: {config}' ) __SCREAMING_SNAKE_CASE = model_class(a__ ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): __SCREAMING_SNAKE_CASE = cached_file( a__ , a__ , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: __SCREAMING_SNAKE_CASE = load_pytorch_checkpoint_in_tfa_model(a__ , a__ ) if compare_with_pt_model: __SCREAMING_SNAKE_CASE = tf_model(tf_model.dummy_inputs , training=a__ ) # build the network __SCREAMING_SNAKE_CASE = torch.load(a__ , map_location="""cpu""" ) __SCREAMING_SNAKE_CASE = pt_model_class.from_pretrained( pretrained_model_name_or_path=a__ , config=a__ , state_dict=a__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = pt_model(**pt_model.dummy_inputs ) __SCREAMING_SNAKE_CASE = pto[0].numpy() __SCREAMING_SNAKE_CASE = tfo[0].numpy() __SCREAMING_SNAKE_CASE = np.amax(np.abs(np_pt - np_tf ) ) print(F'Max absolute difference between models outputs {diff}' ) assert diff <= 2E-2, F'Error, model absolute difference is >2e-2: {diff}' # Save pytorch-model print(F'Save TensorFlow model to {tf_dump_path}' ) tf_model.save_weights(a__ , save_format="""h5""" ) def a__ ( a__ , a__ , a__=None , a__=None , a__=False , a__=False , a__=False , a__=False , ): """simple docstring""" if args_model_type is None: __SCREAMING_SNAKE_CASE = list(MODEL_CLASSES.keys() ) else: __SCREAMING_SNAKE_CASE = [args_model_type] for j, model_type in enumerate(a__ , start=1 ): print("""=""" * 1_00 ) print(F' Converting model type {j}/{len(a__ )}: {model_type}' ) print("""=""" * 1_00 ) if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(a__ , a__ ) , start=1 ): print("""-""" * 1_00 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(F' Skipping finetuned checkpoint {model_shortcut_name}' ) continue __SCREAMING_SNAKE_CASE = model_shortcut_name elif only_convert_finetuned_models: print(F' Skipping not finetuned checkpoint {model_shortcut_name}' ) continue print( F' Converting checkpoint {i}/{len(a__ )}: {model_shortcut_name} - model_type {model_type}' ) print("""-""" * 1_00 ) if config_shortcut_name in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = config_shortcut_name if model_shortcut_name in aws_model_maps: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = model_shortcut_name if os.path.isfile(a__ ): __SCREAMING_SNAKE_CASE = """converted_model""" convert_pt_checkpoint_to_tf( model_type=a__ , pytorch_checkpoint_path=a__ , config_file=a__ , tf_dump_path=os.path.join(a__ , model_shortcut_name + """-tf_model.h5""" ) , compare_with_pt_model=a__ , ) if remove_cached_files: os.remove(a__ ) os.remove(a__ ) if __name__ == "__main__": UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_dump_path', default=None, type=str, required=True, help='Path to the output Tensorflow dump file.' ) parser.add_argument( '--model_type', default=None, type=str, help=( f"""Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and """ 'convert all the models from AWS.' ), ) parser.add_argument( '--pytorch_checkpoint_path', default=None, type=str, help=( 'Path to the PyTorch checkpoint path or shortcut name to download from AWS. ' 'If not given, will download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--config_file', default=None, type=str, help=( 'The config json file corresponding to the pre-trained model. \n' 'This specifies the model architecture. If not given and ' '--pytorch_checkpoint_path is not given or is a shortcut name ' 'use the configuration associated to the shortcut name on the AWS' ), ) parser.add_argument( '--compare_with_pt_model', action='store_true', help='Compare Tensorflow and PyTorch model predictions.' ) parser.add_argument( '--use_cached_models', action='store_true', help='Use cached models if possible instead of updating to latest checkpoint versions.', ) parser.add_argument( '--remove_cached_files', action='store_true', help='Remove pytorch models after conversion (save memory when converting in batches).', ) parser.add_argument('--only_convert_finetuned_models', action='store_true', help='Only convert finetuned models.') UpperCAmelCase : List[Any] = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
267
0
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING A : Optional[int] = logging.get_logger(__name__) class __A( a ): snake_case_ = '''upernet''' def __init__( self , _snake_case=None , _snake_case=512 , _snake_case=0.02 , _snake_case=[1, 2, 3, 6] , _snake_case=True , _snake_case=0.4 , _snake_case=384 , _snake_case=256 , _snake_case=1 , _snake_case=False , _snake_case=255 , **_snake_case , ) -> Optional[Any]: '''simple docstring''' super().__init__(**__SCREAMING_SNAKE_CASE ) if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) __a = CONFIG_MAPPING['''resnet'''](out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] ) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): __a = backbone_config.get('''model_type''' ) __a = CONFIG_MAPPING[backbone_model_type] __a = config_class.from_dict(__SCREAMING_SNAKE_CASE ) __a = backbone_config __a = hidden_size __a = initializer_range __a = pool_scales __a = use_auxiliary_head __a = auxiliary_loss_weight __a = auxiliary_in_channels __a = auxiliary_channels __a = auxiliary_num_convs __a = auxiliary_concat_input __a = loss_ignore_index def SCREAMING_SNAKE_CASE_ ( self ) -> str: '''simple docstring''' __a = copy.deepcopy(self.__dict__ ) __a = self.backbone_config.to_dict() __a = self.__class__.model_type return output
6
'''simple docstring''' def a__ ( a__ ): """simple docstring""" if isinstance(a__ , a__ ): raise TypeError("""'float' object cannot be interpreted as an integer""" ) if isinstance(a__ , a__ ): raise TypeError("""'str' object cannot be interpreted as an integer""" ) if num == 0: return "0b0" __SCREAMING_SNAKE_CASE = False if num < 0: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = -num __SCREAMING_SNAKE_CASE = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(a__ ) for e in binary ) return "0b" + "".join(str(a__ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
267
0
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_rembert import RemBertTokenizer else: __A = None __A = logging.get_logger(__name__) __A = {'vocab_file': 'sentencepiece.model', 'tokenizer_file': 'tokenizer.json'} __A = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, 'tokenizer_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/tokenizer.json', }, } __A = { 'google/rembert': 2_5_6, } __A = '▁' class UpperCAmelCase (_UpperCAmelCase ): """simple docstring""" _UpperCAmelCase :Optional[Any] = VOCAB_FILES_NAMES _UpperCAmelCase :Optional[int] = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase :Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase :Tuple = RemBertTokenizer def __init__( self , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=False , _UpperCAmelCase="[CLS]" , _UpperCAmelCase="[SEP]" , _UpperCAmelCase="<unk>" , _UpperCAmelCase="[SEP]" , _UpperCAmelCase="<pad>" , _UpperCAmelCase="[CLS]" , _UpperCAmelCase="[MASK]" , **_UpperCAmelCase , ): lowercase__: Dict = AddedToken(__SCREAMING_SNAKE_CASE , lstrip=__SCREAMING_SNAKE_CASE , rstrip=__SCREAMING_SNAKE_CASE ) if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else mask_token super().__init__( __SCREAMING_SNAKE_CASE , tokenizer_file=__SCREAMING_SNAKE_CASE , do_lower_case=__SCREAMING_SNAKE_CASE , remove_space=__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE , bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , cls_token=__SCREAMING_SNAKE_CASE , mask_token=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) lowercase__: Dict = do_lower_case lowercase__: Optional[int] = remove_space lowercase__: str = keep_accents lowercase__: str = vocab_file lowercase__: Tuple = False if not self.vocab_file else True def _snake_case ( self , _UpperCAmelCase , _UpperCAmelCase = None ): lowercase__: List[str] = [self.sep_token_id] lowercase__: List[Any] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def _snake_case ( self , _UpperCAmelCase , _UpperCAmelCase = None , _UpperCAmelCase = False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( '''You should not supply a second sequence if the provided sequence of ''' '''ids is already formatted with special tokens for the model.''' ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(__SCREAMING_SNAKE_CASE )) + [1] + ([0] * len(__SCREAMING_SNAKE_CASE )) + [1] return [1] + ([0] * len(__SCREAMING_SNAKE_CASE )) + [1] def _snake_case ( self , _UpperCAmelCase , _UpperCAmelCase = None ): lowercase__: List[str] = [self.sep_token_id] lowercase__: 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 ) * [0] + len(token_ids_a + sep ) * [1] def _snake_case ( self , _UpperCAmelCase , _UpperCAmelCase = None ): if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error('''Vocabulary path ({}) should be a directory'''.format(__SCREAMING_SNAKE_CASE ) ) return lowercase__: str = os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ): copyfile(self.vocab_file , __SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
177
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : Optional[int] = logging.get_logger(__name__) UpperCAmelCase : str = { 'facebook/convnextv2-tiny-1k-224': 'https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json', } class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "convnextv2" def __init__( self : Any , __SCREAMING_SNAKE_CASE : int=3 , __SCREAMING_SNAKE_CASE : Dict=4 , __SCREAMING_SNAKE_CASE : List[Any]=4 , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Optional[int]="gelu" , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.02 , __SCREAMING_SNAKE_CASE : Dict=1E-12 , __SCREAMING_SNAKE_CASE : List[str]=0.0 , __SCREAMING_SNAKE_CASE : Optional[Any]=224 , __SCREAMING_SNAKE_CASE : Tuple=None , __SCREAMING_SNAKE_CASE : List[str]=None , **__SCREAMING_SNAKE_CASE : Union[str, Any] , ) -> Union[str, Any]: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_stages __SCREAMING_SNAKE_CASE = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes __SCREAMING_SNAKE_CASE = [3, 3, 9, 3] if depths is None else depths __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(self.depths ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
0
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 a__ = getLogger(__name__) a__ = 'cuda' if torch.cuda.is_available() else 'cpu' def lowercase ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] = 8 , SCREAMING_SNAKE_CASE__ : Dict = DEFAULT_DEVICE , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : Optional[int]="summarization" , SCREAMING_SNAKE_CASE__ : str=None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> Optional[Any]: _snake_case : Any = Path(a__ ).open("""w""" , encoding="""utf-8""" ) _snake_case : Optional[Any] = str(a__ ) _snake_case : Optional[Any] = AutoModelForSeqaSeqLM.from_pretrained(a__ ).to(a__ ) if fpaa: _snake_case : Dict = model.half() _snake_case : str = AutoTokenizer.from_pretrained(a__ ) logger.info(F'''Inferred tokenizer type: {tokenizer.__class__}''' ) # if this is wrong, check config.model_type. _snake_case : Optional[Any] = time.time() # update config with task specific params use_task_specific_params(a__ , a__ ) if prefix is None: _snake_case : int = prefix or getattr(model.config , """prefix""" , """""" ) or """""" for examples_chunk in tqdm(list(chunks(a__ , a__ ) ) ): _snake_case : Tuple = [prefix + text for text in examples_chunk] _snake_case : Tuple = tokenizer(a__ , return_tensors="""pt""" , truncation=a__ , padding="""longest""" ).to(a__ ) _snake_case : str = model.generate( input_ids=batch.input_ids , attention_mask=batch.attention_mask , **a__ , ) _snake_case : Optional[int] = 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() _snake_case : Any = int(time.time() - start_time ) # seconds _snake_case : Union[str, Any] = len(a__ ) return {"n_obs": n_obs, "runtime": runtime, "seconds_per_sample": round(runtime / n_obs , 4 )} def lowercase ( ) -> str: return datetime.datetime.now().strftime("""%Y-%m-%d %H:%M:%S""" ) def lowercase ( SCREAMING_SNAKE_CASE__ : Union[str, Any]=True ) -> Dict: _snake_case : List[Any] = 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 _snake_case , _snake_case : Any = parser.parse_known_args() _snake_case : Union[str, Any] = parse_numeric_n_bool_cl_kwargs(a__ ) if parsed_args and verbose: print(F'''parsed the following generate kwargs: {parsed_args}''' ) _snake_case : Any = [""" """ + x.rstrip() if """t5""" in args.model_name else x.rstrip() for x in open(args.input_path ).readlines()] if args.n_obs > 0: _snake_case : Dict = 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""" ) _snake_case : List[Any] = 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 _snake_case : List[str] = calculate_bleu if """translation""" in args.task else calculate_rouge _snake_case : Any = [x.rstrip() for x in open(args.save_path ).readlines()] _snake_case : str = [x.rstrip() for x in open(args.reference_path ).readlines()][: len(a__ )] _snake_case : Dict = score_fn(a__ , a__ ) scores.update(a__ ) if args.dump_args: scores.update(a__ ) if args.info: _snake_case : Optional[int] = 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)
317
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : List[str] = logging.get_logger(__name__) class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "maskformer-swin" lowerCAmelCase__ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : str , __SCREAMING_SNAKE_CASE : Tuple=224 , __SCREAMING_SNAKE_CASE : str=4 , __SCREAMING_SNAKE_CASE : Union[str, Any]=3 , __SCREAMING_SNAKE_CASE : Optional[Any]=96 , __SCREAMING_SNAKE_CASE : Optional[Any]=[2, 2, 6, 2] , __SCREAMING_SNAKE_CASE : Any=[3, 6, 12, 24] , __SCREAMING_SNAKE_CASE : Dict=7 , __SCREAMING_SNAKE_CASE : Dict=4.0 , __SCREAMING_SNAKE_CASE : Dict=True , __SCREAMING_SNAKE_CASE : str=0.0 , __SCREAMING_SNAKE_CASE : int=0.0 , __SCREAMING_SNAKE_CASE : str=0.1 , __SCREAMING_SNAKE_CASE : List[Any]="gelu" , __SCREAMING_SNAKE_CASE : str=False , __SCREAMING_SNAKE_CASE : Optional[int]=0.02 , __SCREAMING_SNAKE_CASE : Optional[int]=1E-5 , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Dict=None , **__SCREAMING_SNAKE_CASE : Tuple , ) -> Tuple: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = embed_dim __SCREAMING_SNAKE_CASE = depths __SCREAMING_SNAKE_CASE = len(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_heads __SCREAMING_SNAKE_CASE = window_size __SCREAMING_SNAKE_CASE = mlp_ratio __SCREAMING_SNAKE_CASE = qkv_bias __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = use_absolute_embeddings __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __SCREAMING_SNAKE_CASE = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) ) __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
0
"""simple docstring""" import inspect from typing import Callable, List, Optional, Union import torch from transformers import ( CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, WhisperForConditionalGeneration, WhisperProcessor, ) from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.utils import logging lowerCAmelCase_ = logging.get_logger(__name__) # pylint: disable=invalid-name class __A ( A_ ): '''simple docstring''' def __init__( self : Union[str, Any] ,_snake_case : WhisperForConditionalGeneration ,_snake_case : WhisperProcessor ,_snake_case : AutoencoderKL ,_snake_case : CLIPTextModel ,_snake_case : CLIPTokenizer ,_snake_case : UNetaDConditionModel ,_snake_case : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] ,_snake_case : StableDiffusionSafetyChecker ,_snake_case : CLIPImageProcessor ,) -> int: """simple docstring""" super().__init__() if safety_checker is None: logger.warning( f"""You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure""" ''' that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered''' ''' results in services or applications open to the public. Both the diffusers team and Hugging Face''' ''' strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling''' ''' it only for use-cases that involve analyzing network behavior or auditing its results. For more''' ''' information, please have a look at https://github.com/huggingface/diffusers/pull/254 .''' ) self.register_modules( speech_model=__SCREAMING_SNAKE_CASE ,speech_processor=__SCREAMING_SNAKE_CASE ,vae=__SCREAMING_SNAKE_CASE ,text_encoder=__SCREAMING_SNAKE_CASE ,tokenizer=__SCREAMING_SNAKE_CASE ,unet=__SCREAMING_SNAKE_CASE ,scheduler=__SCREAMING_SNAKE_CASE ,feature_extractor=__SCREAMING_SNAKE_CASE ,) def UpperCAmelCase ( self : Tuple ,_snake_case : Optional[Union[str, int]] = "auto" ) -> int: """simple docstring""" if slice_size == "auto": lowercase__ : int = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self : Dict ) -> Optional[Any]: """simple docstring""" self.enable_attention_slicing(__SCREAMING_SNAKE_CASE ) @torch.no_grad() def __call__( self : Optional[int] ,_snake_case : Any ,_snake_case : Tuple=16_000 ,_snake_case : int = 512 ,_snake_case : int = 512 ,_snake_case : int = 50 ,_snake_case : float = 7.5 ,_snake_case : Optional[Union[str, List[str]]] = None ,_snake_case : Optional[int] = 1 ,_snake_case : float = 0.0 ,_snake_case : Optional[torch.Generator] = None ,_snake_case : Optional[torch.FloatTensor] = None ,_snake_case : Optional[str] = "pil" ,_snake_case : bool = True ,_snake_case : Optional[Callable[[int, int, torch.FloatTensor], None]] = None ,_snake_case : int = 1 ,**_snake_case : str ,) -> Optional[Any]: """simple docstring""" lowercase__ : Any = self.speech_processor.feature_extractor( __SCREAMING_SNAKE_CASE ,return_tensors='''pt''' ,sampling_rate=__SCREAMING_SNAKE_CASE ).input_features.to(self.device ) lowercase__ : Dict = self.speech_model.generate(__SCREAMING_SNAKE_CASE ,max_length=480_000 ) lowercase__ : Optional[Any] = self.speech_processor.tokenizer.batch_decode(__SCREAMING_SNAKE_CASE ,skip_special_tokens=__SCREAMING_SNAKE_CASE ,normalize=__SCREAMING_SNAKE_CASE )[ 0 ] if isinstance(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ): lowercase__ : Optional[int] = 1 elif isinstance(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ): lowercase__ : Union[str, Any] = len(__SCREAMING_SNAKE_CASE ) else: raise ValueError(f"""`prompt` has to be of type `str` or `list` but is {type(__SCREAMING_SNAKE_CASE )}""" ) if height % 8 != 0 or width % 8 != 0: raise ValueError(f"""`height` and `width` have to be divisible by 8 but are {height} and {width}.""" ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ) or callback_steps <= 0) ): raise ValueError( f"""`callback_steps` has to be a positive integer but is {callback_steps} of type""" f""" {type(__SCREAMING_SNAKE_CASE )}.""" ) # get prompt text embeddings lowercase__ : Optional[int] = self.tokenizer( __SCREAMING_SNAKE_CASE ,padding='''max_length''' ,max_length=self.tokenizer.model_max_length ,return_tensors='''pt''' ,) lowercase__ : Optional[Any] = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: lowercase__ : Optional[int] = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( '''The following part of your input was truncated because CLIP can only handle sequences up to''' f""" {self.tokenizer.model_max_length} tokens: {removed_text}""" ) lowercase__ : Dict = text_input_ids[:, : self.tokenizer.model_max_length] lowercase__ : List[str] = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method lowercase__ , lowercase__ , lowercase__ : str = text_embeddings.shape lowercase__ : Optional[Any] = text_embeddings.repeat(1 ,__SCREAMING_SNAKE_CASE ,1 ) lowercase__ : str = text_embeddings.view(bs_embed * num_images_per_prompt ,__SCREAMING_SNAKE_CASE ,-1 ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. lowercase__ : List[Any] = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: lowercase__ : Optional[int] = 42 if negative_prompt is None: lowercase__ : Any = [''''''] * batch_size elif type(__SCREAMING_SNAKE_CASE ) is not type(__SCREAMING_SNAKE_CASE ): raise TypeError( f"""`negative_prompt` should be the same type to `prompt`, but got {type(__SCREAMING_SNAKE_CASE )} !=""" f""" {type(__SCREAMING_SNAKE_CASE )}.""" ) elif isinstance(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ): lowercase__ : str = [negative_prompt] elif batch_size != len(__SCREAMING_SNAKE_CASE ): raise ValueError( f"""`negative_prompt`: {negative_prompt} has batch size {len(__SCREAMING_SNAKE_CASE )}, but `prompt`:""" f""" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches""" ''' the batch size of `prompt`.''' ) else: lowercase__ : str = negative_prompt lowercase__ : Optional[Any] = text_input_ids.shape[-1] lowercase__ : List[str] = self.tokenizer( __SCREAMING_SNAKE_CASE ,padding='''max_length''' ,max_length=__SCREAMING_SNAKE_CASE ,truncation=__SCREAMING_SNAKE_CASE ,return_tensors='''pt''' ,) lowercase__ : Optional[int] = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method lowercase__ : int = uncond_embeddings.shape[1] lowercase__ : Tuple = uncond_embeddings.repeat(1 ,__SCREAMING_SNAKE_CASE ,1 ) lowercase__ : Tuple = uncond_embeddings.view(batch_size * num_images_per_prompt ,__SCREAMING_SNAKE_CASE ,-1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes lowercase__ : Union[str, Any] = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. lowercase__ : Dict = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) lowercase__ : Optional[int] = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps lowercase__ : List[Any] = torch.randn(__SCREAMING_SNAKE_CASE ,generator=__SCREAMING_SNAKE_CASE ,device='''cpu''' ,dtype=__SCREAMING_SNAKE_CASE ).to( self.device ) else: lowercase__ : Optional[Any] = torch.randn(__SCREAMING_SNAKE_CASE ,generator=__SCREAMING_SNAKE_CASE ,device=self.device ,dtype=__SCREAMING_SNAKE_CASE ) else: if latents.shape != latents_shape: raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}""" ) lowercase__ : Optional[int] = latents.to(self.device ) # set timesteps self.scheduler.set_timesteps(__SCREAMING_SNAKE_CASE ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand lowercase__ : Union[str, Any] = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler lowercase__ : List[Any] = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] lowercase__ : List[str] = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) lowercase__ : int = {} if accepts_eta: lowercase__ : str = eta for i, t in enumerate(self.progress_bar(__SCREAMING_SNAKE_CASE ) ): # expand the latents if we are doing classifier free guidance lowercase__ : Optional[int] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents lowercase__ : List[str] = self.scheduler.scale_model_input(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ) # predict the noise residual lowercase__ : Optional[int] = self.unet(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,encoder_hidden_states=__SCREAMING_SNAKE_CASE ).sample # perform guidance if do_classifier_free_guidance: lowercase__ , lowercase__ : Dict = noise_pred.chunk(2 ) lowercase__ : Optional[int] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 lowercase__ : Optional[Any] = self.scheduler.step(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,**__SCREAMING_SNAKE_CASE ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ) lowercase__ : str = 1 / 0.1_8215 * latents lowercase__ : List[Any] = self.vae.decode(__SCREAMING_SNAKE_CASE ).sample lowercase__ : Union[str, Any] = (image / 2 + 0.5).clamp(0 ,1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 lowercase__ : List[Any] = image.cpu().permute(0 ,2 ,3 ,1 ).float().numpy() if output_type == "pil": lowercase__ : List[str] = self.numpy_to_pil(__SCREAMING_SNAKE_CASE ) if not return_dict: return image return StableDiffusionPipelineOutput(images=__SCREAMING_SNAKE_CASE ,nsfw_content_detected=__SCREAMING_SNAKE_CASE )
16
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = n __SCREAMING_SNAKE_CASE = [None] * self.n __SCREAMING_SNAKE_CASE = 0 # index of the first element __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 def __len__( self : Tuple ) -> int: """simple docstring""" return self.size def UpperCAmelCase__ ( self : Optional[Any] ) -> bool: """simple docstring""" return self.size == 0 def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" return False if self.is_empty() else self.array[self.front] def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Dict: """simple docstring""" if self.size >= self.n: raise Exception("""QUEUE IS FULL""" ) __SCREAMING_SNAKE_CASE = data __SCREAMING_SNAKE_CASE = (self.rear + 1) % self.n self.size += 1 return self def UpperCAmelCase__ ( self : List[str] ) -> Optional[Any]: """simple docstring""" if self.size == 0: raise Exception("""UNDERFLOW""" ) __SCREAMING_SNAKE_CASE = self.array[self.front] __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = (self.front + 1) % self.n self.size -= 1 return temp
267
0
import os def UpperCAmelCase__ ( lowerCamelCase = "matrix.txt" ): with open(os.path.join(os.path.dirname(a__ ), a__ ) ) as in_file: lowercase :Union[str, Any] = in_file.read() lowercase :int = [[int(a__ ) for cell in row.split("," )] for row in data.strip().splitlines()] lowercase :Optional[int] = [[0 for cell in row] for row in grid] lowercase :Tuple = len(grid[0] ) lowercase :List[Any] = [[0 for i in range(a__ )] for j in range(a__ )] lowercase :Optional[int] = grid[0][0] for i in range(1, a__ ): lowercase :List[str] = grid[0][i] + dp[0][i - 1] for i in range(1, a__ ): lowercase :str = grid[i][0] + dp[i - 1][0] for i in range(1, a__ ): for j in range(1, a__ ): lowercase :List[str] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1] ) return dp[-1][-1] if __name__ == "__main__": print(f'''{solution() = }''')
236
'''simple docstring''' import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @property def UpperCAmelCase__ ( self : List[str] ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("""DownBlock2D""", """AttnDownBlock2D""") , up_block_types=("""AttnUpBlock2D""", """UpBlock2D""") , ) return model def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.dummy_uncond_unet __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" , return_dict=__SCREAMING_SNAKE_CASE )[0] __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """google/ddpm-cifar10-32""" __SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array([0.1564, 0.14645, 0.1406, 0.14715, 0.12425, 0.14045, 0.13115, 0.12175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
267
0
'''simple docstring''' def _lowercase ( __A ): '''simple docstring''' return " ".join(input_str.split()[::-1] ) if __name__ == "__main__": import doctest doctest.testmod()
349
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : """simple docstring""" @staticmethod def UpperCAmelCase__ ( *__SCREAMING_SNAKE_CASE : Tuple , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: """simple docstring""" pass @is_pipeline_test @require_vision @require_timm @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = MODEL_FOR_OBJECT_DETECTION_MAPPING def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Tuple ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = object_detector("""./tests/fixtures/tests_samples/COCO/000000039769.png""" , threshold=0.0 ) self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) import datasets __SCREAMING_SNAKE_CASE = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) __SCREAMING_SNAKE_CASE = [ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ] __SCREAMING_SNAKE_CASE = object_detector(__SCREAMING_SNAKE_CASE , threshold=0.0 ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(__SCREAMING_SNAKE_CASE ) ) for outputs in batch_outputs: self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) @require_tf @unittest.skip("""Object detection not implemented in TF""" ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" pass @require_torch def UpperCAmelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """hf-internal-testing/tiny-detr-mobilenetsv3""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=0.0 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Dict ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = 0.9985 __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=__SCREAMING_SNAKE_CASE ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) @require_torch @require_pytesseract @slow def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """Narsil/layoutlmv3-finetuned-funsd""" __SCREAMING_SNAKE_CASE = 0.9993 __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE , threshold=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector( """https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, ] , )
267
0
import argparse import fairseq import torch from torch import nn from transformers import ( MBartaaTokenizer, MBartConfig, MBartForCausalLM, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() __A : Any = logging.get_logger(__name__) __A : int = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', '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', } __A : Union[str, Any] = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', ] def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Any: '''simple docstring''' for attribute in key.split('''.''' ): UpperCAmelCase = getattr(a__ , a__ ) if weight_type is not None: UpperCAmelCase = getattr(a__ , a__ ).shape else: UpperCAmelCase = hf_pointer.shape assert hf_shape == value.shape, ( 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": UpperCAmelCase = value elif weight_type == "weight_g": UpperCAmelCase = value elif weight_type == "weight_v": UpperCAmelCase = value elif weight_type == "bias": UpperCAmelCase = value else: UpperCAmelCase = value logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__ ) -> Optional[int]: '''simple docstring''' UpperCAmelCase = [] UpperCAmelCase = fairseq_model.state_dict() UpperCAmelCase = hf_model.feature_extractor UpperCAmelCase = hf_model.adapter for name, value in fairseq_dict.items(): UpperCAmelCase = False if "conv_layers" in name: load_conv_layer( a__ , a__ , a__ , a__ , hf_model.config.feat_extract_norm == '''group''' , ) UpperCAmelCase = True elif any(x in name for x in ['''adaptor''', '''w2v_encoder.proj.''', '''w2v_proj_ln.'''] ): load_adapter(a__ , a__ , a__ , a__ ) UpperCAmelCase = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: UpperCAmelCase = True if "*" in mapped_key: UpperCAmelCase = name.split(a__ )[0].split('''.''' )[-2] UpperCAmelCase = mapped_key.replace('''*''' , a__ ) if "weight_g" in name: UpperCAmelCase = '''weight_g''' elif "weight_v" in name: UpperCAmelCase = '''weight_v''' elif "bias" in name: UpperCAmelCase = '''bias''' elif "weight" in name: UpperCAmelCase = '''weight''' else: UpperCAmelCase = 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 __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Tuple: '''simple docstring''' UpperCAmelCase = full_name.split('''conv_layers.''' )[-1] UpperCAmelCase = name.split('''.''' ) UpperCAmelCase = int(items[0] ) UpperCAmelCase = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) UpperCAmelCase = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) UpperCAmelCase = 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: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) UpperCAmelCase = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) UpperCAmelCase = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(a__ ) def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Tuple: '''simple docstring''' UpperCAmelCase = full_name.split('''adaptor.''' )[-1] UpperCAmelCase = name.split('''.''' ) if items[1].isdigit(): UpperCAmelCase = int(items[1] ) else: UpperCAmelCase = None if "adaptor" not in full_name: if "proj_ln" in full_name: # has to be layer norm if "bias" in name: assert ( value.shape == adapter.proj_layer_norm.bias.data.shape ), F"""{full_name} has size {value.shape}, but {adapter.proj_layer_norm.bias.data.shape} was found.""" UpperCAmelCase = value logger.info(F"""Adapter proj layer norm bias was initialized from {full_name}.""" ) if "weight" in name: assert ( value.shape == adapter.proj_layer_norm.weight.data.shape ), F"""{full_name} has size {value.shape}, but {adapter.proj_layer_norm.weight.data.shape} was found.""" UpperCAmelCase = value else: # has to be projection layer if "bias" in name: assert ( value.shape == adapter.proj.bias.data.shape ), F"""{full_name} has size {value.shape}, but {adapter.proj.bias.data.shape} was found.""" UpperCAmelCase = value logger.info(F"""Adapter proj layer bias was initialized from {full_name}.""" ) if "weight" in name: assert ( value.shape == adapter.proj.weight.data.shape ), F"""{full_name} has size {value.shape}, but {adapter.proj.weight.data.shape} was found.""" UpperCAmelCase = value logger.info(F"""Adapter proj layer weight was initialized from {full_name}.""" ) elif isinstance(a__ , a__ ): if "bias" in name: assert ( value.shape == adapter.layers[layer_id].conv.bias.data.shape ), F"""{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.bias.data.shape} was found.""" UpperCAmelCase = value logger.info(F"""Adapter layer {layer_id} bias was initialized from {full_name}.""" ) elif "weight" in name: assert ( value.shape == adapter.layers[layer_id].conv.weight.data.shape ), F"""{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.weight.data.shape} was found.""" UpperCAmelCase = value logger.info(F"""Adapter layer {layer_id} bias was initialized from {full_name}.""" ) else: unused_weights.append(a__ ) def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ ) -> Any: '''simple docstring''' UpperCAmelCase , UpperCAmelCase = emb.weight.shape UpperCAmelCase = nn.Linear(a__ , a__ , bias=a__ ) UpperCAmelCase = emb.weight.data return lin_layer @torch.no_grad() def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase = WavaVecaConfig.from_pretrained( a__ , add_adapter=a__ , adapter_stride=a__ , adapter_kernel_size=a__ , use_auth_token=a__ , output_hidden_size=a__ , ) UpperCAmelCase = MBartConfig.from_pretrained(a__ ) # load model UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={ '''config_yaml''': config_yaml_path, '''data''': '''/'''.join(dict_path.split('''/''' )[:-1] ), '''w2v_path''': checkpoint_path, '''load_pretrained_decoder_from''': None, } , ) UpperCAmelCase = model[0].eval() # load feature extractor UpperCAmelCase = WavaVecaFeatureExtractor.from_pretrained(a__ , use_auth_token=a__ ) # set weights for wav2vec2 encoder UpperCAmelCase = WavaVecaModel(a__ ) recursively_load_weights_wavaveca(model.encoder , a__ ) # load decoder weights UpperCAmelCase = MBartForCausalLM(a__ ) UpperCAmelCase , UpperCAmelCase = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=a__ ) logger.warning(F"""The following keys are missing when loading the decoder weights: {missing_keys}""" ) logger.warning(F"""The following keys are unexpected when loading the decoder weights: {unexpected_keys}""" ) UpperCAmelCase = SpeechEncoderDecoderModel(encoder=a__ , decoder=a__ ) UpperCAmelCase = False UpperCAmelCase = MBartaaTokenizer(a__ ) tokenizer.save_pretrained(a__ ) UpperCAmelCase = hf_wavavec.config.to_dict() UpperCAmelCase = tokenizer.pad_token_id UpperCAmelCase = tokenizer.bos_token_id UpperCAmelCase = tokenizer.eos_token_id UpperCAmelCase = '''mbart50''' UpperCAmelCase = '''wav2vec2''' UpperCAmelCase = tokenizer.eos_token_id UpperCAmelCase = 25_0004 UpperCAmelCase = tokenizer.eos_token_id UpperCAmelCase = SpeechEncoderDecoderConfig.from_dict(a__ ) hf_wavavec.save_pretrained(a__ ) feature_extractor.save_pretrained(a__ ) if __name__ == "__main__": __A : Any = 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_yaml_path", default=None, type=str, help="Path to yaml file of fine-tuned model") parser.add_argument( "--encoder_config_path", default="facebook/wav2vec2-xls-r-1b", type=str, help="Path to hf encoder wav2vec2 checkpoint config", ) parser.add_argument( "--decoder_config_path", default="facebook/mbart-large-50-one-to-many-mmt", type=str, help="Path to hf decoder checkpoint config", ) parser.add_argument("--add_adapter", default=True, type=bool, help="whethere to add model adapter layers") parser.add_argument("--adapter_stride", default=2, type=int, help="stride of adapter layers") parser.add_argument("--adapter_kernel_size", default=3, type=int, help="kernel size of adapter layers") parser.add_argument("--encoder_output_dim", default=1_024, type=int, help="encoder output dim") parser.add_argument("--start_token_id", default=250_004, type=int, help="`decoder_start_token_id` of model config") __A : List[str] = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, args.config_yaml_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, add_adapter=args.add_adapter, adapter_kernel_size=args.adapter_kernel_size, adapter_stride=args.adapter_stride, decoder_start_token_id=args.start_token_id, encoder_output_dim=args.encoder_output_dim, )
273
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = FlaxAutoencoderKL @property def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (32, 32) __SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0 ) __SCREAMING_SNAKE_CASE = jax.random.uniform(__SCREAMING_SNAKE_CASE , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 4, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict
267
0
import json import os import sys import tempfile import unittest from pathlib import Path from shutil import copyfile from huggingface_hub import HfFolder, Repository, create_repo, delete_repo from requests.exceptions import HTTPError import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, PROCESSOR_MAPPING, TOKENIZER_MAPPING, AutoConfig, AutoFeatureExtractor, AutoProcessor, AutoTokenizer, BertTokenizer, ProcessorMixin, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaProcessor, ) from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE from transformers.utils import FEATURE_EXTRACTOR_NAME, is_tokenizers_available sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 from test_module.custom_processing import CustomProcessor # noqa E402 from test_module.custom_tokenization import CustomTokenizer # noqa E402 lowercase = get_tests_dir("fixtures/dummy_feature_extractor_config.json") lowercase = get_tests_dir("fixtures/vocab.json") lowercase = get_tests_dir("fixtures") class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' lowerCAmelCase = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''bla''', '''blou'''] def _UpperCamelCase ( self ) -> str: snake_case_ = 0 def _UpperCamelCase ( self ) -> List[str]: snake_case_ = AutoProcessor.from_pretrained('facebook/wav2vec2-base-960h' ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _UpperCamelCase ( self ) -> Union[str, Any]: with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ = WavaVecaConfig() snake_case_ = AutoProcessor.from_pretrained('facebook/wav2vec2-base-960h' ) # save in new folder model_config.save_pretrained(__SCREAMING_SNAKE_CASE ) processor.save_pretrained(__SCREAMING_SNAKE_CASE ) snake_case_ = AutoProcessor.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _UpperCamelCase ( self ) -> Tuple: with tempfile.TemporaryDirectory() as tmpdirname: # copy relevant files copyfile(__SCREAMING_SNAKE_CASE , os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) copyfile(__SCREAMING_SNAKE_CASE , os.path.join(__SCREAMING_SNAKE_CASE , 'vocab.json' ) ) snake_case_ = AutoProcessor.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _UpperCamelCase ( self ) -> Tuple: with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ = WavaVecaFeatureExtractor() snake_case_ = AutoTokenizer.from_pretrained('facebook/wav2vec2-base-960h' ) snake_case_ = WavaVecaProcessor(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # save in new folder processor.save_pretrained(__SCREAMING_SNAKE_CASE ) # drop `processor_class` in tokenizer with open(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , 'r' ) as f: snake_case_ = json.load(__SCREAMING_SNAKE_CASE ) config_dict.pop('processor_class' ) with open(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , 'w' ) as f: f.write(json.dumps(__SCREAMING_SNAKE_CASE ) ) snake_case_ = AutoProcessor.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _UpperCamelCase ( self ) -> str: with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ = WavaVecaFeatureExtractor() snake_case_ = AutoTokenizer.from_pretrained('facebook/wav2vec2-base-960h' ) snake_case_ = WavaVecaProcessor(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # save in new folder processor.save_pretrained(__SCREAMING_SNAKE_CASE ) # drop `processor_class` in feature extractor with open(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , 'r' ) as f: snake_case_ = json.load(__SCREAMING_SNAKE_CASE ) config_dict.pop('processor_class' ) with open(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , 'w' ) as f: f.write(json.dumps(__SCREAMING_SNAKE_CASE ) ) snake_case_ = AutoProcessor.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _UpperCamelCase ( self ) -> List[str]: with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ = WavaVecaConfig(processor_class='Wav2Vec2Processor' ) model_config.save_pretrained(__SCREAMING_SNAKE_CASE ) # copy relevant files copyfile(__SCREAMING_SNAKE_CASE , os.path.join(__SCREAMING_SNAKE_CASE , 'vocab.json' ) ) # create emtpy sample processor with open(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , 'w' ) as f: f.write('{}' ) snake_case_ = AutoProcessor.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _UpperCamelCase ( self ) -> Tuple: with self.assertRaises(__SCREAMING_SNAKE_CASE ): snake_case_ = AutoProcessor.from_pretrained('hf-internal-testing/test_dynamic_processor' ) # If remote code is disabled, we can't load this config. with self.assertRaises(__SCREAMING_SNAKE_CASE ): snake_case_ = AutoProcessor.from_pretrained( 'hf-internal-testing/test_dynamic_processor' , trust_remote_code=__SCREAMING_SNAKE_CASE ) snake_case_ = AutoProcessor.from_pretrained('hf-internal-testing/test_dynamic_processor' , trust_remote_code=__SCREAMING_SNAKE_CASE ) self.assertTrue(processor.special_attribute_present ) self.assertEqual(processor.__class__.__name__ , 'NewProcessor' ) snake_case_ = processor.feature_extractor self.assertTrue(feature_extractor.special_attribute_present ) self.assertEqual(feature_extractor.__class__.__name__ , 'NewFeatureExtractor' ) snake_case_ = processor.tokenizer self.assertTrue(tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , 'NewTokenizerFast' ) # Test we can also load the slow version snake_case_ = AutoProcessor.from_pretrained( 'hf-internal-testing/test_dynamic_processor' , trust_remote_code=__SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE ) snake_case_ = new_processor.tokenizer self.assertTrue(new_tokenizer.special_attribute_present ) self.assertEqual(new_tokenizer.__class__.__name__ , 'NewTokenizer' ) else: self.assertEqual(tokenizer.__class__.__name__ , 'NewTokenizer' ) def _UpperCamelCase ( self ) -> Any: try: AutoConfig.register('custom' , __SCREAMING_SNAKE_CASE ) AutoFeatureExtractor.register(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) AutoTokenizer.register(__SCREAMING_SNAKE_CASE , slow_tokenizer_class=__SCREAMING_SNAKE_CASE ) AutoProcessor.register(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(__SCREAMING_SNAKE_CASE ): AutoProcessor.register(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Now that the config is registered, it can be used as any other config with the auto-API snake_case_ = CustomFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ = os.path.join(__SCREAMING_SNAKE_CASE , 'vocab.txt' ) with open(__SCREAMING_SNAKE_CASE , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) snake_case_ = CustomTokenizer(__SCREAMING_SNAKE_CASE ) snake_case_ = CustomProcessor(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained(__SCREAMING_SNAKE_CASE ) snake_case_ = AutoProcessor.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] if CustomConfig in PROCESSOR_MAPPING._extra_content: del PROCESSOR_MAPPING._extra_content[CustomConfig] def _UpperCamelCase ( self ) -> Tuple: class UpperCamelCase_ ( snake_case_ ): '''simple docstring''' lowerCAmelCase = False class UpperCamelCase_ ( snake_case_ ): '''simple docstring''' lowerCAmelCase = False class UpperCamelCase_ ( snake_case_ ): '''simple docstring''' lowerCAmelCase = '''AutoFeatureExtractor''' lowerCAmelCase = '''AutoTokenizer''' lowerCAmelCase = False try: AutoConfig.register('custom' , __SCREAMING_SNAKE_CASE ) AutoFeatureExtractor.register(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) AutoTokenizer.register(__SCREAMING_SNAKE_CASE , slow_tokenizer_class=__SCREAMING_SNAKE_CASE ) AutoProcessor.register(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # If remote code is not set, the default is to use local classes. snake_case_ = AutoProcessor.from_pretrained('hf-internal-testing/test_dynamic_processor' ) self.assertEqual(processor.__class__.__name__ , 'NewProcessor' ) self.assertFalse(processor.special_attribute_present ) self.assertFalse(processor.feature_extractor.special_attribute_present ) self.assertFalse(processor.tokenizer.special_attribute_present ) # If remote code is disabled, we load the local ones. snake_case_ = AutoProcessor.from_pretrained( 'hf-internal-testing/test_dynamic_processor' , trust_remote_code=__SCREAMING_SNAKE_CASE ) self.assertEqual(processor.__class__.__name__ , 'NewProcessor' ) self.assertFalse(processor.special_attribute_present ) self.assertFalse(processor.feature_extractor.special_attribute_present ) self.assertFalse(processor.tokenizer.special_attribute_present ) # If remote is enabled, we load from the Hub. snake_case_ = AutoProcessor.from_pretrained( 'hf-internal-testing/test_dynamic_processor' , trust_remote_code=__SCREAMING_SNAKE_CASE ) self.assertEqual(processor.__class__.__name__ , 'NewProcessor' ) self.assertTrue(processor.special_attribute_present ) self.assertTrue(processor.feature_extractor.special_attribute_present ) self.assertTrue(processor.tokenizer.special_attribute_present ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] if CustomConfig in PROCESSOR_MAPPING._extra_content: del PROCESSOR_MAPPING._extra_content[CustomConfig] def _UpperCamelCase ( self ) -> Tuple: snake_case_ = AutoProcessor.from_pretrained('hf-internal-testing/tiny-random-bert' ) self.assertEqual(processor.__class__.__name__ , 'BertTokenizerFast' ) def _UpperCamelCase ( self ) -> List[str]: snake_case_ = AutoProcessor.from_pretrained('hf-internal-testing/tiny-random-convnext' ) self.assertEqual(processor.__class__.__name__ , 'ConvNextImageProcessor' ) @is_staging_test class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' lowerCAmelCase = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''bla''', '''blou'''] @classmethod def _UpperCamelCase ( cls ) -> Dict: snake_case_ = TOKEN HfFolder.save_token(__SCREAMING_SNAKE_CASE ) @classmethod def _UpperCamelCase ( cls ) -> int: try: delete_repo(token=cls._token , repo_id='test-processor' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='valid_org/test-processor-org' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='test-dynamic-processor' ) except HTTPError: pass def _UpperCamelCase ( self ) -> Union[str, Any]: snake_case_ = WavaVecaProcessor.from_pretrained(__SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained( os.path.join(__SCREAMING_SNAKE_CASE , 'test-processor' ) , push_to_hub=__SCREAMING_SNAKE_CASE , use_auth_token=self._token ) snake_case_ = WavaVecaProcessor.from_pretrained(F'''{USER}/test-processor''' ) for k, v in processor.feature_extractor.__dict__.items(): self.assertEqual(__SCREAMING_SNAKE_CASE , getattr(new_processor.feature_extractor , __SCREAMING_SNAKE_CASE ) ) self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab() ) def _UpperCamelCase ( self ) -> Optional[Any]: snake_case_ = WavaVecaProcessor.from_pretrained(__SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained( os.path.join(__SCREAMING_SNAKE_CASE , 'test-processor-org' ) , push_to_hub=__SCREAMING_SNAKE_CASE , use_auth_token=self._token , organization='valid_org' , ) snake_case_ = WavaVecaProcessor.from_pretrained('valid_org/test-processor-org' ) for k, v in processor.feature_extractor.__dict__.items(): self.assertEqual(__SCREAMING_SNAKE_CASE , getattr(new_processor.feature_extractor , __SCREAMING_SNAKE_CASE ) ) self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab() ) def _UpperCamelCase ( self ) -> Tuple: CustomFeatureExtractor.register_for_auto_class() CustomTokenizer.register_for_auto_class() CustomProcessor.register_for_auto_class() snake_case_ = CustomFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ = os.path.join(__SCREAMING_SNAKE_CASE , 'vocab.txt' ) with open(__SCREAMING_SNAKE_CASE , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) snake_case_ = CustomTokenizer(__SCREAMING_SNAKE_CASE ) snake_case_ = CustomProcessor(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: create_repo(F'''{USER}/test-dynamic-processor''' , token=self._token ) snake_case_ = Repository(__SCREAMING_SNAKE_CASE , clone_from=F'''{USER}/test-dynamic-processor''' , token=self._token ) processor.save_pretrained(__SCREAMING_SNAKE_CASE ) # This has added the proper auto_map field to the feature extractor config self.assertDictEqual( processor.feature_extractor.auto_map , { 'AutoFeatureExtractor': 'custom_feature_extraction.CustomFeatureExtractor', 'AutoProcessor': 'custom_processing.CustomProcessor', } , ) # This has added the proper auto_map field to the tokenizer config with open(os.path.join(__SCREAMING_SNAKE_CASE , 'tokenizer_config.json' ) ) as f: snake_case_ = json.load(__SCREAMING_SNAKE_CASE ) self.assertDictEqual( tokenizer_config['auto_map'] , { 'AutoTokenizer': ['custom_tokenization.CustomTokenizer', None], 'AutoProcessor': 'custom_processing.CustomProcessor', } , ) # The code has been copied from fixtures self.assertTrue(os.path.isfile(os.path.join(__SCREAMING_SNAKE_CASE , 'custom_feature_extraction.py' ) ) ) self.assertTrue(os.path.isfile(os.path.join(__SCREAMING_SNAKE_CASE , 'custom_tokenization.py' ) ) ) self.assertTrue(os.path.isfile(os.path.join(__SCREAMING_SNAKE_CASE , 'custom_processing.py' ) ) ) repo.push_to_hub() snake_case_ = AutoProcessor.from_pretrained(F'''{USER}/test-dynamic-processor''' , trust_remote_code=__SCREAMING_SNAKE_CASE ) # Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module self.assertEqual(new_processor.__class__.__name__ , 'CustomProcessor' )
178
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch UpperCAmelCase : int = random.Random() def a__ ( a__ , a__=1.0 , a__=None , a__=None ): """simple docstring""" if rng is None: __SCREAMING_SNAKE_CASE = global_rng __SCREAMING_SNAKE_CASE = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : str=7 , __SCREAMING_SNAKE_CASE : List[str]=400 , __SCREAMING_SNAKE_CASE : Any=2_000 , __SCREAMING_SNAKE_CASE : List[str]=10 , __SCREAMING_SNAKE_CASE : Optional[int]=160 , __SCREAMING_SNAKE_CASE : List[str]=8 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.0 , __SCREAMING_SNAKE_CASE : Dict=4_000 , __SCREAMING_SNAKE_CASE : Optional[int]=False , __SCREAMING_SNAKE_CASE : List[Any]=True , ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = min_seq_length __SCREAMING_SNAKE_CASE = max_seq_length __SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = return_attention_mask __SCREAMING_SNAKE_CASE = do_normalize __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = chunk_length __SCREAMING_SNAKE_CASE = hop_length def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring""" return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Union[str, Any]: """simple docstring""" def _flatten(__SCREAMING_SNAKE_CASE : Dict ): return list(itertools.chain(*__SCREAMING_SNAKE_CASE ) ) if equal_length: __SCREAMING_SNAKE_CASE = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size __SCREAMING_SNAKE_CASE = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = WhisperFeatureExtractor if is_speech_available() else None def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = WhisperFeatureExtractionTester(self ) def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = os.path.join(__SCREAMING_SNAKE_CASE , """feat_extract.json""" ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] # Test feature size __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , padding="""max_length""" , return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input __SCREAMING_SNAKE_CASE = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test batched __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in (800, 800, 800)] __SCREAMING_SNAKE_CASE = np.asarray(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test truncation required __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] __SCREAMING_SNAKE_CASE = [x[: feature_extractor.n_samples] for x in speech_inputs] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs_truncated] __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" import torch __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = np.random.rand(100 , 32 ).astype(np.floataa ) __SCREAMING_SNAKE_CASE = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Tuple ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech __SCREAMING_SNAKE_CASE = ds.sort("""id""" ).select(range(__SCREAMING_SNAKE_CASE ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def UpperCAmelCase__ ( self : Tuple ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on __SCREAMING_SNAKE_CASE = self._load_datasamples(1 ) __SCREAMING_SNAKE_CASE = WhisperFeatureExtractor() __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).input_features self.assertEqual(input_features.shape , (1, 80, 3_000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) ) def UpperCAmelCase__ ( self : List[Any] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = self._load_datasamples(1 )[0] __SCREAMING_SNAKE_CASE = ((audio - audio.min()) / (audio.max() - audio.min())) * 65_535 # Rescale to [0, 65535] to show issue __SCREAMING_SNAKE_CASE = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(np.all(np.mean(__SCREAMING_SNAKE_CASE ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(__SCREAMING_SNAKE_CASE ) - 1 ) < 1E-3 ) )
267
0
from collections import deque class A__ : def __init__( self : List[str] , _UpperCAmelCase : str , _UpperCAmelCase : int , _UpperCAmelCase : int ) -> None: """simple docstring""" __lowercase = process_name # process name __lowercase = arrival_time # arrival time of the process # completion time of finished process or last interrupted time __lowercase = arrival_time __lowercase = burst_time # remaining burst time __lowercase = 0 # total time of the process wait in ready queue __lowercase = 0 # time from arrival time to completion time class A__ : def __init__( self : List[Any] , _UpperCAmelCase : int , _UpperCAmelCase : list[int] , _UpperCAmelCase : deque[Process] , _UpperCAmelCase : int , ) -> None: """simple docstring""" __lowercase = number_of_queues # time slice of queues that round robin algorithm applied __lowercase = time_slices # unfinished process is in this ready_queue __lowercase = queue # current time __lowercase = current_time # finished process is in this sequence queue __lowercase = deque() def a__ ( self : Dict ) -> list[str]: """simple docstring""" __lowercase = [] for i in range(len(self.finish_queue ) ): sequence.append(self.finish_queue[i].process_name ) return sequence def a__ ( self : int , _UpperCAmelCase : list[Process] ) -> list[int]: """simple docstring""" __lowercase = [] for i in range(len(__SCREAMING_SNAKE_CASE ) ): waiting_times.append(queue[i].waiting_time ) return waiting_times def a__ ( self : Optional[int] , _UpperCAmelCase : list[Process] ) -> list[int]: """simple docstring""" __lowercase = [] for i in range(len(__SCREAMING_SNAKE_CASE ) ): turnaround_times.append(queue[i].turnaround_time ) return turnaround_times def a__ ( self : Union[str, Any] , _UpperCAmelCase : list[Process] ) -> list[int]: """simple docstring""" __lowercase = [] for i in range(len(__SCREAMING_SNAKE_CASE ) ): completion_times.append(queue[i].stop_time ) return completion_times def a__ ( self : Dict , _UpperCAmelCase : deque[Process] ) -> list[int]: """simple docstring""" return [q.burst_time for q in queue] def a__ ( self : Optional[Any] , _UpperCAmelCase : Process ) -> int: """simple docstring""" process.waiting_time += self.current_time - process.stop_time return process.waiting_time def a__ ( self : int , _UpperCAmelCase : deque[Process] ) -> deque[Process]: """simple docstring""" __lowercase = deque() # sequence deque of finished process while len(__SCREAMING_SNAKE_CASE ) != 0: __lowercase = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of current process self.update_waiting_time(__SCREAMING_SNAKE_CASE ) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 __lowercase = 0 # set the process's turnaround time because it is finished __lowercase = self.current_time - cp.arrival_time # set the completion time __lowercase = self.current_time # add the process to queue that has finished queue finished.append(__SCREAMING_SNAKE_CASE ) self.finish_queue.extend(__SCREAMING_SNAKE_CASE ) # add finished process to finish queue # FCFS will finish all remaining processes return finished def a__ ( self : int , _UpperCAmelCase : deque[Process] , _UpperCAmelCase : int ) -> tuple[deque[Process], deque[Process]]: """simple docstring""" __lowercase = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(__SCREAMING_SNAKE_CASE ) ): __lowercase = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of unfinished processes self.update_waiting_time(__SCREAMING_SNAKE_CASE ) # if the burst time of process is bigger than time-slice if cp.burst_time > time_slice: # use CPU for only time-slice self.current_time += time_slice # update remaining burst time cp.burst_time -= time_slice # update end point time __lowercase = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(__SCREAMING_SNAKE_CASE ) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished __lowercase = 0 # set the finish time __lowercase = self.current_time # update the process' turnaround time because it is finished __lowercase = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(__SCREAMING_SNAKE_CASE ) self.finish_queue.extend(__SCREAMING_SNAKE_CASE ) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def a__ ( self : Dict ) -> deque[Process]: """simple docstring""" for i in range(self.number_of_queues - 1 ): __lowercase , __lowercase = self.round_robin( self.ready_queue , self.time_slices[i] ) # the last queue has first_come_first_served algorithm self.first_come_first_served(self.ready_queue ) return self.finish_queue if __name__ == "__main__": import doctest SCREAMING_SNAKE_CASE__ = Process("""P1""", 0, 53) SCREAMING_SNAKE_CASE__ = Process("""P2""", 0, 17) SCREAMING_SNAKE_CASE__ = Process("""P3""", 0, 68) SCREAMING_SNAKE_CASE__ = Process("""P4""", 0, 24) SCREAMING_SNAKE_CASE__ = 3 SCREAMING_SNAKE_CASE__ = [17, 25] SCREAMING_SNAKE_CASE__ = deque([Pa, Pa, Pa, Pa]) if len(time_slices) != number_of_queues - 1: raise SystemExit(0) doctest.testmod(extraglobs={"""queue""": deque([Pa, Pa, Pa, Pa])}) SCREAMING_SNAKE_CASE__ = Process("""P1""", 0, 53) SCREAMING_SNAKE_CASE__ = Process("""P2""", 0, 17) SCREAMING_SNAKE_CASE__ = Process("""P3""", 0, 68) SCREAMING_SNAKE_CASE__ = Process("""P4""", 0, 24) SCREAMING_SNAKE_CASE__ = 3 SCREAMING_SNAKE_CASE__ = [17, 25] SCREAMING_SNAKE_CASE__ = deque([Pa, Pa, Pa, Pa]) SCREAMING_SNAKE_CASE__ = MLFQ(number_of_queues, time_slices, queue, 0) SCREAMING_SNAKE_CASE__ = mlfq.multi_level_feedback_queue() # print total waiting times of processes(P1, P2, P3, P4) print( F'''waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [Pa, Pa, Pa, Pa])}''' ) # print completion times of processes(P1, P2, P3, P4) print( F'''completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [Pa, Pa, Pa, Pa])}''' ) # print total turnaround times of processes(P1, P2, P3, P4) print( F'''turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [Pa, Pa, Pa, Pa])}''' ) # print sequence of finished processes print( F'''sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}''' )
325
'''simple docstring''' from __future__ import annotations def a__ ( a__ , a__ , a__ ): """simple docstring""" if len(a__ ) == 0: raise ValueError("""find_max() arg is an empty sequence""" ) if ( left >= len(a__ ) or left < -len(a__ ) or right >= len(a__ ) or right < -len(a__ ) ): raise IndexError("""list index out of range""" ) if left == right: return nums[left] __SCREAMING_SNAKE_CASE = (left + right) >> 1 # the middle __SCREAMING_SNAKE_CASE = find_max(a__ , a__ , a__ ) # find max in range[left, mid] __SCREAMING_SNAKE_CASE = find_max(a__ , mid + 1 , a__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
267
0
'''simple docstring''' import unittest from transformers import TrOCRConfig from transformers.testing_utils import is_torch_available, require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM @require_torch class _lowerCAmelCase : def __init__(self , lowercase , lowercase=99 , lowercase=13 , lowercase=16 , lowercase=7 , lowercase=True , lowercase=True , lowercase=True , lowercase=False , lowercase=True , lowercase=2 , lowercase=32 , lowercase=4 , lowercase=4 , lowercase=30 , lowercase=0 , lowercase=1 , lowercase=2 , lowercase=None , ): A_ : Optional[int] = parent A_ : List[Any] = batch_size A_ : Any = decoder_seq_length # For common tests A_ : str = self.decoder_seq_length A_ : Optional[int] = is_training A_ : Union[str, Any] = use_attention_mask A_ : Union[str, Any] = use_labels A_ : int = vocab_size A_ : int = d_model A_ : List[str] = d_model A_ : Optional[int] = decoder_layers A_ : Union[str, Any] = decoder_layers A_ : Union[str, Any] = decoder_ffn_dim A_ : Dict = decoder_attention_heads A_ : str = decoder_attention_heads A_ : Union[str, Any] = eos_token_id A_ : Any = bos_token_id A_ : Any = pad_token_id A_ : Optional[int] = decoder_start_token_id A_ : str = use_cache A_ : List[str] = max_position_embeddings A_ : Optional[Any] = None A_ : int = decoder_seq_length A_ : List[str] = 2 A_ : int = 1 def _a (self ): A_ : Union[str, Any] = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) A_ : Optional[Any] = None if self.use_attention_mask: A_ : List[Any] = ids_tensor([self.batch_size, self.decoder_seq_length] , vocab_size=2 ) A_ : Any = None if self.use_labels: A_ : Dict = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) A_ : str = TrOCRConfig( vocab_size=self.vocab_size , d_model=self.d_model , decoder_layers=self.decoder_layers , decoder_ffn_dim=self.decoder_ffn_dim , decoder_attention_heads=self.decoder_attention_heads , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , use_cache=self.use_cache , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , max_position_embeddings=self.max_position_embeddings , ) return (config, input_ids, attention_mask, lm_labels) def _a (self , lowercase , lowercase , lowercase , lowercase , ): A_ : int = True A_ : Tuple = TrOCRDecoder(config=__SCREAMING_SNAKE_CASE ).to(__SCREAMING_SNAKE_CASE ).eval() A_ : Optional[int] = input_ids[:2] input_ids[input_ids == 0] += 1 # first forward pass A_ : int = model(__SCREAMING_SNAKE_CASE , use_cache=__SCREAMING_SNAKE_CASE ) A_ : Dict = model(__SCREAMING_SNAKE_CASE ) A_ : List[str] = model(__SCREAMING_SNAKE_CASE , use_cache=__SCREAMING_SNAKE_CASE ) self.parent.assertTrue(len(__SCREAMING_SNAKE_CASE ) == len(__SCREAMING_SNAKE_CASE ) ) self.parent.assertTrue(len(__SCREAMING_SNAKE_CASE ) == len(__SCREAMING_SNAKE_CASE ) + 1 ) A_ : str = outputs["""past_key_values"""] # create hypothetical next token and extent to next_input_ids A_ : Union[str, Any] = ids_tensor((2, 1) , config.vocab_size - 1 ) + 1 # append to next input_ids and A_ : List[Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) A_ : Optional[int] = model(__SCREAMING_SNAKE_CASE )["""last_hidden_state"""] A_ : int = model(__SCREAMING_SNAKE_CASE , past_key_values=__SCREAMING_SNAKE_CASE )["""last_hidden_state"""] # select random slice A_ : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() A_ : List[Any] = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach() A_ : Tuple = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice assert torch.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) def _a (self ): A_ : Union[str, Any] = self.prepare_config_and_inputs() A_, A_, A_, A_ : Optional[Any] = config_and_inputs A_ : Optional[Any] = {"""input_ids""": input_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_torch class _lowerCAmelCase ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): __SCREAMING_SNAKE_CASE : List[Any] = (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else () __SCREAMING_SNAKE_CASE : Optional[Any] = (TrOCRForCausalLM,) if is_torch_available() else () __SCREAMING_SNAKE_CASE : List[str] = {'text-generation': TrOCRForCausalLM} if is_torch_available() else {} __SCREAMING_SNAKE_CASE : int = True __SCREAMING_SNAKE_CASE : Union[str, Any] = False def _a (self ): A_ : Any = TrOCRStandaloneDecoderModelTester(self , is_training=__SCREAMING_SNAKE_CASE ) A_ : int = ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE ) def _a (self ): pass def _a (self ): pass def _a (self ): pass def _a (self ): self.config_tester.run_common_tests() def _a (self ): A_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past(*__SCREAMING_SNAKE_CASE ) def _a (self ): return @unittest.skip("""The model doesn't support left padding""" ) # and it's not used enough to be worth fixing :) def _a (self ): pass
206
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) # Initialize Result __SCREAMING_SNAKE_CASE = [] # Traverse through all denomination for denomination in reversed(a__ ): # Find denominations while int(a__ ) >= int(a__ ): total_value -= int(a__ ) answer.append(a__ ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase : Dict = [] UpperCAmelCase : List[str] = '0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): UpperCAmelCase : List[str] = int(input('Enter the number of denominations you want to add: ').strip()) for i in range(0, n): denominations.append(int(input(f"""Denomination {i}: """).strip())) UpperCAmelCase : str = input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter UpperCAmelCase : int = [1, 2, 5, 1_0, 2_0, 5_0, 1_0_0, 5_0_0, 2_0_0_0] UpperCAmelCase : Any = input('Enter the change you want to make: ').strip() if int(value) == 0 or int(value) < 0: print('The total value cannot be zero or negative.') else: print(f"""Following is minimal change for {value}: """) UpperCAmelCase : Any = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
267
0
'''simple docstring''' from dataclasses import dataclass, field from typing import Optional from transformers import AutoConfig, AutoImageProcessor, AutoTokenizer, FlaxVisionEncoderDecoderModel, HfArgumentParser @dataclass class A : __magic_name__ = field( metadata={'''help''': '''The output directory where the model will be written.'''} , ) __magic_name__ = field( metadata={ '''help''': ( '''The encoder model checkpoint for weights initialization.''' '''Don\'t set if you want to train an encoder model from scratch.''' ) } , ) __magic_name__ = field( metadata={ '''help''': ( '''The decoder model checkpoint for weights initialization.''' '''Don\'t set if you want to train a decoder model from scratch.''' ) } , ) __magic_name__ = field( default=__snake_case , metadata={'''help''': '''Pretrained encoder config name or path if not the same as encoder_model_name'''} ) __magic_name__ = field( default=__snake_case , metadata={'''help''': '''Pretrained decoder config name or path if not the same as decoder_model_name'''} ) def lowerCAmelCase_ ( ): '''simple docstring''' A : str = HfArgumentParser((ModelArguments,) ) ((A ), ) : Optional[Any] = parser.parse_args_into_dataclasses() # Load pretrained model and tokenizer # Use explicit specified encoder config if model_args.encoder_config_name: A : List[Any] = AutoConfig.from_pretrained(model_args.encoder_config_name ) # Use pretrained encoder model's config else: A : Tuple = AutoConfig.from_pretrained(model_args.encoder_model_name_or_path ) # Use explicit specified decoder config if model_args.decoder_config_name: A : Union[str, Any] = AutoConfig.from_pretrained(model_args.decoder_config_name ) # Use pretrained decoder model's config else: A : Optional[int] = AutoConfig.from_pretrained(model_args.decoder_model_name_or_path ) # necessary for `from_encoder_decoder_pretrained` when `decoder_config` is passed A : Dict = True A : int = True A : Optional[int] = FlaxVisionEncoderDecoderModel.from_encoder_decoder_pretrained( encoder_pretrained_model_name_or_path=model_args.encoder_model_name_or_path , decoder_pretrained_model_name_or_path=model_args.decoder_model_name_or_path , encoder_config=a__ , decoder_config=a__ , ) # GPT2 only has bos/eos tokens but not decoder_start/pad tokens A : Union[str, Any] = decoder_config.decoder_start_token_id A : str = decoder_config.pad_token_id if decoder_start_token_id is None: A : Any = decoder_config.bos_token_id if pad_token_id is None: A : Dict = decoder_config.eos_token_id # This is necessary to make Flax's generate() work A : List[str] = decoder_config.eos_token_id A : List[str] = decoder_start_token_id A : List[Any] = pad_token_id A : Any = AutoImageProcessor.from_pretrained(model_args.encoder_model_name_or_path ) A : List[str] = AutoTokenizer.from_pretrained(model_args.decoder_model_name_or_path ) A : Optional[int] = tokenizer.convert_ids_to_tokens(model.config.pad_token_id ) model.save_pretrained(model_args.output_dir ) image_processor.save_pretrained(model_args.output_dir ) tokenizer.save_pretrained(model_args.output_dir ) if __name__ == "__main__": main()
3
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu UpperCAmelCase : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def a__ ( a__ , a__=None , a__=None , a__=None ): """simple docstring""" __SCREAMING_SNAKE_CASE = True while ask_again: __SCREAMING_SNAKE_CASE = input(a__ ) try: if default is not None and len(a__ ) == 0: return default return convert_value(a__ ) if convert_value is not None else result except Exception: if error_message is not None: print(a__ ) def a__ ( a__ , a__=[] , a__=None , a__=0 ): """simple docstring""" __SCREAMING_SNAKE_CASE = BulletMenu(a__ , a__ ) __SCREAMING_SNAKE_CASE = menu.run(default_choice=a__ ) return convert_value(a__ ) if convert_value is not None else result def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value] ) def a__ ( a__ ): """simple docstring""" return {"yes": True, "no": False}[value.lower()] class lowerCAmelCase__ ( argparse.RawDescriptionHelpFormatter ): """simple docstring""" def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = super()._format_usage(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = usage.replace("""<command> [<args>] """ , """""" ) return usage
267
0
import doctest from collections import deque import numpy as np class __A: def __init__( self ) -> None: '''simple docstring''' __a = [2, 1, 2, -1] __a = [1, 2, 3, 4] def SCREAMING_SNAKE_CASE_ ( self ) -> list[float]: '''simple docstring''' __a = len(self.first_signal ) __a = len(self.second_signal ) __a = max(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # create a zero matrix of max_length x max_length __a = [[0] * max_length for i in range(__SCREAMING_SNAKE_CASE )] # fills the smaller signal with zeros to make both signals of same length if length_first_signal < length_second_signal: self.first_signal += [0] * (max_length - length_first_signal) elif length_first_signal > length_second_signal: self.second_signal += [0] * (max_length - length_second_signal) for i in range(__SCREAMING_SNAKE_CASE ): __a = deque(self.second_signal ) rotated_signal.rotate(__SCREAMING_SNAKE_CASE ) for j, item in enumerate(__SCREAMING_SNAKE_CASE ): matrix[i][j] += item # multiply the matrix with the first signal __a = np.matmul(np.transpose(__SCREAMING_SNAKE_CASE ) , np.transpose(self.first_signal ) ) # rounding-off to two decimal places return [round(__SCREAMING_SNAKE_CASE , 2 ) for i in final_signal] if __name__ == "__main__": doctest.testmod()
6
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) if n == 0: return 0 __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + naive_cut_rod_recursive(n - i , a__ ) ) return max_revue def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ ): """simple docstring""" if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , a__ , a__ ) , ) __SCREAMING_SNAKE_CASE = max_revenue return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] __SCREAMING_SNAKE_CASE = 0 for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max_rev[i] for j in range(1 , i + 1 ): __SCREAMING_SNAKE_CASE = max(a__ , prices[j - 1] + max_rev[i - j] ) __SCREAMING_SNAKE_CASE = max_revenue_i return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" if n < 0: __SCREAMING_SNAKE_CASE = F'n must be greater than or equal to 0. Got n = {n}' raise ValueError(a__ ) if n > len(a__ ): __SCREAMING_SNAKE_CASE = ( """Each integral piece of rod must have a corresponding price. """ F'Got n = {n} but length of prices = {len(a__ )}' ) raise ValueError(a__ ) def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = [6, 10, 12, 15, 20, 23] __SCREAMING_SNAKE_CASE = len(a__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __SCREAMING_SNAKE_CASE = 36 __SCREAMING_SNAKE_CASE = top_down_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = bottom_up_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = naive_cut_rod_recursive(a__ , a__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
267
0
"""simple docstring""" import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, ) from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class UpperCAmelCase : """simple docstring""" def __init__( self , _UpperCAmelCase , _UpperCAmelCase=2 , _UpperCAmelCase=3 , _UpperCAmelCase=4 , _UpperCAmelCase=2 , _UpperCAmelCase=7 , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=99 , _UpperCAmelCase=36 , _UpperCAmelCase=3 , _UpperCAmelCase=4 , _UpperCAmelCase=37 , _UpperCAmelCase="gelu" , _UpperCAmelCase=0.1 , _UpperCAmelCase=0.1 , _UpperCAmelCase=512 , _UpperCAmelCase=16 , _UpperCAmelCase=2 , _UpperCAmelCase=0.02 , _UpperCAmelCase=6 , _UpperCAmelCase=6 , _UpperCAmelCase=3 , _UpperCAmelCase=4 , _UpperCAmelCase=None , _UpperCAmelCase=1000 , ): lowercase__: Any = parent lowercase__: Any = batch_size lowercase__: Optional[Any] = num_channels lowercase__: str = image_size lowercase__: List[str] = patch_size lowercase__: Union[str, Any] = text_seq_length lowercase__: Dict = is_training lowercase__: Union[str, Any] = use_input_mask lowercase__: Optional[int] = use_token_type_ids lowercase__: int = use_labels lowercase__: Optional[int] = vocab_size lowercase__: Optional[int] = hidden_size lowercase__: Any = num_hidden_layers lowercase__: Any = num_attention_heads lowercase__: Optional[int] = intermediate_size lowercase__: int = hidden_act lowercase__: List[Any] = hidden_dropout_prob lowercase__: str = attention_probs_dropout_prob lowercase__: str = max_position_embeddings lowercase__: List[str] = type_vocab_size lowercase__: Dict = type_sequence_label_size lowercase__: Optional[int] = initializer_range lowercase__: int = coordinate_size lowercase__: int = shape_size lowercase__: Tuple = num_labels lowercase__: Dict = num_choices lowercase__: Tuple = scope lowercase__: Tuple = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) lowercase__: Optional[int] = text_seq_length lowercase__: int = (image_size // patch_size) ** 2 + 1 lowercase__: Optional[int] = self.text_seq_length + self.image_seq_length def _snake_case ( self ): lowercase__: Union[str, Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) lowercase__: Optional[Any] = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: lowercase__: Any = bbox[i, j, 3] lowercase__: Any = bbox[i, j, 1] lowercase__: Dict = t if bbox[i, j, 2] < bbox[i, j, 0]: lowercase__: str = bbox[i, j, 2] lowercase__: Union[str, Any] = bbox[i, j, 0] lowercase__: List[str] = t lowercase__: Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase__: Optional[int] = None if self.use_input_mask: lowercase__: Any = random_attention_mask([self.batch_size, self.text_seq_length] ) lowercase__: int = None if self.use_token_type_ids: lowercase__: Tuple = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) lowercase__: int = None lowercase__: Any = None if self.use_labels: lowercase__: List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase__: str = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) lowercase__: List[Any] = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def _snake_case ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): lowercase__: Tuple = LayoutLMvaModel(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() # text + image lowercase__: int = model(__SCREAMING_SNAKE_CASE , pixel_values=__SCREAMING_SNAKE_CASE ) lowercase__: int = model( __SCREAMING_SNAKE_CASE , bbox=__SCREAMING_SNAKE_CASE , pixel_values=__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE ) lowercase__: List[str] = model(__SCREAMING_SNAKE_CASE , bbox=__SCREAMING_SNAKE_CASE , pixel_values=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE ) lowercase__: List[Any] = model(__SCREAMING_SNAKE_CASE , bbox=__SCREAMING_SNAKE_CASE , pixel_values=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only lowercase__: Optional[int] = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only lowercase__: List[str] = model(pixel_values=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def _snake_case ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): lowercase__: Tuple = self.num_labels lowercase__: str = LayoutLMvaForSequenceClassification(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() lowercase__: Optional[Any] = model( __SCREAMING_SNAKE_CASE , bbox=__SCREAMING_SNAKE_CASE , pixel_values=__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): lowercase__: Union[str, Any] = self.num_labels lowercase__: Optional[int] = LayoutLMvaForTokenClassification(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() lowercase__: Tuple = model( __SCREAMING_SNAKE_CASE , bbox=__SCREAMING_SNAKE_CASE , pixel_values=__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def _snake_case ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): lowercase__: Dict = LayoutLMvaForQuestionAnswering(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() lowercase__: int = model( __SCREAMING_SNAKE_CASE , bbox=__SCREAMING_SNAKE_CASE , pixel_values=__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , start_positions=__SCREAMING_SNAKE_CASE , end_positions=__SCREAMING_SNAKE_CASE , ) 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 _snake_case ( self ): lowercase__: Dict = self.prepare_config_and_inputs() ( ( lowercase__ ), ( lowercase__ ), ( lowercase__ ), ( lowercase__ ), ( lowercase__ ), ( lowercase__ ), ( lowercase__ ), ( lowercase__ ), ): Any = config_and_inputs lowercase__: Optional[int] = { '''input_ids''': input_ids, '''bbox''': bbox, '''pixel_values''': pixel_values, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class UpperCAmelCase (_UpperCAmelCase ,_UpperCAmelCase ,unittest.TestCase ): """simple docstring""" _UpperCAmelCase :Any = False _UpperCAmelCase :Optional[int] = False _UpperCAmelCase :Dict = False _UpperCAmelCase :List[Any] = ( ( LayoutLMvaModel, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaForQuestionAnswering, ) if is_torch_available() else () ) _UpperCAmelCase :int = ( {"document-question-answering": LayoutLMvaForQuestionAnswering, "feature-extraction": LayoutLMvaModel} if is_torch_available() else {} ) def _snake_case ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): return True def _snake_case ( self ): lowercase__: Optional[int] = LayoutLMvaModelTester(self ) lowercase__: Optional[int] = ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , hidden_size=37 ) def _snake_case ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=False ): lowercase__: Optional[Any] = copy.deepcopy(__SCREAMING_SNAKE_CASE ) if model_class in get_values(__SCREAMING_SNAKE_CASE ): lowercase__: Dict = { k: v.unsqueeze(1 ).expand(-1 , self.model_tester.num_choices , -1 ).contiguous() if isinstance(__SCREAMING_SNAKE_CASE , torch.Tensor ) and v.ndim > 1 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(__SCREAMING_SNAKE_CASE ): lowercase__: str = torch.ones(self.model_tester.batch_size , dtype=torch.long , device=__SCREAMING_SNAKE_CASE ) elif model_class in get_values(__SCREAMING_SNAKE_CASE ): lowercase__: List[str] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__SCREAMING_SNAKE_CASE ) lowercase__: Dict = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__SCREAMING_SNAKE_CASE ) elif model_class in [ *get_values(__SCREAMING_SNAKE_CASE ), ]: lowercase__: Optional[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__SCREAMING_SNAKE_CASE ) elif model_class in [ *get_values(__SCREAMING_SNAKE_CASE ), ]: lowercase__: Optional[Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=torch.long , device=__SCREAMING_SNAKE_CASE , ) return inputs_dict def _snake_case ( self ): self.config_tester.run_common_tests() def _snake_case ( self ): lowercase__: Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): lowercase__: List[Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: lowercase__: List[str] = type self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): lowercase__: List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): lowercase__: Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): lowercase__: Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__SCREAMING_SNAKE_CASE ) @slow def _snake_case ( self ): for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase__: Tuple = LayoutLMvaModel.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE__ ( ) -> Any: lowercase__: Any = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch class UpperCAmelCase (unittest.TestCase ): """simple docstring""" @cached_property def _snake_case ( self ): return LayoutLMvaImageProcessor(apply_ocr=__SCREAMING_SNAKE_CASE ) if is_vision_available() else None @slow def _snake_case ( self ): lowercase__: Optional[Any] = LayoutLMvaModel.from_pretrained('''microsoft/layoutlmv3-base''' ).to(__SCREAMING_SNAKE_CASE ) lowercase__: int = self.default_image_processor lowercase__: Tuple = prepare_img() lowercase__: str = image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).pixel_values.to(__SCREAMING_SNAKE_CASE ) lowercase__: Union[str, Any] = torch.tensor([[1, 2]] ) lowercase__: Any = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]] ).unsqueeze(0 ) # forward pass lowercase__: str = model( input_ids=input_ids.to(__SCREAMING_SNAKE_CASE ) , bbox=bbox.to(__SCREAMING_SNAKE_CASE ) , pixel_values=pixel_values.to(__SCREAMING_SNAKE_CASE ) , ) # verify the logits lowercase__: List[str] = torch.Size((1, 199, 768) ) self.assertEqual(outputs.last_hidden_state.shape , __SCREAMING_SNAKE_CASE ) lowercase__: Tuple = torch.tensor( [[-0.0_529, 0.3_618, 0.1_632], [-0.1_587, -0.1_667, -0.0_400], [-0.1_557, -0.1_671, -0.0_505]] ).to(__SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , __SCREAMING_SNAKE_CASE , atol=1e-4 ) )
177
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : Union[str, Any] = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ 'SEW_PRETRAINED_MODEL_ARCHIVE_LIST', 'SEWForCTC', 'SEWForSequenceClassification', 'SEWModel', 'SEWPreTrainedModel', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys UpperCAmelCase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
267
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a__ = { 'configuration_jukebox': [ 'JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP', 'JukeboxConfig', 'JukeboxPriorConfig', 'JukeboxVQVAEConfig', ], 'tokenization_jukebox': ['JukeboxTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ = [ 'JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST', 'JukeboxModel', 'JukeboxPreTrainedModel', 'JukeboxVQVAE', 'JukeboxPrior', ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys a__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
317
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = name __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = weight def __repr__( self : str ) -> Union[str, Any]: """simple docstring""" return f'{self.__class__.__name__}({self.name}, {self.value}, {self.weight})' def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" return self.value def UpperCAmelCase__ ( self : Any ) -> str: """simple docstring""" return self.name def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.weight def UpperCAmelCase__ ( self : int ) -> Tuple: """simple docstring""" return self.value / self.weight def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = [] for i in range(len(a__ ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = sorted(a__ , key=a__ , reverse=a__ ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 0.0, 0.0 for i in range(len(a__ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def a__ ( ): """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
267
0
"""simple docstring""" import unittest from diffusers.models.unet_ad_blocks import * # noqa F403 from diffusers.utils import torch_device from .test_unet_blocks_common import UNetBlockTesterMixin class __A ( A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : str = DownBlockaD # noqa F405 lowerCAmelCase : List[str] = "down" def UpperCAmelCase ( self : List[str] ) -> Tuple: """simple docstring""" lowercase__ : Dict = [-0.0232, -0.9869, 0.8054, -0.0637, -0.1688, -1.4264, 0.4470, -1.3394, 0.0904] super().test_output(__SCREAMING_SNAKE_CASE ) class __A ( A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : Union[str, Any] = ResnetDownsampleBlockaD # noqa F405 lowerCAmelCase : str = "down" def UpperCAmelCase ( self : Any ) -> Any: """simple docstring""" lowercase__ : Dict = [0.0710, 0.2410, -0.7320, -1.0757, -1.1343, 0.3540, -0.0133, -0.2576, 0.0948] super().test_output(__SCREAMING_SNAKE_CASE ) class __A ( A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : Union[str, Any] = AttnDownBlockaD # noqa F405 lowerCAmelCase : Optional[int] = "down" def UpperCAmelCase ( self : List[str] ) -> List[str]: """simple docstring""" lowercase__ : Optional[Any] = [0.0636, 0.8964, -0.6234, -1.0131, 0.0844, 0.4935, 0.3437, 0.0911, -0.2957] super().test_output(__SCREAMING_SNAKE_CASE ) class __A ( A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : Tuple = CrossAttnDownBlockaD # noqa F405 lowerCAmelCase : Optional[Any] = "down" def UpperCAmelCase ( self : Dict ) -> Tuple: """simple docstring""" lowercase__ , lowercase__ : Dict = super().prepare_init_args_and_inputs_for_common() lowercase__ : Any = 32 return init_dict, inputs_dict def UpperCAmelCase ( self : Any ) -> str: """simple docstring""" lowercase__ : Dict = [0.2238, -0.7396, -0.2255, -0.3829, 0.1925, 1.1665, 0.0603, -0.7295, 0.1983] super().test_output(__SCREAMING_SNAKE_CASE ) class __A ( A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : Dict = SimpleCrossAttnDownBlockaD # noqa F405 lowerCAmelCase : List[Any] = "down" @property def UpperCAmelCase ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return super().get_dummy_input(include_encoder_hidden_states=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" lowercase__ , lowercase__ : Union[str, Any] = super().prepare_init_args_and_inputs_for_common() lowercase__ : int = 32 return init_dict, inputs_dict @unittest.skipIf(torch_device == '''mps''' ,'''MPS result is not consistent''' ) def UpperCAmelCase ( self : Optional[int] ) -> str: """simple docstring""" lowercase__ : List[Any] = [0.7921, -0.0992, -0.1962, -0.7695, -0.4242, 0.7804, 0.4737, 0.2765, 0.3338] super().test_output(__SCREAMING_SNAKE_CASE ) class __A ( A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : Dict = SkipDownBlockaD # noqa F405 lowerCAmelCase : Any = "down" @property def UpperCAmelCase ( self : Union[str, Any] ) -> Dict: """simple docstring""" return super().get_dummy_input(include_skip_sample=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self : List[Any] ) -> Any: """simple docstring""" lowercase__ : int = [-0.0845, -0.2087, -0.2465, 0.0971, 0.1900, -0.0484, 0.2664, 0.4179, 0.5069] super().test_output(__SCREAMING_SNAKE_CASE ) class __A ( A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : int = AttnSkipDownBlockaD # noqa F405 lowerCAmelCase : List[Any] = "down" @property def UpperCAmelCase ( self : List[str] ) -> str: """simple docstring""" return super().get_dummy_input(include_skip_sample=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self : List[Any] ) -> List[Any]: """simple docstring""" lowercase__ : Any = [0.5539, 0.1609, 0.4924, 0.0537, -0.1995, 0.4050, 0.0979, -0.2721, -0.0642] super().test_output(__SCREAMING_SNAKE_CASE ) class __A ( A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : Optional[int] = DownEncoderBlockaD # noqa F405 lowerCAmelCase : Optional[Any] = "down" @property def UpperCAmelCase ( self : str ) -> Optional[int]: """simple docstring""" return super().get_dummy_input(include_temb=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self : int ) -> List[Any]: """simple docstring""" lowercase__ : List[str] = { '''in_channels''': 32, '''out_channels''': 32, } lowercase__ : Dict = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase ( self : str ) -> List[str]: """simple docstring""" lowercase__ : int = [1.1102, 0.5302, 0.4872, -0.0023, -0.8042, 0.0483, -0.3489, -0.5632, 0.7626] super().test_output(__SCREAMING_SNAKE_CASE ) class __A ( A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : Union[str, Any] = AttnDownEncoderBlockaD # noqa F405 lowerCAmelCase : Union[str, Any] = "down" @property def UpperCAmelCase ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" return super().get_dummy_input(include_temb=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self : Tuple ) -> Optional[Any]: """simple docstring""" lowercase__ : int = { '''in_channels''': 32, '''out_channels''': 32, } lowercase__ : Optional[int] = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase ( self : int ) -> Any: """simple docstring""" lowercase__ : Any = [0.8966, -0.1486, 0.8568, 0.8141, -0.9046, -0.1342, -0.0972, -0.7417, 0.1538] super().test_output(__SCREAMING_SNAKE_CASE ) class __A ( A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : int = UNetMidBlockaD # noqa F405 lowerCAmelCase : Optional[Any] = "mid" def UpperCAmelCase ( self : List[Any] ) -> Dict: """simple docstring""" lowercase__ : Union[str, Any] = { '''in_channels''': 32, '''temb_channels''': 128, } lowercase__ : Tuple = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase ( self : int ) -> List[Any]: """simple docstring""" lowercase__ : Dict = [-0.1062, 1.7248, 0.3494, 1.4569, -0.0910, -1.2421, -0.9984, 0.6736, 1.0028] super().test_output(__SCREAMING_SNAKE_CASE ) class __A ( A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : int = UNetMidBlockaDCrossAttn # noqa F405 lowerCAmelCase : str = "mid" def UpperCAmelCase ( self : List[Any] ) -> int: """simple docstring""" lowercase__ , lowercase__ : List[Any] = super().prepare_init_args_and_inputs_for_common() lowercase__ : Tuple = 32 return init_dict, inputs_dict def UpperCAmelCase ( self : str ) -> int: """simple docstring""" lowercase__ : Union[str, Any] = [0.0187, 2.4220, 0.4484, 1.1203, -0.6121, -1.5122, -0.8270, 0.7851, 1.8335] super().test_output(__SCREAMING_SNAKE_CASE ) class __A ( A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : Union[str, Any] = UNetMidBlockaDSimpleCrossAttn # noqa F405 lowerCAmelCase : List[str] = "mid" @property def UpperCAmelCase ( self : Optional[Any] ) -> List[str]: """simple docstring""" return super().get_dummy_input(include_encoder_hidden_states=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self : List[Any] ) -> Optional[int]: """simple docstring""" lowercase__ , lowercase__ : Optional[Any] = super().prepare_init_args_and_inputs_for_common() lowercase__ : List[Any] = 32 return init_dict, inputs_dict def UpperCAmelCase ( self : str ) -> Any: """simple docstring""" lowercase__ : Tuple = [0.7143, 1.9974, 0.5448, 1.3977, 0.1282, -1.1237, -1.4238, 0.5530, 0.8880] super().test_output(__SCREAMING_SNAKE_CASE ) class __A ( A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : Optional[int] = UpBlockaD # noqa F405 lowerCAmelCase : List[Any] = "up" @property def UpperCAmelCase ( self : str ) -> Optional[int]: """simple docstring""" return super().get_dummy_input(include_res_hidden_states_tuple=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self : Union[str, Any] ) -> Dict: """simple docstring""" lowercase__ : Optional[int] = [-0.2041, -0.4165, -0.3022, 0.0041, -0.6628, -0.7053, 0.1928, -0.0325, 0.0523] super().test_output(__SCREAMING_SNAKE_CASE ) class __A ( A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : List[str] = ResnetUpsampleBlockaD # noqa F405 lowerCAmelCase : List[str] = "up" @property def UpperCAmelCase ( self : Optional[int] ) -> str: """simple docstring""" return super().get_dummy_input(include_res_hidden_states_tuple=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self : Optional[int] ) -> Any: """simple docstring""" lowercase__ : List[Any] = [0.2287, 0.3549, -0.1346, 0.4797, -0.1715, -0.9649, 0.7305, -0.5864, -0.6244] super().test_output(__SCREAMING_SNAKE_CASE ) class __A ( A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : Optional[Any] = CrossAttnUpBlockaD # noqa F405 lowerCAmelCase : Tuple = "up" @property def UpperCAmelCase ( self : str ) -> Union[str, Any]: """simple docstring""" return super().get_dummy_input(include_res_hidden_states_tuple=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self : List[str] ) -> int: """simple docstring""" lowercase__ , lowercase__ : Optional[Any] = super().prepare_init_args_and_inputs_for_common() lowercase__ : List[Any] = 32 return init_dict, inputs_dict def UpperCAmelCase ( self : Any ) -> List[str]: """simple docstring""" lowercase__ : int = [-0.1403, -0.3515, -0.0420, -0.1425, 0.3167, 0.5094, -0.2181, 0.5931, 0.5582] super().test_output(__SCREAMING_SNAKE_CASE ) class __A ( A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : List[Any] = SimpleCrossAttnUpBlockaD # noqa F405 lowerCAmelCase : Tuple = "up" @property def UpperCAmelCase ( self : List[str] ) -> Dict: """simple docstring""" return super().get_dummy_input(include_res_hidden_states_tuple=__SCREAMING_SNAKE_CASE ,include_encoder_hidden_states=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self : Any ) -> List[Any]: """simple docstring""" lowercase__ , lowercase__ : Any = super().prepare_init_args_and_inputs_for_common() lowercase__ : int = 32 return init_dict, inputs_dict def UpperCAmelCase ( self : str ) -> List[str]: """simple docstring""" lowercase__ : Dict = [0.2645, 0.1480, 0.0909, 0.8044, -0.9758, -0.9083, 0.0994, -1.1453, -0.7402] super().test_output(__SCREAMING_SNAKE_CASE ) class __A ( A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : str = AttnUpBlockaD # noqa F405 lowerCAmelCase : int = "up" @property def UpperCAmelCase ( self : Union[str, Any] ) -> Tuple: """simple docstring""" return super().get_dummy_input(include_res_hidden_states_tuple=__SCREAMING_SNAKE_CASE ) @unittest.skipIf(torch_device == '''mps''' ,'''MPS result is not consistent''' ) def UpperCAmelCase ( self : List[Any] ) -> str: """simple docstring""" lowercase__ : str = [0.0979, 0.1326, 0.0021, 0.0659, 0.2249, 0.0059, 0.1132, 0.5952, 0.1033] super().test_output(__SCREAMING_SNAKE_CASE ) class __A ( A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : str = SkipUpBlockaD # noqa F405 lowerCAmelCase : List[str] = "up" @property def UpperCAmelCase ( self : Any ) -> int: """simple docstring""" return super().get_dummy_input(include_res_hidden_states_tuple=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self : List[str] ) -> Dict: """simple docstring""" lowercase__ : Union[str, Any] = [-0.0893, -0.1234, -0.1506, -0.0332, 0.0123, -0.0211, 0.0566, 0.0143, 0.0362] super().test_output(__SCREAMING_SNAKE_CASE ) class __A ( A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : Tuple = AttnSkipUpBlockaD # noqa F405 lowerCAmelCase : Union[str, Any] = "up" @property def UpperCAmelCase ( self : Optional[Any] ) -> int: """simple docstring""" return super().get_dummy_input(include_res_hidden_states_tuple=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" lowercase__ : int = [0.0361, 0.0617, 0.2787, -0.0350, 0.0342, 0.3421, -0.0843, 0.0913, 0.3015] super().test_output(__SCREAMING_SNAKE_CASE ) class __A ( A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : Tuple = UpDecoderBlockaD # noqa F405 lowerCAmelCase : List[str] = "up" @property def UpperCAmelCase ( self : Union[str, Any] ) -> List[str]: """simple docstring""" return super().get_dummy_input(include_temb=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self : Tuple ) -> Tuple: """simple docstring""" lowercase__ : str = {'''in_channels''': 32, '''out_channels''': 32} lowercase__ : Any = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" lowercase__ : Any = [0.4404, 0.1998, -0.9886, -0.3320, -0.3128, -0.7034, -0.6955, -0.2338, -0.3137] super().test_output(__SCREAMING_SNAKE_CASE ) class __A ( A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : Dict = AttnUpDecoderBlockaD # noqa F405 lowerCAmelCase : Any = "up" @property def UpperCAmelCase ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" return super().get_dummy_input(include_temb=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self : Union[str, Any] ) -> Any: """simple docstring""" lowercase__ : int = {'''in_channels''': 32, '''out_channels''': 32} lowercase__ : Optional[Any] = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase ( self : List[Any] ) -> str: """simple docstring""" lowercase__ : Any = [0.6738, 0.4491, 0.1055, 1.0710, 0.7316, 0.3339, 0.3352, 0.1023, 0.3568] super().test_output(__SCREAMING_SNAKE_CASE )
16
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE = ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on __SCREAMING_SNAKE_CASE = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) __SCREAMING_SNAKE_CASE = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] __SCREAMING_SNAKE_CASE = {"""unk_token""": """<unk>"""} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__SCREAMING_SNAKE_CASE ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48145466, 0.4578275, 0.40821073], """image_std""": [0.26862954, 0.26130258, 0.27577711], } __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , __SCREAMING_SNAKE_CASE ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> str: """simple docstring""" return CLIPTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple , **__SCREAMING_SNAKE_CASE : Any ) -> int: """simple docstring""" return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> List[str]: """simple docstring""" return CLIPImageProcessor.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(__SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_slow.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_fast.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) __SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = image_processor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) __SCREAMING_SNAKE_CASE = processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer(__SCREAMING_SNAKE_CASE ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase__ ( self : Dict ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(__SCREAMING_SNAKE_CASE ): processor() def UpperCAmelCase__ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE = processor.batch_decode(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
267
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL _UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) class __lowerCAmelCase ( lowerCAmelCase): _a = ['''pixel_values'''] def __init__( self: Any , _lowerCAmelCase: bool = True , _lowerCAmelCase: Dict[str, int] = None , _lowerCAmelCase: PILImageResampling = PILImageResampling.BICUBIC , _lowerCAmelCase: bool = True , _lowerCAmelCase: Union[int, float] = 1 / 2_55 , _lowerCAmelCase: bool = True , _lowerCAmelCase: Optional[Union[float, List[float]]] = None , _lowerCAmelCase: Optional[Union[float, List[float]]] = None , _lowerCAmelCase: bool = True , **_lowerCAmelCase: Optional[Any] , ): super().__init__(**__SCREAMING_SNAKE_CASE ) lowercase :List[Any] = size if size is not None else {"height": 3_84, "width": 3_84} lowercase :List[str] = get_size_dict(__SCREAMING_SNAKE_CASE , default_to_square=__SCREAMING_SNAKE_CASE ) lowercase :Optional[Any] = do_resize lowercase :Dict = size lowercase :int = resample lowercase :Optional[int] = do_rescale lowercase :List[str] = rescale_factor lowercase :Any = do_normalize lowercase :Optional[int] = image_mean if image_mean is not None else OPENAI_CLIP_MEAN lowercase :Union[str, Any] = image_std if image_std is not None else OPENAI_CLIP_STD lowercase :Optional[Any] = do_convert_rgb def SCREAMING_SNAKE_CASE ( self: str , _lowerCAmelCase: np.ndarray , _lowerCAmelCase: Dict[str, int] , _lowerCAmelCase: PILImageResampling = PILImageResampling.BICUBIC , _lowerCAmelCase: Optional[Union[str, ChannelDimension]] = None , **_lowerCAmelCase: Union[str, Any] , ): lowercase :Dict = get_size_dict(__SCREAMING_SNAKE_CASE , default_to_square=__SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(F"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}" ) lowercase :str = (size["height"], size["width"]) return resize(__SCREAMING_SNAKE_CASE , size=__SCREAMING_SNAKE_CASE , resample=__SCREAMING_SNAKE_CASE , data_format=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE ( self: Optional[int] , _lowerCAmelCase: np.ndarray , _lowerCAmelCase: Union[int, float] , _lowerCAmelCase: Optional[Union[str, ChannelDimension]] = None , **_lowerCAmelCase: Any , ): return rescale(__SCREAMING_SNAKE_CASE , scale=__SCREAMING_SNAKE_CASE , data_format=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE ( self: List[Any] , _lowerCAmelCase: np.ndarray , _lowerCAmelCase: Union[float, List[float]] , _lowerCAmelCase: Union[float, List[float]] , _lowerCAmelCase: Optional[Union[str, ChannelDimension]] = None , **_lowerCAmelCase: Dict , ): return normalize(__SCREAMING_SNAKE_CASE , mean=__SCREAMING_SNAKE_CASE , std=__SCREAMING_SNAKE_CASE , data_format=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE ( self: Optional[Any] , _lowerCAmelCase: ImageInput , _lowerCAmelCase: Optional[bool] = None , _lowerCAmelCase: Optional[Dict[str, int]] = None , _lowerCAmelCase: PILImageResampling = None , _lowerCAmelCase: Optional[bool] = None , _lowerCAmelCase: Optional[float] = None , _lowerCAmelCase: Optional[bool] = None , _lowerCAmelCase: Optional[Union[float, List[float]]] = None , _lowerCAmelCase: Optional[Union[float, List[float]]] = None , _lowerCAmelCase: Optional[Union[str, TensorType]] = None , _lowerCAmelCase: bool = None , _lowerCAmelCase: ChannelDimension = ChannelDimension.FIRST , **_lowerCAmelCase: str , ): lowercase :int = do_resize if do_resize is not None else self.do_resize lowercase :Optional[int] = resample if resample is not None else self.resample lowercase :Tuple = do_rescale if do_rescale is not None else self.do_rescale lowercase :str = rescale_factor if rescale_factor is not None else self.rescale_factor lowercase :str = do_normalize if do_normalize is not None else self.do_normalize lowercase :Dict = image_mean if image_mean is not None else self.image_mean lowercase :int = image_std if image_std is not None else self.image_std lowercase :Tuple = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb lowercase :Dict = size if size is not None else self.size lowercase :str = get_size_dict(__SCREAMING_SNAKE_CASE , default_to_square=__SCREAMING_SNAKE_CASE ) lowercase :int = make_list_of_images(__SCREAMING_SNAKE_CASE ) if not valid_images(__SCREAMING_SNAKE_CASE ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # PIL RGBA images are converted to RGB if do_convert_rgb: lowercase :int = [convert_to_rgb(__SCREAMING_SNAKE_CASE ) for image in images] # All transformations expect numpy arrays. lowercase :Optional[Any] = [to_numpy_array(__SCREAMING_SNAKE_CASE ) for image in images] if do_resize: lowercase :List[Any] = [self.resize(image=__SCREAMING_SNAKE_CASE , size=__SCREAMING_SNAKE_CASE , resample=__SCREAMING_SNAKE_CASE ) for image in images] if do_rescale: lowercase :Tuple = [self.rescale(image=__SCREAMING_SNAKE_CASE , scale=__SCREAMING_SNAKE_CASE ) for image in images] if do_normalize: lowercase :Tuple = [self.normalize(image=__SCREAMING_SNAKE_CASE , mean=__SCREAMING_SNAKE_CASE , std=__SCREAMING_SNAKE_CASE ) for image in images] lowercase :Tuple = [to_channel_dimension_format(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for image in images] lowercase :Union[str, Any] = BatchFeature(data={"pixel_values": images} , tensor_type=__SCREAMING_SNAKE_CASE ) return encoded_outputs
236
'''simple docstring''' import numpy as np def a__ ( a__ , a__ , a__ = 1E-1_2 , a__ = 1_00 , ): """simple docstring""" assert np.shape(a__ )[0] == np.shape(a__ )[1] # Ensure proper dimensionality. assert np.shape(a__ )[0] == np.shape(a__ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(a__ ) == np.iscomplexobj(a__ ) __SCREAMING_SNAKE_CASE = np.iscomplexobj(a__ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(a__ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 1E1_2 while not convergence: # Multiple matrix by the vector. __SCREAMING_SNAKE_CASE = np.dot(a__ , a__ ) # Normalize the resulting output vector. __SCREAMING_SNAKE_CASE = w / np.linalg.norm(a__ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __SCREAMING_SNAKE_CASE = vector.conj().T if is_complex else vector.T __SCREAMING_SNAKE_CASE = np.dot(a__ , np.dot(a__ , a__ ) ) # Check convergence. __SCREAMING_SNAKE_CASE = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = lambda_ if is_complex: __SCREAMING_SNAKE_CASE = np.real(lambda_ ) return lambda_, vector def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ) __SCREAMING_SNAKE_CASE = real_input_matrix.astype(np.complexaaa ) __SCREAMING_SNAKE_CASE = np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __SCREAMING_SNAKE_CASE = real_input_matrix __SCREAMING_SNAKE_CASE = real_vector elif problem_type == "complex": __SCREAMING_SNAKE_CASE = complex_input_matrix __SCREAMING_SNAKE_CASE = complex_vector # Our implementation. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = power_iteration(a__ , a__ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = np.linalg.eigh(a__ ) # Last eigenvalue is the maximum one. __SCREAMING_SNAKE_CASE = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __SCREAMING_SNAKE_CASE = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(a__ ) - np.abs(a__ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
267
0
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class UpperCAmelCase__ ( unittest.TestCase): def __init__( self , lowercase , lowercase=1_3 , lowercase=3 , lowercase=2_2_4 , lowercase=3_0 , lowercase=4_0_0 , lowercase=True , lowercase=None , lowercase=True , lowercase=[0.5, 0.5, 0.5] , lowercase=[0.5, 0.5, 0.5] , ) -> Tuple: __UpperCamelCase = size if size is not None else {"""height""": 1_8, """width""": 1_8} __UpperCamelCase = parent __UpperCamelCase = batch_size __UpperCamelCase = num_channels __UpperCamelCase = image_size __UpperCamelCase = min_resolution __UpperCamelCase = max_resolution __UpperCamelCase = do_resize __UpperCamelCase = size __UpperCamelCase = do_normalize __UpperCamelCase = image_mean __UpperCamelCase = image_std def __lowerCamelCase ( self ) -> int: return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class UpperCAmelCase__ ( UpperCAmelCase_ , unittest.TestCase): __SCREAMING_SNAKE_CASE = ViTImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ) -> str: __UpperCamelCase = EfficientFormerImageProcessorTester(self ) @property def __lowerCamelCase ( self ) -> List[str]: return self.image_proc_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ) -> Tuple: __UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """image_mean""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """image_std""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """do_normalize""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """do_resize""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """size""" ) ) def __lowerCamelCase ( self ) -> str: pass def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __UpperCamelCase = prepare_image_inputs(self.image_proc_tester , equal_resolution=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , Image.Image ) # Test not batched input __UpperCamelCase = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched __UpperCamelCase = image_processor(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __UpperCamelCase = prepare_image_inputs(self.image_proc_tester , equal_resolution=__SCREAMING_SNAKE_CASE , numpify=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , np.ndarray ) # Test not batched input __UpperCamelCase = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched __UpperCamelCase = image_processor(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __UpperCamelCase = prepare_image_inputs(self.image_proc_tester , equal_resolution=__SCREAMING_SNAKE_CASE , torchify=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , torch.Tensor ) # Test not batched input __UpperCamelCase = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched __UpperCamelCase = image_processor(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , )
349
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( a , a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = StableDiffusionInpaintPipeline lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowerCAmelCase__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowerCAmelCase__ = frozenset([] ) def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = PNDMScheduler(skip_prk_steps=__SCREAMING_SNAKE_CASE ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) __SCREAMING_SNAKE_CASE = CLIPTextModel(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __SCREAMING_SNAKE_CASE = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any]=0 ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 )[0] __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE ) ).convert("""RGB""" ).resize((64, 64) ) __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): __SCREAMING_SNAKE_CASE = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = """cpu""" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe.to(__SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe(**__SCREAMING_SNAKE_CASE ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __SCREAMING_SNAKE_CASE = np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : List[str] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained(__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def UpperCAmelCase__ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , safety_checker=__SCREAMING_SNAKE_CASE , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def UpperCAmelCase__ ( self : Tuple ) -> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = PNDMScheduler.from_pretrained(__SCREAMING_SNAKE_CASE , subfolder="""scheduler""" ) __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
267
0
import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=True , UpperCamelCase__="pt" ) -> str: '''simple docstring''' UpperCAmelCase = {'''add_prefix_space''': True} if isinstance(a__ , a__ ) and not line.startswith(''' ''' ) else {} UpperCAmelCase = padding_side return tokenizer( [line] , max_length=a__ , padding='''max_length''' if pad_to_max_length else None , truncation=a__ , return_tensors=a__ , add_special_tokens=a__ , **a__ , ) def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=None , ) -> Optional[int]: '''simple docstring''' UpperCAmelCase = input_ids.ne(a__ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class A_ (a_ ): def __init__( self , _A , _A , _A , _A , _A="train" , _A=None , _A=None , _A=None , _A="" , ): '''simple docstring''' super().__init__() UpperCAmelCase = Path(__SCREAMING_SNAKE_CASE ).joinpath(type_path + '''.source''' ) UpperCAmelCase = Path(__SCREAMING_SNAKE_CASE ).joinpath(type_path + '''.target''' ) UpperCAmelCase = self.get_char_lens(self.src_file ) UpperCAmelCase = max_source_length UpperCAmelCase = max_target_length assert min(self.src_lens ) > 0, F"""found empty line in {self.src_file}""" UpperCAmelCase = tokenizer UpperCAmelCase = prefix if n_obs is not None: UpperCAmelCase = self.src_lens[:n_obs] UpperCAmelCase = src_lang UpperCAmelCase = tgt_lang def __len__( self ): '''simple docstring''' return len(self.src_lens ) def __getitem__( self , _A ): '''simple docstring''' UpperCAmelCase = index + 1 # linecache starts at 1 UpperCAmelCase = self.prefix + linecache.getline(str(self.src_file ) , __SCREAMING_SNAKE_CASE ).rstrip('''\n''' ) UpperCAmelCase = linecache.getline(str(self.tgt_file ) , __SCREAMING_SNAKE_CASE ).rstrip('''\n''' ) assert source_line, F"""empty source line for index {index}""" assert tgt_line, F"""empty tgt line for index {index}""" # Need to add eos token manually for T5 if isinstance(self.tokenizer , __SCREAMING_SNAKE_CASE ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right UpperCAmelCase = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , __SCREAMING_SNAKE_CASE ) else self.tokenizer ) UpperCAmelCase = self.tokenizer.generator if isinstance(self.tokenizer , __SCREAMING_SNAKE_CASE ) else self.tokenizer UpperCAmelCase = encode_line(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , self.max_source_length , '''right''' ) UpperCAmelCase = encode_line(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , self.max_target_length , '''right''' ) UpperCAmelCase = source_inputs['''input_ids'''].squeeze() UpperCAmelCase = target_inputs['''input_ids'''].squeeze() UpperCAmelCase = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def _lowercase ( _A ): '''simple docstring''' return [len(__SCREAMING_SNAKE_CASE ) for x in Path(__SCREAMING_SNAKE_CASE ).open().readlines()] def _lowercase ( self , _A ): '''simple docstring''' UpperCAmelCase = torch.stack([x['''input_ids'''] for x in batch] ) UpperCAmelCase = torch.stack([x['''attention_mask'''] for x in batch] ) UpperCAmelCase = torch.stack([x['''decoder_input_ids'''] for x in batch] ) UpperCAmelCase = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , __SCREAMING_SNAKE_CASE ) else self.tokenizer.pad_token_id ) UpperCAmelCase = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , __SCREAMING_SNAKE_CASE ) else self.tokenizer.pad_token_id ) UpperCAmelCase = trim_batch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) UpperCAmelCase , UpperCAmelCase = trim_batch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ) UpperCAmelCase = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch __A : str = getLogger(__name__) def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ ) -> Optional[Any]: '''simple docstring''' return list(itertools.chain.from_iterable(a__ ) ) def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ ) -> Dict: '''simple docstring''' UpperCAmelCase = get_git_info() save_json(a__ , os.path.join(a__ , '''git_log.json''' ) ) def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=4 , **UpperCamelCase__ ) -> Tuple: '''simple docstring''' with open(a__ , '''w''' ) as f: json.dump(a__ , a__ , indent=a__ , **a__ ) def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ ) -> Any: '''simple docstring''' with open(a__ ) as f: return json.load(a__ ) def __SCREAMING_SNAKE_CASE ( ) -> Tuple: '''simple docstring''' UpperCAmelCase = git.Repo(search_parent_directories=a__ ) UpperCAmelCase = { '''repo_id''': str(a__ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__ ) -> Dict: '''simple docstring''' return list(map(a__ , a__ ) ) def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__ ) -> Tuple: '''simple docstring''' with open(a__ , '''wb''' ) as f: return pickle.dump(a__ , a__ ) def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ ) -> List[str]: '''simple docstring''' def remove_articles(UpperCamelCase__ ): return re.sub(R'''\b(a|an|the)\b''' , ''' ''' , a__ ) def white_space_fix(UpperCamelCase__ ): return " ".join(text.split() ) def remove_punc(UpperCamelCase__ ): UpperCAmelCase = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(UpperCamelCase__ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(a__ ) ) ) ) def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__ ) -> Any: '''simple docstring''' UpperCAmelCase = normalize_answer(a__ ).split() UpperCAmelCase = normalize_answer(a__ ).split() UpperCAmelCase = Counter(a__ ) & Counter(a__ ) UpperCAmelCase = sum(common.values() ) if num_same == 0: return 0 UpperCAmelCase = 1.0 * num_same / len(a__ ) UpperCAmelCase = 1.0 * num_same / len(a__ ) UpperCAmelCase = (2 * precision * recall) / (precision + recall) return fa def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__ ) -> List[Any]: '''simple docstring''' return normalize_answer(a__ ) == normalize_answer(a__ ) def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__ ) -> str: '''simple docstring''' assert len(a__ ) == len(a__ ) UpperCAmelCase = 0 for hypo, pred in zip(a__ , a__ ): em += exact_match_score(a__ , a__ ) if len(a__ ) > 0: em /= len(a__ ) return {"em": em} def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ ) -> int: '''simple docstring''' return model_prefix.startswith('''rag''' ) def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead UpperCAmelCase = '''dropout_rate''' for p in extra_params: if getattr(a__ , a__ , a__ ): if not hasattr(a__ , a__ ) and not hasattr(a__ , equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(a__ ) ) delattr(a__ , a__ ) continue UpperCAmelCase = p if hasattr(a__ , a__ ) else equivalent_param[p] setattr(a__ , a__ , getattr(a__ , a__ ) ) delattr(a__ , a__ ) return hparams, config
273
'''simple docstring''' from itertools import count def a__ ( a__ = 50 ): """simple docstring""" __SCREAMING_SNAKE_CASE = [1] * min_block_length for n in count(a__ ): fill_count_functions.append(1 ) for block_length in range(a__ , n + 1 ): for block_start in range(n - block_length ): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_00_00_00: break return n if __name__ == "__main__": print(f"""{solution() = }""")
267
0
from queue import Queue from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from ..models.auto import AutoTokenizer class UpperCamelCase_ : '''simple docstring''' def _UpperCamelCase ( self , a ) -> str: raise NotImplementedError() def _UpperCamelCase ( self ) -> List[Any]: raise NotImplementedError() class UpperCamelCase_ ( snake_case_ ): '''simple docstring''' def __init__( self , a , a = False , **a ) -> Tuple: snake_case_ = tokenizer snake_case_ = skip_prompt snake_case_ = decode_kwargs # variables used in the streaming process snake_case_ = [] snake_case_ = 0 snake_case_ = True def _UpperCamelCase ( self , a ) -> Dict: if len(value.shape ) > 1 and value.shape[0] > 1: raise ValueError('TextStreamer only supports batch size 1' ) elif len(value.shape ) > 1: snake_case_ = value[0] if self.skip_prompt and self.next_tokens_are_prompt: snake_case_ = False return # Add the new token to the cache and decodes the entire thing. self.token_cache.extend(value.tolist() ) snake_case_ = self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) # After the symbol for a new line, we flush the cache. if text.endswith('\n' ): snake_case_ = text[self.print_len :] snake_case_ = [] snake_case_ = 0 # If the last token is a CJK character, we print the characters. elif len(__SCREAMING_SNAKE_CASE ) > 0 and self._is_chinese_char(ord(text[-1] ) ): snake_case_ = text[self.print_len :] self.print_len += len(__SCREAMING_SNAKE_CASE ) # Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words, # which may change with the subsequent token -- there are probably smarter ways to do this!) else: snake_case_ = text[self.print_len : text.rfind(' ' ) + 1] self.print_len += len(__SCREAMING_SNAKE_CASE ) self.on_finalized_text(__SCREAMING_SNAKE_CASE ) def _UpperCamelCase ( self ) -> Union[str, Any]: if len(self.token_cache ) > 0: snake_case_ = self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) snake_case_ = text[self.print_len :] snake_case_ = [] snake_case_ = 0 else: snake_case_ = '' snake_case_ = True self.on_finalized_text(__SCREAMING_SNAKE_CASE , stream_end=__SCREAMING_SNAKE_CASE ) def _UpperCamelCase ( self , a , a = False ) -> str: print(__SCREAMING_SNAKE_CASE , flush=__SCREAMING_SNAKE_CASE , end='' if not stream_end else None ) def _UpperCamelCase ( self , a ) -> List[str]: if ( (cp >= 0x4_E_0_0 and cp <= 0x9_F_F_F) or (cp >= 0x3_4_0_0 and cp <= 0x4_D_B_F) # or (cp >= 0x2_0_0_0_0 and cp <= 0x2_A_6_D_F) # or (cp >= 0x2_A_7_0_0 and cp <= 0x2_B_7_3_F) # or (cp >= 0x2_B_7_4_0 and cp <= 0x2_B_8_1_F) # or (cp >= 0x2_B_8_2_0 and cp <= 0x2_C_E_A_F) # or (cp >= 0xF_9_0_0 and cp <= 0xF_A_F_F) or (cp >= 0x2_F_8_0_0 and cp <= 0x2_F_A_1_F) # ): # return True return False class UpperCamelCase_ ( snake_case_ ): '''simple docstring''' def __init__( self , a , a = False , a = None , **a ) -> List[Any]: super().__init__(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) snake_case_ = Queue() snake_case_ = None snake_case_ = timeout def _UpperCamelCase ( self , a , a = False ) -> Any: self.text_queue.put(__SCREAMING_SNAKE_CASE , timeout=self.timeout ) if stream_end: self.text_queue.put(self.stop_signal , timeout=self.timeout ) def __iter__( self ) -> Optional[Any]: return self def _UpperCamelCase ( self ) -> List[Any]: snake_case_ = self.text_queue.get(timeout=self.timeout ) if value == self.stop_signal: raise StopIteration() else: return value
178
'''simple docstring''' import logging import os import threading import time try: import warnings except ImportError: UpperCAmelCase : Optional[Any] = None try: import msvcrt except ImportError: UpperCAmelCase : List[Any] = None try: import fcntl except ImportError: UpperCAmelCase : int = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: UpperCAmelCase : Union[str, Any] = OSError # Data # ------------------------------------------------ UpperCAmelCase : List[Any] = [ 'Timeout', 'BaseFileLock', 'WindowsFileLock', 'UnixFileLock', 'SoftFileLock', 'FileLock', ] UpperCAmelCase : Tuple = '3.0.12' UpperCAmelCase : str = None def a__ ( ): """simple docstring""" global _logger __SCREAMING_SNAKE_CASE = _logger or logging.getLogger(__name__ ) return _logger class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock_file return None def __str__( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = f'The file lock \'{self.lock_file}\' could not be acquired.' return temp class lowerCAmelCase__ : """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock return None def __enter__( self : List[str] ) -> List[Any]: """simple docstring""" return self.lock def __exit__( self : Tuple , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[str]: """simple docstring""" self.lock.release() return None class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = max_filename_length if max_filename_length is not None else 255 # Hash the filename if it's too long __SCREAMING_SNAKE_CASE = self.hash_filename_if_too_long(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # The path to the lock file. __SCREAMING_SNAKE_CASE = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. __SCREAMING_SNAKE_CASE = None # The default timeout value. __SCREAMING_SNAKE_CASE = timeout # We use this lock primarily for the lock counter. __SCREAMING_SNAKE_CASE = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. __SCREAMING_SNAKE_CASE = 0 return None @property def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" return self._lock_file @property def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" return self._timeout @timeout.setter def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = float(__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" raise NotImplementedError() def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" raise NotImplementedError() @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" return self._lock_file_fd is not None def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=None , __SCREAMING_SNAKE_CASE : Optional[int]=0.05 ) -> Optional[Any]: """simple docstring""" if timeout is None: __SCREAMING_SNAKE_CASE = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file __SCREAMING_SNAKE_CASE = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(f'Attempting to acquire lock {lock_id} on {lock_filename}' ) self._acquire() if self.is_locked: logger().debug(f'Lock {lock_id} acquired on {lock_filename}' ) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(f'Timeout on acquiring lock {lock_id} on {lock_filename}' ) raise Timeout(self._lock_file ) else: logger().debug( f'Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...' ) time.sleep(__SCREAMING_SNAKE_CASE ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: __SCREAMING_SNAKE_CASE = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Dict: """simple docstring""" with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file logger().debug(f'Attempting to release lock {lock_id} on {lock_filename}' ) self._release() __SCREAMING_SNAKE_CASE = 0 logger().debug(f'Lock {lock_id} released on {lock_filename}' ) return None def __enter__( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" self.acquire() return self def __exit__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" self.release() return None def __del__( self : str ) -> Union[str, Any]: """simple docstring""" self.release(force=__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = os.path.basename(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > max_length and max_length > 0: __SCREAMING_SNAKE_CASE = os.path.dirname(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = str(hash(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = filename[: max_length - len(__SCREAMING_SNAKE_CASE ) - 8] + """...""" + hashed_filename + """.lock""" return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: return path class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Dict=-1 , __SCREAMING_SNAKE_CASE : Dict=None ) -> List[Any]: """simple docstring""" from .file_utils import relative_to_absolute_path super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """\\\\?\\""" + relative_to_absolute_path(self.lock_file ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: try: msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_UNLCK , 1 ) os.close(__SCREAMING_SNAKE_CASE ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any]=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = os.statvfs(os.path.dirname(__SCREAMING_SNAKE_CASE ) ).f_namemax super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) try: fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_UN ) os.close(__SCREAMING_SNAKE_CASE ) return None class lowerCAmelCase__ ( a ): """simple docstring""" def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : int ) -> Optional[int]: """simple docstring""" os.close(self._lock_file_fd ) __SCREAMING_SNAKE_CASE = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None UpperCAmelCase : Dict = None if msvcrt: UpperCAmelCase : Optional[int] = WindowsFileLock elif fcntl: UpperCAmelCase : Optional[Any] = UnixFileLock else: UpperCAmelCase : int = SoftFileLock if warnings is not None: warnings.warn('only soft file lock is available')
267
0