code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def UpperCamelCase ( snake_case__ : Tuple ) -> Dict: # picklable for multiprocessing return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def UpperCamelCase ( ) -> Dict: with parallel_backend('spark' ): assert ParallelBackendConfig.backend_name == "spark" UpperCamelCase : Tuple = [1, 2, 3] with pytest.raises(snake_case__ ): with parallel_backend('unsupported backend' ): map_nested(snake_case__ , snake_case__ , num_proc=2 ) with pytest.raises(snake_case__ ): with parallel_backend('unsupported backend' ): map_nested(snake_case__ , snake_case__ , num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize('num_proc' , [2, -1] ) def UpperCamelCase ( snake_case__ : int ) -> Any: UpperCamelCase : Dict = [1, 2] UpperCamelCase : List[str] = {'a': 1, 'b': 2} UpperCamelCase : List[str] = {'a': [1, 2], 'b': [3, 4]} UpperCamelCase : Optional[Any] = {'a': {'1': 1}, 'b': 2} UpperCamelCase : Union[str, Any] = {'a': 1, 'b': 2, 'c': 3, 'd': 4} UpperCamelCase : Any = [2, 3] UpperCamelCase : Optional[Any] = {'a': 2, 'b': 3} UpperCamelCase : Any = {'a': [2, 3], 'b': [4, 5]} UpperCamelCase : List[Any] = {'a': {'1': 2}, 'b': 3} UpperCamelCase : str = {'a': 2, 'b': 3, 'c': 4, 'd': 5} with parallel_backend('spark' ): assert map_nested(snake_case__ , snake_case__ , num_proc=snake_case__ ) == expected_map_nested_sa assert map_nested(snake_case__ , snake_case__ , num_proc=snake_case__ ) == expected_map_nested_sa assert map_nested(snake_case__ , snake_case__ , num_proc=snake_case__ ) == expected_map_nested_sa assert map_nested(snake_case__ , snake_case__ , num_proc=snake_case__ ) == expected_map_nested_sa assert map_nested(snake_case__ , snake_case__ , num_proc=snake_case__ ) == expected_map_nested_sa
40
from math import asin, atan, cos, radians, sin, sqrt, tan lowerCAmelCase : Union[str, Any] = 637_8137.0 lowerCAmelCase : int = 635_6752.31_4245 lowerCAmelCase : Union[str, Any] = 6378137 def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: List[Any] = (AXIS_A - AXIS_B) / AXIS_A SCREAMING_SNAKE_CASE_: str = atan((1 - flattening) * tan(radians(_UpperCAmelCase ) ) ) SCREAMING_SNAKE_CASE_: Optional[int] = atan((1 - flattening) * tan(radians(_UpperCAmelCase ) ) ) SCREAMING_SNAKE_CASE_: Any = radians(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Dict = radians(_UpperCAmelCase ) # Equation SCREAMING_SNAKE_CASE_: str = sin((phi_a - phi_a) / 2 ) SCREAMING_SNAKE_CASE_: List[Any] = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda SCREAMING_SNAKE_CASE_: Tuple = sqrt(sin_sq_phi + (cos(_UpperCAmelCase ) * cos(_UpperCAmelCase ) * sin_sq_lambda) ) return 2 * RADIUS * asin(_UpperCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
671
0
'''simple docstring''' # coding=utf-8 # Copyright 2023 The HuggingFace Inc. team. # # 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. # this script dumps information about the environment import os import platform import sys lowerCAmelCase__ = '''3''' print('''Python version:''', sys.version) print('''OS platform:''', platform.platform()) print('''OS architecture:''', platform.machine()) try: import torch print('''Torch version:''', torch.__version__) print('''Cuda available:''', torch.cuda.is_available()) print('''Cuda version:''', torch.version.cuda) print('''CuDNN version:''', torch.backends.cudnn.version()) print('''Number of GPUs available:''', torch.cuda.device_count()) except ImportError: print('''Torch version:''', None) try: import transformers print('''transformers version:''', transformers.__version__) except ImportError: print('''transformers version:''', None)
41
import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): # Initialise PyTorch model SCREAMING_SNAKE_CASE_: List[Any] = BertConfig.from_json_file(_UpperCAmelCase ) print(f"Building PyTorch model from configuration: {config}" ) SCREAMING_SNAKE_CASE_: Tuple = BertForPreTraining(_UpperCAmelCase ) # Load weights from tf checkpoint load_tf_weights_in_bert(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) # Save pytorch-model print(f"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , _UpperCAmelCase ) if __name__ == "__main__": lowerCAmelCase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--bert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained BERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) lowerCAmelCase : Optional[Any] = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
671
0
'''simple docstring''' import copy from typing import Any, Dict, List, Optional, Union import numpy as np import torch from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import TensorType, logging A_ = logging.get_logger(__name__) class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = ['input_features', 'is_longer'] def __init__( self , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_=48000 , SCREAMING_SNAKE_CASE_=480 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_ = 0 , SCREAMING_SNAKE_CASE_ = 14000 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "fusion" , SCREAMING_SNAKE_CASE_ = "repeatpad" , **SCREAMING_SNAKE_CASE_ , ) -> List[Any]: '''simple docstring''' super().__init__( feature_size=SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , padding_value=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) lowerCamelCase_ = top_db lowerCamelCase_ = truncation lowerCamelCase_ = padding lowerCamelCase_ = fft_window_size lowerCamelCase_ = (fft_window_size >> 1) + 1 lowerCamelCase_ = hop_length lowerCamelCase_ = max_length_s lowerCamelCase_ = max_length_s * sampling_rate lowerCamelCase_ = sampling_rate lowerCamelCase_ = frequency_min lowerCamelCase_ = frequency_max lowerCamelCase_ = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=SCREAMING_SNAKE_CASE_ , min_frequency=SCREAMING_SNAKE_CASE_ , max_frequency=SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , norm=SCREAMING_SNAKE_CASE_ , mel_scale='htk' , ) lowerCamelCase_ = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=SCREAMING_SNAKE_CASE_ , min_frequency=SCREAMING_SNAKE_CASE_ , max_frequency=SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , norm='slaney' , mel_scale='slaney' , ) def UpperCamelCase( self ) -> Dict[str, Any]: '''simple docstring''' lowerCamelCase_ = copy.deepcopy(self.__dict__ ) lowerCamelCase_ = self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] if "mel_filters_slaney" in output: del output["mel_filters_slaney"] return output def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> np.ndarray: '''simple docstring''' lowerCamelCase_ = spectrogram( SCREAMING_SNAKE_CASE_ , window_function(self.fft_window_size , 'hann' ) , frame_length=self.fft_window_size , hop_length=self.hop_length , power=2.0 , mel_filters=SCREAMING_SNAKE_CASE_ , log_mel='dB' , ) return log_mel_spectrogram.T def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[str]: '''simple docstring''' lowerCamelCase_ = np.array_split(list(range(0 , total_frames - chunk_frames + 1 ) ) , 3 ) if len(ranges[1] ) == 0: # if the audio is too short, we just use the first chunk lowerCamelCase_ = [0] if len(ranges[2] ) == 0: # if the audio is too short, we just use the first chunk lowerCamelCase_ = [0] # randomly choose index for each part lowerCamelCase_ = np.random.choice(ranges[0] ) lowerCamelCase_ = np.random.choice(ranges[1] ) lowerCamelCase_ = np.random.choice(ranges[2] ) lowerCamelCase_ = mel[idx_front : idx_front + chunk_frames, :] lowerCamelCase_ = mel[idx_middle : idx_middle + chunk_frames, :] lowerCamelCase_ = mel[idx_back : idx_back + chunk_frames, :] lowerCamelCase_ = torch.tensor(mel[None, None, :] ) lowerCamelCase_ = torch.nn.functional.interpolate( SCREAMING_SNAKE_CASE_ , size=[chunk_frames, 64] , mode='bilinear' , align_corners=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = mel_shrink[0][0].numpy() lowerCamelCase_ = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] , axis=0 ) return mel_fusion def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> np.array: '''simple docstring''' if waveform.shape[0] > max_length: if truncation == "rand_trunc": lowerCamelCase_ = True # random crop to max_length (for compatibility) -> this should be handled by self.pad lowerCamelCase_ = len(SCREAMING_SNAKE_CASE_ ) - max_length lowerCamelCase_ = np.random.randint(0 , overflow + 1 ) lowerCamelCase_ = waveform[idx : idx + max_length] lowerCamelCase_ = self._np_extract_fbank_features(SCREAMING_SNAKE_CASE_ , self.mel_filters_slaney )[None, :] elif truncation == "fusion": lowerCamelCase_ = self._np_extract_fbank_features(SCREAMING_SNAKE_CASE_ , self.mel_filters ) lowerCamelCase_ = max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed lowerCamelCase_ = mel.shape[0] if chunk_frames == total_frames: # there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length. # In this case, we just use the whole audio. lowerCamelCase_ = np.stack([mel, mel, mel, mel] , axis=0 ) lowerCamelCase_ = False else: lowerCamelCase_ = self._random_mel_fusion(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = True else: raise NotImplementedError(f'''data_truncating {truncation} not implemented''' ) else: lowerCamelCase_ = False # only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding if waveform.shape[0] < max_length: if padding == "repeat": lowerCamelCase_ = int(max_length / len(SCREAMING_SNAKE_CASE_ ) ) lowerCamelCase_ = np.stack(np.tile(SCREAMING_SNAKE_CASE_ , n_repeat + 1 ) )[:max_length] if padding == "repeatpad": lowerCamelCase_ = int(max_length / len(SCREAMING_SNAKE_CASE_ ) ) lowerCamelCase_ = np.stack(np.tile(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) lowerCamelCase_ = np.pad(SCREAMING_SNAKE_CASE_ , (0, max_length - waveform.shape[0]) , mode='constant' , constant_values=0 ) if truncation == "fusion": lowerCamelCase_ = self._np_extract_fbank_features(SCREAMING_SNAKE_CASE_ , self.mel_filters ) lowerCamelCase_ = np.stack([input_mel, input_mel, input_mel, input_mel] , axis=0 ) else: lowerCamelCase_ = self._np_extract_fbank_features(SCREAMING_SNAKE_CASE_ , self.mel_filters_slaney )[None, :] return input_mel, longer def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ) -> BatchFeature: '''simple docstring''' lowerCamelCase_ = truncation if truncation is not None else self.truncation lowerCamelCase_ = padding if padding else self.padding if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'''The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a''' f''' sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input''' f''' was sampled with {self.sampling_rate} and not {sampling_rate}.''' ) else: logger.warning( 'It is strongly recommended to pass the `sampling_rate` argument to this function. ' 'Failing to do so can result in silent errors that might be hard to debug.' ) lowerCamelCase_ = isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'''Only mono-channel audio is supported for input to {self}''' ) lowerCamelCase_ = is_batched_numpy or ( isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: lowerCamelCase_ = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ): lowerCamelCase_ = np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) elif isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): lowerCamelCase_ = raw_speech.astype(np.floataa ) # always return batch if not is_batched: lowerCamelCase_ = [np.asarray(SCREAMING_SNAKE_CASE_ )] # convert to mel spectrogram, truncate and pad if needed. lowerCamelCase_ = [ self._get_input_mel(SCREAMING_SNAKE_CASE_ , max_length if max_length else self.nb_max_samples , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for waveform in raw_speech ] lowerCamelCase_ = [] lowerCamelCase_ = [] for mel, longer in padded_inputs: input_mel.append(SCREAMING_SNAKE_CASE_ ) is_longer.append(SCREAMING_SNAKE_CASE_ ) if truncation == "fusion" and sum(SCREAMING_SNAKE_CASE_ ) == 0: # if no audio is longer than 10s, then randomly select one audio to be longer lowerCamelCase_ = np.random.randint(0 , len(SCREAMING_SNAKE_CASE_ ) ) lowerCamelCase_ = True if isinstance(input_mel[0] , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) for feature in input_mel] # is_longer is a list of bool lowerCamelCase_ = [[longer] for longer in is_longer] lowerCamelCase_ = {'input_features': input_mel, 'is_longer': is_longer} lowerCamelCase_ = BatchFeature(SCREAMING_SNAKE_CASE_ ) if return_tensors is not None: lowerCamelCase_ = input_features.convert_to_tensors(SCREAMING_SNAKE_CASE_ ) return input_features
42
import math def A_ ( _UpperCAmelCase ): if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_UpperCAmelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def A_ ( _UpperCAmelCase = 0.1 ): SCREAMING_SNAKE_CASE_: Union[str, Any] = 3 SCREAMING_SNAKE_CASE_: Optional[int] = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ): primes += is_prime(_UpperCAmelCase ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
671
0
from __future__ import annotations import copy import inspect import json import math import os import tempfile import unittest from importlib import import_module import numpy as np from transformers import ViTMAEConfig from transformers.file_utils import cached_property, is_tf_available, is_vision_available from transformers.testing_utils import require_tf, require_vision, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFViTMAEForPreTraining, TFViTMAEModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _a : def __init__( self: Tuple , UpperCamelCase_: int , UpperCamelCase_: Optional[Any]=13 , UpperCamelCase_: Any=30 , UpperCamelCase_: Union[str, Any]=2 , UpperCamelCase_: Tuple=3 , UpperCamelCase_: Optional[Any]=True , UpperCamelCase_: Tuple=True , UpperCamelCase_: List[Any]=32 , UpperCamelCase_: int=2 , UpperCamelCase_: List[str]=4 , UpperCamelCase_: Optional[int]=37 , UpperCamelCase_: int="gelu" , UpperCamelCase_: Any=0.1 , UpperCamelCase_: Any=0.1 , UpperCamelCase_: Optional[int]=10 , UpperCamelCase_: List[str]=0.02 , UpperCamelCase_: List[Any]=3 , UpperCamelCase_: Any=0.6 , UpperCamelCase_: Any=None , ) -> str: """simple docstring""" lowercase__ = parent lowercase__ = batch_size lowercase__ = image_size lowercase__ = patch_size lowercase__ = num_channels lowercase__ = is_training lowercase__ = use_labels lowercase__ = hidden_size lowercase__ = num_hidden_layers lowercase__ = num_attention_heads lowercase__ = intermediate_size lowercase__ = hidden_act lowercase__ = hidden_dropout_prob lowercase__ = attention_probs_dropout_prob lowercase__ = type_sequence_label_size lowercase__ = initializer_range lowercase__ = mask_ratio lowercase__ = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) lowercase__ = (image_size // patch_size) ** 2 lowercase__ = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def lowerCamelCase_ ( self: List[str] ) -> str: """simple docstring""" lowercase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase__ = None if self.use_labels: lowercase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase__ = self.get_config() return config, pixel_values, labels def lowerCamelCase_ ( self: Dict ) -> List[str]: """simple docstring""" return ViTMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , decoder_hidden_size=self.hidden_size , decoder_num_hidden_layers=self.num_hidden_layers , decoder_num_attention_heads=self.num_attention_heads , decoder_intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=UpperCamelCase_ , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , ) def lowerCamelCase_ ( self: List[Any] , UpperCamelCase_: int , UpperCamelCase_: List[Any] , UpperCamelCase_: List[Any] ) -> Optional[Any]: """simple docstring""" lowercase__ = TFViTMAEModel(config=UpperCamelCase_ ) lowercase__ = model(UpperCamelCase_ , training=UpperCamelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase_ ( self: Union[str, Any] , UpperCamelCase_: Tuple , UpperCamelCase_: Tuple , UpperCamelCase_: Any ) -> Union[str, Any]: """simple docstring""" lowercase__ = TFViTMAEForPreTraining(UpperCamelCase_ ) lowercase__ = model(UpperCamelCase_ , training=UpperCamelCase_ ) # expected sequence length = num_patches lowercase__ = (self.image_size // self.patch_size) ** 2 lowercase__ = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) # test greyscale images lowercase__ = 1 lowercase__ = TFViTMAEForPreTraining(UpperCamelCase_ ) lowercase__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowercase__ = model(UpperCamelCase_ , training=UpperCamelCase_ ) lowercase__ = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) def lowerCamelCase_ ( self: str ) -> int: """simple docstring""" lowercase__ = self.prepare_config_and_inputs() ((lowercase__) , (lowercase__) , (lowercase__)) = config_and_inputs lowercase__ = {'''pixel_values''': pixel_values} return config, inputs_dict @require_tf class _a ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): _lowercase : int = (TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else () _lowercase : List[str] = {'''feature-extraction''': TFViTMAEModel} if is_tf_available() else {} _lowercase : Optional[int] = False _lowercase : List[str] = False _lowercase : Optional[int] = False _lowercase : Optional[int] = False def lowerCamelCase_ ( self: List[str] ) -> Union[str, Any]: """simple docstring""" lowercase__ = TFViTMAEModelTester(self ) lowercase__ = ConfigTester(self , config_class=UpperCamelCase_ , has_text_modality=UpperCamelCase_ , hidden_size=37 ) def lowerCamelCase_ ( self: List[Any] ) -> Optional[int]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''ViTMAE does not use inputs_embeds''' ) def lowerCamelCase_ ( self: Dict ) -> List[str]: """simple docstring""" pass def lowerCamelCase_ ( self: List[Any] ) -> List[Any]: """simple docstring""" lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ = model_class(UpperCamelCase_ ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) lowercase__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCamelCase_ , tf.keras.layers.Layer ) ) def lowerCamelCase_ ( self: Optional[int] ) -> List[str]: """simple docstring""" lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ = model_class(UpperCamelCase_ ) lowercase__ = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase__ = [*signature.parameters.keys()] lowercase__ = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , UpperCamelCase_ ) def lowerCamelCase_ ( self: Tuple ) -> int: """simple docstring""" lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase_ ) def lowerCamelCase_ ( self: int ) -> str: """simple docstring""" lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*UpperCamelCase_ ) def lowerCamelCase_ ( self: Union[str, Any] ) -> Any: """simple docstring""" np.random.seed(2 ) lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ = int((config.image_size // config.patch_size) ** 2 ) lowercase__ = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: lowercase__ = model_class(UpperCamelCase_ ) lowercase__ = self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ ) lowercase__ = model(UpperCamelCase_ , noise=UpperCamelCase_ ) lowercase__ = copy.deepcopy(self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ ) ) lowercase__ = model(**UpperCamelCase_ , noise=UpperCamelCase_ ) lowercase__ = outputs_dict[0].numpy() lowercase__ = outputs_keywords[0].numpy() self.assertLess(np.sum(np.abs(output_dict - output_keywords ) ) , 1E-6 ) def lowerCamelCase_ ( self: Optional[int] ) -> Optional[Any]: """simple docstring""" np.random.seed(2 ) lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ = int((config.image_size // config.patch_size) ** 2 ) lowercase__ = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) def prepare_numpy_arrays(UpperCamelCase_: List[Any] ): lowercase__ = {} for k, v in inputs_dict.items(): if tf.is_tensor(UpperCamelCase_ ): lowercase__ = v.numpy() else: lowercase__ = np.array(UpperCamelCase_ ) return inputs_np_dict for model_class in self.all_model_classes: lowercase__ = model_class(UpperCamelCase_ ) lowercase__ = self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ ) lowercase__ = prepare_numpy_arrays(UpperCamelCase_ ) lowercase__ = model(UpperCamelCase_ , noise=UpperCamelCase_ ) lowercase__ = model(**UpperCamelCase_ , noise=UpperCamelCase_ ) self.assert_outputs_same(UpperCamelCase_ , UpperCamelCase_ ) def lowerCamelCase_ ( self: int , UpperCamelCase_: Optional[int] , UpperCamelCase_: List[Any] , UpperCamelCase_: Tuple ) -> str: """simple docstring""" np.random.seed(2 ) lowercase__ = int((tf_model.config.image_size // tf_model.config.patch_size) ** 2 ) lowercase__ = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) lowercase__ = tf.constant(UpperCamelCase_ ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument lowercase__ = tf_noise super().check_pt_tf_models(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) def lowerCamelCase_ ( self: Dict ) -> Dict: """simple docstring""" np.random.seed(2 ) lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ = { module_member for model_class in self.all_model_classes for module in (import_module(model_class.__module__ ),) for module_member_name in dir(UpperCamelCase_ ) if module_member_name.endswith('''MainLayer''' ) # This condition is required, since `modeling_tf_clip.py` has 3 classes whose names end with `MainLayer`. and module_member_name[: -len('''MainLayer''' )] == model_class.__name__[: -len('''Model''' )] for module_member in (getattr(UpperCamelCase_ , UpperCamelCase_ ),) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) and tf.keras.layers.Layer in module_member.__bases__ and getattr(UpperCamelCase_ , '''_keras_serializable''' , UpperCamelCase_ ) } lowercase__ = int((config.image_size // config.patch_size) ** 2 ) lowercase__ = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) lowercase__ = tf.convert_to_tensor(UpperCamelCase_ ) inputs_dict.update({'''noise''': noise} ) for main_layer_class in tf_main_layer_classes: lowercase__ = main_layer_class(UpperCamelCase_ ) lowercase__ = { name: tf.keras.Input(tensor.shape[1:] , dtype=tensor.dtype ) for name, tensor in inputs_dict.items() } lowercase__ = tf.keras.Model(UpperCamelCase_ , outputs=main_layer(UpperCamelCase_ ) ) lowercase__ = model(UpperCamelCase_ ) with tempfile.TemporaryDirectory() as tmpdirname: lowercase__ = os.path.join(UpperCamelCase_ , '''keras_model.h5''' ) model.save(UpperCamelCase_ ) lowercase__ = tf.keras.models.load_model( UpperCamelCase_ , custom_objects={main_layer_class.__name__: main_layer_class} ) assert isinstance(UpperCamelCase_ , tf.keras.Model ) lowercase__ = model(UpperCamelCase_ ) self.assert_outputs_same(UpperCamelCase_ , UpperCamelCase_ ) @slow def lowerCamelCase_ ( self: List[Any] ) -> Optional[Any]: """simple docstring""" np.random.seed(2 ) lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ = int((config.image_size // config.patch_size) ** 2 ) lowercase__ = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: lowercase__ = model_class(UpperCamelCase_ ) lowercase__ = self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ ) lowercase__ = model(UpperCamelCase_ , noise=UpperCamelCase_ ) if model_class.__name__ == "TFViTMAEModel": lowercase__ = outputs.last_hidden_state.numpy() lowercase__ = 0 else: lowercase__ = outputs.logits.numpy() lowercase__ = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(UpperCamelCase_ , saved_model=UpperCamelCase_ ) lowercase__ = model_class.from_pretrained(UpperCamelCase_ ) lowercase__ = model(UpperCamelCase_ , noise=UpperCamelCase_ ) if model_class.__name__ == "TFViTMAEModel": lowercase__ = after_outputs['''last_hidden_state'''].numpy() lowercase__ = 0 else: lowercase__ = after_outputs['''logits'''].numpy() lowercase__ = 0 lowercase__ = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(UpperCamelCase_ , 1E-5 ) def lowerCamelCase_ ( self: Tuple ) -> List[Any]: """simple docstring""" np.random.seed(2 ) lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ = int((config.image_size // config.patch_size) ** 2 ) lowercase__ = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: lowercase__ = model_class(UpperCamelCase_ ) lowercase__ = self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ ) lowercase__ = model(UpperCamelCase_ , noise=UpperCamelCase_ ) lowercase__ = model.get_config() # make sure that returned config is jsonifiable, which is required by keras json.dumps(UpperCamelCase_ ) lowercase__ = model_class.from_config(model.get_config() ) # make sure it also accepts a normal config lowercase__ = model_class.from_config(model.config ) lowercase__ = new_model(UpperCamelCase_ ) # Build model new_model.set_weights(model.get_weights() ) lowercase__ = new_model(UpperCamelCase_ , noise=UpperCamelCase_ ) self.assert_outputs_same(UpperCamelCase_ , UpperCamelCase_ ) @unittest.skip( reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.''' ) def lowerCamelCase_ ( self: Optional[int] ) -> str: """simple docstring""" pass @unittest.skip(reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load''' ) def lowerCamelCase_ ( self: Any ) -> Dict: """simple docstring""" pass @slow def lowerCamelCase_ ( self: List[Any] ) -> Optional[int]: """simple docstring""" lowercase__ = TFViTMAEModel.from_pretrained('''google/vit-base-patch16-224''' ) self.assertIsNotNone(UpperCamelCase_ ) def _a ( ): """simple docstring""" lowercase__ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf @require_vision class _a ( unittest.TestCase ): @cached_property def lowerCamelCase_ ( self: Tuple ) -> Tuple: """simple docstring""" return ViTImageProcessor.from_pretrained('''facebook/vit-mae-base''' ) if is_vision_available() else None @slow def lowerCamelCase_ ( self: int ) -> Optional[int]: """simple docstring""" np.random.seed(2 ) lowercase__ = TFViTMAEForPreTraining.from_pretrained('''facebook/vit-mae-base''' ) lowercase__ = self.default_image_processor lowercase__ = prepare_img() lowercase__ = image_processor(images=UpperCamelCase_ , return_tensors='''tf''' ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) lowercase__ = ViTMAEConfig() lowercase__ = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) lowercase__ = np.random.uniform(size=(1, num_patches) ) # forward pass lowercase__ = model(**UpperCamelCase_ , noise=UpperCamelCase_ ) # verify the logits lowercase__ = tf.convert_to_tensor([1, 196, 768] ) self.assertEqual(outputs.logits.shape , UpperCamelCase_ ) lowercase__ = tf.convert_to_tensor( [[-0.0548, -1.7023, -0.9325], [0.3721, -0.5670, -0.2233], [0.8235, -1.3878, -0.3524]] ) tf.debugging.assert_near(outputs.logits[0, :3, :3] , UpperCamelCase_ , atol=1E-4 )
43
import re def A_ ( _UpperCAmelCase ): return [char.split() for char in re.split(R"[^ a-z A-Z 0-9 \s]" , str_ )] def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: int = split_input(str_ ) return "".join( ["".join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): try: SCREAMING_SNAKE_CASE_: List[Any] = split_input(_UpperCAmelCase ) if upper: SCREAMING_SNAKE_CASE_: List[str] = "".join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: SCREAMING_SNAKE_CASE_: Optional[int] = "".join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def A_ ( _UpperCAmelCase ): return to_simple_case(_UpperCAmelCase ) def A_ ( _UpperCAmelCase ): try: SCREAMING_SNAKE_CASE_: Optional[int] = to_simple_case(_UpperCAmelCase ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def A_ ( _UpperCAmelCase , _UpperCAmelCase ): return to_complex_case(_UpperCAmelCase , _UpperCAmelCase , "_" ) def A_ ( _UpperCAmelCase , _UpperCAmelCase ): return to_complex_case(_UpperCAmelCase , _UpperCAmelCase , "-" ) if __name__ == "__main__": __import__("""doctest""").testmod()
671
0
'''simple docstring''' import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from transformers import TensorFlowBenchmark, TensorFlowBenchmarkArguments @require_tf class UpperCAmelCase__ ( unittest.TestCase ): def lowerCamelCase_ ( self : Optional[int],__A : Any ): for model_result in results.values(): for batch_size, sequence_length in zip(model_result["bs"],model_result["ss"] ): _lowerCamelCase : Optional[Any] = model_result["result"][batch_size][sequence_length] self.assertIsNotNone(__A ) def lowerCamelCase_ ( self : int ): _lowerCamelCase : List[Any] = "sshleifer/tiny-gpt2" _lowerCamelCase : str = TensorFlowBenchmarkArguments( models=[MODEL_ID],training=__A,inference=__A,sequence_lengths=[8],batch_sizes=[1],eager_mode=__A,multi_process=__A,) _lowerCamelCase : Optional[Any] = TensorFlowBenchmark(__A ) _lowerCamelCase : Union[str, Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def lowerCamelCase_ ( self : List[str] ): _lowerCamelCase : Optional[int] = "sgugger/tiny-distilbert-classification" _lowerCamelCase : List[str] = TensorFlowBenchmarkArguments( models=[MODEL_ID],training=__A,inference=__A,sequence_lengths=[8],batch_sizes=[1],multi_process=__A,only_pretrain_model=__A,) _lowerCamelCase : Dict = TensorFlowBenchmark(__A ) _lowerCamelCase : Tuple = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def lowerCamelCase_ ( self : str ): _lowerCamelCase : List[str] = "sshleifer/tiny-gpt2" _lowerCamelCase : Dict = TensorFlowBenchmarkArguments( models=[MODEL_ID],training=__A,inference=__A,sequence_lengths=[8],batch_sizes=[1],multi_process=__A,) _lowerCamelCase : str = TensorFlowBenchmark(__A ) _lowerCamelCase : int = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def lowerCamelCase_ ( self : Dict ): _lowerCamelCase : Any = "sshleifer/tiny-gpt2" _lowerCamelCase : List[Any] = AutoConfig.from_pretrained(__A ) _lowerCamelCase : Union[str, Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID],training=__A,inference=__A,sequence_lengths=[8],batch_sizes=[1],eager_mode=__A,multi_process=__A,) _lowerCamelCase : Any = TensorFlowBenchmark(__A,[config] ) _lowerCamelCase : Optional[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def lowerCamelCase_ ( self : Dict ): _lowerCamelCase : Any = "sshleifer/tiny-gpt2" _lowerCamelCase : Tuple = AutoConfig.from_pretrained(__A ) _lowerCamelCase : Tuple = TensorFlowBenchmarkArguments( models=[MODEL_ID],training=__A,inference=__A,sequence_lengths=[8],batch_sizes=[1],multi_process=__A,) _lowerCamelCase : Optional[Any] = TensorFlowBenchmark(__A,[config] ) _lowerCamelCase : List[str] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def lowerCamelCase_ ( self : Optional[Any] ): _lowerCamelCase : int = "sshleifer/tiny-gpt2" _lowerCamelCase : List[str] = TensorFlowBenchmarkArguments( models=[MODEL_ID],training=__A,inference=__A,sequence_lengths=[8],batch_sizes=[1],multi_process=__A,) _lowerCamelCase : int = TensorFlowBenchmark(__A ) _lowerCamelCase : Any = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def lowerCamelCase_ ( self : List[str] ): _lowerCamelCase : Dict = "sshleifer/tiny-gpt2" _lowerCamelCase : Dict = AutoConfig.from_pretrained(__A ) _lowerCamelCase : Any = TensorFlowBenchmarkArguments( models=[MODEL_ID],training=__A,inference=__A,sequence_lengths=[8],batch_sizes=[1],multi_process=__A,) _lowerCamelCase : Union[str, Any] = TensorFlowBenchmark(__A,[config] ) _lowerCamelCase : Any = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def lowerCamelCase_ ( self : List[str] ): _lowerCamelCase : Optional[Any] = "patrickvonplaten/t5-tiny-random" _lowerCamelCase : List[str] = AutoConfig.from_pretrained(__A ) _lowerCamelCase : Tuple = TensorFlowBenchmarkArguments( models=[MODEL_ID],training=__A,inference=__A,sequence_lengths=[8],batch_sizes=[1],multi_process=__A,) _lowerCamelCase : Dict = TensorFlowBenchmark(__A,configs=[config] ) _lowerCamelCase : List[str] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(is_tf_available() and len(tf.config.list_physical_devices("GPU" ) ) == 0,"Cannot do xla on CPU." ) def lowerCamelCase_ ( self : Optional[int] ): _lowerCamelCase : Tuple = "sshleifer/tiny-gpt2" _lowerCamelCase : List[str] = TensorFlowBenchmarkArguments( models=[MODEL_ID],training=__A,inference=__A,sequence_lengths=[8],batch_sizes=[1],use_xla=__A,multi_process=__A,) _lowerCamelCase : str = TensorFlowBenchmark(__A ) _lowerCamelCase : List[str] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def lowerCamelCase_ ( self : Dict ): _lowerCamelCase : List[Any] = "sshleifer/tiny-gpt2" with tempfile.TemporaryDirectory() as tmp_dir: _lowerCamelCase : Any = TensorFlowBenchmarkArguments( models=[MODEL_ID],inference=__A,save_to_csv=__A,sequence_lengths=[8],batch_sizes=[1],inference_time_csv_file=os.path.join(__A,"inf_time.csv" ),inference_memory_csv_file=os.path.join(__A,"inf_mem.csv" ),env_info_csv_file=os.path.join(__A,"env.csv" ),multi_process=__A,) _lowerCamelCase : Dict = TensorFlowBenchmark(__A ) benchmark.run() self.assertTrue(Path(os.path.join(__A,"inf_time.csv" ) ).exists() ) self.assertTrue(Path(os.path.join(__A,"inf_mem.csv" ) ).exists() ) self.assertTrue(Path(os.path.join(__A,"env.csv" ) ).exists() ) def lowerCamelCase_ ( self : Tuple ): _lowerCamelCase : Optional[int] = "sshleifer/tiny-gpt2" def _check_summary_is_not_empty(__A : List[Any] ): self.assertTrue(hasattr(__A,"sequential" ) ) self.assertTrue(hasattr(__A,"cumulative" ) ) self.assertTrue(hasattr(__A,"current" ) ) self.assertTrue(hasattr(__A,"total" ) ) with tempfile.TemporaryDirectory() as tmp_dir: _lowerCamelCase : List[Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID],inference=__A,sequence_lengths=[8],batch_sizes=[1],log_filename=os.path.join(__A,"log.txt" ),log_print=__A,trace_memory_line_by_line=__A,eager_mode=__A,multi_process=__A,) _lowerCamelCase : Tuple = TensorFlowBenchmark(__A ) _lowerCamelCase : str = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) self.assertTrue(Path(os.path.join(__A,"log.txt" ) ).exists() )
44
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING lowerCAmelCase : Union[str, Any] = logging.get_logger(__name__) class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : List[Any] = '''upernet''' def __init__( self : Any , lowerCAmelCase__ : Union[str, Any]=None , lowerCAmelCase__ : List[str]=512 , lowerCAmelCase__ : Any=0.02 , lowerCAmelCase__ : str=[1, 2, 3, 6] , lowerCAmelCase__ : Optional[Any]=True , lowerCAmelCase__ : Dict=0.4 , lowerCAmelCase__ : int=384 , lowerCAmelCase__ : Union[str, Any]=256 , lowerCAmelCase__ : Any=1 , lowerCAmelCase__ : Tuple=False , lowerCAmelCase__ : List[str]=255 , **lowerCAmelCase__ : List[str] , ): super().__init__(**lowerCAmelCase__) if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.") SCREAMING_SNAKE_CASE_: Dict = CONFIG_MAPPING["resnet"](out_features=["stage1", "stage2", "stage3", "stage4"]) elif isinstance(lowerCAmelCase__ , lowerCAmelCase__): SCREAMING_SNAKE_CASE_: str = backbone_config.get("model_type") SCREAMING_SNAKE_CASE_: str = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE_: Tuple = config_class.from_dict(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: str = backbone_config SCREAMING_SNAKE_CASE_: Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_: Dict = initializer_range SCREAMING_SNAKE_CASE_: Any = pool_scales SCREAMING_SNAKE_CASE_: Optional[Any] = use_auxiliary_head SCREAMING_SNAKE_CASE_: str = auxiliary_loss_weight SCREAMING_SNAKE_CASE_: List[Any] = auxiliary_in_channels SCREAMING_SNAKE_CASE_: Union[str, Any] = auxiliary_channels SCREAMING_SNAKE_CASE_: Dict = auxiliary_num_convs SCREAMING_SNAKE_CASE_: str = auxiliary_concat_input SCREAMING_SNAKE_CASE_: Dict = loss_ignore_index def _SCREAMING_SNAKE_CASE ( self : Tuple): SCREAMING_SNAKE_CASE_: Tuple = copy.deepcopy(self.__dict__) SCREAMING_SNAKE_CASE_: int = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE_: Optional[int] = self.__class__.model_type return output
671
0
import unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokenizerBase def A ( lowercase__ : Any , lowercase__ : List[Any] , lowercase__ : int , lowercase__ : Optional[Any] ) -> Optional[Any]: if isinstance(lowercase__ , lowercase__ ): UpperCamelCase__ :Tuple = np.full((len(lowercase__ ), sequence_length, 2) , lowercase__ ) else: UpperCamelCase__ :List[str] = np.full((len(lowercase__ ), sequence_length) , lowercase__ ) for i, tensor in enumerate(lowercase__ ): if padding_side == "right": if isinstance(lowercase__ , lowercase__ ): UpperCamelCase__ :List[Any] = tensor[:sequence_length] else: UpperCamelCase__ :Dict = tensor[:sequence_length] else: if isinstance(lowercase__ , lowercase__ ): UpperCamelCase__ :Optional[int] = tensor[:sequence_length] else: UpperCamelCase__ :Optional[int] = tensor[:sequence_length] return out_tensor.tolist() def A ( lowercase__ : Dict ) -> Optional[Any]: UpperCamelCase__ :List[Any] = ord(lowercase__ ) if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126): return True UpperCamelCase__ :str = unicodedata.category(lowercase__ ) if cat.startswith("""P""" ): return True return False @dataclass class lowerCAmelCase_ ( lowercase ): """simple docstring""" _snake_case : PreTrainedTokenizerBase _snake_case : Union[bool, str, PaddingStrategy] = True _snake_case : Optional[int] = None _snake_case : Optional[int] = None _snake_case : int = -100 _snake_case : str = "pt" def __a ( self :Any , lowerCamelCase__ :int ): import torch UpperCamelCase__ :str = """label""" if """label""" in features[0].keys() else """labels""" UpperCamelCase__ :str = [feature[label_name] for feature in features] if label_name in features[0].keys() else None UpperCamelCase__ :Any = self.tokenizer.pad( lowerCamelCase__ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="""pt""" if labels is None else None , ) if labels is None: return batch UpperCamelCase__ :List[Any] = torch.tensor(batch["""entity_ids"""] ).shape[1] UpperCamelCase__ :Optional[int] = self.tokenizer.padding_side if padding_side == "right": UpperCamelCase__ :Optional[Any] = [ list(lowerCamelCase__ ) + [self.label_pad_token_id] * (sequence_length - len(lowerCamelCase__ )) for label in labels ] else: UpperCamelCase__ :Union[str, Any] = [ [self.label_pad_token_id] * (sequence_length - len(lowerCamelCase__ )) + list(lowerCamelCase__ ) for label in labels ] UpperCamelCase__ :Optional[Any] = [feature["""ner_tags"""] for feature in features] UpperCamelCase__ :Optional[int] = padding_tensor(lowerCamelCase__ , -1 , lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase__ :Union[str, Any] = [feature["""original_entity_spans"""] for feature in features] UpperCamelCase__ :Tuple = padding_tensor(lowerCamelCase__ , (-1, -1) , lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase__ :int = {k: torch.tensor(lowerCamelCase__ , dtype=torch.intaa ) for k, v in batch.items()} return batch
45
import pickle import unittest import torch from accelerate import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils import require_cpu @require_cpu class __lowercase ( unittest.TestCase ): """simple docstring""" def _SCREAMING_SNAKE_CASE ( self : Any): SCREAMING_SNAKE_CASE_: List[str] = torch.nn.Linear(10 , 10) SCREAMING_SNAKE_CASE_: Union[str, Any] = torch.optim.SGD(model.parameters() , 0.1) SCREAMING_SNAKE_CASE_: Any = Accelerator() SCREAMING_SNAKE_CASE_: List[str] = accelerator.prepare(lowerCAmelCase__) try: pickle.loads(pickle.dumps(lowerCAmelCase__)) except Exception as e: self.fail(F"Accelerated optimizer pickling failed with {e}") AcceleratorState._reset_state()
671
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCAmelCase : List[Any] = { '''configuration_electra''': ['''ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ElectraConfig''', '''ElectraOnnxConfig'''], '''tokenization_electra''': ['''ElectraTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : Optional[int] = ['''ElectraTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : Tuple = [ '''ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ElectraForCausalLM''', '''ElectraForMaskedLM''', '''ElectraForMultipleChoice''', '''ElectraForPreTraining''', '''ElectraForQuestionAnswering''', '''ElectraForSequenceClassification''', '''ElectraForTokenClassification''', '''ElectraModel''', '''ElectraPreTrainedModel''', '''load_tf_weights_in_electra''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : Optional[int] = [ '''TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFElectraForMaskedLM''', '''TFElectraForMultipleChoice''', '''TFElectraForPreTraining''', '''TFElectraForQuestionAnswering''', '''TFElectraForSequenceClassification''', '''TFElectraForTokenClassification''', '''TFElectraModel''', '''TFElectraPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : Union[str, Any] = [ '''FlaxElectraForCausalLM''', '''FlaxElectraForMaskedLM''', '''FlaxElectraForMultipleChoice''', '''FlaxElectraForPreTraining''', '''FlaxElectraForQuestionAnswering''', '''FlaxElectraForSequenceClassification''', '''FlaxElectraForTokenClassification''', '''FlaxElectraModel''', '''FlaxElectraPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig from .tokenization_electra import ElectraTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_electra_fast import ElectraTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_electra import ( ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, ElectraForCausalLM, ElectraForMaskedLM, ElectraForMultipleChoice, ElectraForPreTraining, ElectraForQuestionAnswering, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel, ElectraPreTrainedModel, load_tf_weights_in_electra, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_electra import ( TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, TFElectraForMaskedLM, TFElectraForMultipleChoice, TFElectraForPreTraining, TFElectraForQuestionAnswering, TFElectraForSequenceClassification, TFElectraForTokenClassification, TFElectraModel, TFElectraPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_electra import ( FlaxElectraForCausalLM, FlaxElectraForMaskedLM, FlaxElectraForMultipleChoice, FlaxElectraForPreTraining, FlaxElectraForQuestionAnswering, FlaxElectraForSequenceClassification, FlaxElectraForTokenClassification, FlaxElectraModel, FlaxElectraPreTrainedModel, ) else: import sys _lowerCAmelCase : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
46
from itertools import count def A_ ( _UpperCAmelCase = 50 ): SCREAMING_SNAKE_CASE_: Union[str, Any] = [1] * min_block_length for n in count(_UpperCAmelCase ): fill_count_functions.append(1 ) for block_length in range(_UpperCAmelCase , 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() = }''')
671
0
def UpperCAmelCase__ ( lowerCamelCase_ : str ): if n_term == "": return [] __a : list = [] for temp in range(int(lowerCamelCase_ ) ): series.append(f'''1/{temp + 1}''' if series else '1' ) return series if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = input('''Enter the last number (nth term) of the Harmonic Series''') print('''Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n''') print(harmonic_series(nth_term))
47
def A_ ( _UpperCAmelCase ): if not isinstance(_UpperCAmelCase , _UpperCAmelCase ): raise TypeError("only integers accepted as input" ) else: SCREAMING_SNAKE_CASE_: List[Any] = str(abs(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE_: Tuple = [list(_UpperCAmelCase ) for char in range(len(_UpperCAmelCase ) )] for index in range(len(_UpperCAmelCase ) ): num_transpositions[index].pop(_UpperCAmelCase ) return max( int("".join(list(_UpperCAmelCase ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__("""doctest""").testmod()
671
0
'''simple docstring''' import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def A ( UpperCamelCase_ : Tuple , UpperCamelCase_ : Optional[int]=None ) -> List[str]: '''simple docstring''' lowerCAmelCase__ = None if token is not None: lowerCAmelCase__ = {"Accept": "application/vnd.github+json", "Authorization": F"""Bearer {token}"""} lowerCAmelCase__ = F"""https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100""" lowerCAmelCase__ = requests.get(UpperCamelCase_ , headers=UpperCamelCase_ ).json() lowerCAmelCase__ = {} try: job_links.update({job["name"]: job["html_url"] for job in result["jobs"]} ) lowerCAmelCase__ = math.ceil((result["total_count"] - 1_00) / 1_00 ) for i in range(UpperCamelCase_ ): lowerCAmelCase__ = requests.get(url + F"""&page={i + 2}""" , headers=UpperCamelCase_ ).json() job_links.update({job["name"]: job["html_url"] for job in result["jobs"]} ) return job_links except Exception: print(F"""Unknown error, could not fetch links:\n{traceback.format_exc()}""" ) return {} def A ( UpperCamelCase_ : Tuple , UpperCamelCase_ : Dict=None ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase__ = None if token is not None: lowerCAmelCase__ = {"Accept": "application/vnd.github+json", "Authorization": F"""Bearer {token}"""} lowerCAmelCase__ = F"""https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100""" lowerCAmelCase__ = requests.get(UpperCamelCase_ , headers=UpperCamelCase_ ).json() lowerCAmelCase__ = {} try: artifacts.update({artifact["name"]: artifact["archive_download_url"] for artifact in result["artifacts"]} ) lowerCAmelCase__ = math.ceil((result["total_count"] - 1_00) / 1_00 ) for i in range(UpperCamelCase_ ): lowerCAmelCase__ = requests.get(url + F"""&page={i + 2}""" , headers=UpperCamelCase_ ).json() artifacts.update({artifact["name"]: artifact["archive_download_url"] for artifact in result["artifacts"]} ) return artifacts except Exception: print(F"""Unknown error, could not fetch links:\n{traceback.format_exc()}""" ) return {} def A ( UpperCamelCase_ : List[Any] , UpperCamelCase_ : List[Any] , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : int ) -> List[Any]: '''simple docstring''' lowerCAmelCase__ = None if token is not None: lowerCAmelCase__ = {"Accept": "application/vnd.github+json", "Authorization": F"""Bearer {token}"""} lowerCAmelCase__ = requests.get(UpperCamelCase_ , headers=UpperCamelCase_ , allow_redirects=UpperCamelCase_ ) lowerCAmelCase__ = result.headers["Location"] lowerCAmelCase__ = requests.get(UpperCamelCase_ , allow_redirects=UpperCamelCase_ ) lowerCAmelCase__ = os.path.join(UpperCamelCase_ , F"""{artifact_name}.zip""" ) with open(UpperCamelCase_ , "wb" ) as fp: fp.write(response.content ) def A ( UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : Optional[int]=None ) -> int: '''simple docstring''' lowerCAmelCase__ = [] lowerCAmelCase__ = [] lowerCAmelCase__ = None with zipfile.ZipFile(UpperCamelCase_ ) as z: for filename in z.namelist(): if not os.path.isdir(UpperCamelCase_ ): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(UpperCamelCase_ ) as f: for line in f: lowerCAmelCase__ = line.decode("UTF-8" ).strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs lowerCAmelCase__ = line[: line.index(": " )] lowerCAmelCase__ = line[line.index(": " ) + len(": " ) :] errors.append([error_line, error] ) except Exception: # skip un-related lines pass elif filename == "summary_short.txt" and line.startswith("FAILED " ): # `test` is the test method that failed lowerCAmelCase__ = line[len("FAILED " ) :] failed_tests.append(UpperCamelCase_ ) elif filename == "job_name.txt": lowerCAmelCase__ = line if len(UpperCamelCase_ ) != len(UpperCamelCase_ ): raise ValueError( F"""`errors` and `failed_tests` should have the same number of elements. Got {len(UpperCamelCase_ )} for `errors` """ F"""and {len(UpperCamelCase_ )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some""" " problem." ) lowerCAmelCase__ = None if job_name and job_links: lowerCAmelCase__ = job_links.get(UpperCamelCase_ , UpperCamelCase_ ) # A list with elements of the form (line of error, error, failed test) lowerCAmelCase__ = [x + [y] + [job_link] for x, y in zip(UpperCamelCase_ , UpperCamelCase_ )] return result def A ( UpperCamelCase_ : str , UpperCamelCase_ : str=None ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase__ = [] lowerCAmelCase__ = [os.path.join(UpperCamelCase_ , UpperCamelCase_ ) for p in os.listdir(UpperCamelCase_ ) if p.endswith(".zip" )] for p in paths: errors.extend(get_errors_from_single_artifact(UpperCamelCase_ , job_links=UpperCamelCase_ ) ) return errors def A ( UpperCamelCase_ : Tuple , UpperCamelCase_ : List[str]=None ) -> int: '''simple docstring''' lowerCAmelCase__ = Counter() counter.update([x[1] for x in logs] ) lowerCAmelCase__ = counter.most_common() lowerCAmelCase__ = {} for error, count in counts: if error_filter is None or error not in error_filter: lowerCAmelCase__ = {"count": count, "failed_tests": [(x[2], x[0]) for x in logs if x[1] == error]} lowerCAmelCase__ = dict(sorted(r.items() , key=lambda UpperCamelCase_ : item[1]["count"] , reverse=UpperCamelCase_ ) ) return r def A ( UpperCamelCase_ : List[str] ) -> Tuple: '''simple docstring''' lowerCAmelCase__ = test.split("::" )[0] if test.startswith("tests/models/" ): lowerCAmelCase__ = test.split("/" )[2] else: lowerCAmelCase__ = None return test def A ( UpperCamelCase_ : List[str] , UpperCamelCase_ : List[str]=None ) -> List[Any]: '''simple docstring''' lowerCAmelCase__ = [(x[0], x[1], get_model(x[2] )) for x in logs] lowerCAmelCase__ = [x for x in logs if x[2] is not None] lowerCAmelCase__ = {x[2] for x in logs} lowerCAmelCase__ = {} for test in tests: lowerCAmelCase__ = Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test] ) lowerCAmelCase__ = counter.most_common() lowerCAmelCase__ = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} lowerCAmelCase__ = sum(error_counts.values() ) if n_errors > 0: lowerCAmelCase__ = {"count": n_errors, "errors": error_counts} lowerCAmelCase__ = dict(sorted(r.items() , key=lambda UpperCamelCase_ : item[1]["count"] , reverse=UpperCamelCase_ ) ) return r def A ( UpperCamelCase_ : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase__ = "| no. | error | status |" lowerCAmelCase__ = "|-:|:-|:-|" lowerCAmelCase__ = [header, sep] for error in reduced_by_error: lowerCAmelCase__ = reduced_by_error[error]["count"] lowerCAmelCase__ = F"""| {count} | {error[:1_00]} | |""" lines.append(UpperCamelCase_ ) return "\n".join(UpperCamelCase_ ) def A ( UpperCamelCase_ : Tuple ) -> Dict: '''simple docstring''' lowerCAmelCase__ = "| model | no. of errors | major error | count |" lowerCAmelCase__ = "|-:|-:|-:|-:|" lowerCAmelCase__ = [header, sep] for model in reduced_by_model: lowerCAmelCase__ = reduced_by_model[model]["count"] lowerCAmelCase__ ,lowerCAmelCase__ = list(reduced_by_model[model]["errors"].items() )[0] lowerCAmelCase__ = F"""| {model} | {count} | {error[:60]} | {_count} |""" lines.append(UpperCamelCase_ ) return "\n".join(UpperCamelCase_ ) if __name__ == "__main__": UpperCAmelCase__ : Any = argparse.ArgumentParser() # Required parameters parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.") parser.add_argument( "--output_dir", type=str, required=True, help="Where to store the downloaded artifacts and other result files.", ) parser.add_argument("--token", default=None, type=str, help="A token that has actions:read permission.") UpperCAmelCase__ : List[Any] = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) UpperCAmelCase__ : List[Any] = get_job_links(args.workflow_run_id, token=args.token) UpperCAmelCase__ : List[str] = {} # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. if _job_links: for k, v in _job_links.items(): # This is how GitHub actions combine job names. if " / " in k: UpperCAmelCase__ : List[str] = k.find(" / ") UpperCAmelCase__ : Tuple = k[index + len(" / ") :] UpperCAmelCase__ : List[str] = v with open(os.path.join(args.output_dir, "job_links.json"), "w", encoding="UTF-8") as fp: json.dump(job_links, fp, ensure_ascii=False, indent=4) UpperCAmelCase__ : Optional[int] = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, "artifacts.json"), "w", encoding="UTF-8") as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) for idx, (name, url) in enumerate(artifacts.items()): download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) UpperCAmelCase__ : str = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error UpperCAmelCase__ : List[str] = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors UpperCAmelCase__ : str = counter.most_common(30) for item in most_common: print(item) with open(os.path.join(args.output_dir, "errors.json"), "w", encoding="UTF-8") as fp: json.dump(errors, fp, ensure_ascii=False, indent=4) UpperCAmelCase__ : int = reduce_by_error(errors) UpperCAmelCase__ : List[str] = reduce_by_model(errors) UpperCAmelCase__ : Union[str, Any] = make_github_table(reduced_by_error) UpperCAmelCase__ : Dict = make_github_table_per_model(reduced_by_model) with open(os.path.join(args.output_dir, "reduced_by_error.txt"), "w", encoding="UTF-8") as fp: fp.write(sa) with open(os.path.join(args.output_dir, "reduced_by_model.txt"), "w", encoding="UTF-8") as fp: fp.write(sa)
48
from __future__ import annotations from collections.abc import Iterator from typing import Any class __lowercase : """simple docstring""" def __init__( self : List[str] , lowerCAmelCase__ : Any): SCREAMING_SNAKE_CASE_: Any = data SCREAMING_SNAKE_CASE_: Node | None = None class __lowercase : """simple docstring""" def __init__( self : int): SCREAMING_SNAKE_CASE_: Dict = None SCREAMING_SNAKE_CASE_: str = None def __iter__( self : List[str]): SCREAMING_SNAKE_CASE_: Tuple = self.head while self.head: yield node.data SCREAMING_SNAKE_CASE_: List[str] = node.next if node == self.head: break def __len__( self : Dict): return sum(1 for _ in self) def __repr__( self : Dict): return "->".join(str(lowerCAmelCase__) for item in iter(self)) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase__ : Any): self.insert_nth(len(self) , lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase__ : Any): self.insert_nth(0 , lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : Any): if index < 0 or index > len(self): raise IndexError("list index out of range.") SCREAMING_SNAKE_CASE_: Any = Node(lowerCAmelCase__) if self.head is None: SCREAMING_SNAKE_CASE_: str = new_node # first node points itself SCREAMING_SNAKE_CASE_: Optional[Any] = new_node elif index == 0: # insert at head SCREAMING_SNAKE_CASE_: Optional[Any] = self.head SCREAMING_SNAKE_CASE_: str = new_node else: SCREAMING_SNAKE_CASE_: int = self.head for _ in range(index - 1): SCREAMING_SNAKE_CASE_: Optional[Any] = temp.next SCREAMING_SNAKE_CASE_: List[str] = temp.next SCREAMING_SNAKE_CASE_: int = new_node if index == len(self) - 1: # insert at tail SCREAMING_SNAKE_CASE_: Any = new_node def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): return self.delete_nth(0) def _SCREAMING_SNAKE_CASE ( self : Any): return self.delete_nth(len(self) - 1) def _SCREAMING_SNAKE_CASE ( self : Any , lowerCAmelCase__ : int = 0): if not 0 <= index < len(self): raise IndexError("list index out of range.") SCREAMING_SNAKE_CASE_: Optional[Any] = self.head if self.head == self.tail: # just one node SCREAMING_SNAKE_CASE_: List[str] = None elif index == 0: # delete head node SCREAMING_SNAKE_CASE_: int = self.tail.next.next SCREAMING_SNAKE_CASE_: Tuple = self.head.next else: SCREAMING_SNAKE_CASE_: Optional[int] = self.head for _ in range(index - 1): SCREAMING_SNAKE_CASE_: Any = temp.next SCREAMING_SNAKE_CASE_: Optional[Any] = temp.next SCREAMING_SNAKE_CASE_: int = temp.next.next if index == len(self) - 1: # delete at tail SCREAMING_SNAKE_CASE_: int = temp return delete_node.data def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): return len(self) == 0 def A_ ( ): SCREAMING_SNAKE_CASE_: Dict = CircularLinkedList() assert len(_UpperCAmelCase ) == 0 assert circular_linked_list.is_empty() is True assert str(_UpperCAmelCase ) == "" try: circular_linked_list.delete_front() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_tail() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_nth(-1 ) raise AssertionError except IndexError: assert True try: circular_linked_list.delete_nth(0 ) raise AssertionError except IndexError: assert True assert circular_linked_list.is_empty() is True for i in range(5 ): assert len(_UpperCAmelCase ) == i circular_linked_list.insert_nth(_UpperCAmelCase , i + 1 ) assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 6 ) ) circular_linked_list.insert_tail(6 ) assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 7 ) ) circular_linked_list.insert_head(0 ) assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(0 , 7 ) ) assert circular_linked_list.delete_front() == 0 assert circular_linked_list.delete_tail() == 6 assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 6 ) ) assert circular_linked_list.delete_nth(2 ) == 3 circular_linked_list.insert_nth(2 , 3 ) assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 6 ) ) assert circular_linked_list.is_empty() is False if __name__ == "__main__": import doctest doctest.testmod()
671
0
"""simple docstring""" def lowercase__ ( snake_case_ :List[str]=28_123 ): __UpperCAmelCase = [1] * (limit + 1) for i in range(2 , int(limit**0.5 ) + 1 ): sum_divs[i * i] += i for k in range(i + 1 , limit // i + 1 ): sum_divs[k * i] += k + i __UpperCAmelCase = set() __UpperCAmelCase = 0 for n in range(1 , limit + 1 ): if sum_divs[n] > n: abundants.add(snake_case_ ) if not any((n - a in abundants) for a in abundants ): res += n return res if __name__ == "__main__": print(solution())
49
from collections import defaultdict from math import ceil, sqrt def A_ ( _UpperCAmelCase = 1_00_00_00 , _UpperCAmelCase = 10 ): SCREAMING_SNAKE_CASE_: defaultdict = defaultdict(_UpperCAmelCase ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: SCREAMING_SNAKE_CASE_: Tuple = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: SCREAMING_SNAKE_CASE_: Optional[Any] = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(_UpperCAmelCase , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(f'''{solution() = }''')
671
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase : Optional[Any] = logging.get_logger(__name__) UpperCamelCase : Optional[int] = { 'alibaba-damo/mgp-str-base': 'https://huggingface.co/alibaba-damo/mgp-str-base/resolve/main/config.json', } class UpperCamelCase__ (a ): '''simple docstring''' _UpperCamelCase = 'mgp-str' def __init__( self ,_lowerCAmelCase=[32, 1_28] ,_lowerCAmelCase=4 ,_lowerCAmelCase=3 ,_lowerCAmelCase=27 ,_lowerCAmelCase=38 ,_lowerCAmelCase=5_02_57 ,_lowerCAmelCase=3_05_22 ,_lowerCAmelCase=7_68 ,_lowerCAmelCase=12 ,_lowerCAmelCase=12 ,_lowerCAmelCase=4.0 ,_lowerCAmelCase=True ,_lowerCAmelCase=False ,_lowerCAmelCase=1E-5 ,_lowerCAmelCase=0.0 ,_lowerCAmelCase=0.0 ,_lowerCAmelCase=0.0 ,_lowerCAmelCase=False ,_lowerCAmelCase=0.02 ,**_lowerCAmelCase ,): super().__init__(**_lowerCAmelCase ) lowerCamelCase__ = image_size lowerCamelCase__ = patch_size lowerCamelCase__ = num_channels lowerCamelCase__ = max_token_length lowerCamelCase__ = num_character_labels lowerCamelCase__ = num_bpe_labels lowerCamelCase__ = num_wordpiece_labels lowerCamelCase__ = hidden_size lowerCamelCase__ = num_hidden_layers lowerCamelCase__ = num_attention_heads lowerCamelCase__ = mlp_ratio lowerCamelCase__ = distilled lowerCamelCase__ = layer_norm_eps lowerCamelCase__ = drop_rate lowerCamelCase__ = qkv_bias lowerCamelCase__ = attn_drop_rate lowerCamelCase__ = drop_path_rate lowerCamelCase__ = output_aa_attentions lowerCamelCase__ = initializer_range
50
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCAmelCase : str = { """configuration_xlm""": ["""XLM_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLMConfig""", """XLMOnnxConfig"""], """tokenization_xlm""": ["""XLMTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : Dict = [ """XLM_PRETRAINED_MODEL_ARCHIVE_LIST""", """XLMForMultipleChoice""", """XLMForQuestionAnswering""", """XLMForQuestionAnsweringSimple""", """XLMForSequenceClassification""", """XLMForTokenClassification""", """XLMModel""", """XLMPreTrainedModel""", """XLMWithLMHeadModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : List[str] = [ """TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFXLMForMultipleChoice""", """TFXLMForQuestionAnsweringSimple""", """TFXLMForSequenceClassification""", """TFXLMForTokenClassification""", """TFXLMMainLayer""", """TFXLMModel""", """TFXLMPreTrainedModel""", """TFXLMWithLMHeadModel""", ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys lowerCAmelCase : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
671
0
'''simple docstring''' import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": a__ : Optional[Any] = pd.read_csv('sample_data.csv', header=None) a__ : str = df.shape[:1][0] # If you're using some other dataset input the target column a__ : Dict = df.iloc[:, 1:2] a__ : Tuple = actual_data.values.reshape(len_data, 1) a__ : int = MinMaxScaler().fit_transform(actual_data) a__ : int = 10 a__ : int = 5 a__ : Dict = 20 a__ : Union[str, Any] = len_data - periods * look_back a__ : Optional[int] = actual_data[:division] a__ : Union[str, Any] = actual_data[division - look_back :] a__ , a__ : Any = [], [] a__ , a__ : Tuple = [], [] for i in range(0, len(train_data) - forward_days - look_back + 1): train_x.append(train_data[i : i + look_back]) train_y.append(train_data[i + look_back : i + look_back + forward_days]) for i in range(0, len(test_data) - forward_days - look_back + 1): test_x.append(test_data[i : i + look_back]) test_y.append(test_data[i + look_back : i + look_back + forward_days]) a__ : Any = np.array(train_x) a__ : List[str] = np.array(test_x) a__ : str = np.array([list(i.ravel()) for i in train_y]) a__ : Optional[int] = np.array([list(i.ravel()) for i in test_y]) a__ : int = Sequential() model.add(LSTM(128, input_shape=(look_back, 1), return_sequences=True)) model.add(LSTM(64, input_shape=(128, 1))) model.add(Dense(forward_days)) model.compile(loss='mean_squared_error', optimizer='adam') a__ : Optional[Any] = model.fit( x_train, y_train, epochs=150, verbose=1, shuffle=True, batch_size=4 ) a__ : List[Any] = model.predict(x_test)
51
lowerCAmelCase : List[str] = { """A""": ["""B""", """C""", """E"""], """B""": ["""A""", """D""", """E"""], """C""": ["""A""", """F""", """G"""], """D""": ["""B"""], """E""": ["""A""", """B""", """D"""], """F""": ["""C"""], """G""": ["""C"""], } def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Any = set() # keep track of all the paths to be checked SCREAMING_SNAKE_CASE_: Tuple = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue SCREAMING_SNAKE_CASE_: List[Any] = queue.pop(0 ) # get the last node from the path SCREAMING_SNAKE_CASE_: Tuple = path[-1] if node not in explored: SCREAMING_SNAKE_CASE_: Union[str, Any] = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: SCREAMING_SNAKE_CASE_: int = list(_UpperCAmelCase ) new_path.append(_UpperCAmelCase ) queue.append(_UpperCAmelCase ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(_UpperCAmelCase ) # in case there's no path between the 2 nodes return [] def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 SCREAMING_SNAKE_CASE_: List[Any] = [start] SCREAMING_SNAKE_CASE_: List[str] = set(_UpperCAmelCase ) # Keep tab on distances from `start` node. SCREAMING_SNAKE_CASE_: Union[str, Any] = {start: 0, target: -1} while queue: SCREAMING_SNAKE_CASE_: Dict = queue.pop(0 ) if node == target: SCREAMING_SNAKE_CASE_: Tuple = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(_UpperCAmelCase ) queue.append(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, """G""", """D""")) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, """G""", """D""")) # returns 4
671
0
"""simple docstring""" from __future__ import annotations from typing import Any def __A ( a_ :list[Any]) -> None: create_state_space_tree(a_ , [] , 0) def __A ( a_ :list[Any] , a_ :list[Any] , a_ :int) -> None: if index == len(a_): print(a_) return create_state_space_tree(a_ , a_ , index + 1) current_subsequence.append(sequence[index]) create_state_space_tree(a_ , a_ , index + 1) current_subsequence.pop() if __name__ == "__main__": A = [3, 1, 2, 4] generate_all_subsequences(seq) seq.clear() seq.extend(['''A''', '''B''', '''C''']) generate_all_subsequences(seq)
52
from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class __lowercase ( UpperCAmelCase_ ): """simple docstring""" def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowerCAmelCase__ : float): return 0.0 def A_ ( _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: List[str] = min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] ) SCREAMING_SNAKE_CASE_: Dict = max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def A_ ( _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[int] = 5_12 SCREAMING_SNAKE_CASE_: str = [1] + [0] * (size - 1) SCREAMING_SNAKE_CASE_: Dict = [filter_type.process(_UpperCAmelCase ) for item in inputs] SCREAMING_SNAKE_CASE_: Optional[Any] = [0] * (samplerate - size) # zero-padding outputs += filler SCREAMING_SNAKE_CASE_: Tuple = np.abs(np.fft.fft(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE_: Optional[Any] = 20 * np.logaa(_UpperCAmelCase ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel("Frequency (Hz)" ) plt.xscale("log" ) # Display within reasonable bounds SCREAMING_SNAKE_CASE_: Any = get_bounds(_UpperCAmelCase , _UpperCAmelCase ) plt.ylim(max([-80, bounds[0]] ) , min([80, bounds[1]] ) ) plt.ylabel("Gain (dB)" ) plt.plot(_UpperCAmelCase ) plt.show() def A_ ( _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[int] = 5_12 SCREAMING_SNAKE_CASE_: Union[str, Any] = [1] + [0] * (size - 1) SCREAMING_SNAKE_CASE_: Dict = [filter_type.process(_UpperCAmelCase ) for item in inputs] SCREAMING_SNAKE_CASE_: int = [0] * (samplerate - size) # zero-padding outputs += filler SCREAMING_SNAKE_CASE_: Any = np.angle(np.fft.fft(_UpperCAmelCase ) ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel("Frequency (Hz)" ) plt.xscale("log" ) plt.ylim(-2 * pi , 2 * pi ) plt.ylabel("Phase shift (Radians)" ) plt.plot(np.unwrap(_UpperCAmelCase , -2 * pi ) ) plt.show()
671
0
from dataclasses import dataclass from typing import Optional import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .modeling_utils import ModelMixin @dataclass class _UpperCAmelCase ( _UpperCamelCase ): """simple docstring""" a_ = 42 class _UpperCAmelCase ( _UpperCamelCase , _UpperCamelCase ): """simple docstring""" @register_to_config def __init__( self : int , lowerCAmelCase_ : int = 1_6 , lowerCAmelCase_ : int = 8_8 , lowerCAmelCase_ : Optional[int] = None , lowerCAmelCase_ : Optional[int] = None , lowerCAmelCase_ : int = 1 , lowerCAmelCase_ : float = 0.0 , lowerCAmelCase_ : int = 3_2 , lowerCAmelCase_ : Optional[int] = None , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : Optional[int] = None , lowerCAmelCase_ : str = "geglu" , lowerCAmelCase_ : bool = True , lowerCAmelCase_ : bool = True , ) -> str: super().__init__() __lowerCAmelCase = num_attention_heads __lowerCAmelCase = attention_head_dim __lowerCAmelCase = num_attention_heads * attention_head_dim __lowerCAmelCase = in_channels __lowerCAmelCase = torch.nn.GroupNorm(num_groups=lowerCAmelCase_ , num_channels=lowerCAmelCase_ , eps=1e-6 , affine=lowerCAmelCase_ ) __lowerCAmelCase = nn.Linear(lowerCAmelCase_ , lowerCAmelCase_ ) # 3. Define transformers blocks __lowerCAmelCase = nn.ModuleList( [ BasicTransformerBlock( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , dropout=lowerCAmelCase_ , cross_attention_dim=lowerCAmelCase_ , activation_fn=lowerCAmelCase_ , attention_bias=lowerCAmelCase_ , double_self_attention=lowerCAmelCase_ , norm_elementwise_affine=lowerCAmelCase_ , ) for d in range(lowerCAmelCase_ ) ] ) __lowerCAmelCase = nn.Linear(lowerCAmelCase_ , lowerCAmelCase_ ) def lowercase ( self : Union[str, Any] , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Any=None , lowerCAmelCase_ : List[str]=None , lowerCAmelCase_ : Union[str, Any]=None , lowerCAmelCase_ : Union[str, Any]=1 , lowerCAmelCase_ : Optional[int]=None , lowerCAmelCase_ : bool = True , ) -> Optional[Any]: __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = hidden_states.shape __lowerCAmelCase = batch_frames // num_frames __lowerCAmelCase = hidden_states __lowerCAmelCase = hidden_states[None, :].reshape(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) __lowerCAmelCase = hidden_states.permute(0 , 2 , 1 , 3 , 4 ) __lowerCAmelCase = self.norm(lowerCAmelCase_ ) __lowerCAmelCase = hidden_states.permute(0 , 3 , 4 , 2 , 1 ).reshape(batch_size * height * width , lowerCAmelCase_ , lowerCAmelCase_ ) __lowerCAmelCase = self.proj_in(lowerCAmelCase_ ) # 2. Blocks for block in self.transformer_blocks: __lowerCAmelCase = block( lowerCAmelCase_ , encoder_hidden_states=lowerCAmelCase_ , timestep=lowerCAmelCase_ , cross_attention_kwargs=lowerCAmelCase_ , class_labels=lowerCAmelCase_ , ) # 3. Output __lowerCAmelCase = self.proj_out(lowerCAmelCase_ ) __lowerCAmelCase = ( hidden_states[None, None, :] .reshape(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) .permute(0 , 3 , 4 , 1 , 2 ) .contiguous() ) __lowerCAmelCase = hidden_states.reshape(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) __lowerCAmelCase = hidden_states + residual if not return_dict: return (output,) return TransformerTemporalModelOutput(sample=lowerCAmelCase_ )
53
from __future__ import annotations from math import ceil, floor, sqrt def A_ ( _UpperCAmelCase = 2_00_00_00 ): SCREAMING_SNAKE_CASE_: list[int] = [0] SCREAMING_SNAKE_CASE_: int for idx in range(1 , ceil(sqrt(target * 2 ) * 1.1 ) ): triangle_numbers.append(triangle_numbers[-1] + idx ) # we want this to be as close as possible to target SCREAMING_SNAKE_CASE_: int = 0 # the area corresponding to the grid that gives the product closest to target SCREAMING_SNAKE_CASE_: int = 0 # an estimate of b, using the quadratic formula SCREAMING_SNAKE_CASE_: float # the largest integer less than b_estimate SCREAMING_SNAKE_CASE_: int # the largest integer less than b_estimate SCREAMING_SNAKE_CASE_: int # the triangle number corresponding to b_floor SCREAMING_SNAKE_CASE_: int # the triangle number corresponding to b_ceil SCREAMING_SNAKE_CASE_: int for idx_a, triangle_a in enumerate(triangle_numbers[1:] , 1 ): SCREAMING_SNAKE_CASE_: List[Any] = (-1 + sqrt(1 + 8 * target / triangle_a )) / 2 SCREAMING_SNAKE_CASE_: Any = floor(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] = ceil(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Any = triangle_numbers[b_floor] SCREAMING_SNAKE_CASE_: List[Any] = triangle_numbers[b_ceil] if abs(target - triangle_b_first_guess * triangle_a ) < abs( target - best_product ): SCREAMING_SNAKE_CASE_: int = triangle_b_first_guess * triangle_a SCREAMING_SNAKE_CASE_: int = idx_a * b_floor if abs(target - triangle_b_second_guess * triangle_a ) < abs( target - best_product ): SCREAMING_SNAKE_CASE_: Optional[Any] = triangle_b_second_guess * triangle_a SCREAMING_SNAKE_CASE_: Tuple = idx_a * b_ceil return area if __name__ == "__main__": print(f'''{solution() = }''')
671
0
import heapq def a__ ( lowercase__ ): '''simple docstring''' UpperCAmelCase_ =[] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq works with a min priority queue, so I used -1*len(v) to build it for key, value in graph.items(): # O(log(n)) heapq.heappush(lowercase__ , [-1 * len(lowercase__ ), (key, value)] ) # chosen_vertices = set of chosen vertices UpperCAmelCase_ =set() # while queue isn't empty and there are still edges # (queue[0][0] is the rank of the node with max rank) while queue and queue[0][0] != 0: # extract vertex with max rank from queue and add it to chosen_vertices UpperCAmelCase_ =heapq.heappop(lowercase__ )[1][0] chosen_vertices.add(lowercase__ ) # Remove all arcs adjacent to argmax for elem in queue: # if v haven't adjacent node, skip if elem[0] == 0: continue # if argmax is reachable from elem # remove argmax from elem's adjacent list and update his rank if argmax in elem[1][1]: UpperCAmelCase_ =elem[1][1].index(lowercase__ ) del elem[1][1][index] elem[0] += 1 # re-order the queue heapq.heapify(lowercase__ ) return chosen_vertices if __name__ == "__main__": import doctest doctest.testmod() __lowercase : Dict ={0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} print(f"""Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}""")
54
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase : Optional[int] = { """configuration_longformer""": [ """LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LongformerConfig""", """LongformerOnnxConfig""", ], """tokenization_longformer""": ["""LongformerTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : List[str] = ["""LongformerTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : Union[str, Any] = [ """LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """LongformerForMaskedLM""", """LongformerForMultipleChoice""", """LongformerForQuestionAnswering""", """LongformerForSequenceClassification""", """LongformerForTokenClassification""", """LongformerModel""", """LongformerPreTrainedModel""", """LongformerSelfAttention""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : int = [ """TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFLongformerForMaskedLM""", """TFLongformerForMultipleChoice""", """TFLongformerForQuestionAnswering""", """TFLongformerForSequenceClassification""", """TFLongformerForTokenClassification""", """TFLongformerModel""", """TFLongformerPreTrainedModel""", """TFLongformerSelfAttention""", ] if TYPE_CHECKING: from .configuration_longformer import ( LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, LongformerConfig, LongformerOnnxConfig, ) from .tokenization_longformer import LongformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_longformer_fast import LongformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longformer import ( LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, LongformerForMaskedLM, LongformerForMultipleChoice, LongformerForQuestionAnswering, LongformerForSequenceClassification, LongformerForTokenClassification, LongformerModel, LongformerPreTrainedModel, LongformerSelfAttention, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_longformer import ( TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFLongformerForMaskedLM, TFLongformerForMultipleChoice, TFLongformerForQuestionAnswering, TFLongformerForSequenceClassification, TFLongformerForTokenClassification, TFLongformerModel, TFLongformerPreTrainedModel, TFLongformerSelfAttention, ) else: import sys lowerCAmelCase : Optional[int] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
671
0
from collections import namedtuple import requests from lxml import html # type: ignore SCREAMING_SNAKE_CASE :int = namedtuple('covid_data', 'cases deaths recovered') def UpperCAmelCase ( a_ = "https://www.worldometers.info/coronavirus/" ) -> covid_data: """simple docstring""" __A = "//div[@class = \"maincounter-number\"]/span/text()" return covid_data(*html.fromstring(requests.get(a_ ).content ).xpath(a_ ) ) SCREAMING_SNAKE_CASE :List[str] = 'Total COVID-19 cases in the world: {}\nTotal deaths due to COVID-19 in the world: {}\nTotal COVID-19 patients recovered in the world: {}' print(fmt.format(*covid_stats()))
55
import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# lowerCAmelCase : Optional[int] = [ # (stable-diffusion, HF Diffusers) ("""time_embed.0.weight""", """time_embedding.linear_1.weight"""), ("""time_embed.0.bias""", """time_embedding.linear_1.bias"""), ("""time_embed.2.weight""", """time_embedding.linear_2.weight"""), ("""time_embed.2.bias""", """time_embedding.linear_2.bias"""), ("""input_blocks.0.0.weight""", """conv_in.weight"""), ("""input_blocks.0.0.bias""", """conv_in.bias"""), ("""out.0.weight""", """conv_norm_out.weight"""), ("""out.0.bias""", """conv_norm_out.bias"""), ("""out.2.weight""", """conv_out.weight"""), ("""out.2.bias""", """conv_out.bias"""), ] lowerCAmelCase : str = [ # (stable-diffusion, HF Diffusers) ("""in_layers.0""", """norm1"""), ("""in_layers.2""", """conv1"""), ("""out_layers.0""", """norm2"""), ("""out_layers.3""", """conv2"""), ("""emb_layers.1""", """time_emb_proj"""), ("""skip_connection""", """conv_shortcut"""), ] lowerCAmelCase : List[str] = [] # hardcoded number of downblocks and resnets/attentions... # would need smarter logic for other networks. for i in range(4): # loop over downblocks/upblocks for j in range(2): # loop over resnets/attentions for downblocks lowerCAmelCase : int = f'''down_blocks.{i}.resnets.{j}.''' lowerCAmelCase : List[str] = f'''input_blocks.{3*i + j + 1}.0.''' unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix)) if i < 3: # no attention layers in down_blocks.3 lowerCAmelCase : Any = f'''down_blocks.{i}.attentions.{j}.''' lowerCAmelCase : List[Any] = f'''input_blocks.{3*i + j + 1}.1.''' unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix)) for j in range(3): # loop over resnets/attentions for upblocks lowerCAmelCase : Any = f'''up_blocks.{i}.resnets.{j}.''' lowerCAmelCase : str = f'''output_blocks.{3*i + j}.0.''' unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix)) if i > 0: # no attention layers in up_blocks.0 lowerCAmelCase : List[Any] = f'''up_blocks.{i}.attentions.{j}.''' lowerCAmelCase : str = f'''output_blocks.{3*i + j}.1.''' unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix)) if i < 3: # no downsample in down_blocks.3 lowerCAmelCase : Any = f'''down_blocks.{i}.downsamplers.0.conv.''' lowerCAmelCase : Tuple = f'''input_blocks.{3*(i+1)}.0.op.''' unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix)) # no upsample in up_blocks.3 lowerCAmelCase : Tuple = f'''up_blocks.{i}.upsamplers.0.''' lowerCAmelCase : Tuple = f'''output_blocks.{3*i + 2}.{1 if i == 0 else 2}.''' unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix)) lowerCAmelCase : Any = """mid_block.attentions.0.""" lowerCAmelCase : Dict = """middle_block.1.""" unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix)) for j in range(2): lowerCAmelCase : int = f'''mid_block.resnets.{j}.''' lowerCAmelCase : Union[str, Any] = f'''middle_block.{2*j}.''' unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix)) def A_ ( _UpperCAmelCase ): # buyer beware: this is a *brittle* function, # and correct output requires that all of these pieces interact in # the exact order in which I have arranged them. SCREAMING_SNAKE_CASE_: Dict = {k: k for k in unet_state_dict.keys()} for sd_name, hf_name in unet_conversion_map: SCREAMING_SNAKE_CASE_: Optional[int] = sd_name for k, v in mapping.items(): if "resnets" in k: for sd_part, hf_part in unet_conversion_map_resnet: SCREAMING_SNAKE_CASE_: Any = v.replace(_UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: str = v for k, v in mapping.items(): for sd_part, hf_part in unet_conversion_map_layer: SCREAMING_SNAKE_CASE_: Optional[Any] = v.replace(_UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] = v SCREAMING_SNAKE_CASE_: Optional[Any] = {v: unet_state_dict[k] for k, v in mapping.items()} return new_state_dict # ================# # VAE Conversion # # ================# lowerCAmelCase : Union[str, Any] = [ # (stable-diffusion, HF Diffusers) ("""nin_shortcut""", """conv_shortcut"""), ("""norm_out""", """conv_norm_out"""), ("""mid.attn_1.""", """mid_block.attentions.0."""), ] for i in range(4): # down_blocks have two resnets for j in range(2): lowerCAmelCase : Union[str, Any] = f'''encoder.down_blocks.{i}.resnets.{j}.''' lowerCAmelCase : Optional[Any] = f'''encoder.down.{i}.block.{j}.''' vae_conversion_map.append((sd_down_prefix, hf_down_prefix)) if i < 3: lowerCAmelCase : Dict = f'''down_blocks.{i}.downsamplers.0.''' lowerCAmelCase : List[str] = f'''down.{i}.downsample.''' vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix)) lowerCAmelCase : List[str] = f'''up_blocks.{i}.upsamplers.0.''' lowerCAmelCase : int = f'''up.{3-i}.upsample.''' vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix)) # up_blocks have three resnets # also, up blocks in hf are numbered in reverse from sd for j in range(3): lowerCAmelCase : Any = f'''decoder.up_blocks.{i}.resnets.{j}.''' lowerCAmelCase : int = f'''decoder.up.{3-i}.block.{j}.''' vae_conversion_map.append((sd_up_prefix, hf_up_prefix)) # this part accounts for mid blocks in both the encoder and the decoder for i in range(2): lowerCAmelCase : str = f'''mid_block.resnets.{i}.''' lowerCAmelCase : Tuple = f'''mid.block_{i+1}.''' vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix)) lowerCAmelCase : List[Any] = [ # (stable-diffusion, HF Diffusers) ("""norm.""", """group_norm."""), ("""q.""", """query."""), ("""k.""", """key."""), ("""v.""", """value."""), ("""proj_out.""", """proj_attn."""), ] def A_ ( _UpperCAmelCase ): # convert HF linear weights to SD conv2d weights return w.reshape(*w.shape , 1 , 1 ) def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[Any] = {k: k for k in vae_state_dict.keys()} for k, v in mapping.items(): for sd_part, hf_part in vae_conversion_map: SCREAMING_SNAKE_CASE_: Union[str, Any] = v.replace(_UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] = v for k, v in mapping.items(): if "attentions" in k: for sd_part, hf_part in vae_conversion_map_attn: SCREAMING_SNAKE_CASE_: Any = v.replace(_UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] = v SCREAMING_SNAKE_CASE_: Tuple = {v: vae_state_dict[k] for k, v in mapping.items()} SCREAMING_SNAKE_CASE_: Union[str, Any] = ["q", "k", "v", "proj_out"] for k, v in new_state_dict.items(): for weight_name in weights_to_convert: if f"mid.attn_1.{weight_name}.weight" in k: print(f"Reshaping {k} for SD format" ) SCREAMING_SNAKE_CASE_: List[str] = reshape_weight_for_sd(_UpperCAmelCase ) return new_state_dict # =========================# # Text Encoder Conversion # # =========================# lowerCAmelCase : Optional[Any] = [ # (stable-diffusion, HF Diffusers) ("""resblocks.""", """text_model.encoder.layers."""), ("""ln_1""", """layer_norm1"""), ("""ln_2""", """layer_norm2"""), (""".c_fc.""", """.fc1."""), (""".c_proj.""", """.fc2."""), (""".attn""", """.self_attn"""), ("""ln_final.""", """transformer.text_model.final_layer_norm."""), ("""token_embedding.weight""", """transformer.text_model.embeddings.token_embedding.weight"""), ("""positional_embedding""", """transformer.text_model.embeddings.position_embedding.weight"""), ] lowerCAmelCase : Optional[Any] = {re.escape(x[1]): x[0] for x in textenc_conversion_lst} lowerCAmelCase : Optional[int] = re.compile("""|""".join(protected.keys())) # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp lowerCAmelCase : str = {"""q""": 0, """k""": 1, """v""": 2} def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: str = {} SCREAMING_SNAKE_CASE_: str = {} SCREAMING_SNAKE_CASE_: List[str] = {} for k, v in text_enc_dict.items(): if ( k.endswith(".self_attn.q_proj.weight" ) or k.endswith(".self_attn.k_proj.weight" ) or k.endswith(".self_attn.v_proj.weight" ) ): SCREAMING_SNAKE_CASE_: str = k[: -len(".q_proj.weight" )] SCREAMING_SNAKE_CASE_: Dict = k[-len("q_proj.weight" )] if k_pre not in capture_qkv_weight: SCREAMING_SNAKE_CASE_: Tuple = [None, None, None] SCREAMING_SNAKE_CASE_: Union[str, Any] = v continue if ( k.endswith(".self_attn.q_proj.bias" ) or k.endswith(".self_attn.k_proj.bias" ) or k.endswith(".self_attn.v_proj.bias" ) ): SCREAMING_SNAKE_CASE_: Union[str, Any] = k[: -len(".q_proj.bias" )] SCREAMING_SNAKE_CASE_: Any = k[-len("q_proj.bias" )] if k_pre not in capture_qkv_bias: SCREAMING_SNAKE_CASE_: List[Any] = [None, None, None] SCREAMING_SNAKE_CASE_: List[str] = v continue SCREAMING_SNAKE_CASE_: int = textenc_pattern.sub(lambda _UpperCAmelCase : protected[re.escape(m.group(0 ) )] , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Dict = v for k_pre, tensors in capture_qkv_weight.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) SCREAMING_SNAKE_CASE_: str = textenc_pattern.sub(lambda _UpperCAmelCase : protected[re.escape(m.group(0 ) )] , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: int = torch.cat(_UpperCAmelCase ) for k_pre, tensors in capture_qkv_bias.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) SCREAMING_SNAKE_CASE_: Optional[int] = textenc_pattern.sub(lambda _UpperCAmelCase : protected[re.escape(m.group(0 ) )] , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] = torch.cat(_UpperCAmelCase ) return new_state_dict def A_ ( _UpperCAmelCase ): return text_enc_dict if __name__ == "__main__": lowerCAmelCase : int = argparse.ArgumentParser() parser.add_argument("""--model_path""", default=None, type=str, required=True, help="""Path to the model to convert.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, required=True, help="""Path to the output model.""") parser.add_argument("""--half""", action="""store_true""", help="""Save weights in half precision.""") parser.add_argument( """--use_safetensors""", action="""store_true""", help="""Save weights use safetensors, default is ckpt.""" ) lowerCAmelCase : Optional[Any] = parser.parse_args() assert args.model_path is not None, "Must provide a model path!" assert args.checkpoint_path is not None, "Must provide a checkpoint path!" # Path for safetensors lowerCAmelCase : int = osp.join(args.model_path, """unet""", """diffusion_pytorch_model.safetensors""") lowerCAmelCase : List[str] = osp.join(args.model_path, """vae""", """diffusion_pytorch_model.safetensors""") lowerCAmelCase : Optional[int] = osp.join(args.model_path, """text_encoder""", """model.safetensors""") # Load models from safetensors if it exists, if it doesn't pytorch if osp.exists(unet_path): lowerCAmelCase : Optional[int] = load_file(unet_path, device="""cpu""") else: lowerCAmelCase : Union[str, Any] = osp.join(args.model_path, """unet""", """diffusion_pytorch_model.bin""") lowerCAmelCase : Optional[Any] = torch.load(unet_path, map_location="""cpu""") if osp.exists(vae_path): lowerCAmelCase : str = load_file(vae_path, device="""cpu""") else: lowerCAmelCase : List[Any] = osp.join(args.model_path, """vae""", """diffusion_pytorch_model.bin""") lowerCAmelCase : Optional[Any] = torch.load(vae_path, map_location="""cpu""") if osp.exists(text_enc_path): lowerCAmelCase : List[Any] = load_file(text_enc_path, device="""cpu""") else: lowerCAmelCase : List[Any] = osp.join(args.model_path, """text_encoder""", """pytorch_model.bin""") lowerCAmelCase : Optional[Any] = torch.load(text_enc_path, map_location="""cpu""") # Convert the UNet model lowerCAmelCase : int = convert_unet_state_dict(unet_state_dict) lowerCAmelCase : Optional[int] = {"""model.diffusion_model.""" + k: v for k, v in unet_state_dict.items()} # Convert the VAE model lowerCAmelCase : Union[str, Any] = convert_vae_state_dict(vae_state_dict) lowerCAmelCase : Optional[int] = {"""first_stage_model.""" + k: v for k, v in vae_state_dict.items()} # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper lowerCAmelCase : Any = """text_model.encoder.layers.22.layer_norm2.bias""" in text_enc_dict if is_vaa_model: # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm lowerCAmelCase : Any = {"""transformer.""" + k: v for k, v in text_enc_dict.items()} lowerCAmelCase : str = convert_text_enc_state_dict_vaa(text_enc_dict) lowerCAmelCase : Dict = {"""cond_stage_model.model.""" + k: v for k, v in text_enc_dict.items()} else: lowerCAmelCase : Any = convert_text_enc_state_dict(text_enc_dict) lowerCAmelCase : Optional[Any] = {"""cond_stage_model.transformer.""" + k: v for k, v in text_enc_dict.items()} # Put together new checkpoint lowerCAmelCase : Union[str, Any] = {**unet_state_dict, **vae_state_dict, **text_enc_dict} if args.half: lowerCAmelCase : str = {k: v.half() for k, v in state_dict.items()} if args.use_safetensors: save_file(state_dict, args.checkpoint_path) else: lowerCAmelCase : int = {"""state_dict""": state_dict} torch.save(state_dict, args.checkpoint_path)
671
0
'''simple docstring''' from math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter def _a (lowercase__ : int , lowercase__ : int , lowercase__ : float = 1 / sqrt(2 ) ) -> IIRFilter: """simple docstring""" __snake_case = tau * frequency / samplerate __snake_case = sin(lowercase__ ) __snake_case = cos(lowercase__ ) __snake_case = _sin / (2 * q_factor) __snake_case = (1 - _cos) / 2 __snake_case = 1 - _cos __snake_case = 1 + alpha __snake_case = -2 * _cos __snake_case = 1 - alpha __snake_case = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _a (lowercase__ : int , lowercase__ : int , lowercase__ : float = 1 / sqrt(2 ) ) -> IIRFilter: """simple docstring""" __snake_case = tau * frequency / samplerate __snake_case = sin(lowercase__ ) __snake_case = cos(lowercase__ ) __snake_case = _sin / (2 * q_factor) __snake_case = (1 + _cos) / 2 __snake_case = -1 - _cos __snake_case = 1 + alpha __snake_case = -2 * _cos __snake_case = 1 - alpha __snake_case = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _a (lowercase__ : int , lowercase__ : int , lowercase__ : float = 1 / sqrt(2 ) ) -> IIRFilter: """simple docstring""" __snake_case = tau * frequency / samplerate __snake_case = sin(lowercase__ ) __snake_case = cos(lowercase__ ) __snake_case = _sin / (2 * q_factor) __snake_case = _sin / 2 __snake_case = 0 __snake_case = -ba __snake_case = 1 + alpha __snake_case = -2 * _cos __snake_case = 1 - alpha __snake_case = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _a (lowercase__ : int , lowercase__ : int , lowercase__ : float = 1 / sqrt(2 ) ) -> IIRFilter: """simple docstring""" __snake_case = tau * frequency / samplerate __snake_case = sin(lowercase__ ) __snake_case = cos(lowercase__ ) __snake_case = _sin / (2 * q_factor) __snake_case = 1 - alpha __snake_case = -2 * _cos __snake_case = 1 + alpha __snake_case = IIRFilter(2 ) filt.set_coefficients([ba, ba, ba] , [ba, ba, ba] ) return filt def _a (lowercase__ : int , lowercase__ : int , lowercase__ : float , lowercase__ : float = 1 / sqrt(2 ) , ) -> IIRFilter: """simple docstring""" __snake_case = tau * frequency / samplerate __snake_case = sin(lowercase__ ) __snake_case = cos(lowercase__ ) __snake_case = _sin / (2 * q_factor) __snake_case = 1_0 ** (gain_db / 4_0) __snake_case = 1 + alpha * big_a __snake_case = -2 * _cos __snake_case = 1 - alpha * big_a __snake_case = 1 + alpha / big_a __snake_case = -2 * _cos __snake_case = 1 - alpha / big_a __snake_case = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _a (lowercase__ : int , lowercase__ : int , lowercase__ : float , lowercase__ : float = 1 / sqrt(2 ) , ) -> IIRFilter: """simple docstring""" __snake_case = tau * frequency / samplerate __snake_case = sin(lowercase__ ) __snake_case = cos(lowercase__ ) __snake_case = _sin / (2 * q_factor) __snake_case = 1_0 ** (gain_db / 4_0) __snake_case = (big_a + 1) - (big_a - 1) * _cos __snake_case = (big_a + 1) + (big_a - 1) * _cos __snake_case = (big_a - 1) - (big_a + 1) * _cos __snake_case = (big_a - 1) + (big_a + 1) * _cos __snake_case = 2 * sqrt(lowercase__ ) * alpha __snake_case = big_a * (pmc + aaa) __snake_case = 2 * big_a * mpc __snake_case = big_a * (pmc - aaa) __snake_case = ppmc + aaa __snake_case = -2 * pmpc __snake_case = ppmc - aaa __snake_case = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _a (lowercase__ : int , lowercase__ : int , lowercase__ : float , lowercase__ : float = 1 / sqrt(2 ) , ) -> IIRFilter: """simple docstring""" __snake_case = tau * frequency / samplerate __snake_case = sin(lowercase__ ) __snake_case = cos(lowercase__ ) __snake_case = _sin / (2 * q_factor) __snake_case = 1_0 ** (gain_db / 4_0) __snake_case = (big_a + 1) - (big_a - 1) * _cos __snake_case = (big_a + 1) + (big_a - 1) * _cos __snake_case = (big_a - 1) - (big_a + 1) * _cos __snake_case = (big_a - 1) + (big_a + 1) * _cos __snake_case = 2 * sqrt(lowercase__ ) * alpha __snake_case = big_a * (ppmc + aaa) __snake_case = -2 * big_a * pmpc __snake_case = big_a * (ppmc - aaa) __snake_case = pmc + aaa __snake_case = 2 * mpc __snake_case = pmc - aaa __snake_case = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt
56
from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase : int = logging.get_logger(__name__) lowerCAmelCase : Dict = { """microsoft/xprophetnet-large-wiki100-cased""": ( """https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json""" ), } class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : Optional[Any] = '''xlm-prophetnet''' _UpperCAmelCase : Any = ['''past_key_values'''] _UpperCAmelCase : Tuple = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self : str , lowerCAmelCase__ : Optional[float] = 0.1 , lowerCAmelCase__ : Optional[Union[str, Callable]] = "gelu" , lowerCAmelCase__ : Optional[int] = 3_0522 , lowerCAmelCase__ : Optional[int] = 1024 , lowerCAmelCase__ : Optional[int] = 4096 , lowerCAmelCase__ : Optional[int] = 12 , lowerCAmelCase__ : Optional[int] = 16 , lowerCAmelCase__ : Optional[int] = 4096 , lowerCAmelCase__ : Optional[int] = 12 , lowerCAmelCase__ : Optional[int] = 16 , lowerCAmelCase__ : Optional[float] = 0.1 , lowerCAmelCase__ : Optional[float] = 0.1 , lowerCAmelCase__ : Optional[int] = 512 , lowerCAmelCase__ : Optional[float] = 0.02 , lowerCAmelCase__ : Optional[bool] = True , lowerCAmelCase__ : Optional[bool] = True , lowerCAmelCase__ : Optional[int] = 0 , lowerCAmelCase__ : Optional[int] = 2 , lowerCAmelCase__ : Optional[int] = 32 , lowerCAmelCase__ : Optional[int] = 128 , lowerCAmelCase__ : Optional[bool] = False , lowerCAmelCase__ : Optional[float] = 0.0 , lowerCAmelCase__ : Optional[bool] = True , lowerCAmelCase__ : Optional[int] = 0 , lowerCAmelCase__ : Optional[int] = 1 , lowerCAmelCase__ : Optional[int] = 2 , **lowerCAmelCase__ : List[str] , ): SCREAMING_SNAKE_CASE_: List[Any] = vocab_size SCREAMING_SNAKE_CASE_: int = hidden_size SCREAMING_SNAKE_CASE_: Any = encoder_ffn_dim SCREAMING_SNAKE_CASE_: Tuple = num_encoder_layers SCREAMING_SNAKE_CASE_: List[Any] = num_encoder_attention_heads SCREAMING_SNAKE_CASE_: Dict = decoder_ffn_dim SCREAMING_SNAKE_CASE_: Any = num_decoder_layers SCREAMING_SNAKE_CASE_: Tuple = num_decoder_attention_heads SCREAMING_SNAKE_CASE_: str = max_position_embeddings SCREAMING_SNAKE_CASE_: str = init_std # Normal(0, this parameter) SCREAMING_SNAKE_CASE_: Dict = activation_function # parameters for xlmprophetnet SCREAMING_SNAKE_CASE_: Optional[int] = ngram SCREAMING_SNAKE_CASE_: Tuple = num_buckets SCREAMING_SNAKE_CASE_: Union[str, Any] = relative_max_distance SCREAMING_SNAKE_CASE_: List[str] = disable_ngram_loss SCREAMING_SNAKE_CASE_: Dict = eps # 3 Types of Dropout SCREAMING_SNAKE_CASE_: Any = attention_dropout SCREAMING_SNAKE_CASE_: Optional[int] = activation_dropout SCREAMING_SNAKE_CASE_: str = dropout SCREAMING_SNAKE_CASE_: Optional[int] = use_cache super().__init__( pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , is_encoder_decoder=lowerCAmelCase__ , add_cross_attention=lowerCAmelCase__ , decoder_start_token_id=lowerCAmelCase__ , **lowerCAmelCase__ , ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def _SCREAMING_SNAKE_CASE ( self : int , lowerCAmelCase__ : Any): raise NotImplementedError( "This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and" " `num_decoder_layers`.")
671
0
import gc import unittest from diffusers import FlaxControlNetModel, FlaxStableDiffusionControlNetPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" def _a ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() def _a ( self ): UpperCamelCase_ ,UpperCamelCase_: str = FlaxControlNetModel.from_pretrained( 'lllyasviel/sd-controlnet-canny' , from_pt=_lowerCamelCase , dtype=jnp.bfloataa ) UpperCamelCase_ ,UpperCamelCase_: List[str] = FlaxStableDiffusionControlNetPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , controlnet=_lowerCamelCase , from_pt=_lowerCamelCase , dtype=jnp.bfloataa ) UpperCamelCase_: List[str] = controlnet_params UpperCamelCase_: Any = 'bird' UpperCamelCase_: Optional[int] = jax.device_count() UpperCamelCase_: str = pipe.prepare_text_inputs([prompts] * num_samples ) UpperCamelCase_: List[str] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png' ) UpperCamelCase_: Union[str, Any] = pipe.prepare_image_inputs([canny_image] * num_samples ) UpperCamelCase_: Tuple = jax.random.PRNGKey(0 ) UpperCamelCase_: Optional[Any] = jax.random.split(_lowerCamelCase , jax.device_count() ) UpperCamelCase_: Optional[Any] = replicate(_lowerCamelCase ) UpperCamelCase_: List[Any] = shard(_lowerCamelCase ) UpperCamelCase_: List[Any] = shard(_lowerCamelCase ) UpperCamelCase_: Tuple = pipe( prompt_ids=_lowerCamelCase , image=_lowerCamelCase , params=_lowerCamelCase , prng_seed=_lowerCamelCase , num_inference_steps=5_0 , jit=_lowerCamelCase , ).images assert images.shape == (jax.device_count(), 1, 7_6_8, 5_1_2, 3) UpperCamelCase_: Dict = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) UpperCamelCase_: str = images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] UpperCamelCase_: int = jnp.asarray(jax.device_get(image_slice.flatten() ) ) UpperCamelCase_: Any = jnp.array( [0.1_6_7_9_6_9, 0.1_1_6_6_9_9, 0.0_8_1_5_4_3, 0.1_5_4_2_9_7, 0.1_3_2_8_1_2, 0.1_0_8_8_8_7, 0.1_6_9_9_2_2, 0.1_6_9_9_2_2, 0.2_0_5_0_7_8] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2 def _a ( self ): UpperCamelCase_ ,UpperCamelCase_: int = FlaxControlNetModel.from_pretrained( 'lllyasviel/sd-controlnet-openpose' , from_pt=_lowerCamelCase , dtype=jnp.bfloataa ) UpperCamelCase_ ,UpperCamelCase_: List[str] = FlaxStableDiffusionControlNetPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , controlnet=_lowerCamelCase , from_pt=_lowerCamelCase , dtype=jnp.bfloataa ) UpperCamelCase_: str = controlnet_params UpperCamelCase_: Any = 'Chef in the kitchen' UpperCamelCase_: Any = jax.device_count() UpperCamelCase_: List[str] = pipe.prepare_text_inputs([prompts] * num_samples ) UpperCamelCase_: List[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/pose.png' ) UpperCamelCase_: Any = pipe.prepare_image_inputs([pose_image] * num_samples ) UpperCamelCase_: Optional[Any] = jax.random.PRNGKey(0 ) UpperCamelCase_: List[str] = jax.random.split(_lowerCamelCase , jax.device_count() ) UpperCamelCase_: Union[str, Any] = replicate(_lowerCamelCase ) UpperCamelCase_: List[str] = shard(_lowerCamelCase ) UpperCamelCase_: List[str] = shard(_lowerCamelCase ) UpperCamelCase_: List[Any] = pipe( prompt_ids=_lowerCamelCase , image=_lowerCamelCase , params=_lowerCamelCase , prng_seed=_lowerCamelCase , num_inference_steps=5_0 , jit=_lowerCamelCase , ).images assert images.shape == (jax.device_count(), 1, 7_6_8, 5_1_2, 3) UpperCamelCase_: Any = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) UpperCamelCase_: Optional[int] = images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] UpperCamelCase_: str = jnp.asarray(jax.device_get(image_slice.flatten() ) ) UpperCamelCase_: Any = jnp.array( [[0.2_7_1_4_8_4, 0.2_6_1_7_1_9, 0.2_7_5_3_9_1, 0.2_7_7_3_4_4, 0.2_7_9_2_9_7, 0.2_9_1_0_1_6, 0.2_9_4_9_2_2, 0.3_0_2_7_3_4, 0.3_0_2_7_3_4]] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
57
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL lowerCAmelCase : Dict = logging.get_logger(__name__) def A_ ( _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[int] = b.T SCREAMING_SNAKE_CASE_: Dict = np.sum(np.square(_UpperCAmelCase ) , axis=1 ) SCREAMING_SNAKE_CASE_: Tuple = np.sum(np.square(_UpperCAmelCase ) , axis=0 ) SCREAMING_SNAKE_CASE_: List[Any] = np.matmul(_UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Dict = aa[:, None] - 2 * ab + ba[None, :] return d def A_ ( _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: int = x.reshape(-1 , 3 ) SCREAMING_SNAKE_CASE_: Tuple = squared_euclidean_distance(_UpperCAmelCase , _UpperCAmelCase ) return np.argmin(_UpperCAmelCase , axis=1 ) class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : int = ['''pixel_values'''] def __init__( self : Tuple , lowerCAmelCase__ : Optional[Union[List[List[int]], np.ndarray]] = None , lowerCAmelCase__ : bool = True , lowerCAmelCase__ : Dict[str, int] = None , lowerCAmelCase__ : PILImageResampling = PILImageResampling.BILINEAR , lowerCAmelCase__ : bool = True , lowerCAmelCase__ : bool = True , **lowerCAmelCase__ : List[str] , ): super().__init__(**lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Any = size if size is not None else {"height": 256, "width": 256} SCREAMING_SNAKE_CASE_: Tuple = get_size_dict(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Tuple = np.array(lowerCAmelCase__) if clusters is not None else None SCREAMING_SNAKE_CASE_: Dict = do_resize SCREAMING_SNAKE_CASE_: str = size SCREAMING_SNAKE_CASE_: List[Any] = resample SCREAMING_SNAKE_CASE_: Optional[int] = do_normalize SCREAMING_SNAKE_CASE_: Dict = do_color_quantize def _SCREAMING_SNAKE_CASE ( self : List[str] , lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : Dict[str, int] , lowerCAmelCase__ : PILImageResampling = PILImageResampling.BILINEAR , lowerCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **lowerCAmelCase__ : Optional[Any] , ): SCREAMING_SNAKE_CASE_: List[str] = get_size_dict(lowerCAmelCase__) if "height" not in size or "width" not in size: raise ValueError(F"Size dictionary must contain both height and width keys. Got {size.keys()}") return resize( lowerCAmelCase__ , size=(size["height"], size["width"]) , resample=lowerCAmelCase__ , data_format=lowerCAmelCase__ , **lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , ): SCREAMING_SNAKE_CASE_: str = rescale(image=lowerCAmelCase__ , scale=1 / 127.5 , data_format=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Optional[int] = image - 1 return image def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase__ : ImageInput , lowerCAmelCase__ : bool = None , lowerCAmelCase__ : Dict[str, int] = None , lowerCAmelCase__ : PILImageResampling = None , lowerCAmelCase__ : bool = None , lowerCAmelCase__ : Optional[bool] = None , lowerCAmelCase__ : Optional[Union[List[List[int]], np.ndarray]] = None , lowerCAmelCase__ : Optional[Union[str, TensorType]] = None , lowerCAmelCase__ : Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST , **lowerCAmelCase__ : Union[str, Any] , ): SCREAMING_SNAKE_CASE_: Tuple = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE_: Optional[int] = size if size is not None else self.size SCREAMING_SNAKE_CASE_: Dict = get_size_dict(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[str] = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE_: int = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE_: List[str] = do_color_quantize if do_color_quantize is not None else self.do_color_quantize SCREAMING_SNAKE_CASE_: Tuple = clusters if clusters is not None else self.clusters SCREAMING_SNAKE_CASE_: Optional[int] = np.array(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Optional[int] = make_list_of_images(lowerCAmelCase__) if not valid_images(lowerCAmelCase__): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray.") if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True.") if do_color_quantize and clusters is None: raise ValueError("Clusters must be specified if do_color_quantize is True.") # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE_: Union[str, Any] = [to_numpy_array(lowerCAmelCase__) for image in images] if do_resize: SCREAMING_SNAKE_CASE_: Optional[Any] = [self.resize(image=lowerCAmelCase__ , size=lowerCAmelCase__ , resample=lowerCAmelCase__) for image in images] if do_normalize: SCREAMING_SNAKE_CASE_: str = [self.normalize(image=lowerCAmelCase__) for image in images] if do_color_quantize: SCREAMING_SNAKE_CASE_: Any = [to_channel_dimension_format(lowerCAmelCase__ , ChannelDimension.LAST) for image in images] # color quantize from (batch_size, height, width, 3) to (batch_size, height, width) SCREAMING_SNAKE_CASE_: List[Any] = np.array(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[str] = color_quantize(lowerCAmelCase__ , lowerCAmelCase__).reshape(images.shape[:-1]) # flatten to (batch_size, height*width) SCREAMING_SNAKE_CASE_: str = images.shape[0] SCREAMING_SNAKE_CASE_: Tuple = images.reshape(lowerCAmelCase__ , -1) # We need to convert back to a list of images to keep consistent behaviour across processors. SCREAMING_SNAKE_CASE_: str = list(lowerCAmelCase__) else: SCREAMING_SNAKE_CASE_: Dict = [to_channel_dimension_format(lowerCAmelCase__ , lowerCAmelCase__) for image in images] SCREAMING_SNAKE_CASE_: Optional[Any] = {"input_ids": images} return BatchFeature(data=lowerCAmelCase__ , tensor_type=lowerCAmelCase__)
671
0
"""simple docstring""" from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features from .utils import DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor from .xnli import xnli_output_modes, xnli_processors, xnli_tasks_num_labels
58
import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert import BertTokenizer lowerCAmelCase : Optional[int] = logging.get_logger(__name__) lowerCAmelCase : str = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} lowerCAmelCase : Tuple = { """vocab_file""": { """facebook/dpr-ctx_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt""" ), """facebook/dpr-ctx_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """facebook/dpr-ctx_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json""" ), """facebook/dpr-ctx_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json""" ), }, } lowerCAmelCase : Union[str, Any] = { """vocab_file""": { """facebook/dpr-question_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt""" ), """facebook/dpr-question_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """facebook/dpr-question_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json""" ), """facebook/dpr-question_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json""" ), }, } lowerCAmelCase : List[str] = { """vocab_file""": { """facebook/dpr-reader-single-nq-base""": ( """https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt""" ), """facebook/dpr-reader-multiset-base""": ( """https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """facebook/dpr-reader-single-nq-base""": ( """https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json""" ), """facebook/dpr-reader-multiset-base""": ( """https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json""" ), }, } lowerCAmelCase : int = { """facebook/dpr-ctx_encoder-single-nq-base""": 512, """facebook/dpr-ctx_encoder-multiset-base""": 512, } lowerCAmelCase : int = { """facebook/dpr-question_encoder-single-nq-base""": 512, """facebook/dpr-question_encoder-multiset-base""": 512, } lowerCAmelCase : List[Any] = { """facebook/dpr-reader-single-nq-base""": 512, """facebook/dpr-reader-multiset-base""": 512, } lowerCAmelCase : Optional[int] = { """facebook/dpr-ctx_encoder-single-nq-base""": {"""do_lower_case""": True}, """facebook/dpr-ctx_encoder-multiset-base""": {"""do_lower_case""": True}, } lowerCAmelCase : Optional[int] = { """facebook/dpr-question_encoder-single-nq-base""": {"""do_lower_case""": True}, """facebook/dpr-question_encoder-multiset-base""": {"""do_lower_case""": True}, } lowerCAmelCase : List[str] = { """facebook/dpr-reader-single-nq-base""": {"""do_lower_case""": True}, """facebook/dpr-reader-multiset-base""": {"""do_lower_case""": True}, } class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : Any = VOCAB_FILES_NAMES _UpperCAmelCase : Optional[Any] = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : List[Any] = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : List[Any] = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : Union[str, Any] = VOCAB_FILES_NAMES _UpperCAmelCase : Optional[int] = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Any = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : str = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION lowerCAmelCase : List[Any] = collections.namedtuple( """DPRSpanPrediction""", ["""span_score""", """relevance_score""", """doc_id""", """start_index""", """end_index""", """text"""] ) lowerCAmelCase : Optional[Any] = collections.namedtuple("""DPRReaderOutput""", ["""start_logits""", """end_logits""", """relevance_logits"""]) lowerCAmelCase : int = R""" Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`. It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers), using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)` with the format: ``` [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids> ``` Args: questions (`str` or `List[str]`): The questions to be encoded. You can specify one question for many passages. In this case, the question will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in `titles` or `texts`. titles (`str` or `List[str]`): The passages titles to be encoded. This can be a string or a list of strings if there are several passages. texts (`str` or `List[str]`): The passages texts to be encoded. This can be a string or a list of strings if there are several passages. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`): Activates and controls padding. Accepts the following values: - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different lengths). truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`): Activates and controls truncation. Accepts the following values: - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided. - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size). max_length (`int`, *optional*): Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length is required by one of the truncation/padding parameters. If the model has no specific maximum input length (like XLNet) truncation/padding to a maximum length will be deactivated. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors instead of list of python integers. Acceptable values are: - `'tf'`: Return TensorFlow `tf.constant` objects. - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return Numpy `np.ndarray` objects. return_attention_mask (`bool`, *optional*): Whether or not to return the attention mask. If not set, will return the attention mask according to the specific tokenizer's default, defined by the `return_outputs` attribute. [What are attention masks?](../glossary#attention-mask) Returns: `Dict[str, List[List[int]]]`: A dictionary with the following keys: - `input_ids`: List of token ids to be fed to a model. - `attention_mask`: List of indices specifying which tokens should be attended to by the model. """ @add_start_docstrings(UpperCAmelCase_ ) class __lowercase : """simple docstring""" def __call__( self : List[Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : Optional[str] = None , lowerCAmelCase__ : Optional[str] = None , lowerCAmelCase__ : Union[bool, str] = False , lowerCAmelCase__ : Union[bool, str] = False , lowerCAmelCase__ : Optional[int] = None , lowerCAmelCase__ : Optional[Union[str, TensorType]] = None , lowerCAmelCase__ : Optional[bool] = None , **lowerCAmelCase__ : Tuple , ): if titles is None and texts is None: return super().__call__( lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , max_length=lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , **lowerCAmelCase__ , ) elif titles is None or texts is None: SCREAMING_SNAKE_CASE_: List[str] = titles if texts is None else texts return super().__call__( lowerCAmelCase__ , lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , max_length=lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , **lowerCAmelCase__ , ) SCREAMING_SNAKE_CASE_: Optional[int] = titles if not isinstance(lowerCAmelCase__ , lowerCAmelCase__) else [titles] SCREAMING_SNAKE_CASE_: int = texts if not isinstance(lowerCAmelCase__ , lowerCAmelCase__) else [texts] SCREAMING_SNAKE_CASE_: str = len(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Tuple = questions if not isinstance(lowerCAmelCase__ , lowerCAmelCase__) else [questions] * n_passages if len(lowerCAmelCase__) != len(lowerCAmelCase__): raise ValueError( F"There should be as many titles than texts but got {len(lowerCAmelCase__)} titles and {len(lowerCAmelCase__)} texts.") SCREAMING_SNAKE_CASE_: Optional[Any] = super().__call__(lowerCAmelCase__ , lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__)["input_ids"] SCREAMING_SNAKE_CASE_: Union[str, Any] = super().__call__(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__)["input_ids"] SCREAMING_SNAKE_CASE_: int = { "input_ids": [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(lowerCAmelCase__ , lowerCAmelCase__) ] } if return_attention_mask is not False: SCREAMING_SNAKE_CASE_: Dict = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id) for input_id in input_ids]) SCREAMING_SNAKE_CASE_: int = attention_mask return self.pad(lowerCAmelCase__ , padding=lowerCAmelCase__ , max_length=lowerCAmelCase__ , return_tensors=lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Any , lowerCAmelCase__ : BatchEncoding , lowerCAmelCase__ : DPRReaderOutput , lowerCAmelCase__ : int = 16 , lowerCAmelCase__ : int = 64 , lowerCAmelCase__ : int = 4 , ): SCREAMING_SNAKE_CASE_: int = reader_input["input_ids"] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: int = reader_output[:3] SCREAMING_SNAKE_CASE_: Tuple = len(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Union[str, Any] = sorted(range(lowerCAmelCase__) , reverse=lowerCAmelCase__ , key=relevance_logits.__getitem__) SCREAMING_SNAKE_CASE_: List[DPRReaderOutput] = [] for doc_id in sorted_docs: SCREAMING_SNAKE_CASE_: Optional[int] = list(input_ids[doc_id]) # assuming question & title information is at the beginning of the sequence SCREAMING_SNAKE_CASE_: str = sequence_ids.index(self.sep_token_id , 2) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: SCREAMING_SNAKE_CASE_: List[Any] = sequence_ids.index(self.pad_token_id) else: SCREAMING_SNAKE_CASE_: Dict = len(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Optional[Any] = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=lowerCAmelCase__ , top_spans=lowerCAmelCase__ , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=lowerCAmelCase__ , start_index=lowerCAmelCase__ , end_index=lowerCAmelCase__ , text=self.decode(sequence_ids[start_index : end_index + 1]) , )) if len(lowerCAmelCase__) >= num_spans: break return nbest_spans_predictions[:num_spans] def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase__ : List[int] , lowerCAmelCase__ : List[int] , lowerCAmelCase__ : int , lowerCAmelCase__ : int , ): SCREAMING_SNAKE_CASE_: Any = [] for start_index, start_score in enumerate(lowerCAmelCase__): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length]): scores.append(((start_index, start_index + answer_length), start_score + end_score)) SCREAMING_SNAKE_CASE_: Union[str, Any] = sorted(lowerCAmelCase__ , key=lambda lowerCAmelCase__: x[1] , reverse=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[str] = [] for (start_index, end_index), score in scores: if start_index > end_index: raise ValueError(F"Wrong span indices: [{start_index}:{end_index}]") SCREAMING_SNAKE_CASE_: int = end_index - start_index + 1 if length > max_answer_length: raise ValueError(F"Span is too long: {length} > {max_answer_length}") if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals): continue chosen_span_intervals.append((start_index, end_index)) if len(lowerCAmelCase__) == top_spans: break return chosen_span_intervals @add_end_docstrings(UpperCAmelCase_ ) class __lowercase ( UpperCAmelCase_ , UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : Any = VOCAB_FILES_NAMES _UpperCAmelCase : Optional[Any] = READER_PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : int = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : Optional[int] = READER_PRETRAINED_INIT_CONFIGURATION _UpperCAmelCase : str = ['''input_ids''', '''attention_mask''']
671
0
from __future__ import annotations from collections.abc import Callable from typing import Any, Generic, TypeVar __A = TypeVar("T") class _SCREAMING_SNAKE_CASE ( Generic[T] ): '''simple docstring''' def __init__(self : Optional[Any] , UpperCAmelCase_ : list[T] , UpperCAmelCase_ : Callable[[T, T], T]) ->None: '''simple docstring''' lowerCamelCase__: Any | T =None lowerCamelCase__: int =len(UpperCAmelCase_) lowerCamelCase__: list[T] =[any_type for _ in range(self.N)] + arr lowerCamelCase__: Optional[int] =fnc self.build() def SCREAMING_SNAKE_CASE_ (self : int) ->None: '''simple docstring''' for p in range(self.N - 1 , 0 , -1): lowerCamelCase__: Union[str, Any] =self.fn(self.st[p * 2] , self.st[p * 2 + 1]) def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : T) ->None: '''simple docstring''' p += self.N lowerCamelCase__: Any =v while p > 1: lowerCamelCase__: int =p // 2 lowerCamelCase__: List[str] =self.fn(self.st[p * 2] , self.st[p * 2 + 1]) def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : int , UpperCAmelCase_ : int) ->T | None: # noqa: E741 '''simple docstring''' lowerCamelCase__ , lowerCamelCase__: List[str] =l + self.N, r + self.N lowerCamelCase__: T | None =None while l <= r: if l % 2 == 1: lowerCamelCase__: Optional[Any] =self.st[l] if res is None else self.fn(UpperCAmelCase_ , self.st[l]) if r % 2 == 0: lowerCamelCase__: int =self.st[r] if res is None else self.fn(UpperCAmelCase_ , self.st[r]) lowerCamelCase__ , lowerCamelCase__: str =(l + 1) // 2, (r - 1) // 2 return res if __name__ == "__main__": from functools import reduce __A = [1, 10, -2, 9, -3, 8, 4, -7, 5, 6, 11, -12] __A = { 0: 7, 1: 2, 2: 6, 3: -14, 4: 5, 5: 4, 6: 7, 7: -10, 8: 9, 9: 10, 10: 12, 11: 1, } __A = SegmentTree(test_array, min) __A = SegmentTree(test_array, max) __A = SegmentTree(test_array, lambda a, b: a + b) def lowerCAmelCase_ ( ) -> None: """simple docstring""" for i in range(len(__a ) ): for j in range(__a , len(__a ) ): lowerCamelCase__: str =reduce(__a , test_array[i : j + 1] ) lowerCamelCase__: Optional[Any] =reduce(__a , test_array[i : j + 1] ) lowerCamelCase__: Optional[Any] =reduce(lambda __a , __a : a + b , test_array[i : j + 1] ) assert min_range == min_segment_tree.query(__a , __a ) assert max_range == max_segment_tree.query(__a , __a ) assert sum_range == sum_segment_tree.query(__a , __a ) test_all_segments() for index, value in test_updates.items(): __A = value min_segment_tree.update(index, value) max_segment_tree.update(index, value) sum_segment_tree.update(index, value) test_all_segments()
59
from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : Optional[Any] = DistilBertTokenizer _UpperCAmelCase : Union[str, Any] = DistilBertTokenizerFast _UpperCAmelCase : int = True @slow def _SCREAMING_SNAKE_CASE ( self : Any): SCREAMING_SNAKE_CASE_: Optional[Any] = DistilBertTokenizer.from_pretrained("distilbert-base-uncased") SCREAMING_SNAKE_CASE_: Any = tokenizer.encode("sequence builders" , add_special_tokens=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[Any] = tokenizer.encode("multi-sequence build" , add_special_tokens=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Tuple = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: int = 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 ]
671
0
import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import MaMaaaTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from transformers.utils import is_sentencepiece_available if is_sentencepiece_available(): from transformers.models.mam_aaa.tokenization_mam_aaa import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin if is_sentencepiece_available(): lowerCAmelCase_ = get_tests_dir('''fixtures/test_sentencepiece.model''') if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right lowerCAmelCase_ = 1_2_8_0_2_2 lowerCAmelCase_ = 1_2_8_0_2_8 @require_sentencepiece class __lowerCAmelCase ( _a, unittest.TestCase ): lowerCamelCase_ : Any = MaMaaaTokenizer lowerCamelCase_ : Dict = False lowerCamelCase_ : Dict = False lowerCamelCase_ : Optional[Any] = True def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' super().setUp() snake_case_ : str = ['''</s>''', '''<unk>''', '''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''', '''\u0120''', '''<pad>'''] snake_case_ : Dict = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) ) snake_case_ : List[str] = Path(self.tmpdirname ) save_json(__magic_name__ , save_dir / VOCAB_FILES_NAMES['''vocab_file'''] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(__magic_name__ , save_dir / VOCAB_FILES_NAMES['''spm_file'''] ) snake_case_ : Dict = MaMaaaTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase (self , **__magic_name__ ) -> str: '''simple docstring''' return MaMaaaTokenizer.from_pretrained(self.tmpdirname , **__magic_name__ ) def lowerCamelCase (self , __magic_name__ ) -> Tuple: '''simple docstring''' return ( "This is a test", "This is a test", ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : str = '''</s>''' snake_case_ : List[str] = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__magic_name__ ) , __magic_name__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__magic_name__ ) , __magic_name__ ) def lowerCamelCase (self ) -> List[str]: '''simple docstring''' snake_case_ : Any = self.get_tokenizer() snake_case_ : List[Any] = list(tokenizer.get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''</s>''' ) self.assertEqual(vocab_keys[1] , '''<unk>''' ) self.assertEqual(vocab_keys[-1] , '''<s>''' ) self.assertEqual(len(__magic_name__ ) , tokenizer.vocab_size + len(tokenizer.get_added_vocab() ) ) @unittest.skip('''Skip this test while all models are still to be uploaded.''' ) def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' pass def lowerCamelCase (self ) -> Tuple: '''simple docstring''' snake_case_ : Union[str, Any] = self.get_tokenizer() snake_case_ : str = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(__magic_name__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__magic_name__ ) , [2, 3, 4, 5, 6] , ) snake_case_ : Tuple = tokenizer.convert_ids_to_tokens([2, 3, 4, 5, 6] ) self.assertListEqual(__magic_name__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) snake_case_ : Optional[int] = tokenizer.convert_tokens_to_string(__magic_name__ ) self.assertEqual(__magic_name__ , '''This is a test''' ) @slow def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Optional[int] = {'''input_ids''': [[12_8022, 11_0108, 397, 11, 3_8272, 2247, 12_4811, 285, 1_8105, 1586, 207, 7, 3_9534, 4428, 397, 1019, 1_8105, 1586, 207, 7, 4_1337, 1_6786, 241, 7, 2_0214, 17, 12_5690, 1_0398, 7, 4_4378, 5_8069, 6_8342, 7798, 7343, 11, 299, 3_3310, 4, 158, 3_7350, 9_4077, 4569, 299, 3_3310, 90, 4, 5_2840, 290, 4, 3_1270, 112, 299, 682, 4, 5_2840, 3_9953, 1_4079, 193, 5_2519, 9_0894, 1_7894, 12_0697, 11, 4_0445, 551, 17, 1019, 5_2519, 9_0894, 1_7756, 963, 11, 4_0445, 480, 17, 9792, 1120, 5173, 1393, 6240, 1_6786, 241, 12_0996, 28, 1245, 1393, 11_8240, 1_1123, 1019, 9_3612, 2691, 1_0618, 9_8058, 12_0409, 1928, 279, 4, 4_0683, 367, 178, 207, 1019, 103, 10_3121, 506, 6_5296, 5, 2], [12_8022, 2_1217, 367, 117, 12_5450, 128, 719, 7, 7308, 40, 9_3612, 1_2669, 1116, 1_6704, 71, 1_7785, 3699, 1_5592, 35, 144, 9584, 241, 1_1943, 713, 950, 799, 2247, 8_8427, 150, 149, 11_8813, 12_0706, 1019, 10_6906, 8_1518, 28, 1224, 2_2799, 397, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [12_8022, 1658, 12_3311, 5155, 5578, 4722, 279, 1_4947, 2366, 1120, 1197, 14, 1348, 9232, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], '''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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__magic_name__ , model_name='''facebook/m2m100_418M''' , revision='''c168bae485c864188cf9aa0e4108b0b6934dc91e''' , ) @require_torch @require_sentencepiece @require_tokenizers class __lowerCAmelCase ( unittest.TestCase ): lowerCamelCase_ : List[str] = '''facebook/m2m100_418M''' lowerCamelCase_ : List[Any] = [ '''In my opinion, there are two levels of response from the French government.''', '''NSA Affair Emphasizes Complete Lack of Debate on Intelligence''', ] lowerCamelCase_ : int = [ '''Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.''', '''L\'affaire NSA souligne l\'absence totale de débat sur le renseignement''', ] # fmt: off lowerCamelCase_ : Optional[int] = [EN_CODE, 593, 1_949, 115_781, 4, 71_586, 4_234, 60_633, 126_233, 432, 123_808, 15_592, 1_197, 117_132, 120_618, 5, 2] @classmethod def lowerCamelCase (cls ) -> Optional[int]: '''simple docstring''' snake_case_ : MaMaaaTokenizer = MaMaaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang='''en''' , tgt_lang='''fr''' ) snake_case_ : Union[str, Any] = 1 return cls def lowerCamelCase (self ) -> Dict: '''simple docstring''' self.assertEqual(self.tokenizer.get_lang_id('''ar''' ) , 12_8006 ) self.assertEqual(self.tokenizer.get_lang_id('''en''' ) , 12_8022 ) self.assertEqual(self.tokenizer.get_lang_id('''ro''' ) , 12_8076 ) self.assertEqual(self.tokenizer.get_lang_id('''mr''' ) , 12_8063 ) def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : List[Any] = self.tokenizer.get_vocab() self.assertEqual(len(__magic_name__ ) , self.tokenizer.vocab_size ) self.assertEqual(vocab['''<unk>'''] , 3 ) self.assertIn(self.tokenizer.get_lang_token('''en''' ) , __magic_name__ ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Optional[int] = '''en''' snake_case_ : Dict = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __magic_name__ ) def lowerCamelCase (self ) -> str: '''simple docstring''' self.assertIn(__magic_name__ , self.tokenizer.all_special_ids ) # fmt: off snake_case_ : Dict = [FR_CODE, 5364, 82, 8642, 4, 294, 47, 8, 1_4028, 136, 3286, 9706, 6, 9_0797, 6, 14_4012, 162, 8_8128, 3_0061, 5, 2] # fmt: on snake_case_ : Union[str, Any] = self.tokenizer.decode(__magic_name__ , skip_special_tokens=__magic_name__ ) snake_case_ : Any = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ ) self.assertNotIn(self.tokenizer.eos_token , __magic_name__ ) def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' snake_case_ : Tuple = tempfile.mkdtemp() snake_case_ : List[Any] = self.tokenizer.lang_token_to_id self.tokenizer.save_pretrained(__magic_name__ ) snake_case_ : Union[str, Any] = MaMaaaTokenizer.from_pretrained(__magic_name__ ) self.assertDictEqual(new_tok.lang_token_to_id , __magic_name__ ) @require_torch def lowerCamelCase (self ) -> List[str]: '''simple docstring''' snake_case_ : int = '''en''' snake_case_ : Union[str, Any] = '''fr''' snake_case_ : Any = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=__magic_name__ , return_tensors='''pt''' ) snake_case_ : Optional[Any] = shift_tokens_right( batch['''labels'''] , self.tokenizer.pad_token_id , self.tokenizer.eos_token_id ) for k in batch: snake_case_ : Union[str, Any] = batch[k].tolist() # batch = {k: v.tolist() for k,v in batch.items()} # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 # batch.decoder_inputs_ids[0][0] == assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == FR_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2] == [2, FR_CODE] @require_torch def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Optional[int] = '''mr''' self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''mr''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) snake_case_ : Optional[int] = '''zh''' self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''zh''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) @require_torch def lowerCamelCase (self ) -> Tuple: '''simple docstring''' snake_case_ : Dict = '''mr''' self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''mr''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) snake_case_ : Optional[int] = '''zh''' self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''zh''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) @require_torch def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Optional[Any] = self.tokenizer._build_translation_inputs('''A test''' , return_tensors='''pt''' , src_lang='''en''' , tgt_lang='''ar''' ) self.assertEqual( nested_simplify(__magic_name__ ) , { # en_XX, A, test, EOS '''input_ids''': [[12_8022, 58, 4183, 2]], '''attention_mask''': [[1, 1, 1, 1]], # ar_AR '''forced_bos_token_id''': 12_8006, } , )
60
import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient lowerCAmelCase : List[Any] = WebClient(token=os.environ["""CI_SLACK_BOT_TOKEN"""]) def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[int] = test_results.split(" " ) SCREAMING_SNAKE_CASE_: Tuple = 0 SCREAMING_SNAKE_CASE_: str = 0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. SCREAMING_SNAKE_CASE_: Optional[Any] = expressions[-2] if "=" in expressions[-1] else expressions[-1] for i, expression in enumerate(_UpperCAmelCase ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: str = {} SCREAMING_SNAKE_CASE_: Any = None SCREAMING_SNAKE_CASE_: Union[str, Any] = False for line in failures_short_lines.split("\n" ): if re.search(R"_ \[doctest\]" , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: List[Any] = True SCREAMING_SNAKE_CASE_: Dict = line.split(" " )[2] elif in_error and not line.split(" " )[0].isdigit(): SCREAMING_SNAKE_CASE_: Union[str, Any] = line SCREAMING_SNAKE_CASE_: List[str] = False return failures class __lowercase : """simple docstring""" def __init__( self : Any , lowerCAmelCase__ : str , lowerCAmelCase__ : Dict): SCREAMING_SNAKE_CASE_: Dict = title SCREAMING_SNAKE_CASE_: int = doc_test_results["time_spent"].split(",")[0] SCREAMING_SNAKE_CASE_: int = doc_test_results["success"] SCREAMING_SNAKE_CASE_: Optional[Any] = doc_test_results["failures"] SCREAMING_SNAKE_CASE_: Any = self.n_success + self.n_failures # Failures and success of the modeling tests SCREAMING_SNAKE_CASE_: Optional[int] = doc_test_results @property def _SCREAMING_SNAKE_CASE ( self : Any): SCREAMING_SNAKE_CASE_: int = [self._time_spent] SCREAMING_SNAKE_CASE_: List[Any] = 0 for time in time_spent: SCREAMING_SNAKE_CASE_: Union[str, Any] = time.split(":") # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(lowerCAmelCase__) == 1: SCREAMING_SNAKE_CASE_: Dict = [0, 0, time_parts[0]] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: int = int(time_parts[0]), int(time_parts[1]), float(time_parts[2]) total_secs += hours * 3600 + minutes * 60 + seconds SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: str = total_secs // 3600, (total_secs % 3600) // 60, total_secs % 60 return F"{int(lowerCAmelCase__)}h{int(lowerCAmelCase__)}m{int(lowerCAmelCase__)}s" @property def _SCREAMING_SNAKE_CASE ( self : List[Any]): return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): return { "type": "section", "text": { "type": "plain_text", "text": F"🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.", "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": F"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", }, } @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): return { "type": "section", "text": { "type": "plain_text", "text": ( F"There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in" F" {self.time}." ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": F"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", }, } @property def _SCREAMING_SNAKE_CASE ( self : Any): SCREAMING_SNAKE_CASE_: Optional[Any] = 40 SCREAMING_SNAKE_CASE_: List[str] = {k: v["failed"] for k, v in doc_test_results.items() if isinstance(lowerCAmelCase__ , lowerCAmelCase__)} SCREAMING_SNAKE_CASE_: Tuple = "" for category, failures in category_failures.items(): if len(lowerCAmelCase__) == 0: continue if report != "": report += "\n\n" report += F"*{category} failures*:".ljust(line_length // 2).rjust(line_length // 2) + "\n" report += "`" report += "`\n`".join(lowerCAmelCase__) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": F"The following examples had failures:\n\n\n{report}\n", }, } @property def _SCREAMING_SNAKE_CASE ( self : str): SCREAMING_SNAKE_CASE_: Optional[Any] = [self.header] if self.n_failures > 0: blocks.append(self.failures) if self.n_failures > 0: blocks.extend([self.category_failures]) if self.n_failures == 0: blocks.append(self.no_failures) return json.dumps(lowerCAmelCase__) @staticmethod def _SCREAMING_SNAKE_CASE ( ): SCREAMING_SNAKE_CASE_: List[str] = [ { "type": "section", "text": { "type": "plain_text", "text": "There was an issue running the tests.", }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": F"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", }, } ] print("Sending the following payload") print(json.dumps({"blocks": json.loads(lowerCAmelCase__)})) client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , text="There was an issue running the tests." , blocks=lowerCAmelCase__ , ) def _SCREAMING_SNAKE_CASE ( self : Tuple): print("Sending the following payload") print(json.dumps({"blocks": json.loads(self.payload)})) SCREAMING_SNAKE_CASE_: Optional[Any] = F"{self.n_failures} failures out of {self.n_tests} tests," if self.n_failures else "All tests passed." SCREAMING_SNAKE_CASE_: List[Any] = client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , blocks=self.payload , text=lowerCAmelCase__ , ) def _SCREAMING_SNAKE_CASE ( self : Dict , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any]): SCREAMING_SNAKE_CASE_: Dict = "" for key, value in failures.items(): SCREAMING_SNAKE_CASE_: str = value[:200] + " [Truncated]" if len(lowerCAmelCase__) > 250 else value failures_text += F"*{key}*\n_{value}_\n\n" SCREAMING_SNAKE_CASE_: Any = job_name SCREAMING_SNAKE_CASE_: List[Any] = {"type": "section", "text": {"type": "mrkdwn", "text": text}} if job_link is not None: SCREAMING_SNAKE_CASE_: Tuple = { "type": "button", "text": {"type": "plain_text", "text": "GitHub Action job", "emoji": True}, "url": job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def _SCREAMING_SNAKE_CASE ( self : Any): if self.thread_ts is None: raise ValueError("Can only post reply if a post has been made.") SCREAMING_SNAKE_CASE_: Tuple = self.doc_test_results.pop("job_link") self.doc_test_results.pop("failures") self.doc_test_results.pop("success") self.doc_test_results.pop("time_spent") SCREAMING_SNAKE_CASE_: Any = sorted(self.doc_test_results.items() , key=lambda lowerCAmelCase__: t[0]) for job, job_result in sorted_dict: if len(job_result["failures"]): SCREAMING_SNAKE_CASE_: Union[str, Any] = F"*Num failures* :{len(job_result['failed'])} \n" SCREAMING_SNAKE_CASE_: Optional[Any] = job_result["failures"] SCREAMING_SNAKE_CASE_: Optional[Any] = self.get_reply_blocks(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , text=lowerCAmelCase__) print("Sending the following reply") print(json.dumps({"blocks": blocks})) client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , text=F"Results for {job}" , blocks=lowerCAmelCase__ , thread_ts=self.thread_ts["ts"] , ) time.sleep(1) def A_ ( ): SCREAMING_SNAKE_CASE_: Tuple = os.environ["GITHUB_RUN_ID"] SCREAMING_SNAKE_CASE_: Any = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100" SCREAMING_SNAKE_CASE_: List[Any] = requests.get(_UpperCAmelCase ).json() SCREAMING_SNAKE_CASE_: Optional[Any] = {} try: jobs.update({job["name"]: job["html_url"] for job in result["jobs"]} ) SCREAMING_SNAKE_CASE_: Any = math.ceil((result["total_count"] - 1_00) / 1_00 ) for i in range(_UpperCAmelCase ): SCREAMING_SNAKE_CASE_: str = requests.get(url + f"&page={i + 2}" ).json() jobs.update({job["name"]: job["html_url"] for job in result["jobs"]} ) return jobs except Exception as e: print("Unknown error, could not fetch links." , _UpperCAmelCase ) return {} def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[Any] = {} if os.path.exists(_UpperCAmelCase ): SCREAMING_SNAKE_CASE_: List[str] = os.listdir(_UpperCAmelCase ) for file in files: try: with open(os.path.join(_UpperCAmelCase , _UpperCAmelCase ) , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE_: Dict = f.read() except UnicodeDecodeError as e: raise ValueError(f"Could not open {os.path.join(_UpperCAmelCase , _UpperCAmelCase )}." ) from e return _artifact def A_ ( ): class __lowercase : """simple docstring""" def __init__( self : List[str] , lowerCAmelCase__ : str): SCREAMING_SNAKE_CASE_: Dict = name SCREAMING_SNAKE_CASE_: List[str] = [] def __str__( self : Optional[Any]): return self.name def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase__ : str): self.paths.append({"name": self.name, "path": path}) SCREAMING_SNAKE_CASE_: Dict[str, Artifact] = {} SCREAMING_SNAKE_CASE_: List[Any] = filter(os.path.isdir , os.listdir() ) for directory in directories: SCREAMING_SNAKE_CASE_: Dict = directory if artifact_name not in _available_artifacts: SCREAMING_SNAKE_CASE_: Tuple = Artifact(_UpperCAmelCase ) _available_artifacts[artifact_name].add_path(_UpperCAmelCase ) return _available_artifacts if __name__ == "__main__": lowerCAmelCase : Tuple = get_job_links() lowerCAmelCase : Optional[Any] = retrieve_available_artifacts() lowerCAmelCase : Any = collections.OrderedDict( [ ("""*.py""", """API Examples"""), ("""*.md""", """MD Examples"""), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' lowerCAmelCase : int = { v: { """failed""": [], """failures""": {}, } for v in docs.values() } # Link to the GitHub Action job lowerCAmelCase : Optional[int] = github_actions_job_links.get("""run_doctests""") lowerCAmelCase : List[Any] = available_artifacts["""doc_tests_gpu_test_reports"""].paths[0] lowerCAmelCase : Any = retrieve_artifact(artifact_path["""name"""]) if "stats" in artifact: lowerCAmelCase , lowerCAmelCase , lowerCAmelCase : List[str] = handle_test_results(artifact["""stats"""]) lowerCAmelCase : List[str] = failed lowerCAmelCase : Any = success lowerCAmelCase : Dict = time_spent[1:-1] + """, """ lowerCAmelCase : str = extract_first_line_failure(artifact["""failures_short"""]) for line in artifact["summary_short"].split("""\n"""): if re.search("""FAILED""", line): lowerCAmelCase : Tuple = line.replace("""FAILED """, """""") lowerCAmelCase : str = line.split()[0].replace("""\n""", """""") if "::" in line: lowerCAmelCase , lowerCAmelCase : Optional[int] = line.split("""::""") else: lowerCAmelCase , lowerCAmelCase : str = line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): lowerCAmelCase : str = docs[file_regex] doc_test_results[category]["failed"].append(test) lowerCAmelCase : str = all_failures[test] if test in all_failures else """N/A""" lowerCAmelCase : Any = failure break lowerCAmelCase : Union[str, Any] = Message("""🤗 Results of the doc tests.""", doc_test_results) message.post() message.post_reply()
671
0
# NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works 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, )
61
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # and perform gradient accumulation # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## lowerCAmelCase : str = 16 lowerCAmelCase : List[Any] = 32 def A_ ( _UpperCAmelCase , _UpperCAmelCase = 16 ): SCREAMING_SNAKE_CASE_: List[Any] = AutoTokenizer.from_pretrained("bert-base-cased" ) SCREAMING_SNAKE_CASE_: Tuple = load_dataset("glue" , "mrpc" ) def tokenize_function(_UpperCAmelCase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE_: List[Any] = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE_: str = datasets.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=["idx", "sentence1", "sentence2"] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE_: Optional[Any] = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(_UpperCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE_: List[Any] = 1_28 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE_: Tuple = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE_: int = 8 else: SCREAMING_SNAKE_CASE_: Any = None return tokenizer.pad( _UpperCAmelCase , padding="longest" , max_length=_UpperCAmelCase , pad_to_multiple_of=_UpperCAmelCase , return_tensors="pt" , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE_: Optional[Any] = DataLoader( tokenized_datasets["train"] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple = DataLoader( tokenized_datasets["validation"] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""", None) == "1": from accelerate.test_utils.training import mocked_dataloaders lowerCAmelCase : Optional[int] = mocked_dataloaders # noqa: F811 def A_ ( _UpperCAmelCase , _UpperCAmelCase ): # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS" , _UpperCAmelCase ) == "1": SCREAMING_SNAKE_CASE_: Tuple = 2 # New Code # SCREAMING_SNAKE_CASE_: List[str] = int(args.gradient_accumulation_steps ) # Initialize accelerator SCREAMING_SNAKE_CASE_: int = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=_UpperCAmelCase ) if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1: raise NotImplementedError( "Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE_: Tuple = config["lr"] SCREAMING_SNAKE_CASE_: List[str] = int(config["num_epochs"] ) SCREAMING_SNAKE_CASE_: List[str] = int(config["seed"] ) SCREAMING_SNAKE_CASE_: Optional[int] = int(config["batch_size"] ) SCREAMING_SNAKE_CASE_: str = evaluate.load("glue" , "mrpc" ) set_seed(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[str] = get_dataloaders(_UpperCAmelCase , _UpperCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE_: Union[str, Any] = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=_UpperCAmelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE_: List[Any] = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE_: Union[str, Any] = AdamW(params=model.parameters() , lr=_UpperCAmelCase ) # Instantiate scheduler SCREAMING_SNAKE_CASE_: str = get_linear_schedule_with_warmup( optimizer=_UpperCAmelCase , num_warmup_steps=1_00 , num_training_steps=(len(_UpperCAmelCase ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Dict = accelerator.prepare( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) # Now we train the model for epoch in range(_UpperCAmelCase ): model.train() for step, batch in enumerate(_UpperCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(_UpperCAmelCase ): SCREAMING_SNAKE_CASE_: List[Any] = model(**_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] = output.loss accelerator.backward(_UpperCAmelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(_UpperCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE_: Optional[Any] = model(**_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=_UpperCAmelCase , references=_UpperCAmelCase , ) SCREAMING_SNAKE_CASE_: List[str] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"epoch {epoch}:" , _UpperCAmelCase ) def A_ ( ): SCREAMING_SNAKE_CASE_: str = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=_UpperCAmelCase , default=_UpperCAmelCase , choices=["no", "fp16", "bf16", "fp8"] , help="Whether to use mixed precision. Choose" "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." "and an Nvidia Ampere GPU." , ) # New Code # parser.add_argument( "--gradient_accumulation_steps" , type=_UpperCAmelCase , default=1 , help="The number of minibatches to be ran before gradients are accumulated." , ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) SCREAMING_SNAKE_CASE_: List[Any] = parser.parse_args() SCREAMING_SNAKE_CASE_: Tuple = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(_UpperCAmelCase , _UpperCAmelCase ) if __name__ == "__main__": main()
671
0
import os import pickle import unittest from transformers import AutoTokenizer from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.models.bert_japanese.tokenization_bert_japanese import ( VOCAB_FILES_NAMES, BertJapaneseTokenizer, CharacterTokenizer, JumanppTokenizer, MecabTokenizer, SudachiTokenizer, WordpieceTokenizer, ) from transformers.testing_utils import custom_tokenizers, require_jumanpp, require_sudachi from ...test_tokenization_common import TokenizerTesterMixin @custom_tokenizers class SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : List[Any] = BertJapaneseTokenizer UpperCamelCase_ : Optional[Any] = False UpperCamelCase_ : str = True def _A ( self : Tuple ): super().setUp() SCREAMING_SNAKE_CASE : Dict = [ "[UNK]", "[CLS]", "[SEP]", "こんにちは", "こん", "にちは", "ばんは", "##こん", "##にちは", "##ばんは", "世界", "##世界", "、", "##、", "。", "##。", ] SCREAMING_SNAKE_CASE : 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 _A ( self : Tuple , UpperCAmelCase_ : int ): SCREAMING_SNAKE_CASE : List[str] = "こんにちは、世界。 \nこんばんは、世界。" SCREAMING_SNAKE_CASE : Tuple = "こんにちは 、 世界 。 こんばんは 、 世界 。" return input_text, output_text def _A ( self : List[Any] , UpperCAmelCase_ : Any ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = self.get_input_output_texts(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.encode(UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = tokenizer.decode(UpperCAmelCase_ , clean_up_tokenization_spaces=UpperCAmelCase_ ) return text, ids def _A ( self : List[Any] ): pass # TODO add if relevant def _A ( self : str ): pass # TODO add if relevant def _A ( self : Optional[Any] ): pass # TODO add if relevant def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.tokenize("こんにちは、世界。\nこんばんは、世界。" ) self.assertListEqual(UpperCAmelCase_ , ["こんにちは", "、", "世界", "。", "こん", "##ばんは", "、", "世界", "。"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer_class(self.vocab_file , word_tokenizer_type="mecab" ) self.assertIsNotNone(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = "こんにちは、世界。\nこんばんは、世界。" SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.tokenize(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , ["こんにちは", "、", "世界", "。", "こん", "##ばんは", "、", "世界", "。"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(self.tmpdirname , "tokenizer.bin" ) with open(UpperCAmelCase_ , "wb" ) as handle: pickle.dump(UpperCAmelCase_ , UpperCAmelCase_ ) with open(UpperCAmelCase_ , "rb" ) as handle: SCREAMING_SNAKE_CASE : List[Any] = pickle.load(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = tokenizer_new.tokenize(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Optional[Any] = MecabTokenizer(mecab_dic="ipadic" ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , ["アップルストア", "で", "iPhone", "8", "が", "発売", "さ", "れ", "た", "。"] , ) def _A ( self : Dict ): try: SCREAMING_SNAKE_CASE : List[Any] = MecabTokenizer(mecab_dic="unidic_lite" ) except ModuleNotFoundError: return self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , ["アップル", "ストア", "で", "iPhone", "8", "が", "発売", "さ", "れ", "た", "。"] , ) def _A ( self : Dict ): try: SCREAMING_SNAKE_CASE : Optional[Any] = MecabTokenizer(mecab_dic="unidic" ) except ModuleNotFoundError: return self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , ["アップル", "ストア", "で", "iPhone", "8", "が", "発売", "さ", "れ", "た", "。"] , ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : Any = MecabTokenizer(do_lower_case=UpperCAmelCase_ , mecab_dic="ipadic" ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , ["アップルストア", "で", "iphone", "8", "が", "発売", "さ", "れ", "た", "。"] , ) def _A ( self : List[str] ): try: SCREAMING_SNAKE_CASE : Tuple = MecabTokenizer( do_lower_case=UpperCAmelCase_ , normalize_text=UpperCAmelCase_ , mecab_option="-d /usr/local/lib/mecab/dic/jumandic" ) except RuntimeError: # if dict doesn't exist in the system, previous code raises this error. return self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , ["アップルストア", "で", "iPhone", "8", "が", "発売", "さ", "れた", "\u3000", "。"] , ) def _A ( self : Dict ): SCREAMING_SNAKE_CASE : List[Any] = MecabTokenizer(normalize_text=UpperCAmelCase_ , mecab_dic="ipadic" ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , ["アップルストア", "で", "iPhone", "8", "が", "発売", "さ", "れ", "た", " ", "。"] , ) @require_sudachi def _A ( self : Dict ): SCREAMING_SNAKE_CASE : Any = self.tokenizer_class(self.vocab_file , word_tokenizer_type="sudachi" ) self.assertIsNotNone(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = "こんにちは、世界。\nこんばんは、世界。" SCREAMING_SNAKE_CASE : List[str] = tokenizer.tokenize(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , ["こんにちは", "、", "世界", "。", "こん", "##ばんは", "、", "世界", "。"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) SCREAMING_SNAKE_CASE : Tuple = os.path.join(self.tmpdirname , "tokenizer.bin" ) with open(UpperCAmelCase_ , "wb" ) as handle: pickle.dump(UpperCAmelCase_ , UpperCAmelCase_ ) with open(UpperCAmelCase_ , "rb" ) as handle: SCREAMING_SNAKE_CASE : List[str] = pickle.load(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = tokenizer_new.tokenize(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) @require_sudachi def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : str = SudachiTokenizer(sudachi_dict_type="core" ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , [" ", "\t", "アップル", "ストア", "で", "iPhone", "8", " ", "が", " ", " ", "\n ", "発売", "さ", "れ", "た", " ", "。", " ", " "] , ) @require_sudachi def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any = SudachiTokenizer(sudachi_dict_type="core" , sudachi_split_mode="A" ) self.assertListEqual(tokenizer.tokenize("外国人参政権" ) , ["外国", "人", "参政", "権"] ) @require_sudachi def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : str = SudachiTokenizer(sudachi_dict_type="core" , sudachi_split_mode="B" ) self.assertListEqual(tokenizer.tokenize("外国人参政権" ) , ["外国人", "参政権"] ) @require_sudachi def _A ( self : str ): SCREAMING_SNAKE_CASE : Dict = SudachiTokenizer(sudachi_dict_type="core" , sudachi_split_mode="C" ) self.assertListEqual(tokenizer.tokenize("外国人参政権" ) , ["外国人参政権"] ) @require_sudachi def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : Dict = SudachiTokenizer(do_lower_case=UpperCAmelCase_ , sudachi_dict_type="core" ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , [" ", "\t", "アップル", "ストア", "で", "iphone", "8", " ", "が", " ", " ", "\n ", "発売", "さ", "れ", "た", " ", "。", " ", " "] , ) @require_sudachi def _A ( self : Dict ): SCREAMING_SNAKE_CASE : int = SudachiTokenizer(normalize_text=UpperCAmelCase_ , sudachi_dict_type="core" ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , [" ", "\t", "アップル", "ストア", "で", "iPhone", "8", " ", "が", " ", " ", "\n ", "発売", "さ", "れ", "た", "\u3000", "。", " ", " "] , ) @require_sudachi def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : Union[str, Any] = SudachiTokenizer(trim_whitespace=UpperCAmelCase_ , sudachi_dict_type="core" ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , ["アップル", "ストア", "で", "iPhone", "8", "が", "発売", "さ", "れ", "た", "。"] , ) @require_jumanpp def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any = self.tokenizer_class(self.vocab_file , word_tokenizer_type="jumanpp" ) self.assertIsNotNone(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = "こんにちは、世界。\nこんばんは、世界。" SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.tokenize(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , ["こんにちは", "、", "世界", "。", "こん", "##ばんは", "、", "世界", "。"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) SCREAMING_SNAKE_CASE : Optional[int] = os.path.join(self.tmpdirname , "tokenizer.bin" ) with open(UpperCAmelCase_ , "wb" ) as handle: pickle.dump(UpperCAmelCase_ , UpperCAmelCase_ ) with open(UpperCAmelCase_ , "rb" ) as handle: SCREAMING_SNAKE_CASE : List[Any] = pickle.load(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = tokenizer_new.tokenize(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) @require_jumanpp def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : str = JumanppTokenizer() self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , ["アップル", "ストア", "で", "iPhone", "8", "\u3000", "が", "\u3000", "\u3000", "\u3000", "発売", "さ", "れた", "\u3000", "。"] , ) @require_jumanpp def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : List[Any] = JumanppTokenizer(do_lower_case=UpperCAmelCase_ ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , ["アップル", "ストア", "で", "iphone", "8", "\u3000", "が", "\u3000", "\u3000", "\u3000", "発売", "さ", "れた", "\u3000", "。"] , ) @require_jumanpp def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : str = JumanppTokenizer(normalize_text=UpperCAmelCase_ ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , ["ア", "ッ", "フ", "゚", "ル", "ストア", "で", "iPhone", "8", "\u3000", "が", "\u3000", "\u3000", "\u3000", "発売", "さ", "れた", "\u3000", "。"] , ) @require_jumanpp def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : str = JumanppTokenizer(trim_whitespace=UpperCAmelCase_ ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) , ["アップル", "ストア", "で", "iPhone", "8", "が", "発売", "さ", "れた", "。"] , ) @require_jumanpp def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : List[str] = JumanppTokenizer() self.assertListEqual( tokenizer.tokenize("ありがとうございますm(_ _)m見つけるのが大変です。" ) , ["ありがとう", "ございます", "m(_ _)m", "見つける", "の", "が", "大変です", "。"] , ) def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[Any] = ["[UNK]", "[CLS]", "[SEP]", "こんにちは", "こん", "にちは", "ばんは", "##こん", "##にちは", "##ばんは"] SCREAMING_SNAKE_CASE : str = {} for i, token in enumerate(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : str = i SCREAMING_SNAKE_CASE : Optional[Any] = WordpieceTokenizer(vocab=UpperCAmelCase_ , unk_token="[UNK]" ) self.assertListEqual(tokenizer.tokenize("" ) , [] ) self.assertListEqual(tokenizer.tokenize("こんにちは" ) , ["こんにちは"] ) self.assertListEqual(tokenizer.tokenize("こんばんは" ) , ["こん", "##ばんは"] ) self.assertListEqual(tokenizer.tokenize("こんばんは こんばんにちは こんにちは" ) , ["こん", "##ばんは", "[UNK]", "こんにちは"] ) def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : Optional[Any] = BertJapaneseTokenizer.from_pretrained("nlp-waseda/roberta-base-japanese-with-auto-jumanpp" ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.subword_tokenizer SCREAMING_SNAKE_CASE : Any = subword_tokenizer.tokenize("国境 の 長い トンネル を 抜ける と 雪国 であった 。" ) self.assertListEqual(UpperCAmelCase_ , ["▁国境", "▁の", "▁長い", "▁トンネル", "▁を", "▁抜ける", "▁と", "▁雪", "国", "▁であった", "▁。"] ) SCREAMING_SNAKE_CASE : List[str] = subword_tokenizer.tokenize("こんばんは こんばん にち は こんにちは" ) self.assertListEqual(UpperCAmelCase_ , ["▁こん", "ばん", "は", "▁こん", "ばん", "▁に", "ち", "▁は", "▁こんにちは"] ) def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer_class.from_pretrained("cl-tohoku/bert-base-japanese" ) SCREAMING_SNAKE_CASE : Dict = tokenizer.encode("ありがとう。" , add_special_tokens=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.encode("どういたしまして。" , add_special_tokens=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase_ , UpperCAmelCase_ ) # 2 is for "[CLS]", 3 is for "[SEP]" assert encoded_sentence == [2] + text + [3] assert encoded_pair == [2] + text + [3] + text_a + [3] @custom_tokenizers class SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = BertJapaneseTokenizer UpperCamelCase_ : Tuple = False def _A ( self : str ): super().setUp() SCREAMING_SNAKE_CASE : Tuple = ["[UNK]", "[CLS]", "[SEP]", "こ", "ん", "に", "ち", "は", "ば", "世", "界", "、", "。"] SCREAMING_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 _A ( self : str , **UpperCAmelCase_ : int ): return BertJapaneseTokenizer.from_pretrained(self.tmpdirname , subword_tokenizer_type="character" , **UpperCAmelCase_ ) def _A ( self : List[str] , UpperCAmelCase_ : Union[str, Any] ): SCREAMING_SNAKE_CASE : Tuple = "こんにちは、世界。 \nこんばんは、世界。" SCREAMING_SNAKE_CASE : Optional[Any] = "こ ん に ち は 、 世 界 。 こ ん ば ん は 、 世 界 。" return input_text, output_text def _A ( self : Any ): pass # TODO add if relevant def _A ( self : Optional[int] ): pass # TODO add if relevant def _A ( self : Dict ): pass # TODO add if relevant def _A ( self : Dict ): SCREAMING_SNAKE_CASE : Dict = self.tokenizer_class(self.vocab_file , subword_tokenizer_type="character" ) SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.tokenize("こんにちは、世界。 \nこんばんは、世界。" ) self.assertListEqual( UpperCAmelCase_ , ["こ", "ん", "に", "ち", "は", "、", "世", "界", "。", "こ", "ん", "ば", "ん", "は", "、", "世", "界", "。"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , [3, 4, 5, 6, 7, 11, 9, 10, 12, 3, 4, 8, 4, 7, 11, 9, 10, 12] ) def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : List[str] = ["[UNK]", "[CLS]", "[SEP]", "こ", "ん", "に", "ち", "は", "ば", "世", "界", "、", "。"] SCREAMING_SNAKE_CASE : Optional[int] = {} for i, token in enumerate(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : str = i SCREAMING_SNAKE_CASE : List[str] = CharacterTokenizer(vocab=UpperCAmelCase_ , unk_token="[UNK]" ) self.assertListEqual(tokenizer.tokenize("" ) , [] ) self.assertListEqual(tokenizer.tokenize("こんにちは" ) , ["こ", "ん", "に", "ち", "は"] ) self.assertListEqual(tokenizer.tokenize("こんにちほ" ) , ["こ", "ん", "に", "ち", "[UNK]"] ) def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : Any = self.tokenizer_class.from_pretrained("cl-tohoku/bert-base-japanese-char" ) SCREAMING_SNAKE_CASE : str = tokenizer.encode("ありがとう。" , add_special_tokens=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = tokenizer.encode("どういたしまして。" , add_special_tokens=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase_ , UpperCAmelCase_ ) # 2 is for "[CLS]", 3 is for "[SEP]" assert encoded_sentence == [2] + text + [3] assert encoded_pair == [2] + text + [3] + text_a + [3] @custom_tokenizers class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : List[str] = "cl-tohoku/bert-base-japanese" SCREAMING_SNAKE_CASE : Any = AutoTokenizer.from_pretrained(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : int ): SCREAMING_SNAKE_CASE : Any = "cl-tohoku/bert-base-japanese" with self.assertLogs("transformers" , level="WARNING" ) as cm: BertTokenizer.from_pretrained(UpperCAmelCase_ ) self.assertTrue( cm.records[0].message.startswith( "The tokenizer class you load from this checkpoint is not the same type as the class this function" " is called from." ) ) SCREAMING_SNAKE_CASE : Optional[Any] = "bert-base-cased" with self.assertLogs("transformers" , level="WARNING" ) as cm: BertJapaneseTokenizer.from_pretrained(UpperCAmelCase_ ) self.assertTrue( cm.records[0].message.startswith( "The tokenizer class you load from this checkpoint is not the same type as the class this function" " is called from." ) )
62
from math import asin, atan, cos, radians, sin, sqrt, tan lowerCAmelCase : Union[str, Any] = 637_8137.0 lowerCAmelCase : int = 635_6752.31_4245 lowerCAmelCase : Union[str, Any] = 6378137 def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: List[Any] = (AXIS_A - AXIS_B) / AXIS_A SCREAMING_SNAKE_CASE_: str = atan((1 - flattening) * tan(radians(_UpperCAmelCase ) ) ) SCREAMING_SNAKE_CASE_: Optional[int] = atan((1 - flattening) * tan(radians(_UpperCAmelCase ) ) ) SCREAMING_SNAKE_CASE_: Any = radians(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Dict = radians(_UpperCAmelCase ) # Equation SCREAMING_SNAKE_CASE_: str = sin((phi_a - phi_a) / 2 ) SCREAMING_SNAKE_CASE_: List[Any] = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda SCREAMING_SNAKE_CASE_: Tuple = sqrt(sin_sq_phi + (cos(_UpperCAmelCase ) * cos(_UpperCAmelCase ) * sin_sq_lambda) ) return 2 * RADIUS * asin(_UpperCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
671
0
def lowerCamelCase__ ( __lowerCamelCase : int , __lowerCamelCase : float , __lowerCamelCase : float ): return round(float(moles / volume ) * nfactor ) def lowerCamelCase__ ( __lowerCamelCase : float , __lowerCamelCase : float , __lowerCamelCase : float ): return round(float((moles * 0.0_8_2_1 * temperature) / (volume) ) ) def lowerCamelCase__ ( __lowerCamelCase : float , __lowerCamelCase : float , __lowerCamelCase : float ): return round(float((moles * 0.0_8_2_1 * temperature) / (pressure) ) ) def lowerCamelCase__ ( __lowerCamelCase : float , __lowerCamelCase : float , __lowerCamelCase : float ): return round(float((pressure * volume) / (0.0_8_2_1 * moles) ) ) if __name__ == "__main__": import doctest doctest.testmod()
63
import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): # Initialise PyTorch model SCREAMING_SNAKE_CASE_: List[Any] = BertConfig.from_json_file(_UpperCAmelCase ) print(f"Building PyTorch model from configuration: {config}" ) SCREAMING_SNAKE_CASE_: Tuple = BertForPreTraining(_UpperCAmelCase ) # Load weights from tf checkpoint load_tf_weights_in_bert(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) # Save pytorch-model print(f"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , _UpperCAmelCase ) if __name__ == "__main__": lowerCAmelCase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--bert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained BERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) lowerCAmelCase : Optional[Any] = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
671
0
import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": lowercase_ : List[Any] = argparse.ArgumentParser() parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument( '--txt2img_unclip', default='kakaobrain/karlo-v1-alpha', type=str, required=False, help='The pretrained txt2img unclip.', ) lowercase_ : Dict = parser.parse_args() lowercase_ : int = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) lowercase_ : Any = CLIPImageProcessor() lowercase_ : str = CLIPVisionModelWithProjection.from_pretrained('openai/clip-vit-large-patch14') lowercase_ : int = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
64
import math def A_ ( _UpperCAmelCase ): if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_UpperCAmelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def A_ ( _UpperCAmelCase = 0.1 ): SCREAMING_SNAKE_CASE_: Union[str, Any] = 3 SCREAMING_SNAKE_CASE_: Optional[int] = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ): primes += is_prime(_UpperCAmelCase ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
671
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __UpperCAmelCase = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ['NllbTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ['NllbTokenizerFast'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb import NllbTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb_fast import NllbTokenizerFast else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
65
import re def A_ ( _UpperCAmelCase ): return [char.split() for char in re.split(R"[^ a-z A-Z 0-9 \s]" , str_ )] def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: int = split_input(str_ ) return "".join( ["".join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): try: SCREAMING_SNAKE_CASE_: List[Any] = split_input(_UpperCAmelCase ) if upper: SCREAMING_SNAKE_CASE_: List[str] = "".join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: SCREAMING_SNAKE_CASE_: Optional[int] = "".join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def A_ ( _UpperCAmelCase ): return to_simple_case(_UpperCAmelCase ) def A_ ( _UpperCAmelCase ): try: SCREAMING_SNAKE_CASE_: Optional[int] = to_simple_case(_UpperCAmelCase ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def A_ ( _UpperCAmelCase , _UpperCAmelCase ): return to_complex_case(_UpperCAmelCase , _UpperCAmelCase , "_" ) def A_ ( _UpperCAmelCase , _UpperCAmelCase ): return to_complex_case(_UpperCAmelCase , _UpperCAmelCase , "-" ) if __name__ == "__main__": __import__("""doctest""").testmod()
671
0
import os import zipfile import pytest from datasets.utils.extract import ( BzipaExtractor, Extractor, GzipExtractor, LzaExtractor, SevenZipExtractor, TarExtractor, XzExtractor, ZipExtractor, ZstdExtractor, ) from .utils import require_lza, require_pyazr, require_zstandard @pytest.mark.parametrize( 'compression_format, is_archive' , [ ('7z', True), ('bz2', False), ('gzip', False), ('lz4', False), ('tar', True), ('xz', False), ('zip', True), ('zstd', False), ] , ) def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> Dict: _lowercase : Optional[Any] = { '7z': (seven_zip_file, SevenZipExtractor), 'bz2': (bza_file, BzipaExtractor), 'gzip': (gz_file, GzipExtractor), 'lz4': (lza_file, LzaExtractor), 'tar': (tar_file, TarExtractor), 'xz': (xz_file, XzExtractor), 'zip': (zip_file, ZipExtractor), 'zstd': (zstd_file, ZstdExtractor), } _lowercase , _lowercase : Any = input_paths_and_base_extractors[compression_format] if input_path is None: _lowercase : List[str] = F"""for '{compression_format}' compression_format, """ if compression_format == "7z": reason += require_pyazr.kwargs["reason"] elif compression_format == "lz4": reason += require_lza.kwargs["reason"] elif compression_format == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(SCREAMING_SNAKE_CASE ) assert base_extractor.is_extractable(SCREAMING_SNAKE_CASE ) _lowercase : Any = tmp_path / ('extracted' if is_archive else 'extracted.txt') base_extractor.extract(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if is_archive: assert output_path.is_dir() for file_path in output_path.iterdir(): assert file_path.name == text_file.name _lowercase : Optional[int] = file_path.read_text(encoding='utf-8' ) else: _lowercase : Any = output_path.read_text(encoding='utf-8' ) _lowercase : str = text_file.read_text(encoding='utf-8' ) assert extracted_file_content == expected_file_content @pytest.mark.parametrize( 'compression_format, is_archive' , [ ('7z', True), ('bz2', False), ('gzip', False), ('lz4', False), ('tar', True), ('xz', False), ('zip', True), ('zstd', False), ] , ) def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> Optional[Any]: _lowercase : Tuple = { '7z': seven_zip_file, 'bz2': bza_file, 'gzip': gz_file, 'lz4': lza_file, 'tar': tar_file, 'xz': xz_file, 'zip': zip_file, 'zstd': zstd_file, } _lowercase : Any = input_paths[compression_format] if input_path is None: _lowercase : List[str] = F"""for '{compression_format}' compression_format, """ if compression_format == "7z": reason += require_pyazr.kwargs["reason"] elif compression_format == "lz4": reason += require_lza.kwargs["reason"] elif compression_format == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(SCREAMING_SNAKE_CASE ) _lowercase : Tuple = Extractor.infer_extractor_format(SCREAMING_SNAKE_CASE ) assert extractor_format is not None _lowercase : int = tmp_path / ('extracted' if is_archive else 'extracted.txt') Extractor.extract(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if is_archive: assert output_path.is_dir() for file_path in output_path.iterdir(): assert file_path.name == text_file.name _lowercase : List[Any] = file_path.read_text(encoding='utf-8' ) else: _lowercase : List[str] = output_path.read_text(encoding='utf-8' ) _lowercase : str = text_file.read_text(encoding='utf-8' ) assert extracted_file_content == expected_file_content @pytest.fixture def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Union[str, Any]: import tarfile _lowercase : List[Any] = tmp_path / 'data_dot_dot' directory.mkdir() _lowercase : Optional[Any] = directory / 'tar_file_with_dot_dot.tar' with tarfile.TarFile(SCREAMING_SNAKE_CASE , 'w' ) as f: f.add(SCREAMING_SNAKE_CASE , arcname=os.path.join('..' , text_file.name ) ) return path @pytest.fixture def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> Any: import tarfile _lowercase : List[Any] = tmp_path / 'data_sym_link' directory.mkdir() _lowercase : str = directory / 'tar_file_with_sym_link.tar' os.symlink('..' , directory / 'subdir' , target_is_directory=SCREAMING_SNAKE_CASE ) with tarfile.TarFile(SCREAMING_SNAKE_CASE , 'w' ) as f: f.add(str(directory / 'subdir' ) , arcname='subdir' ) # str required by os.readlink on Windows and Python < 3.8 return path @pytest.mark.parametrize( 'insecure_tar_file, error_log' , [('tar_file_with_dot_dot', 'illegal path'), ('tar_file_with_sym_link', 'Symlink')] , ) def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Union[str, Any]: _lowercase : Optional[int] = { 'tar_file_with_dot_dot': tar_file_with_dot_dot, 'tar_file_with_sym_link': tar_file_with_sym_link, } _lowercase : str = insecure_tar_files[insecure_tar_file] _lowercase : List[Any] = tmp_path / 'extracted' TarExtractor.extract(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) assert caplog.text for record in caplog.records: assert record.levelname == "ERROR" assert error_log in record.msg def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> Optional[int]: # We should have less false positives than zipfile.is_zipfile # We do that by checking only the magic number _lowercase : List[str] = tmpdir / 'not_a_zip_file' # From: https://github.com/python/cpython/pull/5053 _lowercase : List[str] = ( b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00' b'\x00\x02\x08\x06\x00\x00\x00\x99\x81\xb6\'\x00\x00\x00\x15I' b'DATx\x01\x01\n\x00\xf5\xff\x00PK\x05\x06\x00PK\x06\x06\x07' b'\xac\x01N\xc6|a\r\x00\x00\x00\x00IEND\xaeB`\x82' ) with not_a_zip_file.open('wb' ) as f: f.write(SCREAMING_SNAKE_CASE ) assert zipfile.is_zipfile(str(SCREAMING_SNAKE_CASE ) ) # is a false positive for `zipfile` assert not ZipExtractor.is_extractable(SCREAMING_SNAKE_CASE ) # but we're right
66
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING lowerCAmelCase : Union[str, Any] = logging.get_logger(__name__) class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : List[Any] = '''upernet''' def __init__( self : Any , lowerCAmelCase__ : Union[str, Any]=None , lowerCAmelCase__ : List[str]=512 , lowerCAmelCase__ : Any=0.02 , lowerCAmelCase__ : str=[1, 2, 3, 6] , lowerCAmelCase__ : Optional[Any]=True , lowerCAmelCase__ : Dict=0.4 , lowerCAmelCase__ : int=384 , lowerCAmelCase__ : Union[str, Any]=256 , lowerCAmelCase__ : Any=1 , lowerCAmelCase__ : Tuple=False , lowerCAmelCase__ : List[str]=255 , **lowerCAmelCase__ : List[str] , ): super().__init__(**lowerCAmelCase__) if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.") SCREAMING_SNAKE_CASE_: Dict = CONFIG_MAPPING["resnet"](out_features=["stage1", "stage2", "stage3", "stage4"]) elif isinstance(lowerCAmelCase__ , lowerCAmelCase__): SCREAMING_SNAKE_CASE_: str = backbone_config.get("model_type") SCREAMING_SNAKE_CASE_: str = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE_: Tuple = config_class.from_dict(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: str = backbone_config SCREAMING_SNAKE_CASE_: Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_: Dict = initializer_range SCREAMING_SNAKE_CASE_: Any = pool_scales SCREAMING_SNAKE_CASE_: Optional[Any] = use_auxiliary_head SCREAMING_SNAKE_CASE_: str = auxiliary_loss_weight SCREAMING_SNAKE_CASE_: List[Any] = auxiliary_in_channels SCREAMING_SNAKE_CASE_: Union[str, Any] = auxiliary_channels SCREAMING_SNAKE_CASE_: Dict = auxiliary_num_convs SCREAMING_SNAKE_CASE_: str = auxiliary_concat_input SCREAMING_SNAKE_CASE_: Dict = loss_ignore_index def _SCREAMING_SNAKE_CASE ( self : Tuple): SCREAMING_SNAKE_CASE_: Tuple = copy.deepcopy(self.__dict__) SCREAMING_SNAKE_CASE_: int = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE_: Optional[int] = self.__class__.model_type return output
671
0
def SCREAMING_SNAKE_CASE__ ( snake_case__ :str ) -> Union[str, Any]: _lowercase = len(snake_case__ ) _lowercase = sum(snake_case__ ) _lowercase = [[False for x in range(s + 1 )] for y in range(n + 1 )] for i in range(1 , n + 1 ): _lowercase = True for i in range(1 , s + 1 ): _lowercase = False for i in range(1 , n + 1 ): for j in range(1 , s + 1 ): _lowercase = dp[i][j - 1] if arr[i - 1] <= j: _lowercase = dp[i][j] or dp[i - 1][j - arr[i - 1]] for j in range(int(s / 2 ) , -1 , -1 ): if dp[n][j] is True: _lowercase = s - 2 * j break return diff
67
import pickle import unittest import torch from accelerate import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils import require_cpu @require_cpu class __lowercase ( unittest.TestCase ): """simple docstring""" def _SCREAMING_SNAKE_CASE ( self : Any): SCREAMING_SNAKE_CASE_: List[str] = torch.nn.Linear(10 , 10) SCREAMING_SNAKE_CASE_: Union[str, Any] = torch.optim.SGD(model.parameters() , 0.1) SCREAMING_SNAKE_CASE_: Any = Accelerator() SCREAMING_SNAKE_CASE_: List[str] = accelerator.prepare(lowerCAmelCase__) try: pickle.loads(pickle.dumps(lowerCAmelCase__)) except Exception as e: self.fail(F"Accelerated optimizer pickling failed with {e}") AcceleratorState._reset_state()
671
0
import pytest import requests from datasets.utils.file_utils import http_head from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline @pytest.mark.integration def lowercase__ ( ) -> Union[str, Any]: """simple docstring""" with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT ): with pytest.raises(A_ ): requests.request("""GET""" , """https://huggingface.co""" ) with pytest.raises(requests.exceptions.ConnectTimeout ): requests.request("""GET""" , """https://huggingface.co""" , timeout=1.0 ) @pytest.mark.integration def lowercase__ ( ) -> int: """simple docstring""" with offline(OfflineSimulationMode.CONNECTION_FAILS ): with pytest.raises(requests.exceptions.ConnectionError ): requests.request("""GET""" , """https://huggingface.co""" ) def lowercase__ ( ) -> Optional[int]: """simple docstring""" with offline(OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1 ): with pytest.raises(A_ ): http_head("""https://huggingface.co""" )
68
from itertools import count def A_ ( _UpperCAmelCase = 50 ): SCREAMING_SNAKE_CASE_: Union[str, Any] = [1] * min_block_length for n in count(_UpperCAmelCase ): fill_count_functions.append(1 ) for block_length in range(_UpperCAmelCase , 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() = }''')
671
0
'''simple docstring''' import inspect import unittest from transformers import ViTMSNConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTMSNForImageClassification, ViTMSNModel from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class SCREAMING_SNAKE_CASE__ : def __init__( self : List[str] , a_ : str , a_ : Any=13 , a_ : Union[str, Any]=30 , a_ : Union[str, Any]=2 , a_ : Union[str, Any]=3 , a_ : List[str]=True , a_ : Union[str, Any]=True , a_ : Union[str, Any]=32 , a_ : List[str]=5 , a_ : Union[str, Any]=4 , a_ : Union[str, Any]=37 , a_ : Tuple="gelu" , a_ : str=0.1 , a_ : Optional[Any]=0.1 , a_ : Optional[Any]=10 , a_ : Tuple=0.02 , a_ : Union[str, Any]=None , ): """simple docstring""" __snake_case = parent __snake_case = batch_size __snake_case = image_size __snake_case = patch_size __snake_case = num_channels __snake_case = is_training __snake_case = use_labels __snake_case = hidden_size __snake_case = num_hidden_layers __snake_case = num_attention_heads __snake_case = intermediate_size __snake_case = hidden_act __snake_case = hidden_dropout_prob __snake_case = attention_probs_dropout_prob __snake_case = type_sequence_label_size __snake_case = initializer_range __snake_case = scope # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) __snake_case = (image_size // patch_size) ** 2 __snake_case = num_patches + 1 def A ( self : List[str] ): """simple docstring""" __snake_case = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __snake_case = None if self.use_labels: __snake_case = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __snake_case = self.get_config() return config, pixel_values, labels def A ( self : int ): """simple docstring""" return ViTMSNConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , 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 , initializer_range=self.initializer_range , ) def A ( self : str , a_ : Tuple , a_ : Optional[int] , a_ : int ): """simple docstring""" __snake_case = ViTMSNModel(config=a_ ) model.to(a_ ) model.eval() __snake_case = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def A ( self : Dict , a_ : Union[str, Any] , a_ : Any , a_ : List[Any] ): """simple docstring""" __snake_case = self.type_sequence_label_size __snake_case = ViTMSNForImageClassification(a_ ) model.to(a_ ) model.eval() __snake_case = model(a_ , labels=a_ ) print("Pixel and labels shape: {pixel_values.shape}, {labels.shape}" ) print("Labels: {labels}" ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __snake_case = 1 __snake_case = ViTMSNForImageClassification(a_ ) model.to(a_ ) model.eval() __snake_case = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __snake_case = model(a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def A ( self : Tuple ): """simple docstring""" __snake_case = self.prepare_config_and_inputs() __snake_case , __snake_case , __snake_case = config_and_inputs __snake_case = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): __SCREAMING_SNAKE_CASE = (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else () __SCREAMING_SNAKE_CASE = ( {"""feature-extraction""": ViTMSNModel, """image-classification""": ViTMSNForImageClassification} if is_torch_available() else {} ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False def A ( self : Optional[int] ): """simple docstring""" __snake_case = ViTMSNModelTester(self ) __snake_case = ConfigTester(self , config_class=a_ , has_text_modality=a_ , hidden_size=37 ) def A ( self : Any ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="ViTMSN does not use inputs_embeds" ) def A ( self : Any ): """simple docstring""" pass def A ( self : str ): """simple docstring""" __snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case = model_class(a_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __snake_case = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a_ , nn.Linear ) ) def A ( self : Dict ): """simple docstring""" __snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case = model_class(a_ ) __snake_case = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __snake_case = [*signature.parameters.keys()] __snake_case = ["pixel_values"] self.assertListEqual(arg_names[:1] , a_ ) def A ( self : Optional[Any] ): """simple docstring""" __snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def A ( self : List[str] ): """simple docstring""" __snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) @slow def A ( self : int ): """simple docstring""" for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case = ViTMSNModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def __UpperCAmelCase ( ) -> Any: __snake_case = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @cached_property def A ( self : List[Any] ): """simple docstring""" return ViTImageProcessor.from_pretrained("facebook/vit-msn-small" ) if is_vision_available() else None @slow def A ( self : List[str] ): """simple docstring""" torch.manual_seed(2 ) __snake_case = ViTMSNForImageClassification.from_pretrained("facebook/vit-msn-small" ).to(a_ ) __snake_case = self.default_image_processor __snake_case = prepare_img() __snake_case = image_processor(images=a_ , return_tensors="pt" ).to(a_ ) # forward pass with torch.no_grad(): __snake_case = model(**a_ ) # verify the logits __snake_case = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , a_ ) __snake_case = torch.tensor([-0.0803, -0.4454, -0.2375] ).to(a_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a_ , atol=1e-4 ) )
69
def A_ ( _UpperCAmelCase ): if not isinstance(_UpperCAmelCase , _UpperCAmelCase ): raise TypeError("only integers accepted as input" ) else: SCREAMING_SNAKE_CASE_: List[Any] = str(abs(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE_: Tuple = [list(_UpperCAmelCase ) for char in range(len(_UpperCAmelCase ) )] for index in range(len(_UpperCAmelCase ) ): num_transpositions[index].pop(_UpperCAmelCase ) return max( int("".join(list(_UpperCAmelCase ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__("""doctest""").testmod()
671
0
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowerCamelCase : Any = logging.get_logger(__name__) lowerCamelCase : Optional[int] = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} lowerCamelCase : List[Any] = { "tokenizer_file": { "EleutherAI/gpt-neox-20b": "https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json", }, } lowerCamelCase : Dict = { "gpt-neox-20b": 2_048, } class A( UpperCamelCase ): '''simple docstring''' UpperCamelCase = VOCAB_FILES_NAMES UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase = ['''input_ids''', '''attention_mask'''] def __init__( self : List[str] , A_ : List[Any]=None , A_ : Tuple=None , A_ : Union[str, Any]=None , A_ : Any="<|endoftext|>" , A_ : str="<|endoftext|>" , A_ : int="<|endoftext|>" , A_ : Optional[Any]=False , **A_ : List[Any] , ) -> int: """simple docstring""" super().__init__( A_ , A_ , tokenizer_file=A_ , unk_token=A_ , bos_token=A_ , eos_token=A_ , add_prefix_space=A_ , **A_ , ) lowerCamelCase_ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('add_prefix_space' , A_ ) != add_prefix_space: lowerCamelCase_ = getattr(A_ , pre_tok_state.pop('type' ) ) lowerCamelCase_ = add_prefix_space lowerCamelCase_ = pre_tok_class(**A_ ) lowerCamelCase_ = add_prefix_space def a__ ( self : Optional[int] , A_ : str , A_ : Optional[str] = None ) -> Tuple[str]: """simple docstring""" lowerCamelCase_ = self._tokenizer.model.save(A_ , name=A_ ) return tuple(A_ ) def a__ ( self : List[str] , A_ : "Conversation" ) -> List[int]: """simple docstring""" lowerCamelCase_ = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(A_ , add_special_tokens=A_ ) + [self.eos_token_id] ) if len(A_ ) > self.model_max_length: lowerCamelCase_ = input_ids[-self.model_max_length :] return input_ids
70
from __future__ import annotations from collections.abc import Iterator from typing import Any class __lowercase : """simple docstring""" def __init__( self : List[str] , lowerCAmelCase__ : Any): SCREAMING_SNAKE_CASE_: Any = data SCREAMING_SNAKE_CASE_: Node | None = None class __lowercase : """simple docstring""" def __init__( self : int): SCREAMING_SNAKE_CASE_: Dict = None SCREAMING_SNAKE_CASE_: str = None def __iter__( self : List[str]): SCREAMING_SNAKE_CASE_: Tuple = self.head while self.head: yield node.data SCREAMING_SNAKE_CASE_: List[str] = node.next if node == self.head: break def __len__( self : Dict): return sum(1 for _ in self) def __repr__( self : Dict): return "->".join(str(lowerCAmelCase__) for item in iter(self)) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase__ : Any): self.insert_nth(len(self) , lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase__ : Any): self.insert_nth(0 , lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : Any): if index < 0 or index > len(self): raise IndexError("list index out of range.") SCREAMING_SNAKE_CASE_: Any = Node(lowerCAmelCase__) if self.head is None: SCREAMING_SNAKE_CASE_: str = new_node # first node points itself SCREAMING_SNAKE_CASE_: Optional[Any] = new_node elif index == 0: # insert at head SCREAMING_SNAKE_CASE_: Optional[Any] = self.head SCREAMING_SNAKE_CASE_: str = new_node else: SCREAMING_SNAKE_CASE_: int = self.head for _ in range(index - 1): SCREAMING_SNAKE_CASE_: Optional[Any] = temp.next SCREAMING_SNAKE_CASE_: List[str] = temp.next SCREAMING_SNAKE_CASE_: int = new_node if index == len(self) - 1: # insert at tail SCREAMING_SNAKE_CASE_: Any = new_node def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): return self.delete_nth(0) def _SCREAMING_SNAKE_CASE ( self : Any): return self.delete_nth(len(self) - 1) def _SCREAMING_SNAKE_CASE ( self : Any , lowerCAmelCase__ : int = 0): if not 0 <= index < len(self): raise IndexError("list index out of range.") SCREAMING_SNAKE_CASE_: Optional[Any] = self.head if self.head == self.tail: # just one node SCREAMING_SNAKE_CASE_: List[str] = None elif index == 0: # delete head node SCREAMING_SNAKE_CASE_: int = self.tail.next.next SCREAMING_SNAKE_CASE_: Tuple = self.head.next else: SCREAMING_SNAKE_CASE_: Optional[int] = self.head for _ in range(index - 1): SCREAMING_SNAKE_CASE_: Any = temp.next SCREAMING_SNAKE_CASE_: Optional[Any] = temp.next SCREAMING_SNAKE_CASE_: int = temp.next.next if index == len(self) - 1: # delete at tail SCREAMING_SNAKE_CASE_: int = temp return delete_node.data def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): return len(self) == 0 def A_ ( ): SCREAMING_SNAKE_CASE_: Dict = CircularLinkedList() assert len(_UpperCAmelCase ) == 0 assert circular_linked_list.is_empty() is True assert str(_UpperCAmelCase ) == "" try: circular_linked_list.delete_front() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_tail() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_nth(-1 ) raise AssertionError except IndexError: assert True try: circular_linked_list.delete_nth(0 ) raise AssertionError except IndexError: assert True assert circular_linked_list.is_empty() is True for i in range(5 ): assert len(_UpperCAmelCase ) == i circular_linked_list.insert_nth(_UpperCAmelCase , i + 1 ) assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 6 ) ) circular_linked_list.insert_tail(6 ) assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 7 ) ) circular_linked_list.insert_head(0 ) assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(0 , 7 ) ) assert circular_linked_list.delete_front() == 0 assert circular_linked_list.delete_tail() == 6 assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 6 ) ) assert circular_linked_list.delete_nth(2 ) == 3 circular_linked_list.insert_nth(2 , 3 ) assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 6 ) ) assert circular_linked_list.is_empty() is False if __name__ == "__main__": import doctest doctest.testmod()
671
0
'''simple docstring''' import unittest from transformers import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device if is_torch_available(): import torch from transformers import AutoModelForImageClassification if is_vision_available(): from transformers import AutoImageProcessor @require_torch @require_vision class _snake_case (unittest.TestCase): @slow def UpperCamelCase__ ( self ): UpperCAmelCase_ : int = AutoImageProcessor.from_pretrained("microsoft/dit-base-finetuned-rvlcdip" ) UpperCAmelCase_ : Tuple = AutoModelForImageClassification.from_pretrained("microsoft/dit-base-finetuned-rvlcdip" ) model.to(_snake_case ) from datasets import load_dataset UpperCAmelCase_ : Tuple = load_dataset("nielsr/rvlcdip-demo" ) UpperCAmelCase_ : Dict = dataset["train"][0]["image"].convert("RGB" ) UpperCAmelCase_ : Optional[Any] = image_processor(_snake_case ,return_tensors="pt" ).to(_snake_case ) # forward pass with torch.no_grad(): UpperCAmelCase_ : Optional[int] = model(**_snake_case ) UpperCAmelCase_ : Any = outputs.logits UpperCAmelCase_ : List[Any] = torch.Size((1, 16) ) self.assertEqual(logits.shape ,_snake_case ) UpperCAmelCase_ : Dict = torch.tensor( [-0.4158, -0.4092, -0.4347] ,device=_snake_case ,dtype=torch.float ,) self.assertTrue(torch.allclose(logits[0, :3] ,_snake_case ,atol=1E-4 ) )
71
from collections import defaultdict from math import ceil, sqrt def A_ ( _UpperCAmelCase = 1_00_00_00 , _UpperCAmelCase = 10 ): SCREAMING_SNAKE_CASE_: defaultdict = defaultdict(_UpperCAmelCase ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: SCREAMING_SNAKE_CASE_: Tuple = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: SCREAMING_SNAKE_CASE_: Optional[Any] = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(_UpperCAmelCase , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(f'''{solution() = }''')
671
0
'''simple docstring''' from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split _UpperCAmelCase : List[Any] = datasets.load_iris() _UpperCAmelCase : Dict = np.array(data['''data''']) _UpperCAmelCase : Union[str, Any] = np.array(data['''target''']) _UpperCAmelCase : int = data['''target_names'''] _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase : Union[str, Any] = train_test_split(X, y) def UpperCamelCase ( lowercase_ : str , lowercase_ : Optional[Any] ) -> int: '''simple docstring''' return np.linalg.norm(np.array(lowercase_ ) - np.array(lowercase_ ) ) def UpperCamelCase ( lowercase_ : Any , lowercase_ : Any , lowercase_ : int , lowercase_ : Tuple , lowercase_ : Tuple=5 ) -> List[Any]: '''simple docstring''' lowercase =zip(lowercase_ , lowercase_ ) # List of distances of all points from the point to be classified lowercase =[] for data_point in data: lowercase =euclidean_distance(data_point[0] , lowercase_ ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. lowercase =[i[1] for i in sorted(lowercase_ )[:k]] # Most commonly occurring class among them # is the class into which the point is classified lowercase =Counter(lowercase_ ).most_common(1 )[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
72
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCAmelCase : str = { """configuration_xlm""": ["""XLM_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLMConfig""", """XLMOnnxConfig"""], """tokenization_xlm""": ["""XLMTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : Dict = [ """XLM_PRETRAINED_MODEL_ARCHIVE_LIST""", """XLMForMultipleChoice""", """XLMForQuestionAnswering""", """XLMForQuestionAnsweringSimple""", """XLMForSequenceClassification""", """XLMForTokenClassification""", """XLMModel""", """XLMPreTrainedModel""", """XLMWithLMHeadModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : List[str] = [ """TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFXLMForMultipleChoice""", """TFXLMForQuestionAnsweringSimple""", """TFXLMForSequenceClassification""", """TFXLMForTokenClassification""", """TFXLMMainLayer""", """TFXLMModel""", """TFXLMPreTrainedModel""", """TFXLMWithLMHeadModel""", ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys lowerCAmelCase : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
671
0
import unittest from transformers import BigBirdTokenizer, BigBirdTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin a_ : List[str] = '▁' a_ : str = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class _snake_case ( A__ , unittest.TestCase ): _lowercase : str = BigBirdTokenizer _lowercase : Any = BigBirdTokenizerFast _lowercase : Tuple = True _lowercase : int = True def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: super().setUp() SCREAMING_SNAKE_CASE = self.tokenizer_class(a , keep_accents=a) tokenizer.save_pretrained(self.tmpdirname) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = '<s>' SCREAMING_SNAKE_CASE = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a) , a) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a) , a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , '<unk>') self.assertEqual(vocab_keys[1] , '<s>') self.assertEqual(vocab_keys[-1] , '[MASK]') self.assertEqual(len(a) , 1004) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: self.assertEqual(self.get_tokenizer().vocab_size , 1000) def SCREAMING_SNAKE_CASE__ ( self) -> str: if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE = 'I was born in 92000, and this is falsé.' SCREAMING_SNAKE_CASE = tokenizer.tokenize(a) SCREAMING_SNAKE_CASE = rust_tokenizer.tokenize(a) self.assertListEqual(a , a) SCREAMING_SNAKE_CASE = tokenizer.encode(a , add_special_tokens=a) SCREAMING_SNAKE_CASE = rust_tokenizer.encode(a , add_special_tokens=a) self.assertListEqual(a , a) SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE = tokenizer.encode(a) SCREAMING_SNAKE_CASE = rust_tokenizer.encode(a) self.assertListEqual(a , a) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = BigBirdTokenizer(a , keep_accents=a) SCREAMING_SNAKE_CASE = tokenizer.tokenize('This is a test') self.assertListEqual(a , ['▁This', '▁is', '▁a', '▁t', 'est']) self.assertListEqual( tokenizer.convert_tokens_to_ids(a) , [285, 46, 10, 170, 382] , ) SCREAMING_SNAKE_CASE = tokenizer.tokenize('I was born in 92000, and this is falsé.') self.assertListEqual( a , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(a) self.assertListEqual( a , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(a) self.assertListEqual( a , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) @cached_property def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return BigBirdTokenizer.from_pretrained('google/bigbird-roberta-base') @slow def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = 'Hello World!' SCREAMING_SNAKE_CASE = [65, 1_8536, 2260, 101, 66] self.assertListEqual(a , self.big_tokenizer.encode(a)) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = ( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth' ) # fmt: off SCREAMING_SNAKE_CASE = [65, 871, 419, 358, 946, 991, 2521, 452, 358, 1357, 387, 7751, 3536, 112, 985, 456, 126, 865, 938, 5400, 5734, 458, 1368, 467, 786, 2462, 5246, 1159, 633, 865, 4519, 457, 582, 852, 2557, 427, 916, 508, 405, 3_4324, 497, 391, 408, 1_1342, 1244, 385, 100, 938, 985, 456, 574, 362, 1_2597, 3200, 3129, 1172, 66] # noqa: E231 # fmt: on self.assertListEqual(a , self.big_tokenizer.encode(a)) @require_torch @slow def SCREAMING_SNAKE_CASE__ ( self) -> Any: import torch from transformers import BigBirdConfig, BigBirdModel # Build sequence SCREAMING_SNAKE_CASE = list(self.big_tokenizer.get_vocab().keys())[:10] SCREAMING_SNAKE_CASE = ' '.join(a) SCREAMING_SNAKE_CASE = self.big_tokenizer.encode_plus(a , return_tensors='pt' , return_token_type_ids=a) SCREAMING_SNAKE_CASE = self.big_tokenizer.batch_encode_plus( [sequence + ' ' + sequence] , return_tensors='pt' , return_token_type_ids=a) SCREAMING_SNAKE_CASE = BigBirdConfig(attention_type='original_full') SCREAMING_SNAKE_CASE = BigBirdModel(a) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**a) model(**a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = BigBirdTokenizer.from_pretrained('google/bigbird-roberta-base') SCREAMING_SNAKE_CASE = tokenizer.decode(tokenizer('Paris is the [MASK].').input_ids) self.assertTrue(decoded_text == '[CLS] Paris is the[MASK].[SEP]') @slow def SCREAMING_SNAKE_CASE__ ( self) -> Dict: # fmt: off SCREAMING_SNAKE_CASE = {'input_ids': [[65, 3_9286, 458, 3_6335, 2001, 456, 1_3073, 1_3266, 455, 113, 7746, 1741, 1_1157, 391, 1_3073, 1_3266, 455, 113, 3967, 3_5412, 113, 4936, 109, 3870, 2377, 113, 3_0084, 4_5720, 458, 134, 1_7496, 112, 503, 1_1672, 113, 118, 112, 5665, 1_3347, 3_8687, 112, 1496, 3_1389, 112, 3268, 4_7264, 134, 962, 112, 1_6377, 8035, 2_3130, 430, 1_2169, 1_5518, 2_8592, 458, 146, 4_1697, 109, 391, 1_2169, 1_5518, 1_6689, 458, 146, 4_1358, 109, 452, 726, 4034, 111, 763, 3_5412, 5082, 388, 1903, 111, 9051, 391, 2870, 4_8918, 1900, 1123, 550, 998, 112, 9586, 1_5985, 455, 391, 410, 2_2955, 3_7636, 114, 66], [65, 448, 1_7496, 419, 3663, 385, 763, 113, 2_7533, 2870, 3283, 1_3043, 1639, 2_4713, 523, 656, 2_4013, 1_8550, 2521, 517, 2_7014, 2_1244, 420, 1212, 1465, 391, 927, 4833, 388, 578, 1_1786, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [65, 484, 2169, 7687, 2_1932, 1_8146, 726, 363, 1_7032, 3391, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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], [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]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a , model_name='google/bigbird-roberta-base' , revision='215c99f1600e06f83acce68422f2035b2b5c3510' , )
73
lowerCAmelCase : List[str] = { """A""": ["""B""", """C""", """E"""], """B""": ["""A""", """D""", """E"""], """C""": ["""A""", """F""", """G"""], """D""": ["""B"""], """E""": ["""A""", """B""", """D"""], """F""": ["""C"""], """G""": ["""C"""], } def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Any = set() # keep track of all the paths to be checked SCREAMING_SNAKE_CASE_: Tuple = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue SCREAMING_SNAKE_CASE_: List[Any] = queue.pop(0 ) # get the last node from the path SCREAMING_SNAKE_CASE_: Tuple = path[-1] if node not in explored: SCREAMING_SNAKE_CASE_: Union[str, Any] = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: SCREAMING_SNAKE_CASE_: int = list(_UpperCAmelCase ) new_path.append(_UpperCAmelCase ) queue.append(_UpperCAmelCase ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(_UpperCAmelCase ) # in case there's no path between the 2 nodes return [] def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 SCREAMING_SNAKE_CASE_: List[Any] = [start] SCREAMING_SNAKE_CASE_: List[str] = set(_UpperCAmelCase ) # Keep tab on distances from `start` node. SCREAMING_SNAKE_CASE_: Union[str, Any] = {start: 0, target: -1} while queue: SCREAMING_SNAKE_CASE_: Dict = queue.pop(0 ) if node == target: SCREAMING_SNAKE_CASE_: Tuple = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(_UpperCAmelCase ) queue.append(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, """G""", """D""")) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, """G""", """D""")) # returns 4
671
0
import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference from . import IFPipelineTesterMixin @skip_mps class __UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ): """simple docstring""" lowerCAmelCase_ = IFPipeline lowerCAmelCase_ = TEXT_TO_IMAGE_PARAMS - {'''width''', '''height''', '''latents'''} lowerCAmelCase_ = TEXT_TO_IMAGE_BATCH_PARAMS lowerCAmelCase_ = PipelineTesterMixin.required_optional_params - {'''latents'''} def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" return self._get_dummy_components() def UpperCAmelCase__ ( self : Optional[int] , _A : Dict , _A : Dict=0 ): """simple docstring""" if str(_A ).startswith('''mps''' ): __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.manual_seed(_A ) else: __SCREAMING_SNAKE_CASE : Optional[Any] = torch.Generator(device=_A ).manual_seed(_A ) __SCREAMING_SNAKE_CASE : Optional[int] = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def UpperCAmelCase__ ( self : List[Any] ): """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != '''cuda''' , reason='''float16 requires CUDA''' ) def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" super().test_save_load_floataa(expected_max_diff=1e-1 ) def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" self._test_save_load_local() def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1e-2 , ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) @slow @require_torch_gpu class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Any ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = IFPipeline.from_pretrained('''DeepFloyd/IF-I-XL-v1.0''' , variant='''fp16''' , torch_dtype=torch.floataa ) __SCREAMING_SNAKE_CASE : int = IFSuperResolutionPipeline.from_pretrained( '''DeepFloyd/IF-II-L-v1.0''' , variant='''fp16''' , torch_dtype=torch.floataa , text_encoder=_A , tokenizer=_A ) # pre compute text embeddings and remove T5 to save memory pipe_a.text_encoder.to('''cuda''' ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Optional[int] = pipe_a.encode_prompt('''anime turtle''' , device='''cuda''' ) del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() __SCREAMING_SNAKE_CASE : List[Any] = None __SCREAMING_SNAKE_CASE : str = None pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if(_A , _A , _A , _A ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # img2img __SCREAMING_SNAKE_CASE : Dict = IFImgaImgPipeline(**pipe_a.components ) __SCREAMING_SNAKE_CASE : int = IFImgaImgSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_imgaimg(_A , _A , _A , _A ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # inpainting __SCREAMING_SNAKE_CASE : int = IFInpaintingPipeline(**pipe_a.components ) __SCREAMING_SNAKE_CASE : Dict = IFInpaintingSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_inpainting(_A , _A , _A , _A ) def UpperCAmelCase__ ( self : Optional[Any] , _A : str , _A : Optional[Any] , _A : Tuple , _A : List[str] ): """simple docstring""" _start_torch_memory_measurement() __SCREAMING_SNAKE_CASE : List[Any] = torch.Generator(device='''cpu''' ).manual_seed(0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = pipe_a( prompt_embeds=_A , negative_prompt_embeds=_A , num_inference_steps=2 , generator=_A , output_type='''np''' , ) __SCREAMING_SNAKE_CASE : int = output.images[0] assert image.shape == (64, 64, 3) __SCREAMING_SNAKE_CASE : Dict = torch.cuda.max_memory_allocated() assert mem_bytes < 13 * 10**9 __SCREAMING_SNAKE_CASE : List[str] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy''' ) assert_mean_pixel_difference(_A , _A ) # pipeline 2 _start_torch_memory_measurement() __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Generator(device='''cpu''' ).manual_seed(0 ) __SCREAMING_SNAKE_CASE : Dict = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(_A ) __SCREAMING_SNAKE_CASE : int = pipe_a( prompt_embeds=_A , negative_prompt_embeds=_A , image=_A , generator=_A , num_inference_steps=2 , output_type='''np''' , ) __SCREAMING_SNAKE_CASE : int = output.images[0] assert image.shape == (256, 256, 3) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 __SCREAMING_SNAKE_CASE : Optional[int] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(_A , _A ) def UpperCAmelCase__ ( self : Dict , _A : Optional[Any] , _A : List[Any] , _A : Optional[int] , _A : Union[str, Any] ): """simple docstring""" _start_torch_memory_measurement() __SCREAMING_SNAKE_CASE : Optional[int] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(_A ) __SCREAMING_SNAKE_CASE : Optional[Any] = torch.Generator(device='''cpu''' ).manual_seed(0 ) __SCREAMING_SNAKE_CASE : List[Any] = pipe_a( prompt_embeds=_A , negative_prompt_embeds=_A , image=_A , num_inference_steps=2 , generator=_A , output_type='''np''' , ) __SCREAMING_SNAKE_CASE : Any = output.images[0] assert image.shape == (64, 64, 3) __SCREAMING_SNAKE_CASE : List[str] = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 __SCREAMING_SNAKE_CASE : Any = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy''' ) assert_mean_pixel_difference(_A , _A ) # pipeline 2 _start_torch_memory_measurement() __SCREAMING_SNAKE_CASE : Tuple = torch.Generator(device='''cpu''' ).manual_seed(0 ) __SCREAMING_SNAKE_CASE : Optional[int] = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(_A ) __SCREAMING_SNAKE_CASE : Optional[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(_A ) __SCREAMING_SNAKE_CASE : Optional[int] = pipe_a( prompt_embeds=_A , negative_prompt_embeds=_A , image=_A , original_image=_A , generator=_A , num_inference_steps=2 , output_type='''np''' , ) __SCREAMING_SNAKE_CASE : List[Any] = output.images[0] assert image.shape == (256, 256, 3) __SCREAMING_SNAKE_CASE : Dict = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 __SCREAMING_SNAKE_CASE : List[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(_A , _A ) def UpperCAmelCase__ ( self : Optional[int] , _A : List[str] , _A : List[str] , _A : Any , _A : Dict ): """simple docstring""" _start_torch_memory_measurement() __SCREAMING_SNAKE_CASE : Tuple = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(_A ) __SCREAMING_SNAKE_CASE : Union[str, Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(1 ) ).to(_A ) __SCREAMING_SNAKE_CASE : int = torch.Generator(device='''cpu''' ).manual_seed(0 ) __SCREAMING_SNAKE_CASE : Tuple = pipe_a( prompt_embeds=_A , negative_prompt_embeds=_A , image=_A , mask_image=_A , num_inference_steps=2 , generator=_A , output_type='''np''' , ) __SCREAMING_SNAKE_CASE : List[Any] = output.images[0] assert image.shape == (64, 64, 3) __SCREAMING_SNAKE_CASE : int = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 __SCREAMING_SNAKE_CASE : Dict = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy''' ) assert_mean_pixel_difference(_A , _A ) # pipeline 2 _start_torch_memory_measurement() __SCREAMING_SNAKE_CASE : Dict = torch.Generator(device='''cpu''' ).manual_seed(0 ) __SCREAMING_SNAKE_CASE : int = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(_A ) __SCREAMING_SNAKE_CASE : Optional[Any] = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(_A ) __SCREAMING_SNAKE_CASE : Tuple = floats_tensor((1, 3, 256, 256) , rng=random.Random(1 ) ).to(_A ) __SCREAMING_SNAKE_CASE : Optional[Any] = pipe_a( prompt_embeds=_A , negative_prompt_embeds=_A , image=_A , mask_image=_A , original_image=_A , generator=_A , num_inference_steps=2 , output_type='''np''' , ) __SCREAMING_SNAKE_CASE : Union[str, Any] = output.images[0] assert image.shape == (256, 256, 3) __SCREAMING_SNAKE_CASE : List[str] = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 __SCREAMING_SNAKE_CASE : List[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(_A , _A ) def a__ ( ): """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
74
from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class __lowercase ( UpperCAmelCase_ ): """simple docstring""" def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowerCAmelCase__ : float): return 0.0 def A_ ( _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: List[str] = min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] ) SCREAMING_SNAKE_CASE_: Dict = max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def A_ ( _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[int] = 5_12 SCREAMING_SNAKE_CASE_: str = [1] + [0] * (size - 1) SCREAMING_SNAKE_CASE_: Dict = [filter_type.process(_UpperCAmelCase ) for item in inputs] SCREAMING_SNAKE_CASE_: Optional[Any] = [0] * (samplerate - size) # zero-padding outputs += filler SCREAMING_SNAKE_CASE_: Tuple = np.abs(np.fft.fft(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE_: Optional[Any] = 20 * np.logaa(_UpperCAmelCase ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel("Frequency (Hz)" ) plt.xscale("log" ) # Display within reasonable bounds SCREAMING_SNAKE_CASE_: Any = get_bounds(_UpperCAmelCase , _UpperCAmelCase ) plt.ylim(max([-80, bounds[0]] ) , min([80, bounds[1]] ) ) plt.ylabel("Gain (dB)" ) plt.plot(_UpperCAmelCase ) plt.show() def A_ ( _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[int] = 5_12 SCREAMING_SNAKE_CASE_: Union[str, Any] = [1] + [0] * (size - 1) SCREAMING_SNAKE_CASE_: Dict = [filter_type.process(_UpperCAmelCase ) for item in inputs] SCREAMING_SNAKE_CASE_: int = [0] * (samplerate - size) # zero-padding outputs += filler SCREAMING_SNAKE_CASE_: Any = np.angle(np.fft.fft(_UpperCAmelCase ) ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel("Frequency (Hz)" ) plt.xscale("log" ) plt.ylim(-2 * pi , 2 * pi ) plt.ylabel("Phase shift (Radians)" ) plt.plot(np.unwrap(_UpperCAmelCase , -2 * pi ) ) plt.show()
671
0
'''simple docstring''' import os from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen, xsplitext from ..table import array_cast from ..utils.py_utils import no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: from .features import FeatureType UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = False, False, False @dataclass class lowerCamelCase_ : lowerCAmelCase__ = None lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = None # Automatically constructed lowerCAmelCase__ = "dict" lowerCAmelCase__ = pa.struct({'bytes': pa.binary(), 'path': pa.string()} ) lowerCAmelCase__ = field(default='Audio' , init=__a , repr=__a ) def __call__( self : Optional[int] ): '''simple docstring''' return self.pa_type def lowercase_ ( self : Dict , _A : Union[str, bytes, dict] ): '''simple docstring''' try: import soundfile as sf # soundfile is a dependency of librosa, needed to decode audio files. except ImportError as err: raise ImportError('''To support encoding audio data, please install \'soundfile\'.''' ) from err if isinstance(_A , _A ): return {"bytes": None, "path": value} elif isinstance(_A , _A ): return {"bytes": value, "path": None} elif "array" in value: # convert the audio array to wav bytes UpperCAmelCase__ : Optional[int] = BytesIO() sf.write(_A , value['''array'''] , value['''sampling_rate'''] , format='''wav''' ) return {"bytes": buffer.getvalue(), "path": None} elif value.get('''path''' ) is not None and os.path.isfile(value['''path'''] ): # we set "bytes": None to not duplicate the data if they're already available locally if value["path"].endswith('''pcm''' ): # "PCM" only has raw audio bytes if value.get('''sampling_rate''' ) is None: # At least, If you want to convert "PCM-byte" to "WAV-byte", you have to know sampling rate raise KeyError('''To use PCM files, please specify a \'sampling_rate\' in Audio object''' ) if value.get('''bytes''' ): # If we already had PCM-byte, we don`t have to make "read file, make bytes" (just use it!) UpperCAmelCase__ : Dict = np.frombuffer(value['''bytes'''] , dtype=np.intaa ).astype(np.floataa ) / 32_767 else: UpperCAmelCase__ : Optional[int] = np.memmap(value['''path'''] , dtype='''h''' , mode='''r''' ).astype(np.floataa ) / 32_767 UpperCAmelCase__ : Tuple = BytesIO(bytes() ) sf.write(_A , _A , value['''sampling_rate'''] , format='''wav''' ) return {"bytes": buffer.getvalue(), "path": None} else: return {"bytes": None, "path": value.get('''path''' )} elif value.get('''bytes''' ) is not None or value.get('''path''' ) is not None: # store the audio bytes, and path is used to infer the audio format using the file extension return {"bytes": value.get('''bytes''' ), "path": value.get('''path''' )} else: raise ValueError( f"""An audio sample should have one of 'path' or 'bytes' but they are missing or None in {value}.""" ) def lowercase_ ( self : Tuple , _A : dict , _A : Optional[Dict[str, Union[str, bool, None]]] = None ): '''simple docstring''' if not self.decode: raise RuntimeError('''Decoding is disabled for this feature. Please use Audio(decode=True) instead.''' ) UpperCAmelCase__ , UpperCAmelCase__ : List[str] = (value['''path'''], BytesIO(value['''bytes'''] )) if value['''bytes'''] is not None else (value['''path'''], None) if path is None and file is None: raise ValueError(f"""An audio sample should have one of 'path' or 'bytes' but both are None in {value}.""" ) try: import librosa import soundfile as sf except ImportError as err: raise ImportError('''To support decoding audio files, please install \'librosa\' and \'soundfile\'.''' ) from err UpperCAmelCase__ : Optional[Any] = xsplitext(_A )[1][1:].lower() if path is not None else None if not config.IS_OPUS_SUPPORTED and audio_format == "opus": raise RuntimeError( '''Decoding \'opus\' files requires system library \'libsndfile\'>=1.0.31, ''' '''You can try to update `soundfile` python library: `pip install "soundfile>=0.12.1"`. ''' ) elif not config.IS_MP3_SUPPORTED and audio_format == "mp3": raise RuntimeError( '''Decoding \'mp3\' files requires system library \'libsndfile\'>=1.1.0, ''' '''You can try to update `soundfile` python library: `pip install "soundfile>=0.12.1"`. ''' ) if file is None: UpperCAmelCase__ : Tuple = token_per_repo_id or {} UpperCAmelCase__ : Optional[Any] = path.split('''::''' )[-1] try: UpperCAmelCase__ : int = string_to_dict(_A , config.HUB_DATASETS_URL )['''repo_id'''] UpperCAmelCase__ : Union[str, Any] = token_per_repo_id[repo_id] except (ValueError, KeyError): UpperCAmelCase__ : List[str] = None with xopen(_A , '''rb''' , use_auth_token=_A ) as f: UpperCAmelCase__ , UpperCAmelCase__ : str = sf.read(_A ) else: UpperCAmelCase__ , UpperCAmelCase__ : str = sf.read(_A ) UpperCAmelCase__ : int = array.T if self.mono: UpperCAmelCase__ : str = librosa.to_mono(_A ) if self.sampling_rate and self.sampling_rate != sampling_rate: UpperCAmelCase__ : Optional[Any] = librosa.resample(_A , orig_sr=_A , target_sr=self.sampling_rate ) UpperCAmelCase__ : int = self.sampling_rate return {"path": path, "array": array, "sampling_rate": sampling_rate} def lowercase_ ( self : Dict ): '''simple docstring''' from .features import Value if self.decode: raise ValueError('''Cannot flatten a decoded Audio feature.''' ) return { "bytes": Value('''binary''' ), "path": Value('''string''' ), } def lowercase_ ( self : str , _A : Union[pa.StringArray, pa.StructArray] ): '''simple docstring''' if pa.types.is_string(storage.type ): UpperCAmelCase__ : Optional[Any] = pa.array([None] * len(_A ) , type=pa.binary() ) UpperCAmelCase__ : List[Any] = pa.StructArray.from_arrays([bytes_array, storage] , ['''bytes''', '''path'''] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): UpperCAmelCase__ : Optional[int] = pa.array([None] * len(_A ) , type=pa.string() ) UpperCAmelCase__ : int = pa.StructArray.from_arrays([storage, path_array] , ['''bytes''', '''path'''] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ) and storage.type.get_all_field_indices('''array''' ): UpperCAmelCase__ : List[Any] = pa.array([Audio().encode_example(_A ) if x is not None else None for x in storage.to_pylist()] ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index('''bytes''' ) >= 0: UpperCAmelCase__ : Optional[Any] = storage.field('''bytes''' ) else: UpperCAmelCase__ : Any = pa.array([None] * len(_A ) , type=pa.binary() ) if storage.type.get_field_index('''path''' ) >= 0: UpperCAmelCase__ : List[Any] = storage.field('''path''' ) else: UpperCAmelCase__ : List[str] = pa.array([None] * len(_A ) , type=pa.string() ) UpperCAmelCase__ : Tuple = pa.StructArray.from_arrays([bytes_array, path_array] , ['''bytes''', '''path'''] , mask=storage.is_null() ) return array_cast(_A , self.pa_type ) def lowercase_ ( self : Tuple , _A : pa.StructArray ): '''simple docstring''' @no_op_if_value_is_null def path_to_bytes(_A : Optional[Any] ): with xopen(_A , '''rb''' ) as f: UpperCAmelCase__ : List[str] = f.read() return bytes_ UpperCAmelCase__ : Any = pa.array( [ (path_to_bytes(x['''path'''] ) if x['''bytes'''] is None else x['''bytes''']) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) UpperCAmelCase__ : Tuple = pa.array( [os.path.basename(_A ) if path is not None else None for path in storage.field('''path''' ).to_pylist()] , type=pa.string() , ) UpperCAmelCase__ : List[str] = pa.StructArray.from_arrays([bytes_array, path_array] , ['''bytes''', '''path'''] , mask=bytes_array.is_null() ) return array_cast(_A , self.pa_type )
75
from __future__ import annotations from math import ceil, floor, sqrt def A_ ( _UpperCAmelCase = 2_00_00_00 ): SCREAMING_SNAKE_CASE_: list[int] = [0] SCREAMING_SNAKE_CASE_: int for idx in range(1 , ceil(sqrt(target * 2 ) * 1.1 ) ): triangle_numbers.append(triangle_numbers[-1] + idx ) # we want this to be as close as possible to target SCREAMING_SNAKE_CASE_: int = 0 # the area corresponding to the grid that gives the product closest to target SCREAMING_SNAKE_CASE_: int = 0 # an estimate of b, using the quadratic formula SCREAMING_SNAKE_CASE_: float # the largest integer less than b_estimate SCREAMING_SNAKE_CASE_: int # the largest integer less than b_estimate SCREAMING_SNAKE_CASE_: int # the triangle number corresponding to b_floor SCREAMING_SNAKE_CASE_: int # the triangle number corresponding to b_ceil SCREAMING_SNAKE_CASE_: int for idx_a, triangle_a in enumerate(triangle_numbers[1:] , 1 ): SCREAMING_SNAKE_CASE_: List[Any] = (-1 + sqrt(1 + 8 * target / triangle_a )) / 2 SCREAMING_SNAKE_CASE_: Any = floor(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] = ceil(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Any = triangle_numbers[b_floor] SCREAMING_SNAKE_CASE_: List[Any] = triangle_numbers[b_ceil] if abs(target - triangle_b_first_guess * triangle_a ) < abs( target - best_product ): SCREAMING_SNAKE_CASE_: int = triangle_b_first_guess * triangle_a SCREAMING_SNAKE_CASE_: int = idx_a * b_floor if abs(target - triangle_b_second_guess * triangle_a ) < abs( target - best_product ): SCREAMING_SNAKE_CASE_: Optional[Any] = triangle_b_second_guess * triangle_a SCREAMING_SNAKE_CASE_: Tuple = idx_a * b_ceil return area if __name__ == "__main__": print(f'''{solution() = }''')
671
0
"""simple docstring""" import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv("TEST_SAGEMAKER" , "False" ) ) is not True , reason="Skipping test because should only be run when releasing minor transformers version" , ) @pytest.mark.usefixtures("sm_env" ) @parameterized_class( [ { "framework": "pytorch", "script": "run_glue.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.p3.16xlarge", "results": {"train_runtime": 6_50, "eval_accuracy": 0.7, "eval_loss": 0.6}, }, { "framework": "pytorch", "script": "run_ddp.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.p3.16xlarge", "results": {"train_runtime": 6_00, "eval_accuracy": 0.7, "eval_loss": 0.6}, }, { "framework": "tensorflow", "script": "run_tf_dist.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.p3.16xlarge", "results": {"train_runtime": 6_00, "eval_accuracy": 0.6, "eval_loss": 0.7}, }, ] ) class UpperCAmelCase_ ( unittest.TestCase ): def _lowerCamelCase ( self ) -> Optional[Any]: if self.framework == "pytorch": subprocess.run( F"""cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py""".split() , encoding='''utf-8''' , check=UpperCamelCase_ , ) assert hasattr(self , '''env''' ) def _lowerCamelCase ( self , UpperCamelCase_ ) -> Union[str, Any]: __lowercase : str = F"""{self.env.base_job_name}-{instance_count}-{"ddp" if "ddp" in self.script else "smd"}""" # distributed data settings __lowercase : List[str] = {'''smdistributed''': {'''dataparallel''': {'''enabled''': True}}} if self.script != '''run_ddp.py''' else None # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=UpperCamelCase_ , instance_count=UpperCamelCase_ , instance_type=self.instance_type , debugger_hook_config=UpperCamelCase_ , hyperparameters={**self.env.distributed_hyperparameters, '''model_name_or_path''': self.model_name_or_path} , metric_definitions=self.env.metric_definitions , distribution=UpperCamelCase_ , py_version='''py36''' , ) def _lowerCamelCase ( self , UpperCamelCase_ ) -> List[Any]: TrainingJobAnalytics(UpperCamelCase_ ).export_csv(F"""{self.env.test_path}/{job_name}_metrics.csv""" ) @parameterized.expand([(2,)] ) def _lowerCamelCase ( self , UpperCamelCase_ ) -> Any: # create estimator __lowercase : List[str] = self.create_estimator(UpperCamelCase_ ) # run training estimator.fit() # result dataframe __lowercase : Dict = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __lowercase : int = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) __lowercase : Optional[Any] = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowercase : int = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 99_99_99 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy ) assert all(t <= self.results['''eval_loss'''] for t in eval_loss ) # dump tests result into json file to share in PR with open(F"""{estimator.latest_training_job.name}.json""" , '''w''' ) as outfile: json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss} , UpperCamelCase_ )
76
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase : Optional[int] = { """configuration_longformer""": [ """LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LongformerConfig""", """LongformerOnnxConfig""", ], """tokenization_longformer""": ["""LongformerTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : List[str] = ["""LongformerTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : Union[str, Any] = [ """LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """LongformerForMaskedLM""", """LongformerForMultipleChoice""", """LongformerForQuestionAnswering""", """LongformerForSequenceClassification""", """LongformerForTokenClassification""", """LongformerModel""", """LongformerPreTrainedModel""", """LongformerSelfAttention""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : int = [ """TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFLongformerForMaskedLM""", """TFLongformerForMultipleChoice""", """TFLongformerForQuestionAnswering""", """TFLongformerForSequenceClassification""", """TFLongformerForTokenClassification""", """TFLongformerModel""", """TFLongformerPreTrainedModel""", """TFLongformerSelfAttention""", ] if TYPE_CHECKING: from .configuration_longformer import ( LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, LongformerConfig, LongformerOnnxConfig, ) from .tokenization_longformer import LongformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_longformer_fast import LongformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longformer import ( LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, LongformerForMaskedLM, LongformerForMultipleChoice, LongformerForQuestionAnswering, LongformerForSequenceClassification, LongformerForTokenClassification, LongformerModel, LongformerPreTrainedModel, LongformerSelfAttention, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_longformer import ( TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFLongformerForMaskedLM, TFLongformerForMultipleChoice, TFLongformerForQuestionAnswering, TFLongformerForSequenceClassification, TFLongformerForTokenClassification, TFLongformerModel, TFLongformerPreTrainedModel, TFLongformerSelfAttention, ) else: import sys lowerCAmelCase : Optional[int] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
671
0
"""simple docstring""" def _UpperCamelCase ( UpperCamelCase , UpperCamelCase ) -> str: """simple docstring""" __UpperCAmelCase : Any = "" for word_or_phrase in separated: if not isinstance(UpperCamelCase , UpperCamelCase ): raise Exception("join() accepts only strings to be joined" ) joined += word_or_phrase + separator return joined.strip(UpperCamelCase ) if __name__ == "__main__": from doctest import testmod testmod()
77
import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# lowerCAmelCase : Optional[int] = [ # (stable-diffusion, HF Diffusers) ("""time_embed.0.weight""", """time_embedding.linear_1.weight"""), ("""time_embed.0.bias""", """time_embedding.linear_1.bias"""), ("""time_embed.2.weight""", """time_embedding.linear_2.weight"""), ("""time_embed.2.bias""", """time_embedding.linear_2.bias"""), ("""input_blocks.0.0.weight""", """conv_in.weight"""), ("""input_blocks.0.0.bias""", """conv_in.bias"""), ("""out.0.weight""", """conv_norm_out.weight"""), ("""out.0.bias""", """conv_norm_out.bias"""), ("""out.2.weight""", """conv_out.weight"""), ("""out.2.bias""", """conv_out.bias"""), ] lowerCAmelCase : str = [ # (stable-diffusion, HF Diffusers) ("""in_layers.0""", """norm1"""), ("""in_layers.2""", """conv1"""), ("""out_layers.0""", """norm2"""), ("""out_layers.3""", """conv2"""), ("""emb_layers.1""", """time_emb_proj"""), ("""skip_connection""", """conv_shortcut"""), ] lowerCAmelCase : List[str] = [] # hardcoded number of downblocks and resnets/attentions... # would need smarter logic for other networks. for i in range(4): # loop over downblocks/upblocks for j in range(2): # loop over resnets/attentions for downblocks lowerCAmelCase : int = f'''down_blocks.{i}.resnets.{j}.''' lowerCAmelCase : List[str] = f'''input_blocks.{3*i + j + 1}.0.''' unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix)) if i < 3: # no attention layers in down_blocks.3 lowerCAmelCase : Any = f'''down_blocks.{i}.attentions.{j}.''' lowerCAmelCase : List[Any] = f'''input_blocks.{3*i + j + 1}.1.''' unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix)) for j in range(3): # loop over resnets/attentions for upblocks lowerCAmelCase : Any = f'''up_blocks.{i}.resnets.{j}.''' lowerCAmelCase : str = f'''output_blocks.{3*i + j}.0.''' unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix)) if i > 0: # no attention layers in up_blocks.0 lowerCAmelCase : List[Any] = f'''up_blocks.{i}.attentions.{j}.''' lowerCAmelCase : str = f'''output_blocks.{3*i + j}.1.''' unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix)) if i < 3: # no downsample in down_blocks.3 lowerCAmelCase : Any = f'''down_blocks.{i}.downsamplers.0.conv.''' lowerCAmelCase : Tuple = f'''input_blocks.{3*(i+1)}.0.op.''' unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix)) # no upsample in up_blocks.3 lowerCAmelCase : Tuple = f'''up_blocks.{i}.upsamplers.0.''' lowerCAmelCase : Tuple = f'''output_blocks.{3*i + 2}.{1 if i == 0 else 2}.''' unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix)) lowerCAmelCase : Any = """mid_block.attentions.0.""" lowerCAmelCase : Dict = """middle_block.1.""" unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix)) for j in range(2): lowerCAmelCase : int = f'''mid_block.resnets.{j}.''' lowerCAmelCase : Union[str, Any] = f'''middle_block.{2*j}.''' unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix)) def A_ ( _UpperCAmelCase ): # buyer beware: this is a *brittle* function, # and correct output requires that all of these pieces interact in # the exact order in which I have arranged them. SCREAMING_SNAKE_CASE_: Dict = {k: k for k in unet_state_dict.keys()} for sd_name, hf_name in unet_conversion_map: SCREAMING_SNAKE_CASE_: Optional[int] = sd_name for k, v in mapping.items(): if "resnets" in k: for sd_part, hf_part in unet_conversion_map_resnet: SCREAMING_SNAKE_CASE_: Any = v.replace(_UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: str = v for k, v in mapping.items(): for sd_part, hf_part in unet_conversion_map_layer: SCREAMING_SNAKE_CASE_: Optional[Any] = v.replace(_UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] = v SCREAMING_SNAKE_CASE_: Optional[Any] = {v: unet_state_dict[k] for k, v in mapping.items()} return new_state_dict # ================# # VAE Conversion # # ================# lowerCAmelCase : Union[str, Any] = [ # (stable-diffusion, HF Diffusers) ("""nin_shortcut""", """conv_shortcut"""), ("""norm_out""", """conv_norm_out"""), ("""mid.attn_1.""", """mid_block.attentions.0."""), ] for i in range(4): # down_blocks have two resnets for j in range(2): lowerCAmelCase : Union[str, Any] = f'''encoder.down_blocks.{i}.resnets.{j}.''' lowerCAmelCase : Optional[Any] = f'''encoder.down.{i}.block.{j}.''' vae_conversion_map.append((sd_down_prefix, hf_down_prefix)) if i < 3: lowerCAmelCase : Dict = f'''down_blocks.{i}.downsamplers.0.''' lowerCAmelCase : List[str] = f'''down.{i}.downsample.''' vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix)) lowerCAmelCase : List[str] = f'''up_blocks.{i}.upsamplers.0.''' lowerCAmelCase : int = f'''up.{3-i}.upsample.''' vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix)) # up_blocks have three resnets # also, up blocks in hf are numbered in reverse from sd for j in range(3): lowerCAmelCase : Any = f'''decoder.up_blocks.{i}.resnets.{j}.''' lowerCAmelCase : int = f'''decoder.up.{3-i}.block.{j}.''' vae_conversion_map.append((sd_up_prefix, hf_up_prefix)) # this part accounts for mid blocks in both the encoder and the decoder for i in range(2): lowerCAmelCase : str = f'''mid_block.resnets.{i}.''' lowerCAmelCase : Tuple = f'''mid.block_{i+1}.''' vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix)) lowerCAmelCase : List[Any] = [ # (stable-diffusion, HF Diffusers) ("""norm.""", """group_norm."""), ("""q.""", """query."""), ("""k.""", """key."""), ("""v.""", """value."""), ("""proj_out.""", """proj_attn."""), ] def A_ ( _UpperCAmelCase ): # convert HF linear weights to SD conv2d weights return w.reshape(*w.shape , 1 , 1 ) def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[Any] = {k: k for k in vae_state_dict.keys()} for k, v in mapping.items(): for sd_part, hf_part in vae_conversion_map: SCREAMING_SNAKE_CASE_: Union[str, Any] = v.replace(_UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] = v for k, v in mapping.items(): if "attentions" in k: for sd_part, hf_part in vae_conversion_map_attn: SCREAMING_SNAKE_CASE_: Any = v.replace(_UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] = v SCREAMING_SNAKE_CASE_: Tuple = {v: vae_state_dict[k] for k, v in mapping.items()} SCREAMING_SNAKE_CASE_: Union[str, Any] = ["q", "k", "v", "proj_out"] for k, v in new_state_dict.items(): for weight_name in weights_to_convert: if f"mid.attn_1.{weight_name}.weight" in k: print(f"Reshaping {k} for SD format" ) SCREAMING_SNAKE_CASE_: List[str] = reshape_weight_for_sd(_UpperCAmelCase ) return new_state_dict # =========================# # Text Encoder Conversion # # =========================# lowerCAmelCase : Optional[Any] = [ # (stable-diffusion, HF Diffusers) ("""resblocks.""", """text_model.encoder.layers."""), ("""ln_1""", """layer_norm1"""), ("""ln_2""", """layer_norm2"""), (""".c_fc.""", """.fc1."""), (""".c_proj.""", """.fc2."""), (""".attn""", """.self_attn"""), ("""ln_final.""", """transformer.text_model.final_layer_norm."""), ("""token_embedding.weight""", """transformer.text_model.embeddings.token_embedding.weight"""), ("""positional_embedding""", """transformer.text_model.embeddings.position_embedding.weight"""), ] lowerCAmelCase : Optional[Any] = {re.escape(x[1]): x[0] for x in textenc_conversion_lst} lowerCAmelCase : Optional[int] = re.compile("""|""".join(protected.keys())) # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp lowerCAmelCase : str = {"""q""": 0, """k""": 1, """v""": 2} def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: str = {} SCREAMING_SNAKE_CASE_: str = {} SCREAMING_SNAKE_CASE_: List[str] = {} for k, v in text_enc_dict.items(): if ( k.endswith(".self_attn.q_proj.weight" ) or k.endswith(".self_attn.k_proj.weight" ) or k.endswith(".self_attn.v_proj.weight" ) ): SCREAMING_SNAKE_CASE_: str = k[: -len(".q_proj.weight" )] SCREAMING_SNAKE_CASE_: Dict = k[-len("q_proj.weight" )] if k_pre not in capture_qkv_weight: SCREAMING_SNAKE_CASE_: Tuple = [None, None, None] SCREAMING_SNAKE_CASE_: Union[str, Any] = v continue if ( k.endswith(".self_attn.q_proj.bias" ) or k.endswith(".self_attn.k_proj.bias" ) or k.endswith(".self_attn.v_proj.bias" ) ): SCREAMING_SNAKE_CASE_: Union[str, Any] = k[: -len(".q_proj.bias" )] SCREAMING_SNAKE_CASE_: Any = k[-len("q_proj.bias" )] if k_pre not in capture_qkv_bias: SCREAMING_SNAKE_CASE_: List[Any] = [None, None, None] SCREAMING_SNAKE_CASE_: List[str] = v continue SCREAMING_SNAKE_CASE_: int = textenc_pattern.sub(lambda _UpperCAmelCase : protected[re.escape(m.group(0 ) )] , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Dict = v for k_pre, tensors in capture_qkv_weight.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) SCREAMING_SNAKE_CASE_: str = textenc_pattern.sub(lambda _UpperCAmelCase : protected[re.escape(m.group(0 ) )] , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: int = torch.cat(_UpperCAmelCase ) for k_pre, tensors in capture_qkv_bias.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) SCREAMING_SNAKE_CASE_: Optional[int] = textenc_pattern.sub(lambda _UpperCAmelCase : protected[re.escape(m.group(0 ) )] , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] = torch.cat(_UpperCAmelCase ) return new_state_dict def A_ ( _UpperCAmelCase ): return text_enc_dict if __name__ == "__main__": lowerCAmelCase : int = argparse.ArgumentParser() parser.add_argument("""--model_path""", default=None, type=str, required=True, help="""Path to the model to convert.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, required=True, help="""Path to the output model.""") parser.add_argument("""--half""", action="""store_true""", help="""Save weights in half precision.""") parser.add_argument( """--use_safetensors""", action="""store_true""", help="""Save weights use safetensors, default is ckpt.""" ) lowerCAmelCase : Optional[Any] = parser.parse_args() assert args.model_path is not None, "Must provide a model path!" assert args.checkpoint_path is not None, "Must provide a checkpoint path!" # Path for safetensors lowerCAmelCase : int = osp.join(args.model_path, """unet""", """diffusion_pytorch_model.safetensors""") lowerCAmelCase : List[str] = osp.join(args.model_path, """vae""", """diffusion_pytorch_model.safetensors""") lowerCAmelCase : Optional[int] = osp.join(args.model_path, """text_encoder""", """model.safetensors""") # Load models from safetensors if it exists, if it doesn't pytorch if osp.exists(unet_path): lowerCAmelCase : Optional[int] = load_file(unet_path, device="""cpu""") else: lowerCAmelCase : Union[str, Any] = osp.join(args.model_path, """unet""", """diffusion_pytorch_model.bin""") lowerCAmelCase : Optional[Any] = torch.load(unet_path, map_location="""cpu""") if osp.exists(vae_path): lowerCAmelCase : str = load_file(vae_path, device="""cpu""") else: lowerCAmelCase : List[Any] = osp.join(args.model_path, """vae""", """diffusion_pytorch_model.bin""") lowerCAmelCase : Optional[Any] = torch.load(vae_path, map_location="""cpu""") if osp.exists(text_enc_path): lowerCAmelCase : List[Any] = load_file(text_enc_path, device="""cpu""") else: lowerCAmelCase : List[Any] = osp.join(args.model_path, """text_encoder""", """pytorch_model.bin""") lowerCAmelCase : Optional[Any] = torch.load(text_enc_path, map_location="""cpu""") # Convert the UNet model lowerCAmelCase : int = convert_unet_state_dict(unet_state_dict) lowerCAmelCase : Optional[int] = {"""model.diffusion_model.""" + k: v for k, v in unet_state_dict.items()} # Convert the VAE model lowerCAmelCase : Union[str, Any] = convert_vae_state_dict(vae_state_dict) lowerCAmelCase : Optional[int] = {"""first_stage_model.""" + k: v for k, v in vae_state_dict.items()} # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper lowerCAmelCase : Any = """text_model.encoder.layers.22.layer_norm2.bias""" in text_enc_dict if is_vaa_model: # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm lowerCAmelCase : Any = {"""transformer.""" + k: v for k, v in text_enc_dict.items()} lowerCAmelCase : str = convert_text_enc_state_dict_vaa(text_enc_dict) lowerCAmelCase : Dict = {"""cond_stage_model.model.""" + k: v for k, v in text_enc_dict.items()} else: lowerCAmelCase : Any = convert_text_enc_state_dict(text_enc_dict) lowerCAmelCase : Optional[Any] = {"""cond_stage_model.transformer.""" + k: v for k, v in text_enc_dict.items()} # Put together new checkpoint lowerCAmelCase : Union[str, Any] = {**unet_state_dict, **vae_state_dict, **text_enc_dict} if args.half: lowerCAmelCase : str = {k: v.half() for k, v in state_dict.items()} if args.use_safetensors: save_file(state_dict, args.checkpoint_path) else: lowerCAmelCase : int = {"""state_dict""": state_dict} torch.save(state_dict, args.checkpoint_path)
671
0
'''simple docstring''' import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class __A : def __init__(self : Tuple , __a : Dict , __a : Union[str, Any]=2 , __a : List[Any]=True , __a : str=False , __a : List[Any]=10 , __a : Optional[int]=3 , __a : Any=32 * 4 , __a : Any=32 * 6 , __a : Optional[int]=4 , __a : Optional[Any]=32 , ): UpperCAmelCase_ = parent UpperCAmelCase_ = batch_size UpperCAmelCase_ = is_training UpperCAmelCase_ = use_auxiliary_loss UpperCAmelCase_ = num_queries UpperCAmelCase_ = num_channels UpperCAmelCase_ = min_size UpperCAmelCase_ = max_size UpperCAmelCase_ = num_labels UpperCAmelCase_ = mask_feature_size def _lowercase (self : Dict ): UpperCAmelCase_ = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( __a ) UpperCAmelCase_ = torch.ones([self.batch_size, self.min_size, self.max_size] , device=__a ) UpperCAmelCase_ = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=__a ) > 0.5 ).float() UpperCAmelCase_ = (torch.rand((self.batch_size, self.num_labels) , device=__a ) > 0.5).long() UpperCAmelCase_ = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def _lowercase (self : Union[str, Any] ): return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=128 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def _lowercase (self : List[str] ): UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = self.prepare_config_and_inputs() UpperCAmelCase_ = {"pixel_values": pixel_values, "pixel_mask": pixel_mask} return config, inputs_dict def _lowercase (self : int , __a : int , __a : Union[str, Any] ): UpperCAmelCase_ = output.encoder_hidden_states UpperCAmelCase_ = output.pixel_decoder_hidden_states UpperCAmelCase_ = output.transformer_decoder_hidden_states self.parent.assertTrue(len(__a ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(__a ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(__a ) , config.decoder_config.decoder_layers ) def _lowercase (self : Tuple , __a : Union[str, Any] , __a : Any , __a : Union[str, Any] , __a : Any=False ): with torch.no_grad(): UpperCAmelCase_ = MaskFormerModel(config=__a ) model.to(__a ) model.eval() UpperCAmelCase_ = model(pixel_values=__a , pixel_mask=__a ) UpperCAmelCase_ = model(__a , output_hidden_states=__a ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(__a , __a ) def _lowercase (self : Optional[Any] , __a : int , __a : List[str] , __a : Dict , __a : Any , __a : Optional[Any] ): UpperCAmelCase_ = MaskFormerForInstanceSegmentation(config=__a ) model.to(__a ) model.eval() def comm_check_on_output(__a : Any ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): UpperCAmelCase_ = model(pixel_values=__a , pixel_mask=__a ) UpperCAmelCase_ = model(__a ) comm_check_on_output(__a ) UpperCAmelCase_ = model( pixel_values=__a , pixel_mask=__a , mask_labels=__a , class_labels=__a ) comm_check_on_output(__a ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class __A ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): a__ : List[str] = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () a__ : List[Any] = ( {"""feature-extraction""": MaskFormerModel, """image-segmentation""": MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) a__ : Optional[int] = False a__ : str = False a__ : Dict = False a__ : List[Any] = False def _lowercase (self : int ): UpperCAmelCase_ = MaskFormerModelTester(self ) UpperCAmelCase_ = ConfigTester(self , config_class=__a , has_text_modality=__a ) def _lowercase (self : Optional[Any] ): self.config_tester.run_common_tests() def _lowercase (self : Any ): UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(__a , **__a , output_hidden_states=__a ) def _lowercase (self : int ): UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*__a ) @unittest.skip(reason="MaskFormer does not use inputs_embeds" ) def _lowercase (self : str ): pass @unittest.skip(reason="MaskFormer does not have a get_input_embeddings method" ) def _lowercase (self : Any ): pass @unittest.skip(reason="MaskFormer is not a generative model" ) def _lowercase (self : str ): pass @unittest.skip(reason="MaskFormer does not use token embeddings" ) def _lowercase (self : Any ): pass @require_torch_multi_gpu @unittest.skip( reason="MaskFormer has some layers using `add_module` which doesn't work well with `nn.DataParallel`" ) def _lowercase (self : List[Any] ): pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def _lowercase (self : str ): pass def _lowercase (self : int ): UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_ = model_class(__a ) UpperCAmelCase_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase_ = [*signature.parameters.keys()] UpperCAmelCase_ = ["pixel_values"] self.assertListEqual(arg_names[:1] , __a ) @slow def _lowercase (self : List[str] ): for model_name in ["facebook/maskformer-swin-small-coco"]: UpperCAmelCase_ = MaskFormerModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def _lowercase (self : Any ): UpperCAmelCase_ = (self.model_tester.min_size,) * 2 UpperCAmelCase_ = { "pixel_values": torch.randn((2, 3, *size) , device=__a ), "mask_labels": torch.randn((2, 10, *size) , device=__a ), "class_labels": torch.zeros(2 , 10 , device=__a ).long(), } UpperCAmelCase_ = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(__a ) UpperCAmelCase_ = model(**__a ) self.assertTrue(outputs.loss is not None ) def _lowercase (self : Optional[int] ): UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(__a , **__a , output_hidden_states=__a ) def _lowercase (self : List[str] ): UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_ = model_class(__a ).to(__a ) UpperCAmelCase_ = model(**__a , output_attentions=__a ) self.assertTrue(outputs.attentions is not None ) def _lowercase (self : List[Any] ): if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss UpperCAmelCase_ = self.all_model_classes[1] UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() UpperCAmelCase_ = model_class(__a ) model.to(__a ) model.train() UpperCAmelCase_ = model(__a , mask_labels=__a , class_labels=__a ).loss loss.backward() def _lowercase (self : Optional[Any] ): # only MaskFormerForInstanceSegmentation has the loss UpperCAmelCase_ = self.all_model_classes[1] UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() UpperCAmelCase_ = True UpperCAmelCase_ = True UpperCAmelCase_ = model_class(__a ) model.to(__a ) model.train() UpperCAmelCase_ = model(__a , mask_labels=__a , class_labels=__a ) UpperCAmelCase_ = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() UpperCAmelCase_ = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't UpperCAmelCase_ = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() UpperCAmelCase_ = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=__a ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) SCREAMING_SNAKE_CASE_: int =1E-4 def lowerCAmelCase_ ( ) -> Optional[int]: '''simple docstring''' UpperCAmelCase_ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_vision @slow class __A ( unittest.TestCase ): @cached_property def _lowercase (self : str ): return ( MaskFormerImageProcessor.from_pretrained("facebook/maskformer-swin-small-coco" ) if is_vision_available() else None ) def _lowercase (self : str ): UpperCAmelCase_ = MaskFormerModel.from_pretrained("facebook/maskformer-swin-small-coco" ).to(__a ) UpperCAmelCase_ = self.default_image_processor UpperCAmelCase_ = prepare_img() UpperCAmelCase_ = image_processor(__a , return_tensors="pt" ).to(__a ) UpperCAmelCase_ = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(__a , (1, 3, 800, 1088) ) with torch.no_grad(): UpperCAmelCase_ = model(**__a ) UpperCAmelCase_ = torch.tensor( [[-0.04_82, 0.92_28, 0.49_51], [-0.25_47, 0.80_17, 0.85_27], [-0.00_69, 0.33_85, -0.00_89]] ).to(__a ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , __a , atol=__a ) ) UpperCAmelCase_ = torch.tensor( [[-0.84_22, -0.84_34, -0.97_18], [-1.01_44, -0.55_65, -0.41_95], [-1.00_38, -0.44_84, -0.19_61]] ).to(__a ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , __a , atol=__a ) ) UpperCAmelCase_ = torch.tensor( [[0.28_52, -0.01_59, 0.97_35], [0.62_54, 0.18_58, 0.85_29], [-0.06_80, -0.41_16, 1.84_13]] ).to(__a ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , __a , atol=__a ) ) def _lowercase (self : Optional[int] ): UpperCAmelCase_ = ( MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco" ) .to(__a ) .eval() ) UpperCAmelCase_ = self.default_image_processor UpperCAmelCase_ = prepare_img() UpperCAmelCase_ = image_processor(__a , return_tensors="pt" ).to(__a ) UpperCAmelCase_ = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(__a , (1, 3, 800, 1088) ) with torch.no_grad(): UpperCAmelCase_ = model(**__a ) # masks_queries_logits UpperCAmelCase_ = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) UpperCAmelCase_ = [ [-1.3_73_71_24, -1.7_72_49_37, -1.9_36_42_33], [-1.5_97_72_81, -1.9_86_79_39, -2.1_52_36_95], [-1.5_79_53_98, -1.9_26_98_32, -2.09_39_42], ] UpperCAmelCase_ = torch.tensor(__a ).to(__a ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , __a , atol=__a ) ) # class_queries_logits UpperCAmelCase_ = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) UpperCAmelCase_ = torch.tensor( [ [1.6512E00, -5.2572E00, -3.3519E00], [3.6169E-02, -5.9025E00, -2.9313E00], [1.0766E-04, -7.7630E00, -5.1263E00], ] ).to(__a ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , __a , atol=__a ) ) def _lowercase (self : Tuple ): UpperCAmelCase_ = ( MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-resnet101-coco-stuff" ) .to(__a ) .eval() ) UpperCAmelCase_ = self.default_image_processor UpperCAmelCase_ = prepare_img() UpperCAmelCase_ = image_processor(__a , return_tensors="pt" ).to(__a ) UpperCAmelCase_ = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(__a , (1, 3, 800, 1088) ) with torch.no_grad(): UpperCAmelCase_ = model(**__a ) # masks_queries_logits UpperCAmelCase_ = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) UpperCAmelCase_ = [[-0.90_46, -2.63_66, -4.60_62], [-3.41_79, -5.78_90, -8.80_57], [-4.91_79, -7.65_60, -10.77_11]] UpperCAmelCase_ = torch.tensor(__a ).to(__a ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , __a , atol=__a ) ) # class_queries_logits UpperCAmelCase_ = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) UpperCAmelCase_ = torch.tensor( [[4.71_88, -3.25_85, -2.88_57], [6.68_71, -2.91_81, -1.24_87], [7.24_49, -2.27_64, -2.18_74]] ).to(__a ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , __a , atol=__a ) ) def _lowercase (self : List[str] ): UpperCAmelCase_ = ( MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco" ) .to(__a ) .eval() ) UpperCAmelCase_ = self.default_image_processor UpperCAmelCase_ = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors="pt" , ) UpperCAmelCase_ = inputs["pixel_values"].to(__a ) UpperCAmelCase_ = [el.to(__a ) for el in inputs["mask_labels"]] UpperCAmelCase_ = [el.to(__a ) for el in inputs["class_labels"]] with torch.no_grad(): UpperCAmelCase_ = model(**__a ) self.assertTrue(outputs.loss is not None )
78
from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase : int = logging.get_logger(__name__) lowerCAmelCase : Dict = { """microsoft/xprophetnet-large-wiki100-cased""": ( """https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json""" ), } class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : Optional[Any] = '''xlm-prophetnet''' _UpperCAmelCase : Any = ['''past_key_values'''] _UpperCAmelCase : Tuple = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self : str , lowerCAmelCase__ : Optional[float] = 0.1 , lowerCAmelCase__ : Optional[Union[str, Callable]] = "gelu" , lowerCAmelCase__ : Optional[int] = 3_0522 , lowerCAmelCase__ : Optional[int] = 1024 , lowerCAmelCase__ : Optional[int] = 4096 , lowerCAmelCase__ : Optional[int] = 12 , lowerCAmelCase__ : Optional[int] = 16 , lowerCAmelCase__ : Optional[int] = 4096 , lowerCAmelCase__ : Optional[int] = 12 , lowerCAmelCase__ : Optional[int] = 16 , lowerCAmelCase__ : Optional[float] = 0.1 , lowerCAmelCase__ : Optional[float] = 0.1 , lowerCAmelCase__ : Optional[int] = 512 , lowerCAmelCase__ : Optional[float] = 0.02 , lowerCAmelCase__ : Optional[bool] = True , lowerCAmelCase__ : Optional[bool] = True , lowerCAmelCase__ : Optional[int] = 0 , lowerCAmelCase__ : Optional[int] = 2 , lowerCAmelCase__ : Optional[int] = 32 , lowerCAmelCase__ : Optional[int] = 128 , lowerCAmelCase__ : Optional[bool] = False , lowerCAmelCase__ : Optional[float] = 0.0 , lowerCAmelCase__ : Optional[bool] = True , lowerCAmelCase__ : Optional[int] = 0 , lowerCAmelCase__ : Optional[int] = 1 , lowerCAmelCase__ : Optional[int] = 2 , **lowerCAmelCase__ : List[str] , ): SCREAMING_SNAKE_CASE_: List[Any] = vocab_size SCREAMING_SNAKE_CASE_: int = hidden_size SCREAMING_SNAKE_CASE_: Any = encoder_ffn_dim SCREAMING_SNAKE_CASE_: Tuple = num_encoder_layers SCREAMING_SNAKE_CASE_: List[Any] = num_encoder_attention_heads SCREAMING_SNAKE_CASE_: Dict = decoder_ffn_dim SCREAMING_SNAKE_CASE_: Any = num_decoder_layers SCREAMING_SNAKE_CASE_: Tuple = num_decoder_attention_heads SCREAMING_SNAKE_CASE_: str = max_position_embeddings SCREAMING_SNAKE_CASE_: str = init_std # Normal(0, this parameter) SCREAMING_SNAKE_CASE_: Dict = activation_function # parameters for xlmprophetnet SCREAMING_SNAKE_CASE_: Optional[int] = ngram SCREAMING_SNAKE_CASE_: Tuple = num_buckets SCREAMING_SNAKE_CASE_: Union[str, Any] = relative_max_distance SCREAMING_SNAKE_CASE_: List[str] = disable_ngram_loss SCREAMING_SNAKE_CASE_: Dict = eps # 3 Types of Dropout SCREAMING_SNAKE_CASE_: Any = attention_dropout SCREAMING_SNAKE_CASE_: Optional[int] = activation_dropout SCREAMING_SNAKE_CASE_: str = dropout SCREAMING_SNAKE_CASE_: Optional[int] = use_cache super().__init__( pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , is_encoder_decoder=lowerCAmelCase__ , add_cross_attention=lowerCAmelCase__ , decoder_start_token_id=lowerCAmelCase__ , **lowerCAmelCase__ , ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def _SCREAMING_SNAKE_CASE ( self : int , lowerCAmelCase__ : Any): raise NotImplementedError( "This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and" " `num_decoder_layers`.")
671
0
import json import os import tempfile import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class UpperCAmelCase_ ( unittest.TestCase ): def __init__( self , _lowerCAmelCase , _lowerCAmelCase=7 , _lowerCAmelCase=3 , _lowerCAmelCase=18 , _lowerCAmelCase=30 , _lowerCAmelCase=400 , _lowerCAmelCase=True , _lowerCAmelCase=None , _lowerCAmelCase=True , ): UpperCAmelCase__ : List[str] = size if size is not None else {"""height""": 18, """width""": 18} UpperCAmelCase__ : Union[str, Any] = parent UpperCAmelCase__ : int = batch_size UpperCAmelCase__ : Tuple = num_channels UpperCAmelCase__ : Dict = image_size UpperCAmelCase__ : List[Any] = min_resolution UpperCAmelCase__ : str = max_resolution UpperCAmelCase__ : Union[str, Any] = do_resize UpperCAmelCase__ : Tuple = size UpperCAmelCase__ : int = do_normalize def __UpperCAmelCase ( self ): return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.8_8_6_6_4_4_3_6_3_4_0_3_3_2_0_3, 0.6_6_1_8_8_2_9_3_6_9_5_4_4_9_8_3, 0.3_8_9_1_7_4_6_4_0_1_7_8_6_8_0_4], [-0.6_0_4_2_5_5_9_1_4_6_8_8_1_1_0_4, -0.0_2_2_9_5_0_0_8_8_6_0_5_2_8_4_6_9, 0.5_4_2_3_7_9_7_3_6_9_0_0_3_2_9_6], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class UpperCAmelCase_ ( __lowerCamelCase , unittest.TestCase ): __lowerCamelCase = ImageGPTImageProcessor if is_vision_available() else None def __UpperCAmelCase ( self ): UpperCAmelCase__ : Any = ImageGPTImageProcessingTester(self ) @property def __UpperCAmelCase ( self ): return self.image_processor_tester.prepare_image_processor_dict() def __UpperCAmelCase ( self ): UpperCAmelCase__ : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCAmelCase , """clusters""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """do_resize""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """size""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """do_normalize""" ) ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 18, """width""": 18} ) UpperCAmelCase__ : Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) UpperCAmelCase__ : Optional[int] = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(_lowerCAmelCase , obj[key] ) ) else: self.assertEqual(obj[key] , _lowerCAmelCase ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase__ : Union[str, Any] = os.path.join(_lowerCAmelCase , """image_processor.json""" ) image_processor_first.to_json_file(_lowerCAmelCase ) UpperCAmelCase__ : Optional[Any] = self.image_processing_class.from_json_file(_lowerCAmelCase ).to_dict() UpperCAmelCase__ : Dict = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(_lowerCAmelCase , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , _lowerCAmelCase ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : str = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(_lowerCAmelCase ) UpperCAmelCase__ : List[Any] = self.image_processing_class.from_pretrained(_lowerCAmelCase ).to_dict() UpperCAmelCase__ : Tuple = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(_lowerCAmelCase , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , _lowerCAmelCase ) @unittest.skip("""ImageGPT requires clusters at initialization""" ) def __UpperCAmelCase ( self ): pass def _lowerCamelCase ( ) -> Tuple: '''simple docstring''' UpperCAmelCase__ : Any = load_dataset("""hf-internal-testing/fixtures_image_utils""" , split="""test""" ) UpperCAmelCase__ : Dict = Image.open(dataset[4]["""file"""] ) UpperCAmelCase__ : Optional[Any] = Image.open(dataset[5]["""file"""] ) UpperCAmelCase__ : List[Any] = [imagea, imagea] return images @require_vision @require_torch class UpperCAmelCase_ ( unittest.TestCase ): @slow def __UpperCAmelCase ( self ): UpperCAmelCase__ : Tuple = ImageGPTImageProcessor.from_pretrained("""openai/imagegpt-small""" ) UpperCAmelCase__ : int = prepare_images() # test non-batched UpperCAmelCase__ : List[str] = image_processing(images[0] , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (1, 1024) ) UpperCAmelCase__ : List[Any] = [306, 191, 191] self.assertEqual(encoding.input_ids[0, :3].tolist() , _lowerCAmelCase ) # test batched UpperCAmelCase__ : List[str] = image_processing(_lowerCAmelCase , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (2, 1024) ) UpperCAmelCase__ : Any = [303, 13, 13] self.assertEqual(encoding.input_ids[1, -3:].tolist() , _lowerCAmelCase )
79
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL lowerCAmelCase : Dict = logging.get_logger(__name__) def A_ ( _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[int] = b.T SCREAMING_SNAKE_CASE_: Dict = np.sum(np.square(_UpperCAmelCase ) , axis=1 ) SCREAMING_SNAKE_CASE_: Tuple = np.sum(np.square(_UpperCAmelCase ) , axis=0 ) SCREAMING_SNAKE_CASE_: List[Any] = np.matmul(_UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Dict = aa[:, None] - 2 * ab + ba[None, :] return d def A_ ( _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: int = x.reshape(-1 , 3 ) SCREAMING_SNAKE_CASE_: Tuple = squared_euclidean_distance(_UpperCAmelCase , _UpperCAmelCase ) return np.argmin(_UpperCAmelCase , axis=1 ) class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : int = ['''pixel_values'''] def __init__( self : Tuple , lowerCAmelCase__ : Optional[Union[List[List[int]], np.ndarray]] = None , lowerCAmelCase__ : bool = True , lowerCAmelCase__ : Dict[str, int] = None , lowerCAmelCase__ : PILImageResampling = PILImageResampling.BILINEAR , lowerCAmelCase__ : bool = True , lowerCAmelCase__ : bool = True , **lowerCAmelCase__ : List[str] , ): super().__init__(**lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Any = size if size is not None else {"height": 256, "width": 256} SCREAMING_SNAKE_CASE_: Tuple = get_size_dict(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Tuple = np.array(lowerCAmelCase__) if clusters is not None else None SCREAMING_SNAKE_CASE_: Dict = do_resize SCREAMING_SNAKE_CASE_: str = size SCREAMING_SNAKE_CASE_: List[Any] = resample SCREAMING_SNAKE_CASE_: Optional[int] = do_normalize SCREAMING_SNAKE_CASE_: Dict = do_color_quantize def _SCREAMING_SNAKE_CASE ( self : List[str] , lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : Dict[str, int] , lowerCAmelCase__ : PILImageResampling = PILImageResampling.BILINEAR , lowerCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **lowerCAmelCase__ : Optional[Any] , ): SCREAMING_SNAKE_CASE_: List[str] = get_size_dict(lowerCAmelCase__) if "height" not in size or "width" not in size: raise ValueError(F"Size dictionary must contain both height and width keys. Got {size.keys()}") return resize( lowerCAmelCase__ , size=(size["height"], size["width"]) , resample=lowerCAmelCase__ , data_format=lowerCAmelCase__ , **lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , ): SCREAMING_SNAKE_CASE_: str = rescale(image=lowerCAmelCase__ , scale=1 / 127.5 , data_format=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Optional[int] = image - 1 return image def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase__ : ImageInput , lowerCAmelCase__ : bool = None , lowerCAmelCase__ : Dict[str, int] = None , lowerCAmelCase__ : PILImageResampling = None , lowerCAmelCase__ : bool = None , lowerCAmelCase__ : Optional[bool] = None , lowerCAmelCase__ : Optional[Union[List[List[int]], np.ndarray]] = None , lowerCAmelCase__ : Optional[Union[str, TensorType]] = None , lowerCAmelCase__ : Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST , **lowerCAmelCase__ : Union[str, Any] , ): SCREAMING_SNAKE_CASE_: Tuple = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE_: Optional[int] = size if size is not None else self.size SCREAMING_SNAKE_CASE_: Dict = get_size_dict(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[str] = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE_: int = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE_: List[str] = do_color_quantize if do_color_quantize is not None else self.do_color_quantize SCREAMING_SNAKE_CASE_: Tuple = clusters if clusters is not None else self.clusters SCREAMING_SNAKE_CASE_: Optional[int] = np.array(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Optional[int] = make_list_of_images(lowerCAmelCase__) if not valid_images(lowerCAmelCase__): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray.") if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True.") if do_color_quantize and clusters is None: raise ValueError("Clusters must be specified if do_color_quantize is True.") # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE_: Union[str, Any] = [to_numpy_array(lowerCAmelCase__) for image in images] if do_resize: SCREAMING_SNAKE_CASE_: Optional[Any] = [self.resize(image=lowerCAmelCase__ , size=lowerCAmelCase__ , resample=lowerCAmelCase__) for image in images] if do_normalize: SCREAMING_SNAKE_CASE_: str = [self.normalize(image=lowerCAmelCase__) for image in images] if do_color_quantize: SCREAMING_SNAKE_CASE_: Any = [to_channel_dimension_format(lowerCAmelCase__ , ChannelDimension.LAST) for image in images] # color quantize from (batch_size, height, width, 3) to (batch_size, height, width) SCREAMING_SNAKE_CASE_: List[Any] = np.array(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[str] = color_quantize(lowerCAmelCase__ , lowerCAmelCase__).reshape(images.shape[:-1]) # flatten to (batch_size, height*width) SCREAMING_SNAKE_CASE_: str = images.shape[0] SCREAMING_SNAKE_CASE_: Tuple = images.reshape(lowerCAmelCase__ , -1) # We need to convert back to a list of images to keep consistent behaviour across processors. SCREAMING_SNAKE_CASE_: str = list(lowerCAmelCase__) else: SCREAMING_SNAKE_CASE_: Dict = [to_channel_dimension_format(lowerCAmelCase__ , lowerCAmelCase__) for image in images] SCREAMING_SNAKE_CASE_: Optional[Any] = {"input_ids": images} return BatchFeature(data=lowerCAmelCase__ , tensor_type=lowerCAmelCase__)
671
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available __UpperCamelCase : Union[str, Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : int = ["""BartphoTokenizer"""] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bartpho import BartphoTokenizer else: import sys __UpperCamelCase : List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
80
import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert import BertTokenizer lowerCAmelCase : Optional[int] = logging.get_logger(__name__) lowerCAmelCase : str = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} lowerCAmelCase : Tuple = { """vocab_file""": { """facebook/dpr-ctx_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt""" ), """facebook/dpr-ctx_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """facebook/dpr-ctx_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json""" ), """facebook/dpr-ctx_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json""" ), }, } lowerCAmelCase : Union[str, Any] = { """vocab_file""": { """facebook/dpr-question_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt""" ), """facebook/dpr-question_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """facebook/dpr-question_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json""" ), """facebook/dpr-question_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json""" ), }, } lowerCAmelCase : List[str] = { """vocab_file""": { """facebook/dpr-reader-single-nq-base""": ( """https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt""" ), """facebook/dpr-reader-multiset-base""": ( """https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """facebook/dpr-reader-single-nq-base""": ( """https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json""" ), """facebook/dpr-reader-multiset-base""": ( """https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json""" ), }, } lowerCAmelCase : int = { """facebook/dpr-ctx_encoder-single-nq-base""": 512, """facebook/dpr-ctx_encoder-multiset-base""": 512, } lowerCAmelCase : int = { """facebook/dpr-question_encoder-single-nq-base""": 512, """facebook/dpr-question_encoder-multiset-base""": 512, } lowerCAmelCase : List[Any] = { """facebook/dpr-reader-single-nq-base""": 512, """facebook/dpr-reader-multiset-base""": 512, } lowerCAmelCase : Optional[int] = { """facebook/dpr-ctx_encoder-single-nq-base""": {"""do_lower_case""": True}, """facebook/dpr-ctx_encoder-multiset-base""": {"""do_lower_case""": True}, } lowerCAmelCase : Optional[int] = { """facebook/dpr-question_encoder-single-nq-base""": {"""do_lower_case""": True}, """facebook/dpr-question_encoder-multiset-base""": {"""do_lower_case""": True}, } lowerCAmelCase : List[str] = { """facebook/dpr-reader-single-nq-base""": {"""do_lower_case""": True}, """facebook/dpr-reader-multiset-base""": {"""do_lower_case""": True}, } class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : Any = VOCAB_FILES_NAMES _UpperCAmelCase : Optional[Any] = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : List[Any] = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : List[Any] = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : Union[str, Any] = VOCAB_FILES_NAMES _UpperCAmelCase : Optional[int] = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Any = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : str = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION lowerCAmelCase : List[Any] = collections.namedtuple( """DPRSpanPrediction""", ["""span_score""", """relevance_score""", """doc_id""", """start_index""", """end_index""", """text"""] ) lowerCAmelCase : Optional[Any] = collections.namedtuple("""DPRReaderOutput""", ["""start_logits""", """end_logits""", """relevance_logits"""]) lowerCAmelCase : int = R""" Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`. It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers), using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)` with the format: ``` [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids> ``` Args: questions (`str` or `List[str]`): The questions to be encoded. You can specify one question for many passages. In this case, the question will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in `titles` or `texts`. titles (`str` or `List[str]`): The passages titles to be encoded. This can be a string or a list of strings if there are several passages. texts (`str` or `List[str]`): The passages texts to be encoded. This can be a string or a list of strings if there are several passages. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`): Activates and controls padding. Accepts the following values: - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different lengths). truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`): Activates and controls truncation. Accepts the following values: - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided. - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size). max_length (`int`, *optional*): Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length is required by one of the truncation/padding parameters. If the model has no specific maximum input length (like XLNet) truncation/padding to a maximum length will be deactivated. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors instead of list of python integers. Acceptable values are: - `'tf'`: Return TensorFlow `tf.constant` objects. - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return Numpy `np.ndarray` objects. return_attention_mask (`bool`, *optional*): Whether or not to return the attention mask. If not set, will return the attention mask according to the specific tokenizer's default, defined by the `return_outputs` attribute. [What are attention masks?](../glossary#attention-mask) Returns: `Dict[str, List[List[int]]]`: A dictionary with the following keys: - `input_ids`: List of token ids to be fed to a model. - `attention_mask`: List of indices specifying which tokens should be attended to by the model. """ @add_start_docstrings(UpperCAmelCase_ ) class __lowercase : """simple docstring""" def __call__( self : List[Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : Optional[str] = None , lowerCAmelCase__ : Optional[str] = None , lowerCAmelCase__ : Union[bool, str] = False , lowerCAmelCase__ : Union[bool, str] = False , lowerCAmelCase__ : Optional[int] = None , lowerCAmelCase__ : Optional[Union[str, TensorType]] = None , lowerCAmelCase__ : Optional[bool] = None , **lowerCAmelCase__ : Tuple , ): if titles is None and texts is None: return super().__call__( lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , max_length=lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , **lowerCAmelCase__ , ) elif titles is None or texts is None: SCREAMING_SNAKE_CASE_: List[str] = titles if texts is None else texts return super().__call__( lowerCAmelCase__ , lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , max_length=lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , **lowerCAmelCase__ , ) SCREAMING_SNAKE_CASE_: Optional[int] = titles if not isinstance(lowerCAmelCase__ , lowerCAmelCase__) else [titles] SCREAMING_SNAKE_CASE_: int = texts if not isinstance(lowerCAmelCase__ , lowerCAmelCase__) else [texts] SCREAMING_SNAKE_CASE_: str = len(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Tuple = questions if not isinstance(lowerCAmelCase__ , lowerCAmelCase__) else [questions] * n_passages if len(lowerCAmelCase__) != len(lowerCAmelCase__): raise ValueError( F"There should be as many titles than texts but got {len(lowerCAmelCase__)} titles and {len(lowerCAmelCase__)} texts.") SCREAMING_SNAKE_CASE_: Optional[Any] = super().__call__(lowerCAmelCase__ , lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__)["input_ids"] SCREAMING_SNAKE_CASE_: Union[str, Any] = super().__call__(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__)["input_ids"] SCREAMING_SNAKE_CASE_: int = { "input_ids": [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(lowerCAmelCase__ , lowerCAmelCase__) ] } if return_attention_mask is not False: SCREAMING_SNAKE_CASE_: Dict = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id) for input_id in input_ids]) SCREAMING_SNAKE_CASE_: int = attention_mask return self.pad(lowerCAmelCase__ , padding=lowerCAmelCase__ , max_length=lowerCAmelCase__ , return_tensors=lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Any , lowerCAmelCase__ : BatchEncoding , lowerCAmelCase__ : DPRReaderOutput , lowerCAmelCase__ : int = 16 , lowerCAmelCase__ : int = 64 , lowerCAmelCase__ : int = 4 , ): SCREAMING_SNAKE_CASE_: int = reader_input["input_ids"] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: int = reader_output[:3] SCREAMING_SNAKE_CASE_: Tuple = len(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Union[str, Any] = sorted(range(lowerCAmelCase__) , reverse=lowerCAmelCase__ , key=relevance_logits.__getitem__) SCREAMING_SNAKE_CASE_: List[DPRReaderOutput] = [] for doc_id in sorted_docs: SCREAMING_SNAKE_CASE_: Optional[int] = list(input_ids[doc_id]) # assuming question & title information is at the beginning of the sequence SCREAMING_SNAKE_CASE_: str = sequence_ids.index(self.sep_token_id , 2) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: SCREAMING_SNAKE_CASE_: List[Any] = sequence_ids.index(self.pad_token_id) else: SCREAMING_SNAKE_CASE_: Dict = len(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Optional[Any] = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=lowerCAmelCase__ , top_spans=lowerCAmelCase__ , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=lowerCAmelCase__ , start_index=lowerCAmelCase__ , end_index=lowerCAmelCase__ , text=self.decode(sequence_ids[start_index : end_index + 1]) , )) if len(lowerCAmelCase__) >= num_spans: break return nbest_spans_predictions[:num_spans] def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase__ : List[int] , lowerCAmelCase__ : List[int] , lowerCAmelCase__ : int , lowerCAmelCase__ : int , ): SCREAMING_SNAKE_CASE_: Any = [] for start_index, start_score in enumerate(lowerCAmelCase__): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length]): scores.append(((start_index, start_index + answer_length), start_score + end_score)) SCREAMING_SNAKE_CASE_: Union[str, Any] = sorted(lowerCAmelCase__ , key=lambda lowerCAmelCase__: x[1] , reverse=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[str] = [] for (start_index, end_index), score in scores: if start_index > end_index: raise ValueError(F"Wrong span indices: [{start_index}:{end_index}]") SCREAMING_SNAKE_CASE_: int = end_index - start_index + 1 if length > max_answer_length: raise ValueError(F"Span is too long: {length} > {max_answer_length}") if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals): continue chosen_span_intervals.append((start_index, end_index)) if len(lowerCAmelCase__) == top_spans: break return chosen_span_intervals @add_end_docstrings(UpperCAmelCase_ ) class __lowercase ( UpperCAmelCase_ , UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : Any = VOCAB_FILES_NAMES _UpperCAmelCase : Optional[Any] = READER_PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : int = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : Optional[int] = READER_PRETRAINED_INIT_CONFIGURATION _UpperCAmelCase : str = ['''input_ids''', '''attention_mask''']
671
0
from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging _snake_case : str = logging.get_logger(__name__) _snake_case : Tuple = { "Salesforce/codegen-350M-nl": "https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json", "Salesforce/codegen-350M-multi": "https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json", "Salesforce/codegen-350M-mono": "https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json", "Salesforce/codegen-2B-nl": "https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json", "Salesforce/codegen-2B-multi": "https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json", "Salesforce/codegen-2B-mono": "https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json", "Salesforce/codegen-6B-nl": "https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json", "Salesforce/codegen-6B-multi": "https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json", "Salesforce/codegen-6B-mono": "https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json", "Salesforce/codegen-16B-nl": "https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json", "Salesforce/codegen-16B-multi": "https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json", "Salesforce/codegen-16B-mono": "https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json", } class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = "codegen" __UpperCAmelCase : Dict = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : Optional[int] , lowerCamelCase : Dict=50400 , lowerCamelCase : int=2048 , lowerCamelCase : List[Any]=2048 , lowerCamelCase : List[Any]=4096 , lowerCamelCase : Dict=28 , lowerCamelCase : List[str]=16 , lowerCamelCase : str=64 , lowerCamelCase : Any=None , lowerCamelCase : Optional[int]="gelu_new" , lowerCamelCase : Any=0.0 , lowerCamelCase : Union[str, Any]=0.0 , lowerCamelCase : int=0.0 , lowerCamelCase : List[str]=1E-5 , lowerCamelCase : List[Any]=0.02 , lowerCamelCase : List[str]=True , lowerCamelCase : Optional[Any]=50256 , lowerCamelCase : int=50256 , lowerCamelCase : str=False , **lowerCamelCase : int , ) -> Union[str, Any]: __snake_case : str = vocab_size __snake_case : List[Any] = n_ctx __snake_case : Tuple = n_positions __snake_case : int = n_embd __snake_case : List[str] = n_layer __snake_case : int = n_head __snake_case : Union[str, Any] = n_inner __snake_case : List[Any] = rotary_dim __snake_case : Tuple = activation_function __snake_case : str = resid_pdrop __snake_case : Dict = embd_pdrop __snake_case : Optional[int] = attn_pdrop __snake_case : Dict = layer_norm_epsilon __snake_case : Tuple = initializer_range __snake_case : Union[str, Any] = use_cache __snake_case : Dict = bos_token_id __snake_case : Any = eos_token_id super().__init__( bos_token_id=lowerCamelCase , eos_token_id=lowerCamelCase , tie_word_embeddings=lowerCamelCase , **lowerCamelCase ) class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : str , lowerCamelCase : PretrainedConfig , lowerCamelCase : str = "default" , lowerCamelCase : List[PatchingSpec] = None , lowerCamelCase : bool = False , ) -> Any: super().__init__(lowerCamelCase , task=lowerCamelCase , patching_specs=lowerCamelCase , use_past=lowerCamelCase ) if not getattr(self._config , "pad_token_id" , lowerCamelCase ): # TODO: how to do that better? __snake_case : Any = 0 @property def __snake_case ( self : Union[str, Any] ) -> Mapping[str, Mapping[int, str]]: __snake_case : Dict = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}} ) if self.use_past: self.fill_with_past_key_values_(lowerCamelCase , direction="inputs" ) __snake_case : Optional[Any] = {0: "batch", 1: "past_sequence + sequence"} else: __snake_case : int = {0: "batch", 1: "sequence"} return common_inputs @property def __snake_case ( self : int ) -> int: return self._config.n_layer @property def __snake_case ( self : List[str] ) -> int: return self._config.n_head def __snake_case ( self : Tuple , lowerCamelCase : PreTrainedTokenizer , lowerCamelCase : int = -1 , lowerCamelCase : int = -1 , lowerCamelCase : bool = False , lowerCamelCase : Optional[TensorType] = None , ) -> Mapping[str, Any]: __snake_case : Union[str, Any] = super(lowerCamelCase , self ).generate_dummy_inputs( lowerCamelCase , batch_size=lowerCamelCase , seq_length=lowerCamelCase , is_pair=lowerCamelCase , framework=lowerCamelCase ) # We need to order the input in the way they appears in the forward() __snake_case : List[str] = OrderedDict({"input_ids": common_inputs["input_ids"]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch __snake_case , __snake_case : Optional[Any] = common_inputs["input_ids"].shape # Not using the same length for past_key_values __snake_case : Optional[Any] = seqlen + 2 __snake_case : str = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) __snake_case : str = [ (torch.zeros(lowerCamelCase ), torch.zeros(lowerCamelCase )) for _ in range(self.num_layers ) ] __snake_case : List[Any] = common_inputs["attention_mask"] if self.use_past: __snake_case : List[Any] = ordered_inputs["attention_mask"].dtype __snake_case : Any = torch.cat( [ordered_inputs["attention_mask"], torch.ones(lowerCamelCase , lowerCamelCase , dtype=lowerCamelCase )] , dim=1 ) return ordered_inputs @property def __snake_case ( self : Tuple ) -> int: return 13
81
from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : Optional[Any] = DistilBertTokenizer _UpperCAmelCase : Union[str, Any] = DistilBertTokenizerFast _UpperCAmelCase : int = True @slow def _SCREAMING_SNAKE_CASE ( self : Any): SCREAMING_SNAKE_CASE_: Optional[Any] = DistilBertTokenizer.from_pretrained("distilbert-base-uncased") SCREAMING_SNAKE_CASE_: Any = tokenizer.encode("sequence builders" , add_special_tokens=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[Any] = tokenizer.encode("multi-sequence build" , add_special_tokens=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Tuple = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: int = 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 ]
671
0
"""simple docstring""" def a__ ( lowerCAmelCase__ ): if len(lowerCAmelCase__ ) <= 1: return lst UpperCAmelCase_ = 1 while i < len(lowerCAmelCase__ ): if lst[i - 1] <= lst[i]: i += 1 else: UpperCAmelCase_ , UpperCAmelCase_ = lst[i], lst[i - 1] i -= 1 if i == 0: UpperCAmelCase_ = 1 return lst if __name__ == "__main__": lowerCamelCase = input("""Enter numbers separated by a comma:\n""").strip() lowerCamelCase = [int(item) for item in user_input.split(""",""")] print(gnome_sort(unsorted))
82
import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient lowerCAmelCase : List[Any] = WebClient(token=os.environ["""CI_SLACK_BOT_TOKEN"""]) def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[int] = test_results.split(" " ) SCREAMING_SNAKE_CASE_: Tuple = 0 SCREAMING_SNAKE_CASE_: str = 0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. SCREAMING_SNAKE_CASE_: Optional[Any] = expressions[-2] if "=" in expressions[-1] else expressions[-1] for i, expression in enumerate(_UpperCAmelCase ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: str = {} SCREAMING_SNAKE_CASE_: Any = None SCREAMING_SNAKE_CASE_: Union[str, Any] = False for line in failures_short_lines.split("\n" ): if re.search(R"_ \[doctest\]" , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: List[Any] = True SCREAMING_SNAKE_CASE_: Dict = line.split(" " )[2] elif in_error and not line.split(" " )[0].isdigit(): SCREAMING_SNAKE_CASE_: Union[str, Any] = line SCREAMING_SNAKE_CASE_: List[str] = False return failures class __lowercase : """simple docstring""" def __init__( self : Any , lowerCAmelCase__ : str , lowerCAmelCase__ : Dict): SCREAMING_SNAKE_CASE_: Dict = title SCREAMING_SNAKE_CASE_: int = doc_test_results["time_spent"].split(",")[0] SCREAMING_SNAKE_CASE_: int = doc_test_results["success"] SCREAMING_SNAKE_CASE_: Optional[Any] = doc_test_results["failures"] SCREAMING_SNAKE_CASE_: Any = self.n_success + self.n_failures # Failures and success of the modeling tests SCREAMING_SNAKE_CASE_: Optional[int] = doc_test_results @property def _SCREAMING_SNAKE_CASE ( self : Any): SCREAMING_SNAKE_CASE_: int = [self._time_spent] SCREAMING_SNAKE_CASE_: List[Any] = 0 for time in time_spent: SCREAMING_SNAKE_CASE_: Union[str, Any] = time.split(":") # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(lowerCAmelCase__) == 1: SCREAMING_SNAKE_CASE_: Dict = [0, 0, time_parts[0]] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: int = int(time_parts[0]), int(time_parts[1]), float(time_parts[2]) total_secs += hours * 3600 + minutes * 60 + seconds SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: str = total_secs // 3600, (total_secs % 3600) // 60, total_secs % 60 return F"{int(lowerCAmelCase__)}h{int(lowerCAmelCase__)}m{int(lowerCAmelCase__)}s" @property def _SCREAMING_SNAKE_CASE ( self : List[Any]): return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): return { "type": "section", "text": { "type": "plain_text", "text": F"🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.", "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": F"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", }, } @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): return { "type": "section", "text": { "type": "plain_text", "text": ( F"There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in" F" {self.time}." ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": F"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", }, } @property def _SCREAMING_SNAKE_CASE ( self : Any): SCREAMING_SNAKE_CASE_: Optional[Any] = 40 SCREAMING_SNAKE_CASE_: List[str] = {k: v["failed"] for k, v in doc_test_results.items() if isinstance(lowerCAmelCase__ , lowerCAmelCase__)} SCREAMING_SNAKE_CASE_: Tuple = "" for category, failures in category_failures.items(): if len(lowerCAmelCase__) == 0: continue if report != "": report += "\n\n" report += F"*{category} failures*:".ljust(line_length // 2).rjust(line_length // 2) + "\n" report += "`" report += "`\n`".join(lowerCAmelCase__) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": F"The following examples had failures:\n\n\n{report}\n", }, } @property def _SCREAMING_SNAKE_CASE ( self : str): SCREAMING_SNAKE_CASE_: Optional[Any] = [self.header] if self.n_failures > 0: blocks.append(self.failures) if self.n_failures > 0: blocks.extend([self.category_failures]) if self.n_failures == 0: blocks.append(self.no_failures) return json.dumps(lowerCAmelCase__) @staticmethod def _SCREAMING_SNAKE_CASE ( ): SCREAMING_SNAKE_CASE_: List[str] = [ { "type": "section", "text": { "type": "plain_text", "text": "There was an issue running the tests.", }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": F"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", }, } ] print("Sending the following payload") print(json.dumps({"blocks": json.loads(lowerCAmelCase__)})) client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , text="There was an issue running the tests." , blocks=lowerCAmelCase__ , ) def _SCREAMING_SNAKE_CASE ( self : Tuple): print("Sending the following payload") print(json.dumps({"blocks": json.loads(self.payload)})) SCREAMING_SNAKE_CASE_: Optional[Any] = F"{self.n_failures} failures out of {self.n_tests} tests," if self.n_failures else "All tests passed." SCREAMING_SNAKE_CASE_: List[Any] = client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , blocks=self.payload , text=lowerCAmelCase__ , ) def _SCREAMING_SNAKE_CASE ( self : Dict , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any]): SCREAMING_SNAKE_CASE_: Dict = "" for key, value in failures.items(): SCREAMING_SNAKE_CASE_: str = value[:200] + " [Truncated]" if len(lowerCAmelCase__) > 250 else value failures_text += F"*{key}*\n_{value}_\n\n" SCREAMING_SNAKE_CASE_: Any = job_name SCREAMING_SNAKE_CASE_: List[Any] = {"type": "section", "text": {"type": "mrkdwn", "text": text}} if job_link is not None: SCREAMING_SNAKE_CASE_: Tuple = { "type": "button", "text": {"type": "plain_text", "text": "GitHub Action job", "emoji": True}, "url": job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def _SCREAMING_SNAKE_CASE ( self : Any): if self.thread_ts is None: raise ValueError("Can only post reply if a post has been made.") SCREAMING_SNAKE_CASE_: Tuple = self.doc_test_results.pop("job_link") self.doc_test_results.pop("failures") self.doc_test_results.pop("success") self.doc_test_results.pop("time_spent") SCREAMING_SNAKE_CASE_: Any = sorted(self.doc_test_results.items() , key=lambda lowerCAmelCase__: t[0]) for job, job_result in sorted_dict: if len(job_result["failures"]): SCREAMING_SNAKE_CASE_: Union[str, Any] = F"*Num failures* :{len(job_result['failed'])} \n" SCREAMING_SNAKE_CASE_: Optional[Any] = job_result["failures"] SCREAMING_SNAKE_CASE_: Optional[Any] = self.get_reply_blocks(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , text=lowerCAmelCase__) print("Sending the following reply") print(json.dumps({"blocks": blocks})) client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , text=F"Results for {job}" , blocks=lowerCAmelCase__ , thread_ts=self.thread_ts["ts"] , ) time.sleep(1) def A_ ( ): SCREAMING_SNAKE_CASE_: Tuple = os.environ["GITHUB_RUN_ID"] SCREAMING_SNAKE_CASE_: Any = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100" SCREAMING_SNAKE_CASE_: List[Any] = requests.get(_UpperCAmelCase ).json() SCREAMING_SNAKE_CASE_: Optional[Any] = {} try: jobs.update({job["name"]: job["html_url"] for job in result["jobs"]} ) SCREAMING_SNAKE_CASE_: Any = math.ceil((result["total_count"] - 1_00) / 1_00 ) for i in range(_UpperCAmelCase ): SCREAMING_SNAKE_CASE_: str = requests.get(url + f"&page={i + 2}" ).json() jobs.update({job["name"]: job["html_url"] for job in result["jobs"]} ) return jobs except Exception as e: print("Unknown error, could not fetch links." , _UpperCAmelCase ) return {} def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[Any] = {} if os.path.exists(_UpperCAmelCase ): SCREAMING_SNAKE_CASE_: List[str] = os.listdir(_UpperCAmelCase ) for file in files: try: with open(os.path.join(_UpperCAmelCase , _UpperCAmelCase ) , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE_: Dict = f.read() except UnicodeDecodeError as e: raise ValueError(f"Could not open {os.path.join(_UpperCAmelCase , _UpperCAmelCase )}." ) from e return _artifact def A_ ( ): class __lowercase : """simple docstring""" def __init__( self : List[str] , lowerCAmelCase__ : str): SCREAMING_SNAKE_CASE_: Dict = name SCREAMING_SNAKE_CASE_: List[str] = [] def __str__( self : Optional[Any]): return self.name def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase__ : str): self.paths.append({"name": self.name, "path": path}) SCREAMING_SNAKE_CASE_: Dict[str, Artifact] = {} SCREAMING_SNAKE_CASE_: List[Any] = filter(os.path.isdir , os.listdir() ) for directory in directories: SCREAMING_SNAKE_CASE_: Dict = directory if artifact_name not in _available_artifacts: SCREAMING_SNAKE_CASE_: Tuple = Artifact(_UpperCAmelCase ) _available_artifacts[artifact_name].add_path(_UpperCAmelCase ) return _available_artifacts if __name__ == "__main__": lowerCAmelCase : Tuple = get_job_links() lowerCAmelCase : Optional[Any] = retrieve_available_artifacts() lowerCAmelCase : Any = collections.OrderedDict( [ ("""*.py""", """API Examples"""), ("""*.md""", """MD Examples"""), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' lowerCAmelCase : int = { v: { """failed""": [], """failures""": {}, } for v in docs.values() } # Link to the GitHub Action job lowerCAmelCase : Optional[int] = github_actions_job_links.get("""run_doctests""") lowerCAmelCase : List[Any] = available_artifacts["""doc_tests_gpu_test_reports"""].paths[0] lowerCAmelCase : Any = retrieve_artifact(artifact_path["""name"""]) if "stats" in artifact: lowerCAmelCase , lowerCAmelCase , lowerCAmelCase : List[str] = handle_test_results(artifact["""stats"""]) lowerCAmelCase : List[str] = failed lowerCAmelCase : Any = success lowerCAmelCase : Dict = time_spent[1:-1] + """, """ lowerCAmelCase : str = extract_first_line_failure(artifact["""failures_short"""]) for line in artifact["summary_short"].split("""\n"""): if re.search("""FAILED""", line): lowerCAmelCase : Tuple = line.replace("""FAILED """, """""") lowerCAmelCase : str = line.split()[0].replace("""\n""", """""") if "::" in line: lowerCAmelCase , lowerCAmelCase : Optional[int] = line.split("""::""") else: lowerCAmelCase , lowerCAmelCase : str = line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): lowerCAmelCase : str = docs[file_regex] doc_test_results[category]["failed"].append(test) lowerCAmelCase : str = all_failures[test] if test in all_failures else """N/A""" lowerCAmelCase : Any = failure break lowerCAmelCase : Union[str, Any] = Message("""🤗 Results of the doc tests.""", doc_test_results) message.post() message.post_reply()
671
0
"""simple docstring""" import contextlib import copy import random from typing import Any, Dict, Iterable, Optional, Union import numpy as np import torch from .utils import deprecate, is_transformers_available if is_transformers_available(): import transformers def snake_case_ ( A_ : int ): '''simple docstring''' random.seed(A_ ) np.random.seed(A_ ) torch.manual_seed(A_ ) torch.cuda.manual_seed_all(A_ ) # ^^ safe to call this function even if cuda is not available class __snake_case : def __init__( self : int , __lowerCAmelCase : Iterable[torch.nn.Parameter] , __lowerCAmelCase : float = 0.99_99 , __lowerCAmelCase : float = 0.0 , __lowerCAmelCase : int = 0 , __lowerCAmelCase : bool = False , __lowerCAmelCase : Union[float, int] = 1.0 , __lowerCAmelCase : Union[float, int] = 2 / 3 , __lowerCAmelCase : Optional[Any] = None , __lowerCAmelCase : Dict[str, Any] = None , **__lowerCAmelCase : Optional[Any] , ): """simple docstring""" if isinstance(__lowerCAmelCase , torch.nn.Module ): _lowerCamelCase : Dict = ( '''Passing a `torch.nn.Module` to `ExponentialMovingAverage` is deprecated. ''' '''Please pass the parameters of the module instead.''' ) deprecate( '''passing a `torch.nn.Module` to `ExponentialMovingAverage`''' , '''1.0.0''' , __lowerCAmelCase , standard_warn=__lowerCAmelCase , ) _lowerCamelCase : int = parameters.parameters() # set use_ema_warmup to True if a torch.nn.Module is passed for backwards compatibility _lowerCamelCase : Optional[int] = True if kwargs.get('''max_value''' , __lowerCAmelCase ) is not None: _lowerCamelCase : str = '''The `max_value` argument is deprecated. Please use `decay` instead.''' deprecate('''max_value''' , '''1.0.0''' , __lowerCAmelCase , standard_warn=__lowerCAmelCase ) _lowerCamelCase : Any = kwargs['''max_value'''] if kwargs.get('''min_value''' , __lowerCAmelCase ) is not None: _lowerCamelCase : Optional[int] = '''The `min_value` argument is deprecated. Please use `min_decay` instead.''' deprecate('''min_value''' , '''1.0.0''' , __lowerCAmelCase , standard_warn=__lowerCAmelCase ) _lowerCamelCase : Optional[int] = kwargs['''min_value'''] _lowerCamelCase : int = list(__lowerCAmelCase ) _lowerCamelCase : int = [p.clone().detach() for p in parameters] if kwargs.get('''device''' , __lowerCAmelCase ) is not None: _lowerCamelCase : Tuple = '''The `device` argument is deprecated. Please use `to` instead.''' deprecate('''device''' , '''1.0.0''' , __lowerCAmelCase , standard_warn=__lowerCAmelCase ) self.to(device=kwargs['''device'''] ) _lowerCamelCase : Union[str, Any] = None _lowerCamelCase : Tuple = decay _lowerCamelCase : Any = min_decay _lowerCamelCase : str = update_after_step _lowerCamelCase : Any = use_ema_warmup _lowerCamelCase : Optional[Any] = inv_gamma _lowerCamelCase : Tuple = power _lowerCamelCase : Any = 0 _lowerCamelCase : Any = None # set in `step()` _lowerCamelCase : int = model_cls _lowerCamelCase : Dict = model_config @classmethod def SCREAMING_SNAKE_CASE ( cls : int , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[int] ): """simple docstring""" _lowerCamelCase , _lowerCamelCase : Optional[int] = model_cls.load_config(__lowerCAmelCase , return_unused_kwargs=__lowerCAmelCase ) _lowerCamelCase : int = model_cls.from_pretrained(__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = cls(model.parameters() , model_cls=__lowerCAmelCase , model_config=model.config ) ema_model.load_state_dict(__lowerCAmelCase ) return ema_model def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : Optional[int] ): """simple docstring""" if self.model_cls is None: raise ValueError('''`save_pretrained` can only be used if `model_cls` was defined at __init__.''' ) if self.model_config is None: raise ValueError('''`save_pretrained` can only be used if `model_config` was defined at __init__.''' ) _lowerCamelCase : Dict = self.model_cls.from_config(self.model_config ) _lowerCamelCase : int = self.state_dict() state_dict.pop('''shadow_params''' , __lowerCAmelCase ) model.register_to_config(**__lowerCAmelCase ) self.copy_to(model.parameters() ) model.save_pretrained(__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : int ): """simple docstring""" _lowerCamelCase : List[str] = max(0 , optimization_step - self.update_after_step - 1 ) if step <= 0: return 0.0 if self.use_ema_warmup: _lowerCamelCase : List[Any] = 1 - (1 + step / self.inv_gamma) ** -self.power else: _lowerCamelCase : str = (1 + step) / (1_0 + step) _lowerCamelCase : List[Any] = min(__lowerCAmelCase , self.decay ) # make sure decay is not smaller than min_decay _lowerCamelCase : str = max(__lowerCAmelCase , self.min_decay ) return cur_decay_value @torch.no_grad() def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : Iterable[torch.nn.Parameter] ): """simple docstring""" if isinstance(__lowerCAmelCase , torch.nn.Module ): _lowerCamelCase : int = ( '''Passing a `torch.nn.Module` to `ExponentialMovingAverage.step` is deprecated. ''' '''Please pass the parameters of the module instead.''' ) deprecate( '''passing a `torch.nn.Module` to `ExponentialMovingAverage.step`''' , '''1.0.0''' , __lowerCAmelCase , standard_warn=__lowerCAmelCase , ) _lowerCamelCase : Dict = parameters.parameters() _lowerCamelCase : List[Any] = list(__lowerCAmelCase ) self.optimization_step += 1 # Compute the decay factor for the exponential moving average. _lowerCamelCase : Optional[int] = self.get_decay(self.optimization_step ) _lowerCamelCase : Optional[Any] = decay _lowerCamelCase : Union[str, Any] = 1 - decay _lowerCamelCase : Dict = contextlib.nullcontext if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled(): import deepspeed for s_param, param in zip(self.shadow_params , __lowerCAmelCase ): if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled(): _lowerCamelCase : Optional[int] = deepspeed.zero.GatheredParameters(__lowerCAmelCase , modifier_rank=__lowerCAmelCase ) with context_manager(): if param.requires_grad: s_param.sub_(one_minus_decay * (s_param - param) ) else: s_param.copy_(__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : Iterable[torch.nn.Parameter] ): """simple docstring""" _lowerCamelCase : List[str] = list(__lowerCAmelCase ) for s_param, param in zip(self.shadow_params , __lowerCAmelCase ): param.data.copy_(s_param.to(param.device ).data ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __lowerCAmelCase : List[Any]=None , __lowerCAmelCase : List[str]=None ): """simple docstring""" _lowerCamelCase : Optional[Any] = [ p.to(device=__lowerCAmelCase , dtype=__lowerCAmelCase ) if p.is_floating_point() else p.to(device=__lowerCAmelCase ) for p in self.shadow_params ] def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return { "decay": self.decay, "min_decay": self.min_decay, "optimization_step": self.optimization_step, "update_after_step": self.update_after_step, "use_ema_warmup": self.use_ema_warmup, "inv_gamma": self.inv_gamma, "power": self.power, "shadow_params": self.shadow_params, } def SCREAMING_SNAKE_CASE ( self : Tuple , __lowerCAmelCase : Iterable[torch.nn.Parameter] ): """simple docstring""" _lowerCamelCase : Optional[Any] = [param.detach().cpu().clone() for param in parameters] def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : Iterable[torch.nn.Parameter] ): """simple docstring""" if self.temp_stored_params is None: raise RuntimeError('''This ExponentialMovingAverage has no `store()`ed weights ''' '''to `restore()`''' ) for c_param, param in zip(self.temp_stored_params , __lowerCAmelCase ): param.data.copy_(c_param.data ) # Better memory-wise. _lowerCamelCase : str = None def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : dict ): """simple docstring""" _lowerCamelCase : Any = copy.deepcopy(__lowerCAmelCase ) _lowerCamelCase : str = state_dict.get('''decay''' , self.decay ) if self.decay < 0.0 or self.decay > 1.0: raise ValueError('''Decay must be between 0 and 1''' ) _lowerCamelCase : Any = state_dict.get('''min_decay''' , self.min_decay ) if not isinstance(self.min_decay , __lowerCAmelCase ): raise ValueError('''Invalid min_decay''' ) _lowerCamelCase : Union[str, Any] = state_dict.get('''optimization_step''' , self.optimization_step ) if not isinstance(self.optimization_step , __lowerCAmelCase ): raise ValueError('''Invalid optimization_step''' ) _lowerCamelCase : Optional[Any] = state_dict.get('''update_after_step''' , self.update_after_step ) if not isinstance(self.update_after_step , __lowerCAmelCase ): raise ValueError('''Invalid update_after_step''' ) _lowerCamelCase : Tuple = state_dict.get('''use_ema_warmup''' , self.use_ema_warmup ) if not isinstance(self.use_ema_warmup , __lowerCAmelCase ): raise ValueError('''Invalid use_ema_warmup''' ) _lowerCamelCase : int = state_dict.get('''inv_gamma''' , self.inv_gamma ) if not isinstance(self.inv_gamma , (float, int) ): raise ValueError('''Invalid inv_gamma''' ) _lowerCamelCase : Tuple = state_dict.get('''power''' , self.power ) if not isinstance(self.power , (float, int) ): raise ValueError('''Invalid power''' ) _lowerCamelCase : List[Any] = state_dict.get('''shadow_params''' , __lowerCAmelCase ) if shadow_params is not None: _lowerCamelCase : Optional[Any] = shadow_params if not isinstance(self.shadow_params , __lowerCAmelCase ): raise ValueError('''shadow_params must be a list''' ) if not all(isinstance(__lowerCAmelCase , torch.Tensor ) for p in self.shadow_params ): raise ValueError('''shadow_params must all be Tensors''' )
83
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # and perform gradient accumulation # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## lowerCAmelCase : str = 16 lowerCAmelCase : List[Any] = 32 def A_ ( _UpperCAmelCase , _UpperCAmelCase = 16 ): SCREAMING_SNAKE_CASE_: List[Any] = AutoTokenizer.from_pretrained("bert-base-cased" ) SCREAMING_SNAKE_CASE_: Tuple = load_dataset("glue" , "mrpc" ) def tokenize_function(_UpperCAmelCase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE_: List[Any] = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE_: str = datasets.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=["idx", "sentence1", "sentence2"] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE_: Optional[Any] = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(_UpperCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE_: List[Any] = 1_28 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE_: Tuple = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE_: int = 8 else: SCREAMING_SNAKE_CASE_: Any = None return tokenizer.pad( _UpperCAmelCase , padding="longest" , max_length=_UpperCAmelCase , pad_to_multiple_of=_UpperCAmelCase , return_tensors="pt" , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE_: Optional[Any] = DataLoader( tokenized_datasets["train"] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple = DataLoader( tokenized_datasets["validation"] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""", None) == "1": from accelerate.test_utils.training import mocked_dataloaders lowerCAmelCase : Optional[int] = mocked_dataloaders # noqa: F811 def A_ ( _UpperCAmelCase , _UpperCAmelCase ): # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS" , _UpperCAmelCase ) == "1": SCREAMING_SNAKE_CASE_: Tuple = 2 # New Code # SCREAMING_SNAKE_CASE_: List[str] = int(args.gradient_accumulation_steps ) # Initialize accelerator SCREAMING_SNAKE_CASE_: int = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=_UpperCAmelCase ) if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1: raise NotImplementedError( "Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE_: Tuple = config["lr"] SCREAMING_SNAKE_CASE_: List[str] = int(config["num_epochs"] ) SCREAMING_SNAKE_CASE_: List[str] = int(config["seed"] ) SCREAMING_SNAKE_CASE_: Optional[int] = int(config["batch_size"] ) SCREAMING_SNAKE_CASE_: str = evaluate.load("glue" , "mrpc" ) set_seed(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[str] = get_dataloaders(_UpperCAmelCase , _UpperCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE_: Union[str, Any] = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=_UpperCAmelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE_: List[Any] = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE_: Union[str, Any] = AdamW(params=model.parameters() , lr=_UpperCAmelCase ) # Instantiate scheduler SCREAMING_SNAKE_CASE_: str = get_linear_schedule_with_warmup( optimizer=_UpperCAmelCase , num_warmup_steps=1_00 , num_training_steps=(len(_UpperCAmelCase ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Dict = accelerator.prepare( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) # Now we train the model for epoch in range(_UpperCAmelCase ): model.train() for step, batch in enumerate(_UpperCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(_UpperCAmelCase ): SCREAMING_SNAKE_CASE_: List[Any] = model(**_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] = output.loss accelerator.backward(_UpperCAmelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(_UpperCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE_: Optional[Any] = model(**_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=_UpperCAmelCase , references=_UpperCAmelCase , ) SCREAMING_SNAKE_CASE_: List[str] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"epoch {epoch}:" , _UpperCAmelCase ) def A_ ( ): SCREAMING_SNAKE_CASE_: str = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=_UpperCAmelCase , default=_UpperCAmelCase , choices=["no", "fp16", "bf16", "fp8"] , help="Whether to use mixed precision. Choose" "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." "and an Nvidia Ampere GPU." , ) # New Code # parser.add_argument( "--gradient_accumulation_steps" , type=_UpperCAmelCase , default=1 , help="The number of minibatches to be ran before gradients are accumulated." , ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) SCREAMING_SNAKE_CASE_: List[Any] = parser.parse_args() SCREAMING_SNAKE_CASE_: Tuple = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(_UpperCAmelCase , _UpperCAmelCase ) if __name__ == "__main__": main()
671
0
from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf UpperCAmelCase = logging.get_logger(__name__) @dataclass class A_ ( __lowerCamelCase ): '''simple docstring''' _UpperCamelCase : Dict = [ """no_inference""", """no_cuda""", """no_tpu""", """no_speed""", """no_memory""", """no_env_print""", """no_multi_process""", ] def __init__( self , **snake_case ): for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: lowercase = deprecated_arg[3:] lowercase = not kwargs.pop(snake_case ) logger.warning( F'''{deprecated_arg} is depreciated. Please use --no-{positive_arg} or''' F''' {positive_arg}={kwargs[positive_arg]}''' ) lowercase = kwargs.pop('tpu_name' , self.tpu_name ) lowercase = kwargs.pop('device_idx' , self.device_idx ) lowercase = kwargs.pop('eager_mode' , self.eager_mode ) lowercase = kwargs.pop('use_xla' , self.use_xla ) super().__init__(**snake_case ) _UpperCamelCase : str = field( default=__lowerCamelCase , metadata={"""help""": """Name of TPU"""} , ) _UpperCamelCase : int = field( default=0 , metadata={"""help""": """CPU / GPU device index. Defaults to 0."""} , ) _UpperCamelCase : bool = field(default=__lowerCamelCase , metadata={"""help""": """Benchmark models in eager model."""} ) _UpperCamelCase : bool = field( default=__lowerCamelCase , metadata={ """help""": """Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.""" } , ) @cached_property def SCREAMING_SNAKE_CASE__ ( self ): requires_backends(self , ['tf'] ) lowercase = None if self.tpu: try: if self.tpu_name: lowercase = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: lowercase = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: lowercase = None return tpu @cached_property def SCREAMING_SNAKE_CASE__ ( self ): requires_backends(self , ['tf'] ) if self.is_tpu: tf.config.experimental_connect_to_cluster(self._setup_tpu ) tf.tpu.experimental.initialize_tpu_system(self._setup_tpu ) lowercase = tf.distribute.TPUStrategy(self._setup_tpu ) else: # currently no multi gpu is allowed if self.is_gpu: # TODO: Currently only single GPU is supported tf.config.set_visible_devices(self.gpu_list[self.device_idx] , 'GPU' ) lowercase = tf.distribute.OneDeviceStrategy(device=F'''/gpu:{self.device_idx}''' ) else: tf.config.set_visible_devices([] , 'GPU' ) # disable GPU lowercase = tf.distribute.OneDeviceStrategy(device=F'''/cpu:{self.device_idx}''' ) return strategy @property def SCREAMING_SNAKE_CASE__ ( self ): requires_backends(self , ['tf'] ) return self._setup_tpu is not None @property def SCREAMING_SNAKE_CASE__ ( self ): requires_backends(self , ['tf'] ) return self._setup_strategy @property def SCREAMING_SNAKE_CASE__ ( self ): requires_backends(self , ['tf'] ) return tf.config.list_physical_devices('GPU' ) @property def SCREAMING_SNAKE_CASE__ ( self ): requires_backends(self , ['tf'] ) if self.cuda: return len(self.gpu_list ) return 0 @property def SCREAMING_SNAKE_CASE__ ( self ): return self.n_gpu > 0
84
from math import asin, atan, cos, radians, sin, sqrt, tan lowerCAmelCase : Union[str, Any] = 637_8137.0 lowerCAmelCase : int = 635_6752.31_4245 lowerCAmelCase : Union[str, Any] = 6378137 def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: List[Any] = (AXIS_A - AXIS_B) / AXIS_A SCREAMING_SNAKE_CASE_: str = atan((1 - flattening) * tan(radians(_UpperCAmelCase ) ) ) SCREAMING_SNAKE_CASE_: Optional[int] = atan((1 - flattening) * tan(radians(_UpperCAmelCase ) ) ) SCREAMING_SNAKE_CASE_: Any = radians(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Dict = radians(_UpperCAmelCase ) # Equation SCREAMING_SNAKE_CASE_: str = sin((phi_a - phi_a) / 2 ) SCREAMING_SNAKE_CASE_: List[Any] = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda SCREAMING_SNAKE_CASE_: Tuple = sqrt(sin_sq_phi + (cos(_UpperCAmelCase ) * cos(_UpperCAmelCase ) * sin_sq_lambda) ) return 2 * RADIUS * asin(_UpperCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
671
0
import qiskit def _a ( lowercase__ : int = 2 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = qubits # Using Aer's simulator SCREAMING_SNAKE_CASE__ : Optional[Any] = qiskit.Aer.get_backend('aer_simulator' ) # Creating a Quantum Circuit acting on the q register SCREAMING_SNAKE_CASE__ : Dict = qiskit.QuantumCircuit(lowercase__ , lowercase__ ) # Adding a H gate on qubit 0 (now q0 in superposition) circuit.h(0 ) for i in range(1 , lowercase__ ): # Adding CX (CNOT) gate circuit.cx(i - 1 , lowercase__ ) # Mapping the quantum measurement to the classical bits circuit.measure(list(range(lowercase__ ) ) , list(range(lowercase__ ) ) ) # Now measuring any one qubit would affect other qubits to collapse # their super position and have same state as the measured one. # Executing the circuit on the simulator SCREAMING_SNAKE_CASE__ : str = qiskit.execute(lowercase__ , lowercase__ , shots=10_00 ) return job.result().get_counts(lowercase__ ) if __name__ == "__main__": print(F"""Total count for various states are: {quantum_entanglement(3)}""")
85
import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): # Initialise PyTorch model SCREAMING_SNAKE_CASE_: List[Any] = BertConfig.from_json_file(_UpperCAmelCase ) print(f"Building PyTorch model from configuration: {config}" ) SCREAMING_SNAKE_CASE_: Tuple = BertForPreTraining(_UpperCAmelCase ) # Load weights from tf checkpoint load_tf_weights_in_bert(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) # Save pytorch-model print(f"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , _UpperCAmelCase ) if __name__ == "__main__": lowerCAmelCase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--bert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained BERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) lowerCAmelCase : Optional[Any] = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
671
0
import argparse import json import os import torch from transformers import LukeConfig, LukeModel, LukeTokenizer, RobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def __snake_case ( __UpperCamelCase : Tuple ,__UpperCamelCase : Dict ,__UpperCamelCase : Union[str, Any] ,__UpperCamelCase : List[Any] ,__UpperCamelCase : List[Any] ): """simple docstring""" with open(__UpperCamelCase ) as metadata_file: A_ = json.load(__UpperCamelCase ) A_ = LukeConfig(use_entity_aware_attention=__UpperCamelCase ,**metadata["model_config"] ) # Load in the weights from the checkpoint_path A_ = torch.load(__UpperCamelCase ,map_location="cpu" ) # Load the entity vocab file A_ = load_entity_vocab(__UpperCamelCase ) A_ = RobertaTokenizer.from_pretrained(metadata["model_config"]["bert_model_name"] ) # Add special tokens to the token vocabulary for downstream tasks A_ = AddedToken("<ent>" ,lstrip=__UpperCamelCase ,rstrip=__UpperCamelCase ) A_ = AddedToken("<ent2>" ,lstrip=__UpperCamelCase ,rstrip=__UpperCamelCase ) tokenizer.add_special_tokens({"additional_special_tokens": [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(f'''Saving tokenizer to {pytorch_dump_folder_path}''' ) tokenizer.save_pretrained(__UpperCamelCase ) with open(os.path.join(__UpperCamelCase ,LukeTokenizer.vocab_files_names["entity_vocab_file"] ) ,"w" ) as f: json.dump(__UpperCamelCase ,__UpperCamelCase ) A_ = LukeTokenizer.from_pretrained(__UpperCamelCase ) # Initialize the embeddings of the special tokens A_ = state_dict["embeddings.word_embeddings.weight"] A_ = word_emb[tokenizer.convert_tokens_to_ids(["@"] )[0]].unsqueeze(0 ) A_ = word_emb[tokenizer.convert_tokens_to_ids(["#"] )[0]].unsqueeze(0 ) A_ = torch.cat([word_emb, ent_emb, enta_emb] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: A_ = f'''encoder.layer.{layer_index}.attention.self.''' A_ = state_dict[prefix + matrix_name] A_ = state_dict[prefix + matrix_name] A_ = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks A_ = state_dict["entity_embeddings.entity_embeddings.weight"] A_ = entity_emb[entity_vocab["[MASK]"]] A_ = LukeModel(config=__UpperCamelCase ).eval() A_ , A_ = model.load_state_dict(__UpperCamelCase ,strict=__UpperCamelCase ) if not (len(__UpperCamelCase ) == 1 and missing_keys[0] == "embeddings.position_ids"): raise ValueError(f'''Missing keys {", ".join(__UpperCamelCase )}. Expected only missing embeddings.position_ids''' ) if not (all(key.startswith("entity_predictions" ) or key.startswith("lm_head" ) for key in unexpected_keys )): raise ValueError( "Unexpected keys" f''' {", ".join([key for key in unexpected_keys if not (key.startswith("entity_predictions" ) or key.startswith("lm_head" ))] )}''' ) # Check outputs A_ = LukeTokenizer.from_pretrained(__UpperCamelCase ,task="entity_classification" ) A_ = ( "Top seed Ana Ivanovic said on Thursday she could hardly believe her luck as a fortuitous netcord helped the" " new world number one avoid a humiliating second- round exit at Wimbledon ." ) A_ = (39, 42) A_ = tokenizer(__UpperCamelCase ,entity_spans=[span] ,add_prefix_space=__UpperCamelCase ,return_tensors="pt" ) A_ = model(**__UpperCamelCase ) # Verify word hidden states if model_size == "large": A_ = torch.Size((1, 42, 1024) ) A_ = torch.tensor( [[0.0133, 0.0865, 0.0095], [0.3093, -0.2576, -0.7418], [-0.1720, -0.2117, -0.2869]] ) else: # base A_ = torch.Size((1, 42, 768) ) A_ = torch.tensor([[0.0037, 0.1368, -0.0091], [0.1099, 0.3329, -0.1095], [0.0765, 0.5335, 0.1179]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( f'''Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}''' ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] ,__UpperCamelCase ,atol=1E-4 ): raise ValueError # Verify entity hidden states if model_size == "large": A_ = torch.Size((1, 1, 1024) ) A_ = torch.tensor([[0.0466, -0.0106, -0.0179]] ) else: # base A_ = torch.Size((1, 1, 768) ) A_ = torch.tensor([[0.1457, 0.1044, 0.0174]] ) if not (outputs.entity_last_hidden_state.shape != expected_shape): raise ValueError( f'''Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is''' f''' {expected_shape}''' ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] ,__UpperCamelCase ,atol=1E-4 ): raise ValueError # Finally, save our PyTorch model and tokenizer print("Saving PyTorch model to {}".format(__UpperCamelCase ) ) model.save_pretrained(__UpperCamelCase ) def __snake_case ( __UpperCamelCase : str ): """simple docstring""" A_ = {} with open(__UpperCamelCase ,"r" ,encoding="utf-8" ) as f: for index, line in enumerate(__UpperCamelCase ): A_ , A_ = line.rstrip().split("\t" ) A_ = index return entity_vocab if __name__ == "__main__": __a :Dict = argparse.ArgumentParser() # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Path to a pytorch_model.bin file.') parser.add_argument( '--metadata_path', default=None, type=str, help='Path to a metadata.json file, defining the configuration.' ) parser.add_argument( '--entity_vocab_path', default=None, type=str, help='Path to an entity_vocab.tsv file, containing the entity vocabulary.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to where to dump the output PyTorch model.' ) parser.add_argument( '--model_size', default='base', type=str, choices=['base', 'large'], help='Size of the model to be converted.' ) __a :Tuple = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
86
import math def A_ ( _UpperCAmelCase ): if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_UpperCAmelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def A_ ( _UpperCAmelCase = 0.1 ): SCREAMING_SNAKE_CASE_: Union[str, Any] = 3 SCREAMING_SNAKE_CASE_: Optional[int] = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ): primes += is_prime(_UpperCAmelCase ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
671
0
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCamelCase : Any = { """configuration_mctct""": ["""MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MCTCTConfig"""], """feature_extraction_mctct""": ["""MCTCTFeatureExtractor"""], """processing_mctct""": ["""MCTCTProcessor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Optional[int] = [ """MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST""", """MCTCTForCTC""", """MCTCTModel""", """MCTCTPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mctct import MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP, MCTCTConfig from .feature_extraction_mctct import MCTCTFeatureExtractor from .processing_mctct import MCTCTProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mctct import MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST, MCTCTForCTC, MCTCTModel, MCTCTPreTrainedModel else: import sys _lowerCamelCase : List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
87
import re def A_ ( _UpperCAmelCase ): return [char.split() for char in re.split(R"[^ a-z A-Z 0-9 \s]" , str_ )] def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: int = split_input(str_ ) return "".join( ["".join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): try: SCREAMING_SNAKE_CASE_: List[Any] = split_input(_UpperCAmelCase ) if upper: SCREAMING_SNAKE_CASE_: List[str] = "".join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: SCREAMING_SNAKE_CASE_: Optional[int] = "".join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def A_ ( _UpperCAmelCase ): return to_simple_case(_UpperCAmelCase ) def A_ ( _UpperCAmelCase ): try: SCREAMING_SNAKE_CASE_: Optional[int] = to_simple_case(_UpperCAmelCase ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def A_ ( _UpperCAmelCase , _UpperCAmelCase ): return to_complex_case(_UpperCAmelCase , _UpperCAmelCase , "_" ) def A_ ( _UpperCAmelCase , _UpperCAmelCase ): return to_complex_case(_UpperCAmelCase , _UpperCAmelCase , "-" ) if __name__ == "__main__": __import__("""doctest""").testmod()
671
0
"""simple docstring""" def _snake_case ( __snake_case : str , __snake_case : str ): """simple docstring""" _lowerCamelCase : str = len(__snake_case ) _lowerCamelCase : Union[str, Any] = len(__snake_case ) _lowerCamelCase : int = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] _lowerCamelCase : Union[str, Any] = True for i in range(__snake_case ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: _lowerCamelCase : Tuple = True if a[i].islower(): _lowerCamelCase : Tuple = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
88
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING lowerCAmelCase : Union[str, Any] = logging.get_logger(__name__) class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : List[Any] = '''upernet''' def __init__( self : Any , lowerCAmelCase__ : Union[str, Any]=None , lowerCAmelCase__ : List[str]=512 , lowerCAmelCase__ : Any=0.02 , lowerCAmelCase__ : str=[1, 2, 3, 6] , lowerCAmelCase__ : Optional[Any]=True , lowerCAmelCase__ : Dict=0.4 , lowerCAmelCase__ : int=384 , lowerCAmelCase__ : Union[str, Any]=256 , lowerCAmelCase__ : Any=1 , lowerCAmelCase__ : Tuple=False , lowerCAmelCase__ : List[str]=255 , **lowerCAmelCase__ : List[str] , ): super().__init__(**lowerCAmelCase__) if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.") SCREAMING_SNAKE_CASE_: Dict = CONFIG_MAPPING["resnet"](out_features=["stage1", "stage2", "stage3", "stage4"]) elif isinstance(lowerCAmelCase__ , lowerCAmelCase__): SCREAMING_SNAKE_CASE_: str = backbone_config.get("model_type") SCREAMING_SNAKE_CASE_: str = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE_: Tuple = config_class.from_dict(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: str = backbone_config SCREAMING_SNAKE_CASE_: Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_: Dict = initializer_range SCREAMING_SNAKE_CASE_: Any = pool_scales SCREAMING_SNAKE_CASE_: Optional[Any] = use_auxiliary_head SCREAMING_SNAKE_CASE_: str = auxiliary_loss_weight SCREAMING_SNAKE_CASE_: List[Any] = auxiliary_in_channels SCREAMING_SNAKE_CASE_: Union[str, Any] = auxiliary_channels SCREAMING_SNAKE_CASE_: Dict = auxiliary_num_convs SCREAMING_SNAKE_CASE_: str = auxiliary_concat_input SCREAMING_SNAKE_CASE_: Dict = loss_ignore_index def _SCREAMING_SNAKE_CASE ( self : Tuple): SCREAMING_SNAKE_CASE_: Tuple = copy.deepcopy(self.__dict__) SCREAMING_SNAKE_CASE_: int = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE_: Optional[int] = self.__class__.model_type return output
671
0
from __future__ import annotations import unittest from transformers import FunnelConfig, is_tf_available from transformers.testing_utils import require_tf from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, ) class _lowerCamelCase: def __init__( self, lowerCamelCase, lowerCamelCase=13, lowerCamelCase=7, lowerCamelCase=True, lowerCamelCase=True, lowerCamelCase=True, lowerCamelCase=True, lowerCamelCase=99, lowerCamelCase=[1, 1, 2], lowerCamelCase=1, lowerCamelCase=32, lowerCamelCase=4, lowerCamelCase=8, lowerCamelCase=37, lowerCamelCase="gelu_new", lowerCamelCase=0.1, lowerCamelCase=0.1, lowerCamelCase=0.0, lowerCamelCase=5_12, lowerCamelCase=3, lowerCamelCase=0.0_2, lowerCamelCase=3, lowerCamelCase=4, lowerCamelCase=None, lowerCamelCase=False, ) -> str: """simple docstring""" _lowercase : Any = parent _lowercase : Union[str, Any] = batch_size _lowercase : Any = seq_length _lowercase : Any = is_training _lowercase : Union[str, Any] = use_input_mask _lowercase : List[Any] = use_token_type_ids _lowercase : Tuple = use_labels _lowercase : str = vocab_size _lowercase : List[Any] = block_sizes _lowercase : List[str] = num_decoder_layers _lowercase : Tuple = d_model _lowercase : Union[str, Any] = n_head _lowercase : List[str] = d_head _lowercase : Optional[Any] = d_inner _lowercase : Union[str, Any] = hidden_act _lowercase : Optional[Any] = hidden_dropout _lowercase : Union[str, Any] = attention_dropout _lowercase : int = activation_dropout _lowercase : str = max_position_embeddings _lowercase : Optional[Any] = type_vocab_size _lowercase : Union[str, Any] = 2 _lowercase : str = num_labels _lowercase : List[str] = num_choices _lowercase : Any = scope _lowercase : List[str] = initializer_std # Used in the tests to check the size of the first attention layer _lowercase : Tuple = n_head # Used in the tests to check the size of the first hidden state _lowercase : Optional[Any] = self.d_model # Used in the tests to check the number of output hidden states/attentions _lowercase : List[str] = sum(self.block_sizes) + (0 if base else self.num_decoder_layers) # FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with # the last hidden state of the first block (which is the first hidden state of the decoder). if not base: _lowercase : List[Any] = self.num_hidden_layers + 2 def UpperCamelCase ( self) -> str: """simple docstring""" _lowercase : List[Any] = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) _lowercase : str = None if self.use_input_mask: _lowercase : List[Any] = random_attention_mask([self.batch_size, self.seq_length]) _lowercase : Dict = None if self.use_token_type_ids: _lowercase : Dict = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) _lowercase : Dict = None _lowercase : List[Any] = None _lowercase : Optional[Any] = None if self.use_labels: _lowercase : Any = ids_tensor([self.batch_size], self.type_sequence_label_size) _lowercase : Tuple = ids_tensor([self.batch_size, self.seq_length], self.num_labels) _lowercase : Union[str, Any] = ids_tensor([self.batch_size], self.num_choices) _lowercase : Any = FunnelConfig( vocab_size=self.vocab_size, block_sizes=self.block_sizes, num_decoder_layers=self.num_decoder_layers, d_model=self.d_model, n_head=self.n_head, d_head=self.d_head, d_inner=self.d_inner, hidden_act=self.hidden_act, hidden_dropout=self.hidden_dropout, attention_dropout=self.attention_dropout, activation_dropout=self.activation_dropout, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, initializer_std=self.initializer_std, ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, ) -> int: """simple docstring""" _lowercase : List[Any] = TFFunnelModel(config=lowerCamelCase) _lowercase : List[str] = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} _lowercase : Tuple = model(lowerCamelCase) _lowercase : Tuple = [input_ids, input_mask] _lowercase : Tuple = model(lowerCamelCase) _lowercase : List[str] = model(lowerCamelCase) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.d_model)) _lowercase : Union[str, Any] = False _lowercase : Union[str, Any] = TFFunnelModel(config=lowerCamelCase) _lowercase : Optional[int] = model(lowerCamelCase) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.d_model)) _lowercase : Optional[int] = False _lowercase : Any = TFFunnelModel(config=lowerCamelCase) _lowercase : List[str] = model(lowerCamelCase) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.d_model)) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, ) -> str: """simple docstring""" _lowercase : Optional[int] = TFFunnelBaseModel(config=lowerCamelCase) _lowercase : List[Any] = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} _lowercase : Any = model(lowerCamelCase) _lowercase : str = [input_ids, input_mask] _lowercase : Optional[Any] = model(lowerCamelCase) _lowercase : str = model(lowerCamelCase) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, 2, self.d_model)) _lowercase : List[str] = False _lowercase : Dict = TFFunnelBaseModel(config=lowerCamelCase) _lowercase : List[str] = model(lowerCamelCase) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, 3, self.d_model)) _lowercase : List[Any] = False _lowercase : str = TFFunnelBaseModel(config=lowerCamelCase) _lowercase : Union[str, Any] = model(lowerCamelCase) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, 2, self.d_model)) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, ) -> Tuple: """simple docstring""" _lowercase : Dict = TFFunnelForPreTraining(config=lowerCamelCase) _lowercase : str = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} _lowercase : List[Any] = model(lowerCamelCase) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length)) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, ) -> Dict: """simple docstring""" _lowercase : Tuple = TFFunnelForMaskedLM(config=lowerCamelCase) _lowercase : List[str] = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} _lowercase : List[str] = model(lowerCamelCase) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, ) -> Tuple: """simple docstring""" _lowercase : Dict = self.num_labels _lowercase : List[str] = TFFunnelForSequenceClassification(config=lowerCamelCase) _lowercase : Union[str, Any] = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} _lowercase : Optional[int] = model(lowerCamelCase) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, ) -> str: """simple docstring""" _lowercase : List[Any] = self.num_choices _lowercase : Any = TFFunnelForMultipleChoice(config=lowerCamelCase) _lowercase : Dict = tf.tile(tf.expand_dims(lowerCamelCase, 1), (1, self.num_choices, 1)) _lowercase : Dict = tf.tile(tf.expand_dims(lowerCamelCase, 1), (1, self.num_choices, 1)) _lowercase : List[Any] = tf.tile(tf.expand_dims(lowerCamelCase, 1), (1, self.num_choices, 1)) _lowercase : int = { 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, 'token_type_ids': multiple_choice_token_type_ids, } _lowercase : Optional[int] = model(lowerCamelCase) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, ) -> Optional[int]: """simple docstring""" _lowercase : Tuple = self.num_labels _lowercase : Optional[int] = TFFunnelForTokenClassification(config=lowerCamelCase) _lowercase : List[str] = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} _lowercase : int = model(lowerCamelCase) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, ) -> Tuple: """simple docstring""" _lowercase : Dict = TFFunnelForQuestionAnswering(config=lowerCamelCase) _lowercase : Union[str, Any] = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} _lowercase : Any = model(lowerCamelCase) self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) def UpperCamelCase ( self) -> Optional[Any]: """simple docstring""" _lowercase : List[str] = self.prepare_config_and_inputs() ( ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ) : Dict = config_and_inputs _lowercase : Any = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class _lowerCamelCase( _a, _a, unittest.TestCase ): lowercase_ : int = ( ( TFFunnelModel, TFFunnelForMaskedLM, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForTokenClassification, ) if is_tf_available() else () ) lowercase_ : Optional[int] = ( { """feature-extraction""": (TFFunnelBaseModel, TFFunnelModel), """fill-mask""": TFFunnelForMaskedLM, """question-answering""": TFFunnelForQuestionAnswering, """text-classification""": TFFunnelForSequenceClassification, """token-classification""": TFFunnelForTokenClassification, """zero-shot""": TFFunnelForSequenceClassification, } if is_tf_available() else {} ) lowercase_ : Optional[Any] = False lowercase_ : Tuple = False def UpperCamelCase ( self) -> Union[str, Any]: """simple docstring""" _lowercase : Optional[int] = TFFunnelModelTester(self) _lowercase : Any = ConfigTester(self, config_class=lowerCamelCase) def UpperCamelCase ( self) -> Optional[int]: """simple docstring""" self.config_tester.run_common_tests() def UpperCamelCase ( self) -> Optional[int]: """simple docstring""" _lowercase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase) def UpperCamelCase ( self) -> Optional[Any]: """simple docstring""" _lowercase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*lowerCamelCase) def UpperCamelCase ( self) -> Any: """simple docstring""" _lowercase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*lowerCamelCase) def UpperCamelCase ( self) -> Tuple: """simple docstring""" _lowercase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowerCamelCase) def UpperCamelCase ( self) -> Optional[int]: """simple docstring""" _lowercase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowerCamelCase) @require_tf class _lowerCamelCase( _a, unittest.TestCase ): lowercase_ : int = ( (TFFunnelBaseModel, TFFunnelForMultipleChoice, TFFunnelForSequenceClassification) if is_tf_available() else () ) lowercase_ : Dict = False lowercase_ : List[Any] = False def UpperCamelCase ( self) -> List[Any]: """simple docstring""" _lowercase : Tuple = TFFunnelModelTester(self, base=lowerCamelCase) _lowercase : List[str] = ConfigTester(self, config_class=lowerCamelCase) def UpperCamelCase ( self) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def UpperCamelCase ( self) -> List[str]: """simple docstring""" _lowercase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_base_model(*lowerCamelCase) def UpperCamelCase ( self) -> Any: """simple docstring""" _lowercase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*lowerCamelCase) def UpperCamelCase ( self) -> List[str]: """simple docstring""" _lowercase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*lowerCamelCase)
89
import pickle import unittest import torch from accelerate import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils import require_cpu @require_cpu class __lowercase ( unittest.TestCase ): """simple docstring""" def _SCREAMING_SNAKE_CASE ( self : Any): SCREAMING_SNAKE_CASE_: List[str] = torch.nn.Linear(10 , 10) SCREAMING_SNAKE_CASE_: Union[str, Any] = torch.optim.SGD(model.parameters() , 0.1) SCREAMING_SNAKE_CASE_: Any = Accelerator() SCREAMING_SNAKE_CASE_: List[str] = accelerator.prepare(lowerCAmelCase__) try: pickle.loads(pickle.dumps(lowerCAmelCase__)) except Exception as e: self.fail(F"Accelerated optimizer pickling failed with {e}") AcceleratorState._reset_state()
671
0
'''simple docstring''' from __future__ import annotations def _snake_case ( A , A ) -> float: lowerCAmelCase__ = sorted(numsa + numsa ) lowerCAmelCase__ , lowerCAmelCase__ = divmod(len(A ) , 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() __UpperCAmelCase = [float(x) for x in input('''Enter the elements of first array: ''').split()] __UpperCAmelCase = [float(x) for x in input('''Enter the elements of second array: ''').split()] print(f"""The median of two arrays is: {median_of_two_arrays(array_a, array_a)}""")
90
from itertools import count def A_ ( _UpperCAmelCase = 50 ): SCREAMING_SNAKE_CASE_: Union[str, Any] = [1] * min_block_length for n in count(_UpperCAmelCase ): fill_count_functions.append(1 ) for block_length in range(_UpperCAmelCase , 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() = }''')
671
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _lowercase = { '''configuration_groupvit''': [ '''GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GroupViTConfig''', '''GroupViTOnnxConfig''', '''GroupViTTextConfig''', '''GroupViTVisionConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GroupViTModel''', '''GroupViTPreTrainedModel''', '''GroupViTTextModel''', '''GroupViTVisionModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase = [ '''TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFGroupViTModel''', '''TFGroupViTPreTrainedModel''', '''TFGroupViTTextModel''', '''TFGroupViTVisionModel''', ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys _lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
91
def A_ ( _UpperCAmelCase ): if not isinstance(_UpperCAmelCase , _UpperCAmelCase ): raise TypeError("only integers accepted as input" ) else: SCREAMING_SNAKE_CASE_: List[Any] = str(abs(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE_: Tuple = [list(_UpperCAmelCase ) for char in range(len(_UpperCAmelCase ) )] for index in range(len(_UpperCAmelCase ) ): num_transpositions[index].pop(_UpperCAmelCase ) return max( int("".join(list(_UpperCAmelCase ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__("""doctest""").testmod()
671
0
'''simple docstring''' # Imports import numpy as np class __SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] , UpperCAmelCase__ : Optional[Any]=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : str=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : List[Any]=None ): '''simple docstring''' self.set_matricies(red=UpperCAmelCase__ , green=UpperCAmelCase__ , blue=UpperCAmelCase__ , red_edge=UpperCAmelCase__ , nir=UpperCAmelCase__ ) def lowerCamelCase_ ( self : Optional[Any] , UpperCAmelCase__ : str=None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : List[Any]=None ): '''simple docstring''' if red is not None: lowercase : int =red if green is not None: lowercase : int =green if blue is not None: lowercase : Tuple =blue if red_edge is not None: lowercase : Union[str, Any] =red_edge if nir is not None: lowercase : Optional[int] =nir return True def lowerCamelCase_ ( self : Tuple , UpperCAmelCase__ : int="" , UpperCAmelCase__ : Optional[Any]=None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : Union[str, Any]=None ): '''simple docstring''' self.set_matricies(red=UpperCAmelCase__ , green=UpperCAmelCase__ , blue=UpperCAmelCase__ , red_edge=UpperCAmelCase__ , nir=UpperCAmelCase__ ) lowercase : int ={ '''ARVI2''': self.arvaa, '''CCCI''': self.ccci, '''CVI''': self.cvi, '''GLI''': self.gli, '''NDVI''': self.ndvi, '''BNDVI''': self.bndvi, '''redEdgeNDVI''': self.red_edge_ndvi, '''GNDVI''': self.gndvi, '''GBNDVI''': self.gbndvi, '''GRNDVI''': self.grndvi, '''RBNDVI''': self.rbndvi, '''PNDVI''': self.pndvi, '''ATSAVI''': self.atsavi, '''BWDRVI''': self.bwdrvi, '''CIgreen''': self.ci_green, '''CIrededge''': self.ci_rededge, '''CI''': self.ci, '''CTVI''': self.ctvi, '''GDVI''': self.gdvi, '''EVI''': self.evi, '''GEMI''': self.gemi, '''GOSAVI''': self.gosavi, '''GSAVI''': self.gsavi, '''Hue''': self.hue, '''IVI''': self.ivi, '''IPVI''': self.ipvi, '''I''': self.i, '''RVI''': self.rvi, '''MRVI''': self.mrvi, '''MSAVI''': self.m_savi, '''NormG''': self.norm_g, '''NormNIR''': self.norm_nir, '''NormR''': self.norm_r, '''NGRDI''': self.ngrdi, '''RI''': self.ri, '''S''': self.s, '''IF''': self._if, '''DVI''': self.dvi, '''TVI''': self.tvi, '''NDRE''': self.ndre, } try: return funcs[index]() except KeyError: print('''Index not in the list!''' ) return False def lowerCamelCase_ ( self : Any ): '''simple docstring''' return -0.18 + (1.17 * ((self.nir - self.red) / (self.nir + self.red))) def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / ( (self.nir - self.red) / (self.nir + self.red) ) def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return self.nir * (self.red / (self.green**2)) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' return (2 * self.green - self.red - self.blue) / ( 2 * self.green + self.red + self.blue ) def lowerCamelCase_ ( self : int ): '''simple docstring''' return (self.nir - self.red) / (self.nir + self.red) def lowerCamelCase_ ( self : str ): '''simple docstring''' return (self.nir - self.blue) / (self.nir + self.blue) def lowerCamelCase_ ( self : Any ): '''simple docstring''' return (self.redEdge - self.red) / (self.redEdge + self.red) def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return (self.nir - self.green) / (self.nir + self.green) def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' return (self.nir - (self.green + self.blue)) / ( self.nir + (self.green + self.blue) ) def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' return (self.nir - (self.green + self.red)) / ( self.nir + (self.green + self.red) ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red)) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' return (self.nir - (self.green + self.red + self.blue)) / ( self.nir + (self.green + self.red + self.blue) ) def lowerCamelCase_ ( self : str , UpperCAmelCase__ : List[Any]=0.08 , UpperCAmelCase__ : Tuple=1.22 , UpperCAmelCase__ : List[str]=0.03 ): '''simple docstring''' return a * ( (self.nir - a * self.red - b) / (a * self.nir + self.red - a * b + x * (1 + a**2)) ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' return (self.nir / self.green) - 1 def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' return (self.nir / self.redEdge) - 1 def lowerCamelCase_ ( self : Dict ): '''simple docstring''' return (self.red - self.blue) / self.red def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' lowercase : int =self.ndvi() return ((ndvi + 0.5) / (abs(ndvi + 0.5 ))) * (abs(ndvi + 0.5 ) ** (1 / 2)) def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' return self.nir - self.green def lowerCamelCase_ ( self : str ): '''simple docstring''' return 2.5 * ( (self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1) ) def lowerCamelCase_ ( self : str ): '''simple docstring''' lowercase : Union[str, Any] =(2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) / ( self.nir + self.red + 0.5 ) return n * (1 - 0.25 * n) - (self.red - 0.1_25) / (1 - self.red) def lowerCamelCase_ ( self : str , UpperCAmelCase__ : List[Any]=0.16 ): '''simple docstring''' return (self.nir - self.green) / (self.nir + self.green + y) def lowerCamelCase_ ( self : List[Any] , UpperCAmelCase__ : int=0.5 ): '''simple docstring''' return ((self.nir - self.green) / (self.nir + self.green + n)) * (1 + n) def lowerCamelCase_ ( self : str ): '''simple docstring''' return np.arctan( ((2 * self.red - self.green - self.blue) / 30.5) * (self.green - self.blue) ) def lowerCamelCase_ ( self : int , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : int=None ): '''simple docstring''' return (self.nir - b) / (a * self.red) def lowerCamelCase_ ( self : int ): '''simple docstring''' return (self.nir / ((self.nir + self.red) / 2)) * (self.ndvi() + 1) def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' return (self.red + self.green + self.blue) / 30.5 def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' return self.nir / self.red def lowerCamelCase_ ( self : int ): '''simple docstring''' return (self.rvi() - 1) / (self.rvi() + 1) def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' return ( (2 * self.nir + 1) - ((2 * self.nir + 1) ** 2 - 8 * (self.nir - self.red)) ** (1 / 2) ) / 2 def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' return self.green / (self.nir + self.red + self.green) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' return self.nir / (self.nir + self.red + self.green) def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' return self.red / (self.nir + self.red + self.green) def lowerCamelCase_ ( self : Any ): '''simple docstring''' return (self.green - self.red) / (self.green + self.red) def lowerCamelCase_ ( self : Any ): '''simple docstring''' return (self.red - self.green) / (self.red + self.green) def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' lowercase : Optional[Any] =np.max([np.max(self.red ), np.max(self.green ), np.max(self.blue )] ) lowercase : Union[str, Any] =np.min([np.min(self.red ), np.min(self.green ), np.min(self.blue )] ) return (max_value - min_value) / max_value def lowerCamelCase_ ( self : Dict ): '''simple docstring''' return (2 * self.red - self.green - self.blue) / (self.green - self.blue) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' return self.nir / self.red def lowerCamelCase_ ( self : int ): '''simple docstring''' return (self.ndvi() + 0.5) ** (1 / 2) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' return (self.nir - self.redEdge) / (self.nir + self.redEdge)
92
from __future__ import annotations from collections.abc import Iterator from typing import Any class __lowercase : """simple docstring""" def __init__( self : List[str] , lowerCAmelCase__ : Any): SCREAMING_SNAKE_CASE_: Any = data SCREAMING_SNAKE_CASE_: Node | None = None class __lowercase : """simple docstring""" def __init__( self : int): SCREAMING_SNAKE_CASE_: Dict = None SCREAMING_SNAKE_CASE_: str = None def __iter__( self : List[str]): SCREAMING_SNAKE_CASE_: Tuple = self.head while self.head: yield node.data SCREAMING_SNAKE_CASE_: List[str] = node.next if node == self.head: break def __len__( self : Dict): return sum(1 for _ in self) def __repr__( self : Dict): return "->".join(str(lowerCAmelCase__) for item in iter(self)) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase__ : Any): self.insert_nth(len(self) , lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase__ : Any): self.insert_nth(0 , lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : Any): if index < 0 or index > len(self): raise IndexError("list index out of range.") SCREAMING_SNAKE_CASE_: Any = Node(lowerCAmelCase__) if self.head is None: SCREAMING_SNAKE_CASE_: str = new_node # first node points itself SCREAMING_SNAKE_CASE_: Optional[Any] = new_node elif index == 0: # insert at head SCREAMING_SNAKE_CASE_: Optional[Any] = self.head SCREAMING_SNAKE_CASE_: str = new_node else: SCREAMING_SNAKE_CASE_: int = self.head for _ in range(index - 1): SCREAMING_SNAKE_CASE_: Optional[Any] = temp.next SCREAMING_SNAKE_CASE_: List[str] = temp.next SCREAMING_SNAKE_CASE_: int = new_node if index == len(self) - 1: # insert at tail SCREAMING_SNAKE_CASE_: Any = new_node def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): return self.delete_nth(0) def _SCREAMING_SNAKE_CASE ( self : Any): return self.delete_nth(len(self) - 1) def _SCREAMING_SNAKE_CASE ( self : Any , lowerCAmelCase__ : int = 0): if not 0 <= index < len(self): raise IndexError("list index out of range.") SCREAMING_SNAKE_CASE_: Optional[Any] = self.head if self.head == self.tail: # just one node SCREAMING_SNAKE_CASE_: List[str] = None elif index == 0: # delete head node SCREAMING_SNAKE_CASE_: int = self.tail.next.next SCREAMING_SNAKE_CASE_: Tuple = self.head.next else: SCREAMING_SNAKE_CASE_: Optional[int] = self.head for _ in range(index - 1): SCREAMING_SNAKE_CASE_: Any = temp.next SCREAMING_SNAKE_CASE_: Optional[Any] = temp.next SCREAMING_SNAKE_CASE_: int = temp.next.next if index == len(self) - 1: # delete at tail SCREAMING_SNAKE_CASE_: int = temp return delete_node.data def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): return len(self) == 0 def A_ ( ): SCREAMING_SNAKE_CASE_: Dict = CircularLinkedList() assert len(_UpperCAmelCase ) == 0 assert circular_linked_list.is_empty() is True assert str(_UpperCAmelCase ) == "" try: circular_linked_list.delete_front() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_tail() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_nth(-1 ) raise AssertionError except IndexError: assert True try: circular_linked_list.delete_nth(0 ) raise AssertionError except IndexError: assert True assert circular_linked_list.is_empty() is True for i in range(5 ): assert len(_UpperCAmelCase ) == i circular_linked_list.insert_nth(_UpperCAmelCase , i + 1 ) assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 6 ) ) circular_linked_list.insert_tail(6 ) assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 7 ) ) circular_linked_list.insert_head(0 ) assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(0 , 7 ) ) assert circular_linked_list.delete_front() == 0 assert circular_linked_list.delete_tail() == 6 assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 6 ) ) assert circular_linked_list.delete_nth(2 ) == 3 circular_linked_list.insert_nth(2 , 3 ) assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 6 ) ) assert circular_linked_list.is_empty() is False if __name__ == "__main__": import doctest doctest.testmod()
671
0
"""simple docstring""" import json import os import unittest from transformers import DebertaTokenizer, DebertaTokenizerFast from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class _lowerCAmelCase ( a , unittest.TestCase ): """simple docstring""" __magic_name__ :Optional[Any] = DebertaTokenizer __magic_name__ :str = True __magic_name__ :Dict = DebertaTokenizerFast def snake_case ( self ): '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt lowerCAmelCase__ :Dict = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '[UNK]', ] lowerCAmelCase__ :Union[str, Any] = dict(zip(__UpperCAmelCase , range(len(__UpperCAmelCase ) ) ) ) lowerCAmelCase__ :Dict = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] lowerCAmelCase__ :int = {'unk_token': '[UNK]'} lowerCAmelCase__ :List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) lowerCAmelCase__ :Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(__UpperCAmelCase ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(__UpperCAmelCase ) ) def snake_case ( self , **__UpperCAmelCase ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = 'lower newer' lowerCAmelCase__ :List[str] = 'lower newer' return input_text, output_text def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = self.get_tokenizer() lowerCAmelCase__ :List[Any] = 'lower newer' lowerCAmelCase__ :Optional[int] = ['l', 'o', 'w', 'er', '\u0120', 'n', 'e', 'w', 'er'] lowerCAmelCase__ :Tuple = tokenizer.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Any = tokens + [tokenizer.unk_token] lowerCAmelCase__ :str = [0, 1, 2, 1_5, 1_0, 9, 3, 2, 1_5, 1_9] self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = self.get_tokenizer() lowerCAmelCase__ :Optional[int] = tokenizer('Hello' , 'World' ) lowerCAmelCase__ :List[Any] = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] self.assertListEqual(tokd['token_type_ids'] , __UpperCAmelCase ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Any = self.tokenizer_class.from_pretrained('microsoft/deberta-base' ) lowerCAmelCase__ :Optional[Any] = tokenizer.encode('sequence builders' , add_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ :str = tokenizer.encode('multi-sequence build' , add_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = tokenizer.encode( 'sequence builders' , add_special_tokens=__UpperCAmelCase , add_prefix_space=__UpperCAmelCase ) lowerCAmelCase__ :Any = tokenizer.encode( 'sequence builders' , 'multi-sequence build' , add_special_tokens=__UpperCAmelCase , add_prefix_space=__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase ) lowerCAmelCase__ :str = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase , __UpperCAmelCase ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Any = [self.tokenizer_class] if self.test_rust_tokenizer: tokenizer_classes.append(self.rust_tokenizer_class ) for tokenizer_class in tokenizer_classes: lowerCAmelCase__ :Tuple = tokenizer_class.from_pretrained('microsoft/deberta-base' ) lowerCAmelCase__ :Optional[int] = [ 'ALBERT: A Lite BERT for Self-supervised Learning of Language Representations', 'ALBERT incorporates two parameter reduction techniques', 'The first one is a factorized embedding parameterization. By decomposing the large vocabulary' ' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of' ' vocabulary embedding.', ] lowerCAmelCase__ :Optional[int] = tokenizer(__UpperCAmelCase , padding=__UpperCAmelCase ) lowerCAmelCase__ :Tuple = [tokenizer.decode(__UpperCAmelCase , skip_special_tokens=__UpperCAmelCase ) for seq in encoding['input_ids']] # fmt: off lowerCAmelCase__ :Tuple = { 'input_ids': [ [1, 2_1_1_8, 1_1_1_2_6, 5_6_5, 3_5, 8_3, 2_5_1_9_1, 1_6_3, 1_8_8_5_4, 1_3, 1_2_1_5_6, 1_2, 1_6_1_0_1, 2_5_3_7_6, 1_3_8_0_7, 9, 2_2_2_0_5, 2_7_8_9_3, 1_6_3_5, 2, 0, 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, 2_1_1_8, 1_1_1_2_6, 5_6_5, 2_4_5_3_6, 8_0, 4_3_7_9_7, 4_8_7_8, 7_3_7_3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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_3_3, 7_8, 6_5, 1_6, 1_0, 3_7_2_4, 1_5_3_8, 3_3_1_8_3, 1_1_3_0_3, 4_3_7_9_7, 1_9_3_8, 4, 8_7_0, 2_4_1_6_5, 2_9_1_0_5, 5, 7_3_9, 3_2_6_4_4, 3_3_1_8_3, 1_1_3_0_3, 3_6_1_7_3, 8_8, 8_0, 6_5_0, 7_8_2_1, 4_5_9_4_0, 6, 5_2, 2_5_5_9, 5, 1_8_3_6, 9, 5, 7_3_9_7, 1_3_1_7_1, 3_1, 5, 1_8_3_6, 9, 3_2_6_4_4, 3_3_1_8_3, 1_1_3_0_3, 4, 2] ], 'token_type_ids': [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ], 'attention_mask': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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] ] } # fmt: on lowerCAmelCase__ :List[Any] = [ 'ALBERT: A Lite BERT for Self-supervised Learning of Language Representations', 'ALBERT incorporates two parameter reduction techniques', 'The first one is a factorized embedding parameterization. By decomposing the large vocabulary' ' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of' ' vocabulary embedding.', ] self.assertDictEqual(encoding.data , __UpperCAmelCase ) for expected, decoded in zip(__UpperCAmelCase , __UpperCAmelCase ): self.assertEqual(__UpperCAmelCase , __UpperCAmelCase )
93
from collections import defaultdict from math import ceil, sqrt def A_ ( _UpperCAmelCase = 1_00_00_00 , _UpperCAmelCase = 10 ): SCREAMING_SNAKE_CASE_: defaultdict = defaultdict(_UpperCAmelCase ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: SCREAMING_SNAKE_CASE_: Tuple = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: SCREAMING_SNAKE_CASE_: Optional[Any] = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(_UpperCAmelCase , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(f'''{solution() = }''')
671
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE = logging.get_logger(__name__) SCREAMING_SNAKE_CASE = { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/config.json', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/config.json' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/config.json', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/config.json' ), 'distilbert-base-german-cased': 'https://huggingface.co/distilbert-base-german-cased/resolve/main/config.json', 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/config.json' ), 'distilbert-base-uncased-finetuned-sst-2-english': ( 'https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json' ), } class UpperCAmelCase_ ( __A ): """simple docstring""" UpperCamelCase_ = '''distilbert''' UpperCamelCase_ = { '''hidden_size''': '''dim''', '''num_attention_heads''': '''n_heads''', '''num_hidden_layers''': '''n_layers''', } def __init__( self : Optional[int] , UpperCAmelCase : str=3_0522 , UpperCAmelCase : Any=512 , UpperCAmelCase : int=False , UpperCAmelCase : List[str]=6 , UpperCAmelCase : Optional[int]=12 , UpperCAmelCase : Dict=768 , UpperCAmelCase : str=4 * 768 , UpperCAmelCase : int=0.1 , UpperCAmelCase : Optional[int]=0.1 , UpperCAmelCase : List[Any]="gelu" , UpperCAmelCase : List[Any]=0.0_2 , UpperCAmelCase : List[Any]=0.1 , UpperCAmelCase : Optional[int]=0.2 , UpperCAmelCase : List[Any]=0 , **UpperCAmelCase : Dict , ) -> str: '''simple docstring''' lowercase : Dict =vocab_size lowercase : Union[str, Any] =max_position_embeddings lowercase : Any =sinusoidal_pos_embds lowercase : Dict =n_layers lowercase : Optional[int] =n_heads lowercase : Optional[Any] =dim lowercase : Any =hidden_dim lowercase : Optional[int] =dropout lowercase : str =attention_dropout lowercase : Any =activation lowercase : Optional[Any] =initializer_range lowercase : Optional[int] =qa_dropout lowercase : Optional[Any] =seq_classif_dropout super().__init__(**UpperCAmelCase , pad_token_id=UpperCAmelCase ) class UpperCAmelCase_ ( __A ): """simple docstring""" @property def A__ ( self : Tuple ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": lowercase : Tuple ={0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: lowercase : Any ={0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
94
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCAmelCase : str = { """configuration_xlm""": ["""XLM_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLMConfig""", """XLMOnnxConfig"""], """tokenization_xlm""": ["""XLMTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : Dict = [ """XLM_PRETRAINED_MODEL_ARCHIVE_LIST""", """XLMForMultipleChoice""", """XLMForQuestionAnswering""", """XLMForQuestionAnsweringSimple""", """XLMForSequenceClassification""", """XLMForTokenClassification""", """XLMModel""", """XLMPreTrainedModel""", """XLMWithLMHeadModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : List[str] = [ """TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFXLMForMultipleChoice""", """TFXLMForQuestionAnsweringSimple""", """TFXLMForSequenceClassification""", """TFXLMForTokenClassification""", """TFXLMMainLayer""", """TFXLMModel""", """TFXLMPreTrainedModel""", """TFXLMWithLMHeadModel""", ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys lowerCAmelCase : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
671
0
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaConfig, WavaVecaFeatureExtractor from transformers.testing_utils import require_torch, slow from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin lowerCamelCase_ = random.Random() def snake_case ( A__ ,A__=1.0 ,A__=None ,A__=None ): if rng is None: UpperCAmelCase_ : str = global_rng UpperCAmelCase_ : str = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class UpperCamelCase_ (unittest.TestCase ): def __init__( self : List[Any] , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Any=7 , lowerCAmelCase_ : Dict=400 , lowerCAmelCase_ : int=2_000 , lowerCAmelCase_ : int=1 , lowerCAmelCase_ : str=0.0 , lowerCAmelCase_ : Optional[Any]=16_000 , lowerCAmelCase_ : Dict=True , lowerCAmelCase_ : Tuple=True , ) -> Any: UpperCAmelCase_ : str = parent UpperCAmelCase_ : Tuple = batch_size UpperCAmelCase_ : Tuple = min_seq_length UpperCAmelCase_ : Any = max_seq_length UpperCAmelCase_ : Optional[Any] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) UpperCAmelCase_ : List[Any] = feature_size UpperCAmelCase_ : List[Any] = padding_value UpperCAmelCase_ : Union[str, Any] = sampling_rate UpperCAmelCase_ : Union[str, Any] = return_attention_mask UpperCAmelCase_ : List[Any] = do_normalize def _SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]: return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowerCAmelCase_ : List[Any]=False , lowerCAmelCase_ : Optional[int]=False ) -> Union[str, Any]: def _flatten(lowerCAmelCase_ : List[str] ): return list(itertools.chain(*lowerCAmelCase_ ) ) if equal_length: UpperCAmelCase_ : Tuple = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size UpperCAmelCase_ : List[Any] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: UpperCAmelCase_ : str = [np.asarray(lowerCAmelCase_ ) for x in speech_inputs] return speech_inputs class UpperCamelCase_ (__A , unittest.TestCase ): __magic_name__ = WavaVecaFeatureExtractor def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: UpperCAmelCase_ : List[str] = WavaVecaFeatureExtractionTester(self ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowerCAmelCase_ : int ) -> List[str]: self.assertTrue(np.all(np.mean(lowerCAmelCase_ , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(lowerCAmelCase_ , axis=0 ) - 1 ) < 1e-3 ) ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: # Tests that all call wrap to encode_plus and batch_encode_plus UpperCAmelCase_ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 UpperCAmelCase_ : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] UpperCAmelCase_ : Dict = [np.asarray(lowerCAmelCase_ ) for speech_input in speech_inputs] # Test not batched input UpperCAmelCase_ : List[Any] = feat_extract(speech_inputs[0] , return_tensors="np" ).input_values UpperCAmelCase_ : int = feat_extract(np_speech_inputs[0] , return_tensors="np" ).input_values self.assertTrue(np.allclose(lowerCAmelCase_ , lowerCAmelCase_ , atol=1e-3 ) ) # Test batched UpperCAmelCase_ : Optional[int] = feat_extract(lowerCAmelCase_ , return_tensors="np" ).input_values UpperCAmelCase_ : List[str] = feat_extract(lowerCAmelCase_ , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(lowerCAmelCase_ , lowerCAmelCase_ ): self.assertTrue(np.allclose(lowerCAmelCase_ , lowerCAmelCase_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. UpperCAmelCase_ : Tuple = [floats_list((1, x) )[0] for x in (800, 800, 800)] UpperCAmelCase_ : str = np.asarray(lowerCAmelCase_ ) UpperCAmelCase_ : Optional[Any] = feat_extract(lowerCAmelCase_ , return_tensors="np" ).input_values UpperCAmelCase_ : Optional[int] = feat_extract(lowerCAmelCase_ , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(lowerCAmelCase_ , lowerCAmelCase_ ): self.assertTrue(np.allclose(lowerCAmelCase_ , lowerCAmelCase_ , atol=1e-3 ) ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Dict: UpperCAmelCase_ : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCAmelCase_ : Dict = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] UpperCAmelCase_ : Optional[int] = ["longest", "max_length", "do_not_pad"] UpperCAmelCase_ : Union[str, Any] = [None, 1_600, None] for max_length, padding in zip(lowerCAmelCase_ , lowerCAmelCase_ ): UpperCAmelCase_ : str = feat_extract(lowerCAmelCase_ , padding=lowerCAmelCase_ , max_length=lowerCAmelCase_ , return_tensors="np" ) UpperCAmelCase_ : Optional[Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self.assertTrue(input_values[0][800:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1_000] ) self.assertTrue(input_values[0][1_000:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1_200] ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: UpperCAmelCase_ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCAmelCase_ : Dict = range(800 , 1_400 , 200 ) UpperCAmelCase_ : Any = [floats_list((1, x) )[0] for x in lengths] UpperCAmelCase_ : Tuple = ["longest", "max_length", "do_not_pad"] UpperCAmelCase_ : Optional[Any] = [None, 1_600, None] for max_length, padding in zip(lowerCAmelCase_ , lowerCAmelCase_ ): UpperCAmelCase_ : List[Any] = feat_extract(lowerCAmelCase_ , max_length=lowerCAmelCase_ , padding=lowerCAmelCase_ ) UpperCAmelCase_ : Dict = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self._check_zero_mean_unit_variance(input_values[1][:1_000] ) self._check_zero_mean_unit_variance(input_values[2][:1_200] ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[Any]: UpperCAmelCase_ : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCAmelCase_ : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] UpperCAmelCase_ : Optional[Any] = feat_extract( lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=1_000 , padding="max_length" , return_tensors="np" ) UpperCAmelCase_ : Any = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: UpperCAmelCase_ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCAmelCase_ : int = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] UpperCAmelCase_ : Optional[int] = feat_extract( lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=1_000 , padding="longest" , return_tensors="np" ) UpperCAmelCase_ : List[str] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1_000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1_000) ) UpperCAmelCase_ : str = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] UpperCAmelCase_ : List[str] = feat_extract( lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=2_000 , padding="longest" , return_tensors="np" ) UpperCAmelCase_ : Optional[Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1_000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1_200) ) @require_torch def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]: import torch UpperCAmelCase_ : List[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCAmelCase_ : Optional[int] = np.random.rand(100 ).astype(np.floataa ) UpperCAmelCase_ : Union[str, Any] = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: UpperCAmelCase_ : List[Any] = feature_extractor.pad([{"input_values": inputs}] , return_tensors="np" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) UpperCAmelCase_ : int = feature_extractor.pad([{"input_values": inputs}] , return_tensors="pt" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) @slow @require_torch def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: # this test makes sure that models that are using # group norm don't have their feature extractor return the # attention_mask for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST: UpperCAmelCase_ : Optional[int] = WavaVecaConfig.from_pretrained(lowerCAmelCase_ ) UpperCAmelCase_ : Optional[Any] = WavaVecaFeatureExtractor.from_pretrained(lowerCAmelCase_ ) # only "layer" feature extraction norm should make use of # attention_mask self.assertEqual(feat_extract.return_attention_mask , config.feat_extract_norm == "layer" )
95
lowerCAmelCase : List[str] = { """A""": ["""B""", """C""", """E"""], """B""": ["""A""", """D""", """E"""], """C""": ["""A""", """F""", """G"""], """D""": ["""B"""], """E""": ["""A""", """B""", """D"""], """F""": ["""C"""], """G""": ["""C"""], } def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Any = set() # keep track of all the paths to be checked SCREAMING_SNAKE_CASE_: Tuple = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue SCREAMING_SNAKE_CASE_: List[Any] = queue.pop(0 ) # get the last node from the path SCREAMING_SNAKE_CASE_: Tuple = path[-1] if node not in explored: SCREAMING_SNAKE_CASE_: Union[str, Any] = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: SCREAMING_SNAKE_CASE_: int = list(_UpperCAmelCase ) new_path.append(_UpperCAmelCase ) queue.append(_UpperCAmelCase ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(_UpperCAmelCase ) # in case there's no path between the 2 nodes return [] def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 SCREAMING_SNAKE_CASE_: List[Any] = [start] SCREAMING_SNAKE_CASE_: List[str] = set(_UpperCAmelCase ) # Keep tab on distances from `start` node. SCREAMING_SNAKE_CASE_: Union[str, Any] = {start: 0, target: -1} while queue: SCREAMING_SNAKE_CASE_: Dict = queue.pop(0 ) if node == target: SCREAMING_SNAKE_CASE_: Tuple = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(_UpperCAmelCase ) queue.append(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, """G""", """D""")) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, """G""", """D""")) # returns 4
671
0
"""simple docstring""" def a ( __UpperCAmelCase : str ) -> bool: if not all(x.isalpha() for x in string ): raise ValueError("""String must only contain alphabetic characters.""" ) __magic_name__: Optional[Any] = sorted(string.lower() ) return len(__UpperCAmelCase ) == len(set(__UpperCAmelCase ) ) if __name__ == "__main__": __lowerCamelCase = input('Enter a string ').strip() __lowerCamelCase = is_isogram(input_str) print(f'''{input_str} is {'an' if isogram else 'not an'} isogram.''')
96
from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class __lowercase ( UpperCAmelCase_ ): """simple docstring""" def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowerCAmelCase__ : float): return 0.0 def A_ ( _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: List[str] = min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] ) SCREAMING_SNAKE_CASE_: Dict = max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def A_ ( _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[int] = 5_12 SCREAMING_SNAKE_CASE_: str = [1] + [0] * (size - 1) SCREAMING_SNAKE_CASE_: Dict = [filter_type.process(_UpperCAmelCase ) for item in inputs] SCREAMING_SNAKE_CASE_: Optional[Any] = [0] * (samplerate - size) # zero-padding outputs += filler SCREAMING_SNAKE_CASE_: Tuple = np.abs(np.fft.fft(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE_: Optional[Any] = 20 * np.logaa(_UpperCAmelCase ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel("Frequency (Hz)" ) plt.xscale("log" ) # Display within reasonable bounds SCREAMING_SNAKE_CASE_: Any = get_bounds(_UpperCAmelCase , _UpperCAmelCase ) plt.ylim(max([-80, bounds[0]] ) , min([80, bounds[1]] ) ) plt.ylabel("Gain (dB)" ) plt.plot(_UpperCAmelCase ) plt.show() def A_ ( _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[int] = 5_12 SCREAMING_SNAKE_CASE_: Union[str, Any] = [1] + [0] * (size - 1) SCREAMING_SNAKE_CASE_: Dict = [filter_type.process(_UpperCAmelCase ) for item in inputs] SCREAMING_SNAKE_CASE_: int = [0] * (samplerate - size) # zero-padding outputs += filler SCREAMING_SNAKE_CASE_: Any = np.angle(np.fft.fft(_UpperCAmelCase ) ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel("Frequency (Hz)" ) plt.xscale("log" ) plt.ylim(-2 * pi , 2 * pi ) plt.ylabel("Phase shift (Radians)" ) plt.plot(np.unwrap(_UpperCAmelCase , -2 * pi ) ) plt.show()
671
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) __a = {'configuration_vit_mae': ['VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTMAEConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a = [ 'VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST', 'ViTMAEForPreTraining', 'ViTMAELayer', 'ViTMAEModel', 'ViTMAEPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a = [ 'TFViTMAEForPreTraining', 'TFViTMAEModel', 'TFViTMAEPreTrainedModel', ] if TYPE_CHECKING: from .configuration_vit_mae import VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMAEConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_mae import ( VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMAEForPreTraining, ViTMAELayer, ViTMAEModel, ViTMAEPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit_mae import TFViTMAEForPreTraining, TFViTMAEModel, TFViTMAEPreTrainedModel else: import sys __a = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
97
from __future__ import annotations from math import ceil, floor, sqrt def A_ ( _UpperCAmelCase = 2_00_00_00 ): SCREAMING_SNAKE_CASE_: list[int] = [0] SCREAMING_SNAKE_CASE_: int for idx in range(1 , ceil(sqrt(target * 2 ) * 1.1 ) ): triangle_numbers.append(triangle_numbers[-1] + idx ) # we want this to be as close as possible to target SCREAMING_SNAKE_CASE_: int = 0 # the area corresponding to the grid that gives the product closest to target SCREAMING_SNAKE_CASE_: int = 0 # an estimate of b, using the quadratic formula SCREAMING_SNAKE_CASE_: float # the largest integer less than b_estimate SCREAMING_SNAKE_CASE_: int # the largest integer less than b_estimate SCREAMING_SNAKE_CASE_: int # the triangle number corresponding to b_floor SCREAMING_SNAKE_CASE_: int # the triangle number corresponding to b_ceil SCREAMING_SNAKE_CASE_: int for idx_a, triangle_a in enumerate(triangle_numbers[1:] , 1 ): SCREAMING_SNAKE_CASE_: List[Any] = (-1 + sqrt(1 + 8 * target / triangle_a )) / 2 SCREAMING_SNAKE_CASE_: Any = floor(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] = ceil(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Any = triangle_numbers[b_floor] SCREAMING_SNAKE_CASE_: List[Any] = triangle_numbers[b_ceil] if abs(target - triangle_b_first_guess * triangle_a ) < abs( target - best_product ): SCREAMING_SNAKE_CASE_: int = triangle_b_first_guess * triangle_a SCREAMING_SNAKE_CASE_: int = idx_a * b_floor if abs(target - triangle_b_second_guess * triangle_a ) < abs( target - best_product ): SCREAMING_SNAKE_CASE_: Optional[Any] = triangle_b_second_guess * triangle_a SCREAMING_SNAKE_CASE_: Tuple = idx_a * b_ceil return area if __name__ == "__main__": print(f'''{solution() = }''')
671
0
'''simple docstring''' from datetime import datetime as dt import os from github import Github lowercase__ : Optional[int] = [ 'good first issue', 'good second issue', 'good difficult issue', 'feature request', 'new model', 'wip', ] def a__ ( ) -> Dict: """simple docstring""" _UpperCamelCase = Github(os.environ['''GITHUB_TOKEN'''] ) _UpperCamelCase = g.get_repo('''huggingface/transformers''' ) _UpperCamelCase = repo.get_issues(state='''open''' ) for issue in open_issues: _UpperCamelCase = sorted([comment for comment in issue.get_comments()], key=lambda lowercase : i.created_at, reverse=lowercase ) _UpperCamelCase = comments[0] if len(lowercase ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.") issue.edit(state='''closed''' ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would add stale comment to {issue.number}") issue.create_comment( '''This issue has been automatically marked as stale because it has not had ''' '''recent activity. If you think this still needs to be addressed ''' '''please comment on this thread.\n\nPlease note that issues that do not follow the ''' '''[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) ''' '''are likely to be ignored.''' ) if __name__ == "__main__": main()
98
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase : Optional[int] = { """configuration_longformer""": [ """LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LongformerConfig""", """LongformerOnnxConfig""", ], """tokenization_longformer""": ["""LongformerTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : List[str] = ["""LongformerTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : Union[str, Any] = [ """LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """LongformerForMaskedLM""", """LongformerForMultipleChoice""", """LongformerForQuestionAnswering""", """LongformerForSequenceClassification""", """LongformerForTokenClassification""", """LongformerModel""", """LongformerPreTrainedModel""", """LongformerSelfAttention""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : int = [ """TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFLongformerForMaskedLM""", """TFLongformerForMultipleChoice""", """TFLongformerForQuestionAnswering""", """TFLongformerForSequenceClassification""", """TFLongformerForTokenClassification""", """TFLongformerModel""", """TFLongformerPreTrainedModel""", """TFLongformerSelfAttention""", ] if TYPE_CHECKING: from .configuration_longformer import ( LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, LongformerConfig, LongformerOnnxConfig, ) from .tokenization_longformer import LongformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_longformer_fast import LongformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longformer import ( LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, LongformerForMaskedLM, LongformerForMultipleChoice, LongformerForQuestionAnswering, LongformerForSequenceClassification, LongformerForTokenClassification, LongformerModel, LongformerPreTrainedModel, LongformerSelfAttention, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_longformer import ( TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFLongformerForMaskedLM, TFLongformerForMultipleChoice, TFLongformerForQuestionAnswering, TFLongformerForSequenceClassification, TFLongformerForTokenClassification, TFLongformerModel, TFLongformerPreTrainedModel, TFLongformerSelfAttention, ) else: import sys lowerCAmelCase : Optional[int] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
671
0
import logging import re import pytorch_quantization import pytorch_quantization.nn as quant_nn import torch from pytorch_quantization import calib from pytorch_quantization.tensor_quant import QuantDescriptor SCREAMING_SNAKE_CASE = logging.getLogger(__name__) SCREAMING_SNAKE_CASE = 5_0 # max width of layer names SCREAMING_SNAKE_CASE = 7_0 # max width of quantizer names def a (lowerCAmelCase__ ): __a = parser.add_argument_group("""quant_trainer arguments""" ) group.add_argument("""--wprec""" , type=lowerCAmelCase__ , default=8 , help="""weight precision""" ) group.add_argument("""--aprec""" , type=lowerCAmelCase__ , default=8 , help="""activation precision""" ) group.add_argument("""--quant-per-tensor""" , action="""store_true""" , help="""per tensor weight scaling""" ) group.add_argument("""--quant-disable""" , action="""store_true""" , help="""disable all quantizers""" ) group.add_argument("""--quant-disable-embeddings""" , action="""store_true""" , help="""disable all embeddings quantizers""" ) group.add_argument("""--quant-disable-keyword""" , type=lowerCAmelCase__ , nargs="""+""" , help="""disable quantizers by keyword""" ) group.add_argument("""--quant-disable-layer-module""" , type=lowerCAmelCase__ , help="""disable quantizers by keyword under layer.""" ) group.add_argument("""--quant-enable-layer-module""" , type=lowerCAmelCase__ , help="""enable quantizers by keyword under layer""" ) group.add_argument("""--calibrator""" , default="""max""" , help="""which quantization range calibrator to use""" ) group.add_argument("""--percentile""" , default=lowerCAmelCase__ , type=lowerCAmelCase__ , help="""percentile for PercentileCalibrator""" ) group.add_argument("""--fuse-qkv""" , action="""store_true""" , help="""use the same scale factor for qkv""" ) group.add_argument("""--clip-gelu""" , metavar="""N""" , type=lowerCAmelCase__ , help="""clip gelu output maximum value to N""" ) group.add_argument( """--recalibrate-weights""" , action="""store_true""" , help=( """recalibrate weight amaxes by taking the max of the weights.""" """ amaxes will be computed with the current quantization granularity (axis).""" ) , ) def a (lowerCAmelCase__ ): if args.calibrator == "max": __a = """max""" elif args.calibrator == "percentile": if args.percentile is None: raise ValueError("""Specify --percentile when using percentile calibrator""" ) __a = """histogram""" elif args.calibrator == "mse": __a = """histogram""" else: raise ValueError(f'''Invalid calibrator {args.calibrator}''' ) __a = QuantDescriptor(num_bits=args.aprec , calib_method=lowerCAmelCase__ ) __a = QuantDescriptor(num_bits=args.wprec , axis=(None if args.quant_per_tensor else (0,)) ) quant_nn.QuantLinear.set_default_quant_desc_input(lowerCAmelCase__ ) quant_nn.QuantLinear.set_default_quant_desc_weight(lowerCAmelCase__ ) def a (lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=False , lowerCAmelCase__=False ): logger.info("""Configuring Model for Quantization""" ) logger.info(f'''using quantization package {pytorch_quantization.__file__}''' ) if not calib: if args.quant_disable_embeddings: set_quantizer_by_name(lowerCAmelCase__ , ["""embeddings"""] , which="""weight""" , _disabled=lowerCAmelCase__ ) if args.quant_disable: set_quantizer_by_name(lowerCAmelCase__ , [""""""] , _disabled=lowerCAmelCase__ ) if args.quant_disable_keyword: set_quantizer_by_name(lowerCAmelCase__ , args.quant_disable_keyword , _disabled=lowerCAmelCase__ ) if args.quant_disable_layer_module: set_quantizer_by_name(lowerCAmelCase__ , [r"""layer.\d+.""" + args.quant_disable_layer_module] , _disabled=lowerCAmelCase__ ) if args.quant_enable_layer_module: set_quantizer_by_name(lowerCAmelCase__ , [r"""layer.\d+.""" + args.quant_enable_layer_module] , _disabled=lowerCAmelCase__ ) if args.recalibrate_weights: recalibrate_weights(lowerCAmelCase__ ) if args.fuse_qkv: fuse_qkv(lowerCAmelCase__ , lowerCAmelCase__ ) if args.clip_gelu: clip_gelu(lowerCAmelCase__ , args.clip_gelu ) # if args.local_rank in [-1, 0] and not calib: print_quant_summary(lowerCAmelCase__ ) def a (lowerCAmelCase__ ): logger.info("""Enabling Calibration""" ) for name, module in model.named_modules(): if name.endswith("""_quantizer""" ): if module._calibrator is not None: module.disable_quant() module.enable_calib() else: module.disable() logger.info(f'''{name:80}: {module}''' ) def a (lowerCAmelCase__ , lowerCAmelCase__ ): logger.info("""Loading calibrated amax""" ) for name, module in model.named_modules(): if name.endswith("""_quantizer""" ): if module._calibrator is not None: if isinstance(module._calibrator , calib.MaxCalibrator ): module.load_calib_amax() else: module.load_calib_amax("""percentile""" , percentile=args.percentile ) module.enable_quant() module.disable_calib() else: module.enable() model.cuda() print_quant_summary(lowerCAmelCase__ ) def a (lowerCAmelCase__ , lowerCAmelCase__ ): def fusea(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): for mod in [qq, qk, qv]: if not hasattr(lowerCAmelCase__ , """_amax""" ): print(""" WARNING: NO AMAX BUFFER""" ) return __a = qq._amax.detach().item() __a = qk._amax.detach().item() __a = qv._amax.detach().item() __a = max(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) qq._amax.fill_(lowerCAmelCase__ ) qk._amax.fill_(lowerCAmelCase__ ) qv._amax.fill_(lowerCAmelCase__ ) logger.info(f''' q={q:5.2f} k={k:5.2f} v={v:5.2f} -> {amax:5.2f}''' ) for name, mod in model.named_modules(): if name.endswith(""".attention.self""" ): logger.info(f'''FUSE_QKV: {name:{name_width}}''' ) fusea(mod.matmul_q_input_quantizer , mod.matmul_k_input_quantizer , mod.matmul_v_input_quantizer ) if args.quant_per_tensor: fusea(mod.query._weight_quantizer , mod.key._weight_quantizer , mod.value._weight_quantizer ) def a (lowerCAmelCase__ , lowerCAmelCase__ ): for name, mod in model.named_modules(): if name.endswith(""".output.dense""" ) and not name.endswith("""attention.output.dense""" ): __a = mod._input_quantizer._amax.data.detach().item() mod._input_quantizer._amax.data.detach().clamp_(max=lowerCAmelCase__ ) __a = mod._input_quantizer._amax.data.detach().item() logger.info(f'''CLIP_GELU: {name:{name_width}} amax: {amax_init:5.2f} -> {amax:5.2f}''' ) def a (lowerCAmelCase__ ): for name, mod in model.named_modules(): if hasattr(lowerCAmelCase__ , """_weight_quantizer""" ) and mod._weight_quantizer.axis is not None: __a = mod.weight.shape[0] __a = mod._weight_quantizer._amax.detach() __a = torch.ones(lowerCAmelCase__ , dtype=amax.dtype , device=amax.device ) * amax print(f'''expanding {name} {amax} -> {mod._weight_quantizer._amax}''' ) def a (lowerCAmelCase__ ): for name, mod in model.named_modules(): if hasattr(lowerCAmelCase__ , """_weight_quantizer""" ): if not hasattr(mod.weight_quantizer , """_amax""" ): print("""RECALIB: {name:{name_width}} WARNING: NO AMAX BUFFER""" ) continue # determine which axes to reduce across # e.g. a 4D tensor quantized per axis 0 should reduce over (1,2,3) __a = set() if mod._weight_quantizer.axis is None else set(mod._weight_quantizer.axis ) __a = set(range(len(mod.weight.size() ) ) ) - axis_set __a = pytorch_quantization.utils.reduce_amax(mod.weight , axis=lowerCAmelCase__ , keepdims=lowerCAmelCase__ ).detach() logger.info(f'''RECALIB: {name:{name_width}} {mod._weight_quantizer._amax.flatten()} -> {amax.flatten()}''' ) __a = amax def a (lowerCAmelCase__ , lowerCAmelCase__=25 , lowerCAmelCase__=180 , lowerCAmelCase__=None ): if ignore is None: __a = [] elif not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a = [ignore] __a = 0 for name, mod in model.named_modules(): if not hasattr(lowerCAmelCase__ , """weight""" ): continue __a = max(lowerCAmelCase__ , len(lowerCAmelCase__ ) ) for name, mod in model.named_modules(): __a = getattr(lowerCAmelCase__ , """_input_quantizer""" , lowerCAmelCase__ ) __a = getattr(lowerCAmelCase__ , """_weight_quantizer""" , lowerCAmelCase__ ) if not hasattr(lowerCAmelCase__ , """weight""" ): continue if type(lowerCAmelCase__ ) in ignore: continue if [True for s in ignore if type(lowerCAmelCase__ ) is str and s in name]: continue __a = f'''Act:{input_q.extra_repr()}''' __a = f'''Wgt:{weight_q.extra_repr()}''' __a = f'''{name:{name_width}} {act_str} {wgt_str}''' if len(lowerCAmelCase__ ) <= line_width: logger.info(lowerCAmelCase__ ) else: logger.info(f'''{name:{name_width}} {act_str}''' ) logger.info(f'''{' ':{name_width}} {wgt_str}''' ) def a (lowerCAmelCase__ ): __a = 0 for name, mod in model.named_modules(): if isinstance(lowerCAmelCase__ , pytorch_quantization.nn.TensorQuantizer ): print(f'''{name:80} {mod}''' ) count += 1 print(f'''{count} TensorQuantizers found in model''' ) def a (lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): __a = getattr(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) if quantizer_mod is not None: assert hasattr(lowerCAmelCase__ , lowerCAmelCase__ ) setattr(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) else: logger.warning(f'''{name} has no {quantizer}''' ) def a (lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__="both" , **lowerCAmelCase__ ): __a = f'''Warning: changing {which} quantizers of {name:{qname_width}}''' for k, v in kwargs.items(): s += f''' {k}={v}''' if which in ["input", "both"]: set_quantizer(lowerCAmelCase__ , lowerCAmelCase__ , """_input_quantizer""" , lowerCAmelCase__ , lowerCAmelCase__ ) if which in ["weight", "both"]: set_quantizer(lowerCAmelCase__ , lowerCAmelCase__ , """_weight_quantizer""" , lowerCAmelCase__ , lowerCAmelCase__ ) logger.info(lowerCAmelCase__ ) def a (lowerCAmelCase__ , lowerCAmelCase__ , **lowerCAmelCase__ ): for name, mod in model.named_modules(): if hasattr(lowerCAmelCase__ , """_input_quantizer""" ) or hasattr(lowerCAmelCase__ , """_weight_quantizer""" ): for n in names: if re.search(lowerCAmelCase__ , lowerCAmelCase__ ): set_quantizers(lowerCAmelCase__ , lowerCAmelCase__ , **lowerCAmelCase__ ) elif name.endswith("""_quantizer""" ): for n in names: if re.search(lowerCAmelCase__ , lowerCAmelCase__ ): __a = f'''Warning: changing {name:{name_width}}''' for k, v in kwargs.items(): s += f''' {k}={v}''' setattr(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) logger.info(lowerCAmelCase__ )
99
import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# lowerCAmelCase : Optional[int] = [ # (stable-diffusion, HF Diffusers) ("""time_embed.0.weight""", """time_embedding.linear_1.weight"""), ("""time_embed.0.bias""", """time_embedding.linear_1.bias"""), ("""time_embed.2.weight""", """time_embedding.linear_2.weight"""), ("""time_embed.2.bias""", """time_embedding.linear_2.bias"""), ("""input_blocks.0.0.weight""", """conv_in.weight"""), ("""input_blocks.0.0.bias""", """conv_in.bias"""), ("""out.0.weight""", """conv_norm_out.weight"""), ("""out.0.bias""", """conv_norm_out.bias"""), ("""out.2.weight""", """conv_out.weight"""), ("""out.2.bias""", """conv_out.bias"""), ] lowerCAmelCase : str = [ # (stable-diffusion, HF Diffusers) ("""in_layers.0""", """norm1"""), ("""in_layers.2""", """conv1"""), ("""out_layers.0""", """norm2"""), ("""out_layers.3""", """conv2"""), ("""emb_layers.1""", """time_emb_proj"""), ("""skip_connection""", """conv_shortcut"""), ] lowerCAmelCase : List[str] = [] # hardcoded number of downblocks and resnets/attentions... # would need smarter logic for other networks. for i in range(4): # loop over downblocks/upblocks for j in range(2): # loop over resnets/attentions for downblocks lowerCAmelCase : int = f'''down_blocks.{i}.resnets.{j}.''' lowerCAmelCase : List[str] = f'''input_blocks.{3*i + j + 1}.0.''' unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix)) if i < 3: # no attention layers in down_blocks.3 lowerCAmelCase : Any = f'''down_blocks.{i}.attentions.{j}.''' lowerCAmelCase : List[Any] = f'''input_blocks.{3*i + j + 1}.1.''' unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix)) for j in range(3): # loop over resnets/attentions for upblocks lowerCAmelCase : Any = f'''up_blocks.{i}.resnets.{j}.''' lowerCAmelCase : str = f'''output_blocks.{3*i + j}.0.''' unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix)) if i > 0: # no attention layers in up_blocks.0 lowerCAmelCase : List[Any] = f'''up_blocks.{i}.attentions.{j}.''' lowerCAmelCase : str = f'''output_blocks.{3*i + j}.1.''' unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix)) if i < 3: # no downsample in down_blocks.3 lowerCAmelCase : Any = f'''down_blocks.{i}.downsamplers.0.conv.''' lowerCAmelCase : Tuple = f'''input_blocks.{3*(i+1)}.0.op.''' unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix)) # no upsample in up_blocks.3 lowerCAmelCase : Tuple = f'''up_blocks.{i}.upsamplers.0.''' lowerCAmelCase : Tuple = f'''output_blocks.{3*i + 2}.{1 if i == 0 else 2}.''' unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix)) lowerCAmelCase : Any = """mid_block.attentions.0.""" lowerCAmelCase : Dict = """middle_block.1.""" unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix)) for j in range(2): lowerCAmelCase : int = f'''mid_block.resnets.{j}.''' lowerCAmelCase : Union[str, Any] = f'''middle_block.{2*j}.''' unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix)) def A_ ( _UpperCAmelCase ): # buyer beware: this is a *brittle* function, # and correct output requires that all of these pieces interact in # the exact order in which I have arranged them. SCREAMING_SNAKE_CASE_: Dict = {k: k for k in unet_state_dict.keys()} for sd_name, hf_name in unet_conversion_map: SCREAMING_SNAKE_CASE_: Optional[int] = sd_name for k, v in mapping.items(): if "resnets" in k: for sd_part, hf_part in unet_conversion_map_resnet: SCREAMING_SNAKE_CASE_: Any = v.replace(_UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: str = v for k, v in mapping.items(): for sd_part, hf_part in unet_conversion_map_layer: SCREAMING_SNAKE_CASE_: Optional[Any] = v.replace(_UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] = v SCREAMING_SNAKE_CASE_: Optional[Any] = {v: unet_state_dict[k] for k, v in mapping.items()} return new_state_dict # ================# # VAE Conversion # # ================# lowerCAmelCase : Union[str, Any] = [ # (stable-diffusion, HF Diffusers) ("""nin_shortcut""", """conv_shortcut"""), ("""norm_out""", """conv_norm_out"""), ("""mid.attn_1.""", """mid_block.attentions.0."""), ] for i in range(4): # down_blocks have two resnets for j in range(2): lowerCAmelCase : Union[str, Any] = f'''encoder.down_blocks.{i}.resnets.{j}.''' lowerCAmelCase : Optional[Any] = f'''encoder.down.{i}.block.{j}.''' vae_conversion_map.append((sd_down_prefix, hf_down_prefix)) if i < 3: lowerCAmelCase : Dict = f'''down_blocks.{i}.downsamplers.0.''' lowerCAmelCase : List[str] = f'''down.{i}.downsample.''' vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix)) lowerCAmelCase : List[str] = f'''up_blocks.{i}.upsamplers.0.''' lowerCAmelCase : int = f'''up.{3-i}.upsample.''' vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix)) # up_blocks have three resnets # also, up blocks in hf are numbered in reverse from sd for j in range(3): lowerCAmelCase : Any = f'''decoder.up_blocks.{i}.resnets.{j}.''' lowerCAmelCase : int = f'''decoder.up.{3-i}.block.{j}.''' vae_conversion_map.append((sd_up_prefix, hf_up_prefix)) # this part accounts for mid blocks in both the encoder and the decoder for i in range(2): lowerCAmelCase : str = f'''mid_block.resnets.{i}.''' lowerCAmelCase : Tuple = f'''mid.block_{i+1}.''' vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix)) lowerCAmelCase : List[Any] = [ # (stable-diffusion, HF Diffusers) ("""norm.""", """group_norm."""), ("""q.""", """query."""), ("""k.""", """key."""), ("""v.""", """value."""), ("""proj_out.""", """proj_attn."""), ] def A_ ( _UpperCAmelCase ): # convert HF linear weights to SD conv2d weights return w.reshape(*w.shape , 1 , 1 ) def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[Any] = {k: k for k in vae_state_dict.keys()} for k, v in mapping.items(): for sd_part, hf_part in vae_conversion_map: SCREAMING_SNAKE_CASE_: Union[str, Any] = v.replace(_UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] = v for k, v in mapping.items(): if "attentions" in k: for sd_part, hf_part in vae_conversion_map_attn: SCREAMING_SNAKE_CASE_: Any = v.replace(_UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] = v SCREAMING_SNAKE_CASE_: Tuple = {v: vae_state_dict[k] for k, v in mapping.items()} SCREAMING_SNAKE_CASE_: Union[str, Any] = ["q", "k", "v", "proj_out"] for k, v in new_state_dict.items(): for weight_name in weights_to_convert: if f"mid.attn_1.{weight_name}.weight" in k: print(f"Reshaping {k} for SD format" ) SCREAMING_SNAKE_CASE_: List[str] = reshape_weight_for_sd(_UpperCAmelCase ) return new_state_dict # =========================# # Text Encoder Conversion # # =========================# lowerCAmelCase : Optional[Any] = [ # (stable-diffusion, HF Diffusers) ("""resblocks.""", """text_model.encoder.layers."""), ("""ln_1""", """layer_norm1"""), ("""ln_2""", """layer_norm2"""), (""".c_fc.""", """.fc1."""), (""".c_proj.""", """.fc2."""), (""".attn""", """.self_attn"""), ("""ln_final.""", """transformer.text_model.final_layer_norm."""), ("""token_embedding.weight""", """transformer.text_model.embeddings.token_embedding.weight"""), ("""positional_embedding""", """transformer.text_model.embeddings.position_embedding.weight"""), ] lowerCAmelCase : Optional[Any] = {re.escape(x[1]): x[0] for x in textenc_conversion_lst} lowerCAmelCase : Optional[int] = re.compile("""|""".join(protected.keys())) # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp lowerCAmelCase : str = {"""q""": 0, """k""": 1, """v""": 2} def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: str = {} SCREAMING_SNAKE_CASE_: str = {} SCREAMING_SNAKE_CASE_: List[str] = {} for k, v in text_enc_dict.items(): if ( k.endswith(".self_attn.q_proj.weight" ) or k.endswith(".self_attn.k_proj.weight" ) or k.endswith(".self_attn.v_proj.weight" ) ): SCREAMING_SNAKE_CASE_: str = k[: -len(".q_proj.weight" )] SCREAMING_SNAKE_CASE_: Dict = k[-len("q_proj.weight" )] if k_pre not in capture_qkv_weight: SCREAMING_SNAKE_CASE_: Tuple = [None, None, None] SCREAMING_SNAKE_CASE_: Union[str, Any] = v continue if ( k.endswith(".self_attn.q_proj.bias" ) or k.endswith(".self_attn.k_proj.bias" ) or k.endswith(".self_attn.v_proj.bias" ) ): SCREAMING_SNAKE_CASE_: Union[str, Any] = k[: -len(".q_proj.bias" )] SCREAMING_SNAKE_CASE_: Any = k[-len("q_proj.bias" )] if k_pre not in capture_qkv_bias: SCREAMING_SNAKE_CASE_: List[Any] = [None, None, None] SCREAMING_SNAKE_CASE_: List[str] = v continue SCREAMING_SNAKE_CASE_: int = textenc_pattern.sub(lambda _UpperCAmelCase : protected[re.escape(m.group(0 ) )] , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Dict = v for k_pre, tensors in capture_qkv_weight.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) SCREAMING_SNAKE_CASE_: str = textenc_pattern.sub(lambda _UpperCAmelCase : protected[re.escape(m.group(0 ) )] , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: int = torch.cat(_UpperCAmelCase ) for k_pre, tensors in capture_qkv_bias.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) SCREAMING_SNAKE_CASE_: Optional[int] = textenc_pattern.sub(lambda _UpperCAmelCase : protected[re.escape(m.group(0 ) )] , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] = torch.cat(_UpperCAmelCase ) return new_state_dict def A_ ( _UpperCAmelCase ): return text_enc_dict if __name__ == "__main__": lowerCAmelCase : int = argparse.ArgumentParser() parser.add_argument("""--model_path""", default=None, type=str, required=True, help="""Path to the model to convert.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, required=True, help="""Path to the output model.""") parser.add_argument("""--half""", action="""store_true""", help="""Save weights in half precision.""") parser.add_argument( """--use_safetensors""", action="""store_true""", help="""Save weights use safetensors, default is ckpt.""" ) lowerCAmelCase : Optional[Any] = parser.parse_args() assert args.model_path is not None, "Must provide a model path!" assert args.checkpoint_path is not None, "Must provide a checkpoint path!" # Path for safetensors lowerCAmelCase : int = osp.join(args.model_path, """unet""", """diffusion_pytorch_model.safetensors""") lowerCAmelCase : List[str] = osp.join(args.model_path, """vae""", """diffusion_pytorch_model.safetensors""") lowerCAmelCase : Optional[int] = osp.join(args.model_path, """text_encoder""", """model.safetensors""") # Load models from safetensors if it exists, if it doesn't pytorch if osp.exists(unet_path): lowerCAmelCase : Optional[int] = load_file(unet_path, device="""cpu""") else: lowerCAmelCase : Union[str, Any] = osp.join(args.model_path, """unet""", """diffusion_pytorch_model.bin""") lowerCAmelCase : Optional[Any] = torch.load(unet_path, map_location="""cpu""") if osp.exists(vae_path): lowerCAmelCase : str = load_file(vae_path, device="""cpu""") else: lowerCAmelCase : List[Any] = osp.join(args.model_path, """vae""", """diffusion_pytorch_model.bin""") lowerCAmelCase : Optional[Any] = torch.load(vae_path, map_location="""cpu""") if osp.exists(text_enc_path): lowerCAmelCase : List[Any] = load_file(text_enc_path, device="""cpu""") else: lowerCAmelCase : List[Any] = osp.join(args.model_path, """text_encoder""", """pytorch_model.bin""") lowerCAmelCase : Optional[Any] = torch.load(text_enc_path, map_location="""cpu""") # Convert the UNet model lowerCAmelCase : int = convert_unet_state_dict(unet_state_dict) lowerCAmelCase : Optional[int] = {"""model.diffusion_model.""" + k: v for k, v in unet_state_dict.items()} # Convert the VAE model lowerCAmelCase : Union[str, Any] = convert_vae_state_dict(vae_state_dict) lowerCAmelCase : Optional[int] = {"""first_stage_model.""" + k: v for k, v in vae_state_dict.items()} # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper lowerCAmelCase : Any = """text_model.encoder.layers.22.layer_norm2.bias""" in text_enc_dict if is_vaa_model: # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm lowerCAmelCase : Any = {"""transformer.""" + k: v for k, v in text_enc_dict.items()} lowerCAmelCase : str = convert_text_enc_state_dict_vaa(text_enc_dict) lowerCAmelCase : Dict = {"""cond_stage_model.model.""" + k: v for k, v in text_enc_dict.items()} else: lowerCAmelCase : Any = convert_text_enc_state_dict(text_enc_dict) lowerCAmelCase : Optional[Any] = {"""cond_stage_model.transformer.""" + k: v for k, v in text_enc_dict.items()} # Put together new checkpoint lowerCAmelCase : Union[str, Any] = {**unet_state_dict, **vae_state_dict, **text_enc_dict} if args.half: lowerCAmelCase : str = {k: v.half() for k, v in state_dict.items()} if args.use_safetensors: save_file(state_dict, args.checkpoint_path) else: lowerCAmelCase : int = {"""state_dict""": state_dict} torch.save(state_dict, args.checkpoint_path)
671
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _A : Any = {"""configuration_xglm""": ["""XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XGLMConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Optional[Any] = ["""XGLMTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Any = ["""XGLMTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : str = [ """XGLM_PRETRAINED_MODEL_ARCHIVE_LIST""", """XGLMForCausalLM""", """XGLMModel""", """XGLMPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Tuple = [ """FlaxXGLMForCausalLM""", """FlaxXGLMModel""", """FlaxXGLMPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : List[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 _A : List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
100
from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase : int = logging.get_logger(__name__) lowerCAmelCase : Dict = { """microsoft/xprophetnet-large-wiki100-cased""": ( """https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json""" ), } class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : Optional[Any] = '''xlm-prophetnet''' _UpperCAmelCase : Any = ['''past_key_values'''] _UpperCAmelCase : Tuple = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self : str , lowerCAmelCase__ : Optional[float] = 0.1 , lowerCAmelCase__ : Optional[Union[str, Callable]] = "gelu" , lowerCAmelCase__ : Optional[int] = 3_0522 , lowerCAmelCase__ : Optional[int] = 1024 , lowerCAmelCase__ : Optional[int] = 4096 , lowerCAmelCase__ : Optional[int] = 12 , lowerCAmelCase__ : Optional[int] = 16 , lowerCAmelCase__ : Optional[int] = 4096 , lowerCAmelCase__ : Optional[int] = 12 , lowerCAmelCase__ : Optional[int] = 16 , lowerCAmelCase__ : Optional[float] = 0.1 , lowerCAmelCase__ : Optional[float] = 0.1 , lowerCAmelCase__ : Optional[int] = 512 , lowerCAmelCase__ : Optional[float] = 0.02 , lowerCAmelCase__ : Optional[bool] = True , lowerCAmelCase__ : Optional[bool] = True , lowerCAmelCase__ : Optional[int] = 0 , lowerCAmelCase__ : Optional[int] = 2 , lowerCAmelCase__ : Optional[int] = 32 , lowerCAmelCase__ : Optional[int] = 128 , lowerCAmelCase__ : Optional[bool] = False , lowerCAmelCase__ : Optional[float] = 0.0 , lowerCAmelCase__ : Optional[bool] = True , lowerCAmelCase__ : Optional[int] = 0 , lowerCAmelCase__ : Optional[int] = 1 , lowerCAmelCase__ : Optional[int] = 2 , **lowerCAmelCase__ : List[str] , ): SCREAMING_SNAKE_CASE_: List[Any] = vocab_size SCREAMING_SNAKE_CASE_: int = hidden_size SCREAMING_SNAKE_CASE_: Any = encoder_ffn_dim SCREAMING_SNAKE_CASE_: Tuple = num_encoder_layers SCREAMING_SNAKE_CASE_: List[Any] = num_encoder_attention_heads SCREAMING_SNAKE_CASE_: Dict = decoder_ffn_dim SCREAMING_SNAKE_CASE_: Any = num_decoder_layers SCREAMING_SNAKE_CASE_: Tuple = num_decoder_attention_heads SCREAMING_SNAKE_CASE_: str = max_position_embeddings SCREAMING_SNAKE_CASE_: str = init_std # Normal(0, this parameter) SCREAMING_SNAKE_CASE_: Dict = activation_function # parameters for xlmprophetnet SCREAMING_SNAKE_CASE_: Optional[int] = ngram SCREAMING_SNAKE_CASE_: Tuple = num_buckets SCREAMING_SNAKE_CASE_: Union[str, Any] = relative_max_distance SCREAMING_SNAKE_CASE_: List[str] = disable_ngram_loss SCREAMING_SNAKE_CASE_: Dict = eps # 3 Types of Dropout SCREAMING_SNAKE_CASE_: Any = attention_dropout SCREAMING_SNAKE_CASE_: Optional[int] = activation_dropout SCREAMING_SNAKE_CASE_: str = dropout SCREAMING_SNAKE_CASE_: Optional[int] = use_cache super().__init__( pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , is_encoder_decoder=lowerCAmelCase__ , add_cross_attention=lowerCAmelCase__ , decoder_start_token_id=lowerCAmelCase__ , **lowerCAmelCase__ , ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def _SCREAMING_SNAKE_CASE ( self : int , lowerCAmelCase__ : Any): raise NotImplementedError( "This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and" " `num_decoder_layers`.")
671
0
import argparse import requests import torch from PIL import Image from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor def a__ ( A__ ): if "cls_token" in name: SCREAMING_SNAKE_CASE_ : int = name.replace('cls_token', 'vit.embeddings.cls_token' ) if "mask_token" in name: SCREAMING_SNAKE_CASE_ : str = name.replace('mask_token', 'decoder.mask_token' ) if "decoder_pos_embed" in name: SCREAMING_SNAKE_CASE_ : Tuple = name.replace('decoder_pos_embed', 'decoder.decoder_pos_embed' ) if "pos_embed" in name and "decoder" not in name: SCREAMING_SNAKE_CASE_ : Union[str, Any] = name.replace('pos_embed', 'vit.embeddings.position_embeddings' ) if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE_ : List[str] = name.replace('patch_embed.proj', 'vit.embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE_ : List[Any] = name.replace('patch_embed.norm', 'vit.embeddings.norm' ) if "decoder_blocks" in name: SCREAMING_SNAKE_CASE_ : Optional[int] = name.replace('decoder_blocks', 'decoder.decoder_layers' ) if "blocks" in name: SCREAMING_SNAKE_CASE_ : str = name.replace('blocks', 'vit.encoder.layer' ) if "attn.proj" in name: SCREAMING_SNAKE_CASE_ : Optional[Any] = name.replace('attn.proj', 'attention.output.dense' ) if "attn" in name: SCREAMING_SNAKE_CASE_ : Any = name.replace('attn', 'attention.self' ) if "norm1" in name: SCREAMING_SNAKE_CASE_ : str = name.replace('norm1', 'layernorm_before' ) if "norm2" in name: SCREAMING_SNAKE_CASE_ : str = name.replace('norm2', 'layernorm_after' ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE_ : Any = name.replace('mlp.fc1', 'intermediate.dense' ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE_ : str = name.replace('mlp.fc2', 'output.dense' ) if "decoder_embed" in name: SCREAMING_SNAKE_CASE_ : Tuple = name.replace('decoder_embed', 'decoder.decoder_embed' ) if "decoder_norm" in name: SCREAMING_SNAKE_CASE_ : List[Any] = name.replace('decoder_norm', 'decoder.decoder_norm' ) if "decoder_pred" in name: SCREAMING_SNAKE_CASE_ : List[Any] = name.replace('decoder_pred', 'decoder.decoder_pred' ) if "norm.weight" in name and "decoder" not in name: SCREAMING_SNAKE_CASE_ : List[str] = name.replace('norm.weight', 'vit.layernorm.weight' ) if "norm.bias" in name and "decoder" not in name: SCREAMING_SNAKE_CASE_ : str = name.replace('norm.bias', 'vit.layernorm.bias' ) return name def a__ ( A__, A__ ): for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE_ : List[Any] = orig_state_dict.pop(A__ ) if "qkv" in key: SCREAMING_SNAKE_CASE_ : Union[str, Any] = key.split('.' ) SCREAMING_SNAKE_CASE_ : int = int(key_split[1] ) if "decoder_blocks" in key: SCREAMING_SNAKE_CASE_ : List[str] = config.decoder_hidden_size SCREAMING_SNAKE_CASE_ : Dict = 'decoder.decoder_layers.' if "weight" in key: SCREAMING_SNAKE_CASE_ : Tuple = val[:dim, :] SCREAMING_SNAKE_CASE_ : Optional[Any] = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE_ : List[str] = val[-dim:, :] elif "bias" in key: SCREAMING_SNAKE_CASE_ : Optional[int] = val[:dim] SCREAMING_SNAKE_CASE_ : int = val[dim : dim * 2] SCREAMING_SNAKE_CASE_ : Tuple = val[-dim:] else: SCREAMING_SNAKE_CASE_ : List[Any] = config.hidden_size SCREAMING_SNAKE_CASE_ : Optional[int] = 'vit.encoder.layer.' if "weight" in key: SCREAMING_SNAKE_CASE_ : List[Any] = val[:dim, :] SCREAMING_SNAKE_CASE_ : List[Any] = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE_ : Optional[Any] = val[-dim:, :] elif "bias" in key: SCREAMING_SNAKE_CASE_ : Tuple = val[:dim] SCREAMING_SNAKE_CASE_ : Any = val[dim : dim * 2] SCREAMING_SNAKE_CASE_ : Any = val[-dim:] else: SCREAMING_SNAKE_CASE_ : List[Any] = val return orig_state_dict def a__ ( A__, A__ ): SCREAMING_SNAKE_CASE_ : List[str] = ViTMAEConfig() if "large" in checkpoint_url: SCREAMING_SNAKE_CASE_ : Any = 1_0_2_4 SCREAMING_SNAKE_CASE_ : List[Any] = 4_0_9_6 SCREAMING_SNAKE_CASE_ : Union[str, Any] = 2_4 SCREAMING_SNAKE_CASE_ : List[str] = 1_6 elif "huge" in checkpoint_url: SCREAMING_SNAKE_CASE_ : Optional[int] = 1_4 SCREAMING_SNAKE_CASE_ : int = 1_2_8_0 SCREAMING_SNAKE_CASE_ : Union[str, Any] = 5_1_2_0 SCREAMING_SNAKE_CASE_ : Any = 3_2 SCREAMING_SNAKE_CASE_ : Optional[Any] = 1_6 SCREAMING_SNAKE_CASE_ : Optional[Any] = ViTMAEForPreTraining(A__ ) SCREAMING_SNAKE_CASE_ : str = torch.hub.load_state_dict_from_url(A__, map_location='cpu' )['model'] SCREAMING_SNAKE_CASE_ : int = ViTMAEImageProcessor(size=config.image_size ) SCREAMING_SNAKE_CASE_ : str = convert_state_dict(A__, A__ ) model.load_state_dict(A__ ) model.eval() SCREAMING_SNAKE_CASE_ : Optional[int] = 'https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg' SCREAMING_SNAKE_CASE_ : Any = Image.open(requests.get(A__, stream=A__ ).raw ) SCREAMING_SNAKE_CASE_ : str = ViTMAEImageProcessor(size=config.image_size ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_processor(images=A__, return_tensors='pt' ) # forward pass torch.manual_seed(2 ) SCREAMING_SNAKE_CASE_ : Optional[Any] = model(**A__ ) SCREAMING_SNAKE_CASE_ : int = outputs.logits if "large" in checkpoint_url: SCREAMING_SNAKE_CASE_ : Any = torch.tensor( [[-0.73_09, -0.71_28, -1.01_69], [-1.01_61, -0.90_58, -1.18_78], [-1.04_78, -0.94_11, -1.19_11]] ) elif "huge" in checkpoint_url: SCREAMING_SNAKE_CASE_ : List[Any] = torch.tensor( [[-1.15_99, -0.91_99, -1.22_21], [-1.19_52, -0.92_69, -1.23_07], [-1.21_43, -0.93_37, -1.22_62]] ) else: SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.tensor( [[-0.91_92, -0.84_81, -1.12_59], [-1.13_49, -1.00_34, -1.25_99], [-1.17_57, -1.04_29, -1.27_26]] ) # verify logits assert torch.allclose(logits[0, :3, :3], A__, atol=1E-4 ) print(F'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(A__ ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(A__ ) if __name__ == "__main__": lowerCAmelCase__ : str =argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth', type=str, help='URL of the checkpoint you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) lowerCAmelCase__ : str =parser.parse_args() convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
101
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL lowerCAmelCase : Dict = logging.get_logger(__name__) def A_ ( _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[int] = b.T SCREAMING_SNAKE_CASE_: Dict = np.sum(np.square(_UpperCAmelCase ) , axis=1 ) SCREAMING_SNAKE_CASE_: Tuple = np.sum(np.square(_UpperCAmelCase ) , axis=0 ) SCREAMING_SNAKE_CASE_: List[Any] = np.matmul(_UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Dict = aa[:, None] - 2 * ab + ba[None, :] return d def A_ ( _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: int = x.reshape(-1 , 3 ) SCREAMING_SNAKE_CASE_: Tuple = squared_euclidean_distance(_UpperCAmelCase , _UpperCAmelCase ) return np.argmin(_UpperCAmelCase , axis=1 ) class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : int = ['''pixel_values'''] def __init__( self : Tuple , lowerCAmelCase__ : Optional[Union[List[List[int]], np.ndarray]] = None , lowerCAmelCase__ : bool = True , lowerCAmelCase__ : Dict[str, int] = None , lowerCAmelCase__ : PILImageResampling = PILImageResampling.BILINEAR , lowerCAmelCase__ : bool = True , lowerCAmelCase__ : bool = True , **lowerCAmelCase__ : List[str] , ): super().__init__(**lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Any = size if size is not None else {"height": 256, "width": 256} SCREAMING_SNAKE_CASE_: Tuple = get_size_dict(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Tuple = np.array(lowerCAmelCase__) if clusters is not None else None SCREAMING_SNAKE_CASE_: Dict = do_resize SCREAMING_SNAKE_CASE_: str = size SCREAMING_SNAKE_CASE_: List[Any] = resample SCREAMING_SNAKE_CASE_: Optional[int] = do_normalize SCREAMING_SNAKE_CASE_: Dict = do_color_quantize def _SCREAMING_SNAKE_CASE ( self : List[str] , lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : Dict[str, int] , lowerCAmelCase__ : PILImageResampling = PILImageResampling.BILINEAR , lowerCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **lowerCAmelCase__ : Optional[Any] , ): SCREAMING_SNAKE_CASE_: List[str] = get_size_dict(lowerCAmelCase__) if "height" not in size or "width" not in size: raise ValueError(F"Size dictionary must contain both height and width keys. Got {size.keys()}") return resize( lowerCAmelCase__ , size=(size["height"], size["width"]) , resample=lowerCAmelCase__ , data_format=lowerCAmelCase__ , **lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , ): SCREAMING_SNAKE_CASE_: str = rescale(image=lowerCAmelCase__ , scale=1 / 127.5 , data_format=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Optional[int] = image - 1 return image def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase__ : ImageInput , lowerCAmelCase__ : bool = None , lowerCAmelCase__ : Dict[str, int] = None , lowerCAmelCase__ : PILImageResampling = None , lowerCAmelCase__ : bool = None , lowerCAmelCase__ : Optional[bool] = None , lowerCAmelCase__ : Optional[Union[List[List[int]], np.ndarray]] = None , lowerCAmelCase__ : Optional[Union[str, TensorType]] = None , lowerCAmelCase__ : Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST , **lowerCAmelCase__ : Union[str, Any] , ): SCREAMING_SNAKE_CASE_: Tuple = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE_: Optional[int] = size if size is not None else self.size SCREAMING_SNAKE_CASE_: Dict = get_size_dict(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[str] = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE_: int = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE_: List[str] = do_color_quantize if do_color_quantize is not None else self.do_color_quantize SCREAMING_SNAKE_CASE_: Tuple = clusters if clusters is not None else self.clusters SCREAMING_SNAKE_CASE_: Optional[int] = np.array(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Optional[int] = make_list_of_images(lowerCAmelCase__) if not valid_images(lowerCAmelCase__): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray.") if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True.") if do_color_quantize and clusters is None: raise ValueError("Clusters must be specified if do_color_quantize is True.") # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE_: Union[str, Any] = [to_numpy_array(lowerCAmelCase__) for image in images] if do_resize: SCREAMING_SNAKE_CASE_: Optional[Any] = [self.resize(image=lowerCAmelCase__ , size=lowerCAmelCase__ , resample=lowerCAmelCase__) for image in images] if do_normalize: SCREAMING_SNAKE_CASE_: str = [self.normalize(image=lowerCAmelCase__) for image in images] if do_color_quantize: SCREAMING_SNAKE_CASE_: Any = [to_channel_dimension_format(lowerCAmelCase__ , ChannelDimension.LAST) for image in images] # color quantize from (batch_size, height, width, 3) to (batch_size, height, width) SCREAMING_SNAKE_CASE_: List[Any] = np.array(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[str] = color_quantize(lowerCAmelCase__ , lowerCAmelCase__).reshape(images.shape[:-1]) # flatten to (batch_size, height*width) SCREAMING_SNAKE_CASE_: str = images.shape[0] SCREAMING_SNAKE_CASE_: Tuple = images.reshape(lowerCAmelCase__ , -1) # We need to convert back to a list of images to keep consistent behaviour across processors. SCREAMING_SNAKE_CASE_: str = list(lowerCAmelCase__) else: SCREAMING_SNAKE_CASE_: Dict = [to_channel_dimension_format(lowerCAmelCase__ , lowerCAmelCase__) for image in images] SCREAMING_SNAKE_CASE_: Optional[Any] = {"input_ids": images} return BatchFeature(data=lowerCAmelCase__ , tensor_type=lowerCAmelCase__)
671
0
"""simple docstring""" import unittest from transformers import MPNetConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) class lowercase__ : """simple docstring""" def __init__( self , _A , _A=1_3 , _A=7 , _A=True , _A=True , _A=False , _A=True , _A=9_9 , _A=6_4 , _A=5 , _A=4 , _A=6_4 , _A="gelu" , _A=0.1 , _A=0.1 , _A=5_1_2 , _A=1_6 , _A=2 , _A=0.02 , _A=3 , _A=4 , _A=None , ): '''simple docstring''' UpperCamelCase : Union[str, Any] = parent UpperCamelCase : Tuple = batch_size UpperCamelCase : Any = seq_length UpperCamelCase : str = is_training UpperCamelCase : Optional[Any] = use_input_mask UpperCamelCase : Tuple = use_token_type_ids UpperCamelCase : List[str] = use_labels UpperCamelCase : str = vocab_size UpperCamelCase : Union[str, Any] = hidden_size UpperCamelCase : Dict = num_hidden_layers UpperCamelCase : Union[str, Any] = num_attention_heads UpperCamelCase : Any = intermediate_size UpperCamelCase : Any = hidden_act UpperCamelCase : Dict = hidden_dropout_prob UpperCamelCase : Optional[Any] = attention_probs_dropout_prob UpperCamelCase : Any = max_position_embeddings UpperCamelCase : Dict = type_vocab_size UpperCamelCase : Dict = type_sequence_label_size UpperCamelCase : Tuple = initializer_range UpperCamelCase : str = num_labels UpperCamelCase : Optional[Any] = num_choices UpperCamelCase : Optional[int] = scope def _a ( self ): '''simple docstring''' return MPNetConfig.from_pretrained("""microsoft/mpnet-base""" ) def _a ( self ): '''simple docstring''' UpperCamelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Optional[Any] = None if self.use_input_mask: UpperCamelCase : int = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : List[str] = None UpperCamelCase : Dict = None UpperCamelCase : Union[str, Any] = None if self.use_labels: UpperCamelCase : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : List[str] = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : Optional[Any] = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self ): '''simple docstring''' return MPNetConfig( 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 , initializer_range=self.initializer_range , ) def _a ( self , _A , _A , _A , _A , _A , _A ): '''simple docstring''' UpperCamelCase : int = MPNetModel(config=_A ) model.to(_A ) model.eval() UpperCamelCase : Union[str, Any] = model(_A , _A ) UpperCamelCase : List[Any] = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def _a ( self , _A , _A , _A , _A , _A , _A ): '''simple docstring''' UpperCamelCase : Tuple = MPNetForQuestionAnswering(config=_A ) model.to(_A ) model.eval() UpperCamelCase : Tuple = model( _A , attention_mask=_A , start_positions=_A , end_positions=_A , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _a ( self , _A , _A , _A , _A , _A , _A ): '''simple docstring''' UpperCamelCase : Optional[Any] = self.num_labels UpperCamelCase : int = MPNetForSequenceClassification(_A ) model.to(_A ) model.eval() UpperCamelCase : Optional[Any] = model(_A , attention_mask=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _a ( self , _A , _A , _A , _A , _A , _A ): '''simple docstring''' UpperCamelCase : Optional[Any] = self.num_choices UpperCamelCase : Optional[int] = MPNetForMultipleChoice(config=_A ) model.to(_A ) model.eval() UpperCamelCase : str = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : List[Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Union[str, Any] = model( _A , attention_mask=_A , labels=_A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _a ( self , _A , _A , _A , _A , _A , _A ): '''simple docstring''' UpperCamelCase : Any = self.num_labels UpperCamelCase : List[Any] = MPNetForTokenClassification(config=_A ) model.to(_A ) model.eval() UpperCamelCase : Any = model(_A , attention_mask=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _a ( self ): '''simple docstring''' UpperCamelCase : Any = self.prepare_config_and_inputs() ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : List[Any] = config_and_inputs UpperCamelCase : str = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowercase__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): """simple docstring""" __lowerCAmelCase : Tuple = ( ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) if is_torch_available() else () ) __lowerCAmelCase : Any = ( { """feature-extraction""": MPNetModel, """fill-mask""": MPNetForMaskedLM, """question-answering""": MPNetForQuestionAnswering, """text-classification""": MPNetForSequenceClassification, """token-classification""": MPNetForTokenClassification, """zero-shot""": MPNetForSequenceClassification, } if is_torch_available() else {} ) __lowerCAmelCase : Union[str, Any] = False __lowerCAmelCase : int = True def _a ( self ): '''simple docstring''' UpperCamelCase : Optional[Any] = MPNetModelTester(self ) UpperCamelCase : Optional[int] = ConfigTester(self , config_class=_A , hidden_size=3_7 ) def _a ( self ): '''simple docstring''' self.config_tester.run_common_tests() def _a ( self ): '''simple docstring''' UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_model(*_A ) def _a ( self ): '''simple docstring''' UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_sequence_classification(*_A ) def _a ( self ): '''simple docstring''' UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_multiple_choice(*_A ) def _a ( self ): '''simple docstring''' UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_token_classification(*_A ) def _a ( self ): '''simple docstring''' UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_question_answering(*_A ) @require_torch class lowercase__ ( unittest.TestCase ): """simple docstring""" @slow def _a ( self ): '''simple docstring''' UpperCamelCase : Dict = MPNetModel.from_pretrained("""microsoft/mpnet-base""" ) UpperCamelCase : Tuple = torch.tensor([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]] ) UpperCamelCase : Any = model(_A )[0] UpperCamelCase : Tuple = torch.Size((1, 1_1, 7_6_8) ) self.assertEqual(output.shape , _A ) UpperCamelCase : Optional[Any] = torch.tensor( [[[-0.05_50, 0.19_43, -0.07_40], [-0.05_62, 0.22_11, -0.05_79], [-0.04_37, 0.33_37, -0.06_41]]] ) # compare the actual values for a slice. self.assertTrue(torch.allclose(output[:, :3, :3] , _A , atol=1e-4 ) )
102
import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert import BertTokenizer lowerCAmelCase : Optional[int] = logging.get_logger(__name__) lowerCAmelCase : str = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} lowerCAmelCase : Tuple = { """vocab_file""": { """facebook/dpr-ctx_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt""" ), """facebook/dpr-ctx_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """facebook/dpr-ctx_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json""" ), """facebook/dpr-ctx_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json""" ), }, } lowerCAmelCase : Union[str, Any] = { """vocab_file""": { """facebook/dpr-question_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt""" ), """facebook/dpr-question_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """facebook/dpr-question_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json""" ), """facebook/dpr-question_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json""" ), }, } lowerCAmelCase : List[str] = { """vocab_file""": { """facebook/dpr-reader-single-nq-base""": ( """https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt""" ), """facebook/dpr-reader-multiset-base""": ( """https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """facebook/dpr-reader-single-nq-base""": ( """https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json""" ), """facebook/dpr-reader-multiset-base""": ( """https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json""" ), }, } lowerCAmelCase : int = { """facebook/dpr-ctx_encoder-single-nq-base""": 512, """facebook/dpr-ctx_encoder-multiset-base""": 512, } lowerCAmelCase : int = { """facebook/dpr-question_encoder-single-nq-base""": 512, """facebook/dpr-question_encoder-multiset-base""": 512, } lowerCAmelCase : List[Any] = { """facebook/dpr-reader-single-nq-base""": 512, """facebook/dpr-reader-multiset-base""": 512, } lowerCAmelCase : Optional[int] = { """facebook/dpr-ctx_encoder-single-nq-base""": {"""do_lower_case""": True}, """facebook/dpr-ctx_encoder-multiset-base""": {"""do_lower_case""": True}, } lowerCAmelCase : Optional[int] = { """facebook/dpr-question_encoder-single-nq-base""": {"""do_lower_case""": True}, """facebook/dpr-question_encoder-multiset-base""": {"""do_lower_case""": True}, } lowerCAmelCase : List[str] = { """facebook/dpr-reader-single-nq-base""": {"""do_lower_case""": True}, """facebook/dpr-reader-multiset-base""": {"""do_lower_case""": True}, } class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : Any = VOCAB_FILES_NAMES _UpperCAmelCase : Optional[Any] = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : List[Any] = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : List[Any] = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : Union[str, Any] = VOCAB_FILES_NAMES _UpperCAmelCase : Optional[int] = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Any = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : str = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION lowerCAmelCase : List[Any] = collections.namedtuple( """DPRSpanPrediction""", ["""span_score""", """relevance_score""", """doc_id""", """start_index""", """end_index""", """text"""] ) lowerCAmelCase : Optional[Any] = collections.namedtuple("""DPRReaderOutput""", ["""start_logits""", """end_logits""", """relevance_logits"""]) lowerCAmelCase : int = R""" Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`. It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers), using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)` with the format: ``` [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids> ``` Args: questions (`str` or `List[str]`): The questions to be encoded. You can specify one question for many passages. In this case, the question will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in `titles` or `texts`. titles (`str` or `List[str]`): The passages titles to be encoded. This can be a string or a list of strings if there are several passages. texts (`str` or `List[str]`): The passages texts to be encoded. This can be a string or a list of strings if there are several passages. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`): Activates and controls padding. Accepts the following values: - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different lengths). truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`): Activates and controls truncation. Accepts the following values: - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided. - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size). max_length (`int`, *optional*): Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length is required by one of the truncation/padding parameters. If the model has no specific maximum input length (like XLNet) truncation/padding to a maximum length will be deactivated. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors instead of list of python integers. Acceptable values are: - `'tf'`: Return TensorFlow `tf.constant` objects. - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return Numpy `np.ndarray` objects. return_attention_mask (`bool`, *optional*): Whether or not to return the attention mask. If not set, will return the attention mask according to the specific tokenizer's default, defined by the `return_outputs` attribute. [What are attention masks?](../glossary#attention-mask) Returns: `Dict[str, List[List[int]]]`: A dictionary with the following keys: - `input_ids`: List of token ids to be fed to a model. - `attention_mask`: List of indices specifying which tokens should be attended to by the model. """ @add_start_docstrings(UpperCAmelCase_ ) class __lowercase : """simple docstring""" def __call__( self : List[Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : Optional[str] = None , lowerCAmelCase__ : Optional[str] = None , lowerCAmelCase__ : Union[bool, str] = False , lowerCAmelCase__ : Union[bool, str] = False , lowerCAmelCase__ : Optional[int] = None , lowerCAmelCase__ : Optional[Union[str, TensorType]] = None , lowerCAmelCase__ : Optional[bool] = None , **lowerCAmelCase__ : Tuple , ): if titles is None and texts is None: return super().__call__( lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , max_length=lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , **lowerCAmelCase__ , ) elif titles is None or texts is None: SCREAMING_SNAKE_CASE_: List[str] = titles if texts is None else texts return super().__call__( lowerCAmelCase__ , lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , max_length=lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , **lowerCAmelCase__ , ) SCREAMING_SNAKE_CASE_: Optional[int] = titles if not isinstance(lowerCAmelCase__ , lowerCAmelCase__) else [titles] SCREAMING_SNAKE_CASE_: int = texts if not isinstance(lowerCAmelCase__ , lowerCAmelCase__) else [texts] SCREAMING_SNAKE_CASE_: str = len(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Tuple = questions if not isinstance(lowerCAmelCase__ , lowerCAmelCase__) else [questions] * n_passages if len(lowerCAmelCase__) != len(lowerCAmelCase__): raise ValueError( F"There should be as many titles than texts but got {len(lowerCAmelCase__)} titles and {len(lowerCAmelCase__)} texts.") SCREAMING_SNAKE_CASE_: Optional[Any] = super().__call__(lowerCAmelCase__ , lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__)["input_ids"] SCREAMING_SNAKE_CASE_: Union[str, Any] = super().__call__(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__)["input_ids"] SCREAMING_SNAKE_CASE_: int = { "input_ids": [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(lowerCAmelCase__ , lowerCAmelCase__) ] } if return_attention_mask is not False: SCREAMING_SNAKE_CASE_: Dict = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id) for input_id in input_ids]) SCREAMING_SNAKE_CASE_: int = attention_mask return self.pad(lowerCAmelCase__ , padding=lowerCAmelCase__ , max_length=lowerCAmelCase__ , return_tensors=lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Any , lowerCAmelCase__ : BatchEncoding , lowerCAmelCase__ : DPRReaderOutput , lowerCAmelCase__ : int = 16 , lowerCAmelCase__ : int = 64 , lowerCAmelCase__ : int = 4 , ): SCREAMING_SNAKE_CASE_: int = reader_input["input_ids"] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: int = reader_output[:3] SCREAMING_SNAKE_CASE_: Tuple = len(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Union[str, Any] = sorted(range(lowerCAmelCase__) , reverse=lowerCAmelCase__ , key=relevance_logits.__getitem__) SCREAMING_SNAKE_CASE_: List[DPRReaderOutput] = [] for doc_id in sorted_docs: SCREAMING_SNAKE_CASE_: Optional[int] = list(input_ids[doc_id]) # assuming question & title information is at the beginning of the sequence SCREAMING_SNAKE_CASE_: str = sequence_ids.index(self.sep_token_id , 2) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: SCREAMING_SNAKE_CASE_: List[Any] = sequence_ids.index(self.pad_token_id) else: SCREAMING_SNAKE_CASE_: Dict = len(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Optional[Any] = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=lowerCAmelCase__ , top_spans=lowerCAmelCase__ , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=lowerCAmelCase__ , start_index=lowerCAmelCase__ , end_index=lowerCAmelCase__ , text=self.decode(sequence_ids[start_index : end_index + 1]) , )) if len(lowerCAmelCase__) >= num_spans: break return nbest_spans_predictions[:num_spans] def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase__ : List[int] , lowerCAmelCase__ : List[int] , lowerCAmelCase__ : int , lowerCAmelCase__ : int , ): SCREAMING_SNAKE_CASE_: Any = [] for start_index, start_score in enumerate(lowerCAmelCase__): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length]): scores.append(((start_index, start_index + answer_length), start_score + end_score)) SCREAMING_SNAKE_CASE_: Union[str, Any] = sorted(lowerCAmelCase__ , key=lambda lowerCAmelCase__: x[1] , reverse=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[str] = [] for (start_index, end_index), score in scores: if start_index > end_index: raise ValueError(F"Wrong span indices: [{start_index}:{end_index}]") SCREAMING_SNAKE_CASE_: int = end_index - start_index + 1 if length > max_answer_length: raise ValueError(F"Span is too long: {length} > {max_answer_length}") if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals): continue chosen_span_intervals.append((start_index, end_index)) if len(lowerCAmelCase__) == top_spans: break return chosen_span_intervals @add_end_docstrings(UpperCAmelCase_ ) class __lowercase ( UpperCAmelCase_ , UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : Any = VOCAB_FILES_NAMES _UpperCAmelCase : Optional[Any] = READER_PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : int = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : Optional[int] = READER_PRETRAINED_INIT_CONFIGURATION _UpperCAmelCase : str = ['''input_ids''', '''attention_mask''']
671
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case = logging.get_logger(__name__) snake_case = { '''google/switch-base-8''': '''https://huggingface.co/google/switch-base-8/blob/main/config.json''', } class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): A__ : List[str] = '''switch_transformers''' A__ : List[str] = ['''past_key_values'''] A__ : Any = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : List[Any] , __lowerCamelCase : Dict=3_2_1_2_8 , __lowerCamelCase : Optional[int]=7_6_8 , __lowerCamelCase : List[str]=6_4 , __lowerCamelCase : Optional[int]=2_0_4_8 , __lowerCamelCase : Any=6_4 , __lowerCamelCase : str=1_2 , __lowerCamelCase : List[Any]=3 , __lowerCamelCase : int=1_2 , __lowerCamelCase : str=3 , __lowerCamelCase : List[str]=1_2 , __lowerCamelCase : int=8 , __lowerCamelCase : Dict=False , __lowerCamelCase : Optional[int]=0.0_1 , __lowerCamelCase : int="float32" , __lowerCamelCase : Any=False , __lowerCamelCase : Optional[int]=3_2 , __lowerCamelCase : int=1_2_8 , __lowerCamelCase : str=0.1 , __lowerCamelCase : Dict=1E-6 , __lowerCamelCase : List[str]=0.0_0_1 , __lowerCamelCase : Optional[int]=0.0_0_1 , __lowerCamelCase : Dict=1.0 , __lowerCamelCase : Optional[int]="relu" , __lowerCamelCase : List[str]=True , __lowerCamelCase : int=False , __lowerCamelCase : Any=True , __lowerCamelCase : str=0 , __lowerCamelCase : List[Any]=1 , **__lowerCamelCase : Optional[int] , ): """simple docstring""" _snake_case = vocab_size _snake_case = d_model _snake_case = d_kv _snake_case = d_ff _snake_case = num_sparse_encoder_layers _snake_case = num_layers _snake_case = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry _snake_case = num_sparse_decoder_layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_encoder_layers > 0: _snake_case = self.num_layers // self.num_sparse_encoder_layers else: _snake_case = self.num_layers # HACK: this will create 0 sparse layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_decoder_layers > 0: _snake_case = self.num_decoder_layers // self.num_sparse_decoder_layers else: _snake_case = self.num_decoder_layers # HACK: this will create 0 sparse layers _snake_case = num_heads _snake_case = num_experts _snake_case = expert_capacity _snake_case = router_bias _snake_case = router_jitter_noise if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(f"""`router_dtype` must be one of 'float32', 'float16' or 'bfloat16', got {router_dtype}""" ) _snake_case = router_dtype _snake_case = router_ignore_padding_tokens _snake_case = relative_attention_num_buckets _snake_case = relative_attention_max_distance _snake_case = dropout_rate _snake_case = layer_norm_epsilon _snake_case = initializer_factor _snake_case = feed_forward_proj _snake_case = use_cache _snake_case = add_router_probs _snake_case = router_z_loss_coef _snake_case = router_aux_loss_coef _snake_case = self.feed_forward_proj.split('''-''' ) _snake_case = act_info[-1] _snake_case = act_info[0] == '''gated''' if len(__lowerCamelCase ) > 1 and act_info[0] != "gated" or len(__lowerCamelCase ) > 2: raise ValueError( f"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" '''Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ''' '''\'gated-gelu\' or \'relu\'''' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": _snake_case = '''gelu_new''' super().__init__( pad_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , is_encoder_decoder=__lowerCamelCase , **__lowerCamelCase , )
103
from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : Optional[Any] = DistilBertTokenizer _UpperCAmelCase : Union[str, Any] = DistilBertTokenizerFast _UpperCAmelCase : int = True @slow def _SCREAMING_SNAKE_CASE ( self : Any): SCREAMING_SNAKE_CASE_: Optional[Any] = DistilBertTokenizer.from_pretrained("distilbert-base-uncased") SCREAMING_SNAKE_CASE_: Any = tokenizer.encode("sequence builders" , add_special_tokens=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[Any] = tokenizer.encode("multi-sequence build" , add_special_tokens=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Tuple = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: int = 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 ]
671
0
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from typing import Optional import evaluate import numpy as np import torch from datasets import load_dataset from PIL import Image from torchvision.transforms import ( CenterCrop, Compose, Normalize, RandomHorizontalFlip, RandomResizedCrop, Resize, ToTensor, ) import transformers from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, AutoConfig, AutoImageProcessor, AutoModelForImageClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version UpperCamelCase = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("""4.31.0""") require_version("""datasets>=1.8.0""", """To fix: pip install -r examples/pytorch/image-classification/requirements.txt""") UpperCamelCase = list(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING.keys()) UpperCamelCase = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) def _lowerCamelCase ( UpperCAmelCase_ : str ) -> Tuple: """simple docstring""" with open(UpperCAmelCase_, "rb" ) as f: A__ = Image.open(UpperCAmelCase_ ) return im.convert("RGB" ) @dataclass class UpperCamelCase__ : """simple docstring""" A__ : Optional[str] = field( default=_lowerCAmelCase , metadata={ "help": "Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub)." } , ) A__ : Optional[str] = field( default=_lowerCAmelCase , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) A__ : Optional[str] = field(default=_lowerCAmelCase , metadata={"help": "A folder containing the training data."} ) A__ : Optional[str] = field(default=_lowerCAmelCase , metadata={"help": "A folder containing the validation data."} ) A__ : Optional[float] = field( default=0.15 , metadata={"help": "Percent to split off of train for validation."} ) A__ : Optional[int] = field( default=_lowerCAmelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) A__ : Optional[int] = field( default=_lowerCAmelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) def snake_case__ ( self ) -> Optional[Any]: if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None): raise ValueError( "You must specify either a dataset name from the hub or a train and/or validation directory." ) @dataclass class UpperCamelCase__ : """simple docstring""" A__ : str = field( default="google/vit-base-patch16-224-in21k" , metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} , ) A__ : Optional[str] = field( default=_lowerCAmelCase , metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(_lowerCAmelCase )} , ) A__ : Optional[str] = field( default=_lowerCAmelCase , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) A__ : Optional[str] = field( default=_lowerCAmelCase , metadata={"help": "Where do you want to store the pretrained models downloaded from s3"} ) A__ : str = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) A__ : str = field(default=_lowerCAmelCase , metadata={"help": "Name or path of preprocessor config."} ) A__ : bool = field( default=_lowerCAmelCase , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) A__ : bool = field( default=_lowerCAmelCase , metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."} , ) def _lowerCamelCase ( UpperCAmelCase_ : Union[str, Any] ) -> Dict: """simple docstring""" A__ = torch.stack([example["pixel_values"] for example in examples] ) A__ = torch.tensor([example["labels"] for example in examples] ) return {"pixel_values": pixel_values, "labels": labels} def _lowerCamelCase ( ) -> str: """simple docstring""" A__ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. A__ , A__ , A__ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: A__ , A__ , A__ = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("run_image_classification", UpperCAmelCase_, UpperCAmelCase_ ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", handlers=[logging.StreamHandler(sys.stdout )], ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() A__ = training_args.get_process_log_level() logger.setLevel(UpperCAmelCase_ ) transformers.utils.logging.set_verbosity(UpperCAmelCase_ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + F"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(F"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. A__ = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: A__ = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. """ "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Set seed before initializing model. set_seed(training_args.seed ) # Initialize our dataset and prepare it for the 'image-classification' task. if data_args.dataset_name is not None: A__ = load_dataset( data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir, task="image-classification", use_auth_token=True if model_args.use_auth_token else None, ) else: A__ = {} if data_args.train_dir is not None: A__ = os.path.join(data_args.train_dir, "**" ) if data_args.validation_dir is not None: A__ = os.path.join(data_args.validation_dir, "**" ) A__ = load_dataset( "imagefolder", data_files=UpperCAmelCase_, cache_dir=model_args.cache_dir, task="image-classification", ) # If we don't have a validation split, split off a percentage of train as validation. A__ = None if "validation" in dataset.keys() else data_args.train_val_split if isinstance(data_args.train_val_split, UpperCAmelCase_ ) and data_args.train_val_split > 0.0: A__ = dataset["train"].train_test_split(data_args.train_val_split ) A__ = split["train"] A__ = split["test"] # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. A__ = dataset["train"].features["labels"].names A__ , A__ = {}, {} for i, label in enumerate(UpperCAmelCase_ ): A__ = str(UpperCAmelCase_ ) A__ = label # Load the accuracy metric from the datasets package A__ = evaluate.load("accuracy" ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(UpperCAmelCase_ : int ): return metric.compute(predictions=np.argmax(p.predictions, axis=1 ), references=p.label_ids ) A__ = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path, num_labels=len(UpperCAmelCase_ ), labelaid=UpperCAmelCase_, idalabel=UpperCAmelCase_, finetuning_task="image-classification", cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) A__ = AutoModelForImageClassification.from_pretrained( model_args.model_name_or_path, from_tf=bool(".ckpt" in model_args.model_name_or_path ), config=UpperCAmelCase_, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ignore_mismatched_sizes=model_args.ignore_mismatched_sizes, ) A__ = AutoImageProcessor.from_pretrained( model_args.image_processor_name or model_args.model_name_or_path, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) # Define torchvision transforms to be applied to each image. if "shortest_edge" in image_processor.size: A__ = image_processor.size["shortest_edge"] else: A__ = (image_processor.size["height"], image_processor.size["width"]) A__ = Normalize(mean=image_processor.image_mean, std=image_processor.image_std ) A__ = Compose( [ RandomResizedCrop(UpperCAmelCase_ ), RandomHorizontalFlip(), ToTensor(), normalize, ] ) A__ = Compose( [ Resize(UpperCAmelCase_ ), CenterCrop(UpperCAmelCase_ ), ToTensor(), normalize, ] ) def train_transforms(UpperCAmelCase_ : Tuple ): A__ = [ _train_transforms(pil_img.convert("RGB" ) ) for pil_img in example_batch["image"] ] return example_batch def val_transforms(UpperCAmelCase_ : Any ): A__ = [_val_transforms(pil_img.convert("RGB" ) ) for pil_img in example_batch["image"]] return example_batch if training_args.do_train: if "train" not in dataset: raise ValueError("--do_train requires a train dataset" ) if data_args.max_train_samples is not None: A__ = ( dataset["train"].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms dataset["train"].set_transform(UpperCAmelCase_ ) if training_args.do_eval: if "validation" not in dataset: raise ValueError("--do_eval requires a validation dataset" ) if data_args.max_eval_samples is not None: A__ = ( dataset["validation"].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms dataset["validation"].set_transform(UpperCAmelCase_ ) # Initalize our trainer A__ = Trainer( model=UpperCAmelCase_, args=UpperCAmelCase_, train_dataset=dataset["train"] if training_args.do_train else None, eval_dataset=dataset["validation"] if training_args.do_eval else None, compute_metrics=UpperCAmelCase_, tokenizer=UpperCAmelCase_, data_collator=UpperCAmelCase_, ) # Training if training_args.do_train: A__ = None if training_args.resume_from_checkpoint is not None: A__ = training_args.resume_from_checkpoint elif last_checkpoint is not None: A__ = last_checkpoint A__ = trainer.train(resume_from_checkpoint=UpperCAmelCase_ ) trainer.save_model() trainer.log_metrics("train", train_result.metrics ) trainer.save_metrics("train", train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: A__ = trainer.evaluate() trainer.log_metrics("eval", UpperCAmelCase_ ) trainer.save_metrics("eval", UpperCAmelCase_ ) # Write model card and (optionally) push to hub A__ = { "finetuned_from": model_args.model_name_or_path, "tasks": "image-classification", "dataset": data_args.dataset_name, "tags": ["image-classification", "vision"], } if training_args.push_to_hub: trainer.push_to_hub(**UpperCAmelCase_ ) else: trainer.create_model_card(**UpperCAmelCase_ ) if __name__ == "__main__": main()
104
import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient lowerCAmelCase : List[Any] = WebClient(token=os.environ["""CI_SLACK_BOT_TOKEN"""]) def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[int] = test_results.split(" " ) SCREAMING_SNAKE_CASE_: Tuple = 0 SCREAMING_SNAKE_CASE_: str = 0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. SCREAMING_SNAKE_CASE_: Optional[Any] = expressions[-2] if "=" in expressions[-1] else expressions[-1] for i, expression in enumerate(_UpperCAmelCase ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: str = {} SCREAMING_SNAKE_CASE_: Any = None SCREAMING_SNAKE_CASE_: Union[str, Any] = False for line in failures_short_lines.split("\n" ): if re.search(R"_ \[doctest\]" , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: List[Any] = True SCREAMING_SNAKE_CASE_: Dict = line.split(" " )[2] elif in_error and not line.split(" " )[0].isdigit(): SCREAMING_SNAKE_CASE_: Union[str, Any] = line SCREAMING_SNAKE_CASE_: List[str] = False return failures class __lowercase : """simple docstring""" def __init__( self : Any , lowerCAmelCase__ : str , lowerCAmelCase__ : Dict): SCREAMING_SNAKE_CASE_: Dict = title SCREAMING_SNAKE_CASE_: int = doc_test_results["time_spent"].split(",")[0] SCREAMING_SNAKE_CASE_: int = doc_test_results["success"] SCREAMING_SNAKE_CASE_: Optional[Any] = doc_test_results["failures"] SCREAMING_SNAKE_CASE_: Any = self.n_success + self.n_failures # Failures and success of the modeling tests SCREAMING_SNAKE_CASE_: Optional[int] = doc_test_results @property def _SCREAMING_SNAKE_CASE ( self : Any): SCREAMING_SNAKE_CASE_: int = [self._time_spent] SCREAMING_SNAKE_CASE_: List[Any] = 0 for time in time_spent: SCREAMING_SNAKE_CASE_: Union[str, Any] = time.split(":") # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(lowerCAmelCase__) == 1: SCREAMING_SNAKE_CASE_: Dict = [0, 0, time_parts[0]] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: int = int(time_parts[0]), int(time_parts[1]), float(time_parts[2]) total_secs += hours * 3600 + minutes * 60 + seconds SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: str = total_secs // 3600, (total_secs % 3600) // 60, total_secs % 60 return F"{int(lowerCAmelCase__)}h{int(lowerCAmelCase__)}m{int(lowerCAmelCase__)}s" @property def _SCREAMING_SNAKE_CASE ( self : List[Any]): return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): return { "type": "section", "text": { "type": "plain_text", "text": F"🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.", "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": F"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", }, } @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): return { "type": "section", "text": { "type": "plain_text", "text": ( F"There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in" F" {self.time}." ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": F"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", }, } @property def _SCREAMING_SNAKE_CASE ( self : Any): SCREAMING_SNAKE_CASE_: Optional[Any] = 40 SCREAMING_SNAKE_CASE_: List[str] = {k: v["failed"] for k, v in doc_test_results.items() if isinstance(lowerCAmelCase__ , lowerCAmelCase__)} SCREAMING_SNAKE_CASE_: Tuple = "" for category, failures in category_failures.items(): if len(lowerCAmelCase__) == 0: continue if report != "": report += "\n\n" report += F"*{category} failures*:".ljust(line_length // 2).rjust(line_length // 2) + "\n" report += "`" report += "`\n`".join(lowerCAmelCase__) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": F"The following examples had failures:\n\n\n{report}\n", }, } @property def _SCREAMING_SNAKE_CASE ( self : str): SCREAMING_SNAKE_CASE_: Optional[Any] = [self.header] if self.n_failures > 0: blocks.append(self.failures) if self.n_failures > 0: blocks.extend([self.category_failures]) if self.n_failures == 0: blocks.append(self.no_failures) return json.dumps(lowerCAmelCase__) @staticmethod def _SCREAMING_SNAKE_CASE ( ): SCREAMING_SNAKE_CASE_: List[str] = [ { "type": "section", "text": { "type": "plain_text", "text": "There was an issue running the tests.", }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": F"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", }, } ] print("Sending the following payload") print(json.dumps({"blocks": json.loads(lowerCAmelCase__)})) client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , text="There was an issue running the tests." , blocks=lowerCAmelCase__ , ) def _SCREAMING_SNAKE_CASE ( self : Tuple): print("Sending the following payload") print(json.dumps({"blocks": json.loads(self.payload)})) SCREAMING_SNAKE_CASE_: Optional[Any] = F"{self.n_failures} failures out of {self.n_tests} tests," if self.n_failures else "All tests passed." SCREAMING_SNAKE_CASE_: List[Any] = client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , blocks=self.payload , text=lowerCAmelCase__ , ) def _SCREAMING_SNAKE_CASE ( self : Dict , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any]): SCREAMING_SNAKE_CASE_: Dict = "" for key, value in failures.items(): SCREAMING_SNAKE_CASE_: str = value[:200] + " [Truncated]" if len(lowerCAmelCase__) > 250 else value failures_text += F"*{key}*\n_{value}_\n\n" SCREAMING_SNAKE_CASE_: Any = job_name SCREAMING_SNAKE_CASE_: List[Any] = {"type": "section", "text": {"type": "mrkdwn", "text": text}} if job_link is not None: SCREAMING_SNAKE_CASE_: Tuple = { "type": "button", "text": {"type": "plain_text", "text": "GitHub Action job", "emoji": True}, "url": job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def _SCREAMING_SNAKE_CASE ( self : Any): if self.thread_ts is None: raise ValueError("Can only post reply if a post has been made.") SCREAMING_SNAKE_CASE_: Tuple = self.doc_test_results.pop("job_link") self.doc_test_results.pop("failures") self.doc_test_results.pop("success") self.doc_test_results.pop("time_spent") SCREAMING_SNAKE_CASE_: Any = sorted(self.doc_test_results.items() , key=lambda lowerCAmelCase__: t[0]) for job, job_result in sorted_dict: if len(job_result["failures"]): SCREAMING_SNAKE_CASE_: Union[str, Any] = F"*Num failures* :{len(job_result['failed'])} \n" SCREAMING_SNAKE_CASE_: Optional[Any] = job_result["failures"] SCREAMING_SNAKE_CASE_: Optional[Any] = self.get_reply_blocks(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , text=lowerCAmelCase__) print("Sending the following reply") print(json.dumps({"blocks": blocks})) client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , text=F"Results for {job}" , blocks=lowerCAmelCase__ , thread_ts=self.thread_ts["ts"] , ) time.sleep(1) def A_ ( ): SCREAMING_SNAKE_CASE_: Tuple = os.environ["GITHUB_RUN_ID"] SCREAMING_SNAKE_CASE_: Any = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100" SCREAMING_SNAKE_CASE_: List[Any] = requests.get(_UpperCAmelCase ).json() SCREAMING_SNAKE_CASE_: Optional[Any] = {} try: jobs.update({job["name"]: job["html_url"] for job in result["jobs"]} ) SCREAMING_SNAKE_CASE_: Any = math.ceil((result["total_count"] - 1_00) / 1_00 ) for i in range(_UpperCAmelCase ): SCREAMING_SNAKE_CASE_: str = requests.get(url + f"&page={i + 2}" ).json() jobs.update({job["name"]: job["html_url"] for job in result["jobs"]} ) return jobs except Exception as e: print("Unknown error, could not fetch links." , _UpperCAmelCase ) return {} def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[Any] = {} if os.path.exists(_UpperCAmelCase ): SCREAMING_SNAKE_CASE_: List[str] = os.listdir(_UpperCAmelCase ) for file in files: try: with open(os.path.join(_UpperCAmelCase , _UpperCAmelCase ) , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE_: Dict = f.read() except UnicodeDecodeError as e: raise ValueError(f"Could not open {os.path.join(_UpperCAmelCase , _UpperCAmelCase )}." ) from e return _artifact def A_ ( ): class __lowercase : """simple docstring""" def __init__( self : List[str] , lowerCAmelCase__ : str): SCREAMING_SNAKE_CASE_: Dict = name SCREAMING_SNAKE_CASE_: List[str] = [] def __str__( self : Optional[Any]): return self.name def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase__ : str): self.paths.append({"name": self.name, "path": path}) SCREAMING_SNAKE_CASE_: Dict[str, Artifact] = {} SCREAMING_SNAKE_CASE_: List[Any] = filter(os.path.isdir , os.listdir() ) for directory in directories: SCREAMING_SNAKE_CASE_: Dict = directory if artifact_name not in _available_artifacts: SCREAMING_SNAKE_CASE_: Tuple = Artifact(_UpperCAmelCase ) _available_artifacts[artifact_name].add_path(_UpperCAmelCase ) return _available_artifacts if __name__ == "__main__": lowerCAmelCase : Tuple = get_job_links() lowerCAmelCase : Optional[Any] = retrieve_available_artifacts() lowerCAmelCase : Any = collections.OrderedDict( [ ("""*.py""", """API Examples"""), ("""*.md""", """MD Examples"""), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' lowerCAmelCase : int = { v: { """failed""": [], """failures""": {}, } for v in docs.values() } # Link to the GitHub Action job lowerCAmelCase : Optional[int] = github_actions_job_links.get("""run_doctests""") lowerCAmelCase : List[Any] = available_artifacts["""doc_tests_gpu_test_reports"""].paths[0] lowerCAmelCase : Any = retrieve_artifact(artifact_path["""name"""]) if "stats" in artifact: lowerCAmelCase , lowerCAmelCase , lowerCAmelCase : List[str] = handle_test_results(artifact["""stats"""]) lowerCAmelCase : List[str] = failed lowerCAmelCase : Any = success lowerCAmelCase : Dict = time_spent[1:-1] + """, """ lowerCAmelCase : str = extract_first_line_failure(artifact["""failures_short"""]) for line in artifact["summary_short"].split("""\n"""): if re.search("""FAILED""", line): lowerCAmelCase : Tuple = line.replace("""FAILED """, """""") lowerCAmelCase : str = line.split()[0].replace("""\n""", """""") if "::" in line: lowerCAmelCase , lowerCAmelCase : Optional[int] = line.split("""::""") else: lowerCAmelCase , lowerCAmelCase : str = line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): lowerCAmelCase : str = docs[file_regex] doc_test_results[category]["failed"].append(test) lowerCAmelCase : str = all_failures[test] if test in all_failures else """N/A""" lowerCAmelCase : Any = failure break lowerCAmelCase : Union[str, Any] = Message("""🤗 Results of the doc tests.""", doc_test_results) message.post() message.post_reply()
671
0
def __UpperCAmelCase ( lowerCamelCase_ : str ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = 0 for ch in input_str: SCREAMING_SNAKE_CASE_ : Union[str, Any] = ord(lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : Tuple = pow(2 , lowerCamelCase_ ) # If we already turned on bit for current character's unicode if bitmap >> ch_unicode & 1 == 1: return False bitmap |= ch_bit_index_on return True if __name__ == "__main__": import doctest doctest.testmod()
105
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # and perform gradient accumulation # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## lowerCAmelCase : str = 16 lowerCAmelCase : List[Any] = 32 def A_ ( _UpperCAmelCase , _UpperCAmelCase = 16 ): SCREAMING_SNAKE_CASE_: List[Any] = AutoTokenizer.from_pretrained("bert-base-cased" ) SCREAMING_SNAKE_CASE_: Tuple = load_dataset("glue" , "mrpc" ) def tokenize_function(_UpperCAmelCase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE_: List[Any] = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE_: str = datasets.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=["idx", "sentence1", "sentence2"] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE_: Optional[Any] = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(_UpperCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE_: List[Any] = 1_28 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE_: Tuple = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE_: int = 8 else: SCREAMING_SNAKE_CASE_: Any = None return tokenizer.pad( _UpperCAmelCase , padding="longest" , max_length=_UpperCAmelCase , pad_to_multiple_of=_UpperCAmelCase , return_tensors="pt" , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE_: Optional[Any] = DataLoader( tokenized_datasets["train"] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple = DataLoader( tokenized_datasets["validation"] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""", None) == "1": from accelerate.test_utils.training import mocked_dataloaders lowerCAmelCase : Optional[int] = mocked_dataloaders # noqa: F811 def A_ ( _UpperCAmelCase , _UpperCAmelCase ): # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS" , _UpperCAmelCase ) == "1": SCREAMING_SNAKE_CASE_: Tuple = 2 # New Code # SCREAMING_SNAKE_CASE_: List[str] = int(args.gradient_accumulation_steps ) # Initialize accelerator SCREAMING_SNAKE_CASE_: int = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=_UpperCAmelCase ) if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1: raise NotImplementedError( "Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE_: Tuple = config["lr"] SCREAMING_SNAKE_CASE_: List[str] = int(config["num_epochs"] ) SCREAMING_SNAKE_CASE_: List[str] = int(config["seed"] ) SCREAMING_SNAKE_CASE_: Optional[int] = int(config["batch_size"] ) SCREAMING_SNAKE_CASE_: str = evaluate.load("glue" , "mrpc" ) set_seed(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[str] = get_dataloaders(_UpperCAmelCase , _UpperCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE_: Union[str, Any] = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=_UpperCAmelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE_: List[Any] = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE_: Union[str, Any] = AdamW(params=model.parameters() , lr=_UpperCAmelCase ) # Instantiate scheduler SCREAMING_SNAKE_CASE_: str = get_linear_schedule_with_warmup( optimizer=_UpperCAmelCase , num_warmup_steps=1_00 , num_training_steps=(len(_UpperCAmelCase ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Dict = accelerator.prepare( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) # Now we train the model for epoch in range(_UpperCAmelCase ): model.train() for step, batch in enumerate(_UpperCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(_UpperCAmelCase ): SCREAMING_SNAKE_CASE_: List[Any] = model(**_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] = output.loss accelerator.backward(_UpperCAmelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(_UpperCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE_: Optional[Any] = model(**_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=_UpperCAmelCase , references=_UpperCAmelCase , ) SCREAMING_SNAKE_CASE_: List[str] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"epoch {epoch}:" , _UpperCAmelCase ) def A_ ( ): SCREAMING_SNAKE_CASE_: str = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=_UpperCAmelCase , default=_UpperCAmelCase , choices=["no", "fp16", "bf16", "fp8"] , help="Whether to use mixed precision. Choose" "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." "and an Nvidia Ampere GPU." , ) # New Code # parser.add_argument( "--gradient_accumulation_steps" , type=_UpperCAmelCase , default=1 , help="The number of minibatches to be ran before gradients are accumulated." , ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) SCREAMING_SNAKE_CASE_: List[Any] = parser.parse_args() SCREAMING_SNAKE_CASE_: Tuple = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(_UpperCAmelCase , _UpperCAmelCase ) if __name__ == "__main__": main()
671
0
import logging from transformers import PretrainedConfig __snake_case :int =logging.getLogger(__name__) __snake_case :Tuple ={ 'bertabs-finetuned-cnndm': 'https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/resolve/main/config.json', } class lowerCAmelCase__ ( _lowerCamelCase ): A_ : Dict = 'bertabs' def __init__( self : Optional[int] , __UpperCamelCase : int=30_522 , __UpperCamelCase : Tuple=512 , __UpperCamelCase : List[Any]=6 , __UpperCamelCase : Tuple=512 , __UpperCamelCase : Dict=8 , __UpperCamelCase : List[Any]=512 , __UpperCamelCase : Dict=0.2 , __UpperCamelCase : Optional[Any]=6 , __UpperCamelCase : Union[str, Any]=768 , __UpperCamelCase : List[Any]=8 , __UpperCamelCase : Optional[int]=2_048 , __UpperCamelCase : Tuple=0.2 , **__UpperCamelCase : Any , ) -> Union[str, Any]: super().__init__(**__UpperCamelCase ) A = vocab_size A = max_pos A = enc_layers A = enc_hidden_size A = enc_heads A = enc_ff_size A = enc_dropout A = dec_layers A = dec_hidden_size A = dec_heads A = dec_ff_size A = dec_dropout
106
from math import asin, atan, cos, radians, sin, sqrt, tan lowerCAmelCase : Union[str, Any] = 637_8137.0 lowerCAmelCase : int = 635_6752.31_4245 lowerCAmelCase : Union[str, Any] = 6378137 def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: List[Any] = (AXIS_A - AXIS_B) / AXIS_A SCREAMING_SNAKE_CASE_: str = atan((1 - flattening) * tan(radians(_UpperCAmelCase ) ) ) SCREAMING_SNAKE_CASE_: Optional[int] = atan((1 - flattening) * tan(radians(_UpperCAmelCase ) ) ) SCREAMING_SNAKE_CASE_: Any = radians(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Dict = radians(_UpperCAmelCase ) # Equation SCREAMING_SNAKE_CASE_: str = sin((phi_a - phi_a) / 2 ) SCREAMING_SNAKE_CASE_: List[Any] = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda SCREAMING_SNAKE_CASE_: Tuple = sqrt(sin_sq_phi + (cos(_UpperCAmelCase ) * cos(_UpperCAmelCase ) * sin_sq_lambda) ) return 2 * RADIUS * asin(_UpperCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
671
0
'''simple docstring''' import warnings from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class lowercase_ ( _UpperCamelCase ): """simple docstring""" __lowerCAmelCase = ["image_processor", "tokenizer"] __lowerCAmelCase = "FlavaImageProcessor" __lowerCAmelCase = ("BertTokenizer", "BertTokenizerFast") def __init__( self : int, UpperCamelCase__ : str=None, UpperCamelCase__ : Any=None, **UpperCamelCase__ : List[Any] ) -> str: _A = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.', UpperCamelCase__, ) _A = kwargs.pop('feature_extractor' ) _A = 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__(UpperCamelCase__, UpperCamelCase__ ) _A = self.image_processor def __call__( self : Union[str, Any], UpperCamelCase__ : Optional[ImageInput] = None, UpperCamelCase__ : Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None, UpperCamelCase__ : bool = True, UpperCamelCase__ : Union[bool, str, PaddingStrategy] = False, UpperCamelCase__ : Union[bool, str, TruncationStrategy] = False, UpperCamelCase__ : Optional[int] = None, UpperCamelCase__ : int = 0, UpperCamelCase__ : Optional[int] = None, UpperCamelCase__ : Optional[bool] = None, UpperCamelCase__ : Optional[bool] = None, UpperCamelCase__ : Optional[bool] = None, UpperCamelCase__ : Optional[bool] = None, UpperCamelCase__ : bool = False, UpperCamelCase__ : bool = False, UpperCamelCase__ : bool = False, UpperCamelCase__ : bool = False, UpperCamelCase__ : bool = True, UpperCamelCase__ : Optional[Union[str, TensorType]] = None, **UpperCamelCase__ : Dict, ) -> List[str]: 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: _A = self.tokenizer( text=UpperCamelCase__, add_special_tokens=UpperCamelCase__, padding=UpperCamelCase__, truncation=UpperCamelCase__, max_length=UpperCamelCase__, stride=UpperCamelCase__, pad_to_multiple_of=UpperCamelCase__, return_token_type_ids=UpperCamelCase__, return_attention_mask=UpperCamelCase__, return_overflowing_tokens=UpperCamelCase__, return_special_tokens_mask=UpperCamelCase__, return_offsets_mapping=UpperCamelCase__, return_length=UpperCamelCase__, verbose=UpperCamelCase__, return_tensors=UpperCamelCase__, **UpperCamelCase__, ) if images is not None: _A = self.image_processor( UpperCamelCase__, return_image_mask=UpperCamelCase__, return_codebook_pixels=UpperCamelCase__, return_tensors=UpperCamelCase__, **UpperCamelCase__, ) if text is not None and images is not None: encoding.update(UpperCamelCase__ ) return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCamelCase__ ), tensor_type=UpperCamelCase__ ) def __UpperCAmelCase ( self : Union[str, Any], *UpperCamelCase__ : int, **UpperCamelCase__ : Tuple ) -> Union[str, Any]: return self.tokenizer.batch_decode(*UpperCamelCase__, **UpperCamelCase__ ) def __UpperCAmelCase ( self : Any, *UpperCamelCase__ : Dict, **UpperCamelCase__ : Tuple ) -> Optional[Any]: return self.tokenizer.decode(*UpperCamelCase__, **UpperCamelCase__ ) @property def __UpperCAmelCase ( self : Optional[Any] ) -> Optional[int]: _A = self.tokenizer.model_input_names _A = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def __UpperCAmelCase ( self : Any ) -> Optional[Any]: warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.', UpperCamelCase__, ) return self.image_processor_class @property def __UpperCAmelCase ( self : Optional[Any] ) -> Union[str, Any]: warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.', UpperCamelCase__, ) return self.image_processor
107
import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): # Initialise PyTorch model SCREAMING_SNAKE_CASE_: List[Any] = BertConfig.from_json_file(_UpperCAmelCase ) print(f"Building PyTorch model from configuration: {config}" ) SCREAMING_SNAKE_CASE_: Tuple = BertForPreTraining(_UpperCAmelCase ) # Load weights from tf checkpoint load_tf_weights_in_bert(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) # Save pytorch-model print(f"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , _UpperCAmelCase ) if __name__ == "__main__": lowerCAmelCase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--bert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained BERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) lowerCAmelCase : Optional[Any] = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
671
0
from typing import List, Optional, Union import numpy as np from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ....feature_extraction_sequence_utils import SequenceFeatureExtractor from ....feature_extraction_utils import BatchFeature from ....file_utils import PaddingStrategy, TensorType from ....utils import logging __a: List[str] = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase ): '''simple docstring''' _lowerCamelCase = ['''input_features''', '''attention_mask'''] def __init__( self : Optional[int] , lowerCamelCase : List[Any]=80 , lowerCamelCase : str=1_6000 , lowerCamelCase : List[Any]=0.0 , lowerCamelCase : Dict=10 , lowerCamelCase : Dict=25 , lowerCamelCase : str="hamming_window" , lowerCamelCase : Union[str, Any]=3_2768.0 , lowerCamelCase : Any=0.97 , lowerCamelCase : Optional[Any]=1.0 , lowerCamelCase : Tuple=True , lowerCamelCase : List[str]=True , lowerCamelCase : List[str]=False , **lowerCamelCase : int , ) -> Optional[int]: """simple docstring""" super().__init__(feature_size=lowerCamelCase , sampling_rate=lowerCamelCase , padding_value=lowerCamelCase , **lowerCamelCase ) _UpperCAmelCase = feature_size _UpperCAmelCase = sampling_rate _UpperCAmelCase = padding_value _UpperCAmelCase = hop_length _UpperCAmelCase = win_length _UpperCAmelCase = frame_signal_scale _UpperCAmelCase = preemphasis_coeff _UpperCAmelCase = mel_floor _UpperCAmelCase = normalize_means _UpperCAmelCase = normalize_vars _UpperCAmelCase = win_function _UpperCAmelCase = return_attention_mask _UpperCAmelCase = win_length * sampling_rate // 1000 _UpperCAmelCase = hop_length * sampling_rate // 1000 _UpperCAmelCase = optimal_fft_length(self.sample_size ) _UpperCAmelCase = (self.n_fft // 2) + 1 def lowerCamelCase ( self : List[Any] , lowerCamelCase : np.array ) -> np.ndarray: """simple docstring""" if self.win_function == "hamming_window": _UpperCAmelCase = window_function(window_length=self.sample_size , name=self.win_function , periodic=lowerCamelCase ) else: _UpperCAmelCase = window_function(window_length=self.sample_size , name=self.win_function ) _UpperCAmelCase = mel_filter_bank( num_frequency_bins=self.n_freqs , num_mel_filters=self.feature_size , min_frequency=0.0 , max_frequency=self.sampling_rate / 2.0 , sampling_rate=self.sampling_rate , ) _UpperCAmelCase = spectrogram( one_waveform * self.frame_signal_scale , window=lowerCamelCase , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , center=lowerCamelCase , preemphasis=self.preemphasis_coeff , mel_filters=lowerCamelCase , mel_floor=self.mel_floor , log_mel="""log""" , ) return msfc_features.T def lowerCamelCase ( self : List[str] , lowerCamelCase : Union[str, Any] , lowerCamelCase : Union[str, Any] , lowerCamelCase : Any ) -> List[str]: """simple docstring""" # make sure we normalize float32 arrays if self.normalize_means: _UpperCAmelCase = x[:input_length].mean(axis=0 ) _UpperCAmelCase = np.subtract(lowerCamelCase , lowerCamelCase ) if self.normalize_vars: _UpperCAmelCase = x[:input_length].std(axis=0 ) _UpperCAmelCase = np.divide(lowerCamelCase , lowerCamelCase ) if input_length < x.shape[0]: _UpperCAmelCase = padding_value # make sure array is in float32 _UpperCAmelCase = x.astype(np.floataa ) return x def lowerCamelCase ( self : Optional[int] , lowerCamelCase : List[np.ndarray] , lowerCamelCase : Optional[np.ndarray] = None ) -> List[np.ndarray]: """simple docstring""" _UpperCAmelCase = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [self._normalize_one(lowerCamelCase , lowerCamelCase , self.padding_value ) for x, n in zip(lowerCamelCase , lowerCamelCase )] def __call__( self : Union[str, Any] , lowerCamelCase : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , lowerCamelCase : Union[bool, str, PaddingStrategy] = False , lowerCamelCase : Optional[int] = None , lowerCamelCase : bool = False , lowerCamelCase : Optional[int] = None , lowerCamelCase : Optional[bool] = None , lowerCamelCase : Optional[Union[str, TensorType]] = None , lowerCamelCase : Optional[int] = None , **lowerCamelCase : Dict , ) -> BatchFeature: """simple docstring""" if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f"""The model corresponding to this feature extractor: {self} was trained using a sampling rate of""" f""" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with""" f""" {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( """It is strongly recommended to pass the ``sampling_rate`` argument to this function. """ """Failing to do so can result in silent errors that might be hard to debug.""" ) _UpperCAmelCase = isinstance(lowerCamelCase , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f"""Only mono-channel audio is supported for input to {self}""" ) _UpperCAmelCase = is_batched_numpy or ( isinstance(lowerCamelCase , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: _UpperCAmelCase = [np.asarray(lowerCamelCase , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(lowerCamelCase , np.ndarray ): _UpperCAmelCase = np.asarray(lowerCamelCase , dtype=np.floataa ) elif isinstance(lowerCamelCase , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): _UpperCAmelCase = raw_speech.astype(np.floataa ) # always return batch if not is_batched: _UpperCAmelCase = [raw_speech] # extract fbank features _UpperCAmelCase = [self._extract_mfsc_features(lowerCamelCase ) for one_waveform in raw_speech] # convert into correct format for padding _UpperCAmelCase = BatchFeature({"""input_features""": features} ) _UpperCAmelCase = self.pad( lowerCamelCase , padding=lowerCamelCase , max_length=lowerCamelCase , truncation=lowerCamelCase , pad_to_multiple_of=lowerCamelCase , return_attention_mask=lowerCamelCase , **lowerCamelCase , ) # make sure list is in array format _UpperCAmelCase = padded_inputs.get("""input_features""" ) if isinstance(input_features[0] , lowerCamelCase ): _UpperCAmelCase = [np.asarray(lowerCamelCase , dtype=np.floataa ) for feature in input_features] _UpperCAmelCase = padded_inputs.get("""attention_mask""" ) if attention_mask is not None: _UpperCAmelCase = [np.asarray(lowerCamelCase , dtype=np.intaa ) for array in attention_mask] if self.normalize_means or self.normalize_vars: _UpperCAmelCase = ( np.array(lowerCamelCase , dtype=np.intaa ) if self._get_padding_strategies(lowerCamelCase , max_length=lowerCamelCase ) is not PaddingStrategy.DO_NOT_PAD and padding else None ) _UpperCAmelCase = self.normalize( padded_inputs["""input_features"""] , attention_mask=lowerCamelCase ) if return_tensors is not None: _UpperCAmelCase = padded_inputs.convert_to_tensors(lowerCamelCase ) return padded_inputs
108
import math def A_ ( _UpperCAmelCase ): if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_UpperCAmelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def A_ ( _UpperCAmelCase = 0.1 ): SCREAMING_SNAKE_CASE_: Union[str, Any] = 3 SCREAMING_SNAKE_CASE_: Optional[int] = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ): primes += is_prime(_UpperCAmelCase ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
671
0
'''simple docstring''' import os import tempfile import unittest from transformers.models.marian.convert_marian_tatoeba_to_pytorch import DEFAULT_REPO, TatoebaConverter from transformers.testing_utils import slow from transformers.utils import cached_property @unittest.skipUnless(os.path.exists(_snake_case ), 'Tatoeba directory does not exist.' ) class __a ( unittest.TestCase ): @cached_property def UpperCAmelCase__ ( self : Dict ): '''simple docstring''' __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() return TatoebaConverter(save_dir=lowerCamelCase ) @slow def UpperCAmelCase__ ( self : Tuple ): '''simple docstring''' self.resolver.convert_models(["""heb-eng"""] ) @slow def UpperCAmelCase__ ( self : List[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.resolver.write_model_card("""opus-mt-he-en""" ,dry_run=lowerCamelCase ) assert mmeta["long_pair"] == "heb-eng"
109
import re def A_ ( _UpperCAmelCase ): return [char.split() for char in re.split(R"[^ a-z A-Z 0-9 \s]" , str_ )] def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: int = split_input(str_ ) return "".join( ["".join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): try: SCREAMING_SNAKE_CASE_: List[Any] = split_input(_UpperCAmelCase ) if upper: SCREAMING_SNAKE_CASE_: List[str] = "".join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: SCREAMING_SNAKE_CASE_: Optional[int] = "".join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def A_ ( _UpperCAmelCase ): return to_simple_case(_UpperCAmelCase ) def A_ ( _UpperCAmelCase ): try: SCREAMING_SNAKE_CASE_: Optional[int] = to_simple_case(_UpperCAmelCase ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def A_ ( _UpperCAmelCase , _UpperCAmelCase ): return to_complex_case(_UpperCAmelCase , _UpperCAmelCase , "_" ) def A_ ( _UpperCAmelCase , _UpperCAmelCase ): return to_complex_case(_UpperCAmelCase , _UpperCAmelCase , "-" ) if __name__ == "__main__": __import__("""doctest""").testmod()
671
0
from __future__ import annotations import inspect import unittest from math import floor import numpy as np from transformers import CvtConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFCvtForImageClassification, TFCvtModel from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowerCAmelCase_ ( UpperCAmelCase_ ): def __snake_case ( self : Tuple ): lowerCAmelCase__ = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(lowerCAmelCase__ , '''embed_dim''' ) ) self.parent.assertTrue(hasattr(lowerCAmelCase__ , '''num_heads''' ) ) class lowerCAmelCase_ : def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[str]=13 , SCREAMING_SNAKE_CASE_ : List[Any]=64 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=3 , SCREAMING_SNAKE_CASE_ : Optional[int]=[16, 48, 96] , SCREAMING_SNAKE_CASE_ : List[Any]=[1, 3, 6] , SCREAMING_SNAKE_CASE_ : Optional[Any]=[1, 2, 10] , SCREAMING_SNAKE_CASE_ : List[Any]=[7, 3, 3] , SCREAMING_SNAKE_CASE_ : Optional[Any]=[4, 2, 2] , SCREAMING_SNAKE_CASE_ : List[str]=[2, 1, 1] , SCREAMING_SNAKE_CASE_ : Optional[int]=[2, 2, 2] , SCREAMING_SNAKE_CASE_ : Tuple=[False, False, True] , SCREAMING_SNAKE_CASE_ : Union[str, Any]=[0.0, 0.0, 0.0] , SCREAMING_SNAKE_CASE_ : int=0.02 , SCREAMING_SNAKE_CASE_ : Any=1e-12 , SCREAMING_SNAKE_CASE_ : Optional[int]=True , SCREAMING_SNAKE_CASE_ : List[str]=True , SCREAMING_SNAKE_CASE_ : Union[str, Any]=2 , ): lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = image_size lowerCAmelCase__ = patch_sizes lowerCAmelCase__ = patch_stride lowerCAmelCase__ = patch_padding lowerCAmelCase__ = is_training lowerCAmelCase__ = use_labels lowerCAmelCase__ = num_labels lowerCAmelCase__ = num_channels lowerCAmelCase__ = embed_dim lowerCAmelCase__ = num_heads lowerCAmelCase__ = stride_kv lowerCAmelCase__ = depth lowerCAmelCase__ = cls_token lowerCAmelCase__ = attention_drop_rate lowerCAmelCase__ = initializer_range lowerCAmelCase__ = layer_norm_eps def __snake_case ( self : str ): lowerCAmelCase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase__ = None if self.use_labels: # create a random int32 tensor of given shape lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_labels ) lowerCAmelCase__ = self.get_config() return config, pixel_values, labels def __snake_case ( self : List[str] ): return CvtConfig( image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , ) def __snake_case ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[int] ): lowerCAmelCase__ = TFCvtModel(config=lowerCAmelCase__ ) lowerCAmelCase__ = model(lowerCAmelCase__ , training=lowerCAmelCase__ ) lowerCAmelCase__ = (self.image_size, self.image_size) lowerCAmelCase__ = image_size[0], image_size[1] for i in range(len(self.depth ) ): lowerCAmelCase__ = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) lowerCAmelCase__ = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) ) def __snake_case ( self : str , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Union[str, Any] ): lowerCAmelCase__ = self.num_labels lowerCAmelCase__ = TFCvtForImageClassification(lowerCAmelCase__ ) lowerCAmelCase__ = model(lowerCAmelCase__ , labels=lowerCAmelCase__ , training=lowerCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __snake_case ( self : List[Any] ): lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class lowerCAmelCase_ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): UpperCamelCase_ :Tuple = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else () UpperCamelCase_ :Optional[int] = ( {'''feature-extraction''': TFCvtModel, '''image-classification''': TFCvtForImageClassification} if is_tf_available() else {} ) UpperCamelCase_ :Dict = False UpperCamelCase_ :List[Any] = False UpperCamelCase_ :Union[str, Any] = False UpperCamelCase_ :int = False UpperCamelCase_ :Union[str, Any] = False def __snake_case ( self : Optional[Any] ): lowerCAmelCase__ = TFCvtModelTester(self ) lowerCAmelCase__ = TFCvtConfigTester(self , config_class=lowerCAmelCase__ , has_text_modality=lowerCAmelCase__ , hidden_size=37 ) def __snake_case ( self : Optional[int] ): self.config_tester.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() @unittest.skip(reason='''Cvt does not output attentions''' ) def __snake_case ( self : Union[str, Any] ): pass @unittest.skip(reason='''Cvt does not use inputs_embeds''' ) def __snake_case ( self : Any ): pass @unittest.skip(reason='''Cvt does not support input and output embeddings''' ) def __snake_case ( self : str ): pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('''GPU''' ) ) == 0 , reason='''TF does not support backprop for grouped convolutions on CPU.''' , ) def __snake_case ( self : List[str] ): super().test_dataset_conversion() @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('''GPU''' ) ) == 0 , reason='''TF does not support backprop for grouped convolutions on CPU.''' , ) @slow def __snake_case ( self : str ): super().test_keras_fit() @unittest.skip(reason='''Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8''' ) def __snake_case ( self : Optional[Any] ): lowerCAmelCase__ = tf.keras.mixed_precision.Policy('''mixed_float16''' ) tf.keras.mixed_precision.set_global_policy(lowerCAmelCase__ ) super().test_keras_fit() tf.keras.mixed_precision.set_global_policy('''float32''' ) def __snake_case ( self : Union[str, Any] ): lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(lowerCAmelCase__ ) lowerCAmelCase__ = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ = [*signature.parameters.keys()] lowerCAmelCase__ = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowerCAmelCase__ ) def __snake_case ( self : Dict ): def check_hidden_states_output(SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : str ): lowerCAmelCase__ = model_class(lowerCAmelCase__ ) lowerCAmelCase__ = model(**self._prepare_for_class(lowerCAmelCase__ , lowerCAmelCase__ ) ) lowerCAmelCase__ = outputs.hidden_states lowerCAmelCase__ = len(self.model_tester.depth ) self.assertEqual(len(lowerCAmelCase__ ) , lowerCAmelCase__ ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = True check_hidden_states_output(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase__ = True check_hidden_states_output(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) def __snake_case ( self : List[Any] ): lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase__ ) def __snake_case ( self : str ): lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__ ) @slow def __snake_case ( self : List[Any] ): for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ = TFCvtModel.from_pretrained(lowerCAmelCase__ ) self.assertIsNotNone(lowerCAmelCase__ ) def lowerCAmelCase_ () -> Tuple: '''simple docstring''' lowerCAmelCase__ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf @require_vision class lowerCAmelCase_ ( unittest.TestCase ): @cached_property def __snake_case ( self : Optional[int] ): return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def __snake_case ( self : List[Any] ): lowerCAmelCase__ = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) lowerCAmelCase__ = self.default_image_processor lowerCAmelCase__ = prepare_img() lowerCAmelCase__ = image_processor(images=lowerCAmelCase__ , return_tensors='''tf''' ) # forward pass lowerCAmelCase__ = model(**lowerCAmelCase__ ) # verify the logits lowerCAmelCase__ = tf.TensorShape((1, 1_000) ) self.assertEqual(outputs.logits.shape , lowerCAmelCase__ ) lowerCAmelCase__ = tf.constant([0.9_285, 0.9_015, -0.3_150] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , lowerCAmelCase__ , atol=1e-4 ) )
668
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING lowerCAmelCase : Union[str, Any] = logging.get_logger(__name__) class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : List[Any] = '''upernet''' def __init__( self : Any , lowerCAmelCase__ : Union[str, Any]=None , lowerCAmelCase__ : List[str]=512 , lowerCAmelCase__ : Any=0.02 , lowerCAmelCase__ : str=[1, 2, 3, 6] , lowerCAmelCase__ : Optional[Any]=True , lowerCAmelCase__ : Dict=0.4 , lowerCAmelCase__ : int=384 , lowerCAmelCase__ : Union[str, Any]=256 , lowerCAmelCase__ : Any=1 , lowerCAmelCase__ : Tuple=False , lowerCAmelCase__ : List[str]=255 , **lowerCAmelCase__ : List[str] , ): super().__init__(**lowerCAmelCase__) if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.") SCREAMING_SNAKE_CASE_: Dict = CONFIG_MAPPING["resnet"](out_features=["stage1", "stage2", "stage3", "stage4"]) elif isinstance(lowerCAmelCase__ , lowerCAmelCase__): SCREAMING_SNAKE_CASE_: str = backbone_config.get("model_type") SCREAMING_SNAKE_CASE_: str = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE_: Tuple = config_class.from_dict(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: str = backbone_config SCREAMING_SNAKE_CASE_: Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_: Dict = initializer_range SCREAMING_SNAKE_CASE_: Any = pool_scales SCREAMING_SNAKE_CASE_: Optional[Any] = use_auxiliary_head SCREAMING_SNAKE_CASE_: str = auxiliary_loss_weight SCREAMING_SNAKE_CASE_: List[Any] = auxiliary_in_channels SCREAMING_SNAKE_CASE_: Union[str, Any] = auxiliary_channels SCREAMING_SNAKE_CASE_: Dict = auxiliary_num_convs SCREAMING_SNAKE_CASE_: str = auxiliary_concat_input SCREAMING_SNAKE_CASE_: Dict = loss_ignore_index def _SCREAMING_SNAKE_CASE ( self : Tuple): SCREAMING_SNAKE_CASE_: Tuple = copy.deepcopy(self.__dict__) SCREAMING_SNAKE_CASE_: int = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE_: Optional[int] = self.__class__.model_type return output
671
0
import argparse from copy import deepcopy import numpy as np from datasets import ClassLabel, DatasetDict, load_dataset from evaluate import load from transformers import ( AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, Trainer, TrainerCallback, TrainingArguments, set_seed, ) def _lowerCAmelCase ( ): UpperCAmelCase_ = argparse.ArgumentParser() parser.add_argument('''--model_ckpt''' , type=_UpperCAmelCase , default='''microsoft/unixcoder-base-nine''' ) parser.add_argument('''--num_epochs''' , type=_UpperCAmelCase , default=5 ) parser.add_argument('''--batch_size''' , type=_UpperCAmelCase , default=6 ) parser.add_argument('''--gradient_accumulation_steps''' , type=_UpperCAmelCase , default=1 ) parser.add_argument('''--freeze''' , type=_UpperCAmelCase , default=_UpperCAmelCase ) parser.add_argument('''--learning_rate''' , type=_UpperCAmelCase , default=5e-4 ) parser.add_argument('''--seed''' , type=_UpperCAmelCase , default=0 ) parser.add_argument('''--lr_scheduler_type''' , type=_UpperCAmelCase , default='''cosine''' ) parser.add_argument('''--num_warmup_steps''' , type=_UpperCAmelCase , default=1_0 ) parser.add_argument('''--weight_decay''' , type=_UpperCAmelCase , default=0.0_1 ) parser.add_argument('''--output_dir''' , type=_UpperCAmelCase , default='''./results''' ) return parser.parse_args() _lowerCamelCase : Dict = load('accuracy') def _lowerCAmelCase ( __magic_name__ :Union[str, Any] ): UpperCAmelCase_ = eval_pred UpperCAmelCase_ = np.argmax(_UpperCAmelCase , axis=1 ) return metric.compute(predictions=_UpperCAmelCase , references=_UpperCAmelCase ) class snake_case__ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : List[str] , lowerCAmelCase_ : Tuple ) -> List[Any]: super().__init__() UpperCAmelCase_ = trainer def UpperCamelCase ( self : Any , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : str , lowerCAmelCase_ : Union[str, Any] , **lowerCAmelCase_ : List[Any] ) -> Any: if control.should_evaluate: UpperCAmelCase_ = deepcopy(lowerCAmelCase__ ) self._trainer.evaluate(eval_dataset=self._trainer.train_dataset , metric_key_prefix='''train''' ) return control_copy def _lowerCAmelCase ( ): UpperCAmelCase_ = get_args() set_seed(args.seed ) UpperCAmelCase_ = load_dataset('''codeparrot/codecomplex''' , split='''train''' ) UpperCAmelCase_ = dataset.train_test_split(test_size=0.2 ) UpperCAmelCase_ = train_test["test"].train_test_split(test_size=0.5 ) UpperCAmelCase_ = DatasetDict( { '''train''': train_test['''train'''], '''test''': test_validation['''train'''], '''valid''': test_validation['''test'''], } ) print('''Loading tokenizer and model''' ) UpperCAmelCase_ = AutoTokenizer.from_pretrained(args.model_ckpt ) UpperCAmelCase_ = tokenizer.eos_token UpperCAmelCase_ = AutoModelForSequenceClassification.from_pretrained(args.model_ckpt , num_labels=7 ) UpperCAmelCase_ = model.config.eos_token_id if args.freeze: for param in model.roberta.parameters(): UpperCAmelCase_ = False UpperCAmelCase_ = ClassLabel(num_classes=7 , names=list(set(train_test_validation['''train''']['''complexity'''] ) ) ) def tokenize(__magic_name__ :Optional[Any] ): UpperCAmelCase_ = tokenizer(example['''src'''] , truncation=_UpperCAmelCase , max_length=1_0_2_4 ) UpperCAmelCase_ = labels.straint(example['''complexity'''] ) return { "input_ids": inputs["input_ids"], "attention_mask": inputs["attention_mask"], "label": label, } UpperCAmelCase_ = train_test_validation.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=train_test_validation['''train'''].column_names , ) UpperCAmelCase_ = DataCollatorWithPadding(tokenizer=_UpperCAmelCase ) UpperCAmelCase_ = TrainingArguments( output_dir=args.output_dir , learning_rate=args.learning_rate , lr_scheduler_type=args.lr_scheduler_type , evaluation_strategy='''epoch''' , save_strategy='''epoch''' , logging_strategy='''epoch''' , per_device_train_batch_size=args.batch_size , per_device_eval_batch_size=args.batch_size , num_train_epochs=args.num_epochs , gradient_accumulation_steps=args.gradient_accumulation_steps , weight_decay=0.0_1 , metric_for_best_model='''accuracy''' , run_name='''complexity-java''' , report_to='''wandb''' , ) UpperCAmelCase_ = Trainer( model=_UpperCAmelCase , args=_UpperCAmelCase , train_dataset=tokenized_datasets['''train'''] , eval_dataset=tokenized_datasets['''valid'''] , tokenizer=_UpperCAmelCase , data_collator=_UpperCAmelCase , compute_metrics=_UpperCAmelCase , ) print('''Training...''' ) trainer.add_callback(CustomCallback(_UpperCAmelCase ) ) trainer.train() if __name__ == "__main__": main()
121
import pickle import unittest import torch from accelerate import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils import require_cpu @require_cpu class __lowercase ( unittest.TestCase ): """simple docstring""" def _SCREAMING_SNAKE_CASE ( self : Any): SCREAMING_SNAKE_CASE_: List[str] = torch.nn.Linear(10 , 10) SCREAMING_SNAKE_CASE_: Union[str, Any] = torch.optim.SGD(model.parameters() , 0.1) SCREAMING_SNAKE_CASE_: Any = Accelerator() SCREAMING_SNAKE_CASE_: List[str] = accelerator.prepare(lowerCAmelCase__) try: pickle.loads(pickle.dumps(lowerCAmelCase__)) except Exception as e: self.fail(F"Accelerated optimizer pickling failed with {e}") AcceleratorState._reset_state()
671
0
from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class _lowerCamelCase( UpperCAmelCase_ ): def UpperCamelCase ( self, lowerCamelCase) -> Union[str, Any]: """simple docstring""" return 0.0 def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ ) -> Union[str, Any]: _lowercase : List[str] = min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] ) _lowercase : Dict = max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ ) -> Dict: _lowercase : Optional[int] = 512 _lowercase : str = [1] + [0] * (size - 1) _lowercase : Dict = [filter_type.process(_UpperCAmelCase ) for item in inputs] _lowercase : Optional[Any] = [0] * (samplerate - size) # zero-padding outputs += filler _lowercase : Tuple = np.abs(np.fft.fft(_UpperCAmelCase ) ) _lowercase : Optional[Any] = 20 * np.logaa(_UpperCAmelCase ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel('Frequency (Hz)' ) plt.xscale('log' ) # Display within reasonable bounds _lowercase : Any = get_bounds(_UpperCAmelCase , _UpperCAmelCase ) plt.ylim(max([-80, bounds[0]] ) , min([80, bounds[1]] ) ) plt.ylabel('Gain (dB)' ) plt.plot(_UpperCAmelCase ) plt.show() def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ ) -> Union[str, Any]: _lowercase : Optional[int] = 512 _lowercase : Union[str, Any] = [1] + [0] * (size - 1) _lowercase : Dict = [filter_type.process(_UpperCAmelCase ) for item in inputs] _lowercase : int = [0] * (samplerate - size) # zero-padding outputs += filler _lowercase : Any = np.angle(np.fft.fft(_UpperCAmelCase ) ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel('Frequency (Hz)' ) plt.xscale('log' ) plt.ylim(-2 * pi , 2 * pi ) plt.ylabel('Phase shift (Radians)' ) plt.plot(np.unwrap(_UpperCAmelCase , -2 * pi ) ) plt.show()
89
from itertools import count def A_ ( _UpperCAmelCase = 50 ): SCREAMING_SNAKE_CASE_: Union[str, Any] = [1] * min_block_length for n in count(_UpperCAmelCase ): fill_count_functions.append(1 ) for block_length in range(_UpperCAmelCase , 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() = }''')
671
0
from __future__ import annotations from collections.abc import Iterator from typing import Any class lowerCAmelCase__ : def __init__( self , a ) -> Dict: '''simple docstring''' _UpperCamelCase = data _UpperCamelCase = None class lowerCAmelCase__ : def __init__( self ) -> Optional[int]: '''simple docstring''' _UpperCamelCase = None _UpperCamelCase = None def __iter__( self ) -> Optional[int]: '''simple docstring''' _UpperCamelCase = self.head while self.head: yield node.data _UpperCamelCase = node.next if node == self.head: break def __len__( self ) -> Optional[int]: '''simple docstring''' return sum(1 for _ in self ) def __repr__( self ) -> Dict: '''simple docstring''' return "->".join(str(lowerCAmelCase__ ) for item in iter(self ) ) def A_ ( self , a ) -> List[Any]: '''simple docstring''' self.insert_nth(len(self ) , lowerCAmelCase__ ) def A_ ( self , a ) -> Optional[int]: '''simple docstring''' self.insert_nth(0 , lowerCAmelCase__ ) def A_ ( self , a , a ) -> int: '''simple docstring''' if index < 0 or index > len(self ): raise IndexError("""list index out of range.""" ) _UpperCamelCase = Node(lowerCAmelCase__ ) if self.head is None: _UpperCamelCase = new_node # first node points itself _UpperCamelCase = new_node elif index == 0: # insert at head _UpperCamelCase = self.head _UpperCamelCase = new_node else: _UpperCamelCase = self.head for _ in range(index - 1 ): _UpperCamelCase = temp.next _UpperCamelCase = temp.next _UpperCamelCase = new_node if index == len(self ) - 1: # insert at tail _UpperCamelCase = new_node def A_ ( self ) -> str: '''simple docstring''' return self.delete_nth(0 ) def A_ ( self ) -> Union[str, Any]: '''simple docstring''' return self.delete_nth(len(self ) - 1 ) def A_ ( self , a = 0 ) -> int: '''simple docstring''' if not 0 <= index < len(self ): raise IndexError("""list index out of range.""" ) _UpperCamelCase = self.head if self.head == self.tail: # just one node _UpperCamelCase = None elif index == 0: # delete head node _UpperCamelCase = self.tail.next.next _UpperCamelCase = self.head.next else: _UpperCamelCase = self.head for _ in range(index - 1 ): _UpperCamelCase = temp.next _UpperCamelCase = temp.next _UpperCamelCase = temp.next.next if index == len(self ) - 1: # delete at tail _UpperCamelCase = temp return delete_node.data def A_ ( self ) -> Optional[Any]: '''simple docstring''' return len(self ) == 0 def __A() -> Dict: """simple docstring""" _UpperCamelCase = CircularLinkedList() assert len(_UpperCAmelCase ) == 0 assert circular_linked_list.is_empty() is True assert str(_UpperCAmelCase ) == "" try: circular_linked_list.delete_front() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_tail() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_nth(-1 ) raise AssertionError except IndexError: assert True try: circular_linked_list.delete_nth(0 ) raise AssertionError except IndexError: assert True assert circular_linked_list.is_empty() is True for i in range(5 ): assert len(_UpperCAmelCase ) == i circular_linked_list.insert_nth(_UpperCAmelCase , i + 1 ) assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 6 ) ) circular_linked_list.insert_tail(6 ) assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 7 ) ) circular_linked_list.insert_head(0 ) assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(0 , 7 ) ) assert circular_linked_list.delete_front() == 0 assert circular_linked_list.delete_tail() == 6 assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 6 ) ) assert circular_linked_list.delete_nth(2 ) == 3 circular_linked_list.insert_nth(2 , 3 ) assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 6 ) ) assert circular_linked_list.is_empty() is False if __name__ == "__main__": import doctest doctest.testmod()
612
def A_ ( _UpperCAmelCase ): if not isinstance(_UpperCAmelCase , _UpperCAmelCase ): raise TypeError("only integers accepted as input" ) else: SCREAMING_SNAKE_CASE_: List[Any] = str(abs(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE_: Tuple = [list(_UpperCAmelCase ) for char in range(len(_UpperCAmelCase ) )] for index in range(len(_UpperCAmelCase ) ): num_transpositions[index].pop(_UpperCAmelCase ) return max( int("".join(list(_UpperCAmelCase ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__("""doctest""").testmod()
671
0
"""simple docstring""" lowercase__ = frozenset( [ """prompt""", """height""", """width""", """guidance_scale""", """negative_prompt""", """prompt_embeds""", """negative_prompt_embeds""", """cross_attention_kwargs""", ] ) lowercase__ = frozenset(["""prompt""", """negative_prompt"""]) lowercase__ = frozenset([]) lowercase__ = frozenset(["""image"""]) lowercase__ = frozenset( [ """image""", """height""", """width""", """guidance_scale""", ] ) lowercase__ = frozenset(["""image"""]) lowercase__ = frozenset( [ """prompt""", """image""", """height""", """width""", """guidance_scale""", """negative_prompt""", """prompt_embeds""", """negative_prompt_embeds""", ] ) lowercase__ = frozenset(["""prompt""", """image""", """negative_prompt"""]) lowercase__ = frozenset( [ # Text guided image variation with an image mask """prompt""", """image""", """mask_image""", """height""", """width""", """guidance_scale""", """negative_prompt""", """prompt_embeds""", """negative_prompt_embeds""", ] ) lowercase__ = frozenset(["""prompt""", """image""", """mask_image""", """negative_prompt"""]) lowercase__ = frozenset( [ # image variation with an image mask """image""", """mask_image""", """height""", """width""", """guidance_scale""", ] ) lowercase__ = frozenset(["""image""", """mask_image"""]) lowercase__ = frozenset( [ """example_image""", """image""", """mask_image""", """height""", """width""", """guidance_scale""", ] ) lowercase__ = frozenset(["""example_image""", """image""", """mask_image"""]) lowercase__ = frozenset(["""class_labels"""]) lowercase__ = frozenset(["""class_labels"""]) lowercase__ = frozenset(["""batch_size"""]) lowercase__ = frozenset([]) lowercase__ = frozenset(["""batch_size"""]) lowercase__ = frozenset([]) lowercase__ = frozenset( [ """prompt""", """audio_length_in_s""", """guidance_scale""", """negative_prompt""", """prompt_embeds""", """negative_prompt_embeds""", """cross_attention_kwargs""", ] ) lowercase__ = frozenset(["""prompt""", """negative_prompt"""]) lowercase__ = frozenset(["""input_tokens"""]) lowercase__ = frozenset(["""input_tokens"""])
610
from __future__ import annotations from collections.abc import Iterator from typing import Any class __lowercase : """simple docstring""" def __init__( self : List[str] , lowerCAmelCase__ : Any): SCREAMING_SNAKE_CASE_: Any = data SCREAMING_SNAKE_CASE_: Node | None = None class __lowercase : """simple docstring""" def __init__( self : int): SCREAMING_SNAKE_CASE_: Dict = None SCREAMING_SNAKE_CASE_: str = None def __iter__( self : List[str]): SCREAMING_SNAKE_CASE_: Tuple = self.head while self.head: yield node.data SCREAMING_SNAKE_CASE_: List[str] = node.next if node == self.head: break def __len__( self : Dict): return sum(1 for _ in self) def __repr__( self : Dict): return "->".join(str(lowerCAmelCase__) for item in iter(self)) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase__ : Any): self.insert_nth(len(self) , lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase__ : Any): self.insert_nth(0 , lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : Any): if index < 0 or index > len(self): raise IndexError("list index out of range.") SCREAMING_SNAKE_CASE_: Any = Node(lowerCAmelCase__) if self.head is None: SCREAMING_SNAKE_CASE_: str = new_node # first node points itself SCREAMING_SNAKE_CASE_: Optional[Any] = new_node elif index == 0: # insert at head SCREAMING_SNAKE_CASE_: Optional[Any] = self.head SCREAMING_SNAKE_CASE_: str = new_node else: SCREAMING_SNAKE_CASE_: int = self.head for _ in range(index - 1): SCREAMING_SNAKE_CASE_: Optional[Any] = temp.next SCREAMING_SNAKE_CASE_: List[str] = temp.next SCREAMING_SNAKE_CASE_: int = new_node if index == len(self) - 1: # insert at tail SCREAMING_SNAKE_CASE_: Any = new_node def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): return self.delete_nth(0) def _SCREAMING_SNAKE_CASE ( self : Any): return self.delete_nth(len(self) - 1) def _SCREAMING_SNAKE_CASE ( self : Any , lowerCAmelCase__ : int = 0): if not 0 <= index < len(self): raise IndexError("list index out of range.") SCREAMING_SNAKE_CASE_: Optional[Any] = self.head if self.head == self.tail: # just one node SCREAMING_SNAKE_CASE_: List[str] = None elif index == 0: # delete head node SCREAMING_SNAKE_CASE_: int = self.tail.next.next SCREAMING_SNAKE_CASE_: Tuple = self.head.next else: SCREAMING_SNAKE_CASE_: Optional[int] = self.head for _ in range(index - 1): SCREAMING_SNAKE_CASE_: Any = temp.next SCREAMING_SNAKE_CASE_: Optional[Any] = temp.next SCREAMING_SNAKE_CASE_: int = temp.next.next if index == len(self) - 1: # delete at tail SCREAMING_SNAKE_CASE_: int = temp return delete_node.data def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): return len(self) == 0 def A_ ( ): SCREAMING_SNAKE_CASE_: Dict = CircularLinkedList() assert len(_UpperCAmelCase ) == 0 assert circular_linked_list.is_empty() is True assert str(_UpperCAmelCase ) == "" try: circular_linked_list.delete_front() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_tail() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_nth(-1 ) raise AssertionError except IndexError: assert True try: circular_linked_list.delete_nth(0 ) raise AssertionError except IndexError: assert True assert circular_linked_list.is_empty() is True for i in range(5 ): assert len(_UpperCAmelCase ) == i circular_linked_list.insert_nth(_UpperCAmelCase , i + 1 ) assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 6 ) ) circular_linked_list.insert_tail(6 ) assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 7 ) ) circular_linked_list.insert_head(0 ) assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(0 , 7 ) ) assert circular_linked_list.delete_front() == 0 assert circular_linked_list.delete_tail() == 6 assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 6 ) ) assert circular_linked_list.delete_nth(2 ) == 3 circular_linked_list.insert_nth(2 , 3 ) assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 6 ) ) assert circular_linked_list.is_empty() is False if __name__ == "__main__": import doctest doctest.testmod()
671
0
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_camembert import CamembertTokenizer else: __UpperCamelCase : Optional[Any] = None __UpperCamelCase : List[str] = logging.get_logger(__name__) __UpperCamelCase : Optional[Any] = {"""vocab_file""": """sentencepiece.bpe.model""", """tokenizer_file""": """tokenizer.json"""} __UpperCamelCase : int = { """vocab_file""": { """camembert-base""": """https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model""", }, """tokenizer_file""": { """camembert-base""": """https://huggingface.co/camembert-base/resolve/main/tokenizer.json""", }, } __UpperCamelCase : Tuple = { """camembert-base""": 512, } __UpperCamelCase : Optional[Any] = """▁""" class _UpperCamelCase ( UpperCAmelCase_ ): '''simple docstring''' a_ : Tuple = VOCAB_FILES_NAMES a_ : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP a_ : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a_ : Tuple = ['''input_ids''', '''attention_mask'''] a_ : Dict = CamembertTokenizer def __init__( self : Optional[Any] , _lowerCamelCase : str=None , _lowerCamelCase : Union[str, Any]=None , _lowerCamelCase : Dict="<s>" , _lowerCamelCase : Union[str, Any]="</s>" , _lowerCamelCase : int="</s>" , _lowerCamelCase : Any="<s>" , _lowerCamelCase : List[Any]="<unk>" , _lowerCamelCase : Any="<pad>" , _lowerCamelCase : int="<mask>" , _lowerCamelCase : int=["<s>NOTUSED", "</s>NOTUSED"] , **_lowerCamelCase : Optional[Any] , ): '''simple docstring''' __lowerCamelCase : List[Any] = AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else mask_token super().__init__( lowerCAmelCase__ , tokenizer_file=lowerCAmelCase__ , bos_token=lowerCAmelCase__ , eos_token=lowerCAmelCase__ , sep_token=lowerCAmelCase__ , cls_token=lowerCAmelCase__ , unk_token=lowerCAmelCase__ , pad_token=lowerCAmelCase__ , mask_token=lowerCAmelCase__ , additional_special_tokens=lowerCAmelCase__ , **lowerCAmelCase__ , ) __lowerCamelCase : Union[str, Any] = vocab_file __lowerCamelCase : str = False if not self.vocab_file else True def _snake_case ( self : Optional[Any] , _lowerCamelCase : List[int] , _lowerCamelCase : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __lowerCamelCase : str = [self.cls_token_id] __lowerCamelCase : str = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _snake_case ( self : Optional[int] , _lowerCamelCase : List[int] , _lowerCamelCase : Optional[List[int]] = None ): '''simple docstring''' __lowerCamelCase : Optional[Any] = [self.sep_token_id] __lowerCamelCase : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _snake_case ( self : str , _lowerCamelCase : str , _lowerCamelCase : Optional[str] = None ): '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(lowerCAmelCase__ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return __lowerCamelCase : Optional[int] = os.path.join( lowerCAmelCase__ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCAmelCase__ ): copyfile(self.vocab_file , lowerCAmelCase__ ) return (out_vocab_file,)
519
from collections import defaultdict from math import ceil, sqrt def A_ ( _UpperCAmelCase = 1_00_00_00 , _UpperCAmelCase = 10 ): SCREAMING_SNAKE_CASE_: defaultdict = defaultdict(_UpperCAmelCase ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: SCREAMING_SNAKE_CASE_: Tuple = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: SCREAMING_SNAKE_CASE_: Optional[Any] = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(_UpperCAmelCase , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(f'''{solution() = }''')
671
0
class lowerCamelCase_ : '''simple docstring''' def __init__( self : Any , _lowerCAmelCase : str = "" , _lowerCAmelCase : bool = False ): # Mapping from the first character of the prefix of the node SCREAMING_SNAKE_CASE_ = {} # A node will be a leaf if the tree contains its word SCREAMING_SNAKE_CASE_ = is_leaf SCREAMING_SNAKE_CASE_ = prefix def lowerCAmelCase_ ( self : int , _lowerCAmelCase : str ): SCREAMING_SNAKE_CASE_ = 0 for q, w in zip(self.prefix , lowerCAmelCase__ ): if q != w: break x += 1 return self.prefix[:x], self.prefix[x:], word[x:] def lowerCAmelCase_ ( self : Optional[int] , _lowerCAmelCase : list[str] ): for word in words: self.insert(lowerCAmelCase__ ) def lowerCAmelCase_ ( self : Tuple , _lowerCAmelCase : str ): # Case 1: If the word is the prefix of the node # Solution: We set the current node as leaf if self.prefix == word: SCREAMING_SNAKE_CASE_ = True # Case 2: The node has no edges that have a prefix to the word # Solution: We create an edge from the current node to a new one # containing the word elif word[0] not in self.nodes: SCREAMING_SNAKE_CASE_ = RadixNode(prefix=lowerCAmelCase__ , is_leaf=lowerCAmelCase__ ) else: SCREAMING_SNAKE_CASE_ = self.nodes[word[0]] SCREAMING_SNAKE_CASE_ = incoming_node.match( lowerCAmelCase__ ) # Case 3: The node prefix is equal to the matching # Solution: We insert remaining word on the next node if remaining_prefix == "": self.nodes[matching_string[0]].insert(lowerCAmelCase__ ) # Case 4: The word is greater equal to the matching # Solution: Create a node in between both nodes, change # prefixes and add the new node for the remaining word else: SCREAMING_SNAKE_CASE_ = remaining_prefix SCREAMING_SNAKE_CASE_ = self.nodes[matching_string[0]] SCREAMING_SNAKE_CASE_ = RadixNode(lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = aux_node if remaining_word == "": SCREAMING_SNAKE_CASE_ = True else: self.nodes[matching_string[0]].insert(lowerCAmelCase__ ) def lowerCAmelCase_ ( self : Union[str, Any] , _lowerCAmelCase : str ): SCREAMING_SNAKE_CASE_ = self.nodes.get(word[0] , lowerCAmelCase__ ) if not incoming_node: return False else: SCREAMING_SNAKE_CASE_ = incoming_node.match( lowerCAmelCase__ ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # This applies when the word and the prefix are equal elif remaining_word == "": return incoming_node.is_leaf # We have word remaining so we check the next node else: return incoming_node.find(lowerCAmelCase__ ) def lowerCAmelCase_ ( self : str , _lowerCAmelCase : str ): SCREAMING_SNAKE_CASE_ = self.nodes.get(word[0] , lowerCAmelCase__ ) if not incoming_node: return False else: SCREAMING_SNAKE_CASE_ = incoming_node.match( lowerCAmelCase__ ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # We have word remaining so we check the next node elif remaining_word != "": return incoming_node.delete(lowerCAmelCase__ ) else: # If it is not a leaf, we don't have to delete if not incoming_node.is_leaf: return False else: # We delete the nodes if no edges go from it if len(incoming_node.nodes ) == 0: del self.nodes[word[0]] # We merge the current node with its only child if len(self.nodes ) == 1 and not self.is_leaf: SCREAMING_SNAKE_CASE_ = list(self.nodes.values() )[0] SCREAMING_SNAKE_CASE_ = merging_node.is_leaf self.prefix += merging_node.prefix SCREAMING_SNAKE_CASE_ = merging_node.nodes # If there is more than 1 edge, we just mark it as non-leaf elif len(incoming_node.nodes ) > 1: SCREAMING_SNAKE_CASE_ = False # If there is 1 edge, we merge it with its child else: SCREAMING_SNAKE_CASE_ = list(incoming_node.nodes.values() )[0] SCREAMING_SNAKE_CASE_ = merging_node.is_leaf incoming_node.prefix += merging_node.prefix SCREAMING_SNAKE_CASE_ = merging_node.nodes return True def lowerCAmelCase_ ( self : Union[str, Any] , _lowerCAmelCase : int = 0 ): if self.prefix != "": print('-' * height , self.prefix , ' (leaf)' if self.is_leaf else '' ) for value in self.nodes.values(): value.print_tree(height + 1 ) def UpperCAmelCase_ ( ) -> Tuple: SCREAMING_SNAKE_CASE_ = "banana bananas bandana band apple all beast".split() SCREAMING_SNAKE_CASE_ = RadixNode() root.insert_many(_UpperCAmelCase ) assert all(root.find(_UpperCAmelCase ) for word in words ) assert not root.find('bandanas' ) assert not root.find('apps' ) root.delete('all' ) assert not root.find('all' ) root.delete('banana' ) assert not root.find('banana' ) assert root.find('bananas' ) return True def UpperCAmelCase_ ( ) -> int: assert test_trie() def UpperCAmelCase_ ( ) -> Any: SCREAMING_SNAKE_CASE_ = RadixNode() SCREAMING_SNAKE_CASE_ = "banana bananas bandanas bandana band apple all beast".split() root.insert_many(_UpperCAmelCase ) print('Words:' , _UpperCAmelCase ) print('Tree:' ) root.print_tree() if __name__ == "__main__": main()
31
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCAmelCase : str = { """configuration_xlm""": ["""XLM_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLMConfig""", """XLMOnnxConfig"""], """tokenization_xlm""": ["""XLMTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : Dict = [ """XLM_PRETRAINED_MODEL_ARCHIVE_LIST""", """XLMForMultipleChoice""", """XLMForQuestionAnswering""", """XLMForQuestionAnsweringSimple""", """XLMForSequenceClassification""", """XLMForTokenClassification""", """XLMModel""", """XLMPreTrainedModel""", """XLMWithLMHeadModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : List[str] = [ """TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFXLMForMultipleChoice""", """TFXLMForQuestionAnsweringSimple""", """TFXLMForSequenceClassification""", """TFXLMForTokenClassification""", """TFXLMMainLayer""", """TFXLMModel""", """TFXLMPreTrainedModel""", """TFXLMWithLMHeadModel""", ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys lowerCAmelCase : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
671
0
"""simple docstring""" def snake_case__ ( _lowerCamelCase ) ->Any: """simple docstring""" if isinstance(_UpperCAmelCase, _UpperCAmelCase ): raise TypeError("'float' object cannot be interpreted as an integer" ) if isinstance(_UpperCAmelCase, _UpperCAmelCase ): raise TypeError("'str' object cannot be interpreted as an integer" ) if num == 0: return "0b0" __lowercase : Dict = False if num < 0: __lowercase : Union[str, Any] = True __lowercase : str = -num __lowercase : list[int] = [] while num > 0: binary.insert(0, num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(_UpperCAmelCase ) for e in binary ) return "0b" + "".join(str(_UpperCAmelCase ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
575
lowerCAmelCase : List[str] = { """A""": ["""B""", """C""", """E"""], """B""": ["""A""", """D""", """E"""], """C""": ["""A""", """F""", """G"""], """D""": ["""B"""], """E""": ["""A""", """B""", """D"""], """F""": ["""C"""], """G""": ["""C"""], } def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Any = set() # keep track of all the paths to be checked SCREAMING_SNAKE_CASE_: Tuple = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue SCREAMING_SNAKE_CASE_: List[Any] = queue.pop(0 ) # get the last node from the path SCREAMING_SNAKE_CASE_: Tuple = path[-1] if node not in explored: SCREAMING_SNAKE_CASE_: Union[str, Any] = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: SCREAMING_SNAKE_CASE_: int = list(_UpperCAmelCase ) new_path.append(_UpperCAmelCase ) queue.append(_UpperCAmelCase ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(_UpperCAmelCase ) # in case there's no path between the 2 nodes return [] def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 SCREAMING_SNAKE_CASE_: List[Any] = [start] SCREAMING_SNAKE_CASE_: List[str] = set(_UpperCAmelCase ) # Keep tab on distances from `start` node. SCREAMING_SNAKE_CASE_: Union[str, Any] = {start: 0, target: -1} while queue: SCREAMING_SNAKE_CASE_: Dict = queue.pop(0 ) if node == target: SCREAMING_SNAKE_CASE_: Tuple = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(_UpperCAmelCase ) queue.append(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, """G""", """D""")) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, """G""", """D""")) # returns 4
671
0
'''simple docstring''' from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor _a : Optional[int] = transforms.Compose( [ transforms.Resize((256, 256)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def _lowercase ( lowerCamelCase__ ) -> str: """simple docstring""" if isinstance(_UpperCAmelCase , torch.Tensor ): return image elif isinstance(_UpperCAmelCase , PIL.Image.Image ): __UpperCAmelCase : Union[str, Any] = [image] __UpperCAmelCase : str = [trans(img.convert("RGB" ) ) for img in image] __UpperCAmelCase : Dict = torch.stack(_UpperCAmelCase ) return image class __A (UpperCAmelCase_ ): def __init__( self , UpperCamelCase_ , UpperCamelCase_ ): super().__init__() # make sure scheduler can always be converted to DDIM __UpperCAmelCase : Any = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=lowerCAmelCase__ , scheduler=lowerCAmelCase__ ) def _snake_case ( self , UpperCamelCase_ ): if strength < 0 or strength > 1: raise ValueError(f"""The value of strength should in [0.0, 1.0] but is {strength}""" ) def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): # get the original timestep using init_timestep __UpperCAmelCase : Optional[Any] = min(int(num_inference_steps * strength ) , lowerCAmelCase__ ) __UpperCAmelCase : Union[str, Any] = max(num_inference_steps - init_timestep , 0 ) __UpperCAmelCase : Optional[int] = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_=None ): if not isinstance(lowerCAmelCase__ , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( f"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(lowerCAmelCase__ )}""" ) __UpperCAmelCase : List[str] = image.to(device=lowerCAmelCase__ , dtype=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and len(lowerCAmelCase__ ) != batch_size: raise ValueError( f"""You have passed a list of generators of length {len(lowerCAmelCase__ )}, but requested an effective batch""" f""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) __UpperCAmelCase : str = init_latents.shape __UpperCAmelCase : List[Any] = randn_tensor(lowerCAmelCase__ , generator=lowerCAmelCase__ , device=lowerCAmelCase__ , dtype=lowerCAmelCase__ ) # get latents print("add noise to latents at timestep" , lowerCAmelCase__ ) __UpperCAmelCase : Union[str, Any] = self.scheduler.add_noise(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) __UpperCAmelCase : Dict = init_latents return latents @torch.no_grad() def __call__( self , UpperCamelCase_ = None , UpperCamelCase_ = 0.8 , UpperCamelCase_ = 1 , UpperCamelCase_ = None , UpperCamelCase_ = 0.0 , UpperCamelCase_ = 50 , UpperCamelCase_ = None , UpperCamelCase_ = "pil" , UpperCamelCase_ = True , ): self.check_inputs(lowerCAmelCase__ ) # 2. Preprocess image __UpperCAmelCase : Union[str, Any] = preprocess(lowerCAmelCase__ ) # 3. set timesteps self.scheduler.set_timesteps(lowerCAmelCase__ , device=self.device ) __UpperCAmelCase : Union[str, Any] = self.get_timesteps(lowerCAmelCase__ , lowerCAmelCase__ , self.device ) __UpperCAmelCase : Optional[int] = timesteps[:1].repeat(lowerCAmelCase__ ) # 4. Prepare latent variables __UpperCAmelCase : str = self.prepare_latents(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , self.unet.dtype , self.device , lowerCAmelCase__ ) __UpperCAmelCase : Optional[Any] = latents # 5. Denoising loop for t in self.progress_bar(lowerCAmelCase__ ): # 1. predict noise model_output __UpperCAmelCase : Union[str, Any] = self.unet(lowerCAmelCase__ , lowerCAmelCase__ ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 __UpperCAmelCase : int = self.scheduler.step( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , eta=lowerCAmelCase__ , use_clipped_model_output=lowerCAmelCase__ , generator=lowerCAmelCase__ , ).prev_sample __UpperCAmelCase : Optional[int] = (image / 2 + 0.5).clamp(0 , 1 ) __UpperCAmelCase : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __UpperCAmelCase : List[Any] = self.numpy_to_pil(lowerCAmelCase__ ) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=lowerCAmelCase__ )
168
from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class __lowercase ( UpperCAmelCase_ ): """simple docstring""" def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowerCAmelCase__ : float): return 0.0 def A_ ( _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: List[str] = min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] ) SCREAMING_SNAKE_CASE_: Dict = max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def A_ ( _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[int] = 5_12 SCREAMING_SNAKE_CASE_: str = [1] + [0] * (size - 1) SCREAMING_SNAKE_CASE_: Dict = [filter_type.process(_UpperCAmelCase ) for item in inputs] SCREAMING_SNAKE_CASE_: Optional[Any] = [0] * (samplerate - size) # zero-padding outputs += filler SCREAMING_SNAKE_CASE_: Tuple = np.abs(np.fft.fft(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE_: Optional[Any] = 20 * np.logaa(_UpperCAmelCase ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel("Frequency (Hz)" ) plt.xscale("log" ) # Display within reasonable bounds SCREAMING_SNAKE_CASE_: Any = get_bounds(_UpperCAmelCase , _UpperCAmelCase ) plt.ylim(max([-80, bounds[0]] ) , min([80, bounds[1]] ) ) plt.ylabel("Gain (dB)" ) plt.plot(_UpperCAmelCase ) plt.show() def A_ ( _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[int] = 5_12 SCREAMING_SNAKE_CASE_: Union[str, Any] = [1] + [0] * (size - 1) SCREAMING_SNAKE_CASE_: Dict = [filter_type.process(_UpperCAmelCase ) for item in inputs] SCREAMING_SNAKE_CASE_: int = [0] * (samplerate - size) # zero-padding outputs += filler SCREAMING_SNAKE_CASE_: Any = np.angle(np.fft.fft(_UpperCAmelCase ) ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel("Frequency (Hz)" ) plt.xscale("log" ) plt.ylim(-2 * pi , 2 * pi ) plt.ylabel("Phase shift (Radians)" ) plt.plot(np.unwrap(_UpperCAmelCase , -2 * pi ) ) plt.show()
671
0
import warnings warnings.warn( 'memory_utils has been reorganized to utils.memory. Import `find_executable_batchsize` from the main `__init__`: ' '`from accelerate import find_executable_batch_size` to avoid this warning.', FutureWarning, )
417
from __future__ import annotations from math import ceil, floor, sqrt def A_ ( _UpperCAmelCase = 2_00_00_00 ): SCREAMING_SNAKE_CASE_: list[int] = [0] SCREAMING_SNAKE_CASE_: int for idx in range(1 , ceil(sqrt(target * 2 ) * 1.1 ) ): triangle_numbers.append(triangle_numbers[-1] + idx ) # we want this to be as close as possible to target SCREAMING_SNAKE_CASE_: int = 0 # the area corresponding to the grid that gives the product closest to target SCREAMING_SNAKE_CASE_: int = 0 # an estimate of b, using the quadratic formula SCREAMING_SNAKE_CASE_: float # the largest integer less than b_estimate SCREAMING_SNAKE_CASE_: int # the largest integer less than b_estimate SCREAMING_SNAKE_CASE_: int # the triangle number corresponding to b_floor SCREAMING_SNAKE_CASE_: int # the triangle number corresponding to b_ceil SCREAMING_SNAKE_CASE_: int for idx_a, triangle_a in enumerate(triangle_numbers[1:] , 1 ): SCREAMING_SNAKE_CASE_: List[Any] = (-1 + sqrt(1 + 8 * target / triangle_a )) / 2 SCREAMING_SNAKE_CASE_: Any = floor(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] = ceil(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Any = triangle_numbers[b_floor] SCREAMING_SNAKE_CASE_: List[Any] = triangle_numbers[b_ceil] if abs(target - triangle_b_first_guess * triangle_a ) < abs( target - best_product ): SCREAMING_SNAKE_CASE_: int = triangle_b_first_guess * triangle_a SCREAMING_SNAKE_CASE_: int = idx_a * b_floor if abs(target - triangle_b_second_guess * triangle_a ) < abs( target - best_product ): SCREAMING_SNAKE_CASE_: Optional[Any] = triangle_b_second_guess * triangle_a SCREAMING_SNAKE_CASE_: Tuple = idx_a * b_ceil return area if __name__ == "__main__": print(f'''{solution() = }''')
671
0
"""simple docstring""" import argparse import gdown import numpy as np import torch from huggingface_hub import hf_hub_download from transformers import ( CLIPTokenizer, CLIPTokenizerFast, VideoMAEImageProcessor, XCLIPConfig, XCLIPModel, XCLIPProcessor, XCLIPTextConfig, XCLIPVisionConfig, ) def lowercase_ ( _lowerCamelCase: List[Any] , _lowerCamelCase: List[Any] ) -> Tuple: '''simple docstring''' __lowerCamelCase : Optional[Any] = XCLIPTextConfig() # derive patch size from model name __lowerCamelCase : Optional[Any] = model_name.find("patch" ) __lowerCamelCase : int = int(model_name[start_idx + len("patch" ) : start_idx + len("patch" ) + 2] ) __lowerCamelCase : List[Any] = XCLIPVisionConfig(patch_size=_UpperCAmelCase , num_frames=_UpperCAmelCase ) if "large" in model_name: __lowerCamelCase : str = 768 __lowerCamelCase : List[str] = 3072 __lowerCamelCase : int = 12 __lowerCamelCase : int = 1024 __lowerCamelCase : int = 4096 __lowerCamelCase : Any = 16 __lowerCamelCase : Tuple = 24 __lowerCamelCase : Any = 768 __lowerCamelCase : Optional[int] = 3072 if model_name == "xclip-large-patch14-16-frames": __lowerCamelCase : Any = 336 __lowerCamelCase : str = XCLIPConfig.from_text_vision_configs(_UpperCAmelCase , _UpperCAmelCase ) if "large" in model_name: __lowerCamelCase : Dict = 768 return config def lowercase_ ( _lowerCamelCase: int ) -> int: '''simple docstring''' if name == "token_embedding.weight": __lowerCamelCase : Any = name.replace("token_embedding.weight" , "text_model.embeddings.token_embedding.weight" ) if name == "positional_embedding": __lowerCamelCase : Any = name.replace("positional_embedding" , "text_model.embeddings.position_embedding.weight" ) if "ln_1" in name: __lowerCamelCase : Optional[Any] = name.replace("ln_1" , "layer_norm1" ) if "ln_2" in name: __lowerCamelCase : Any = name.replace("ln_2" , "layer_norm2" ) if "c_fc" in name: __lowerCamelCase : Tuple = name.replace("c_fc" , "fc1" ) if "c_proj" in name: __lowerCamelCase : Tuple = name.replace("c_proj" , "fc2" ) if name.startswith("transformer.resblocks" ): __lowerCamelCase : Optional[int] = name.replace("transformer.resblocks" , "text_model.encoder.layers" ) if "attn.out_proj" in name and "message" not in name: __lowerCamelCase : Optional[int] = name.replace("attn.out_proj" , "self_attn.out_proj" ) if "ln_final" in name: __lowerCamelCase : Any = name.replace("ln_final" , "text_model.final_layer_norm" ) # visual encoder if name == "visual.class_embedding": __lowerCamelCase : str = name.replace("visual.class_embedding" , "vision_model.embeddings.class_embedding" ) if name == "visual.positional_embedding": __lowerCamelCase : Dict = name.replace("visual.positional_embedding" , "vision_model.embeddings.position_embedding.weight" ) if name.startswith("visual.transformer.resblocks" ): __lowerCamelCase : int = name.replace("visual.transformer.resblocks" , "vision_model.encoder.layers" ) if "visual.conv1" in name: __lowerCamelCase : Any = name.replace("visual.conv1" , "vision_model.embeddings.patch_embedding" ) if "visual.ln_pre" in name: __lowerCamelCase : Union[str, Any] = name.replace("visual.ln_pre" , "vision_model.pre_layernorm" ) if "visual.ln_post" in name: __lowerCamelCase : Dict = name.replace("visual.ln_post" , "vision_model.post_layernorm" ) if "visual.proj" in name: __lowerCamelCase : Any = name.replace("visual.proj" , "visual_projection.weight" ) if "text_projection" in name: __lowerCamelCase : Any = name.replace("text_projection" , "text_projection.weight" ) # things on top if "prompts_visual_proj" in name: __lowerCamelCase : Any = name.replace("prompts_visual_proj" , "prompts_visual_projection" ) if "prompts_visual_ln" in name: __lowerCamelCase : Optional[int] = name.replace("prompts_visual_ln" , "prompts_visual_layernorm" ) # mit if name == "mit.positional_embedding": __lowerCamelCase : Optional[int] = name.replace("positional" , "position" ) if name.startswith("mit.resblocks" ): __lowerCamelCase : Union[str, Any] = name.replace("mit.resblocks" , "mit.encoder.layers" ) # prompts generator if name.startswith("prompts_generator.norm" ): __lowerCamelCase : str = name.replace("prompts_generator.norm" , "prompts_generator.layernorm" ) return name def lowercase_ ( _lowerCamelCase: int , _lowerCamelCase: Optional[int] ) -> int: '''simple docstring''' for key in orig_state_dict.copy().keys(): __lowerCamelCase : str = orig_state_dict.pop(_UpperCAmelCase ) if "attn.in_proj" in key: __lowerCamelCase : Optional[int] = key.split("." ) if key.startswith("visual" ): __lowerCamelCase : Tuple = key_split[3] __lowerCamelCase : Optional[Any] = config.vision_config.hidden_size if "message_attn" in key: if "weight" in key: __lowerCamelCase : Tuple = val[ :dim, : ] __lowerCamelCase : Dict = val[ dim : dim * 2, : ] __lowerCamelCase : int = val[ -dim:, : ] else: __lowerCamelCase : List[str] = val[ :dim ] __lowerCamelCase : str = val[ dim : dim * 2 ] __lowerCamelCase : int = val[ -dim: ] else: if "weight" in key: __lowerCamelCase : str = val[ :dim, : ] __lowerCamelCase : Optional[Any] = val[ dim : dim * 2, : ] __lowerCamelCase : List[str] = val[ -dim:, : ] else: __lowerCamelCase : Tuple = val[:dim] __lowerCamelCase : Union[str, Any] = val[ dim : dim * 2 ] __lowerCamelCase : Tuple = val[-dim:] elif key.startswith("mit" ): __lowerCamelCase : int = key_split[2] __lowerCamelCase : List[Any] = config.vision_config.mit_hidden_size if "weight" in key: __lowerCamelCase : int = val[:dim, :] __lowerCamelCase : List[str] = val[dim : dim * 2, :] __lowerCamelCase : Dict = val[-dim:, :] else: __lowerCamelCase : List[str] = val[:dim] __lowerCamelCase : List[str] = val[dim : dim * 2] __lowerCamelCase : int = val[-dim:] else: __lowerCamelCase : Tuple = key_split[2] __lowerCamelCase : List[str] = config.text_config.hidden_size if "weight" in key: __lowerCamelCase : Tuple = val[:dim, :] __lowerCamelCase : List[Any] = val[ dim : dim * 2, : ] __lowerCamelCase : List[Any] = val[-dim:, :] else: __lowerCamelCase : Tuple = val[:dim] __lowerCamelCase : int = val[ dim : dim * 2 ] __lowerCamelCase : Optional[int] = val[-dim:] else: __lowerCamelCase : str = rename_key(_UpperCAmelCase ) if new_key_name in ["visual_projection.weight", "text_projection.weight"]: __lowerCamelCase : Union[str, Any] = val.T __lowerCamelCase : List[Any] = val return orig_state_dict def lowercase_ ( _lowerCamelCase: Optional[int] ) -> Tuple: '''simple docstring''' if num_frames == 8: __lowerCamelCase : Union[str, Any] = "eating_spaghetti_8_frames.npy" elif num_frames == 16: __lowerCamelCase : Union[str, Any] = "eating_spaghetti.npy" elif num_frames == 32: __lowerCamelCase : str = "eating_spaghetti_32_frames.npy" __lowerCamelCase : Union[str, Any] = hf_hub_download( repo_id="hf-internal-testing/spaghetti-video" , filename=_UpperCAmelCase , repo_type="dataset" , ) __lowerCamelCase : Any = np.load(_UpperCAmelCase ) return list(_UpperCAmelCase ) def lowercase_ ( _lowerCamelCase: List[Any] , _lowerCamelCase: Union[str, Any]=None , _lowerCamelCase: List[Any]=False ) -> Tuple: '''simple docstring''' __lowerCamelCase : Optional[Any] = { # fully supervised kinetics-400 checkpoints "xclip-base-patch32": "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_8.pth", "xclip-base-patch32-16-frames": ( "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_16.pth" ), "xclip-base-patch16": "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_8.pth", "xclip-base-patch16-16-frames": ( "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_16.pth" ), "xclip-large-patch14": "https://drive.google.com/u/0/uc?id=1NUOImq0o5DlQTST17iIP3vG7DgmHQuCx&amp;export=download&amp;confirm=t&amp;uuid=b26caedc-88e2-473e-830a-9d158b653cdb", "xclip-large-patch14-16-frames": "https://drive.google.com/u/0/uc?id=1FOYgnJc097OJ4lGwtRCCydQyVPJEOH7d&amp;export=download&amp;confirm=t&amp;uuid=538fa810-e671-4050-b385-9a623f89804f", # fully supervised kinetics-600 checkpoints "xclip-base-patch16-kinetics-600": ( "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_8.pth" ), "xclip-base-patch16-kinetics-600-16-frames": ( "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_16.pth" ), "xclip-large-patch14-kinetics-600": "https://drive.google.com/u/0/uc?id=1FV8C1INuM91sLAN4ImjzePLIlpMSihwV&amp;export=download&amp;confirm=t&amp;uuid=141d4977-4a65-44ae-864f-4b0c19f838be", # few shot "xclip-base-patch16-hmdb-2-shot": ( "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_2.pth" ), "xclip-base-patch16-hmdb-4-shot": ( "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_4.pth" ), "xclip-base-patch16-hmdb-8-shot": ( "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_8.pth" ), "xclip-base-patch16-hmdb-16-shot": ( "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_16.pth" ), "xclip-base-patch16-ucf-2-shot": ( "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_2.pth" ), "xclip-base-patch16-ucf-4-shot": ( "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_4.pth" ), "xclip-base-patch16-ucf-8-shot": ( "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_8.pth" ), "xclip-base-patch16-ucf-16-shot": ( "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_16.pth" ), # zero shot "xclip-base-patch16-zero-shot": "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/zero.pth", } __lowerCamelCase : Tuple = model_to_url[model_name] __lowerCamelCase : Optional[Any] = 8 if "16-frames" in model_name: __lowerCamelCase : str = 16 elif "shot" in model_name: __lowerCamelCase : Any = 32 __lowerCamelCase : Any = get_xclip_config(_UpperCAmelCase , _UpperCAmelCase ) __lowerCamelCase : Any = XCLIPModel(_UpperCAmelCase ) model.eval() if "drive" in checkpoint_url: __lowerCamelCase : Dict = "pytorch_model.bin" gdown.cached_download(_UpperCAmelCase , _UpperCAmelCase , quiet=_UpperCAmelCase ) __lowerCamelCase : Union[str, Any] = torch.load(_UpperCAmelCase , map_location="cpu" )["model"] else: __lowerCamelCase : Any = torch.hub.load_state_dict_from_url(_UpperCAmelCase )["model"] __lowerCamelCase : Union[str, Any] = convert_state_dict(_UpperCAmelCase , _UpperCAmelCase ) __lowerCamelCase : Optional[Any] = XCLIPModel(_UpperCAmelCase ) __lowerCamelCase : Dict = model.load_state_dict(_UpperCAmelCase , strict=_UpperCAmelCase ) assert missing_keys == ["text_model.embeddings.position_ids", "vision_model.embeddings.position_ids"] model.eval() __lowerCamelCase : Dict = 336 if model_name == "xclip-large-patch14-16-frames" else 224 __lowerCamelCase : List[Any] = VideoMAEImageProcessor(size=_UpperCAmelCase ) __lowerCamelCase : Any = CLIPTokenizer.from_pretrained("openai/clip-vit-base-patch32" ) __lowerCamelCase : int = CLIPTokenizerFast.from_pretrained("openai/clip-vit-base-patch32" ) __lowerCamelCase : str = XCLIPProcessor(image_processor=_UpperCAmelCase , tokenizer=_UpperCAmelCase ) __lowerCamelCase : List[Any] = prepare_video(_UpperCAmelCase ) __lowerCamelCase : Optional[Any] = processor( text=["playing sports", "eating spaghetti", "go shopping"] , videos=_UpperCAmelCase , return_tensors="pt" , padding=_UpperCAmelCase ) print("Shape of pixel values:" , inputs.pixel_values.shape ) with torch.no_grad(): __lowerCamelCase : Optional[int] = model(**_UpperCAmelCase ) # Verify outputs __lowerCamelCase : Tuple = outputs.logits_per_video __lowerCamelCase : str = logits_per_video.softmax(dim=1 ) print("Probs:" , _UpperCAmelCase ) # kinetics-400 if model_name == "xclip-base-patch32": __lowerCamelCase : str = torch.tensor([[0.0019, 0.9951, 0.0030]] ) elif model_name == "xclip-base-patch32-16-frames": __lowerCamelCase : Optional[Any] = torch.tensor([[7.09_99E-04, 9.98_83E-01, 4.55_80E-04]] ) elif model_name == "xclip-base-patch16": __lowerCamelCase : List[Any] = torch.tensor([[0.0083, 0.9681, 0.0236]] ) elif model_name == "xclip-base-patch16-16-frames": __lowerCamelCase : int = torch.tensor([[7.69_37E-04, 9.97_28E-01, 1.94_73E-03]] ) elif model_name == "xclip-large-patch14": __lowerCamelCase : str = torch.tensor([[0.0062, 0.9864, 0.0075]] ) elif model_name == "xclip-large-patch14-16-frames": __lowerCamelCase : Tuple = torch.tensor([[3.38_77E-04, 9.99_37E-01, 2.88_88E-04]] ) # kinetics-600 elif model_name == "xclip-base-patch16-kinetics-600": __lowerCamelCase : str = torch.tensor([[0.0555, 0.8914, 0.0531]] ) elif model_name == "xclip-base-patch16-kinetics-600-16-frames": __lowerCamelCase : Dict = torch.tensor([[3.85_54E-04, 9.99_29E-01, 3.27_54E-04]] ) elif model_name == "xclip-large-patch14-kinetics-600": __lowerCamelCase : str = torch.tensor([[0.0036, 0.9920, 0.0045]] ) # few shot elif model_name == "xclip-base-patch16-hmdb-2-shot": __lowerCamelCase : Dict = torch.tensor([[7.18_90E-06, 9.99_94E-01, 5.65_59E-05]] ) elif model_name == "xclip-base-patch16-hmdb-4-shot": __lowerCamelCase : Optional[int] = torch.tensor([[1.03_20E-05, 9.99_93E-01, 6.24_35E-05]] ) elif model_name == "xclip-base-patch16-hmdb-8-shot": __lowerCamelCase : Any = torch.tensor([[4.13_77E-06, 9.99_90E-01, 9.83_86E-05]] ) elif model_name == "xclip-base-patch16-hmdb-16-shot": __lowerCamelCase : Optional[Any] = torch.tensor([[4.13_47E-05, 9.99_62E-01, 3.34_11E-04]] ) elif model_name == "xclip-base-patch16-ucf-2-shot": __lowerCamelCase : List[str] = torch.tensor([[8.58_57E-05, 9.99_28E-01, 6.32_91E-04]] ) elif model_name == "xclip-base-patch16-ucf-4-shot": __lowerCamelCase : Any = torch.tensor([[8.58_57E-05, 9.99_28E-01, 6.32_91E-04]] ) elif model_name == "xclip-base-patch16-ucf-8-shot": __lowerCamelCase : Dict = torch.tensor([[0.0027, 0.9904, 0.0070]] ) elif model_name == "xclip-base-patch16-ucf-16-shot": __lowerCamelCase : Optional[int] = torch.tensor([[9.82_19E-04, 9.95_93E-01, 3.08_63E-03]] ) # zero shot elif model_name == "xclip-base-patch16-zero-shot": __lowerCamelCase : List[Any] = torch.tensor([[3.50_82E-04, 9.97_85E-01, 1.79_66E-03]] ) else: raise ValueError(F"""Model name {model_name} not supported""" ) assert torch.allclose(_UpperCAmelCase , _UpperCAmelCase , atol=1E-3 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: print(F"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_UpperCAmelCase ) if push_to_hub: print("Pushing model, processor and slow tokenizer files to the hub..." ) model.push_to_hub(_UpperCAmelCase , organization="nielsr" ) processor.push_to_hub(_UpperCAmelCase , organization="nielsr" ) slow_tokenizer.push_to_hub(_UpperCAmelCase , organization="nielsr" ) if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''xclip-base-patch32''', type=str, help='''Name of the model.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.''' ) __A = parser.parse_args() convert_xclip_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
646
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase : Optional[int] = { """configuration_longformer""": [ """LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LongformerConfig""", """LongformerOnnxConfig""", ], """tokenization_longformer""": ["""LongformerTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : List[str] = ["""LongformerTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : Union[str, Any] = [ """LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """LongformerForMaskedLM""", """LongformerForMultipleChoice""", """LongformerForQuestionAnswering""", """LongformerForSequenceClassification""", """LongformerForTokenClassification""", """LongformerModel""", """LongformerPreTrainedModel""", """LongformerSelfAttention""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : int = [ """TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFLongformerForMaskedLM""", """TFLongformerForMultipleChoice""", """TFLongformerForQuestionAnswering""", """TFLongformerForSequenceClassification""", """TFLongformerForTokenClassification""", """TFLongformerModel""", """TFLongformerPreTrainedModel""", """TFLongformerSelfAttention""", ] if TYPE_CHECKING: from .configuration_longformer import ( LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, LongformerConfig, LongformerOnnxConfig, ) from .tokenization_longformer import LongformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_longformer_fast import LongformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longformer import ( LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, LongformerForMaskedLM, LongformerForMultipleChoice, LongformerForQuestionAnswering, LongformerForSequenceClassification, LongformerForTokenClassification, LongformerModel, LongformerPreTrainedModel, LongformerSelfAttention, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_longformer import ( TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFLongformerForMaskedLM, TFLongformerForMultipleChoice, TFLongformerForQuestionAnswering, TFLongformerForSequenceClassification, TFLongformerForTokenClassification, TFLongformerModel, TFLongformerPreTrainedModel, TFLongformerSelfAttention, ) else: import sys lowerCAmelCase : Optional[int] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
671
0
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class lowerCAmelCase_ ( UpperCAmelCase_ ): UpperCamelCase_ :Dict = ( '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.''' '''It takes two arguments named `image` which should be the original image, and `label` which should be a text ''' '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.''' ) UpperCamelCase_ :int = '''CIDAS/clipseg-rd64-refined''' UpperCamelCase_ :Any = '''image_segmenter''' UpperCamelCase_ :Union[str, Any] = CLIPSegForImageSegmentation UpperCamelCase_ :List[str] = ['''image''', '''text'''] UpperCamelCase_ :Any = ['''image'''] def __init__( self : Any , *SCREAMING_SNAKE_CASE_ : Tuple , **SCREAMING_SNAKE_CASE_ : Optional[Any] ): requires_backends(self , ['''vision'''] ) super().__init__(*lowerCAmelCase__ , **lowerCAmelCase__ ) def __snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : "Image" , SCREAMING_SNAKE_CASE_ : str ): return self.pre_processor(text=[label] , images=[image] , padding=lowerCAmelCase__ , return_tensors='''pt''' ) def __snake_case ( self : int , SCREAMING_SNAKE_CASE_ : Tuple ): with torch.no_grad(): lowerCAmelCase__ = self.model(**lowerCAmelCase__ ).logits return logits def __snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : str ): lowerCAmelCase__ = outputs.cpu().detach().numpy() lowerCAmelCase__ = 0 lowerCAmelCase__ = 1 return Image.fromarray((array * 255).astype(np.uinta ) )
668
import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# lowerCAmelCase : Optional[int] = [ # (stable-diffusion, HF Diffusers) ("""time_embed.0.weight""", """time_embedding.linear_1.weight"""), ("""time_embed.0.bias""", """time_embedding.linear_1.bias"""), ("""time_embed.2.weight""", """time_embedding.linear_2.weight"""), ("""time_embed.2.bias""", """time_embedding.linear_2.bias"""), ("""input_blocks.0.0.weight""", """conv_in.weight"""), ("""input_blocks.0.0.bias""", """conv_in.bias"""), ("""out.0.weight""", """conv_norm_out.weight"""), ("""out.0.bias""", """conv_norm_out.bias"""), ("""out.2.weight""", """conv_out.weight"""), ("""out.2.bias""", """conv_out.bias"""), ] lowerCAmelCase : str = [ # (stable-diffusion, HF Diffusers) ("""in_layers.0""", """norm1"""), ("""in_layers.2""", """conv1"""), ("""out_layers.0""", """norm2"""), ("""out_layers.3""", """conv2"""), ("""emb_layers.1""", """time_emb_proj"""), ("""skip_connection""", """conv_shortcut"""), ] lowerCAmelCase : List[str] = [] # hardcoded number of downblocks and resnets/attentions... # would need smarter logic for other networks. for i in range(4): # loop over downblocks/upblocks for j in range(2): # loop over resnets/attentions for downblocks lowerCAmelCase : int = f'''down_blocks.{i}.resnets.{j}.''' lowerCAmelCase : List[str] = f'''input_blocks.{3*i + j + 1}.0.''' unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix)) if i < 3: # no attention layers in down_blocks.3 lowerCAmelCase : Any = f'''down_blocks.{i}.attentions.{j}.''' lowerCAmelCase : List[Any] = f'''input_blocks.{3*i + j + 1}.1.''' unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix)) for j in range(3): # loop over resnets/attentions for upblocks lowerCAmelCase : Any = f'''up_blocks.{i}.resnets.{j}.''' lowerCAmelCase : str = f'''output_blocks.{3*i + j}.0.''' unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix)) if i > 0: # no attention layers in up_blocks.0 lowerCAmelCase : List[Any] = f'''up_blocks.{i}.attentions.{j}.''' lowerCAmelCase : str = f'''output_blocks.{3*i + j}.1.''' unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix)) if i < 3: # no downsample in down_blocks.3 lowerCAmelCase : Any = f'''down_blocks.{i}.downsamplers.0.conv.''' lowerCAmelCase : Tuple = f'''input_blocks.{3*(i+1)}.0.op.''' unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix)) # no upsample in up_blocks.3 lowerCAmelCase : Tuple = f'''up_blocks.{i}.upsamplers.0.''' lowerCAmelCase : Tuple = f'''output_blocks.{3*i + 2}.{1 if i == 0 else 2}.''' unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix)) lowerCAmelCase : Any = """mid_block.attentions.0.""" lowerCAmelCase : Dict = """middle_block.1.""" unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix)) for j in range(2): lowerCAmelCase : int = f'''mid_block.resnets.{j}.''' lowerCAmelCase : Union[str, Any] = f'''middle_block.{2*j}.''' unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix)) def A_ ( _UpperCAmelCase ): # buyer beware: this is a *brittle* function, # and correct output requires that all of these pieces interact in # the exact order in which I have arranged them. SCREAMING_SNAKE_CASE_: Dict = {k: k for k in unet_state_dict.keys()} for sd_name, hf_name in unet_conversion_map: SCREAMING_SNAKE_CASE_: Optional[int] = sd_name for k, v in mapping.items(): if "resnets" in k: for sd_part, hf_part in unet_conversion_map_resnet: SCREAMING_SNAKE_CASE_: Any = v.replace(_UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: str = v for k, v in mapping.items(): for sd_part, hf_part in unet_conversion_map_layer: SCREAMING_SNAKE_CASE_: Optional[Any] = v.replace(_UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] = v SCREAMING_SNAKE_CASE_: Optional[Any] = {v: unet_state_dict[k] for k, v in mapping.items()} return new_state_dict # ================# # VAE Conversion # # ================# lowerCAmelCase : Union[str, Any] = [ # (stable-diffusion, HF Diffusers) ("""nin_shortcut""", """conv_shortcut"""), ("""norm_out""", """conv_norm_out"""), ("""mid.attn_1.""", """mid_block.attentions.0."""), ] for i in range(4): # down_blocks have two resnets for j in range(2): lowerCAmelCase : Union[str, Any] = f'''encoder.down_blocks.{i}.resnets.{j}.''' lowerCAmelCase : Optional[Any] = f'''encoder.down.{i}.block.{j}.''' vae_conversion_map.append((sd_down_prefix, hf_down_prefix)) if i < 3: lowerCAmelCase : Dict = f'''down_blocks.{i}.downsamplers.0.''' lowerCAmelCase : List[str] = f'''down.{i}.downsample.''' vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix)) lowerCAmelCase : List[str] = f'''up_blocks.{i}.upsamplers.0.''' lowerCAmelCase : int = f'''up.{3-i}.upsample.''' vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix)) # up_blocks have three resnets # also, up blocks in hf are numbered in reverse from sd for j in range(3): lowerCAmelCase : Any = f'''decoder.up_blocks.{i}.resnets.{j}.''' lowerCAmelCase : int = f'''decoder.up.{3-i}.block.{j}.''' vae_conversion_map.append((sd_up_prefix, hf_up_prefix)) # this part accounts for mid blocks in both the encoder and the decoder for i in range(2): lowerCAmelCase : str = f'''mid_block.resnets.{i}.''' lowerCAmelCase : Tuple = f'''mid.block_{i+1}.''' vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix)) lowerCAmelCase : List[Any] = [ # (stable-diffusion, HF Diffusers) ("""norm.""", """group_norm."""), ("""q.""", """query."""), ("""k.""", """key."""), ("""v.""", """value."""), ("""proj_out.""", """proj_attn."""), ] def A_ ( _UpperCAmelCase ): # convert HF linear weights to SD conv2d weights return w.reshape(*w.shape , 1 , 1 ) def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[Any] = {k: k for k in vae_state_dict.keys()} for k, v in mapping.items(): for sd_part, hf_part in vae_conversion_map: SCREAMING_SNAKE_CASE_: Union[str, Any] = v.replace(_UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] = v for k, v in mapping.items(): if "attentions" in k: for sd_part, hf_part in vae_conversion_map_attn: SCREAMING_SNAKE_CASE_: Any = v.replace(_UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] = v SCREAMING_SNAKE_CASE_: Tuple = {v: vae_state_dict[k] for k, v in mapping.items()} SCREAMING_SNAKE_CASE_: Union[str, Any] = ["q", "k", "v", "proj_out"] for k, v in new_state_dict.items(): for weight_name in weights_to_convert: if f"mid.attn_1.{weight_name}.weight" in k: print(f"Reshaping {k} for SD format" ) SCREAMING_SNAKE_CASE_: List[str] = reshape_weight_for_sd(_UpperCAmelCase ) return new_state_dict # =========================# # Text Encoder Conversion # # =========================# lowerCAmelCase : Optional[Any] = [ # (stable-diffusion, HF Diffusers) ("""resblocks.""", """text_model.encoder.layers."""), ("""ln_1""", """layer_norm1"""), ("""ln_2""", """layer_norm2"""), (""".c_fc.""", """.fc1."""), (""".c_proj.""", """.fc2."""), (""".attn""", """.self_attn"""), ("""ln_final.""", """transformer.text_model.final_layer_norm."""), ("""token_embedding.weight""", """transformer.text_model.embeddings.token_embedding.weight"""), ("""positional_embedding""", """transformer.text_model.embeddings.position_embedding.weight"""), ] lowerCAmelCase : Optional[Any] = {re.escape(x[1]): x[0] for x in textenc_conversion_lst} lowerCAmelCase : Optional[int] = re.compile("""|""".join(protected.keys())) # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp lowerCAmelCase : str = {"""q""": 0, """k""": 1, """v""": 2} def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: str = {} SCREAMING_SNAKE_CASE_: str = {} SCREAMING_SNAKE_CASE_: List[str] = {} for k, v in text_enc_dict.items(): if ( k.endswith(".self_attn.q_proj.weight" ) or k.endswith(".self_attn.k_proj.weight" ) or k.endswith(".self_attn.v_proj.weight" ) ): SCREAMING_SNAKE_CASE_: str = k[: -len(".q_proj.weight" )] SCREAMING_SNAKE_CASE_: Dict = k[-len("q_proj.weight" )] if k_pre not in capture_qkv_weight: SCREAMING_SNAKE_CASE_: Tuple = [None, None, None] SCREAMING_SNAKE_CASE_: Union[str, Any] = v continue if ( k.endswith(".self_attn.q_proj.bias" ) or k.endswith(".self_attn.k_proj.bias" ) or k.endswith(".self_attn.v_proj.bias" ) ): SCREAMING_SNAKE_CASE_: Union[str, Any] = k[: -len(".q_proj.bias" )] SCREAMING_SNAKE_CASE_: Any = k[-len("q_proj.bias" )] if k_pre not in capture_qkv_bias: SCREAMING_SNAKE_CASE_: List[Any] = [None, None, None] SCREAMING_SNAKE_CASE_: List[str] = v continue SCREAMING_SNAKE_CASE_: int = textenc_pattern.sub(lambda _UpperCAmelCase : protected[re.escape(m.group(0 ) )] , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Dict = v for k_pre, tensors in capture_qkv_weight.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) SCREAMING_SNAKE_CASE_: str = textenc_pattern.sub(lambda _UpperCAmelCase : protected[re.escape(m.group(0 ) )] , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: int = torch.cat(_UpperCAmelCase ) for k_pre, tensors in capture_qkv_bias.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) SCREAMING_SNAKE_CASE_: Optional[int] = textenc_pattern.sub(lambda _UpperCAmelCase : protected[re.escape(m.group(0 ) )] , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] = torch.cat(_UpperCAmelCase ) return new_state_dict def A_ ( _UpperCAmelCase ): return text_enc_dict if __name__ == "__main__": lowerCAmelCase : int = argparse.ArgumentParser() parser.add_argument("""--model_path""", default=None, type=str, required=True, help="""Path to the model to convert.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, required=True, help="""Path to the output model.""") parser.add_argument("""--half""", action="""store_true""", help="""Save weights in half precision.""") parser.add_argument( """--use_safetensors""", action="""store_true""", help="""Save weights use safetensors, default is ckpt.""" ) lowerCAmelCase : Optional[Any] = parser.parse_args() assert args.model_path is not None, "Must provide a model path!" assert args.checkpoint_path is not None, "Must provide a checkpoint path!" # Path for safetensors lowerCAmelCase : int = osp.join(args.model_path, """unet""", """diffusion_pytorch_model.safetensors""") lowerCAmelCase : List[str] = osp.join(args.model_path, """vae""", """diffusion_pytorch_model.safetensors""") lowerCAmelCase : Optional[int] = osp.join(args.model_path, """text_encoder""", """model.safetensors""") # Load models from safetensors if it exists, if it doesn't pytorch if osp.exists(unet_path): lowerCAmelCase : Optional[int] = load_file(unet_path, device="""cpu""") else: lowerCAmelCase : Union[str, Any] = osp.join(args.model_path, """unet""", """diffusion_pytorch_model.bin""") lowerCAmelCase : Optional[Any] = torch.load(unet_path, map_location="""cpu""") if osp.exists(vae_path): lowerCAmelCase : str = load_file(vae_path, device="""cpu""") else: lowerCAmelCase : List[Any] = osp.join(args.model_path, """vae""", """diffusion_pytorch_model.bin""") lowerCAmelCase : Optional[Any] = torch.load(vae_path, map_location="""cpu""") if osp.exists(text_enc_path): lowerCAmelCase : List[Any] = load_file(text_enc_path, device="""cpu""") else: lowerCAmelCase : List[Any] = osp.join(args.model_path, """text_encoder""", """pytorch_model.bin""") lowerCAmelCase : Optional[Any] = torch.load(text_enc_path, map_location="""cpu""") # Convert the UNet model lowerCAmelCase : int = convert_unet_state_dict(unet_state_dict) lowerCAmelCase : Optional[int] = {"""model.diffusion_model.""" + k: v for k, v in unet_state_dict.items()} # Convert the VAE model lowerCAmelCase : Union[str, Any] = convert_vae_state_dict(vae_state_dict) lowerCAmelCase : Optional[int] = {"""first_stage_model.""" + k: v for k, v in vae_state_dict.items()} # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper lowerCAmelCase : Any = """text_model.encoder.layers.22.layer_norm2.bias""" in text_enc_dict if is_vaa_model: # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm lowerCAmelCase : Any = {"""transformer.""" + k: v for k, v in text_enc_dict.items()} lowerCAmelCase : str = convert_text_enc_state_dict_vaa(text_enc_dict) lowerCAmelCase : Dict = {"""cond_stage_model.model.""" + k: v for k, v in text_enc_dict.items()} else: lowerCAmelCase : Any = convert_text_enc_state_dict(text_enc_dict) lowerCAmelCase : Optional[Any] = {"""cond_stage_model.transformer.""" + k: v for k, v in text_enc_dict.items()} # Put together new checkpoint lowerCAmelCase : Union[str, Any] = {**unet_state_dict, **vae_state_dict, **text_enc_dict} if args.half: lowerCAmelCase : str = {k: v.half() for k, v in state_dict.items()} if args.use_safetensors: save_file(state_dict, args.checkpoint_path) else: lowerCAmelCase : int = {"""state_dict""": state_dict} torch.save(state_dict, args.checkpoint_path)
671
0
import argparse _lowerCamelCase : Optional[Any] = """docs/source/_static/js/custom.js""" def _lowerCAmelCase ( __magic_name__ :str ): with open(_UpperCAmelCase , encoding='''utf-8''' , newline='''\n''' ) as f: UpperCAmelCase_ = f.readlines() UpperCAmelCase_ = 0 # First let's put the right version while not lines[index].startswith('''const stableVersion =''' ): index += 1 UpperCAmelCase_ = F'''const stableVersion = \"v{version}\"\n''' # Then update the dictionary while not lines[index].startswith('''const versionMapping = {''' ): index += 1 # We go until the end while not lines[index].startswith('''}''' ): index += 1 # We add the new version at the end lines[index - 1] += F''' \"v{version}\": \"v{version}\",\n''' with open(_UpperCAmelCase , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(_UpperCAmelCase ) if __name__ == "__main__": _lowerCamelCase : Optional[Any] = argparse.ArgumentParser() parser.add_argument('--version', help='Release version.') _lowerCamelCase : str = parser.parse_args() update_custom_js(args.version)
121
from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase : int = logging.get_logger(__name__) lowerCAmelCase : Dict = { """microsoft/xprophetnet-large-wiki100-cased""": ( """https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json""" ), } class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : Optional[Any] = '''xlm-prophetnet''' _UpperCAmelCase : Any = ['''past_key_values'''] _UpperCAmelCase : Tuple = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self : str , lowerCAmelCase__ : Optional[float] = 0.1 , lowerCAmelCase__ : Optional[Union[str, Callable]] = "gelu" , lowerCAmelCase__ : Optional[int] = 3_0522 , lowerCAmelCase__ : Optional[int] = 1024 , lowerCAmelCase__ : Optional[int] = 4096 , lowerCAmelCase__ : Optional[int] = 12 , lowerCAmelCase__ : Optional[int] = 16 , lowerCAmelCase__ : Optional[int] = 4096 , lowerCAmelCase__ : Optional[int] = 12 , lowerCAmelCase__ : Optional[int] = 16 , lowerCAmelCase__ : Optional[float] = 0.1 , lowerCAmelCase__ : Optional[float] = 0.1 , lowerCAmelCase__ : Optional[int] = 512 , lowerCAmelCase__ : Optional[float] = 0.02 , lowerCAmelCase__ : Optional[bool] = True , lowerCAmelCase__ : Optional[bool] = True , lowerCAmelCase__ : Optional[int] = 0 , lowerCAmelCase__ : Optional[int] = 2 , lowerCAmelCase__ : Optional[int] = 32 , lowerCAmelCase__ : Optional[int] = 128 , lowerCAmelCase__ : Optional[bool] = False , lowerCAmelCase__ : Optional[float] = 0.0 , lowerCAmelCase__ : Optional[bool] = True , lowerCAmelCase__ : Optional[int] = 0 , lowerCAmelCase__ : Optional[int] = 1 , lowerCAmelCase__ : Optional[int] = 2 , **lowerCAmelCase__ : List[str] , ): SCREAMING_SNAKE_CASE_: List[Any] = vocab_size SCREAMING_SNAKE_CASE_: int = hidden_size SCREAMING_SNAKE_CASE_: Any = encoder_ffn_dim SCREAMING_SNAKE_CASE_: Tuple = num_encoder_layers SCREAMING_SNAKE_CASE_: List[Any] = num_encoder_attention_heads SCREAMING_SNAKE_CASE_: Dict = decoder_ffn_dim SCREAMING_SNAKE_CASE_: Any = num_decoder_layers SCREAMING_SNAKE_CASE_: Tuple = num_decoder_attention_heads SCREAMING_SNAKE_CASE_: str = max_position_embeddings SCREAMING_SNAKE_CASE_: str = init_std # Normal(0, this parameter) SCREAMING_SNAKE_CASE_: Dict = activation_function # parameters for xlmprophetnet SCREAMING_SNAKE_CASE_: Optional[int] = ngram SCREAMING_SNAKE_CASE_: Tuple = num_buckets SCREAMING_SNAKE_CASE_: Union[str, Any] = relative_max_distance SCREAMING_SNAKE_CASE_: List[str] = disable_ngram_loss SCREAMING_SNAKE_CASE_: Dict = eps # 3 Types of Dropout SCREAMING_SNAKE_CASE_: Any = attention_dropout SCREAMING_SNAKE_CASE_: Optional[int] = activation_dropout SCREAMING_SNAKE_CASE_: str = dropout SCREAMING_SNAKE_CASE_: Optional[int] = use_cache super().__init__( pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , is_encoder_decoder=lowerCAmelCase__ , add_cross_attention=lowerCAmelCase__ , decoder_start_token_id=lowerCAmelCase__ , **lowerCAmelCase__ , ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def _SCREAMING_SNAKE_CASE ( self : int , lowerCAmelCase__ : Any): raise NotImplementedError( "This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and" " `num_decoder_layers`.")
671
0
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE : Any = logging.get_logger(__name__) SCREAMING_SNAKE_CASE : Dict = { """microsoft/unispeech-sat-base-100h-libri-ft""": ( """https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft/resolve/main/config.json""" ), # See all UniSpeechSat models at https://huggingface.co/models?filter=unispeech_sat } class _lowerCamelCase( UpperCAmelCase_ ): lowercase_ : Union[str, Any] = '''unispeech-sat''' def __init__( self, lowerCamelCase=32, lowerCamelCase=7_68, lowerCamelCase=12, lowerCamelCase=12, lowerCamelCase=30_72, lowerCamelCase="gelu", lowerCamelCase=0.1, lowerCamelCase=0.1, lowerCamelCase=0.1, lowerCamelCase=0.0, lowerCamelCase=0.0, lowerCamelCase=0.1, lowerCamelCase=0.1, lowerCamelCase=0.0_2, lowerCamelCase=1E-5, lowerCamelCase="group", lowerCamelCase="gelu", lowerCamelCase=(5_12, 5_12, 5_12, 5_12, 5_12, 5_12, 5_12), lowerCamelCase=(5, 2, 2, 2, 2, 2, 2), lowerCamelCase=(10, 3, 3, 3, 3, 2, 2), lowerCamelCase=False, lowerCamelCase=1_28, lowerCamelCase=16, lowerCamelCase=False, lowerCamelCase=True, lowerCamelCase=0.0_5, lowerCamelCase=10, lowerCamelCase=2, lowerCamelCase=0.0, lowerCamelCase=10, lowerCamelCase=0, lowerCamelCase=3_20, lowerCamelCase=2, lowerCamelCase=0.1, lowerCamelCase=1_00, lowerCamelCase=2_56, lowerCamelCase=2_56, lowerCamelCase=0.1, lowerCamelCase="mean", lowerCamelCase=False, lowerCamelCase=False, lowerCamelCase=2_56, lowerCamelCase=(5_12, 5_12, 5_12, 5_12, 15_00), lowerCamelCase=(5, 3, 3, 1, 1), lowerCamelCase=(1, 2, 3, 1, 1), lowerCamelCase=5_12, lowerCamelCase=0, lowerCamelCase=1, lowerCamelCase=2, lowerCamelCase=5_04, **lowerCamelCase, ) -> List[str]: """simple docstring""" super().__init__(**lowerCAmelCase__, pad_token_id=lowerCAmelCase__, bos_token_id=lowerCAmelCase__, eos_token_id=lowerCAmelCase__) _lowercase : Optional[Any] = hidden_size _lowercase : Any = feat_extract_norm _lowercase : Optional[int] = feat_extract_activation _lowercase : List[str] = list(lowerCAmelCase__) _lowercase : int = list(lowerCAmelCase__) _lowercase : List[str] = list(lowerCAmelCase__) _lowercase : int = conv_bias _lowercase : List[str] = num_conv_pos_embeddings _lowercase : Optional[int] = num_conv_pos_embedding_groups _lowercase : Optional[int] = len(self.conv_dim) _lowercase : Optional[int] = num_hidden_layers _lowercase : Dict = intermediate_size _lowercase : int = hidden_act _lowercase : Optional[Any] = num_attention_heads _lowercase : Union[str, Any] = hidden_dropout _lowercase : List[Any] = attention_dropout _lowercase : Tuple = activation_dropout _lowercase : List[str] = feat_proj_dropout _lowercase : Optional[int] = final_dropout _lowercase : Optional[int] = layerdrop _lowercase : str = layer_norm_eps _lowercase : Dict = initializer_range _lowercase : Tuple = vocab_size _lowercase : Any = num_clusters _lowercase : int = do_stable_layer_norm _lowercase : Dict = use_weighted_layer_sum if ( (len(self.conv_stride) != self.num_feat_extract_layers) or (len(self.conv_kernel) != self.num_feat_extract_layers) or (len(self.conv_dim) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==' ' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =' F''' {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,''' F''' `len(config.conv_kernel) = {len(self.conv_kernel)}`.''') # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 _lowercase : Tuple = apply_spec_augment _lowercase : List[str] = mask_time_prob _lowercase : str = mask_time_length _lowercase : Union[str, Any] = mask_time_min_masks _lowercase : Union[str, Any] = mask_feature_prob _lowercase : Dict = mask_feature_length _lowercase : Any = mask_feature_min_masks # parameters for pretraining with codevector quantized representations _lowercase : List[str] = num_codevectors_per_group _lowercase : Tuple = num_codevector_groups _lowercase : str = contrastive_logits_temperature _lowercase : Optional[int] = feat_quantizer_dropout _lowercase : List[str] = num_negatives _lowercase : Optional[Any] = codevector_dim _lowercase : Union[str, Any] = proj_codevector_dim _lowercase : str = diversity_loss_weight # ctc loss _lowercase : Optional[Any] = ctc_loss_reduction _lowercase : Optional[int] = ctc_zero_infinity # SequenceClassification-specific parameter. Feel free to ignore for other classes. _lowercase : Tuple = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. _lowercase : Optional[Any] = list(lowerCAmelCase__) _lowercase : Optional[int] = list(lowerCAmelCase__) _lowercase : Optional[Any] = list(lowerCAmelCase__) _lowercase : List[str] = xvector_output_dim @property def UpperCamelCase ( self) -> Union[str, Any]: """simple docstring""" return functools.reduce(operator.mul, self.conv_stride, 1)
89
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL lowerCAmelCase : Dict = logging.get_logger(__name__) def A_ ( _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[int] = b.T SCREAMING_SNAKE_CASE_: Dict = np.sum(np.square(_UpperCAmelCase ) , axis=1 ) SCREAMING_SNAKE_CASE_: Tuple = np.sum(np.square(_UpperCAmelCase ) , axis=0 ) SCREAMING_SNAKE_CASE_: List[Any] = np.matmul(_UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Dict = aa[:, None] - 2 * ab + ba[None, :] return d def A_ ( _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: int = x.reshape(-1 , 3 ) SCREAMING_SNAKE_CASE_: Tuple = squared_euclidean_distance(_UpperCAmelCase , _UpperCAmelCase ) return np.argmin(_UpperCAmelCase , axis=1 ) class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : int = ['''pixel_values'''] def __init__( self : Tuple , lowerCAmelCase__ : Optional[Union[List[List[int]], np.ndarray]] = None , lowerCAmelCase__ : bool = True , lowerCAmelCase__ : Dict[str, int] = None , lowerCAmelCase__ : PILImageResampling = PILImageResampling.BILINEAR , lowerCAmelCase__ : bool = True , lowerCAmelCase__ : bool = True , **lowerCAmelCase__ : List[str] , ): super().__init__(**lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Any = size if size is not None else {"height": 256, "width": 256} SCREAMING_SNAKE_CASE_: Tuple = get_size_dict(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Tuple = np.array(lowerCAmelCase__) if clusters is not None else None SCREAMING_SNAKE_CASE_: Dict = do_resize SCREAMING_SNAKE_CASE_: str = size SCREAMING_SNAKE_CASE_: List[Any] = resample SCREAMING_SNAKE_CASE_: Optional[int] = do_normalize SCREAMING_SNAKE_CASE_: Dict = do_color_quantize def _SCREAMING_SNAKE_CASE ( self : List[str] , lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : Dict[str, int] , lowerCAmelCase__ : PILImageResampling = PILImageResampling.BILINEAR , lowerCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **lowerCAmelCase__ : Optional[Any] , ): SCREAMING_SNAKE_CASE_: List[str] = get_size_dict(lowerCAmelCase__) if "height" not in size or "width" not in size: raise ValueError(F"Size dictionary must contain both height and width keys. Got {size.keys()}") return resize( lowerCAmelCase__ , size=(size["height"], size["width"]) , resample=lowerCAmelCase__ , data_format=lowerCAmelCase__ , **lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , ): SCREAMING_SNAKE_CASE_: str = rescale(image=lowerCAmelCase__ , scale=1 / 127.5 , data_format=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Optional[int] = image - 1 return image def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase__ : ImageInput , lowerCAmelCase__ : bool = None , lowerCAmelCase__ : Dict[str, int] = None , lowerCAmelCase__ : PILImageResampling = None , lowerCAmelCase__ : bool = None , lowerCAmelCase__ : Optional[bool] = None , lowerCAmelCase__ : Optional[Union[List[List[int]], np.ndarray]] = None , lowerCAmelCase__ : Optional[Union[str, TensorType]] = None , lowerCAmelCase__ : Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST , **lowerCAmelCase__ : Union[str, Any] , ): SCREAMING_SNAKE_CASE_: Tuple = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE_: Optional[int] = size if size is not None else self.size SCREAMING_SNAKE_CASE_: Dict = get_size_dict(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[str] = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE_: int = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE_: List[str] = do_color_quantize if do_color_quantize is not None else self.do_color_quantize SCREAMING_SNAKE_CASE_: Tuple = clusters if clusters is not None else self.clusters SCREAMING_SNAKE_CASE_: Optional[int] = np.array(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Optional[int] = make_list_of_images(lowerCAmelCase__) if not valid_images(lowerCAmelCase__): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray.") if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True.") if do_color_quantize and clusters is None: raise ValueError("Clusters must be specified if do_color_quantize is True.") # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE_: Union[str, Any] = [to_numpy_array(lowerCAmelCase__) for image in images] if do_resize: SCREAMING_SNAKE_CASE_: Optional[Any] = [self.resize(image=lowerCAmelCase__ , size=lowerCAmelCase__ , resample=lowerCAmelCase__) for image in images] if do_normalize: SCREAMING_SNAKE_CASE_: str = [self.normalize(image=lowerCAmelCase__) for image in images] if do_color_quantize: SCREAMING_SNAKE_CASE_: Any = [to_channel_dimension_format(lowerCAmelCase__ , ChannelDimension.LAST) for image in images] # color quantize from (batch_size, height, width, 3) to (batch_size, height, width) SCREAMING_SNAKE_CASE_: List[Any] = np.array(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[str] = color_quantize(lowerCAmelCase__ , lowerCAmelCase__).reshape(images.shape[:-1]) # flatten to (batch_size, height*width) SCREAMING_SNAKE_CASE_: str = images.shape[0] SCREAMING_SNAKE_CASE_: Tuple = images.reshape(lowerCAmelCase__ , -1) # We need to convert back to a list of images to keep consistent behaviour across processors. SCREAMING_SNAKE_CASE_: str = list(lowerCAmelCase__) else: SCREAMING_SNAKE_CASE_: Dict = [to_channel_dimension_format(lowerCAmelCase__ , lowerCAmelCase__) for image in images] SCREAMING_SNAKE_CASE_: Optional[Any] = {"input_ids": images} return BatchFeature(data=lowerCAmelCase__ , tensor_type=lowerCAmelCase__)
671
0
from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class lowerCAmelCase__ ( UpperCAmelCase_ ): UpperCamelCase_ : Optional[Any] = DistilBertTokenizer UpperCamelCase_ : Union[str, Any] = DistilBertTokenizerFast UpperCamelCase_ : int = True @slow def A_ ( self ) -> Any: '''simple docstring''' _UpperCamelCase = DistilBertTokenizer.from_pretrained("""distilbert-base-uncased""" ) _UpperCamelCase = tokenizer.encode("""sequence builders""" , add_special_tokens=lowerCAmelCase__ ) _UpperCamelCase = tokenizer.encode("""multi-sequence build""" , add_special_tokens=lowerCAmelCase__ ) _UpperCamelCase = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase__ ) _UpperCamelCase = 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 ]
612
import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert import BertTokenizer lowerCAmelCase : Optional[int] = logging.get_logger(__name__) lowerCAmelCase : str = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} lowerCAmelCase : Tuple = { """vocab_file""": { """facebook/dpr-ctx_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt""" ), """facebook/dpr-ctx_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """facebook/dpr-ctx_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json""" ), """facebook/dpr-ctx_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json""" ), }, } lowerCAmelCase : Union[str, Any] = { """vocab_file""": { """facebook/dpr-question_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt""" ), """facebook/dpr-question_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """facebook/dpr-question_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json""" ), """facebook/dpr-question_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json""" ), }, } lowerCAmelCase : List[str] = { """vocab_file""": { """facebook/dpr-reader-single-nq-base""": ( """https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt""" ), """facebook/dpr-reader-multiset-base""": ( """https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """facebook/dpr-reader-single-nq-base""": ( """https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json""" ), """facebook/dpr-reader-multiset-base""": ( """https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json""" ), }, } lowerCAmelCase : int = { """facebook/dpr-ctx_encoder-single-nq-base""": 512, """facebook/dpr-ctx_encoder-multiset-base""": 512, } lowerCAmelCase : int = { """facebook/dpr-question_encoder-single-nq-base""": 512, """facebook/dpr-question_encoder-multiset-base""": 512, } lowerCAmelCase : List[Any] = { """facebook/dpr-reader-single-nq-base""": 512, """facebook/dpr-reader-multiset-base""": 512, } lowerCAmelCase : Optional[int] = { """facebook/dpr-ctx_encoder-single-nq-base""": {"""do_lower_case""": True}, """facebook/dpr-ctx_encoder-multiset-base""": {"""do_lower_case""": True}, } lowerCAmelCase : Optional[int] = { """facebook/dpr-question_encoder-single-nq-base""": {"""do_lower_case""": True}, """facebook/dpr-question_encoder-multiset-base""": {"""do_lower_case""": True}, } lowerCAmelCase : List[str] = { """facebook/dpr-reader-single-nq-base""": {"""do_lower_case""": True}, """facebook/dpr-reader-multiset-base""": {"""do_lower_case""": True}, } class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : Any = VOCAB_FILES_NAMES _UpperCAmelCase : Optional[Any] = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : List[Any] = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : List[Any] = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : Union[str, Any] = VOCAB_FILES_NAMES _UpperCAmelCase : Optional[int] = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Any = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : str = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION lowerCAmelCase : List[Any] = collections.namedtuple( """DPRSpanPrediction""", ["""span_score""", """relevance_score""", """doc_id""", """start_index""", """end_index""", """text"""] ) lowerCAmelCase : Optional[Any] = collections.namedtuple("""DPRReaderOutput""", ["""start_logits""", """end_logits""", """relevance_logits"""]) lowerCAmelCase : int = R""" Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`. It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers), using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)` with the format: ``` [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids> ``` Args: questions (`str` or `List[str]`): The questions to be encoded. You can specify one question for many passages. In this case, the question will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in `titles` or `texts`. titles (`str` or `List[str]`): The passages titles to be encoded. This can be a string or a list of strings if there are several passages. texts (`str` or `List[str]`): The passages texts to be encoded. This can be a string or a list of strings if there are several passages. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`): Activates and controls padding. Accepts the following values: - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different lengths). truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`): Activates and controls truncation. Accepts the following values: - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided. - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size). max_length (`int`, *optional*): Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length is required by one of the truncation/padding parameters. If the model has no specific maximum input length (like XLNet) truncation/padding to a maximum length will be deactivated. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors instead of list of python integers. Acceptable values are: - `'tf'`: Return TensorFlow `tf.constant` objects. - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return Numpy `np.ndarray` objects. return_attention_mask (`bool`, *optional*): Whether or not to return the attention mask. If not set, will return the attention mask according to the specific tokenizer's default, defined by the `return_outputs` attribute. [What are attention masks?](../glossary#attention-mask) Returns: `Dict[str, List[List[int]]]`: A dictionary with the following keys: - `input_ids`: List of token ids to be fed to a model. - `attention_mask`: List of indices specifying which tokens should be attended to by the model. """ @add_start_docstrings(UpperCAmelCase_ ) class __lowercase : """simple docstring""" def __call__( self : List[Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : Optional[str] = None , lowerCAmelCase__ : Optional[str] = None , lowerCAmelCase__ : Union[bool, str] = False , lowerCAmelCase__ : Union[bool, str] = False , lowerCAmelCase__ : Optional[int] = None , lowerCAmelCase__ : Optional[Union[str, TensorType]] = None , lowerCAmelCase__ : Optional[bool] = None , **lowerCAmelCase__ : Tuple , ): if titles is None and texts is None: return super().__call__( lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , max_length=lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , **lowerCAmelCase__ , ) elif titles is None or texts is None: SCREAMING_SNAKE_CASE_: List[str] = titles if texts is None else texts return super().__call__( lowerCAmelCase__ , lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , max_length=lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , **lowerCAmelCase__ , ) SCREAMING_SNAKE_CASE_: Optional[int] = titles if not isinstance(lowerCAmelCase__ , lowerCAmelCase__) else [titles] SCREAMING_SNAKE_CASE_: int = texts if not isinstance(lowerCAmelCase__ , lowerCAmelCase__) else [texts] SCREAMING_SNAKE_CASE_: str = len(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Tuple = questions if not isinstance(lowerCAmelCase__ , lowerCAmelCase__) else [questions] * n_passages if len(lowerCAmelCase__) != len(lowerCAmelCase__): raise ValueError( F"There should be as many titles than texts but got {len(lowerCAmelCase__)} titles and {len(lowerCAmelCase__)} texts.") SCREAMING_SNAKE_CASE_: Optional[Any] = super().__call__(lowerCAmelCase__ , lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__)["input_ids"] SCREAMING_SNAKE_CASE_: Union[str, Any] = super().__call__(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__)["input_ids"] SCREAMING_SNAKE_CASE_: int = { "input_ids": [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(lowerCAmelCase__ , lowerCAmelCase__) ] } if return_attention_mask is not False: SCREAMING_SNAKE_CASE_: Dict = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id) for input_id in input_ids]) SCREAMING_SNAKE_CASE_: int = attention_mask return self.pad(lowerCAmelCase__ , padding=lowerCAmelCase__ , max_length=lowerCAmelCase__ , return_tensors=lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Any , lowerCAmelCase__ : BatchEncoding , lowerCAmelCase__ : DPRReaderOutput , lowerCAmelCase__ : int = 16 , lowerCAmelCase__ : int = 64 , lowerCAmelCase__ : int = 4 , ): SCREAMING_SNAKE_CASE_: int = reader_input["input_ids"] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: int = reader_output[:3] SCREAMING_SNAKE_CASE_: Tuple = len(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Union[str, Any] = sorted(range(lowerCAmelCase__) , reverse=lowerCAmelCase__ , key=relevance_logits.__getitem__) SCREAMING_SNAKE_CASE_: List[DPRReaderOutput] = [] for doc_id in sorted_docs: SCREAMING_SNAKE_CASE_: Optional[int] = list(input_ids[doc_id]) # assuming question & title information is at the beginning of the sequence SCREAMING_SNAKE_CASE_: str = sequence_ids.index(self.sep_token_id , 2) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: SCREAMING_SNAKE_CASE_: List[Any] = sequence_ids.index(self.pad_token_id) else: SCREAMING_SNAKE_CASE_: Dict = len(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Optional[Any] = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=lowerCAmelCase__ , top_spans=lowerCAmelCase__ , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=lowerCAmelCase__ , start_index=lowerCAmelCase__ , end_index=lowerCAmelCase__ , text=self.decode(sequence_ids[start_index : end_index + 1]) , )) if len(lowerCAmelCase__) >= num_spans: break return nbest_spans_predictions[:num_spans] def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase__ : List[int] , lowerCAmelCase__ : List[int] , lowerCAmelCase__ : int , lowerCAmelCase__ : int , ): SCREAMING_SNAKE_CASE_: Any = [] for start_index, start_score in enumerate(lowerCAmelCase__): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length]): scores.append(((start_index, start_index + answer_length), start_score + end_score)) SCREAMING_SNAKE_CASE_: Union[str, Any] = sorted(lowerCAmelCase__ , key=lambda lowerCAmelCase__: x[1] , reverse=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[str] = [] for (start_index, end_index), score in scores: if start_index > end_index: raise ValueError(F"Wrong span indices: [{start_index}:{end_index}]") SCREAMING_SNAKE_CASE_: int = end_index - start_index + 1 if length > max_answer_length: raise ValueError(F"Span is too long: {length} > {max_answer_length}") if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals): continue chosen_span_intervals.append((start_index, end_index)) if len(lowerCAmelCase__) == top_spans: break return chosen_span_intervals @add_end_docstrings(UpperCAmelCase_ ) class __lowercase ( UpperCAmelCase_ , UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : Any = VOCAB_FILES_NAMES _UpperCAmelCase : Optional[Any] = READER_PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : int = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCAmelCase : Optional[int] = READER_PRETRAINED_INIT_CONFIGURATION _UpperCAmelCase : str = ['''input_ids''', '''attention_mask''']
671
0
"""simple docstring""" import json import logging import math import os import sys from dataclasses import dataclass, field from typing import Optional from datasets import Dataset, load_dataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoModelForMaskedLM, AutoTokenizer, DataCollatorForWholeWordMask, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process lowercase__ = logging.getLogger(__name__) lowercase__ = list(MODEL_FOR_MASKED_LM_MAPPING.keys()) lowercase__ = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class __lowerCamelCase : '''simple docstring''' a_ : Optional[str] = field( default=UpperCAmelCase_ , metadata={ """help""": ( """The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.""" ) } , ) a_ : Optional[str] = field( default=UpperCAmelCase_ , metadata={"""help""": """If training from scratch, pass a model type from the list: """ + """, """.join(UpperCAmelCase_ )} , ) a_ : Optional[str] = field( default=UpperCAmelCase_ , metadata={ """help""": ( """Override some existing default config settings when a model is trained from scratch. Example: """ """n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index""" ) } , ) a_ : Optional[str] = field( default=UpperCAmelCase_ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) a_ : Optional[str] = field( default=UpperCAmelCase_ , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) a_ : Optional[str] = field( default=UpperCAmelCase_ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) a_ : bool = field( default=UpperCAmelCase_ , metadata={"""help""": """Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."""} , ) a_ : str = field( default="""main""" , metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""} , ) a_ : bool = field( default=UpperCAmelCase_ , metadata={ """help""": ( """Will use the token generated when running `huggingface-cli login` (necessary to use this script """ """with private models).""" ) } , ) def lowerCamelCase ( self : Dict ): if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None): raise ValueError( "--config_overrides can't be used in combination with --config_name or --model_name_or_path" ) @dataclass class __lowerCamelCase : '''simple docstring''' a_ : Optional[str] = field( default=UpperCAmelCase_ , metadata={"""help""": """The name of the dataset to use (via the datasets library)."""} ) a_ : Optional[str] = field( default=UpperCAmelCase_ , metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""} ) a_ : Optional[str] = field(default=UpperCAmelCase_ , metadata={"""help""": """The input training data file (a text file)."""} ) a_ : Optional[str] = field( default=UpperCAmelCase_ , metadata={"""help""": """An optional input evaluation data file to evaluate the perplexity on (a text file)."""} , ) a_ : Optional[str] = field( default=UpperCAmelCase_ , metadata={"""help""": """An optional input train ref data file for whole word masking in Chinese."""} , ) a_ : Optional[str] = field( default=UpperCAmelCase_ , metadata={"""help""": """An optional input validation ref data file for whole word masking in Chinese."""} , ) a_ : bool = field( default=UpperCAmelCase_ , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) a_ : Optional[int] = field( default=5 , metadata={ """help""": """The percentage of the train set used as validation set in case there\'s no validation split""" } , ) a_ : Optional[int] = field( default=UpperCAmelCase_ , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated. Default to the max input length of the model.""" ) } , ) a_ : Optional[int] = field( default=UpperCAmelCase_ , metadata={"""help""": """The number of processes to use for the preprocessing."""} , ) a_ : float = field( default=0.15 , metadata={"""help""": """Ratio of tokens to mask for masked language modeling loss"""} ) a_ : bool = field( default=UpperCAmelCase_ , metadata={ """help""": ( """Whether to pad all samples to `max_seq_length`. """ """If False, will pad the samples dynamically when batching to the maximum length in the batch.""" ) } , ) def lowerCamelCase ( self : Tuple ): if self.train_file is not None: lowerCAmelCase_ : int = self.train_file.split("." )[-1] assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file." if self.validation_file is not None: lowerCAmelCase_ : Dict = self.validation_file.split("." )[-1] assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file." def __lowerCamelCase ( __UpperCamelCase , __UpperCamelCase ) -> str: """simple docstring""" with open(_UpperCAmelCase , "r" , encoding="utf-8" ) as f: lowerCAmelCase_ : Optional[int] = [json.loads(_UpperCAmelCase ) for line in f.read().splitlines() if (len(_UpperCAmelCase ) > 0 and not line.isspace())] assert len(_UpperCAmelCase ) == len(_UpperCAmelCase ) lowerCAmelCase_ : Union[str, Any] = {c: dataset[c] for c in dataset.column_names} lowerCAmelCase_ : List[Any] = refs return Dataset.from_dict(_UpperCAmelCase ) def __lowerCamelCase ( ) -> Union[str, Any]: """simple docstring""" lowerCAmelCase_ : Union[str, Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowerCAmelCase_ : Any = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowerCAmelCase_ : Optional[int] = parser.parse_args_into_dataclasses() # Detecting last checkpoint. lowerCAmelCase_ : Dict = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: lowerCAmelCase_ : Optional[int] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f'''Output directory ({training_args.output_dir}) already exists and is not empty. ''' "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None: logger.info( f'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout )] , ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN ) # Log on each process the small summary: logger.warning( f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}''' + f'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("Training/evaluation parameters %s" , _UpperCAmelCase ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. lowerCAmelCase_ : Optional[Any] = load_dataset(data_args.dataset_name , data_args.dataset_config_name ) if "validation" not in datasets.keys(): lowerCAmelCase_ : Optional[Any] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f'''train[:{data_args.validation_split_percentage}%]''' , ) lowerCAmelCase_ : Union[str, Any] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f'''train[{data_args.validation_split_percentage}%:]''' , ) else: lowerCAmelCase_ : Optional[Any] = {} if data_args.train_file is not None: lowerCAmelCase_ : str = data_args.train_file if data_args.validation_file is not None: lowerCAmelCase_ : Optional[Any] = data_args.validation_file lowerCAmelCase_ : Tuple = data_args.train_file.split("." )[-1] if extension == "txt": lowerCAmelCase_ : List[str] = "text" lowerCAmelCase_ : Tuple = load_dataset(_UpperCAmelCase , data_files=_UpperCAmelCase ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCAmelCase_ : str = { "cache_dir": model_args.cache_dir, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, } if model_args.config_name: lowerCAmelCase_ : str = AutoConfig.from_pretrained(model_args.config_name , **_UpperCAmelCase ) elif model_args.model_name_or_path: lowerCAmelCase_ : Any = AutoConfig.from_pretrained(model_args.model_name_or_path , **_UpperCAmelCase ) else: lowerCAmelCase_ : str = CONFIG_MAPPING[model_args.model_type]() logger.warning("You are instantiating a new config instance from scratch." ) if model_args.config_overrides is not None: logger.info(f'''Overriding config: {model_args.config_overrides}''' ) config.update_from_string(model_args.config_overrides ) logger.info(f'''New config: {config}''' ) lowerCAmelCase_ : Dict = { "cache_dir": model_args.cache_dir, "use_fast": model_args.use_fast_tokenizer, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, } if model_args.tokenizer_name: lowerCAmelCase_ : Dict = AutoTokenizer.from_pretrained(model_args.tokenizer_name , **_UpperCAmelCase ) elif model_args.model_name_or_path: lowerCAmelCase_ : List[str] = AutoTokenizer.from_pretrained(model_args.model_name_or_path , **_UpperCAmelCase ) else: raise ValueError( "You are instantiating a new tokenizer from scratch. This is not supported by this script." "You can do it from another script, save it, and load it from here, using --tokenizer_name." ) if model_args.model_name_or_path: lowerCAmelCase_ : str = AutoModelForMaskedLM.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=_UpperCAmelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("Training new model from scratch" ) lowerCAmelCase_ : Tuple = AutoModelForMaskedLM.from_config(_UpperCAmelCase ) model.resize_token_embeddings(len(_UpperCAmelCase ) ) # Preprocessing the datasets. # First we tokenize all the texts. if training_args.do_train: lowerCAmelCase_ : Optional[Any] = datasets["train"].column_names else: lowerCAmelCase_ : Optional[int] = datasets["validation"].column_names lowerCAmelCase_ : Optional[Any] = "text" if "text" in column_names else column_names[0] lowerCAmelCase_ : Any = "max_length" if data_args.pad_to_max_length else False def tokenize_function(__UpperCamelCase ): # Remove empty lines lowerCAmelCase_ : List[str] = [line for line in examples["text"] if len(_UpperCAmelCase ) > 0 and not line.isspace()] return tokenizer(examples["text"] , padding=_UpperCAmelCase , truncation=_UpperCAmelCase , max_length=data_args.max_seq_length ) lowerCAmelCase_ : Dict = datasets.map( _UpperCAmelCase , batched=_UpperCAmelCase , num_proc=data_args.preprocessing_num_workers , remove_columns=[text_column_name] , load_from_cache_file=not data_args.overwrite_cache , ) # Add the chinese references if provided if data_args.train_ref_file is not None: lowerCAmelCase_ : Any = add_chinese_references(tokenized_datasets["train"] , data_args.train_ref_file ) if data_args.validation_ref_file is not None: lowerCAmelCase_ : Tuple = add_chinese_references( tokenized_datasets["validation"] , data_args.validation_ref_file ) # If we have ref files, need to avoid it removed by trainer lowerCAmelCase_ : List[Any] = data_args.train_ref_file or data_args.validation_ref_file if has_ref: lowerCAmelCase_ : str = False # Data collator # This one will take care of randomly masking the tokens. lowerCAmelCase_ : List[str] = DataCollatorForWholeWordMask(tokenizer=_UpperCAmelCase , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer lowerCAmelCase_ : List[str] = Trainer( model=_UpperCAmelCase , args=_UpperCAmelCase , train_dataset=tokenized_datasets["train"] if training_args.do_train else None , eval_dataset=tokenized_datasets["validation"] if training_args.do_eval else None , tokenizer=_UpperCAmelCase , data_collator=_UpperCAmelCase , ) # Training if training_args.do_train: if last_checkpoint is not None: lowerCAmelCase_ : List[str] = last_checkpoint elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ): lowerCAmelCase_ : int = model_args.model_name_or_path else: lowerCAmelCase_ : List[str] = None lowerCAmelCase_ : Dict = trainer.train(resume_from_checkpoint=_UpperCAmelCase ) trainer.save_model() # Saves the tokenizer too for easy upload lowerCAmelCase_ : List[Any] = os.path.join(training_args.output_dir , "train_results.txt" ) if trainer.is_world_process_zero(): with open(_UpperCAmelCase , "w" ) as writer: logger.info("***** Train results *****" ) for key, value in sorted(train_result.metrics.items() ): logger.info(f''' {key} = {value}''' ) writer.write(f'''{key} = {value}\n''' ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , "trainer_state.json" ) ) # Evaluation lowerCAmelCase_ : int = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) lowerCAmelCase_ : int = trainer.evaluate() lowerCAmelCase_ : Tuple = math.exp(eval_output["eval_loss"] ) lowerCAmelCase_ : Any = perplexity lowerCAmelCase_ : str = os.path.join(training_args.output_dir , "eval_results_mlm_wwm.txt" ) if trainer.is_world_process_zero(): with open(_UpperCAmelCase , "w" ) as writer: logger.info("***** Eval results *****" ) for key, value in sorted(results.items() ): logger.info(f''' {key} = {value}''' ) writer.write(f'''{key} = {value}\n''' ) return results def __lowerCamelCase ( __UpperCamelCase ) -> Tuple: """simple docstring""" main() if __name__ == "__main__": main()
610
from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : Optional[Any] = DistilBertTokenizer _UpperCAmelCase : Union[str, Any] = DistilBertTokenizerFast _UpperCAmelCase : int = True @slow def _SCREAMING_SNAKE_CASE ( self : Any): SCREAMING_SNAKE_CASE_: Optional[Any] = DistilBertTokenizer.from_pretrained("distilbert-base-uncased") SCREAMING_SNAKE_CASE_: Any = tokenizer.encode("sequence builders" , add_special_tokens=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: List[Any] = tokenizer.encode("multi-sequence build" , add_special_tokens=lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Tuple = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: int = 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 ]
671
0
import argparse from tax import checkpoints from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM def _UpperCAmelCase ( UpperCAmelCase : List[str] , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : Tuple ): """simple docstring""" __lowerCamelCase : List[Any] = AutoConfig.from_pretrained(_UpperCAmelCase ) __lowerCamelCase : List[Any] = FlaxAutoModelForSeqaSeqLM.from_config(config=_UpperCAmelCase ) __lowerCamelCase : List[str] = checkpoints.load_tax_checkpoint(_UpperCAmelCase ) __lowerCamelCase : Dict = "wi_0" in tax_model["target"]["encoder"]["layers_0"]["mlp"] if config.model_type == "t5": __lowerCamelCase : Tuple = "SelfAttention" if config.model_type == "longt5" and config.encoder_attention_type == "local": __lowerCamelCase : Optional[Any] = "LocalSelfAttention" elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __lowerCamelCase : Dict = "TransientGlobalSelfAttention" else: raise ValueError( """Given config is expected to have `model_type='t5'`, or `model_type='longt5` with `encoder_attention_type`""" """ attribute with a value from ['local', 'transient-global].""" ) # Encoder for layer_index in range(config.num_layers ): __lowerCamelCase : List[Any] = f"""layers_{str(_UpperCAmelCase )}""" # Self-Attention __lowerCamelCase : Tuple = tax_model["target"]["encoder"][layer_name]["attention"]["key"]["kernel"] __lowerCamelCase : Union[str, Any] = tax_model["target"]["encoder"][layer_name]["attention"]["out"]["kernel"] __lowerCamelCase : Optional[Any] = tax_model["target"]["encoder"][layer_name]["attention"]["query"]["kernel"] __lowerCamelCase : List[str] = tax_model["target"]["encoder"][layer_name]["attention"]["value"]["kernel"] # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __lowerCamelCase : Union[str, Any] = tax_model["target"]["encoder"][layer_name]["attention"]["T5LayerNorm_0"]["scale"] # Layer Normalization __lowerCamelCase : Dict = tax_model["target"]["encoder"][layer_name]["pre_attention_layer_norm"]["scale"] if split_mlp_wi: __lowerCamelCase : str = tax_model["target"]["encoder"][layer_name]["mlp"]["wi_0"]["kernel"] __lowerCamelCase : Optional[Any] = tax_model["target"]["encoder"][layer_name]["mlp"]["wi_1"]["kernel"] else: __lowerCamelCase : Tuple = tax_model["target"]["encoder"][layer_name]["mlp"]["wi"]["kernel"] __lowerCamelCase : str = tax_model["target"]["encoder"][layer_name]["mlp"]["wo"]["kernel"] # Layer Normalization __lowerCamelCase : int = tax_model["target"]["encoder"][layer_name]["pre_mlp_layer_norm"]["scale"] # Assigning __lowerCamelCase : Tuple = flax_model.params["encoder"]["block"][str(_UpperCAmelCase )]["layer"] __lowerCamelCase : List[Any] = tax_attention_key __lowerCamelCase : Union[str, Any] = tax_attention_out __lowerCamelCase : Any = tax_attention_query __lowerCamelCase : int = tax_attention_value __lowerCamelCase : Optional[Any] = tax_attention_layer_norm # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __lowerCamelCase : Union[str, Any] = tax_global_layer_norm if split_mlp_wi: __lowerCamelCase : Optional[int] = tax_mlp_wi_a __lowerCamelCase : Tuple = tax_mlp_wi_a else: __lowerCamelCase : Optional[Any] = tax_mlp_wi __lowerCamelCase : Tuple = tax_mlp_wo __lowerCamelCase : Optional[Any] = tax_mlp_layer_norm __lowerCamelCase : Optional[Any] = flax_model_encoder_layer_block # Only for layer 0: __lowerCamelCase : Dict = tax_model["target"]["encoder"]["relpos_bias"]["rel_embedding"].T __lowerCamelCase : Union[str, Any] = tax_encoder_rel_embedding # Side/global relative position_bias + layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __lowerCamelCase : List[str] = tax_model["target"]["encoder"]["side_relpos_bias"]["rel_embedding"].T __lowerCamelCase : Union[str, Any] = tax_encoder_global_rel_embedding # Assigning __lowerCamelCase : Optional[Any] = tax_model["target"]["encoder"]["encoder_norm"]["scale"] __lowerCamelCase : Tuple = tax_encoder_norm # Decoder for layer_index in range(config.num_layers ): __lowerCamelCase : Optional[int] = f"""layers_{str(_UpperCAmelCase )}""" # Self-Attention __lowerCamelCase : List[str] = tax_model["target"]["decoder"][layer_name]["self_attention"]["key"]["kernel"] __lowerCamelCase : Dict = tax_model["target"]["decoder"][layer_name]["self_attention"]["out"]["kernel"] __lowerCamelCase : List[str] = tax_model["target"]["decoder"][layer_name]["self_attention"]["query"]["kernel"] __lowerCamelCase : Union[str, Any] = tax_model["target"]["decoder"][layer_name]["self_attention"]["value"]["kernel"] # Layer Normalization __lowerCamelCase : Optional[int] = tax_model["target"]["decoder"][layer_name]["pre_self_attention_layer_norm"][ "scale" ] # Encoder-Decoder-Attention __lowerCamelCase : Any = tax_model["target"]["decoder"][layer_name]["encoder_decoder_attention"] __lowerCamelCase : Optional[int] = tax_enc_dec_attention_module["key"]["kernel"] __lowerCamelCase : Any = tax_enc_dec_attention_module["out"]["kernel"] __lowerCamelCase : Dict = tax_enc_dec_attention_module["query"]["kernel"] __lowerCamelCase : int = tax_enc_dec_attention_module["value"]["kernel"] # Layer Normalization __lowerCamelCase : str = tax_model["target"]["decoder"][layer_name]["pre_cross_attention_layer_norm"]["scale"] # MLP if split_mlp_wi: __lowerCamelCase : int = tax_model["target"]["decoder"][layer_name]["mlp"]["wi_0"]["kernel"] __lowerCamelCase : List[Any] = tax_model["target"]["decoder"][layer_name]["mlp"]["wi_1"]["kernel"] else: __lowerCamelCase : List[Any] = tax_model["target"]["decoder"][layer_name]["mlp"]["wi"]["kernel"] __lowerCamelCase : Tuple = tax_model["target"]["decoder"][layer_name]["mlp"]["wo"]["kernel"] # Layer Normalization __lowerCamelCase : Dict = tax_model["target"]["decoder"][layer_name]["pre_mlp_layer_norm"]["scale"] # Assigning __lowerCamelCase : Tuple = flax_model.params["decoder"]["block"][str(_UpperCAmelCase )]["layer"] __lowerCamelCase : Optional[int] = tax_attention_key __lowerCamelCase : int = tax_attention_out __lowerCamelCase : Optional[int] = tax_attention_query __lowerCamelCase : List[str] = tax_attention_value __lowerCamelCase : Any = tax_pre_attention_layer_norm __lowerCamelCase : int = tax_enc_dec_attention_key __lowerCamelCase : Dict = tax_enc_dec_attention_out __lowerCamelCase : Tuple = tax_enc_dec_attention_query __lowerCamelCase : Union[str, Any] = tax_enc_dec_attention_value __lowerCamelCase : Union[str, Any] = tax_cross_layer_norm if split_mlp_wi: __lowerCamelCase : Any = tax_mlp_wi_a __lowerCamelCase : Optional[int] = tax_mlp_wi_a else: __lowerCamelCase : Any = tax_mlp_wi __lowerCamelCase : Union[str, Any] = tax_mlp_wo __lowerCamelCase : Optional[Any] = txa_mlp_layer_norm __lowerCamelCase : Union[str, Any] = flax_model_decoder_layer_block # Decoder Normalization __lowerCamelCase : Any = tax_model["target"]["decoder"]["decoder_norm"]["scale"] __lowerCamelCase : str = txa_decoder_norm # Only for layer 0: __lowerCamelCase : Tuple = tax_model["target"]["decoder"]["relpos_bias"]["rel_embedding"].T __lowerCamelCase : List[str] = tax_decoder_rel_embedding # Token Embeddings __lowerCamelCase : str = tax_model["target"]["token_embedder"]["embedding"] __lowerCamelCase : Tuple = txa_token_embeddings # LM Head (only in v1.1 and LongT5 checkpoints) if "logits_dense" in tax_model["target"]["decoder"]: __lowerCamelCase : Union[str, Any] = tax_model["target"]["decoder"]["logits_dense"]["kernel"] flax_model.save_pretrained(_UpperCAmelCase ) print("""T5X Model was sucessfully converted!""" ) if __name__ == "__main__": __UpperCamelCase : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--t5x_checkpoint_path', default=None, type=str, required=True, help='Path the T5X checkpoint.' ) parser.add_argument('--config_name', default=None, type=str, required=True, help='Config name of LongT5/T5 model.') parser.add_argument( '--flax_dump_folder_path', default=None, type=str, required=True, help='Path to the output FLAX model.' ) __UpperCamelCase : Optional[int] = parser.parse_args() convert_tax_checkpoint_to_flax(args.tax_checkpoint_path, args.config_name, args.flax_dump_folder_path)
519
import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient lowerCAmelCase : List[Any] = WebClient(token=os.environ["""CI_SLACK_BOT_TOKEN"""]) def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[int] = test_results.split(" " ) SCREAMING_SNAKE_CASE_: Tuple = 0 SCREAMING_SNAKE_CASE_: str = 0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. SCREAMING_SNAKE_CASE_: Optional[Any] = expressions[-2] if "=" in expressions[-1] else expressions[-1] for i, expression in enumerate(_UpperCAmelCase ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: str = {} SCREAMING_SNAKE_CASE_: Any = None SCREAMING_SNAKE_CASE_: Union[str, Any] = False for line in failures_short_lines.split("\n" ): if re.search(R"_ \[doctest\]" , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: List[Any] = True SCREAMING_SNAKE_CASE_: Dict = line.split(" " )[2] elif in_error and not line.split(" " )[0].isdigit(): SCREAMING_SNAKE_CASE_: Union[str, Any] = line SCREAMING_SNAKE_CASE_: List[str] = False return failures class __lowercase : """simple docstring""" def __init__( self : Any , lowerCAmelCase__ : str , lowerCAmelCase__ : Dict): SCREAMING_SNAKE_CASE_: Dict = title SCREAMING_SNAKE_CASE_: int = doc_test_results["time_spent"].split(",")[0] SCREAMING_SNAKE_CASE_: int = doc_test_results["success"] SCREAMING_SNAKE_CASE_: Optional[Any] = doc_test_results["failures"] SCREAMING_SNAKE_CASE_: Any = self.n_success + self.n_failures # Failures and success of the modeling tests SCREAMING_SNAKE_CASE_: Optional[int] = doc_test_results @property def _SCREAMING_SNAKE_CASE ( self : Any): SCREAMING_SNAKE_CASE_: int = [self._time_spent] SCREAMING_SNAKE_CASE_: List[Any] = 0 for time in time_spent: SCREAMING_SNAKE_CASE_: Union[str, Any] = time.split(":") # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(lowerCAmelCase__) == 1: SCREAMING_SNAKE_CASE_: Dict = [0, 0, time_parts[0]] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: int = int(time_parts[0]), int(time_parts[1]), float(time_parts[2]) total_secs += hours * 3600 + minutes * 60 + seconds SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: str = total_secs // 3600, (total_secs % 3600) // 60, total_secs % 60 return F"{int(lowerCAmelCase__)}h{int(lowerCAmelCase__)}m{int(lowerCAmelCase__)}s" @property def _SCREAMING_SNAKE_CASE ( self : List[Any]): return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): return { "type": "section", "text": { "type": "plain_text", "text": F"🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.", "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": F"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", }, } @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): return { "type": "section", "text": { "type": "plain_text", "text": ( F"There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in" F" {self.time}." ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": F"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", }, } @property def _SCREAMING_SNAKE_CASE ( self : Any): SCREAMING_SNAKE_CASE_: Optional[Any] = 40 SCREAMING_SNAKE_CASE_: List[str] = {k: v["failed"] for k, v in doc_test_results.items() if isinstance(lowerCAmelCase__ , lowerCAmelCase__)} SCREAMING_SNAKE_CASE_: Tuple = "" for category, failures in category_failures.items(): if len(lowerCAmelCase__) == 0: continue if report != "": report += "\n\n" report += F"*{category} failures*:".ljust(line_length // 2).rjust(line_length // 2) + "\n" report += "`" report += "`\n`".join(lowerCAmelCase__) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": F"The following examples had failures:\n\n\n{report}\n", }, } @property def _SCREAMING_SNAKE_CASE ( self : str): SCREAMING_SNAKE_CASE_: Optional[Any] = [self.header] if self.n_failures > 0: blocks.append(self.failures) if self.n_failures > 0: blocks.extend([self.category_failures]) if self.n_failures == 0: blocks.append(self.no_failures) return json.dumps(lowerCAmelCase__) @staticmethod def _SCREAMING_SNAKE_CASE ( ): SCREAMING_SNAKE_CASE_: List[str] = [ { "type": "section", "text": { "type": "plain_text", "text": "There was an issue running the tests.", }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": F"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", }, } ] print("Sending the following payload") print(json.dumps({"blocks": json.loads(lowerCAmelCase__)})) client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , text="There was an issue running the tests." , blocks=lowerCAmelCase__ , ) def _SCREAMING_SNAKE_CASE ( self : Tuple): print("Sending the following payload") print(json.dumps({"blocks": json.loads(self.payload)})) SCREAMING_SNAKE_CASE_: Optional[Any] = F"{self.n_failures} failures out of {self.n_tests} tests," if self.n_failures else "All tests passed." SCREAMING_SNAKE_CASE_: List[Any] = client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , blocks=self.payload , text=lowerCAmelCase__ , ) def _SCREAMING_SNAKE_CASE ( self : Dict , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any]): SCREAMING_SNAKE_CASE_: Dict = "" for key, value in failures.items(): SCREAMING_SNAKE_CASE_: str = value[:200] + " [Truncated]" if len(lowerCAmelCase__) > 250 else value failures_text += F"*{key}*\n_{value}_\n\n" SCREAMING_SNAKE_CASE_: Any = job_name SCREAMING_SNAKE_CASE_: List[Any] = {"type": "section", "text": {"type": "mrkdwn", "text": text}} if job_link is not None: SCREAMING_SNAKE_CASE_: Tuple = { "type": "button", "text": {"type": "plain_text", "text": "GitHub Action job", "emoji": True}, "url": job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def _SCREAMING_SNAKE_CASE ( self : Any): if self.thread_ts is None: raise ValueError("Can only post reply if a post has been made.") SCREAMING_SNAKE_CASE_: Tuple = self.doc_test_results.pop("job_link") self.doc_test_results.pop("failures") self.doc_test_results.pop("success") self.doc_test_results.pop("time_spent") SCREAMING_SNAKE_CASE_: Any = sorted(self.doc_test_results.items() , key=lambda lowerCAmelCase__: t[0]) for job, job_result in sorted_dict: if len(job_result["failures"]): SCREAMING_SNAKE_CASE_: Union[str, Any] = F"*Num failures* :{len(job_result['failed'])} \n" SCREAMING_SNAKE_CASE_: Optional[Any] = job_result["failures"] SCREAMING_SNAKE_CASE_: Optional[Any] = self.get_reply_blocks(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , text=lowerCAmelCase__) print("Sending the following reply") print(json.dumps({"blocks": blocks})) client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"] , text=F"Results for {job}" , blocks=lowerCAmelCase__ , thread_ts=self.thread_ts["ts"] , ) time.sleep(1) def A_ ( ): SCREAMING_SNAKE_CASE_: Tuple = os.environ["GITHUB_RUN_ID"] SCREAMING_SNAKE_CASE_: Any = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100" SCREAMING_SNAKE_CASE_: List[Any] = requests.get(_UpperCAmelCase ).json() SCREAMING_SNAKE_CASE_: Optional[Any] = {} try: jobs.update({job["name"]: job["html_url"] for job in result["jobs"]} ) SCREAMING_SNAKE_CASE_: Any = math.ceil((result["total_count"] - 1_00) / 1_00 ) for i in range(_UpperCAmelCase ): SCREAMING_SNAKE_CASE_: str = requests.get(url + f"&page={i + 2}" ).json() jobs.update({job["name"]: job["html_url"] for job in result["jobs"]} ) return jobs except Exception as e: print("Unknown error, could not fetch links." , _UpperCAmelCase ) return {} def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[Any] = {} if os.path.exists(_UpperCAmelCase ): SCREAMING_SNAKE_CASE_: List[str] = os.listdir(_UpperCAmelCase ) for file in files: try: with open(os.path.join(_UpperCAmelCase , _UpperCAmelCase ) , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE_: Dict = f.read() except UnicodeDecodeError as e: raise ValueError(f"Could not open {os.path.join(_UpperCAmelCase , _UpperCAmelCase )}." ) from e return _artifact def A_ ( ): class __lowercase : """simple docstring""" def __init__( self : List[str] , lowerCAmelCase__ : str): SCREAMING_SNAKE_CASE_: Dict = name SCREAMING_SNAKE_CASE_: List[str] = [] def __str__( self : Optional[Any]): return self.name def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase__ : str): self.paths.append({"name": self.name, "path": path}) SCREAMING_SNAKE_CASE_: Dict[str, Artifact] = {} SCREAMING_SNAKE_CASE_: List[Any] = filter(os.path.isdir , os.listdir() ) for directory in directories: SCREAMING_SNAKE_CASE_: Dict = directory if artifact_name not in _available_artifacts: SCREAMING_SNAKE_CASE_: Tuple = Artifact(_UpperCAmelCase ) _available_artifacts[artifact_name].add_path(_UpperCAmelCase ) return _available_artifacts if __name__ == "__main__": lowerCAmelCase : Tuple = get_job_links() lowerCAmelCase : Optional[Any] = retrieve_available_artifacts() lowerCAmelCase : Any = collections.OrderedDict( [ ("""*.py""", """API Examples"""), ("""*.md""", """MD Examples"""), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' lowerCAmelCase : int = { v: { """failed""": [], """failures""": {}, } for v in docs.values() } # Link to the GitHub Action job lowerCAmelCase : Optional[int] = github_actions_job_links.get("""run_doctests""") lowerCAmelCase : List[Any] = available_artifacts["""doc_tests_gpu_test_reports"""].paths[0] lowerCAmelCase : Any = retrieve_artifact(artifact_path["""name"""]) if "stats" in artifact: lowerCAmelCase , lowerCAmelCase , lowerCAmelCase : List[str] = handle_test_results(artifact["""stats"""]) lowerCAmelCase : List[str] = failed lowerCAmelCase : Any = success lowerCAmelCase : Dict = time_spent[1:-1] + """, """ lowerCAmelCase : str = extract_first_line_failure(artifact["""failures_short"""]) for line in artifact["summary_short"].split("""\n"""): if re.search("""FAILED""", line): lowerCAmelCase : Tuple = line.replace("""FAILED """, """""") lowerCAmelCase : str = line.split()[0].replace("""\n""", """""") if "::" in line: lowerCAmelCase , lowerCAmelCase : Optional[int] = line.split("""::""") else: lowerCAmelCase , lowerCAmelCase : str = line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): lowerCAmelCase : str = docs[file_regex] doc_test_results[category]["failed"].append(test) lowerCAmelCase : str = all_failures[test] if test in all_failures else """N/A""" lowerCAmelCase : Any = failure break lowerCAmelCase : Union[str, Any] = Message("""🤗 Results of the doc tests.""", doc_test_results) message.post() message.post_reply()
671
0
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # and perform gradient accumulation # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## lowerCamelCase__ : str = 16 lowerCamelCase__ : List[Any] = 32 def UpperCAmelCase_ ( __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : int = 16 ) -> Dict: SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained('bert-base-cased' ) SCREAMING_SNAKE_CASE_ = load_dataset('glue' , 'mrpc' ) def tokenize_function(__UpperCAmelCase : Tuple ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE_ = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE_ = datasets.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE_ = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(__UpperCAmelCase : str ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE_ = 1_28 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE_ = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE_ = 8 else: SCREAMING_SNAKE_CASE_ = None return tokenizer.pad( _UpperCAmelCase , padding='longest' , max_length=_UpperCAmelCase , pad_to_multiple_of=_UpperCAmelCase , return_tensors='pt' , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE_ = DataLoader( tokenized_datasets['train'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase ) SCREAMING_SNAKE_CASE_ = DataLoader( tokenized_datasets['validation'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1": from accelerate.test_utils.training import mocked_dataloaders lowerCamelCase__ : Optional[int] = mocked_dataloaders # noqa: F811 def UpperCAmelCase_ ( __UpperCAmelCase : Tuple , __UpperCAmelCase : Union[str, Any] ) -> int: # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS' , _UpperCAmelCase ) == "1": SCREAMING_SNAKE_CASE_ = 2 # New Code # SCREAMING_SNAKE_CASE_ = int(args.gradient_accumulation_steps ) # Initialize accelerator SCREAMING_SNAKE_CASE_ = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=_UpperCAmelCase ) if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1: raise NotImplementedError( 'Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`' ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE_ = config["lr"] SCREAMING_SNAKE_CASE_ = int(config['num_epochs'] ) SCREAMING_SNAKE_CASE_ = int(config['seed'] ) SCREAMING_SNAKE_CASE_ = int(config['batch_size'] ) SCREAMING_SNAKE_CASE_ = evaluate.load('glue' , 'mrpc' ) set_seed(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_ = get_dataloaders(_UpperCAmelCase , _UpperCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE_ = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=_UpperCAmelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE_ = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE_ = AdamW(params=model.parameters() , lr=_UpperCAmelCase ) # Instantiate scheduler SCREAMING_SNAKE_CASE_ = get_linear_schedule_with_warmup( optimizer=_UpperCAmelCase , num_warmup_steps=1_00 , num_training_steps=(len(_UpperCAmelCase ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE_ = accelerator.prepare( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) # Now we train the model for epoch in range(_UpperCAmelCase ): model.train() for step, batch in enumerate(_UpperCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(_UpperCAmelCase ): SCREAMING_SNAKE_CASE_ = model(**_UpperCAmelCase ) SCREAMING_SNAKE_CASE_ = output.loss accelerator.backward(_UpperCAmelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(_UpperCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ = model(**_UpperCAmelCase ) SCREAMING_SNAKE_CASE_ = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE_ = accelerator.gather_for_metrics((predictions, batch['labels']) ) metric.add_batch( predictions=_UpperCAmelCase , references=_UpperCAmelCase , ) SCREAMING_SNAKE_CASE_ = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"epoch {epoch}:" , _UpperCAmelCase ) def UpperCAmelCase_ ( ) -> str: SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument( '--mixed_precision' , type=_UpperCAmelCase , default=_UpperCAmelCase , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) # New Code # parser.add_argument( '--gradient_accumulation_steps' , type=_UpperCAmelCase , default=1 , help='The number of minibatches to be ran before gradients are accumulated.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.' ) SCREAMING_SNAKE_CASE_ = parser.parse_args() SCREAMING_SNAKE_CASE_ = {"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(_UpperCAmelCase , _UpperCAmelCase ) if __name__ == "__main__": main()
31
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # and perform gradient accumulation # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## lowerCAmelCase : str = 16 lowerCAmelCase : List[Any] = 32 def A_ ( _UpperCAmelCase , _UpperCAmelCase = 16 ): SCREAMING_SNAKE_CASE_: List[Any] = AutoTokenizer.from_pretrained("bert-base-cased" ) SCREAMING_SNAKE_CASE_: Tuple = load_dataset("glue" , "mrpc" ) def tokenize_function(_UpperCAmelCase ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE_: List[Any] = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE_: str = datasets.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=["idx", "sentence1", "sentence2"] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE_: Optional[Any] = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(_UpperCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE_: List[Any] = 1_28 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE_: Tuple = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE_: int = 8 else: SCREAMING_SNAKE_CASE_: Any = None return tokenizer.pad( _UpperCAmelCase , padding="longest" , max_length=_UpperCAmelCase , pad_to_multiple_of=_UpperCAmelCase , return_tensors="pt" , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE_: Optional[Any] = DataLoader( tokenized_datasets["train"] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple = DataLoader( tokenized_datasets["validation"] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""", None) == "1": from accelerate.test_utils.training import mocked_dataloaders lowerCAmelCase : Optional[int] = mocked_dataloaders # noqa: F811 def A_ ( _UpperCAmelCase , _UpperCAmelCase ): # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS" , _UpperCAmelCase ) == "1": SCREAMING_SNAKE_CASE_: Tuple = 2 # New Code # SCREAMING_SNAKE_CASE_: List[str] = int(args.gradient_accumulation_steps ) # Initialize accelerator SCREAMING_SNAKE_CASE_: int = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=_UpperCAmelCase ) if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1: raise NotImplementedError( "Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE_: Tuple = config["lr"] SCREAMING_SNAKE_CASE_: List[str] = int(config["num_epochs"] ) SCREAMING_SNAKE_CASE_: List[str] = int(config["seed"] ) SCREAMING_SNAKE_CASE_: Optional[int] = int(config["batch_size"] ) SCREAMING_SNAKE_CASE_: str = evaluate.load("glue" , "mrpc" ) set_seed(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[str] = get_dataloaders(_UpperCAmelCase , _UpperCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE_: Union[str, Any] = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=_UpperCAmelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE_: List[Any] = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE_: Union[str, Any] = AdamW(params=model.parameters() , lr=_UpperCAmelCase ) # Instantiate scheduler SCREAMING_SNAKE_CASE_: str = get_linear_schedule_with_warmup( optimizer=_UpperCAmelCase , num_warmup_steps=1_00 , num_training_steps=(len(_UpperCAmelCase ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Dict = accelerator.prepare( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) # Now we train the model for epoch in range(_UpperCAmelCase ): model.train() for step, batch in enumerate(_UpperCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(_UpperCAmelCase ): SCREAMING_SNAKE_CASE_: List[Any] = model(**_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] = output.loss accelerator.backward(_UpperCAmelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(_UpperCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE_: Optional[Any] = model(**_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=_UpperCAmelCase , references=_UpperCAmelCase , ) SCREAMING_SNAKE_CASE_: List[str] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"epoch {epoch}:" , _UpperCAmelCase ) def A_ ( ): SCREAMING_SNAKE_CASE_: str = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=_UpperCAmelCase , default=_UpperCAmelCase , choices=["no", "fp16", "bf16", "fp8"] , help="Whether to use mixed precision. Choose" "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." "and an Nvidia Ampere GPU." , ) # New Code # parser.add_argument( "--gradient_accumulation_steps" , type=_UpperCAmelCase , default=1 , help="The number of minibatches to be ran before gradients are accumulated." , ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) SCREAMING_SNAKE_CASE_: List[Any] = parser.parse_args() SCREAMING_SNAKE_CASE_: Tuple = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(_UpperCAmelCase , _UpperCAmelCase ) if __name__ == "__main__": main()
671
0
"""simple docstring""" class lowerCAmelCase__ : """simple docstring""" def __init__( self : Tuple , lowercase__ : list ): __lowercase : Union[str, Any] = set_counts __lowercase : Optional[Any] = max(lowerCAmelCase__ ) __lowercase : int = len(lowerCAmelCase__ ) __lowercase : Tuple = [1] * num_sets __lowercase : Union[str, Any] = list(range(lowerCAmelCase__ ) ) def snake_case ( self : Optional[int] , lowercase__ : int , lowercase__ : int ): __lowercase : Optional[int] = self.get_parent(lowerCAmelCase__ ) __lowercase : int = self.get_parent(lowerCAmelCase__ ) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] __lowercase : Dict = 0 __lowercase : List[str] = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 __lowercase : Tuple = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] __lowercase : str = 0 __lowercase : Optional[Any] = src_parent __lowercase : str = self.set_counts[src_parent] __lowercase : List[Any] = max(self.max_set , lowerCAmelCase__ ) return True def snake_case ( self : Any , lowercase__ : int ): if self.parents[disj_set] == disj_set: return disj_set __lowercase : Dict = self.get_parent(self.parents[disj_set] ) return self.parents[disj_set]
575
from math import asin, atan, cos, radians, sin, sqrt, tan lowerCAmelCase : Union[str, Any] = 637_8137.0 lowerCAmelCase : int = 635_6752.31_4245 lowerCAmelCase : Union[str, Any] = 6378137 def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: List[Any] = (AXIS_A - AXIS_B) / AXIS_A SCREAMING_SNAKE_CASE_: str = atan((1 - flattening) * tan(radians(_UpperCAmelCase ) ) ) SCREAMING_SNAKE_CASE_: Optional[int] = atan((1 - flattening) * tan(radians(_UpperCAmelCase ) ) ) SCREAMING_SNAKE_CASE_: Any = radians(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Dict = radians(_UpperCAmelCase ) # Equation SCREAMING_SNAKE_CASE_: str = sin((phi_a - phi_a) / 2 ) SCREAMING_SNAKE_CASE_: List[Any] = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda SCREAMING_SNAKE_CASE_: Tuple = sqrt(sin_sq_phi + (cos(_UpperCAmelCase ) * cos(_UpperCAmelCase ) * sin_sq_lambda) ) return 2 * RADIUS * asin(_UpperCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
671
0
'''simple docstring''' def _lowercase ( lowerCamelCase__ ) -> Optional[int]: """simple docstring""" __UpperCAmelCase : Optional[int] = 1 __UpperCAmelCase : Dict = 2 while i * i <= n: __UpperCAmelCase : int = 0 while n % i == 0: n //= i multiplicity += 1 n_divisors *= multiplicity + 1 i += 1 if n > 1: n_divisors *= 2 return n_divisors def _lowercase ( ) -> Optional[int]: """simple docstring""" __UpperCAmelCase : Union[str, Any] = 1 __UpperCAmelCase : Optional[int] = 1 while True: i += 1 t_num += i if count_divisors(_UpperCAmelCase ) > 500: break return t_num if __name__ == "__main__": print(solution())
168
import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): # Initialise PyTorch model SCREAMING_SNAKE_CASE_: List[Any] = BertConfig.from_json_file(_UpperCAmelCase ) print(f"Building PyTorch model from configuration: {config}" ) SCREAMING_SNAKE_CASE_: Tuple = BertForPreTraining(_UpperCAmelCase ) # Load weights from tf checkpoint load_tf_weights_in_bert(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) # Save pytorch-model print(f"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , _UpperCAmelCase ) if __name__ == "__main__": lowerCAmelCase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--bert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained BERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) lowerCAmelCase : Optional[Any] = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
671
0
from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class _lowercase ( UpperCAmelCase_ ): lowercase = ['''image_processor''', '''tokenizer'''] lowercase = '''BridgeTowerImageProcessor''' lowercase = ('''RobertaTokenizer''', '''RobertaTokenizerFast''') def __init__( self : Dict , snake_case : Optional[int] , snake_case : List[Any] ) -> Optional[int]: """simple docstring""" super().__init__(lowerCAmelCase__ , lowerCAmelCase__ ) def __call__( self : Optional[int] , snake_case : str , snake_case : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , snake_case : bool = True , snake_case : Union[bool, str, PaddingStrategy] = False , snake_case : Union[bool, str, TruncationStrategy] = None , snake_case : Optional[int] = None , snake_case : int = 0 , snake_case : Optional[int] = None , snake_case : Optional[bool] = None , snake_case : Optional[bool] = None , snake_case : bool = False , snake_case : bool = False , snake_case : bool = False , snake_case : bool = False , snake_case : bool = True , snake_case : Optional[Union[str, TensorType]] = None , **snake_case : Tuple , ) -> List[Any]: """simple docstring""" UpperCamelCase_ : List[Any] = self.tokenizer( text=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , max_length=lowerCAmelCase__ , stride=lowerCAmelCase__ , pad_to_multiple_of=lowerCAmelCase__ , return_token_type_ids=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , return_overflowing_tokens=lowerCAmelCase__ , return_special_tokens_mask=lowerCAmelCase__ , return_offsets_mapping=lowerCAmelCase__ , return_length=lowerCAmelCase__ , verbose=lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , **lowerCAmelCase__ , ) # add pixel_values + pixel_mask UpperCamelCase_ : List[str] = self.image_processor( lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , do_normalize=lowerCAmelCase__ , do_center_crop=lowerCAmelCase__ , **lowerCAmelCase__ ) encoding.update(lowerCAmelCase__ ) return encoding def SCREAMING_SNAKE_CASE__ ( self : Any , *snake_case : int , **snake_case : Optional[Any] ) -> int: """simple docstring""" return self.tokenizer.batch_decode(*lowerCAmelCase__ , **lowerCAmelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : int , *snake_case : Optional[int] , **snake_case : Tuple ) -> Tuple: """simple docstring""" return self.tokenizer.decode(*lowerCAmelCase__ , **lowerCAmelCase__ ) @property def SCREAMING_SNAKE_CASE__ ( self : int ) -> Tuple: """simple docstring""" UpperCamelCase_ : Optional[Any] = self.tokenizer.model_input_names UpperCamelCase_ : Dict = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
417
import math def A_ ( _UpperCAmelCase ): if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_UpperCAmelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def A_ ( _UpperCAmelCase = 0.1 ): SCREAMING_SNAKE_CASE_: Union[str, Any] = 3 SCREAMING_SNAKE_CASE_: Optional[int] = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ): primes += is_prime(_UpperCAmelCase ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
671
0
"""simple docstring""" import collections import os import re from pathlib import Path __A = """src/transformers""" # Matches is_xxx_available() __A = re.compile(R'''is\_([a-z_]*)_available()''') # Catches a one-line _import_struct = {xxx} __A = re.compile(R'''^_import_structure\s+=\s+\{([^\}]+)\}''') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] __A = re.compile(R'''\s+\"\S*\":\s+\[([^\]]*)\]''') # Catches a line if not is_foo_available __A = re.compile(R'''^\s*if\s+not\s+is\_[a-z_]*\_available\(\)''') # Catches a line _import_struct["bla"].append("foo") __A = re.compile(R'''^\s*_import_structure\[\"\S*\"\]\.append\(\"(\S*)\"\)''') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] __A = re.compile(R'''^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]''') # Catches a line with an object between quotes and a comma: "MyModel", __A = re.compile(R'''^\s+\"([^\"]+)\",''') # Catches a line with objects between brackets only: ["foo", "bar"], __A = re.compile(R'''^\s+\[([^\]]+)\]''') # Catches a line with from foo import bar, bla, boo __A = re.compile(R'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''') # Catches a line with try: __A = re.compile(R'''^\s*try:''') # Catches a line with else: __A = re.compile(R'''^\s*else:''') def lowercase_ ( _lowerCamelCase: Optional[Any] ) -> int: '''simple docstring''' if _re_test_backend.search(_UpperCAmelCase ) is None: return None __lowerCamelCase : str = [b[0] for b in _re_backend.findall(_UpperCAmelCase )] backends.sort() return "_and_".join(_UpperCAmelCase ) def lowercase_ ( _lowerCamelCase: Dict ) -> Union[str, Any]: '''simple docstring''' with open(_UpperCAmelCase , "r" , encoding="utf-8" , newline="\n" ) as f: __lowerCamelCase : List[str] = f.readlines() __lowerCamelCase : Any = 0 while line_index < len(_UpperCAmelCase ) and not lines[line_index].startswith("_import_structure = {" ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(_UpperCAmelCase ): return None # First grab the objects without a specific backend in _import_structure __lowerCamelCase : Tuple = [] while not lines[line_index].startswith("if TYPE_CHECKING" ) and find_backend(lines[line_index] ) is None: __lowerCamelCase : List[str] = lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(_UpperCAmelCase ): __lowerCamelCase : List[str] = _re_one_line_import_struct.search(_UpperCAmelCase ).groups()[0] __lowerCamelCase : List[Any] = re.findall(r"\[([^\]]+)\]" , _UpperCAmelCase ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(", " )] ) line_index += 1 continue __lowerCamelCase : Dict = _re_import_struct_key_value.search(_UpperCAmelCase ) if single_line_import_search is not None: __lowerCamelCase : Any = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(", " ) if len(_UpperCAmelCase ) > 0] objects.extend(_UpperCAmelCase ) elif line.startswith(" " * 8 + "\"" ): objects.append(line[9:-3] ) line_index += 1 __lowerCamelCase : str = {"none": objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith("if TYPE_CHECKING" ): # If the line is an if not is_backend_available, we grab all objects associated. __lowerCamelCase : Union[str, Any] = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: __lowerCamelCase : str = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 __lowerCamelCase : int = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(" " * 4 ): __lowerCamelCase : Tuple = lines[line_index] if _re_import_struct_add_one.search(_UpperCAmelCase ) is not None: objects.append(_re_import_struct_add_one.search(_UpperCAmelCase ).groups()[0] ) elif _re_import_struct_add_many.search(_UpperCAmelCase ) is not None: __lowerCamelCase : Optional[int] = _re_import_struct_add_many.search(_UpperCAmelCase ).groups()[0].split(", " ) __lowerCamelCase : str = [obj[1:-1] for obj in imports if len(_UpperCAmelCase ) > 0] objects.extend(_UpperCAmelCase ) elif _re_between_brackets.search(_UpperCAmelCase ) is not None: __lowerCamelCase : Optional[int] = _re_between_brackets.search(_UpperCAmelCase ).groups()[0].split(", " ) __lowerCamelCase : Optional[Any] = [obj[1:-1] for obj in imports if len(_UpperCAmelCase ) > 0] objects.extend(_UpperCAmelCase ) elif _re_quote_object.search(_UpperCAmelCase ) is not None: objects.append(_re_quote_object.search(_UpperCAmelCase ).groups()[0] ) elif line.startswith(" " * 8 + "\"" ): objects.append(line[9:-3] ) elif line.startswith(" " * 12 + "\"" ): objects.append(line[13:-3] ) line_index += 1 __lowerCamelCase : Dict = objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend __lowerCamelCase : List[Any] = [] while ( line_index < len(_UpperCAmelCase ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith("else" ) ): __lowerCamelCase : Optional[int] = lines[line_index] __lowerCamelCase : Optional[Any] = _re_import.search(_UpperCAmelCase ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(", " ) ) elif line.startswith(" " * 8 ): objects.append(line[8:-2] ) line_index += 1 __lowerCamelCase : Any = {"none": objects} # Let's continue with backend-specific objects while line_index < len(_UpperCAmelCase ): # If the line is an if is_backend_available, we grab all objects associated. __lowerCamelCase : int = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: __lowerCamelCase : Optional[Any] = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 __lowerCamelCase : int = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(" " * 8 ): __lowerCamelCase : str = lines[line_index] __lowerCamelCase : List[Any] = _re_import.search(_UpperCAmelCase ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(", " ) ) elif line.startswith(" " * 12 ): objects.append(line[12:-2] ) line_index += 1 __lowerCamelCase : Optional[int] = objects else: line_index += 1 return import_dict_objects, type_hint_objects def lowercase_ ( _lowerCamelCase: Union[str, Any] , _lowerCamelCase: str ) -> Union[str, Any]: '''simple docstring''' def find_duplicates(_lowerCamelCase: Any ): return [k for k, v in collections.Counter(_UpperCAmelCase ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] __lowerCamelCase : Dict = [] for key in import_dict_objects.keys(): __lowerCamelCase : List[str] = find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(F"""Duplicate _import_structure definitions for: {duplicate_imports}""" ) __lowerCamelCase : Optional[Any] = find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(F"""Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}""" ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): __lowerCamelCase : Optional[Any] = "base imports" if key == "none" else F"""{key} backend""" errors.append(F"""Differences for {name}:""" ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(F""" {a} in TYPE_HINT but not in _import_structure.""" ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(F""" {a} in _import_structure but not in TYPE_HINT.""" ) return errors def lowercase_ ( ) -> int: '''simple docstring''' __lowerCamelCase : List[Any] = [] for root, _, files in os.walk(_UpperCAmelCase ): if "__init__.py" in files: __lowerCamelCase : List[str] = os.path.join(_UpperCAmelCase , "__init__.py" ) __lowerCamelCase : str = parse_init(_UpperCAmelCase ) if objects is not None: __lowerCamelCase : Any = analyze_results(*_UpperCAmelCase ) if len(_UpperCAmelCase ) > 0: __lowerCamelCase : List[str] = F"""Problem in {fname}, both halves do not define the same objects.\n{errors[0]}""" failures.append("\n".join(_UpperCAmelCase ) ) if len(_UpperCAmelCase ) > 0: raise ValueError("\n\n".join(_UpperCAmelCase ) ) def lowercase_ ( ) -> Any: '''simple docstring''' __lowerCamelCase : Dict = [] for path, directories, files in os.walk(_UpperCAmelCase ): for folder in directories: # Ignore private modules if folder.startswith("_" ): directories.remove(_UpperCAmelCase ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(_UpperCAmelCase ) / folder).glob("*.py" ) ) ) == 0: continue __lowerCamelCase : Tuple = str((Path(_UpperCAmelCase ) / folder).relative_to(_UpperCAmelCase ) ) __lowerCamelCase : str = short_path.replace(os.path.sep , "." ) submodules.append(_UpperCAmelCase ) for fname in files: if fname == "__init__.py": continue __lowerCamelCase : Optional[int] = str((Path(_UpperCAmelCase ) / fname).relative_to(_UpperCAmelCase ) ) __lowerCamelCase : Optional[int] = short_path.replace(".py" , "" ).replace(os.path.sep , "." ) if len(submodule.split("." ) ) == 1: submodules.append(_UpperCAmelCase ) return submodules __A = [ """convert_pytorch_checkpoint_to_tf2""", """modeling_flax_pytorch_utils""", """models.esm.openfold_utils""", ] def lowercase_ ( ) -> Optional[Any]: '''simple docstring''' from transformers.utils import direct_transformers_import __lowerCamelCase : Optional[Any] = direct_transformers_import(_UpperCAmelCase ) __lowerCamelCase : Optional[int] = set(transformers._import_structure.keys() ) # This contains all the base keys of the _import_structure object defined in the init, but if the user is missing # some optional dependencies, they may not have all of them. Thus we read the init to read all additions and # (potentiall re-) add them. with open(os.path.join(_UpperCAmelCase , "__init__.py" ) , "r" ) as f: __lowerCamelCase : Union[str, Any] = f.read() import_structure_keys.update(set(re.findall(r"import_structure\[\"([^\"]*)\"\]" , _UpperCAmelCase ) ) ) __lowerCamelCase : Optional[Any] = [ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in import_structure_keys ] if len(_UpperCAmelCase ) > 0: __lowerCamelCase : Tuple = "\n".join(F"""- {module}""" for module in module_not_registered ) raise ValueError( "The following submodules are not properly registed in the main init of Transformers:\n" F"""{list_of_modules}\n""" "Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value." ) if __name__ == "__main__": check_all_inits() check_submodules()
646
import re def A_ ( _UpperCAmelCase ): return [char.split() for char in re.split(R"[^ a-z A-Z 0-9 \s]" , str_ )] def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: int = split_input(str_ ) return "".join( ["".join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): try: SCREAMING_SNAKE_CASE_: List[Any] = split_input(_UpperCAmelCase ) if upper: SCREAMING_SNAKE_CASE_: List[str] = "".join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: SCREAMING_SNAKE_CASE_: Optional[int] = "".join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def A_ ( _UpperCAmelCase ): return to_simple_case(_UpperCAmelCase ) def A_ ( _UpperCAmelCase ): try: SCREAMING_SNAKE_CASE_: Optional[int] = to_simple_case(_UpperCAmelCase ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def A_ ( _UpperCAmelCase , _UpperCAmelCase ): return to_complex_case(_UpperCAmelCase , _UpperCAmelCase , "_" ) def A_ ( _UpperCAmelCase , _UpperCAmelCase ): return to_complex_case(_UpperCAmelCase , _UpperCAmelCase , "-" ) if __name__ == "__main__": __import__("""doctest""").testmod()
671
0
from __future__ import annotations from math import ceil, floor, sqrt def lowerCAmelCase_ (lowercase__ : Tuple = 2_00_00_00 ) -> Any: '''simple docstring''' lowerCAmelCase__ = [0] lowerCAmelCase__ = 42 for idx in range(1 , ceil(sqrt(target * 2 ) * 1.1 ) ): triangle_numbers.append(triangle_numbers[-1] + idx ) # we want this to be as close as possible to target lowerCAmelCase__ = 0 # the area corresponding to the grid that gives the product closest to target lowerCAmelCase__ = 0 # an estimate of b, using the quadratic formula lowerCAmelCase__ = 42 # the largest integer less than b_estimate lowerCAmelCase__ = 42 # the largest integer less than b_estimate lowerCAmelCase__ = 42 # the triangle number corresponding to b_floor lowerCAmelCase__ = 42 # the triangle number corresponding to b_ceil lowerCAmelCase__ = 42 for idx_a, triangle_a in enumerate(triangle_numbers[1:] , 1 ): lowerCAmelCase__ = (-1 + sqrt(1 + 8 * target / triangle_a )) / 2 lowerCAmelCase__ = floor(_UpperCAmelCase ) lowerCAmelCase__ = ceil(_UpperCAmelCase ) lowerCAmelCase__ = triangle_numbers[b_floor] lowerCAmelCase__ = triangle_numbers[b_ceil] if abs(target - triangle_b_first_guess * triangle_a ) < abs( target - best_product ): lowerCAmelCase__ = triangle_b_first_guess * triangle_a lowerCAmelCase__ = idx_a * b_floor if abs(target - triangle_b_second_guess * triangle_a ) < abs( target - best_product ): lowerCAmelCase__ = triangle_b_second_guess * triangle_a lowerCAmelCase__ = idx_a * b_ceil return area if __name__ == "__main__": print(F'''{solution() = }''')
668
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING lowerCAmelCase : Union[str, Any] = logging.get_logger(__name__) class __lowercase ( UpperCAmelCase_ ): """simple docstring""" _UpperCAmelCase : List[Any] = '''upernet''' def __init__( self : Any , lowerCAmelCase__ : Union[str, Any]=None , lowerCAmelCase__ : List[str]=512 , lowerCAmelCase__ : Any=0.02 , lowerCAmelCase__ : str=[1, 2, 3, 6] , lowerCAmelCase__ : Optional[Any]=True , lowerCAmelCase__ : Dict=0.4 , lowerCAmelCase__ : int=384 , lowerCAmelCase__ : Union[str, Any]=256 , lowerCAmelCase__ : Any=1 , lowerCAmelCase__ : Tuple=False , lowerCAmelCase__ : List[str]=255 , **lowerCAmelCase__ : List[str] , ): super().__init__(**lowerCAmelCase__) if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.") SCREAMING_SNAKE_CASE_: Dict = CONFIG_MAPPING["resnet"](out_features=["stage1", "stage2", "stage3", "stage4"]) elif isinstance(lowerCAmelCase__ , lowerCAmelCase__): SCREAMING_SNAKE_CASE_: str = backbone_config.get("model_type") SCREAMING_SNAKE_CASE_: str = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE_: Tuple = config_class.from_dict(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: str = backbone_config SCREAMING_SNAKE_CASE_: Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_: Dict = initializer_range SCREAMING_SNAKE_CASE_: Any = pool_scales SCREAMING_SNAKE_CASE_: Optional[Any] = use_auxiliary_head SCREAMING_SNAKE_CASE_: str = auxiliary_loss_weight SCREAMING_SNAKE_CASE_: List[Any] = auxiliary_in_channels SCREAMING_SNAKE_CASE_: Union[str, Any] = auxiliary_channels SCREAMING_SNAKE_CASE_: Dict = auxiliary_num_convs SCREAMING_SNAKE_CASE_: str = auxiliary_concat_input SCREAMING_SNAKE_CASE_: Dict = loss_ignore_index def _SCREAMING_SNAKE_CASE ( self : Tuple): SCREAMING_SNAKE_CASE_: Tuple = copy.deepcopy(self.__dict__) SCREAMING_SNAKE_CASE_: int = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE_: Optional[int] = self.__class__.model_type return output
671
0
from ..utils import DummyObject, requires_backends class snake_case__ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' __A = ['''onnx'''] def __init__( self : List[str] , *lowerCAmelCase_ : Optional[int] , **lowerCAmelCase_ : Any ) -> Any: requires_backends(self , ['''onnx'''] ) @classmethod def UpperCamelCase ( cls : int , *lowerCAmelCase_ : List[Any] , **lowerCAmelCase_ : Any ) -> Optional[int]: requires_backends(cls , ['''onnx'''] ) @classmethod def UpperCamelCase ( cls : Optional[Any] , *lowerCAmelCase_ : Tuple , **lowerCAmelCase_ : Any ) -> List[str]: requires_backends(cls , ['''onnx'''] )
121
import pickle import unittest import torch from accelerate import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils import require_cpu @require_cpu class __lowercase ( unittest.TestCase ): """simple docstring""" def _SCREAMING_SNAKE_CASE ( self : Any): SCREAMING_SNAKE_CASE_: List[str] = torch.nn.Linear(10 , 10) SCREAMING_SNAKE_CASE_: Union[str, Any] = torch.optim.SGD(model.parameters() , 0.1) SCREAMING_SNAKE_CASE_: Any = Accelerator() SCREAMING_SNAKE_CASE_: List[str] = accelerator.prepare(lowerCAmelCase__) try: pickle.loads(pickle.dumps(lowerCAmelCase__)) except Exception as e: self.fail(F"Accelerated optimizer pickling failed with {e}") AcceleratorState._reset_state()
671
0
import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImgaImgPipeline, UNetaDConditionModel from diffusers.pipelines.pipeline_utils import DiffusionPipeline from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import ( enable_full_determinism, floats_tensor, load_image, load_numpy, require_torch_gpu, skip_mps, slow, torch_device, ) from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class _lowerCamelCase( UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, unittest.TestCase ): lowercase_ : Optional[int] = StableUnCLIPImgaImgPipeline lowercase_ : Union[str, Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS lowercase_ : Dict = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS lowercase_ : Tuple = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowercase_ : List[Any] = frozenset([] ) def UpperCamelCase ( self) -> List[str]: """simple docstring""" _lowercase : Tuple = 32 _lowercase : Union[str, Any] = embedder_hidden_size # image encoding components _lowercase : Union[str, Any] = CLIPImageProcessor(crop_size=32, size=32) torch.manual_seed(0) _lowercase : str = CLIPVisionModelWithProjection( CLIPVisionConfig( hidden_size=lowerCAmelCase__, projection_dim=lowerCAmelCase__, num_hidden_layers=5, num_attention_heads=4, image_size=32, intermediate_size=37, patch_size=1, )) # regular denoising components torch.manual_seed(0) _lowercase : int = StableUnCLIPImageNormalizer(embedding_dim=lowerCAmelCase__) _lowercase : Optional[int] = DDPMScheduler(beta_schedule='squaredcos_cap_v2') torch.manual_seed(0) _lowercase : Union[str, Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip') torch.manual_seed(0) _lowercase : str = CLIPTextModel( CLIPTextConfig( bos_token_id=0, eos_token_id=2, hidden_size=lowerCAmelCase__, projection_dim=32, intermediate_size=37, layer_norm_eps=1E-05, num_attention_heads=4, num_hidden_layers=5, pad_token_id=1, vocab_size=10_00, )) torch.manual_seed(0) _lowercase : Optional[Any] = UNetaDConditionModel( sample_size=32, in_channels=4, out_channels=4, down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D'), up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D'), block_out_channels=(32, 64), attention_head_dim=(2, 4), class_embed_type='projection', projection_class_embeddings_input_dim=embedder_projection_dim * 2, cross_attention_dim=lowerCAmelCase__, layers_per_block=1, upcast_attention=lowerCAmelCase__, use_linear_projection=lowerCAmelCase__, ) torch.manual_seed(0) _lowercase : Optional[int] = DDIMScheduler( beta_schedule='scaled_linear', beta_start=0.0_0_0_8_5, beta_end=0.0_1_2, prediction_type='v_prediction', set_alpha_to_one=lowerCAmelCase__, steps_offset=1, ) torch.manual_seed(0) _lowercase : Tuple = AutoencoderKL() _lowercase : Dict = { # image encoding components "feature_extractor": feature_extractor, "image_encoder": image_encoder.eval(), # image noising components "image_normalizer": image_normalizer.eval(), "image_noising_scheduler": image_noising_scheduler, # regular denoising components "tokenizer": tokenizer, "text_encoder": text_encoder.eval(), "unet": unet.eval(), "scheduler": scheduler, "vae": vae.eval(), } return components def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase=0, lowerCamelCase=True) -> str: """simple docstring""" if str(lowerCAmelCase__).startswith('mps'): _lowercase : Optional[Any] = torch.manual_seed(lowerCAmelCase__) else: _lowercase : Any = torch.Generator(device=lowerCAmelCase__).manual_seed(lowerCAmelCase__) _lowercase : str = floats_tensor((1, 3, 32, 32), rng=random.Random(lowerCAmelCase__)).to(lowerCAmelCase__) if pil_image: _lowercase : Tuple = input_image * 0.5 + 0.5 _lowercase : List[Any] = input_image.clamp(0, 1) _lowercase : Optional[Any] = input_image.cpu().permute(0, 2, 3, 1).float().numpy() _lowercase : Any = DiffusionPipeline.numpy_to_pil(lowerCAmelCase__)[0] return { "prompt": "An anime racoon running a marathon", "image": input_image, "generator": generator, "num_inference_steps": 2, "output_type": "np", } @skip_mps def UpperCamelCase ( self) -> Any: """simple docstring""" _lowercase : Optional[int] = "cpu" # ensure determinism for the device-dependent torch.Generator _lowercase : str = self.get_dummy_components() _lowercase : List[Any] = StableUnCLIPImgaImgPipeline(**lowerCAmelCase__) _lowercase : List[Any] = sd_pipe.to(lowerCAmelCase__) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__) _lowercase : Optional[int] = self.get_dummy_inputs(lowerCAmelCase__) inputs.update({'image_embeds': None}) _lowercase : List[str] = sd_pipe(**lowerCAmelCase__).images _lowercase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _lowercase : Optional[int] = np.array([0.3_8_7_2, 0.7_2_2_4, 0.5_6_0_1, 0.4_7_4_1, 0.6_8_7_2, 0.5_8_1_4, 0.4_6_3_6, 0.3_8_6_7, 0.5_0_7_8]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-3 def UpperCamelCase ( self) -> Any: """simple docstring""" _lowercase : Optional[int] = torch_device in ["cpu", "mps"] self._test_attention_slicing_forward_pass(test_max_difference=lowerCAmelCase__) def UpperCamelCase ( self) -> str: """simple docstring""" _lowercase : Union[str, Any] = torch_device in ["cpu", "mps"] self._test_inference_batch_single_identical(test_max_difference=lowerCAmelCase__) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available(), reason='XFormers attention is only available with CUDA and `xformers` installed', ) def UpperCamelCase ( self) -> Any: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(test_max_difference=lowerCAmelCase__) @slow @require_torch_gpu class _lowerCamelCase( unittest.TestCase ): def UpperCamelCase ( self) -> List[Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase ( self) -> List[Any]: """simple docstring""" _lowercase : Optional[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png') _lowercase : List[str] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy') _lowercase : Dict = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-l-img2img', torch_dtype=torch.floataa) pipe.to(lowerCAmelCase__) pipe.set_progress_bar_config(disable=lowerCAmelCase__) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() _lowercase : Tuple = torch.Generator(device='cpu').manual_seed(0) _lowercase : Tuple = pipe(lowerCAmelCase__, 'anime turle', generator=lowerCAmelCase__, output_type='np') _lowercase : int = output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(lowerCAmelCase__, lowerCAmelCase__) def UpperCamelCase ( self) -> int: """simple docstring""" _lowercase : Any = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png') _lowercase : str = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy') _lowercase : Tuple = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-h-img2img', torch_dtype=torch.floataa) pipe.to(lowerCAmelCase__) pipe.set_progress_bar_config(disable=lowerCAmelCase__) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() _lowercase : Optional[Any] = torch.Generator(device='cpu').manual_seed(0) _lowercase : str = pipe(lowerCAmelCase__, 'anime turle', generator=lowerCAmelCase__, output_type='np') _lowercase : Union[str, Any] = output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(lowerCAmelCase__, lowerCAmelCase__) def UpperCamelCase ( self) -> Dict: """simple docstring""" _lowercase : int = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png') torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() _lowercase : List[str] = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-h-img2img', torch_dtype=torch.floataa) _lowercase : List[str] = pipe.to(lowerCAmelCase__) pipe.set_progress_bar_config(disable=lowerCAmelCase__) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() _lowercase : Any = pipe( lowerCAmelCase__, 'anime turtle', num_inference_steps=2, output_type='np', ) _lowercase : Union[str, Any] = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
89
from itertools import count def A_ ( _UpperCAmelCase = 50 ): SCREAMING_SNAKE_CASE_: Union[str, Any] = [1] * min_block_length for n in count(_UpperCAmelCase ): fill_count_functions.append(1 ) for block_length in range(_UpperCAmelCase , 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() = }''')
671
0
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import tensorflow as tf from transformers import AutoTokenizer, TFAutoModelForSeqaSeqLM @require_tf @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): @slow def A_ ( self ) -> List[Any]: '''simple docstring''' _UpperCamelCase = TFAutoModelForSeqaSeqLM.from_pretrained("""google/mt5-small""" ) _UpperCamelCase = AutoTokenizer.from_pretrained("""google/mt5-small""" ) _UpperCamelCase = tokenizer("""Hello there""" , return_tensors="""tf""" ).input_ids _UpperCamelCase = tokenizer("""Hi I am""" , return_tensors="""tf""" ).input_ids _UpperCamelCase = model(lowerCAmelCase__ , labels=lowerCAmelCase__ ).loss _UpperCamelCase = -tf.math.reduce_mean(lowerCAmelCase__ ).numpy() _UpperCamelCase = -21.22_8168 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 2e-4 )
612
def A_ ( _UpperCAmelCase ): if not isinstance(_UpperCAmelCase , _UpperCAmelCase ): raise TypeError("only integers accepted as input" ) else: SCREAMING_SNAKE_CASE_: List[Any] = str(abs(_UpperCAmelCase ) ) SCREAMING_SNAKE_CASE_: Tuple = [list(_UpperCAmelCase ) for char in range(len(_UpperCAmelCase ) )] for index in range(len(_UpperCAmelCase ) ): num_transpositions[index].pop(_UpperCAmelCase ) return max( int("".join(list(_UpperCAmelCase ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__("""doctest""").testmod()
671
0
"""simple docstring""" import inspect import unittest from transformers import RegNetConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import RegNetForImageClassification, RegNetModel from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __lowerCamelCase : '''simple docstring''' def __init__( self : List[Any] , a_ : List[Any] , a_ : Tuple=3 , a_ : Any=32 , a_ : Optional[int]=3 , a_ : Optional[Any]=10 , a_ : Optional[Any]=[10, 20, 30, 40] , a_ : str=[1, 1, 2, 1] , a_ : List[Any]=True , a_ : Optional[Any]=True , a_ : List[Any]="relu" , a_ : Union[str, Any]=3 , a_ : List[Any]=None , ): lowerCAmelCase_ : Optional[int] = parent lowerCAmelCase_ : Union[str, Any] = batch_size lowerCAmelCase_ : List[Any] = image_size lowerCAmelCase_ : Tuple = num_channels lowerCAmelCase_ : List[str] = embeddings_size lowerCAmelCase_ : Dict = hidden_sizes lowerCAmelCase_ : int = depths lowerCAmelCase_ : Optional[Any] = is_training lowerCAmelCase_ : Optional[Any] = use_labels lowerCAmelCase_ : Dict = hidden_act lowerCAmelCase_ : int = num_labels lowerCAmelCase_ : Tuple = scope lowerCAmelCase_ : str = len(lowerCAmelCase__ ) def lowerCamelCase ( self : Optional[int] ): lowerCAmelCase_ : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase_ : List[str] = None if self.use_labels: lowerCAmelCase_ : Dict = ids_tensor([self.batch_size] , self.num_labels ) lowerCAmelCase_ : Any = self.get_config() return config, pixel_values, labels def lowerCamelCase ( self : Optional[int] ): return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def lowerCamelCase ( self : int , a_ : List[str] , a_ : List[str] , a_ : Optional[Any] ): lowerCAmelCase_ : Optional[int] = RegNetModel(config=lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() lowerCAmelCase_ : str = model(lowerCAmelCase__ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowerCamelCase ( self : str , a_ : Optional[Any] , a_ : Optional[int] , a_ : Dict ): lowerCAmelCase_ : str = self.num_labels lowerCAmelCase_ : str = RegNetForImageClassification(lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() lowerCAmelCase_ : Optional[Any] = model(lowerCAmelCase__ , labels=lowerCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase ( self : Union[str, Any] ): lowerCAmelCase_ : List[Any] = self.prepare_config_and_inputs() lowerCAmelCase_ : str = config_and_inputs lowerCAmelCase_ : List[str] = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __lowerCamelCase ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' a_ : List[Any] = (RegNetModel, RegNetForImageClassification) if is_torch_available() else () a_ : int = ( {'''feature-extraction''': RegNetModel, '''image-classification''': RegNetForImageClassification} if is_torch_available() else {} ) a_ : Union[str, Any] = False a_ : Optional[Any] = False a_ : List[str] = False a_ : Any = False def lowerCamelCase ( self : Tuple ): lowerCAmelCase_ : int = RegNetModelTester(self ) lowerCAmelCase_ : List[str] = ConfigTester(self , config_class=lowerCAmelCase__ , has_text_modality=lowerCAmelCase__ ) def lowerCamelCase ( self : int ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowerCamelCase ( self : str ): return @unittest.skip(reason="RegNet does not use inputs_embeds" ) def lowerCamelCase ( self : int ): pass @unittest.skip(reason="RegNet does not support input and output embeddings" ) def lowerCamelCase ( self : Any ): pass def lowerCamelCase ( self : str ): lowerCAmelCase_ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase_ : int = model_class(lowerCAmelCase__ ) lowerCAmelCase_ : Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase_ : str = [*signature.parameters.keys()] lowerCAmelCase_ : List[str] = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowerCAmelCase__ ) def lowerCamelCase ( self : Union[str, Any] ): lowerCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase__ ) def lowerCamelCase ( self : Optional[Any] ): lowerCAmelCase_ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase_ : Optional[int] = model_class(config=lowerCAmelCase__ ) for name, module in model.named_modules(): if isinstance(lowerCAmelCase__ , (nn.BatchNormad, nn.GroupNorm) ): self.assertTrue( torch.all(module.weight == 1 ) , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , ) self.assertTrue( torch.all(module.bias == 0 ) , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , ) def lowerCamelCase ( self : Any ): def check_hidden_states_output(a_ : Tuple , a_ : Dict , a_ : Any ): lowerCAmelCase_ : List[Any] = model_class(lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() with torch.no_grad(): lowerCAmelCase_ : Union[str, Any] = model(**self._prepare_for_class(lowerCAmelCase__ , lowerCAmelCase__ ) ) lowerCAmelCase_ : List[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowerCAmelCase_ : Union[str, Any] = self.model_tester.num_stages self.assertEqual(len(lowerCAmelCase__ ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) lowerCAmelCase_ : str = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase_ : Tuple = ["basic", "bottleneck"] for model_class in self.all_model_classes: for layer_type in layers_type: lowerCAmelCase_ : Optional[int] = layer_type lowerCAmelCase_ : Union[str, Any] = True check_hidden_states_output(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase_ : int = True check_hidden_states_output(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) def lowerCamelCase ( self : List[Any] ): lowerCAmelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__ ) @slow def lowerCamelCase ( self : Tuple ): for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase_ : Optional[Any] = RegNetModel.from_pretrained(lowerCAmelCase__ ) self.assertIsNotNone(lowerCAmelCase__ ) def __lowerCamelCase ( ) -> str: """simple docstring""" lowerCAmelCase_ : str = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class __lowerCamelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def lowerCamelCase ( self : List[Any] ): return ( AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def lowerCamelCase ( self : Union[str, Any] ): lowerCAmelCase_ : Any = RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(lowerCAmelCase__ ) lowerCAmelCase_ : List[Any] = self.default_image_processor lowerCAmelCase_ : Tuple = prepare_img() lowerCAmelCase_ : List[Any] = image_processor(images=lowerCAmelCase__ , return_tensors="pt" ).to(lowerCAmelCase__ ) # forward pass with torch.no_grad(): lowerCAmelCase_ : Optional[Any] = model(**lowerCAmelCase__ ) # verify the logits lowerCAmelCase_ : Tuple = torch.Size((1, 10_00) ) self.assertEqual(outputs.logits.shape , lowerCAmelCase__ ) lowerCAmelCase_ : List[Any] = torch.tensor([-0.4180, -1.5051, -3.4836] ).to(lowerCAmelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCAmelCase__ , atol=1e-4 ) )
610
from __future__ import annotations from collections.abc import Iterator from typing import Any class __lowercase : """simple docstring""" def __init__( self : List[str] , lowerCAmelCase__ : Any): SCREAMING_SNAKE_CASE_: Any = data SCREAMING_SNAKE_CASE_: Node | None = None class __lowercase : """simple docstring""" def __init__( self : int): SCREAMING_SNAKE_CASE_: Dict = None SCREAMING_SNAKE_CASE_: str = None def __iter__( self : List[str]): SCREAMING_SNAKE_CASE_: Tuple = self.head while self.head: yield node.data SCREAMING_SNAKE_CASE_: List[str] = node.next if node == self.head: break def __len__( self : Dict): return sum(1 for _ in self) def __repr__( self : Dict): return "->".join(str(lowerCAmelCase__) for item in iter(self)) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase__ : Any): self.insert_nth(len(self) , lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase__ : Any): self.insert_nth(0 , lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : Any): if index < 0 or index > len(self): raise IndexError("list index out of range.") SCREAMING_SNAKE_CASE_: Any = Node(lowerCAmelCase__) if self.head is None: SCREAMING_SNAKE_CASE_: str = new_node # first node points itself SCREAMING_SNAKE_CASE_: Optional[Any] = new_node elif index == 0: # insert at head SCREAMING_SNAKE_CASE_: Optional[Any] = self.head SCREAMING_SNAKE_CASE_: str = new_node else: SCREAMING_SNAKE_CASE_: int = self.head for _ in range(index - 1): SCREAMING_SNAKE_CASE_: Optional[Any] = temp.next SCREAMING_SNAKE_CASE_: List[str] = temp.next SCREAMING_SNAKE_CASE_: int = new_node if index == len(self) - 1: # insert at tail SCREAMING_SNAKE_CASE_: Any = new_node def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): return self.delete_nth(0) def _SCREAMING_SNAKE_CASE ( self : Any): return self.delete_nth(len(self) - 1) def _SCREAMING_SNAKE_CASE ( self : Any , lowerCAmelCase__ : int = 0): if not 0 <= index < len(self): raise IndexError("list index out of range.") SCREAMING_SNAKE_CASE_: Optional[Any] = self.head if self.head == self.tail: # just one node SCREAMING_SNAKE_CASE_: List[str] = None elif index == 0: # delete head node SCREAMING_SNAKE_CASE_: int = self.tail.next.next SCREAMING_SNAKE_CASE_: Tuple = self.head.next else: SCREAMING_SNAKE_CASE_: Optional[int] = self.head for _ in range(index - 1): SCREAMING_SNAKE_CASE_: Any = temp.next SCREAMING_SNAKE_CASE_: Optional[Any] = temp.next SCREAMING_SNAKE_CASE_: int = temp.next.next if index == len(self) - 1: # delete at tail SCREAMING_SNAKE_CASE_: int = temp return delete_node.data def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): return len(self) == 0 def A_ ( ): SCREAMING_SNAKE_CASE_: Dict = CircularLinkedList() assert len(_UpperCAmelCase ) == 0 assert circular_linked_list.is_empty() is True assert str(_UpperCAmelCase ) == "" try: circular_linked_list.delete_front() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_tail() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_nth(-1 ) raise AssertionError except IndexError: assert True try: circular_linked_list.delete_nth(0 ) raise AssertionError except IndexError: assert True assert circular_linked_list.is_empty() is True for i in range(5 ): assert len(_UpperCAmelCase ) == i circular_linked_list.insert_nth(_UpperCAmelCase , i + 1 ) assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 6 ) ) circular_linked_list.insert_tail(6 ) assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 7 ) ) circular_linked_list.insert_head(0 ) assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(0 , 7 ) ) assert circular_linked_list.delete_front() == 0 assert circular_linked_list.delete_tail() == 6 assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 6 ) ) assert circular_linked_list.delete_nth(2 ) == 3 circular_linked_list.insert_nth(2 , 3 ) assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 6 ) ) assert circular_linked_list.is_empty() is False if __name__ == "__main__": import doctest doctest.testmod()
671
0
def _UpperCAmelCase ( UpperCAmelCase : int , UpperCAmelCase : List[str] ): """simple docstring""" __lowerCamelCase : int = len(_UpperCAmelCase ) __lowerCamelCase : List[str] = [[False] * (required_sum + 1) for _ in range(arr_len + 1 )] # for each arr value, a sum of zero(0) can be formed by not taking any element # hence True/1 for i in range(arr_len + 1 ): __lowerCamelCase : str = True # sum is not zero and set is empty then false for i in range(1 , required_sum + 1 ): __lowerCamelCase : List[Any] = False for i in range(1 , arr_len + 1 ): for j in range(1 , required_sum + 1 ): if arr[i - 1] > j: __lowerCamelCase : Tuple = subset[i - 1][j] if arr[i - 1] <= j: __lowerCamelCase : int = subset[i - 1][j] or subset[i - 1][j - arr[i - 1]] return subset[arr_len][required_sum] if __name__ == "__main__": import doctest doctest.testmod()
519
from collections import defaultdict from math import ceil, sqrt def A_ ( _UpperCAmelCase = 1_00_00_00 , _UpperCAmelCase = 10 ): SCREAMING_SNAKE_CASE_: defaultdict = defaultdict(_UpperCAmelCase ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: SCREAMING_SNAKE_CASE_: Tuple = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: SCREAMING_SNAKE_CASE_: Optional[Any] = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(_UpperCAmelCase , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(f'''{solution() = }''')
671
0
from ..utils import DummyObject, requires_backends class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : Union[str, Any] , *_lowerCAmelCase : int , **_lowerCAmelCase : List[Any] ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : List[str] , *_lowerCAmelCase : Tuple , **_lowerCAmelCase : Optional[int] ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : List[str] , *_lowerCAmelCase : Tuple , **_lowerCAmelCase : List[str] ): requires_backends(cls , ['flax'] ) class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : int , *_lowerCAmelCase : Any , **_lowerCAmelCase : int ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Union[str, Any] , *_lowerCAmelCase : str , **_lowerCAmelCase : List[str] ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : List[str] , *_lowerCAmelCase : Union[str, Any] , **_lowerCAmelCase : List[Any] ): requires_backends(cls , ['flax'] ) class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : Union[str, Any] , *_lowerCAmelCase : Any , **_lowerCAmelCase : Tuple ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Union[str, Any] , *_lowerCAmelCase : Optional[Any] , **_lowerCAmelCase : Dict ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : List[str] , *_lowerCAmelCase : Any , **_lowerCAmelCase : Optional[int] ): requires_backends(cls , ['flax'] ) class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : Optional[int] , *_lowerCAmelCase : List[Any] , **_lowerCAmelCase : Any ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Any , *_lowerCAmelCase : Tuple , **_lowerCAmelCase : Any ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Optional[Any] , *_lowerCAmelCase : Dict , **_lowerCAmelCase : Optional[int] ): requires_backends(cls , ['flax'] ) class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : int , *_lowerCAmelCase : Any , **_lowerCAmelCase : Optional[int] ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : int , *_lowerCAmelCase : Optional[int] , **_lowerCAmelCase : int ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Tuple , *_lowerCAmelCase : List[str] , **_lowerCAmelCase : List[str] ): requires_backends(cls , ['flax'] ) class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : List[Any] , *_lowerCAmelCase : Tuple , **_lowerCAmelCase : Optional[int] ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Dict , *_lowerCAmelCase : Union[str, Any] , **_lowerCAmelCase : List[str] ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : str , *_lowerCAmelCase : Optional[Any] , **_lowerCAmelCase : Dict ): requires_backends(cls , ['flax'] ) class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : List[Any] , *_lowerCAmelCase : str , **_lowerCAmelCase : List[str] ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Union[str, Any] , *_lowerCAmelCase : Optional[int] , **_lowerCAmelCase : List[str] ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Tuple , *_lowerCAmelCase : Optional[int] , **_lowerCAmelCase : Optional[Any] ): requires_backends(cls , ['flax'] ) class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : Optional[Any] , *_lowerCAmelCase : Optional[Any] , **_lowerCAmelCase : List[Any] ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Any , *_lowerCAmelCase : Dict , **_lowerCAmelCase : Optional[Any] ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : List[Any] , *_lowerCAmelCase : str , **_lowerCAmelCase : Dict ): requires_backends(cls , ['flax'] ) class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : int , *_lowerCAmelCase : Optional[Any] , **_lowerCAmelCase : Optional[Any] ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Any , *_lowerCAmelCase : Optional[Any] , **_lowerCAmelCase : Optional[int] ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : List[str] , *_lowerCAmelCase : Tuple , **_lowerCAmelCase : Any ): requires_backends(cls , ['flax'] ) class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : List[Any] , *_lowerCAmelCase : Optional[Any] , **_lowerCAmelCase : Union[str, Any] ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : int , *_lowerCAmelCase : Optional[int] , **_lowerCAmelCase : Tuple ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : List[str] , *_lowerCAmelCase : str , **_lowerCAmelCase : Union[str, Any] ): requires_backends(cls , ['flax'] ) class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : List[str] , *_lowerCAmelCase : Tuple , **_lowerCAmelCase : int ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Union[str, Any] , *_lowerCAmelCase : Union[str, Any] , **_lowerCAmelCase : Dict ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : int , *_lowerCAmelCase : int , **_lowerCAmelCase : Optional[Any] ): requires_backends(cls , ['flax'] ) class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : int , *_lowerCAmelCase : Any , **_lowerCAmelCase : Dict ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Optional[Any] , *_lowerCAmelCase : Dict , **_lowerCAmelCase : List[Any] ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : List[str] , *_lowerCAmelCase : int , **_lowerCAmelCase : List[Any] ): requires_backends(cls , ['flax'] ) class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : List[Any] , *_lowerCAmelCase : Dict , **_lowerCAmelCase : Tuple ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : List[str] , *_lowerCAmelCase : List[str] , **_lowerCAmelCase : Optional[Any] ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Dict , *_lowerCAmelCase : Union[str, Any] , **_lowerCAmelCase : List[Any] ): requires_backends(cls , ['flax'] )
31
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCAmelCase : str = { """configuration_xlm""": ["""XLM_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLMConfig""", """XLMOnnxConfig"""], """tokenization_xlm""": ["""XLMTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : Dict = [ """XLM_PRETRAINED_MODEL_ARCHIVE_LIST""", """XLMForMultipleChoice""", """XLMForQuestionAnswering""", """XLMForQuestionAnsweringSimple""", """XLMForSequenceClassification""", """XLMForTokenClassification""", """XLMModel""", """XLMPreTrainedModel""", """XLMWithLMHeadModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : List[str] = [ """TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFXLMForMultipleChoice""", """TFXLMForQuestionAnsweringSimple""", """TFXLMForSequenceClassification""", """TFXLMForTokenClassification""", """TFXLMMainLayer""", """TFXLMModel""", """TFXLMPreTrainedModel""", """TFXLMWithLMHeadModel""", ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys lowerCAmelCase : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
671
0
"""simple docstring""" import copy from typing import Any, Dict, List, Optional, Union import numpy as np import torch from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import TensorType, logging __A : str = logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCAmelCase_ ): """simple docstring""" __UpperCAmelCase : List[str] = ['''input_features''', '''is_longer'''] def __init__( self : Any , lowercase__ : List[Any]=6_4 , lowercase__ : int=4_8_0_0_0 , lowercase__ : Union[str, Any]=4_8_0 , lowercase__ : List[Any]=1_0 , lowercase__ : str=1_0_2_4 , lowercase__ : Tuple=0.0 , lowercase__ : Optional[Any]=False , lowercase__ : float = 0 , lowercase__ : float = 1_4_0_0_0 , lowercase__ : int = None , lowercase__ : str = "fusion" , lowercase__ : str = "repeatpad" , **lowercase__ : int , ): super().__init__( feature_size=lowerCAmelCase__ , sampling_rate=lowerCAmelCase__ , padding_value=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , **lowerCAmelCase__ , ) __lowercase : Union[str, Any] = top_db __lowercase : Any = truncation __lowercase : Tuple = padding __lowercase : Optional[Any] = fft_window_size __lowercase : Union[str, Any] = (fft_window_size >> 1) + 1 __lowercase : List[Any] = hop_length __lowercase : Optional[int] = max_length_s __lowercase : int = max_length_s * sampling_rate __lowercase : List[str] = sampling_rate __lowercase : Optional[Any] = frequency_min __lowercase : Dict = frequency_max __lowercase : Optional[int] = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=lowerCAmelCase__ , min_frequency=lowerCAmelCase__ , max_frequency=lowerCAmelCase__ , sampling_rate=lowerCAmelCase__ , norm=lowerCAmelCase__ , mel_scale="htk" , ) __lowercase : List[Any] = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=lowerCAmelCase__ , min_frequency=lowerCAmelCase__ , max_frequency=lowerCAmelCase__ , sampling_rate=lowerCAmelCase__ , norm="slaney" , mel_scale="slaney" , ) def snake_case ( self : List[Any] ): __lowercase : List[Any] = copy.deepcopy(self.__dict__ ) __lowercase : Tuple = self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] if "mel_filters_slaney" in output: del output["mel_filters_slaney"] return output def snake_case ( self : Tuple , lowercase__ : np.array , lowercase__ : Optional[np.array] = None ): __lowercase : Union[str, Any] = spectrogram( lowerCAmelCase__ , window_function(self.fft_window_size , "hann" ) , frame_length=self.fft_window_size , hop_length=self.hop_length , power=2.0 , mel_filters=lowerCAmelCase__ , log_mel="dB" , ) return log_mel_spectrogram.T def snake_case ( self : int , lowercase__ : int , lowercase__ : Optional[Any] , lowercase__ : Tuple ): __lowercase : Optional[Any] = np.array_split(list(range(0 , total_frames - chunk_frames + 1 ) ) , 3 ) if len(ranges[1] ) == 0: # if the audio is too short, we just use the first chunk __lowercase : int = [0] if len(ranges[2] ) == 0: # if the audio is too short, we just use the first chunk __lowercase : Union[str, Any] = [0] # randomly choose index for each part __lowercase : Tuple = np.random.choice(ranges[0] ) __lowercase : Union[str, Any] = np.random.choice(ranges[1] ) __lowercase : int = np.random.choice(ranges[2] ) __lowercase : str = mel[idx_front : idx_front + chunk_frames, :] __lowercase : Tuple = mel[idx_middle : idx_middle + chunk_frames, :] __lowercase : Optional[Any] = mel[idx_back : idx_back + chunk_frames, :] __lowercase : Union[str, Any] = torch.tensor(mel[None, None, :] ) __lowercase : Any = torch.nn.functional.interpolate( lowerCAmelCase__ , size=[chunk_frames, 6_4] , mode="bilinear" , align_corners=lowerCAmelCase__ ) __lowercase : str = mel_shrink[0][0].numpy() __lowercase : List[Any] = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] , axis=0 ) return mel_fusion def snake_case ( self : Optional[Any] , lowercase__ : np.array , lowercase__ : Union[str, Any] , lowercase__ : Tuple , lowercase__ : Union[str, Any] ): if waveform.shape[0] > max_length: if truncation == "rand_trunc": __lowercase : List[str] = True # random crop to max_length (for compatibility) -> this should be handled by self.pad __lowercase : List[str] = len(lowerCAmelCase__ ) - max_length __lowercase : str = np.random.randint(0 , overflow + 1 ) __lowercase : Union[str, Any] = waveform[idx : idx + max_length] __lowercase : List[str] = self._np_extract_fbank_features(lowerCAmelCase__ , self.mel_filters_slaney )[None, :] elif truncation == "fusion": __lowercase : Tuple = self._np_extract_fbank_features(lowerCAmelCase__ , self.mel_filters ) __lowercase : Union[str, Any] = max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed __lowercase : List[str] = mel.shape[0] if chunk_frames == total_frames: # there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length. # In this case, we just use the whole audio. __lowercase : List[Any] = np.stack([mel, mel, mel, mel] , axis=0 ) __lowercase : Optional[Any] = False else: __lowercase : List[Any] = self._random_mel_fusion(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) __lowercase : str = True else: raise NotImplementedError(f'data_truncating {truncation} not implemented' ) else: __lowercase : Optional[Any] = False # only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding if waveform.shape[0] < max_length: if padding == "repeat": __lowercase : str = int(max_length / len(lowerCAmelCase__ ) ) __lowercase : Tuple = np.stack(np.tile(lowerCAmelCase__ , n_repeat + 1 ) )[:max_length] if padding == "repeatpad": __lowercase : Any = int(max_length / len(lowerCAmelCase__ ) ) __lowercase : List[str] = np.stack(np.tile(lowerCAmelCase__ , lowerCAmelCase__ ) ) __lowercase : Dict = np.pad(lowerCAmelCase__ , (0, max_length - waveform.shape[0]) , mode="constant" , constant_values=0 ) if truncation == "fusion": __lowercase : Optional[int] = self._np_extract_fbank_features(lowerCAmelCase__ , self.mel_filters ) __lowercase : List[Any] = np.stack([input_mel, input_mel, input_mel, input_mel] , axis=0 ) else: __lowercase : Tuple = self._np_extract_fbank_features(lowerCAmelCase__ , self.mel_filters_slaney )[None, :] return input_mel, longer def __call__( self : List[Any] , lowercase__ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , lowercase__ : str = None , lowercase__ : Optional[str] = None , lowercase__ : Optional[int] = None , lowercase__ : Optional[int] = None , lowercase__ : Optional[Union[str, TensorType]] = None , **lowercase__ : Optional[int] , ): __lowercase : List[str] = truncation if truncation is not None else self.truncation __lowercase : List[str] = padding if padding else self.padding if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a' f' sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input' f' was sampled with {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( "It is strongly recommended to pass the `sampling_rate` argument to this function. " "Failing to do so can result in silent errors that might be hard to debug." ) __lowercase : Tuple = isinstance(lowerCAmelCase__ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'Only mono-channel audio is supported for input to {self}' ) __lowercase : Any = is_batched_numpy or ( isinstance(lowerCAmelCase__ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: __lowercase : List[Any] = [np.asarray(lowerCAmelCase__ , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(lowerCAmelCase__ , np.ndarray ): __lowercase : int = np.asarray(lowerCAmelCase__ , dtype=np.floataa ) elif isinstance(lowerCAmelCase__ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): __lowercase : Dict = raw_speech.astype(np.floataa ) # always return batch if not is_batched: __lowercase : int = [np.asarray(lowerCAmelCase__ )] # convert to mel spectrogram, truncate and pad if needed. __lowercase : Union[str, Any] = [ self._get_input_mel(lowerCAmelCase__ , max_length if max_length else self.nb_max_samples , lowerCAmelCase__ , lowerCAmelCase__ ) for waveform in raw_speech ] __lowercase : int = [] __lowercase : Union[str, Any] = [] for mel, longer in padded_inputs: input_mel.append(lowerCAmelCase__ ) is_longer.append(lowerCAmelCase__ ) if truncation == "fusion" and sum(lowerCAmelCase__ ) == 0: # if no audio is longer than 10s, then randomly select one audio to be longer __lowercase : str = np.random.randint(0 , len(lowerCAmelCase__ ) ) __lowercase : Tuple = True if isinstance(input_mel[0] , lowerCAmelCase__ ): __lowercase : List[Any] = [np.asarray(lowerCAmelCase__ , dtype=np.floataa ) for feature in input_mel] # is_longer is a list of bool __lowercase : List[str] = [[longer] for longer in is_longer] __lowercase : List[Any] = {"input_features": input_mel, "is_longer": is_longer} __lowercase : Tuple = BatchFeature(lowerCAmelCase__ ) if return_tensors is not None: __lowercase : Dict = input_features.convert_to_tensors(lowerCAmelCase__ ) return input_features
575
lowerCAmelCase : List[str] = { """A""": ["""B""", """C""", """E"""], """B""": ["""A""", """D""", """E"""], """C""": ["""A""", """F""", """G"""], """D""": ["""B"""], """E""": ["""A""", """B""", """D"""], """F""": ["""C"""], """G""": ["""C"""], } def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Any = set() # keep track of all the paths to be checked SCREAMING_SNAKE_CASE_: Tuple = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue SCREAMING_SNAKE_CASE_: List[Any] = queue.pop(0 ) # get the last node from the path SCREAMING_SNAKE_CASE_: Tuple = path[-1] if node not in explored: SCREAMING_SNAKE_CASE_: Union[str, Any] = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: SCREAMING_SNAKE_CASE_: int = list(_UpperCAmelCase ) new_path.append(_UpperCAmelCase ) queue.append(_UpperCAmelCase ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(_UpperCAmelCase ) # in case there's no path between the 2 nodes return [] def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 SCREAMING_SNAKE_CASE_: List[Any] = [start] SCREAMING_SNAKE_CASE_: List[str] = set(_UpperCAmelCase ) # Keep tab on distances from `start` node. SCREAMING_SNAKE_CASE_: Union[str, Any] = {start: 0, target: -1} while queue: SCREAMING_SNAKE_CASE_: Dict = queue.pop(0 ) if node == target: SCREAMING_SNAKE_CASE_: Tuple = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(_UpperCAmelCase ) queue.append(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Union[str, Any] = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, """G""", """D""")) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, """G""", """D""")) # returns 4
671
0