code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import nn from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel from transformers.utils import ModelOutput @dataclass class lowercase__ ( _lowerCamelCase): UpperCamelCase_ = None UpperCamelCase_ = None UpperCamelCase_ = None UpperCamelCase_ = None class lowercase__ ( _lowerCamelCase): def __init__( self : Optional[Any] , UpperCamelCase__ : Any=1 , UpperCamelCase__ : Union[str, Any]=0 , UpperCamelCase__ : Optional[int]=2 , UpperCamelCase__ : Dict=512 , UpperCamelCase__ : List[str]="cls" , UpperCamelCase__ : Tuple=False , UpperCamelCase__ : Optional[int]=True , **UpperCamelCase__ : int , ): '''simple docstring''' super().__init__(pad_token_id=lowerCAmelCase_ , bos_token_id=lowerCAmelCase_ , eos_token_id=lowerCAmelCase_ , **lowerCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = project_dim SCREAMING_SNAKE_CASE : Dict = pooler_fn SCREAMING_SNAKE_CASE : Union[str, Any] = learn_encoder SCREAMING_SNAKE_CASE : int = use_attention_mask class lowercase__ ( _lowerCamelCase): UpperCamelCase_ = [r"""pooler""", r"""logit_scale"""] UpperCamelCase_ = [r"""position_ids""", r"""predictions.decoder.bias"""] UpperCamelCase_ = """roberta""" UpperCamelCase_ = RobertaSeriesConfig def __init__( self : Union[str, Any] , UpperCamelCase__ : Union[str, Any] ): '''simple docstring''' super().__init__(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE : int = XLMRobertaModel(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE : int = nn.Linear(config.hidden_size , config.project_dim ) SCREAMING_SNAKE_CASE : int = getattr(lowerCAmelCase_ , '''has_pre_transformation''' , lowerCAmelCase_ ) if self.has_pre_transformation: SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Linear(config.hidden_size , config.project_dim ) SCREAMING_SNAKE_CASE : Optional[int] = nn.LayerNorm(config.hidden_size , eps=config.layer_norm_eps ) self.post_init() def __A ( self : Tuple , UpperCamelCase__ : int = None , UpperCamelCase__ : int = None , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : int = None , UpperCamelCase__ : str = None , UpperCamelCase__ : str = None , UpperCamelCase__ : int = None , UpperCamelCase__ : Tuple = None , UpperCamelCase__ : str = None , UpperCamelCase__ : int = None , UpperCamelCase__ : Dict = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE : Tuple = self.base_model( input_ids=lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , position_ids=lowerCAmelCase_ , head_mask=lowerCAmelCase_ , inputs_embeds=lowerCAmelCase_ , encoder_hidden_states=lowerCAmelCase_ , encoder_attention_mask=lowerCAmelCase_ , output_attentions=lowerCAmelCase_ , output_hidden_states=True if self.has_pre_transformation else output_hidden_states , return_dict=lowerCAmelCase_ , ) if self.has_pre_transformation: SCREAMING_SNAKE_CASE : List[str] = outputs['''hidden_states'''][-2] SCREAMING_SNAKE_CASE : List[str] = self.pre_LN(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE : str = self.transformation_pre(lowerCAmelCase_ ) return TransformationModelOutput( projection_state=lowerCAmelCase_ , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , ) else: SCREAMING_SNAKE_CASE : int = self.transformation(outputs.last_hidden_state ) return TransformationModelOutput( projection_state=lowerCAmelCase_ , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
182
'''simple docstring''' import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() lowercase : List[str] = logging.get_logger("transformers.models.speecht5") def SCREAMING_SNAKE_CASE__ ( __A , __A , __A ) -> Dict: hf_model.apply_weight_norm() _snake_case = checkpoint['input_conv.weight_g'] _snake_case = checkpoint['input_conv.weight_v'] _snake_case = checkpoint['input_conv.bias'] for i in range(len(config.upsample_rates ) ): _snake_case = checkpoint[F'upsamples.{i}.1.weight_g'] _snake_case = checkpoint[F'upsamples.{i}.1.weight_v'] _snake_case = checkpoint[F'upsamples.{i}.1.bias'] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): _snake_case = checkpoint[F'blocks.{i}.convs1.{j}.1.weight_g'] _snake_case = checkpoint[F'blocks.{i}.convs1.{j}.1.weight_v'] _snake_case = checkpoint[F'blocks.{i}.convs1.{j}.1.bias'] _snake_case = checkpoint[F'blocks.{i}.convs2.{j}.1.weight_g'] _snake_case = checkpoint[F'blocks.{i}.convs2.{j}.1.weight_v'] _snake_case = checkpoint[F'blocks.{i}.convs2.{j}.1.bias'] _snake_case = checkpoint['output_conv.1.weight_g'] _snake_case = checkpoint['output_conv.1.weight_v'] _snake_case = checkpoint['output_conv.1.bias'] hf_model.remove_weight_norm() @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( __A , __A , __A , __A=None , __A=None , ) -> List[Any]: if config_path is not None: _snake_case = SpeechTaHifiGanConfig.from_pretrained(__A ) else: _snake_case = SpeechTaHifiGanConfig() _snake_case = SpeechTaHifiGan(__A ) _snake_case = torch.load(__A ) load_weights(orig_checkpoint['model']['generator'] , __A , __A ) _snake_case = np.load(__A ) _snake_case = stats[0].reshape(-1 ) _snake_case = stats[1].reshape(-1 ) _snake_case = torch.from_numpy(__A ).float() _snake_case = torch.from_numpy(__A ).float() model.save_pretrained(__A ) if repo_id: print('Pushing to the hub...' ) model.push_to_hub(__A ) if __name__ == "__main__": lowercase : Dict = argparse.ArgumentParser() parser.add_argument("--checkpoint_path", required=True, default=None, type=str, help="Path to original checkpoint") parser.add_argument("--stats_path", required=True, default=None, type=str, help="Path to stats.npy file") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") parser.add_argument( "--pytorch_dump_folder_path", required=True, default=None, type=str, help="Path to the output PyTorch model." ) parser.add_argument( "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub." ) lowercase : List[Any] = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
42
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case : Any = logging.get_logger(__name__) _snake_case : Dict = { "facebook/s2t-wav2vec2-large-en-de": ( "https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json" ), # See all Speech2Text models at https://huggingface.co/models?filter=speech2text2 } class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = "speech_to_text_2" __UpperCAmelCase : Dict = ["past_key_values"] __UpperCAmelCase : str = {"num_attention_heads": "decoder_attention_heads", "hidden_size": "d_model"} def __init__( self : str , lowerCamelCase : List[Any]=10000 , lowerCamelCase : Tuple=6 , lowerCamelCase : Optional[Any]=2048 , lowerCamelCase : Optional[int]=4 , lowerCamelCase : Optional[int]=0.0 , lowerCamelCase : str=True , lowerCamelCase : str="relu" , lowerCamelCase : Tuple=256 , lowerCamelCase : Union[str, Any]=0.1 , lowerCamelCase : Optional[int]=0.0 , lowerCamelCase : Any=0.0 , lowerCamelCase : Optional[int]=0.02 , lowerCamelCase : Dict=2 , lowerCamelCase : List[str]=True , lowerCamelCase : str=1 , lowerCamelCase : Any=0 , lowerCamelCase : List[Any]=2 , lowerCamelCase : List[Any]=1024 , **lowerCamelCase : List[str] , ) -> Any: __snake_case : Tuple = vocab_size __snake_case : int = d_model __snake_case : List[str] = decoder_ffn_dim __snake_case : Union[str, Any] = decoder_layers __snake_case : Dict = decoder_attention_heads __snake_case : Any = dropout __snake_case : List[str] = attention_dropout __snake_case : Optional[Any] = activation_dropout __snake_case : Union[str, Any] = activation_function __snake_case : Union[str, Any] = init_std __snake_case : Union[str, Any] = decoder_layerdrop __snake_case : Optional[int] = use_cache __snake_case : Optional[int] = decoder_layers __snake_case : str = scale_embedding # scale factor will be sqrt(d_model) if True __snake_case : Dict = max_target_positions super().__init__( pad_token_id=lowerCamelCase , bos_token_id=lowerCamelCase , eos_token_id=lowerCamelCase , decoder_start_token_id=lowerCamelCase , **lowerCamelCase , )
366
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 _snake_case : List[Any] = logging.get_logger(__name__) class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = ["input_features", "is_longer"] def __init__( self : Optional[int] , lowerCamelCase : Any=64 , lowerCamelCase : Dict=48000 , lowerCamelCase : Dict=480 , lowerCamelCase : Tuple=10 , lowerCamelCase : Optional[int]=1024 , lowerCamelCase : int=0.0 , lowerCamelCase : Any=False , lowerCamelCase : float = 0 , lowerCamelCase : float = 14000 , lowerCamelCase : int = None , lowerCamelCase : str = "fusion" , lowerCamelCase : str = "repeatpad" , **lowerCamelCase : Optional[int] , ) -> Dict: super().__init__( feature_size=lowerCamelCase , sampling_rate=lowerCamelCase , padding_value=lowerCamelCase , return_attention_mask=lowerCamelCase , **lowerCamelCase , ) __snake_case : Optional[Any] = top_db __snake_case : Dict = truncation __snake_case : Dict = padding __snake_case : Optional[Any] = fft_window_size __snake_case : Optional[Any] = (fft_window_size >> 1) + 1 __snake_case : Dict = hop_length __snake_case : Optional[int] = max_length_s __snake_case : Optional[int] = max_length_s * sampling_rate __snake_case : Dict = sampling_rate __snake_case : Optional[int] = frequency_min __snake_case : Any = frequency_max __snake_case : 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" , ) __snake_case : Tuple = 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 : str ) -> Dict[str, Any]: __snake_case : List[str] = copy.deepcopy(self.__dict__ ) __snake_case : List[Any] = 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 : List[Any] , lowerCamelCase : np.array , lowerCamelCase : Optional[np.array] = None ) -> np.ndarray: __snake_case : List[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 : List[Any] , lowerCamelCase : Any , lowerCamelCase : Union[str, Any] , lowerCamelCase : Any ) -> str: __snake_case : Tuple = 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 __snake_case : Tuple = [0] if len(ranges[2] ) == 0: # if the audio is too short, we just use the first chunk __snake_case : Tuple = [0] # randomly choose index for each part __snake_case : List[Any] = np.random.choice(ranges[0] ) __snake_case : int = np.random.choice(ranges[1] ) __snake_case : List[str] = np.random.choice(ranges[2] ) __snake_case : Dict = mel[idx_front : idx_front + chunk_frames, :] __snake_case : Optional[Any] = mel[idx_middle : idx_middle + chunk_frames, :] __snake_case : Tuple = mel[idx_back : idx_back + chunk_frames, :] __snake_case : Optional[Any] = torch.tensor(mel[None, None, :] ) __snake_case : Optional[int] = torch.nn.functional.interpolate( lowerCamelCase , size=[chunk_frames, 64] , mode="bilinear" , align_corners=lowerCamelCase ) __snake_case : List[Any] = mel_shrink[0][0].numpy() __snake_case : Union[str, Any] = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] , axis=0 ) return mel_fusion def __snake_case ( self : Any , lowerCamelCase : np.array , lowerCamelCase : str , lowerCamelCase : Tuple , lowerCamelCase : Dict ) -> np.array: if waveform.shape[0] > max_length: if truncation == "rand_trunc": __snake_case : List[Any] = True # random crop to max_length (for compatibility) -> this should be handled by self.pad __snake_case : Tuple = len(lowerCamelCase ) - max_length __snake_case : List[Any] = np.random.randint(0 , overflow + 1 ) __snake_case : Dict = waveform[idx : idx + max_length] __snake_case : Optional[int] = self._np_extract_fbank_features(lowerCamelCase , self.mel_filters_slaney )[None, :] elif truncation == "fusion": __snake_case : Any = self._np_extract_fbank_features(lowerCamelCase , self.mel_filters ) __snake_case : Optional[int] = max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed __snake_case : 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. __snake_case : str = np.stack([mel, mel, mel, mel] , axis=0 ) __snake_case : Optional[Any] = False else: __snake_case : Any = self._random_mel_fusion(lowerCamelCase , lowerCamelCase , lowerCamelCase ) __snake_case : Tuple = True else: raise NotImplementedError(F'data_truncating {truncation} not implemented' ) else: __snake_case : Dict = 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": __snake_case : List[str] = int(max_length / len(lowerCamelCase ) ) __snake_case : Any = np.stack(np.tile(lowerCamelCase , n_repeat + 1 ) )[:max_length] if padding == "repeatpad": __snake_case : str = int(max_length / len(lowerCamelCase ) ) __snake_case : List[str] = np.stack(np.tile(lowerCamelCase , lowerCamelCase ) ) __snake_case : str = np.pad(lowerCamelCase , (0, max_length - waveform.shape[0]) , mode="constant" , constant_values=0 ) if truncation == "fusion": __snake_case : List[str] = self._np_extract_fbank_features(lowerCamelCase , self.mel_filters ) __snake_case : List[str] = np.stack([input_mel, input_mel, input_mel, input_mel] , axis=0 ) else: __snake_case : Optional[int] = self._np_extract_fbank_features(lowerCamelCase , self.mel_filters_slaney )[None, :] return input_mel, longer def __call__( self : List[str] , lowerCamelCase : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , lowerCamelCase : str = None , lowerCamelCase : Optional[str] = None , lowerCamelCase : Optional[int] = None , lowerCamelCase : Optional[int] = None , lowerCamelCase : Optional[Union[str, TensorType]] = None , **lowerCamelCase : Any , ) -> BatchFeature: __snake_case : Union[str, Any] = truncation if truncation is not None else self.truncation __snake_case : int = 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." ) __snake_case : Any = 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}' ) __snake_case : str = is_batched_numpy or ( isinstance(lowerCamelCase , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: __snake_case : Tuple = [np.asarray(lowerCamelCase , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(lowerCamelCase , np.ndarray ): __snake_case : str = np.asarray(lowerCamelCase , dtype=np.floataa ) elif isinstance(lowerCamelCase , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): __snake_case : int = raw_speech.astype(np.floataa ) # always return batch if not is_batched: __snake_case : Union[str, Any] = [np.asarray(lowerCamelCase )] # convert to mel spectrogram, truncate and pad if needed. __snake_case : Optional[int] = [ self._get_input_mel(lowerCamelCase , max_length if max_length else self.nb_max_samples , lowerCamelCase , lowerCamelCase ) for waveform in raw_speech ] __snake_case : Optional[int] = [] __snake_case : 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 __snake_case : Optional[Any] = np.random.randint(0 , len(lowerCamelCase ) ) __snake_case : Union[str, Any] = True if isinstance(input_mel[0] , lowerCamelCase ): __snake_case : List[str] = [np.asarray(lowerCamelCase , dtype=np.floataa ) for feature in input_mel] # is_longer is a list of bool __snake_case : Any = [[longer] for longer in is_longer] __snake_case : Tuple = {"input_features": input_mel, "is_longer": is_longer} __snake_case : List[str] = BatchFeature(lowerCamelCase ) if return_tensors is not None: __snake_case : Any = input_features.convert_to_tensors(lowerCamelCase ) return input_features
134
0
'''simple docstring''' import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) lowerCamelCase : Dict = "\\n Text data.\n Second line of data." lowerCamelCase : List[str] = "file" @pytest.fixture(scope='session' ) def _lowerCAmelCase ( _UpperCamelCase : Dict ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE =tmp_path_factory.mktemp('data' ) / (FILE_PATH + '.zstd') _SCREAMING_SNAKE_CASE =bytes(_UpperCamelCase , 'utf-8' ) with zstd.open(_UpperCamelCase , 'wb' ) as f: f.write(_UpperCamelCase ) return path @pytest.fixture def _lowerCAmelCase ( _UpperCamelCase : List[str] ) -> Dict: """simple docstring""" with open(os.path.join(tmpfs.local_root_dir , _UpperCamelCase ) , 'w' ) as f: f.write(_UpperCamelCase ) return FILE_PATH @pytest.mark.parametrize('compression_format' , ['gzip', 'xz', 'zstd'] ) def _lowerCAmelCase ( _UpperCamelCase : Optional[int] , _UpperCamelCase : Optional[Any] , _UpperCamelCase : Optional[Any] , _UpperCamelCase : Any , _UpperCamelCase : Union[str, Any] , _UpperCamelCase : str ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE ={'gzip': gz_file, 'xz': xz_file, 'zstd': zstd_path} _SCREAMING_SNAKE_CASE =input_paths[compression_format] _SCREAMING_SNAKE_CASE =tmp_path / 'cache' _SCREAMING_SNAKE_CASE =DownloadConfig(cache_dir=_UpperCamelCase , extract_compressed_file=_UpperCamelCase ) _SCREAMING_SNAKE_CASE =cached_path(_UpperCamelCase , download_config=_UpperCamelCase ) with open(_UpperCamelCase ) as f: _SCREAMING_SNAKE_CASE =f.read() with open(_UpperCamelCase ) as f: _SCREAMING_SNAKE_CASE =f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize('default_extracted' , [True, False] ) @pytest.mark.parametrize('default_cache_dir' , [True, False] ) def _lowerCAmelCase ( _UpperCamelCase : List[str] , _UpperCamelCase : str , _UpperCamelCase : Tuple , _UpperCamelCase : List[str] , _UpperCamelCase : Optional[int] ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE ='custom_cache' _SCREAMING_SNAKE_CASE ='custom_extracted_dir' _SCREAMING_SNAKE_CASE =tmp_path / 'custom_extracted_path' if default_extracted: _SCREAMING_SNAKE_CASE =('downloads' if default_cache_dir else custom_cache_dir, 'extracted') else: monkeypatch.setattr('datasets.config.EXTRACTED_DATASETS_DIR' , _UpperCamelCase ) monkeypatch.setattr('datasets.config.EXTRACTED_DATASETS_PATH' , str(_UpperCamelCase ) ) _SCREAMING_SNAKE_CASE =custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) _SCREAMING_SNAKE_CASE =xz_file _SCREAMING_SNAKE_CASE =( DownloadConfig(extract_compressed_file=_UpperCamelCase ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=_UpperCamelCase ) ) _SCREAMING_SNAKE_CASE =cached_path(_UpperCamelCase , download_config=_UpperCamelCase ) assert Path(_UpperCamelCase ).parent.parts[-2:] == expected def _lowerCAmelCase ( _UpperCamelCase : Optional[Any] ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE =str(Path(_UpperCamelCase ).resolve() ) assert cached_path(_UpperCamelCase ) == text_file # relative path _SCREAMING_SNAKE_CASE =str(Path(_UpperCamelCase ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(_UpperCamelCase ) == text_file def _lowerCAmelCase ( _UpperCamelCase : List[str] ) -> List[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =str(tmp_path.resolve() / '__missing_file__.txt' ) with pytest.raises(_UpperCamelCase ): cached_path(_UpperCamelCase ) # relative path _SCREAMING_SNAKE_CASE ='./__missing_file__.txt' with pytest.raises(_UpperCamelCase ): cached_path(_UpperCamelCase ) def _lowerCAmelCase ( _UpperCamelCase : Optional[Any] ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =get_from_cache(f"tmp://{tmpfs_file}" ) with open(_UpperCamelCase ) as f: _SCREAMING_SNAKE_CASE =f.read() assert output_file_content == FILE_CONTENT @patch('datasets.config.HF_DATASETS_OFFLINE' , _UpperCamelCase ) def _lowerCAmelCase ( ) -> Union[str, Any]: """simple docstring""" with pytest.raises(_UpperCamelCase ): cached_path('https://huggingface.co' ) @patch('datasets.config.HF_DATASETS_OFFLINE' , _UpperCamelCase ) def _lowerCAmelCase ( _UpperCamelCase : List[str] ) -> Tuple: """simple docstring""" _SCREAMING_SNAKE_CASE =tmp_path_factory.mktemp('data' ) / 'file.html' with pytest.raises(_UpperCamelCase ): http_get('https://huggingface.co' , temp_file=_UpperCamelCase ) with pytest.raises(_UpperCamelCase ): http_head('https://huggingface.co' ) @patch('datasets.config.HF_DATASETS_OFFLINE' , _UpperCamelCase ) def _lowerCAmelCase ( _UpperCamelCase : List[Any] ) -> Union[str, Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =tmp_path_factory.mktemp('data' ) / 'file.html' with pytest.raises(_UpperCamelCase ): ftp_get('ftp://huggingface.co' , temp_file=_UpperCamelCase ) with pytest.raises(_UpperCamelCase ): ftp_head('ftp://huggingface.co' ) @patch('datasets.config.HF_DATASETS_OFFLINE' , _UpperCamelCase ) def _lowerCAmelCase ( _UpperCamelCase : Tuple ) -> Union[str, Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =tmp_path_factory.mktemp('data' ) / 'file.html' with pytest.raises(_UpperCamelCase ): fsspec_get('s3://huggingface.co' , temp_file=_UpperCamelCase ) with pytest.raises(_UpperCamelCase ): fsspec_head('s3://huggingface.co' )
47
import warnings from ...utils import logging from .image_processing_perceiver import PerceiverImageProcessor __UpperCAmelCase : Tuple = logging.get_logger(__name__) class __snake_case ( __lowerCamelCase ): '''simple docstring''' def __init__( self : Union[str, Any] , *A : Union[str, Any] , **A : Optional[int] ): warnings.warn( """The class PerceiverFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use PerceiverImageProcessor instead.""" , A , ) super().__init__(*A , **A )
111
0
'''simple docstring''' from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig _lowerCamelCase : List[str] = logging.get_logger(__name__) # General docstring _lowerCamelCase : Any = 'RegNetConfig' # Base docstring _lowerCamelCase : List[Any] = 'facebook/regnet-y-040' _lowerCamelCase : List[Any] = [1, 1088, 7, 7] # Image classification docstring _lowerCamelCase : int = 'facebook/regnet-y-040' _lowerCamelCase : str = 'tabby, tabby cat' _lowerCamelCase : Optional[Any] = [ 'facebook/regnet-y-040', # See all regnet models at https://huggingface.co/models?filter=regnet ] class __UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__(self : List[str] , _lowerCAmelCase : int , _lowerCAmelCase : int = 3 , _lowerCAmelCase : int = 1 , _lowerCAmelCase : int = 1 , _lowerCAmelCase : Optional[str] = "relu" , **_lowerCAmelCase : str , ): super().__init__(**_lowerCAmelCase ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb A = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) A = tf.keras.layers.ConvaD( filters=_lowerCAmelCase , kernel_size=_lowerCAmelCase , strides=_lowerCAmelCase , padding="""VALID""" , groups=_lowerCAmelCase , use_bias=_lowerCAmelCase , name="""convolution""" , ) A = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name="""normalization""" ) A = ACTaFN[activation] if activation is not None else tf.identity def A (self : Union[str, Any] , _lowerCAmelCase : Optional[Any] ): A = self.convolution(self.padding(_lowerCAmelCase ) ) A = self.normalization(_lowerCAmelCase ) A = self.activation(_lowerCAmelCase ) return hidden_state class __UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__(self : str , _lowerCAmelCase : RegNetConfig , **_lowerCAmelCase : Tuple ): super().__init__(**_lowerCAmelCase ) A = config.num_channels A = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name="""embedder""" , ) def A (self : str , _lowerCAmelCase : List[Any] ): A = shape_list(_lowerCAmelCase )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( """Make sure that the channel dimension of the pixel values match with the one set in the configuration.""" ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) A = tf.transpose(_lowerCAmelCase , perm=(0, 2, 3, 1) ) A = self.embedder(_lowerCAmelCase ) return hidden_state class __UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__(self : List[str] , _lowerCAmelCase : int , _lowerCAmelCase : int = 2 , **_lowerCAmelCase : str ): super().__init__(**_lowerCAmelCase ) A = tf.keras.layers.ConvaD( filters=_lowerCAmelCase , kernel_size=1 , strides=_lowerCAmelCase , use_bias=_lowerCAmelCase , name="""convolution""" ) A = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name="""normalization""" ) def A (self : List[Any] , _lowerCAmelCase : tf.Tensor , _lowerCAmelCase : bool = False ): return self.normalization(self.convolution(_lowerCAmelCase ) , training=_lowerCAmelCase ) class __UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__(self : str , _lowerCAmelCase : int , _lowerCAmelCase : int , **_lowerCAmelCase : Any ): super().__init__(**_lowerCAmelCase ) A = tf.keras.layers.GlobalAveragePoolingaD(keepdims=_lowerCAmelCase , name="""pooler""" ) A = [ tf.keras.layers.ConvaD(filters=_lowerCAmelCase , kernel_size=1 , activation="""relu""" , name="""attention.0""" ), tf.keras.layers.ConvaD(filters=_lowerCAmelCase , kernel_size=1 , activation="""sigmoid""" , name="""attention.2""" ), ] def A (self : str , _lowerCAmelCase : Optional[int] ): # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] A = self.pooler(_lowerCAmelCase ) for layer_module in self.attention: A = layer_module(_lowerCAmelCase ) A = hidden_state * pooled return hidden_state class __UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__(self : Tuple , _lowerCAmelCase : RegNetConfig , _lowerCAmelCase : int , _lowerCAmelCase : int , _lowerCAmelCase : int = 1 , **_lowerCAmelCase : Tuple ): super().__init__(**_lowerCAmelCase ) A = in_channels != out_channels or stride != 1 A = max(1 , out_channels // config.groups_width ) A = ( TFRegNetShortCut(_lowerCAmelCase , stride=_lowerCAmelCase , name="""shortcut""" ) if should_apply_shortcut else tf.keras.layers.Activation("""linear""" , name="""shortcut""" ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. A = [ TFRegNetConvLayer(_lowerCAmelCase , kernel_size=1 , activation=config.hidden_act , name="""layer.0""" ), TFRegNetConvLayer( _lowerCAmelCase , stride=_lowerCAmelCase , groups=_lowerCAmelCase , activation=config.hidden_act , name="""layer.1""" ), TFRegNetConvLayer(_lowerCAmelCase , kernel_size=1 , activation=_lowerCAmelCase , name="""layer.2""" ), ] A = ACTaFN[config.hidden_act] def A (self : Dict , _lowerCAmelCase : Optional[Any] ): A = hidden_state for layer_module in self.layers: A = layer_module(_lowerCAmelCase ) A = self.shortcut(_lowerCAmelCase ) hidden_state += residual A = self.activation(_lowerCAmelCase ) return hidden_state class __UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__(self : Tuple , _lowerCAmelCase : RegNetConfig , _lowerCAmelCase : int , _lowerCAmelCase : int , _lowerCAmelCase : int = 1 , **_lowerCAmelCase : Tuple ): super().__init__(**_lowerCAmelCase ) A = in_channels != out_channels or stride != 1 A = max(1 , out_channels // config.groups_width ) A = ( TFRegNetShortCut(_lowerCAmelCase , stride=_lowerCAmelCase , name="""shortcut""" ) if should_apply_shortcut else tf.keras.layers.Activation("""linear""" , name="""shortcut""" ) ) A = [ TFRegNetConvLayer(_lowerCAmelCase , kernel_size=1 , activation=config.hidden_act , name="""layer.0""" ), TFRegNetConvLayer( _lowerCAmelCase , stride=_lowerCAmelCase , groups=_lowerCAmelCase , activation=config.hidden_act , name="""layer.1""" ), TFRegNetSELayer(_lowerCAmelCase , reduced_channels=int(round(in_channels / 4 ) ) , name="""layer.2""" ), TFRegNetConvLayer(_lowerCAmelCase , kernel_size=1 , activation=_lowerCAmelCase , name="""layer.3""" ), ] A = ACTaFN[config.hidden_act] def A (self : List[Any] , _lowerCAmelCase : Dict ): A = hidden_state for layer_module in self.layers: A = layer_module(_lowerCAmelCase ) A = self.shortcut(_lowerCAmelCase ) hidden_state += residual A = self.activation(_lowerCAmelCase ) return hidden_state class __UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__(self : Union[str, Any] , _lowerCAmelCase : RegNetConfig , _lowerCAmelCase : int , _lowerCAmelCase : int , _lowerCAmelCase : int = 2 , _lowerCAmelCase : int = 2 , **_lowerCAmelCase : int ): super().__init__(**_lowerCAmelCase ) A = TFRegNetXLayer if config.layer_type == """x""" else TFRegNetYLayer A = [ # downsampling is done in the first layer with stride of 2 layer(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , stride=_lowerCAmelCase , name="""layers.0""" ), *[layer(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , name=F"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def A (self : Dict , _lowerCAmelCase : List[str] ): for layer_module in self.layers: A = layer_module(_lowerCAmelCase ) return hidden_state class __UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__(self : Optional[int] , _lowerCAmelCase : RegNetConfig , **_lowerCAmelCase : Dict ): super().__init__(**_lowerCAmelCase ) A = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( _lowerCAmelCase , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name="""stages.0""" , ) ) A = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(_lowerCAmelCase , config.depths[1:] ) ): self.stages.append(TFRegNetStage(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , depth=_lowerCAmelCase , name=F"""stages.{i+1}""" ) ) def A (self : Any , _lowerCAmelCase : tf.Tensor , _lowerCAmelCase : bool = False , _lowerCAmelCase : bool = True ): A = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: A = hidden_states + (hidden_state,) A = stage_module(_lowerCAmelCase ) if output_hidden_states: A = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=_lowerCAmelCase , hidden_states=_lowerCAmelCase ) @keras_serializable class __UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' __lowerCAmelCase = RegNetConfig def __init__(self : Optional[Any] , _lowerCAmelCase : Union[str, Any] , **_lowerCAmelCase : Union[str, Any] ): super().__init__(**_lowerCAmelCase ) A = config A = TFRegNetEmbeddings(_lowerCAmelCase , name="""embedder""" ) A = TFRegNetEncoder(_lowerCAmelCase , name="""encoder""" ) A = tf.keras.layers.GlobalAveragePoolingaD(keepdims=_lowerCAmelCase , name="""pooler""" ) @unpack_inputs def A (self : Tuple , _lowerCAmelCase : tf.Tensor , _lowerCAmelCase : Optional[bool] = None , _lowerCAmelCase : Optional[bool] = None , _lowerCAmelCase : bool = False , ): A = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) A = return_dict if return_dict is not None else self.config.use_return_dict A = self.embedder(_lowerCAmelCase , training=_lowerCAmelCase ) A = self.encoder( _lowerCAmelCase , output_hidden_states=_lowerCAmelCase , return_dict=_lowerCAmelCase , training=_lowerCAmelCase ) A = encoder_outputs[0] A = self.pooler(_lowerCAmelCase ) # Change to NCHW output format have uniformity in the modules A = tf.transpose(_lowerCAmelCase , perm=(0, 3, 1, 2) ) A = tf.transpose(_lowerCAmelCase , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: A = tuple([tf.transpose(_lowerCAmelCase , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=_lowerCAmelCase , pooler_output=_lowerCAmelCase , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class __UpperCAmelCase ( A__ ): '''simple docstring''' __lowerCAmelCase = RegNetConfig __lowerCAmelCase = '''regnet''' __lowerCAmelCase = '''pixel_values''' @property def A (self : Tuple ): return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224) , dtype=tf.floataa )} _lowerCamelCase : List[str] = R'\n Parameters:\n This model is a Tensorflow\n [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and\n behavior.\n config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n' _lowerCamelCase : str = R'\n Args:\n pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConveNextImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( '''The bare RegNet model outputting raw features without any specific head on top.''' , A__ , ) class __UpperCAmelCase ( A__ ): '''simple docstring''' def __init__(self : Any , _lowerCAmelCase : RegNetConfig , *_lowerCAmelCase : List[str] , **_lowerCAmelCase : int ): super().__init__(_lowerCAmelCase , *_lowerCAmelCase , **_lowerCAmelCase ) A = TFRegNetMainLayer(_lowerCAmelCase , name="""regnet""" ) @unpack_inputs @add_start_docstrings_to_model_forward(_lowerCAmelCase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=_lowerCAmelCase , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def A (self : Any , _lowerCAmelCase : tf.Tensor , _lowerCAmelCase : Optional[bool] = None , _lowerCAmelCase : Optional[bool] = None , _lowerCAmelCase : List[str]=False , ): A = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) A = return_dict if return_dict is not None else self.config.use_return_dict A = self.regnet( pixel_values=_lowerCAmelCase , output_hidden_states=_lowerCAmelCase , return_dict=_lowerCAmelCase , training=_lowerCAmelCase , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , ) @add_start_docstrings( ''' RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. ''' , A__ , ) class __UpperCAmelCase ( A__ , A__ ): '''simple docstring''' def __init__(self : Union[str, Any] , _lowerCAmelCase : RegNetConfig , *_lowerCAmelCase : Optional[int] , **_lowerCAmelCase : Any ): super().__init__(_lowerCAmelCase , *_lowerCAmelCase , **_lowerCAmelCase ) A = config.num_labels A = TFRegNetMainLayer(_lowerCAmelCase , name="""regnet""" ) # classification head A = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name="""classifier.1""" ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(_lowerCAmelCase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=_lowerCAmelCase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def A (self : Optional[Any] , _lowerCAmelCase : tf.Tensor = None , _lowerCAmelCase : tf.Tensor = None , _lowerCAmelCase : bool = None , _lowerCAmelCase : bool = None , _lowerCAmelCase : str=False , ): A = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) A = return_dict if return_dict is not None else self.config.use_return_dict A = self.regnet( _lowerCAmelCase , output_hidden_states=_lowerCAmelCase , return_dict=_lowerCAmelCase , training=_lowerCAmelCase ) A = outputs.pooler_output if return_dict else outputs[1] A = self.classifier[0](_lowerCAmelCase ) A = self.classifier[1](_lowerCAmelCase ) A = None if labels is None else self.hf_compute_loss(labels=_lowerCAmelCase , logits=_lowerCAmelCase ) if not return_dict: A = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=_lowerCAmelCase , logits=_lowerCAmelCase , hidden_states=outputs.hidden_states )
357
'''simple docstring''' from typing import List, Optional, Union import numpy as np import tensorflow as tf from .utils import logging _lowerCamelCase : List[Any] = logging.get_logger(__name__) def __a ( UpperCAmelCase ) ->List[int]: """simple docstring""" if isinstance(UpperCAmelCase , np.ndarray ): return list(tensor.shape ) A = tf.shape(UpperCAmelCase ) if tensor.shape == tf.TensorShape(UpperCAmelCase ): return dynamic A = tensor.shape.as_list() return [dynamic[i] if s is None else s for i, s in enumerate(UpperCAmelCase )] def __a ( UpperCAmelCase , UpperCAmelCase = None , UpperCAmelCase = None ) ->tf.Tensor: """simple docstring""" return tf.nn.softmax(logits=logits + 1E-9 , axis=UpperCAmelCase , name=UpperCAmelCase ) def __a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase=1E-5 , UpperCAmelCase=-1 ) ->str: """simple docstring""" if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(UpperCAmelCase , UpperCAmelCase ): raise NotImplementedError("""Only 1D weight and bias tensors are supported for now, with only a single axis.""" ) # Get mean and variance on the axis to be normalized A , A = tf.nn.moments(UpperCAmelCase , axes=[axis] , keepdims=UpperCAmelCase ) if axis != -1: # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions # on every dimension except axis A = [1] * inputs.shape.rank A = shape_list(UpperCAmelCase )[axis] A = tf.reshape(UpperCAmelCase , UpperCAmelCase ) A = tf.reshape(UpperCAmelCase , UpperCAmelCase ) # Compute layer normalization using the batch_normalization # function. A = tf.nn.batch_normalization( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , offset=UpperCAmelCase , scale=UpperCAmelCase , variance_epsilon=UpperCAmelCase , ) return outputs def __a ( UpperCAmelCase , UpperCAmelCase=0 , UpperCAmelCase=-1 ) ->int: """simple docstring""" if end_dim < 0: end_dim += input.shape.rank if start_dim < 0: start_dim += input.shape.rank if start_dim == end_dim: return input A = tf.shape(UpperCAmelCase ) A = tf.math.reduce_prod(in_shape[start_dim : end_dim + 1] ) A = tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]] , axis=0 ) return tf.reshape(UpperCAmelCase , UpperCAmelCase ) def __a ( UpperCAmelCase ) ->tf.Tensor: """simple docstring""" if not isinstance(UpperCAmelCase , tf.Tensor ): A = tf.convert_to_tensor(UpperCAmelCase ) # Catches stray NumPy inputs if encoder_attention_mask.shape.rank == 3: A = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.shape.rank == 2: A = encoder_attention_mask[:, None, None, :] # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow # /transformer/transformer_layers.py#L270 # encoder_extended_attention_mask = (encoder_extended_attention_mask == # encoder_extended_attention_mask.transpose(-1, -2)) A = ( tf.cast(1 , encoder_attention_mask.dtype ) - encoder_extended_attention_mask ) * encoder_extended_attention_mask.dtype.min return encoder_extended_attention_mask def __a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = "input_ids" ) ->None: """simple docstring""" tf.debugging.assert_less( UpperCAmelCase , tf.cast(UpperCAmelCase , dtype=tensor.dtype ) , message=( f"""The maximum value of {tensor_name} ({tf.math.reduce_max(UpperCAmelCase )}) must be smaller than the embedding """ f"""layer's input dimension ({embed_dim}). The likely cause is some problem at tokenization time.""" ) , ) def __a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) ->Optional[Any]: """simple docstring""" A = 64512 # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT` # because in that case even chunking the array would not make the saving # possible. A = [x for x in data if len(UpperCAmelCase ) > HDF5_OBJECT_HEADER_LIMIT] # Expecting this to never be true. if bad_attributes: raise RuntimeError( """The following attributes cannot be saved to HDF5 file because """ f"""they are larger than {HDF5_OBJECT_HEADER_LIMIT} """ f"""bytes: {bad_attributes}""" ) A = np.asarray(UpperCAmelCase ) A = 1 A = np.array_split(UpperCAmelCase , UpperCAmelCase ) # This will never loop forever thanks to the test above. while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data ): num_chunks += 1 A = np.array_split(UpperCAmelCase , UpperCAmelCase ) if num_chunks > 1: for chunk_id, chunk_data in enumerate(UpperCAmelCase ): A = chunk_data else: A = data def __a ( UpperCAmelCase , UpperCAmelCase ) ->int: """simple docstring""" if name in group.attrs: A = [n.decode("""utf8""" ) if hasattr(UpperCAmelCase , """decode""" ) else n for n in group.attrs[name]] else: A = [] A = 0 while "%s%d" % (name, chunk_id) in group.attrs: data.extend( [n.decode("""utf8""" ) if hasattr(UpperCAmelCase , """decode""" ) else n for n in group.attrs["""%s%d""" % (name, chunk_id)]] ) chunk_id += 1 return data def __a ( UpperCAmelCase ) ->Optional[Any]: """simple docstring""" def _expand_single_ad_tensor(UpperCAmelCase ): if isinstance(UpperCAmelCase , tf.Tensor ) and t.shape.rank == 1: return tf.expand_dims(UpperCAmelCase , axis=-1 ) return t return tf.nest.map_structure(_expand_single_ad_tensor , UpperCAmelCase )
337
0
'''simple docstring''' import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class __UpperCamelCase ( lowerCamelCase__ ): def __init__( self, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = False, **lowerCAmelCase, ): """simple docstring""" super().__init__(features=lowerCAmelCase, cache_dir=lowerCAmelCase, keep_in_memory=lowerCAmelCase, **lowerCAmelCase ) lowerCamelCase_ =Sql( cache_dir=lowerCAmelCase, features=lowerCAmelCase, sql=lowerCAmelCase, con=lowerCAmelCase, **lowerCAmelCase, ) def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =None lowerCamelCase_ =None lowerCamelCase_ =None lowerCamelCase_ =None self.builder.download_and_prepare( download_config=lowerCAmelCase, download_mode=lowerCAmelCase, verification_mode=lowerCAmelCase, base_path=lowerCAmelCase, ) # Build dataset for splits lowerCamelCase_ =self.builder.as_dataset( split='''train''', verification_mode=lowerCAmelCase, in_memory=self.keep_in_memory ) return dataset class __UpperCamelCase : def __init__( self, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase = None, lowerCAmelCase = None, **lowerCAmelCase, ): """simple docstring""" if num_proc is not None and num_proc <= 0: raise ValueError(f'''num_proc {num_proc} must be an integer > 0.''' ) lowerCamelCase_ =dataset lowerCamelCase_ =name lowerCamelCase_ =con lowerCamelCase_ =batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE lowerCamelCase_ =num_proc lowerCamelCase_ =to_sql_kwargs def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =self.to_sql_kwargs.pop('''sql''', lowerCAmelCase ) lowerCamelCase_ =self.to_sql_kwargs.pop('''con''', lowerCAmelCase ) lowerCamelCase_ =self.to_sql_kwargs.pop('''index''', lowerCAmelCase ) lowerCamelCase_ =self._write(index=lowerCAmelCase, **self.to_sql_kwargs ) return written def lowercase__ ( self, lowerCAmelCase ): """simple docstring""" lowerCamelCase_, lowerCamelCase_, lowerCamelCase_ =args lowerCamelCase_ ={**to_sql_kwargs, '''if_exists''': '''append'''} if offset > 0 else to_sql_kwargs lowerCamelCase_ =query_table( table=self.dataset.data, key=slice(lowerCAmelCase, offset + self.batch_size ), indices=self.dataset._indices, ) lowerCamelCase_ =batch.to_pandas() lowerCamelCase_ =df.to_sql(self.name, self.con, index=lowerCAmelCase, **lowerCAmelCase ) return num_rows or len(lowerCAmelCase ) def lowercase__ ( self, lowerCAmelCase, **lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0, len(self.dataset ), self.batch_size ), unit='''ba''', disable=not logging.is_progress_bar_enabled(), desc='''Creating SQL from Arrow format''', ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: lowerCamelCase_, lowerCamelCase_ =len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql, [(offset, index, to_sql_kwargs) for offset in range(0, lowerCAmelCase, lowerCAmelCase )], ), total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size, unit='''ba''', disable=not logging.is_progress_bar_enabled(), desc='''Creating SQL from Arrow format''', ): written += num_rows return written
75
'''simple docstring''' import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging a_ : List[Any] = ( """https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py""" ) a_ : Union[str, Any] = logging.get_logger(__name__) # pylint: disable=invalid-name def a_ ( ) -> List[str]: """simple docstring""" lowerCamelCase_ ='''https://pypi.org/pypi/diffusers/json''' lowerCamelCase_ =json.loads(request.urlopen(__snake_case ).read() )['''releases'''].keys() return sorted(__snake_case , key=lambda __snake_case : version.Version(__snake_case ) ) def a_ ( ) -> str: """simple docstring""" # This function has already been executed if HF_MODULES_CACHE already is in the Python path. if HF_MODULES_CACHE in sys.path: return sys.path.append(__snake_case ) os.makedirs(__snake_case , exist_ok=__snake_case ) lowerCamelCase_ =Path(__snake_case ) / '''__init__.py''' if not init_path.exists(): init_path.touch() def a_ ( __snake_case : Union[str, os.PathLike] ) -> List[str]: """simple docstring""" init_hf_modules() lowerCamelCase_ =Path(__snake_case ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__snake_case , exist_ok=__snake_case ) lowerCamelCase_ =dynamic_module_path / '''__init__.py''' if not init_path.exists(): init_path.touch() def a_ ( __snake_case : Tuple ) -> List[str]: """simple docstring""" with open(__snake_case , '''r''' , encoding='''utf-8''' ) as f: lowerCamelCase_ =f.read() # Imports of the form `import .xxx` lowerCamelCase_ =re.findall('''^\s*import\s+\.(\S+)\s*$''' , __snake_case , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import''' , __snake_case , flags=re.MULTILINE ) # Unique-ify return list(set(__snake_case ) ) def a_ ( __snake_case : str ) -> str: """simple docstring""" lowerCamelCase_ =False lowerCamelCase_ =[module_file] lowerCamelCase_ =[] # Let's recurse through all relative imports while not no_change: lowerCamelCase_ =[] for f in files_to_check: new_imports.extend(get_relative_imports(__snake_case ) ) lowerCamelCase_ =Path(__snake_case ).parent lowerCamelCase_ =[str(module_path / m ) for m in new_imports] lowerCamelCase_ =[f for f in new_import_files if f not in all_relative_imports] lowerCamelCase_ =[F'''{f}.py''' for f in new_import_files] lowerCamelCase_ =len(__snake_case ) == 0 all_relative_imports.extend(__snake_case ) return all_relative_imports def a_ ( __snake_case : Union[str, Any] ) -> Optional[int]: """simple docstring""" with open(__snake_case , '''r''' , encoding='''utf-8''' ) as f: lowerCamelCase_ =f.read() # Imports of the form `import xxx` lowerCamelCase_ =re.findall('''^\s*import\s+(\S+)\s*$''' , __snake_case , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('''^\s*from\s+(\S+)\s+import''' , __snake_case , flags=re.MULTILINE ) # Only keep the top-level module lowerCamelCase_ =[imp.split('''.''' )[0] for imp in imports if not imp.startswith('''.''' )] # Unique-ify and test we got them all lowerCamelCase_ =list(set(__snake_case ) ) lowerCamelCase_ =[] for imp in imports: try: importlib.import_module(__snake_case ) except ImportError: missing_packages.append(__snake_case ) if len(__snake_case ) > 0: raise ImportError( '''This modeling file requires the following packages that were not found in your environment: ''' F'''{', '.join(__snake_case )}. Run `pip install {' '.join(__snake_case )}`''' ) return get_relative_imports(__snake_case ) def a_ ( __snake_case : Tuple , __snake_case : Tuple ) -> List[Any]: """simple docstring""" lowerCamelCase_ =module_path.replace(os.path.sep , '''.''' ) lowerCamelCase_ =importlib.import_module(__snake_case ) if class_name is None: return find_pipeline_class(__snake_case ) return getattr(__snake_case , __snake_case ) def a_ ( __snake_case : Dict ) -> Any: """simple docstring""" from ..pipelines import DiffusionPipeline lowerCamelCase_ =dict(inspect.getmembers(__snake_case , inspect.isclass ) ) lowerCamelCase_ =None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __snake_case ) and cls.__module__.split('''.''' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( F'''Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:''' F''' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in''' F''' {loaded_module}.''' ) lowerCamelCase_ =cls return pipeline_class def a_ ( __snake_case : Union[str, os.PathLike] , __snake_case : str , __snake_case : Optional[Union[str, os.PathLike]] = None , __snake_case : bool = False , __snake_case : bool = False , __snake_case : Optional[Dict[str, str]] = None , __snake_case : Optional[Union[bool, str]] = None , __snake_case : Optional[str] = None , __snake_case : bool = False , ) -> Optional[int]: """simple docstring""" lowerCamelCase_ =str(__snake_case ) lowerCamelCase_ =os.path.join(__snake_case , __snake_case ) if os.path.isfile(__snake_case ): lowerCamelCase_ =module_file_or_url lowerCamelCase_ ='''local''' elif pretrained_model_name_or_path.count('''/''' ) == 0: lowerCamelCase_ =get_diffusers_versions() # cut ".dev0" lowerCamelCase_ ='''v''' + '''.'''.join(__version__.split('''.''' )[:3] ) # retrieve github version that matches if revision is None: lowerCamelCase_ =latest_version if latest_version[1:] in available_versions else '''main''' logger.info(F'''Defaulting to latest_version: {revision}.''' ) elif revision in available_versions: lowerCamelCase_ =F'''v{revision}''' elif revision == "main": lowerCamelCase_ =revision else: raise ValueError( F'''`custom_revision`: {revision} does not exist. Please make sure to choose one of''' F''' {', '.join(available_versions + ['main'] )}.''' ) # community pipeline on GitHub lowerCamelCase_ =COMMUNITY_PIPELINES_URL.format(revision=__snake_case , pipeline=__snake_case ) try: lowerCamelCase_ =cached_download( __snake_case , cache_dir=__snake_case , force_download=__snake_case , proxies=__snake_case , resume_download=__snake_case , local_files_only=__snake_case , use_auth_token=__snake_case , ) lowerCamelCase_ ='''git''' lowerCamelCase_ =pretrained_model_name_or_path + '''.py''' except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise else: try: # Load from URL or cache if already cached lowerCamelCase_ =hf_hub_download( __snake_case , __snake_case , cache_dir=__snake_case , force_download=__snake_case , proxies=__snake_case , resume_download=__snake_case , local_files_only=__snake_case , use_auth_token=__snake_case , ) lowerCamelCase_ =os.path.join('''local''' , '''--'''.join(pretrained_model_name_or_path.split('''/''' ) ) ) except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise # Check we have all the requirements in our environment lowerCamelCase_ =check_imports(__snake_case ) # Now we move the module inside our cached dynamic modules. lowerCamelCase_ =DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__snake_case ) lowerCamelCase_ =Path(__snake_case ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__snake_case , submodule_path / module_file ) for module_needed in modules_needed: lowerCamelCase_ =F'''{module_needed}.py''' shutil.copy(os.path.join(__snake_case , __snake_case ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__snake_case , __snake_case ): lowerCamelCase_ =use_auth_token elif use_auth_token is True: lowerCamelCase_ =HfFolder.get_token() else: lowerCamelCase_ =None lowerCamelCase_ =model_info(__snake_case , revision=__snake_case , token=__snake_case ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. lowerCamelCase_ =submodule_path / commit_hash lowerCamelCase_ =full_submodule + os.path.sep + commit_hash create_dynamic_module(__snake_case ) if not (submodule_path / module_file).exists(): shutil.copy(__snake_case , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __snake_case , F'''{module_needed}.py''' , cache_dir=__snake_case , force_download=__snake_case , resume_download=__snake_case , proxies=__snake_case , use_auth_token=__snake_case , revision=__snake_case , local_files_only=__snake_case , ) return os.path.join(__snake_case , __snake_case ) def a_ ( __snake_case : Union[str, os.PathLike] , __snake_case : str , __snake_case : Optional[str] = None , __snake_case : Optional[Union[str, os.PathLike]] = None , __snake_case : bool = False , __snake_case : bool = False , __snake_case : Optional[Dict[str, str]] = None , __snake_case : Optional[Union[bool, str]] = None , __snake_case : Optional[str] = None , __snake_case : bool = False , **__snake_case : Optional[int] , ) -> Optional[int]: """simple docstring""" lowerCamelCase_ =get_cached_module_file( __snake_case , __snake_case , cache_dir=__snake_case , force_download=__snake_case , resume_download=__snake_case , proxies=__snake_case , use_auth_token=__snake_case , revision=__snake_case , local_files_only=__snake_case , ) return get_class_in_module(__snake_case , final_module.replace('''.py''' , '''''' ) )
75
1
'''simple docstring''' import collections import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_flax_cross_test, require_flax, require_torch, require_vision, slow, torch_device, ) from transformers.utils import is_flax_available, is_torch_available, is_vision_available from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_flax_bert import FlaxBertModelTester from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester from ..vit.test_modeling_flax_vit import FlaxViTModelTester if is_flax_available(): from transformers import ( FlaxBertModel, FlaxCLIPVisionModel, FlaxVisionTextDualEncoderModel, FlaxViTModel, VisionTextDualEncoderConfig, VisionTextDualEncoderProcessor, ) from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) if is_torch_available(): import torch from transformers import VisionTextDualEncoderModel if is_vision_available(): from PIL import Image def snake_case_ (UpperCamelCase : int ): '''simple docstring''' if isinstance(UpperCamelCase , collections.abc.Iterable ): return x return (x, x) @require_flax class A : def __lowerCAmelCase ( self : str , lowerCAmelCase_ : Any , lowerCAmelCase_ : Optional[int] ) -> Optional[Any]: """simple docstring""" pass def __lowerCAmelCase ( self : Tuple ) -> Any: """simple docstring""" pass def __lowerCAmelCase ( self : Tuple ) -> str: """simple docstring""" pass def __lowerCAmelCase ( self : Optional[int] , lowerCAmelCase_ : np.ndarray , lowerCAmelCase_ : np.ndarray , lowerCAmelCase_ : float ) -> List[Any]: """simple docstring""" _a = np.abs((a - b) ).max() self.assertLessEqual(lowerCAmelCase_ , lowerCAmelCase_ , F'Difference between torch and flax is {diff} (>= {tol}).' ) def __lowerCAmelCase ( self : List[str] , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[Any]=None , **lowerCAmelCase_ : int ) -> List[Any]: """simple docstring""" _a = VisionTextDualEncoderConfig.from_vision_text_configs(lowerCAmelCase_ , lowerCAmelCase_ ) _a = FlaxVisionTextDualEncoderModel(lowerCAmelCase_ ) _a = model(input_ids=lowerCAmelCase_ , pixel_values=lowerCAmelCase_ , attention_mask=lowerCAmelCase_ ) self.assertEqual(output['''text_embeds'''].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output['''image_embeds'''].shape , (pixel_values.shape[0], config.projection_dim) ) def __lowerCAmelCase ( self : Optional[int] , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : List[str]=None , **lowerCAmelCase_ : List[str] ) -> Union[str, Any]: """simple docstring""" _a , _a = self.get_vision_text_model(lowerCAmelCase_ , lowerCAmelCase_ ) _a = {'''vision_model''': vision_model, '''text_model''': text_model} _a = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCAmelCase_ ) _a = model(input_ids=lowerCAmelCase_ , pixel_values=lowerCAmelCase_ , attention_mask=lowerCAmelCase_ ) self.assertEqual(output['''text_embeds'''].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output['''image_embeds'''].shape , (pixel_values.shape[0], model.config.projection_dim) ) def __lowerCAmelCase ( self : Optional[int] , lowerCAmelCase_ : int , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : int , lowerCAmelCase_ : Any , lowerCAmelCase_ : Tuple=None , **lowerCAmelCase_ : Optional[Any] ) -> Any: """simple docstring""" _a , _a = self.get_vision_text_model(lowerCAmelCase_ , lowerCAmelCase_ ) _a = {'''vision_model''': vision_model, '''text_model''': text_model} _a = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCAmelCase_ ) _a = model(input_ids=lowerCAmelCase_ , pixel_values=lowerCAmelCase_ , attention_mask=lowerCAmelCase_ ) _a = output[0] with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(lowerCAmelCase_ ) _a = FlaxVisionTextDualEncoderModel.from_pretrained(lowerCAmelCase_ ) _a = model(input_ids=lowerCAmelCase_ , pixel_values=lowerCAmelCase_ , attention_mask=lowerCAmelCase_ ) _a = after_output[0] _a = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(lowerCAmelCase_ , 1e-3 ) def __lowerCAmelCase ( self : str , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Any=None , **lowerCAmelCase_ : Dict ) -> int: """simple docstring""" _a , _a = self.get_vision_text_model(lowerCAmelCase_ , lowerCAmelCase_ ) _a = {'''vision_model''': vision_model, '''text_model''': text_model} _a = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCAmelCase_ ) _a = model( input_ids=lowerCAmelCase_ , pixel_values=lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , output_attentions=lowerCAmelCase_ ) _a = output.vision_model_output.attentions self.assertEqual(len(lowerCAmelCase_ ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) _a = to_atuple(vision_model.config.image_size ) _a = to_atuple(vision_model.config.patch_size ) _a = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) _a = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) _a = output.text_model_output.attentions self.assertEqual(len(lowerCAmelCase_ ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def __lowerCAmelCase ( self : Union[str, Any] , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Optional[Any] ) -> int: """simple docstring""" pt_model.to(lowerCAmelCase_ ) pt_model.eval() # prepare inputs _a = inputs_dict _a = {k: torch.tensor(v.tolist() ) for k, v in flax_inputs.items()} with torch.no_grad(): _a = pt_model(**lowerCAmelCase_ ).to_tuple() _a = fx_model(**lowerCAmelCase_ ).to_tuple() self.assertEqual(len(lowerCAmelCase_ ) , len(lowerCAmelCase_ ) , '''Output lengths differ between Flax and PyTorch''' ) for fx_output, pt_output in zip(fx_outputs[:4] , pt_outputs[:4] ): self.assert_almost_equals(lowerCAmelCase_ , pt_output.numpy() , 4e-2 ) # PT -> Flax with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(lowerCAmelCase_ ) _a = FlaxVisionTextDualEncoderModel.from_pretrained(lowerCAmelCase_ , from_pt=lowerCAmelCase_ ) _a = fx_model_loaded(**lowerCAmelCase_ ).to_tuple() self.assertEqual(len(lowerCAmelCase_ ) , len(lowerCAmelCase_ ) , '''Output lengths differ between Flax and PyTorch''' ) for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4] , pt_outputs[:4] ): self.assert_almost_equals(lowerCAmelCase_ , pt_output.numpy() , 4e-2 ) # Flax -> PT with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(lowerCAmelCase_ ) _a = VisionTextDualEncoderModel.from_pretrained(lowerCAmelCase_ , from_flax=lowerCAmelCase_ ) pt_model_loaded.to(lowerCAmelCase_ ) pt_model_loaded.eval() with torch.no_grad(): _a = pt_model_loaded(**lowerCAmelCase_ ).to_tuple() self.assertEqual(len(lowerCAmelCase_ ) , len(lowerCAmelCase_ ) , '''Output lengths differ between Flax and PyTorch''' ) for fx_output, pt_output_loaded in zip(fx_outputs[:4] , pt_outputs_loaded[:4] ): self.assert_almost_equals(lowerCAmelCase_ , pt_output_loaded.numpy() , 4e-2 ) def __lowerCAmelCase ( self : Any , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[Any] ) -> int: """simple docstring""" _a = VisionTextDualEncoderConfig.from_vision_text_configs(lowerCAmelCase_ , lowerCAmelCase_ ) _a = VisionTextDualEncoderModel(lowerCAmelCase_ ) _a = FlaxVisionTextDualEncoderModel(lowerCAmelCase_ ) _a = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , lowerCAmelCase_ ) _a = fx_state self.check_pt_flax_equivalence(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) def __lowerCAmelCase ( self : int , lowerCAmelCase_ : int , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[int] ) -> str: """simple docstring""" _a = VisionTextDualEncoderConfig.from_vision_text_configs(lowerCAmelCase_ , lowerCAmelCase_ ) _a = VisionTextDualEncoderModel(lowerCAmelCase_ ) _a = FlaxVisionTextDualEncoderModel(lowerCAmelCase_ ) _a = load_flax_weights_in_pytorch_model(lowerCAmelCase_ , fx_model.params ) self.check_pt_flax_equivalence(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) def __lowerCAmelCase ( self : Optional[Any] ) -> str: """simple docstring""" _a = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**lowerCAmelCase_ ) def __lowerCAmelCase ( self : Union[str, Any] ) -> int: """simple docstring""" _a = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**lowerCAmelCase_ ) def __lowerCAmelCase ( self : List[str] ) -> List[str]: """simple docstring""" _a = self.prepare_config_and_inputs() self.check_save_load(**lowerCAmelCase_ ) def __lowerCAmelCase ( self : Optional[Any] ) -> Tuple: """simple docstring""" _a = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**lowerCAmelCase_ ) @is_pt_flax_cross_test def __lowerCAmelCase ( self : str ) -> List[str]: """simple docstring""" _a = self.prepare_config_and_inputs() _a = config_inputs_dict.pop('''vision_config''' ) _a = config_inputs_dict.pop('''text_config''' ) _a = config_inputs_dict self.check_equivalence_pt_to_flax(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) self.check_equivalence_flax_to_pt(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) @slow def __lowerCAmelCase ( self : Dict ) -> List[str]: """simple docstring""" _a , _a = self.get_pretrained_model_and_inputs() _a = model_a(**lowerCAmelCase_ ) _a = outputs[0] with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(lowerCAmelCase_ ) _a = FlaxVisionTextDualEncoderModel.from_pretrained(lowerCAmelCase_ ) _a = model_a(**lowerCAmelCase_ ) _a = after_outputs[0] _a = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(lowerCAmelCase_ , 1e-5 ) @require_flax class A ( _a ,unittest.TestCase ): def __lowerCAmelCase ( self : Union[str, Any] ) -> Dict: """simple docstring""" _a = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( '''hf-internal-testing/tiny-random-vit''' , '''hf-internal-testing/tiny-bert''' , vision_from_pt=lowerCAmelCase_ , text_from_pt=lowerCAmelCase_ , ) _a = 13 _a = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) _a = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) _a = random_attention_mask([batch_size, 4] ) _a = {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask} return model, inputs def __lowerCAmelCase ( self : List[Any] , lowerCAmelCase_ : int , lowerCAmelCase_ : List[Any] ) -> List[str]: """simple docstring""" _a = FlaxViTModel(lowerCAmelCase_ ) _a = FlaxBertModel(lowerCAmelCase_ ) return vision_model, text_model def __lowerCAmelCase ( self : Dict ) -> Union[str, Any]: """simple docstring""" _a = FlaxViTModelTester(self ) _a = FlaxBertModelTester(self ) _a = vit_model_tester.prepare_config_and_inputs() _a = bert_model_tester.prepare_config_and_inputs() _a , _a = vision_config_and_inputs _a , _a , _a , _a = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_torch class A ( _a ,unittest.TestCase ): def __lowerCAmelCase ( self : Optional[int] ) -> List[str]: """simple docstring""" _a = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( '''hf-internal-testing/tiny-random-clip''' , '''hf-internal-testing/tiny-bert''' , vision_from_pt=lowerCAmelCase_ , text_from_pt=lowerCAmelCase_ , ) _a = 13 _a = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) _a = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) _a = random_attention_mask([batch_size, 4] ) _a = {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask} return model, inputs def __lowerCAmelCase ( self : Dict , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : List[Any] ) -> Tuple: """simple docstring""" _a = FlaxCLIPVisionModel(lowerCAmelCase_ ) _a = FlaxBertModel(lowerCAmelCase_ ) return vision_model, text_model def __lowerCAmelCase ( self : List[str] ) -> Optional[Any]: """simple docstring""" _a = FlaxCLIPVisionModelTester(self ) _a = FlaxBertModelTester(self ) _a = clip_model_tester.prepare_config_and_inputs() _a = bert_model_tester.prepare_config_and_inputs() _a , _a = vision_config_and_inputs _a , _a , _a , _a = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_flax @require_vision class A ( unittest.TestCase ): @slow def __lowerCAmelCase ( self : Tuple ) -> Union[str, Any]: """simple docstring""" _a = FlaxVisionTextDualEncoderModel.from_pretrained('''clip-italian/clip-italian''' , logit_scale_init_value=1.0 ) _a = VisionTextDualEncoderProcessor.from_pretrained('''clip-italian/clip-italian''' ) _a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) _a = processor( text=['''una foto di un gatto''', '''una foto di un cane'''] , images=lowerCAmelCase_ , padding=lowerCAmelCase_ , return_tensors='''np''' ) _a = model(**lowerCAmelCase_ ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) _a = np.array([[1.2_2_8_4_7_2_7, 0.3_1_0_4_1_2_2]] ) self.assertTrue(np.allclose(outputs.logits_per_image , lowerCAmelCase_ , atol=1e-3 ) )
369
'''simple docstring''' import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class A ( _a ): lowercase_ = 42 lowercase_ = jnp.floataa lowercase_ = True def __lowerCAmelCase ( self : Optional[int] ) -> Dict: """simple docstring""" super().setup() _a = nn.Dense(5 , dtype=self.dtype ) def __call__( self : List[Any] , *lowerCAmelCase_ : str , **lowerCAmelCase_ : Dict ) -> List[Any]: """simple docstring""" _a = super().__call__(*lowerCAmelCase_ , **lowerCAmelCase_ ) _a = self.cls(outputs[2] ) return outputs[:2] + (cls_out,) class A ( _a ): lowercase_ = FlaxBigBirdForNaturalQuestionsModule def snake_case_ (UpperCamelCase : Any , UpperCamelCase : str , UpperCamelCase : int , UpperCamelCase : Tuple , UpperCamelCase : Union[str, Any] , UpperCamelCase : int ): '''simple docstring''' def cross_entropy(UpperCamelCase : int , UpperCamelCase : Optional[Any] , UpperCamelCase : List[str]=None ): _a = logits.shape[-1] _a = (labels[..., None] == jnp.arange(UpperCamelCase )[None]).astype('''f4''' ) _a = jax.nn.log_softmax(UpperCamelCase , axis=-1 ) _a = -jnp.sum(labels * logits , axis=-1 ) if reduction is not None: _a = reduction(UpperCamelCase ) return loss _a = partial(UpperCamelCase , reduction=jnp.mean ) _a = cross_entropy(UpperCamelCase , UpperCamelCase ) _a = cross_entropy(UpperCamelCase , UpperCamelCase ) _a = cross_entropy(UpperCamelCase , UpperCamelCase ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class A : lowercase_ = "google/bigbird-roberta-base" lowercase_ = 3000 lowercase_ = 1_0500 lowercase_ = 128 lowercase_ = 3 lowercase_ = 1 lowercase_ = 5 # tx_args lowercase_ = 3e-5 lowercase_ = 0.0 lowercase_ = 2_0000 lowercase_ = 0.0095 lowercase_ = "bigbird-roberta-natural-questions" lowercase_ = "training-expt" lowercase_ = "data/nq-training.jsonl" lowercase_ = "data/nq-validation.jsonl" def __lowerCAmelCase ( self : Union[str, Any] ) -> Any: """simple docstring""" os.makedirs(self.base_dir , exist_ok=lowerCAmelCase_ ) _a = os.path.join(self.base_dir , self.save_dir ) _a = self.batch_size_per_device * jax.device_count() @dataclass class A : lowercase_ = 42 lowercase_ = 4096 # no dynamic padding on TPUs def __call__( self : str , lowerCAmelCase_ : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" _a = self.collate_fn(lowerCAmelCase_ ) _a = jax.tree_util.tree_map(lowerCAmelCase_ , lowerCAmelCase_ ) return batch def __lowerCAmelCase ( self : List[Any] , lowerCAmelCase_ : List[Any] ) -> int: """simple docstring""" _a , _a = self.fetch_inputs(features['''input_ids'''] ) _a = { '''input_ids''': jnp.array(lowerCAmelCase_ , dtype=jnp.intaa ), '''attention_mask''': jnp.array(lowerCAmelCase_ , dtype=jnp.intaa ), '''start_labels''': jnp.array(features['''start_token'''] , dtype=jnp.intaa ), '''end_labels''': jnp.array(features['''end_token'''] , dtype=jnp.intaa ), '''pooled_labels''': jnp.array(features['''category'''] , dtype=jnp.intaa ), } return batch def __lowerCAmelCase ( self : Dict , lowerCAmelCase_ : list ) -> List[Any]: """simple docstring""" _a = [self._fetch_inputs(lowerCAmelCase_ ) for ids in input_ids] return zip(*lowerCAmelCase_ ) def __lowerCAmelCase ( self : Dict , lowerCAmelCase_ : list ) -> str: """simple docstring""" _a = [1 for _ in range(len(lowerCAmelCase_ ) )] while len(lowerCAmelCase_ ) < self.max_length: input_ids.append(self.pad_id ) attention_mask.append(0 ) return input_ids, attention_mask def snake_case_ (UpperCamelCase : List[Any] , UpperCamelCase : List[Any] , UpperCamelCase : Dict=None ): '''simple docstring''' if seed is not None: _a = dataset.shuffle(seed=UpperCamelCase ) for i in range(len(UpperCamelCase ) // batch_size ): _a = dataset[i * batch_size : (i + 1) * batch_size] yield dict(UpperCamelCase ) @partial(jax.pmap , axis_name='''batch''' ) def snake_case_ (UpperCamelCase : Optional[int] , UpperCamelCase : Tuple , **UpperCamelCase : str ): '''simple docstring''' def loss_fn(UpperCamelCase : List[str] ): _a = model_inputs.pop('''start_labels''' ) _a = model_inputs.pop('''end_labels''' ) _a = model_inputs.pop('''pooled_labels''' ) _a = state.apply_fn(**UpperCamelCase , params=UpperCamelCase , dropout_rng=UpperCamelCase , train=UpperCamelCase ) _a , _a , _a = outputs return state.loss_fn( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , ) _a , _a = jax.random.split(UpperCamelCase ) _a = jax.value_and_grad(UpperCamelCase ) _a , _a = grad_fn(state.params ) _a = jax.lax.pmean({'''loss''': loss} , axis_name='''batch''' ) _a = jax.lax.pmean(UpperCamelCase , '''batch''' ) _a = state.apply_gradients(grads=UpperCamelCase ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name='''batch''' ) def snake_case_ (UpperCamelCase : Any , **UpperCamelCase : Optional[int] ): '''simple docstring''' _a = model_inputs.pop('''start_labels''' ) _a = model_inputs.pop('''end_labels''' ) _a = model_inputs.pop('''pooled_labels''' ) _a = state.apply_fn(**UpperCamelCase , params=state.params , train=UpperCamelCase ) _a , _a , _a = outputs _a = state.loss_fn(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) _a = jax.lax.pmean({'''loss''': loss} , axis_name='''batch''' ) return metrics class A ( train_state.TrainState ): lowercase_ = struct.field(pytree_node=_a ) @dataclass class A : lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = None def __lowerCAmelCase ( self : Tuple , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Optional[int]=None ) -> List[str]: """simple docstring""" _a = model.params _a = TrainState.create( apply_fn=model.__call__ , params=lowerCAmelCase_ , tx=lowerCAmelCase_ , loss_fn=lowerCAmelCase_ , ) if ckpt_dir is not None: _a , _a , _a , _a , _a = restore_checkpoint(lowerCAmelCase_ , lowerCAmelCase_ ) _a = { '''lr''': args.lr, '''init_lr''': args.init_lr, '''warmup_steps''': args.warmup_steps, '''num_train_steps''': num_train_steps, '''weight_decay''': args.weight_decay, } _a , _a = build_tx(**lowerCAmelCase_ ) _a = train_state.TrainState( step=lowerCAmelCase_ , apply_fn=model.__call__ , params=lowerCAmelCase_ , tx=lowerCAmelCase_ , opt_state=lowerCAmelCase_ , ) _a = args _a = data_collator _a = lr _a = params _a = jax_utils.replicate(lowerCAmelCase_ ) return state def __lowerCAmelCase ( self : str , lowerCAmelCase_ : Any , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[Any] ) -> int: """simple docstring""" _a = self.args _a = len(lowerCAmelCase_ ) // args.batch_size _a = jax.random.PRNGKey(0 ) _a = jax.random.split(lowerCAmelCase_ , jax.device_count() ) for epoch in range(args.max_epochs ): _a = jnp.array(0 , dtype=jnp.floataa ) _a = get_batched_dataset(lowerCAmelCase_ , args.batch_size , seed=lowerCAmelCase_ ) _a = 0 for batch in tqdm(lowerCAmelCase_ , total=lowerCAmelCase_ , desc=F'Running EPOCH-{epoch}' ): _a = self.data_collator(lowerCAmelCase_ ) _a , _a , _a = self.train_step_fn(lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ) running_loss += jax_utils.unreplicate(metrics['''loss'''] ) i += 1 if i % args.logging_steps == 0: _a = jax_utils.unreplicate(state.step ) _a = running_loss.item() / i _a = self.scheduler_fn(state_step - 1 ) _a = self.evaluate(lowerCAmelCase_ , lowerCAmelCase_ ) _a = { '''step''': state_step.item(), '''eval_loss''': eval_loss.item(), '''tr_loss''': tr_loss, '''lr''': lr.item(), } tqdm.write(str(lowerCAmelCase_ ) ) self.logger.log(lowerCAmelCase_ , commit=lowerCAmelCase_ ) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + F'-e{epoch}-s{i}' , state=lowerCAmelCase_ ) def __lowerCAmelCase ( self : List[str] , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : str ) -> List[str]: """simple docstring""" _a = get_batched_dataset(lowerCAmelCase_ , self.args.batch_size ) _a = len(lowerCAmelCase_ ) // self.args.batch_size _a = jnp.array(0 , dtype=jnp.floataa ) _a = 0 for batch in tqdm(lowerCAmelCase_ , total=lowerCAmelCase_ , desc='''Evaluating ... ''' ): _a = self.data_collator(lowerCAmelCase_ ) _a = self.val_step_fn(lowerCAmelCase_ , **lowerCAmelCase_ ) running_loss += jax_utils.unreplicate(metrics['''loss'''] ) i += 1 return running_loss / i def __lowerCAmelCase ( self : int , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : str ) -> int: """simple docstring""" _a = jax_utils.unreplicate(lowerCAmelCase_ ) print(F'SAVING CHECKPOINT IN {save_dir}' , end=''' ... ''' ) self.model_save_fn(lowerCAmelCase_ , params=state.params ) with open(os.path.join(lowerCAmelCase_ , '''opt_state.msgpack''' ) , '''wb''' ) as f: f.write(to_bytes(state.opt_state ) ) joblib.dump(self.args , os.path.join(lowerCAmelCase_ , '''args.joblib''' ) ) joblib.dump(self.data_collator , os.path.join(lowerCAmelCase_ , '''data_collator.joblib''' ) ) with open(os.path.join(lowerCAmelCase_ , '''training_state.json''' ) , '''w''' ) as f: json.dump({'''step''': state.step.item()} , lowerCAmelCase_ ) print('''DONE''' ) def snake_case_ (UpperCamelCase : int , UpperCamelCase : Dict ): '''simple docstring''' print(f'RESTORING CHECKPOINT FROM {save_dir}' , end=''' ... ''' ) with open(os.path.join(UpperCamelCase , '''flax_model.msgpack''' ) , '''rb''' ) as f: _a = from_bytes(state.params , f.read() ) with open(os.path.join(UpperCamelCase , '''opt_state.msgpack''' ) , '''rb''' ) as f: _a = from_bytes(state.opt_state , f.read() ) _a = joblib.load(os.path.join(UpperCamelCase , '''args.joblib''' ) ) _a = joblib.load(os.path.join(UpperCamelCase , '''data_collator.joblib''' ) ) with open(os.path.join(UpperCamelCase , '''training_state.json''' ) , '''r''' ) as f: _a = json.load(UpperCamelCase ) _a = training_state['''step'''] print('''DONE''' ) return params, opt_state, step, args, data_collator def snake_case_ (UpperCamelCase : Dict , UpperCamelCase : Optional[int] , UpperCamelCase : Dict , UpperCamelCase : List[Any] ): '''simple docstring''' _a = num_train_steps - warmup_steps _a = optax.linear_schedule(init_value=UpperCamelCase , end_value=UpperCamelCase , transition_steps=UpperCamelCase ) _a = optax.linear_schedule(init_value=UpperCamelCase , end_value=1e-7 , transition_steps=UpperCamelCase ) _a = optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def snake_case_ (UpperCamelCase : Tuple , UpperCamelCase : Optional[Any] , UpperCamelCase : str , UpperCamelCase : Union[str, Any] , UpperCamelCase : int ): '''simple docstring''' def weight_decay_mask(UpperCamelCase : Dict ): _a = traverse_util.flatten_dict(UpperCamelCase ) _a = {k: (v[-1] != '''bias''' and v[-2:] != ('''LayerNorm''', '''scale''')) for k, v in params.items()} return traverse_util.unflatten_dict(UpperCamelCase ) _a = scheduler_fn(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) _a = optax.adamw(learning_rate=UpperCamelCase , weight_decay=UpperCamelCase , mask=UpperCamelCase ) return tx, lr
179
0
import unittest from transformers.testing_utils import require_bsa from transformers.utils import is_bsa_available from ...test_feature_extraction_common import FeatureExtractionSavingTestMixin if is_bsa_available(): from transformers import MarkupLMFeatureExtractor class __snake_case ( unittest.TestCase ): def __init__( self : Optional[Any] , A_ : List[str]): lowerCAmelCase_ : int = parent def UpperCAmelCase__ ( self : Tuple): return {} def UpperCamelCase( ): lowerCAmelCase_ : str = '''<HTML> <HEAD> <TITLE>sample document</TITLE> </HEAD> <BODY BGCOLOR="FFFFFF"> <HR> <a href="http://google.com">Goog</a> <H1>This is one header</H1> <H2>This is a another Header</H2> <P>Travel from <P> <B>SFO to JFK</B> <BR> <B><I>on May 2, 2015 at 2:00 pm. For details go to confirm.com </I></B> <HR> <div style="color:#0000FF"> <h3>Traveler <b> name </b> is <p> John Doe </p> </div>''' lowerCAmelCase_ : List[Any] = ''' <!DOCTYPE html> <html> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> </body> </html> ''' return [html_string_a, html_string_a] @require_bsa class __snake_case ( UpperCamelCase_ ,unittest.TestCase ): _a = MarkupLMFeatureExtractor if is_bsa_available() else None def UpperCAmelCase__ ( self : Dict): lowerCAmelCase_ : int = MarkupLMFeatureExtractionTester(self) @property def UpperCAmelCase__ ( self : Tuple): return self.feature_extract_tester.prepare_feat_extract_dict() def UpperCAmelCase__ ( self : Dict): # Initialize feature_extractor lowerCAmelCase_ : Dict = self.feature_extraction_class() # Test not batched input lowerCAmelCase_ : Dict = get_html_strings()[0] lowerCAmelCase_ : int = feature_extractor(A_) # fmt: off lowerCAmelCase_ : Tuple = [['''sample document''', '''Goog''', '''This is one header''', '''This is a another Header''', '''Travel from''', '''SFO to JFK''', '''on May 2, 2015 at 2:00 pm. For details go to confirm.com''', '''Traveler''', '''name''', '''is''', '''John Doe''']] lowerCAmelCase_ : int = [['''/html/head/title''', '''/html/body/a''', '''/html/body/h1''', '''/html/body/h2''', '''/html/body/p''', '''/html/body/p/p/b[1]''', '''/html/body/p/p/b[2]/i''', '''/html/body/p/p/div/h3''', '''/html/body/p/p/div/h3/b''', '''/html/body/p/p/div/h3''', '''/html/body/p/p/div/h3/p''']] # fmt: on self.assertEqual(encoding.nodes , A_) self.assertEqual(encoding.xpaths , A_) # Test batched lowerCAmelCase_ : Optional[int] = get_html_strings() lowerCAmelCase_ : Optional[int] = feature_extractor(A_) # fmt: off lowerCAmelCase_ : Union[str, Any] = expected_nodes + [['''My First Heading''', '''My first paragraph.''']] lowerCAmelCase_ : int = expected_xpaths + [['''/html/body/h1''', '''/html/body/p''']] self.assertEqual(len(encoding.nodes) , 2) self.assertEqual(len(encoding.xpaths) , 2) self.assertEqual(encoding.nodes , A_) self.assertEqual(encoding.xpaths , A_)
103
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : str = logging.get_logger(__name__) def A ( _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE=False ) -> Any: lowerCamelCase : Any = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''blocks.{i}.norm1.weight''', f'''deit.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''blocks.{i}.norm1.bias''', f'''deit.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append((f'''blocks.{i}.attn.proj.weight''', f'''deit.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append((f'''blocks.{i}.attn.proj.bias''', f'''deit.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''blocks.{i}.norm2.weight''', f'''deit.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''blocks.{i}.norm2.bias''', f'''deit.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append((f'''blocks.{i}.mlp.fc1.weight''', f'''deit.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''blocks.{i}.mlp.fc1.bias''', f'''deit.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''blocks.{i}.mlp.fc2.weight''', f'''deit.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''blocks.{i}.mlp.fc2.bias''', f'''deit.encoder.layer.{i}.output.dense.bias''') ) # projection layer + position embeddings rename_keys.extend( [ ("cls_token", "deit.embeddings.cls_token"), ("dist_token", "deit.embeddings.distillation_token"), ("patch_embed.proj.weight", "deit.embeddings.patch_embeddings.projection.weight"), ("patch_embed.proj.bias", "deit.embeddings.patch_embeddings.projection.bias"), ("pos_embed", "deit.embeddings.position_embeddings"), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("norm.weight", "layernorm.weight"), ("norm.bias", "layernorm.bias"), ("pre_logits.fc.weight", "pooler.dense.weight"), ("pre_logits.fc.bias", "pooler.dense.bias"), ] ) # if just the base model, we should remove "deit" from all keys that start with "deit" lowerCamelCase : Union[str, Any] = [(pair[0], pair[1][4:]) if pair[1].startswith("deit" ) else pair for pair in rename_keys] else: # layernorm + classification heads rename_keys.extend( [ ("norm.weight", "deit.layernorm.weight"), ("norm.bias", "deit.layernorm.bias"), ("head.weight", "cls_classifier.weight"), ("head.bias", "cls_classifier.bias"), ("head_dist.weight", "distillation_classifier.weight"), ("head_dist.bias", "distillation_classifier.bias"), ] ) return rename_keys def A ( _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE=False ) -> str: for i in range(config.num_hidden_layers ): if base_model: lowerCamelCase : Optional[int] = "" else: lowerCamelCase : List[str] = "deit." # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) lowerCamelCase : List[str] = state_dict.pop(f'''blocks.{i}.attn.qkv.weight''' ) lowerCamelCase : Optional[int] = state_dict.pop(f'''blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict lowerCamelCase : List[Any] = in_proj_weight[ : config.hidden_size, : ] lowerCamelCase : Any = in_proj_bias[: config.hidden_size] lowerCamelCase : List[str] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] lowerCamelCase : Optional[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] lowerCamelCase : List[str] = in_proj_weight[ -config.hidden_size :, : ] lowerCamelCase : List[Any] = in_proj_bias[-config.hidden_size :] def A ( _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) -> str: lowerCamelCase : List[str] = dct.pop(_SCREAMING_SNAKE_CASE ) lowerCamelCase : Any = val def A ( ) -> List[str]: lowerCamelCase : Union[str, Any] = "http://images.cocodataset.org/val2017/000000039769.jpg" lowerCamelCase : str = Image.open(requests.get(_SCREAMING_SNAKE_CASE ,stream=_SCREAMING_SNAKE_CASE ).raw ) return im @torch.no_grad() def A ( _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) -> Optional[Any]: lowerCamelCase : Union[str, Any] = DeiTConfig() # all deit models have fine-tuned heads lowerCamelCase : Optional[int] = False # dataset (fine-tuned on ImageNet 2012), patch_size and image_size lowerCamelCase : Dict = 1000 lowerCamelCase : Tuple = "huggingface/label-files" lowerCamelCase : List[str] = "imagenet-1k-id2label.json" lowerCamelCase : List[Any] = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,repo_type="dataset" ) ,"r" ) ) lowerCamelCase : Optional[int] = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} lowerCamelCase : Tuple = idalabel lowerCamelCase : str = {v: k for k, v in idalabel.items()} lowerCamelCase : Dict = int(deit_name[-6:-4] ) lowerCamelCase : Optional[Any] = int(deit_name[-3:] ) # size of the architecture if deit_name[9:].startswith("tiny" ): lowerCamelCase : Optional[Any] = 192 lowerCamelCase : List[str] = 768 lowerCamelCase : Tuple = 12 lowerCamelCase : Optional[Any] = 3 elif deit_name[9:].startswith("small" ): lowerCamelCase : str = 384 lowerCamelCase : Optional[Any] = 1536 lowerCamelCase : Dict = 12 lowerCamelCase : Optional[int] = 6 if deit_name[9:].startswith("base" ): pass elif deit_name[4:].startswith("large" ): lowerCamelCase : str = 1024 lowerCamelCase : List[str] = 4096 lowerCamelCase : Any = 24 lowerCamelCase : Dict = 16 # load original model from timm lowerCamelCase : List[Any] = timm.create_model(_SCREAMING_SNAKE_CASE ,pretrained=_SCREAMING_SNAKE_CASE ) timm_model.eval() # load state_dict of original model, remove and rename some keys lowerCamelCase : Dict = timm_model.state_dict() lowerCamelCase : Dict = create_rename_keys(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) for src, dest in rename_keys: rename_key(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) read_in_q_k_v(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) # load HuggingFace model lowerCamelCase : Optional[Any] = DeiTForImageClassificationWithTeacher(_SCREAMING_SNAKE_CASE ).eval() model.load_state_dict(_SCREAMING_SNAKE_CASE ) # Check outputs on an image, prepared by DeiTImageProcessor lowerCamelCase : Any = int( (256 / 224) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103 lowerCamelCase : Union[str, Any] = DeiTImageProcessor(size=_SCREAMING_SNAKE_CASE ,crop_size=config.image_size ) lowerCamelCase : str = image_processor(images=prepare_img() ,return_tensors="pt" ) lowerCamelCase : int = encoding["pixel_values"] lowerCamelCase : Optional[Any] = model(_SCREAMING_SNAKE_CASE ) lowerCamelCase : Union[str, Any] = timm_model(_SCREAMING_SNAKE_CASE ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(_SCREAMING_SNAKE_CASE ,outputs.logits ,atol=1e-3 ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) print(f'''Saving model {deit_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--deit_name', default='vit_deit_base_distilled_patch16_224', type=str, help='Name of the DeiT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) SCREAMING_SNAKE_CASE__ : List[str] = parser.parse_args() convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
48
0
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py UpperCAmelCase_ = 'src/diffusers' UpperCAmelCase_ = '.' # This is to make sure the diffusers module imported is the one in the repo. UpperCAmelCase_ = importlib.util.spec_from_file_location( 'diffusers', os.path.join(DIFFUSERS_PATH, '__init__.py'), submodule_search_locations=[DIFFUSERS_PATH], ) UpperCAmelCase_ = spec.loader.load_module() def lowerCAmelCase_ ( __UpperCAmelCase: Union[str, Any] , __UpperCAmelCase: List[Any] ) -> Optional[int]: return line.startswith(__UpperCAmelCase ) or len(__UpperCAmelCase ) <= 1 or re.search(r'''^\s*\)(\s*->.*:|:)\s*$''' , __UpperCAmelCase ) is not None def lowerCAmelCase_ ( __UpperCAmelCase: Optional[int] ) -> Optional[int]: UpperCamelCase__ : str = object_name.split('''.''' ) UpperCamelCase__ : Any = 0 # First let's find the module where our object lives. UpperCamelCase__ : Tuple = parts[i] while i < len(__UpperCAmelCase ) and not os.path.isfile(os.path.join(__UpperCAmelCase , f"{module}.py" ) ): i += 1 if i < len(__UpperCAmelCase ): UpperCamelCase__ : Optional[int] = os.path.join(__UpperCAmelCase , parts[i] ) if i >= len(__UpperCAmelCase ): raise ValueError(f"`object_name` should begin with the name of a module of diffusers but got {object_name}." ) with open(os.path.join(__UpperCAmelCase , f"{module}.py" ) , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: UpperCamelCase__ : int = f.readlines() # Now let's find the class / func in the code! UpperCamelCase__ : Tuple = '''''' UpperCamelCase__ : List[Any] = 0 for name in parts[i + 1 :]: while ( line_index < len(__UpperCAmelCase ) and re.search(rf"^{indent}(class|def)\s+{name}(\(|\:)" , lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(__UpperCAmelCase ): raise ValueError(f" {object_name} does not match any function or class in {module}." ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). UpperCamelCase__ : List[Any] = line_index while line_index < len(__UpperCAmelCase ) and _should_continue(lines[line_index] , __UpperCAmelCase ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 UpperCamelCase__ : Any = lines[start_index:line_index] return "".join(__UpperCAmelCase ) UpperCAmelCase_ = re.compile(R'^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)') UpperCAmelCase_ = re.compile(R'^\s*(\S+)->(\S+)(\s+.*|$)') UpperCAmelCase_ = re.compile(R'<FILL\s+[^>]*>') def lowerCAmelCase_ ( __UpperCAmelCase: List[Any] ) -> str: UpperCamelCase__ : Tuple = code.split('''\n''' ) UpperCamelCase__ : Union[str, Any] = 0 while idx < len(__UpperCAmelCase ) and len(lines[idx] ) == 0: idx += 1 if idx < len(__UpperCAmelCase ): return re.search(r'''^(\s*)\S''' , lines[idx] ).groups()[0] return "" def lowerCAmelCase_ ( __UpperCAmelCase: Tuple ) -> Dict: UpperCamelCase__ : Union[str, Any] = len(get_indent(__UpperCAmelCase ) ) > 0 if has_indent: UpperCamelCase__ : str = f"class Bla:\n{code}" UpperCamelCase__ : List[str] = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 , preview=__UpperCAmelCase ) UpperCamelCase__ : Optional[int] = black.format_str(__UpperCAmelCase , mode=__UpperCAmelCase ) UpperCamelCase__ : Dict = style_docstrings_in_code(__UpperCAmelCase ) return result[len('''class Bla:\n''' ) :] if has_indent else result def lowerCAmelCase_ ( __UpperCAmelCase: List[str] , __UpperCAmelCase: Optional[Any]=False ) -> Any: with open(__UpperCAmelCase , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: UpperCamelCase__ : int = f.readlines() UpperCamelCase__ : Optional[int] = [] UpperCamelCase__ : Any = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(__UpperCAmelCase ): UpperCamelCase__ : Optional[Any] = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. UpperCamelCase__ : List[str] = search.groups() UpperCamelCase__ : Tuple = find_code_in_diffusers(__UpperCAmelCase ) UpperCamelCase__ : Tuple = get_indent(__UpperCAmelCase ) UpperCamelCase__ : Union[str, Any] = line_index + 1 if indent == theoretical_indent else line_index + 2 UpperCamelCase__ : Dict = theoretical_indent UpperCamelCase__ : Union[str, Any] = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. UpperCamelCase__ : List[Any] = True while line_index < len(__UpperCAmelCase ) and should_continue: line_index += 1 if line_index >= len(__UpperCAmelCase ): break UpperCamelCase__ : int = lines[line_index] UpperCamelCase__ : Dict = _should_continue(__UpperCAmelCase , __UpperCAmelCase ) and re.search(f"^{indent}# End copy" , __UpperCAmelCase ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 UpperCamelCase__ : str = lines[start_index:line_index] UpperCamelCase__ : List[Any] = ''''''.join(__UpperCAmelCase ) # Remove any nested `Copied from` comments to avoid circular copies UpperCamelCase__ : List[str] = [line for line in theoretical_code.split('''\n''' ) if _re_copy_warning.search(__UpperCAmelCase ) is None] UpperCamelCase__ : List[str] = '''\n'''.join(__UpperCAmelCase ) # Before comparing, use the `replace_pattern` on the original code. if len(__UpperCAmelCase ) > 0: UpperCamelCase__ : Dict = replace_pattern.replace('''with''' , '''''' ).split(''',''' ) UpperCamelCase__ : Optional[int] = [_re_replace_pattern.search(__UpperCAmelCase ) for p in patterns] for pattern in patterns: if pattern is None: continue UpperCamelCase__ : Optional[int] = pattern.groups() UpperCamelCase__ : Tuple = re.sub(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) if option.strip() == "all-casing": UpperCamelCase__ : Any = re.sub(obja.lower() , obja.lower() , __UpperCAmelCase ) UpperCamelCase__ : List[str] = re.sub(obja.upper() , obja.upper() , __UpperCAmelCase ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line UpperCamelCase__ : Any = blackify(lines[start_index - 1] + theoretical_code ) UpperCamelCase__ : Union[str, Any] = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: UpperCamelCase__ : Dict = lines[:start_index] + [theoretical_code] + lines[line_index:] UpperCamelCase__ : Optional[int] = start_index + 1 if overwrite and len(__UpperCAmelCase ) > 0: # Warn the user a file has been modified. print(f"Detected changes, rewriting {filename}." ) with open(__UpperCAmelCase , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(__UpperCAmelCase ) return diffs def lowerCAmelCase_ ( __UpperCAmelCase: bool = False ) -> Dict: UpperCamelCase__ : Dict = glob.glob(os.path.join(__UpperCAmelCase , '''**/*.py''' ) , recursive=__UpperCAmelCase ) UpperCamelCase__ : int = [] for filename in all_files: UpperCamelCase__ : str = is_copy_consistent(__UpperCAmelCase , __UpperCAmelCase ) diffs += [f"- {filename}: copy does not match {d[0]} at line {d[1]}" for d in new_diffs] if not overwrite and len(__UpperCAmelCase ) > 0: UpperCamelCase__ : Optional[int] = '''\n'''.join(__UpperCAmelCase ) raise Exception( '''Found the following copy inconsistencies:\n''' + diff + '''\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.''' ) if __name__ == "__main__": UpperCAmelCase_ = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') UpperCAmelCase_ = parser.parse_args() check_copies(args.fix_and_overwrite)
361
from manim import * class lowercase__ ( __lowerCamelCase ): '''simple docstring''' def UpperCamelCase__ ( self ) -> int: """simple docstring""" UpperCamelCase__ : int = Rectangle(height=0.5, width=0.5 ) UpperCamelCase__ : Optional[int] = Rectangle(height=0.46, width=0.46 ).set_stroke(width=0 ) UpperCamelCase__ : Dict = [mem.copy() for i in range(6 )] UpperCamelCase__ : Any = [mem.copy() for i in range(6 )] UpperCamelCase__ : int = VGroup(*__magic_name__ ).arrange(__magic_name__, buff=0 ) UpperCamelCase__ : Tuple = VGroup(*__magic_name__ ).arrange(__magic_name__, buff=0 ) UpperCamelCase__ : int = VGroup(__magic_name__, __magic_name__ ).arrange(__magic_name__, buff=0 ) UpperCamelCase__ : Optional[int] = Text('''CPU''', font_size=24 ) UpperCamelCase__ : Any = Group(__magic_name__, __magic_name__ ).arrange(__magic_name__, buff=0.5, aligned_edge=__magic_name__ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(__magic_name__ ) UpperCamelCase__ : Any = [mem.copy() for i in range(1 )] UpperCamelCase__ : Optional[int] = VGroup(*__magic_name__ ).arrange(__magic_name__, buff=0 ) UpperCamelCase__ : Union[str, Any] = Text('''GPU''', font_size=24 ) UpperCamelCase__ : List[Any] = Group(__magic_name__, __magic_name__ ).arrange(__magic_name__, buff=0.5, aligned_edge=__magic_name__ ) gpu.align_to(__magic_name__, __magic_name__ ) gpu.set_x(gpu.get_x() - 1 ) self.add(__magic_name__ ) UpperCamelCase__ : str = [mem.copy() for i in range(6 )] UpperCamelCase__ : Optional[int] = VGroup(*__magic_name__ ).arrange(__magic_name__, buff=0 ) UpperCamelCase__ : Optional[int] = Text('''Model''', font_size=24 ) UpperCamelCase__ : int = Group(__magic_name__, __magic_name__ ).arrange(__magic_name__, buff=0.5, aligned_edge=__magic_name__ ) model.move_to([3, -1.0, 0] ) self.play( Create(__magic_name__, run_time=1 ), Create(__magic_name__, run_time=1 ), Create(__magic_name__, run_time=1 ), ) UpperCamelCase__ : Optional[int] = MarkupText( f"First, an empty model skeleton is loaded\ninto <span fgcolor='{YELLOW}'>memory</span> without using much RAM.", font_size=24, ) UpperCamelCase__ : List[str] = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) UpperCamelCase__ : Union[str, Any] = MarkupText( f"<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model", font_size=18, ) key_text.move_to([-5, 2.4, 0] ) step_a.move_to([2, 2, 0] ) self.play(Write(__magic_name__, run_time=2.5 ), Write(__magic_name__ ), Write(__magic_name__ ) ) self.add(__magic_name__ ) UpperCamelCase__ : Dict = [] UpperCamelCase__ : Any = [] UpperCamelCase__ : int = [] for i, rect in enumerate(__magic_name__ ): UpperCamelCase__ : Union[str, Any] = Rectangle(height=0.46, width=0.46 ).set_stroke(width=0.0 ).set_fill(__magic_name__, opacity=0.7 ) cpu_target.move_to(__magic_name__ ) cpu_target.generate_target() UpperCamelCase__ : Tuple = 0.46 / 4 UpperCamelCase__ : Optional[Any] = 0.46 / 3 if i == 0: cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ), buff=0.02, direction=__magic_name__ ) cpu_target.target.set_x(cpu_target.target.get_x() + 0.1 ) elif i == 3: cpu_target.target.next_to(cpu_targs[0].target, direction=__magic_name__, buff=0.0 ) else: cpu_target.target.next_to(cpu_targs[i - 1].target, direction=__magic_name__, buff=0.0 ) cpu_targs.append(__magic_name__ ) first_animations.append(rect.animate(run_time=0.5 ).set_stroke(__magic_name__ ) ) second_animations.append(MoveToTarget(__magic_name__, run_time=1.5 ) ) self.play(*__magic_name__ ) self.play(*__magic_name__ ) self.wait()
247
0
from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class __UpperCAmelCase (_UpperCAmelCase ): __snake_case : Union[str, Any] = CustomTokenizer pass
306
import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def __lowerCamelCase ( snake_case__ ,snake_case__ ,snake_case__=None ) -> Optional[int]: """simple docstring""" assert torch_layer.weight.shape == weight.shape, F'{torch_layer} layer.weight does not match' _SCREAMING_SNAKE_CASE = nn.Parameter(snake_case__ ) if bias is not None: assert torch_layer.bias.shape == bias.shape, F'{torch_layer} layer.bias does not match' _SCREAMING_SNAKE_CASE = nn.Parameter(snake_case__ ) def __lowerCamelCase ( snake_case__ ,snake_case__ ,snake_case__ ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE = np.asarray(weights[0] ) _SCREAMING_SNAKE_CASE = np.asarray(weights[1] ) _SCREAMING_SNAKE_CASE = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key ,torch.tensor(snake_case__ ).transpose(1 ,2 ).contiguous().view(-1 ,snake_case__ ) ,) set_param( torch_layer.self_attention.value ,torch.tensor(snake_case__ ).transpose(1 ,2 ).contiguous().view(-1 ,snake_case__ ) ,) set_param( torch_layer.output.dense ,torch.tensor(snake_case__ ).view(-1 ,snake_case__ ).contiguous().transpose(0 ,1 ) ,) def __lowerCamelCase ( snake_case__ ,snake_case__ ,snake_case__ ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE = np.asarray(weights[0] ) _SCREAMING_SNAKE_CASE = np.asarray(weights[1] ) _SCREAMING_SNAKE_CASE = np.asarray(weights[2] ) _SCREAMING_SNAKE_CASE = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query ,torch.tensor(snake_case__ ).transpose(1 ,2 ).contiguous().view(-1 ,snake_case__ ) ,) set_param( torch_layer.self_attention.key ,torch.tensor(snake_case__ ).transpose(1 ,2 ).contiguous().view(-1 ,snake_case__ ) ,) set_param( torch_layer.self_attention.value ,torch.tensor(snake_case__ ).transpose(1 ,2 ).contiguous().view(-1 ,snake_case__ ) ,) set_param( torch_layer.output.dense ,torch.tensor(snake_case__ ).view(-1 ,snake_case__ ).contiguous().transpose(0 ,1 ) ,) def __lowerCamelCase ( snake_case__ ,snake_case__ ,snake_case__ ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE = weights[0][0][0] _SCREAMING_SNAKE_CASE = np.asarray(layer_norm_a[0] ) _SCREAMING_SNAKE_CASE = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm ,torch.tensor(snake_case__ ) ,torch.tensor(snake_case__ ) ,) # lsh weights + output _SCREAMING_SNAKE_CASE = weights[0][1] if len(snake_case__ ) < 4: set_layer_weights_in_torch_lsh(snake_case__ ,torch_block.attention ,snake_case__ ) else: set_layer_weights_in_torch_local(snake_case__ ,torch_block.attention ,snake_case__ ) # intermediate weighs _SCREAMING_SNAKE_CASE = weights[2][0][1][2] # Chunked Feed Forward if len(snake_case__ ) == 4: _SCREAMING_SNAKE_CASE = intermediate_weights[2] # layernorm 2 _SCREAMING_SNAKE_CASE = np.asarray(intermediate_weights[0][0] ) _SCREAMING_SNAKE_CASE = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm ,torch.tensor(snake_case__ ) ,torch.tensor(snake_case__ ) ,) # intermediate dense _SCREAMING_SNAKE_CASE = np.asarray(intermediate_weights[1][0] ) _SCREAMING_SNAKE_CASE = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense ,torch.tensor(snake_case__ ).transpose(0 ,1 ).contiguous() ,torch.tensor(snake_case__ ) ,) # intermediate out _SCREAMING_SNAKE_CASE = np.asarray(intermediate_weights[4][0] ) _SCREAMING_SNAKE_CASE = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense ,torch.tensor(snake_case__ ).transpose(0 ,1 ).contiguous() ,torch.tensor(snake_case__ ) ,) def __lowerCamelCase ( snake_case__ ,snake_case__ ,snake_case__ ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE = torch_model.reformer # word embeds _SCREAMING_SNAKE_CASE = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings ,torch.tensor(snake_case__ ) ,) if isinstance(weights[3] ,snake_case__ ): _SCREAMING_SNAKE_CASE = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): _SCREAMING_SNAKE_CASE = np.asarray(weights[3][emb_idx][0] ) assert ( position_embeddings.weights[emb_idx].shape == emb_weights.shape ), F'{position_embeddings[emb_idx]} emb does not match' _SCREAMING_SNAKE_CASE = nn.Parameter(torch.tensor(snake_case__ ) ) _SCREAMING_SNAKE_CASE = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( snake_case__ ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): _SCREAMING_SNAKE_CASE = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(snake_case__ ,snake_case__ ,snake_case__ ) # output layer norm _SCREAMING_SNAKE_CASE = np.asarray(weights[7][0] ) _SCREAMING_SNAKE_CASE = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm ,torch.tensor(snake_case__ ) ,torch.tensor(snake_case__ ) ,) # output embeddings _SCREAMING_SNAKE_CASE = np.asarray(weights[9][0] ) _SCREAMING_SNAKE_CASE = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder ,torch.tensor(snake_case__ ).transpose(0 ,1 ).contiguous() ,torch.tensor(snake_case__ ) ,) def __lowerCamelCase ( snake_case__ ,snake_case__ ,snake_case__ ) -> Tuple: """simple docstring""" _SCREAMING_SNAKE_CASE = ReformerConfig.from_json_file(snake_case__ ) print(F'Building PyTorch model from configuration: {config}' ) _SCREAMING_SNAKE_CASE = ReformerModelWithLMHead(snake_case__ ) with open(snake_case__ ,"""rb""" ) as f: _SCREAMING_SNAKE_CASE = pickle.load(snake_case__ )["""weights"""] set_model_weights_in_torch(snake_case__ ,snake_case__ ,config.hidden_size ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) torch.save(model.state_dict() ,snake_case__ ) if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--trax_model_pkl_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained Reformer 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.''' ) UpperCamelCase = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
306
1
"""simple docstring""" import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, PerceiverTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): __A : Optional[int] = "pt" elif is_tf_available(): __A : Dict = "tf" else: __A : Tuple = "jax" class _a ( lowerCAmelCase , unittest.TestCase): """simple docstring""" UpperCamelCase__ = PerceiverTokenizer UpperCamelCase__ = False def lowercase__ ( self : Dict )->Any: super().setUp() _UpperCAmelCase = PerceiverTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def lowercase__ ( self : str )->str: return PerceiverTokenizer.from_pretrained('''deepmind/language-perceiver''' ) def lowercase__ ( self : int , **__UpperCamelCase : Optional[Any] )->PerceiverTokenizer: return self.tokenizer_class.from_pretrained(self.tmpdirname , **__UpperCamelCase ) def lowercase__ ( self : Tuple , __UpperCamelCase : Union[str, Any] , __UpperCamelCase : List[str]=False , __UpperCamelCase : List[Any]=2_0 , __UpperCamelCase : Dict=5 )->Tuple[str, list]: # XXX The default common tokenizer tests assume that every ID is decodable on its own. # This assumption is invalid for Perceiver because single bytes might not be # valid utf-8 (byte 128 for instance). # Here we're overriding the smallest possible method to provide # a clean sequence without making the same assumption. _UpperCAmelCase = [] for i in range(len(__UpperCamelCase ) ): try: _UpperCAmelCase = tokenizer.decode([i] , clean_up_tokenization_spaces=__UpperCamelCase ) except UnicodeDecodeError: pass toks.append((i, tok) ) _UpperCAmelCase = list(filter(lambda __UpperCamelCase : re.match(r'''^[ a-zA-Z]+$''' , t[1] ) , __UpperCamelCase ) ) _UpperCAmelCase = list(filter(lambda __UpperCamelCase : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=__UpperCamelCase ) , __UpperCamelCase ) ) if max_length is not None and len(__UpperCamelCase ) > max_length: _UpperCAmelCase = toks[:max_length] if min_length is not None and len(__UpperCamelCase ) < min_length and len(__UpperCamelCase ) > 0: while len(__UpperCamelCase ) < min_length: _UpperCAmelCase = toks + toks # toks_str = [t[1] for t in toks] _UpperCAmelCase = [t[0] for t in toks] # Ensure consistency _UpperCAmelCase = tokenizer.decode(__UpperCamelCase , clean_up_tokenization_spaces=__UpperCamelCase ) if " " not in output_txt and len(__UpperCamelCase ) > 1: _UpperCAmelCase = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=__UpperCamelCase ) + ''' ''' + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=__UpperCamelCase ) ) if with_prefix_space: _UpperCAmelCase = ''' ''' + output_txt _UpperCAmelCase = tokenizer.encode(__UpperCamelCase , add_special_tokens=__UpperCamelCase ) return output_txt, output_ids def lowercase__ ( self : List[str] )->Dict: _UpperCAmelCase = self.perceiver_tokenizer _UpperCAmelCase = '''Unicode €.''' _UpperCAmelCase = tokenizer(__UpperCamelCase ) _UpperCAmelCase = [4, 9_1, 1_1_6, 1_1_1, 1_0_5, 1_1_7, 1_0_6, 1_0_7, 3_8, 2_3_2, 1_3_6, 1_7_8, 5_2, 5] self.assertEqual(encoded['''input_ids'''] , __UpperCamelCase ) # decoding _UpperCAmelCase = tokenizer.decode(__UpperCamelCase ) self.assertEqual(__UpperCamelCase , '''[CLS]Unicode €.[SEP]''' ) _UpperCAmelCase = tokenizer('''e è é ê ë''' ) _UpperCAmelCase = [4, 1_0_7, 3_8, 2_0_1, 1_7_4, 3_8, 2_0_1, 1_7_5, 3_8, 2_0_1, 1_7_6, 3_8, 2_0_1, 1_7_7, 5] self.assertEqual(encoded['''input_ids'''] , __UpperCamelCase ) # decoding _UpperCAmelCase = tokenizer.decode(__UpperCamelCase ) self.assertEqual(__UpperCamelCase , '''[CLS]e è é ê ë[SEP]''' ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('''e è é ê ë''' ) ) , '''[CLS]e è é ê ë[SEP]''' ) def lowercase__ ( self : List[str] )->Union[str, Any]: _UpperCAmelCase = self.perceiver_tokenizer _UpperCAmelCase = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] # fmt: off _UpperCAmelCase = [4, 7_1, 3_8, 1_1_4, 1_1_7, 1_1_6, 1_0_9, 3_8, 1_1_8, 1_0_3, 1_2_0, 1_0_3, 1_0_9, 1_2_0, 1_0_3, 1_1_8, 1_1_0, 3_8, 1_0_8, 1_1_7, 1_2_0, 3_8, 1_2_1, 1_2_3, 1_1_5, 1_1_5, 1_0_3, 1_2_0, 1_1_1, 1_2_8, 1_0_3, 1_2_2, 1_1_1, 1_1_7, 1_1_6, 5_2, 5, 0] # fmt: on _UpperCAmelCase = tokenizer(__UpperCamelCase , padding=__UpperCamelCase , return_tensors=__UpperCamelCase ) self.assertIsInstance(__UpperCamelCase , __UpperCamelCase ) if FRAMEWORK != "jax": _UpperCAmelCase = list(batch.input_ids.numpy()[0] ) else: _UpperCAmelCase = list(batch.input_ids.tolist()[0] ) self.assertListEqual(__UpperCamelCase , __UpperCamelCase ) self.assertEqual((2, 3_8) , batch.input_ids.shape ) self.assertEqual((2, 3_8) , batch.attention_mask.shape ) def lowercase__ ( self : Optional[int] )->int: _UpperCAmelCase = self.perceiver_tokenizer _UpperCAmelCase = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] _UpperCAmelCase = tokenizer(__UpperCamelCase , padding=__UpperCamelCase , return_tensors=__UpperCamelCase ) # check if input_ids are returned and no decoder_input_ids self.assertIn('''input_ids''' , __UpperCamelCase ) self.assertIn('''attention_mask''' , __UpperCamelCase ) self.assertNotIn('''decoder_input_ids''' , __UpperCamelCase ) self.assertNotIn('''decoder_attention_mask''' , __UpperCamelCase ) def lowercase__ ( self : str )->Optional[Any]: _UpperCAmelCase = self.perceiver_tokenizer _UpperCAmelCase = [ '''Summary of the text.''', '''Another summary.''', ] _UpperCAmelCase = tokenizer( text_target=__UpperCamelCase , max_length=3_2 , padding='''max_length''' , truncation=__UpperCamelCase , return_tensors=__UpperCamelCase ) self.assertEqual(3_2 , targets['''input_ids'''].shape[1] ) def lowercase__ ( self : Any )->int: # safety check on max_len default value so we are sure the test works _UpperCAmelCase = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): self.assertNotEqual(tokenizer.model_max_length , 4_2 ) # Now let's start the test _UpperCAmelCase = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc _UpperCAmelCase = tempfile.mkdtemp() _UpperCAmelCase = ''' He is very happy, UNwant\u00E9d,running''' _UpperCAmelCase = tokenizer.encode(__UpperCamelCase , add_special_tokens=__UpperCamelCase ) tokenizer.save_pretrained(__UpperCamelCase ) _UpperCAmelCase = tokenizer.__class__.from_pretrained(__UpperCamelCase ) _UpperCAmelCase = after_tokenizer.encode(__UpperCamelCase , add_special_tokens=__UpperCamelCase ) self.assertListEqual(__UpperCamelCase , __UpperCamelCase ) shutil.rmtree(__UpperCamelCase ) _UpperCAmelCase = self.get_tokenizers(model_max_length=4_2 ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc _UpperCAmelCase = tempfile.mkdtemp() _UpperCAmelCase = ''' He is very happy, UNwant\u00E9d,running''' tokenizer.add_tokens(['''bim''', '''bambam'''] ) _UpperCAmelCase = tokenizer.additional_special_tokens additional_special_tokens.append('''new_additional_special_token''' ) tokenizer.add_special_tokens({'''additional_special_tokens''': additional_special_tokens} ) _UpperCAmelCase = tokenizer.encode(__UpperCamelCase , add_special_tokens=__UpperCamelCase ) tokenizer.save_pretrained(__UpperCamelCase ) _UpperCAmelCase = tokenizer.__class__.from_pretrained(__UpperCamelCase ) _UpperCAmelCase = after_tokenizer.encode(__UpperCamelCase , add_special_tokens=__UpperCamelCase ) self.assertListEqual(__UpperCamelCase , __UpperCamelCase ) self.assertIn('''new_additional_special_token''' , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 4_2 ) _UpperCAmelCase = tokenizer.__class__.from_pretrained(__UpperCamelCase , model_max_length=4_3 ) self.assertEqual(tokenizer.model_max_length , 4_3 ) shutil.rmtree(__UpperCamelCase ) def lowercase__ ( self : List[Any] )->Tuple: _UpperCAmelCase = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(__UpperCamelCase ) with open(os.path.join(__UpperCamelCase , '''special_tokens_map.json''' ) , encoding='''utf-8''' ) as json_file: _UpperCAmelCase = json.load(__UpperCamelCase ) with open(os.path.join(__UpperCamelCase , '''tokenizer_config.json''' ) , encoding='''utf-8''' ) as json_file: _UpperCAmelCase = json.load(__UpperCamelCase ) _UpperCAmelCase = [F'<extra_id_{i}>' for i in range(1_2_5 )] _UpperCAmelCase = added_tokens_extra_ids + [ '''an_additional_special_token''' ] _UpperCAmelCase = added_tokens_extra_ids + [ '''an_additional_special_token''' ] with open(os.path.join(__UpperCamelCase , '''special_tokens_map.json''' ) , '''w''' , encoding='''utf-8''' ) as outfile: json.dump(__UpperCamelCase , __UpperCamelCase ) with open(os.path.join(__UpperCamelCase , '''tokenizer_config.json''' ) , '''w''' , encoding='''utf-8''' ) as outfile: json.dump(__UpperCamelCase , __UpperCamelCase ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files _UpperCAmelCase = tokenizer_class.from_pretrained( __UpperCamelCase , ) self.assertIn( '''an_additional_special_token''' , tokenizer_without_change_in_init.additional_special_tokens ) self.assertEqual( ['''an_additional_special_token'''] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(['''an_additional_special_token'''] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained _UpperCAmelCase = added_tokens_extra_ids + [AddedToken('''a_new_additional_special_token''' , lstrip=__UpperCamelCase )] _UpperCAmelCase = tokenizer_class.from_pretrained( __UpperCamelCase , additional_special_tokens=__UpperCamelCase , ) self.assertIn('''a_new_additional_special_token''' , tokenizer.additional_special_tokens ) self.assertEqual( ['''a_new_additional_special_token'''] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(['''a_new_additional_special_token'''] ) ) , ) def lowercase__ ( self : Optional[int] )->Optional[int]: _UpperCAmelCase = self.perceiver_tokenizer self.assertEqual(tokenizer.decode([1_7_8] ) , '''�''' ) def lowercase__ ( self : Union[str, Any] )->Any: pass def lowercase__ ( self : List[Any] )->List[Any]: pass def lowercase__ ( self : Dict )->int: pass def lowercase__ ( self : List[str] )->Union[str, Any]: pass def lowercase__ ( self : int )->str: # The default common tokenizer tests uses invalid tokens for Perceiver that can only accept one-character # strings and special added tokens as tokens _UpperCAmelCase = self.get_tokenizers(fast=__UpperCamelCase , do_lower_case=__UpperCamelCase ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): _UpperCAmelCase = ['''[CLS]''', '''t''', '''h''', '''i''', '''s''', ''' ''', '''i''', '''s''', ''' ''', '''a''', ''' ''', '''t''', '''e''', '''s''', '''t''', '''[SEP]'''] _UpperCAmelCase = tokenizer.convert_tokens_to_string(__UpperCamelCase ) self.assertIsInstance(__UpperCamelCase , __UpperCamelCase )
326
"""simple docstring""" # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class _a ( lowerCAmelCase): """simple docstring""" UpperCamelCase__ = 42 UpperCamelCase__ = None def lowercase ( _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Dict=0.999 , _SCREAMING_SNAKE_CASE : Any="cosine" , ): '''simple docstring''' if alpha_transform_type == "cosine": def alpha_bar_fn(_SCREAMING_SNAKE_CASE : Tuple ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(_SCREAMING_SNAKE_CASE : Any ): return math.exp(t * -12.0 ) else: raise ValueError(f'Unsupported alpha_tranform_type: {alpha_transform_type}' ) _UpperCAmelCase = [] for i in range(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase = i / num_diffusion_timesteps _UpperCAmelCase = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(_SCREAMING_SNAKE_CASE ) / alpha_bar_fn(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) ) return torch.tensor(_SCREAMING_SNAKE_CASE , dtype=torch.floataa ) class _a ( lowerCAmelCase , lowerCAmelCase): """simple docstring""" UpperCamelCase__ = 1 @register_to_config def __init__( self : List[Any] , __UpperCamelCase : int = 1_0_0_0 , __UpperCamelCase : float = 0.0_0_0_1 , __UpperCamelCase : float = 0.0_2 , __UpperCamelCase : str = "linear" , __UpperCamelCase : Optional[Union[np.ndarray, List[float]]] = None , __UpperCamelCase : bool = True , __UpperCamelCase : bool = True , __UpperCamelCase : int = 0 , __UpperCamelCase : str = "epsilon" , __UpperCamelCase : float = 1.0 , **__UpperCamelCase : Optional[int] , )->Dict: if kwargs.get('''set_alpha_to_one''' , __UpperCamelCase ) is not None: _UpperCAmelCase = ( '''The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.''' ) deprecate('''set_alpha_to_one''' , '''1.0.0''' , __UpperCamelCase , standard_warn=__UpperCamelCase ) _UpperCAmelCase = kwargs['''set_alpha_to_one'''] if trained_betas is not None: _UpperCAmelCase = torch.tensor(__UpperCamelCase , dtype=torch.floataa ) elif beta_schedule == "linear": _UpperCAmelCase = torch.linspace(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. _UpperCAmelCase = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , __UpperCamelCase , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule _UpperCAmelCase = betas_for_alpha_bar(__UpperCamelCase ) else: raise NotImplementedError(F'{beta_schedule} does is not implemented for {self.__class__}' ) _UpperCAmelCase = 1.0 - self.betas _UpperCAmelCase = torch.cumprod(self.alphas , dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. _UpperCAmelCase = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution _UpperCAmelCase = 1.0 # setable values _UpperCAmelCase = None _UpperCAmelCase = torch.from_numpy(np.arange(0 , __UpperCamelCase ).copy().astype(np.intaa ) ) def lowercase__ ( self : str , __UpperCamelCase : torch.FloatTensor , __UpperCamelCase : Optional[int] = None )->torch.FloatTensor: return sample def lowercase__ ( self : Any , __UpperCamelCase : int , __UpperCamelCase : Union[str, torch.device] = None )->Any: if num_inference_steps > self.config.num_train_timesteps: raise ValueError( F'`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:' F' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle' F' maximal {self.config.num_train_timesteps} timesteps.' ) _UpperCAmelCase = num_inference_steps _UpperCAmelCase = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 _UpperCAmelCase = (np.arange(0 , __UpperCamelCase ) * step_ratio).round().copy().astype(np.intaa ) _UpperCAmelCase = torch.from_numpy(__UpperCamelCase ).to(__UpperCamelCase ) self.timesteps += self.config.steps_offset def lowercase__ ( self : Any , __UpperCamelCase : torch.FloatTensor , __UpperCamelCase : int , __UpperCamelCase : torch.FloatTensor , __UpperCamelCase : float = 0.0 , __UpperCamelCase : bool = False , __UpperCamelCase : Optional[torch.FloatTensor] = None , __UpperCamelCase : bool = True , )->Union[DDIMSchedulerOutput, Tuple]: # 1. get previous step value (=t+1) _UpperCAmelCase = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process _UpperCAmelCase = self.alphas_cumprod[timestep] _UpperCAmelCase = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) _UpperCAmelCase = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf if self.config.prediction_type == "epsilon": _UpperCAmelCase = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 _UpperCAmelCase = model_output elif self.config.prediction_type == "sample": _UpperCAmelCase = model_output _UpperCAmelCase = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": _UpperCAmelCase = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output _UpperCAmelCase = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( F'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or' ''' `v_prediction`''' ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: _UpperCAmelCase = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf _UpperCAmelCase = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf _UpperCAmelCase = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=__UpperCamelCase , pred_original_sample=__UpperCamelCase ) def __len__( self : Any )->str: return self.config.num_train_timesteps
326
1
'''simple docstring''' class _snake_case : def __init__( self : Tuple ,SCREAMING_SNAKE_CASE__ : list ): SCREAMING_SNAKE_CASE:Any = set_counts SCREAMING_SNAKE_CASE:Tuple = max(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Union[str, Any] = len(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Union[str, Any] = [1] * num_sets SCREAMING_SNAKE_CASE:str = list(range(SCREAMING_SNAKE_CASE__ ) ) def __UpperCamelCase ( self : str ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ): SCREAMING_SNAKE_CASE:Optional[Any] = self.get_parent(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE:Union[str, Any] = self.get_parent(SCREAMING_SNAKE_CASE__ ) 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] SCREAMING_SNAKE_CASE:Optional[Any] = 0 SCREAMING_SNAKE_CASE:List[str] = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 SCREAMING_SNAKE_CASE:Optional[int] = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] SCREAMING_SNAKE_CASE:Optional[Any] = 0 SCREAMING_SNAKE_CASE:str = src_parent SCREAMING_SNAKE_CASE:Dict = self.set_counts[src_parent] SCREAMING_SNAKE_CASE:Dict = max(self.max_set ,SCREAMING_SNAKE_CASE__ ) return True def __UpperCamelCase ( self : int ,SCREAMING_SNAKE_CASE__ : int ): if self.parents[disj_set] == disj_set: return disj_set SCREAMING_SNAKE_CASE:Tuple = self.get_parent(self.parents[disj_set] ) return self.parents[disj_set]
139
'''simple docstring''' from math import factorial, pi def A_ ( snake_case , snake_case = 30 ): if not isinstance(snake_case , (int, float) ): raise ValueError("maclaurin_sin() requires either an int or float for theta" ) if not isinstance(snake_case , snake_case ) or accuracy <= 0: raise ValueError("maclaurin_sin() requires a positive int for accuracy" ) SCREAMING_SNAKE_CASE:Optional[int] = float(snake_case ) SCREAMING_SNAKE_CASE:Optional[Any] = theta // (2 * pi) theta -= 2 * div * pi return sum( (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1 ) for r in range(snake_case ) ) def A_ ( snake_case , snake_case = 30 ): if not isinstance(snake_case , (int, float) ): raise ValueError("maclaurin_cos() requires either an int or float for theta" ) if not isinstance(snake_case , snake_case ) or accuracy <= 0: raise ValueError("maclaurin_cos() requires a positive int for accuracy" ) SCREAMING_SNAKE_CASE:Optional[Any] = float(snake_case ) SCREAMING_SNAKE_CASE:List[str] = theta // (2 * pi) theta -= 2 * div * pi return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r ) for r in range(snake_case ) ) if __name__ == "__main__": import doctest doctest.testmod() print(maclaurin_sin(10)) print(maclaurin_sin(-10)) print(maclaurin_sin(10, 15)) print(maclaurin_sin(-10, 15)) print(maclaurin_cos(5)) print(maclaurin_cos(-5)) print(maclaurin_cos(10, 15)) print(maclaurin_cos(-10, 15))
139
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCamelCase_ = { "configuration_graphormer": ["GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "GraphormerConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase_ = [ "GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "GraphormerForGraphClassification", "GraphormerModel", "GraphormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_graphormer import GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, GraphormerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_graphormer import ( GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST, GraphormerForGraphClassification, GraphormerModel, GraphormerPreTrainedModel, ) else: import sys UpperCamelCase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
369
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_nllb import NllbTokenizer else: UpperCamelCase_ = None UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"} UpperCamelCase_ = { "vocab_file": { "facebook/nllb-200-distilled-600M": ( "https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model" ), }, "tokenizer_file": { "facebook/nllb-200-distilled-600M": ( "https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json" ), }, } UpperCamelCase_ = { "facebook/nllb-large-en-ro": 1_0_2_4, "facebook/nllb-200-distilled-600M": 1_0_2_4, } # fmt: off UpperCamelCase_ = ["ace_Arab", "ace_Latn", "acm_Arab", "acq_Arab", "aeb_Arab", "afr_Latn", "ajp_Arab", "aka_Latn", "amh_Ethi", "apc_Arab", "arb_Arab", "ars_Arab", "ary_Arab", "arz_Arab", "asm_Beng", "ast_Latn", "awa_Deva", "ayr_Latn", "azb_Arab", "azj_Latn", "bak_Cyrl", "bam_Latn", "ban_Latn", "bel_Cyrl", "bem_Latn", "ben_Beng", "bho_Deva", "bjn_Arab", "bjn_Latn", "bod_Tibt", "bos_Latn", "bug_Latn", "bul_Cyrl", "cat_Latn", "ceb_Latn", "ces_Latn", "cjk_Latn", "ckb_Arab", "crh_Latn", "cym_Latn", "dan_Latn", "deu_Latn", "dik_Latn", "dyu_Latn", "dzo_Tibt", "ell_Grek", "eng_Latn", "epo_Latn", "est_Latn", "eus_Latn", "ewe_Latn", "fao_Latn", "pes_Arab", "fij_Latn", "fin_Latn", "fon_Latn", "fra_Latn", "fur_Latn", "fuv_Latn", "gla_Latn", "gle_Latn", "glg_Latn", "grn_Latn", "guj_Gujr", "hat_Latn", "hau_Latn", "heb_Hebr", "hin_Deva", "hne_Deva", "hrv_Latn", "hun_Latn", "hye_Armn", "ibo_Latn", "ilo_Latn", "ind_Latn", "isl_Latn", "ita_Latn", "jav_Latn", "jpn_Jpan", "kab_Latn", "kac_Latn", "kam_Latn", "kan_Knda", "kas_Arab", "kas_Deva", "kat_Geor", "knc_Arab", "knc_Latn", "kaz_Cyrl", "kbp_Latn", "kea_Latn", "khm_Khmr", "kik_Latn", "kin_Latn", "kir_Cyrl", "kmb_Latn", "kon_Latn", "kor_Hang", "kmr_Latn", "lao_Laoo", "lvs_Latn", "lij_Latn", "lim_Latn", "lin_Latn", "lit_Latn", "lmo_Latn", "ltg_Latn", "ltz_Latn", "lua_Latn", "lug_Latn", "luo_Latn", "lus_Latn", "mag_Deva", "mai_Deva", "mal_Mlym", "mar_Deva", "min_Latn", "mkd_Cyrl", "plt_Latn", "mlt_Latn", "mni_Beng", "khk_Cyrl", "mos_Latn", "mri_Latn", "zsm_Latn", "mya_Mymr", "nld_Latn", "nno_Latn", "nob_Latn", "npi_Deva", "nso_Latn", "nus_Latn", "nya_Latn", "oci_Latn", "gaz_Latn", "ory_Orya", "pag_Latn", "pan_Guru", "pap_Latn", "pol_Latn", "por_Latn", "prs_Arab", "pbt_Arab", "quy_Latn", "ron_Latn", "run_Latn", "rus_Cyrl", "sag_Latn", "san_Deva", "sat_Beng", "scn_Latn", "shn_Mymr", "sin_Sinh", "slk_Latn", "slv_Latn", "smo_Latn", "sna_Latn", "snd_Arab", "som_Latn", "sot_Latn", "spa_Latn", "als_Latn", "srd_Latn", "srp_Cyrl", "ssw_Latn", "sun_Latn", "swe_Latn", "swh_Latn", "szl_Latn", "tam_Taml", "tat_Cyrl", "tel_Telu", "tgk_Cyrl", "tgl_Latn", "tha_Thai", "tir_Ethi", "taq_Latn", "taq_Tfng", "tpi_Latn", "tsn_Latn", "tso_Latn", "tuk_Latn", "tum_Latn", "tur_Latn", "twi_Latn", "tzm_Tfng", "uig_Arab", "ukr_Cyrl", "umb_Latn", "urd_Arab", "uzn_Latn", "vec_Latn", "vie_Latn", "war_Latn", "wol_Latn", "xho_Latn", "ydd_Hebr", "yor_Latn", "yue_Hant", "zho_Hans", "zho_Hant", "zul_Latn"] class _a ( SCREAMING_SNAKE_CASE ): '''simple docstring''' A : Optional[Any] = VOCAB_FILES_NAMES A : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A : Dict = PRETRAINED_VOCAB_FILES_MAP A : Any = ['''input_ids''', '''attention_mask'''] A : Dict = NllbTokenizer A : List[int] = [] A : List[int] = [] def __init__( self, A=None, A=None, A="<s>", A="</s>", A="</s>", A="<s>", A="<unk>", A="<pad>", A="<mask>", A=None, A=None, A=None, A=False, **A, ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = AddedToken(A, lstrip=A, rstrip=A ) if isinstance(A, A ) else mask_token SCREAMING_SNAKE_CASE : Tuple = legacy_behaviour super().__init__( vocab_file=A, tokenizer_file=A, bos_token=A, eos_token=A, sep_token=A, cls_token=A, unk_token=A, pad_token=A, mask_token=A, src_lang=A, tgt_lang=A, additional_special_tokens=A, legacy_behaviour=A, **A, ) SCREAMING_SNAKE_CASE : Any = vocab_file SCREAMING_SNAKE_CASE : Optional[int] = False if not self.vocab_file else True SCREAMING_SNAKE_CASE : List[str] = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({'additional_special_tokens': _additional_special_tokens} ) SCREAMING_SNAKE_CASE : Optional[Any] = { lang_code: self.convert_tokens_to_ids(A ) for lang_code in FAIRSEQ_LANGUAGE_CODES } SCREAMING_SNAKE_CASE : Dict = src_lang if src_lang is not None else 'eng_Latn' SCREAMING_SNAKE_CASE : Optional[Any] = self.convert_tokens_to_ids(self._src_lang ) SCREAMING_SNAKE_CASE : List[str] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def UpperCamelCase_ ( self ): '''simple docstring''' return self._src_lang @src_lang.setter def UpperCamelCase_ ( self, A ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def UpperCamelCase_ ( self, A, A = None ): '''simple docstring''' if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def UpperCamelCase_ ( self, A, A = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE : Dict = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def UpperCamelCase_ ( self, A, A, A, A, **A ): '''simple docstring''' if src_lang is None or tgt_lang is None: raise ValueError('Translation requires a `src_lang` and a `tgt_lang` for this model' ) SCREAMING_SNAKE_CASE : Union[str, Any] = src_lang SCREAMING_SNAKE_CASE : List[Any] = self(A, add_special_tokens=A, return_tensors=A, **A ) SCREAMING_SNAKE_CASE : Any = self.convert_tokens_to_ids(A ) SCREAMING_SNAKE_CASE : int = tgt_lang_id return inputs def UpperCamelCase_ ( self, A, A = "eng_Latn", A = None, A = "fra_Latn", **A, ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = src_lang SCREAMING_SNAKE_CASE : List[Any] = tgt_lang return super().prepare_seqaseq_batch(A, A, **A ) def UpperCamelCase_ ( self ): '''simple docstring''' return self.set_src_lang_special_tokens(self.src_lang ) def UpperCamelCase_ ( self ): '''simple docstring''' return self.set_tgt_lang_special_tokens(self.tgt_lang ) def UpperCamelCase_ ( self, A ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.convert_tokens_to_ids(A ) if self.legacy_behaviour: SCREAMING_SNAKE_CASE : str = [] SCREAMING_SNAKE_CASE : List[Any] = [self.eos_token_id, self.cur_lang_code] else: SCREAMING_SNAKE_CASE : Tuple = [self.cur_lang_code] SCREAMING_SNAKE_CASE : List[Any] = [self.eos_token_id] SCREAMING_SNAKE_CASE : Tuple = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE : int = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE : Tuple = processors.TemplateProcessing( single=prefix_tokens_str + ['$A'] + suffix_tokens_str, pair=prefix_tokens_str + ['$A', '$B'] + suffix_tokens_str, special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str, self.prefix_tokens + self.suffix_tokens ) ), ) def UpperCamelCase_ ( self, A ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.convert_tokens_to_ids(A ) if self.legacy_behaviour: SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id, self.cur_lang_code] else: SCREAMING_SNAKE_CASE : Dict = [self.cur_lang_code] SCREAMING_SNAKE_CASE : str = [self.eos_token_id] SCREAMING_SNAKE_CASE : Optional[int] = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE : List[str] = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE : Union[str, Any] = processors.TemplateProcessing( single=prefix_tokens_str + ['$A'] + suffix_tokens_str, pair=prefix_tokens_str + ['$A', '$B'] + suffix_tokens_str, special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str, self.prefix_tokens + self.suffix_tokens ) ), ) def UpperCamelCase_ ( self, A, A = 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(A ): logger.error(F"Vocabulary path ({save_directory}) should be a directory." ) return SCREAMING_SNAKE_CASE : int = os.path.join( A, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A ): copyfile(self.vocab_file, A ) return (out_vocab_file,)
246
0
import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": a_ = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) parser.add_argument( '--original_config_file', type=str, required=True, help='The YAML config file corresponding to the original architecture.', ) parser.add_argument( '--num_in_channels', default=None, type=int, help='The number of input channels. If `None` number of input channels will be automatically inferred.', ) parser.add_argument( '--image_size', default=512, type=int, help=( 'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2' ' Base. Use 768 for Stable Diffusion v2.' ), ) parser.add_argument( '--extract_ema', action='store_true', help=( 'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights' ' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield' ' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.' ), ) parser.add_argument( '--upcast_attention', action='store_true', help=( 'Whether the attention computation should always be upcasted. This is necessary when running stable' ' diffusion 2.1.' ), ) parser.add_argument( '--from_safetensors', action='store_true', help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.', ) parser.add_argument( '--to_safetensors', action='store_true', help='Whether to store pipeline in safetensors format or not.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)') def lowerCamelCase__ ( _a): if string == "True": return True elif string == "False": return False else: raise ValueError(f"could not parse string as bool {string}") parser.add_argument( '--use_linear_projection', help='Override for use linear projection', required=False, type=parse_bool ) parser.add_argument('--cross_attention_dim', help='Override for cross attention_dim', required=False, type=int) a_ = parser.parse_args() a_ = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
76
from __future__ import annotations from typing import Dict from ...configuration_utils import PretrainedConfig _UpperCAmelCase : Dict ={ """susnato/ernie-m-base_pytorch""": """https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json""", """susnato/ernie-m-large_pytorch""": """https://huggingface.co/susnato/ernie-m-large_pytorch/blob/main/config.json""", } class snake_case__( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = """ernie_m""" SCREAMING_SNAKE_CASE__ : Dict[str, str] = {"dropout": "classifier_dropout", "num_classes": "num_labels"} def __init__( self , __lowercase = 2_5_0_0_0_2 , __lowercase = 7_6_8 , __lowercase = 1_2 , __lowercase = 1_2 , __lowercase = 3_0_7_2 , __lowercase = "gelu" , __lowercase = 0.1 , __lowercase = 0.1 , __lowercase = 5_1_4 , __lowercase = 0.02 , __lowercase = 1 , __lowercase = 1e-05 , __lowercase=None , __lowercase=False , __lowercase=0.0 , **__lowercase , ) -> Tuple: super().__init__(pad_token_id=__lowercase , **__lowercase ) lowerCAmelCase_ : Tuple = vocab_size lowerCAmelCase_ : Dict = hidden_size lowerCAmelCase_ : Tuple = num_hidden_layers lowerCAmelCase_ : int = num_attention_heads lowerCAmelCase_ : Dict = intermediate_size lowerCAmelCase_ : int = hidden_act lowerCAmelCase_ : Union[str, Any] = hidden_dropout_prob lowerCAmelCase_ : Any = attention_probs_dropout_prob lowerCAmelCase_ : Union[str, Any] = max_position_embeddings lowerCAmelCase_ : str = initializer_range lowerCAmelCase_ : List[str] = layer_norm_eps lowerCAmelCase_ : List[Any] = classifier_dropout lowerCAmelCase_ : Any = is_decoder lowerCAmelCase_ : List[Any] = act_dropout
262
0
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record __lowerCamelCase = """\\n@article{wang2019superglue,\n title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},\n journal={arXiv preprint arXiv:1905.00537},\n year={2019}\n}\n""" __lowerCamelCase = """\\nSuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after\nGLUE with a new set of more difficult language understanding tasks, improved\nresources, and a new public leaderboard.\n""" __lowerCamelCase = """\nCompute SuperGLUE evaluation metric associated to each SuperGLUE dataset.\nArgs:\n predictions: list of predictions to score. Depending on the SuperGlUE subset:\n - for \'record\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'prediction_text\': the predicted answer text\n - for \'multirc\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question-answer pair as specified by the dataset\n - \'prediction\': the predicted answer label\n - otherwise: list of predicted labels\n references: list of reference labels. Depending on the SuperGLUE subset:\n - for \'record\': list of question-answers dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'answers\': list of possible answers\n - otherwise: list of reference labels\nReturns: depending on the SuperGLUE subset:\n - for \'record\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1\': F1 score\n - for \'multirc\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1_m\': Per-question macro-F1 score\n - \'f1_a\': Average F1 score over all answers\n - for \'axb\':\n \'matthews_correlation\': Matthew Correlation\n - for \'cb\':\n - \'accuracy\': Accuracy\n - \'f1\': F1 score\n - for all others:\n - \'accuracy\': Accuracy\nExamples:\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of [\"copa\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"boolq\", \"axg\"]\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\')\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\')\n >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}]\n >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\')\n >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'matthews_correlation\': 1.0}\n""" def UpperCamelCase ( __lowerCamelCase : Optional[int] , __lowerCamelCase : Dict ): return float((preds == labels).mean() ) def UpperCamelCase ( __lowerCamelCase : Any , __lowerCamelCase : Dict , __lowerCamelCase : Dict="binary" ): snake_case : Optional[Any] = simple_accuracy(_lowercase , _lowercase ) snake_case : Union[str, Any] = float(fa_score(y_true=_lowercase , y_pred=_lowercase , average=_lowercase ) ) return { "accuracy": acc, "f1": fa, } def UpperCamelCase ( __lowerCamelCase : Union[str, Any] , __lowerCamelCase : str ): snake_case : Tuple = {} for id_pred, label in zip(_lowercase , _lowercase ): snake_case : str = f"""{id_pred['idx']['paragraph']}-{id_pred['idx']['question']}""" snake_case : Any = id_pred["prediction"] if question_id in question_map: question_map[question_id].append((pred, label) ) else: snake_case : Tuple = [(pred, label)] snake_case , snake_case : int = [], [] for question, preds_labels in question_map.items(): snake_case , snake_case : Any = zip(*_lowercase ) snake_case : int = fa_score(y_true=_lowercase , y_pred=_lowercase , average="macro" ) fas.append(_lowercase ) snake_case : Tuple = int(sum(pred == label for pred, label in preds_labels ) == len(_lowercase ) ) ems.append(_lowercase ) snake_case : int = float(sum(_lowercase ) / len(_lowercase ) ) snake_case : List[Any] = sum(_lowercase ) / len(_lowercase ) snake_case : Union[str, Any] = float(fa_score(y_true=_lowercase , y_pred=[id_pred["prediction"] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class UpperCAmelCase ( datasets.Metric ): def _SCREAMING_SNAKE_CASE (self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( "You should supply a configuration name selected in " "[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="numpy" if not self.config_name == "record" and not self.config_name == "multirc" else None , ) def _SCREAMING_SNAKE_CASE (self : int ) -> List[Any]: '''simple docstring''' if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("int64" ), "query": datasets.Value("int64" ), }, "prediction_text": datasets.Value("string" ), }, "references": { "idx": { "passage": datasets.Value("int64" ), "query": datasets.Value("int64" ), }, "answers": datasets.Sequence(datasets.Value("string" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("int64" ), "paragraph": datasets.Value("int64" ), "question": datasets.Value("int64" ), }, "prediction": datasets.Value("int64" ), }, "references": datasets.Value("int64" ), } else: return { "predictions": datasets.Value("int64" ), "references": datasets.Value("int64" ), } def _SCREAMING_SNAKE_CASE (self : List[str] , snake_case__ : Any , snake_case__ : Union[str, Any] ) -> Optional[int]: '''simple docstring''' if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(__A , __A )} elif self.config_name == "cb": return acc_and_fa(__A , __A , fa_avg="macro" ) elif self.config_name == "record": snake_case : str = [ { "qas": [ {"id": ref["idx"]["query"], "answers": [{"text": ans} for ans in ref["answers"]]} for ref in references ] } ] snake_case : List[Any] = {pred["idx"]["query"]: pred["prediction_text"] for pred in predictions} return evaluate_record(__A , __A )[0] elif self.config_name == "multirc": return evaluate_multirc(__A , __A ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(__A , __A )} else: raise KeyError( "You should supply a configuration name selected in " "[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]" )
358
import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu __lowerCamelCase = get_tests_dir() + """/test_data/fsmt/fsmt_val_data.json""" with io.open(filename, """r""", encoding="""utf-8""") as f: __lowerCamelCase = json.load(f) @require_torch class UpperCAmelCase ( unittest.TestCase ): def _SCREAMING_SNAKE_CASE (self : Dict , snake_case__ : Optional[int] ) -> Any: '''simple docstring''' return FSMTTokenizer.from_pretrained(snake_case__ ) def _SCREAMING_SNAKE_CASE (self : Optional[Any] , snake_case__ : str ) -> List[str]: '''simple docstring''' snake_case : List[Any] = FSMTForConditionalGeneration.from_pretrained(snake_case__ ).to(snake_case__ ) if torch_device == "cuda": model.half() return model @parameterized.expand( [ ["en-ru", 26.0], ["ru-en", 22.0], ["en-de", 22.0], ["de-en", 29.0], ] ) @slow def _SCREAMING_SNAKE_CASE (self : str , snake_case__ : Tuple , snake_case__ : Optional[int] ) -> Any: '''simple docstring''' snake_case : Optional[int] = f"""facebook/wmt19-{pair}""" snake_case : Optional[Any] = self.get_tokenizer(snake_case__ ) snake_case : Dict = self.get_model(snake_case__ ) snake_case : List[Any] = bleu_data[pair]["src"] snake_case : int = bleu_data[pair]["tgt"] snake_case : Union[str, Any] = tokenizer(snake_case__ , return_tensors="pt" , truncation=snake_case__ , padding="longest" ).to(snake_case__ ) snake_case : str = model.generate( input_ids=batch.input_ids , num_beams=8 , ) snake_case : Optional[int] = tokenizer.batch_decode( snake_case__ , skip_special_tokens=snake_case__ , clean_up_tokenization_spaces=snake_case__ ) snake_case : Optional[int] = calculate_bleu(snake_case__ , snake_case__ ) print(snake_case__ ) self.assertGreaterEqual(scores["bleu"] , snake_case__ )
10
0
"""simple docstring""" from math import factorial def __SCREAMING_SNAKE_CASE ( A_ = 1_00 ): return sum(int(A_ ) for x in str(factorial(A_ ) ) ) if __name__ == "__main__": print(solution(int(input('''Enter the Number: ''').strip())))
106
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __UpperCamelCase : Optional[Any] = { '''configuration_rag''': ['''RagConfig'''], '''retrieval_rag''': ['''RagRetriever'''], '''tokenization_rag''': ['''RagTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Tuple = [ '''RagModel''', '''RagPreTrainedModel''', '''RagSequenceForGeneration''', '''RagTokenForGeneration''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Union[str, Any] = [ '''TFRagModel''', '''TFRagPreTrainedModel''', '''TFRagSequenceForGeneration''', '''TFRagTokenForGeneration''', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys __UpperCamelCase : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
106
1
'''simple docstring''' from dataclasses import dataclass, field from typing import Optional from transformers import AutoConfig, AutoImageProcessor, AutoTokenizer, FlaxVisionEncoderDecoderModel, HfArgumentParser @dataclass class lowerCAmelCase_ : '''simple docstring''' lowerCAmelCase_ : str = field( metadata={"""help""": """The output directory where the model will be written."""} , ) lowerCAmelCase_ : str = field( metadata={ """help""": ( """The encoder model checkpoint for weights initialization.""" """Don't set if you want to train an encoder model from scratch.""" ) } , ) lowerCAmelCase_ : str = field( metadata={ """help""": ( """The decoder model checkpoint for weights initialization.""" """Don't set if you want to train a decoder model from scratch.""" ) } , ) lowerCAmelCase_ : Optional[str] = field( default=_a , metadata={"""help""": """Pretrained encoder config name or path if not the same as encoder_model_name"""} ) lowerCAmelCase_ : Optional[str] = field( default=_a , metadata={"""help""": """Pretrained decoder config name or path if not the same as decoder_model_name"""} ) def _UpperCamelCase ( ): '''simple docstring''' UpperCAmelCase__ = HfArgumentParser((ModelArguments,) ) (UpperCAmelCase__ ) = parser.parse_args_into_dataclasses() # Load pretrained model and tokenizer # Use explicit specified encoder config if model_args.encoder_config_name: UpperCAmelCase__ = AutoConfig.from_pretrained(model_args.encoder_config_name ) # Use pretrained encoder model's config else: UpperCAmelCase__ = AutoConfig.from_pretrained(model_args.encoder_model_name_or_path ) # Use explicit specified decoder config if model_args.decoder_config_name: UpperCAmelCase__ = AutoConfig.from_pretrained(model_args.decoder_config_name ) # Use pretrained decoder model's config else: UpperCAmelCase__ = AutoConfig.from_pretrained(model_args.decoder_model_name_or_path ) # necessary for `from_encoder_decoder_pretrained` when `decoder_config` is passed UpperCAmelCase__ = True UpperCAmelCase__ = True UpperCAmelCase__ = FlaxVisionEncoderDecoderModel.from_encoder_decoder_pretrained( encoder_pretrained_model_name_or_path=model_args.encoder_model_name_or_path , decoder_pretrained_model_name_or_path=model_args.decoder_model_name_or_path , encoder_config=SCREAMING_SNAKE_CASE__ , decoder_config=SCREAMING_SNAKE_CASE__ , ) # GPT2 only has bos/eos tokens but not decoder_start/pad tokens UpperCAmelCase__ = decoder_config.decoder_start_token_id UpperCAmelCase__ = decoder_config.pad_token_id if decoder_start_token_id is None: UpperCAmelCase__ = decoder_config.bos_token_id if pad_token_id is None: UpperCAmelCase__ = decoder_config.eos_token_id # This is necessary to make Flax's generate() work UpperCAmelCase__ = decoder_config.eos_token_id UpperCAmelCase__ = decoder_start_token_id UpperCAmelCase__ = pad_token_id UpperCAmelCase__ = AutoImageProcessor.from_pretrained(model_args.encoder_model_name_or_path ) UpperCAmelCase__ = AutoTokenizer.from_pretrained(model_args.decoder_model_name_or_path ) UpperCAmelCase__ = tokenizer.convert_ids_to_tokens(model.config.pad_token_id ) model.save_pretrained(model_args.output_dir ) image_processor.save_pretrained(model_args.output_dir ) tokenizer.save_pretrained(model_args.output_dir ) if __name__ == "__main__": main()
367
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase_ = logging.get_logger(__name__) UpperCAmelCase_ = { 'hustvl/yolos-small': 'https://huggingface.co/hustvl/yolos-small/resolve/main/config.json', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class lowerCAmelCase_ ( lowerCamelCase_ ): '''simple docstring''' lowerCAmelCase_ : List[str] = """yolos""" def __init__( self : str , _UpperCAmelCase : int=7_68 , _UpperCAmelCase : Dict=12 , _UpperCAmelCase : Union[str, Any]=12 , _UpperCAmelCase : Tuple=30_72 , _UpperCAmelCase : int="gelu" , _UpperCAmelCase : Optional[Any]=0.0 , _UpperCAmelCase : List[str]=0.0 , _UpperCAmelCase : Dict=0.02 , _UpperCAmelCase : Optional[Any]=1E-12 , _UpperCAmelCase : Tuple=[5_12, 8_64] , _UpperCAmelCase : str=16 , _UpperCAmelCase : Optional[int]=3 , _UpperCAmelCase : Tuple=True , _UpperCAmelCase : int=1_00 , _UpperCAmelCase : List[str]=True , _UpperCAmelCase : Dict=False , _UpperCAmelCase : Dict=1 , _UpperCAmelCase : Union[str, Any]=5 , _UpperCAmelCase : Dict=2 , _UpperCAmelCase : int=5 , _UpperCAmelCase : str=2 , _UpperCAmelCase : Tuple=0.1 , **_UpperCAmelCase : List[Any] , ): """simple docstring""" super().__init__(**_UpperCAmelCase ) UpperCAmelCase__ = hidden_size UpperCAmelCase__ = num_hidden_layers UpperCAmelCase__ = num_attention_heads UpperCAmelCase__ = intermediate_size UpperCAmelCase__ = hidden_act UpperCAmelCase__ = hidden_dropout_prob UpperCAmelCase__ = attention_probs_dropout_prob UpperCAmelCase__ = initializer_range UpperCAmelCase__ = layer_norm_eps UpperCAmelCase__ = image_size UpperCAmelCase__ = patch_size UpperCAmelCase__ = num_channels UpperCAmelCase__ = qkv_bias UpperCAmelCase__ = num_detection_tokens UpperCAmelCase__ = use_mid_position_embeddings UpperCAmelCase__ = auxiliary_loss # Hungarian matcher UpperCAmelCase__ = class_cost UpperCAmelCase__ = bbox_cost UpperCAmelCase__ = giou_cost # Loss coefficients UpperCAmelCase__ = bbox_loss_coefficient UpperCAmelCase__ = giou_loss_coefficient UpperCAmelCase__ = eos_coefficient class lowerCAmelCase_ ( lowerCamelCase_ ): '''simple docstring''' lowerCAmelCase_ : List[str] = version.parse("""1.11""" ) @property def SCREAMING_SNAKE_CASE__ ( self : int ): """simple docstring""" return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" return 1E-4 @property def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" return 12
61
0
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING __snake_case = logging.get_logger(__name__) __snake_case = { '''Salesforce/instruct-blip-flan-t5''': '''https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json''', } class lowercase ( A__ ): """simple docstring""" _a = 'instructblip_vision_model' def __init__( self , UpperCamelCase_=1408 , UpperCamelCase_=6144 , UpperCamelCase_=39 , UpperCamelCase_=16 , UpperCamelCase_=224 , UpperCamelCase_=14 , UpperCamelCase_="gelu" , UpperCamelCase_=1e-6 , UpperCamelCase_=0.0 , UpperCamelCase_=1e-10 , UpperCamelCase_=True , **UpperCamelCase_ , ): '''simple docstring''' super().__init__(**UpperCamelCase_ ) UpperCamelCase__ :Optional[Any] = hidden_size UpperCamelCase__ :List[Any] = intermediate_size UpperCamelCase__ :Optional[Any] = num_hidden_layers UpperCamelCase__ :List[str] = num_attention_heads UpperCamelCase__ :List[Any] = patch_size UpperCamelCase__ :Tuple = image_size UpperCamelCase__ :List[Any] = initializer_range UpperCamelCase__ :int = attention_dropout UpperCamelCase__ :Union[str, Any] = layer_norm_eps UpperCamelCase__ :List[Any] = hidden_act UpperCamelCase__ :str = qkv_bias @classmethod def lowerCAmelCase__ ( cls , UpperCamelCase_ , **UpperCamelCase_ ): '''simple docstring''' cls._set_token_in_kwargs(UpperCamelCase_ ) UpperCamelCase__ , UpperCamelCase__ :Tuple = cls.get_config_dict(UpperCamelCase_ , **UpperCamelCase_ ) # get the vision config dict if we are loading from InstructBlipConfig if config_dict.get('''model_type''' ) == "instructblip": UpperCamelCase__ :List[Any] = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(UpperCamelCase_ , **UpperCamelCase_ ) class lowercase ( A__ ): """simple docstring""" _a = 'instructblip_qformer' def __init__( self , UpperCamelCase_=30522 , UpperCamelCase_=768 , UpperCamelCase_=12 , UpperCamelCase_=12 , UpperCamelCase_=3072 , UpperCamelCase_="gelu" , UpperCamelCase_=0.1 , UpperCamelCase_=0.1 , UpperCamelCase_=512 , UpperCamelCase_=0.02 , UpperCamelCase_=1e-12 , UpperCamelCase_=0 , UpperCamelCase_="absolute" , UpperCamelCase_=2 , UpperCamelCase_=1408 , **UpperCamelCase_ , ): '''simple docstring''' super().__init__(pad_token_id=UpperCamelCase_ , **UpperCamelCase_ ) UpperCamelCase__ :List[Any] = vocab_size UpperCamelCase__ :List[str] = hidden_size UpperCamelCase__ :List[str] = num_hidden_layers UpperCamelCase__ :Any = num_attention_heads UpperCamelCase__ :List[str] = hidden_act UpperCamelCase__ :List[str] = intermediate_size UpperCamelCase__ :str = hidden_dropout_prob UpperCamelCase__ :Union[str, Any] = attention_probs_dropout_prob UpperCamelCase__ :List[str] = max_position_embeddings UpperCamelCase__ :List[Any] = initializer_range UpperCamelCase__ :List[str] = layer_norm_eps UpperCamelCase__ :Dict = position_embedding_type UpperCamelCase__ :int = cross_attention_frequency UpperCamelCase__ :str = encoder_hidden_size @classmethod def lowerCAmelCase__ ( cls , UpperCamelCase_ , **UpperCamelCase_ ): '''simple docstring''' cls._set_token_in_kwargs(UpperCamelCase_ ) UpperCamelCase__ , UpperCamelCase__ :Dict = cls.get_config_dict(UpperCamelCase_ , **UpperCamelCase_ ) # get the qformer config dict if we are loading from InstructBlipConfig if config_dict.get('''model_type''' ) == "instructblip": UpperCamelCase__ :str = config_dict['''qformer_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(UpperCamelCase_ , **UpperCamelCase_ ) class lowercase ( A__ ): """simple docstring""" _a = 'instructblip' _a = True def __init__( self , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=32 , **UpperCamelCase_ ): '''simple docstring''' super().__init__(**UpperCamelCase_ ) if vision_config is None: UpperCamelCase__ :int = {} logger.info('''vision_config is None. initializing the InstructBlipVisionConfig with default values.''' ) if qformer_config is None: UpperCamelCase__ :Union[str, Any] = {} logger.info('''qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.''' ) if text_config is None: UpperCamelCase__ :str = {} logger.info('''text_config is None. Initializing the text config with default values (`OPTConfig`).''' ) UpperCamelCase__ :Union[str, Any] = InstructBlipVisionConfig(**UpperCamelCase_ ) UpperCamelCase__ :str = InstructBlipQFormerConfig(**UpperCamelCase_ ) UpperCamelCase__ :List[str] = text_config['''model_type'''] if '''model_type''' in text_config else '''opt''' UpperCamelCase__ :Union[str, Any] = CONFIG_MAPPING[text_model_type](**UpperCamelCase_ ) UpperCamelCase__ :Optional[int] = self.text_config.tie_word_embeddings UpperCamelCase__ :int = self.text_config.is_encoder_decoder UpperCamelCase__ :Union[str, Any] = num_query_tokens UpperCamelCase__ :Optional[Any] = self.vision_config.hidden_size UpperCamelCase__ :Any = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES UpperCamelCase__ :str = 1.0 UpperCamelCase__ :List[str] = 0.02 @classmethod def lowerCAmelCase__ ( cls , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , **UpperCamelCase_ , ): '''simple docstring''' return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **UpperCamelCase_ , ) def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :List[str] = copy.deepcopy(self.__dict__ ) UpperCamelCase__ :List[str] = self.vision_config.to_dict() UpperCamelCase__ :Tuple = self.qformer_config.to_dict() UpperCamelCase__ :List[Any] = self.text_config.to_dict() UpperCamelCase__ :Dict = self.__class__.model_type return output
97
'''simple docstring''' from collections import defaultdict class lowercase : """simple docstring""" def __init__( self , UpperCamelCase_ , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :List[Any] = total # total no of tasks (N) # DP table will have a dimension of (2^M)*N # initially all values are set to -1 UpperCamelCase__ :Union[str, Any] = [ [-1 for i in range(total + 1 )] for j in range(2 ** len(UpperCamelCase_ ) ) ] UpperCamelCase__ :str = defaultdict(UpperCamelCase_ ) # stores the list of persons for each task # final_mask is used to check if all persons are included by setting all bits # to 1 UpperCamelCase__ :Optional[int] = (1 << len(UpperCamelCase_ )) - 1 def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ ): '''simple docstring''' if mask == self.final_mask: return 1 # if not everyone gets the task and no more tasks are available, return 0 if task_no > self.total_tasks: return 0 # if case already considered if self.dp[mask][task_no] != -1: return self.dp[mask][task_no] # Number of ways when we don't this task in the arrangement UpperCamelCase__ :str = self.count_ways_until(UpperCamelCase_ , task_no + 1 ) # now assign the tasks one by one to all possible persons and recursively # assign for the remaining tasks. if task_no in self.task: for p in self.task[task_no]: # if p is already given a task if mask & (1 << p): continue # assign this task to p and change the mask value. And recursively # assign tasks with the new mask value. total_ways_util += self.count_ways_until(mask | (1 << p) , task_no + 1 ) # save the value. UpperCamelCase__ :Optional[int] = total_ways_util return self.dp[mask][task_no] def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' for i in range(len(UpperCamelCase_ ) ): for j in task_performed[i]: self.task[j].append(UpperCamelCase_ ) # call the function to fill the DP table, final answer is stored in dp[0][1] return self.count_ways_until(0 , 1 ) if __name__ == "__main__": __snake_case = 5 # total no of tasks (the value of N) # the list of tasks that can be done by M persons. __snake_case = [[1, 3, 4], [1, 2, 5], [3, 4]] print( AssignmentUsingBitmask(task_performed, total_tasks).count_no_of_ways( task_performed ) )
97
1
import warnings 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 lowerCamelCase ( A_ ): UpperCAmelCase__ : Dict = ["image_processor", "tokenizer"] UpperCAmelCase__ : Dict = "LayoutLMv2ImageProcessor" UpperCAmelCase__ : Optional[Any] = ("LayoutXLMTokenizer", "LayoutXLMTokenizerFast") def __init__(self : str , _A : Any=None , _A : Tuple=None , **_A : Optional[Any] ) -> Optional[int]: if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , _A , ) snake_case = kwargs.pop("feature_extractor" ) snake_case = 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__(_A , _A ) def __call__(self : int , _A : List[str] , _A : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , _A : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , _A : Union[List[List[int]], List[List[List[int]]]] = None , _A : Optional[Union[List[int], List[List[int]]]] = None , _A : bool = True , _A : Union[bool, str, PaddingStrategy] = False , _A : Union[bool, str, TruncationStrategy] = None , _A : Optional[int] = None , _A : int = 0 , _A : Optional[int] = None , _A : Optional[bool] = None , _A : Optional[bool] = None , _A : bool = False , _A : bool = False , _A : bool = False , _A : bool = False , _A : bool = True , _A : Optional[Union[str, TensorType]] = None , **_A : Dict , ) -> BatchEncoding: # verify input if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( "You cannot provide bounding boxes " "if you initialized the image processor with apply_ocr set to True." ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( "You cannot provide word labels if you initialized the image processor with apply_ocr set to True." ) if return_overflowing_tokens is True and return_offsets_mapping is False: raise ValueError("You cannot return overflowing tokens without returning the offsets mapping." ) # first, apply the image processor snake_case = self.image_processor(images=_A , return_tensors=_A ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(_A , _A ): snake_case = [text] # add batch dimension (as the image processor always adds a batch dimension) snake_case = features["words"] snake_case = self.tokenizer( text=text if text is not None else features["words"] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features["boxes"] , word_labels=_A , add_special_tokens=_A , padding=_A , truncation=_A , max_length=_A , stride=_A , pad_to_multiple_of=_A , return_token_type_ids=_A , return_attention_mask=_A , return_overflowing_tokens=_A , return_special_tokens_mask=_A , return_offsets_mapping=_A , return_length=_A , verbose=_A , return_tensors=_A , **_A , ) # add pixel values snake_case = features.pop("pixel_values" ) if return_overflowing_tokens is True: snake_case = self.get_overflowing_images(_A , encoded_inputs["overflow_to_sample_mapping"] ) snake_case = images return encoded_inputs def UpperCAmelCase(self : Dict , _A : Dict , _A : List[str] ) -> Optional[int]: # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image snake_case = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(_A ) != len(_A ): raise ValueError( "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got" f' {len(_A )} and {len(_A )}' ) return images_with_overflow def UpperCAmelCase(self : Tuple , *_A : int , **_A : Dict ) -> str: return self.tokenizer.batch_decode(*_A , **_A ) def UpperCAmelCase(self : str , *_A : List[Any] , **_A : List[Any] ) -> Optional[Any]: return self.tokenizer.decode(*_A , **_A ) @property def UpperCAmelCase(self : Tuple ) -> Optional[int]: return ["input_ids", "bbox", "attention_mask", "image"] @property def UpperCAmelCase(self : List[Any] ) -> int: warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , _A , ) return self.image_processor_class @property def UpperCAmelCase(self : Dict ) -> Union[str, Any]: warnings.warn( "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , _A , ) return self.image_processor
355
from collections import defaultdict class lowerCamelCase : def __init__(self : Tuple , _A : Optional[int] , _A : List[str] ) -> Union[str, Any]: snake_case = total # total no of tasks (N) # DP table will have a dimension of (2^M)*N # initially all values are set to -1 snake_case = [ [-1 for i in range(total + 1 )] for j in range(2 ** len(_A ) ) ] snake_case = defaultdict(_A ) # stores the list of persons for each task # final_mask is used to check if all persons are included by setting all bits # to 1 snake_case = (1 << len(_A )) - 1 def UpperCAmelCase(self : str , _A : Optional[Any] , _A : List[Any] ) -> str: # if mask == self.finalmask all persons are distributed tasks, return 1 if mask == self.final_mask: return 1 # if not everyone gets the task and no more tasks are available, return 0 if task_no > self.total_tasks: return 0 # if case already considered if self.dp[mask][task_no] != -1: return self.dp[mask][task_no] # Number of ways when we don't this task in the arrangement snake_case = self.count_ways_until(_A , task_no + 1 ) # now assign the tasks one by one to all possible persons and recursively # assign for the remaining tasks. if task_no in self.task: for p in self.task[task_no]: # if p is already given a task if mask & (1 << p): continue # assign this task to p and change the mask value. And recursively # assign tasks with the new mask value. total_ways_util += self.count_ways_until(mask | (1 << p) , task_no + 1 ) # save the value. snake_case = total_ways_util return self.dp[mask][task_no] def UpperCAmelCase(self : Any , _A : Dict ) -> Optional[Any]: # Store the list of persons for each task for i in range(len(_A ) ): for j in task_performed[i]: self.task[j].append(_A ) # call the function to fill the DP table, final answer is stored in dp[0][1] return self.count_ways_until(0 , 1 ) if __name__ == "__main__": _A = 5 # total no of tasks (the value of N) # the list of tasks that can be done by M persons. _A = [[1, 3, 4], [1, 2, 5], [3, 4]] print( AssignmentUsingBitmask(task_performed, total_tasks).count_no_of_ways( task_performed ) )
137
0
from math import ceil from typing import List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor from ...utils import TensorType, logging __lowerCAmelCase : Dict =logging.get_logger(__name__) class _lowercase ( A__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = ['''audio_values''', '''audio_mask'''] def __init__( self :Optional[Any] , lowerCAmelCase__ :str=2_048 , lowerCAmelCase__ :str=1 , lowerCAmelCase__ :List[Any]=[16, 16] , lowerCAmelCase__ :List[str]=128 , lowerCAmelCase__ :Dict=44_100 , lowerCAmelCase__ :Tuple=86 , lowerCAmelCase__ :List[str]=2_048 , lowerCAmelCase__ :Union[str, Any]=0.0 , **lowerCAmelCase__ :int , ) -> str: super().__init__( feature_size=lowerCAmelCase__ , sampling_rate=lowerCAmelCase__ , padding_value=lowerCAmelCase__ , **lowerCAmelCase__ , ) __SCREAMING_SNAKE_CASE : Union[str, Any] = spectrogram_length __SCREAMING_SNAKE_CASE : Dict = num_channels __SCREAMING_SNAKE_CASE : List[Any] = patch_size __SCREAMING_SNAKE_CASE : Optional[int] = feature_size // self.patch_size[1] __SCREAMING_SNAKE_CASE : Optional[Any] = n_fft __SCREAMING_SNAKE_CASE : int = sampling_rate // hop_length_to_sampling_rate __SCREAMING_SNAKE_CASE : Optional[int] = sampling_rate __SCREAMING_SNAKE_CASE : Tuple = padding_value __SCREAMING_SNAKE_CASE : Dict = mel_filter_bank( num_frequency_bins=1 + n_fft // 2 , num_mel_filters=lowerCAmelCase__ , min_frequency=0.0 , max_frequency=2_2050.0 , sampling_rate=lowerCAmelCase__ , norm='''slaney''' , mel_scale='''slaney''' , ).T def __magic_name__( self :Union[str, Any] , lowerCAmelCase__ :np.array ) -> np.ndarray: __SCREAMING_SNAKE_CASE : Union[str, Any] = spectrogram( lowerCAmelCase__ , window_function(self.n_fft , '''hann''' ) , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters.T , log_mel='''dB''' , db_range=80.0 , ) __SCREAMING_SNAKE_CASE : Tuple = log_spec[:, :-1] __SCREAMING_SNAKE_CASE : Tuple = log_spec - 20.0 __SCREAMING_SNAKE_CASE : List[str] = np.clip(log_spec / 40.0 , -2.0 , 0.0 ) + 1.0 return log_spec def __call__( self :Dict , lowerCAmelCase__ :Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , lowerCAmelCase__ :Optional[Union[str, TensorType]] = None , lowerCAmelCase__ :Optional[bool] = True , lowerCAmelCase__ :Optional[int] = None , lowerCAmelCase__ :bool = False , lowerCAmelCase__ :bool = False , **lowerCAmelCase__ :Union[str, Any] , ) -> BatchFeature: if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( '''This feature extractor is set to support sampling rate''' f''' of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled''' f''' 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.''' ) __SCREAMING_SNAKE_CASE : Any = 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}''' ) __SCREAMING_SNAKE_CASE : str = is_batched_numpy or ( isinstance(lowerCAmelCase__ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: __SCREAMING_SNAKE_CASE : Union[str, Any] = [np.asarray([speech] , dtype=np.floataa ).T for speech in raw_speech] elif not is_batched and not isinstance(lowerCAmelCase__ , np.ndarray ): __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(lowerCAmelCase__ , dtype=np.floataa ) elif isinstance(lowerCAmelCase__ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): __SCREAMING_SNAKE_CASE : Optional[Any] = raw_speech.astype(np.floataa ) # always return batch if not is_batched: __SCREAMING_SNAKE_CASE : str = [np.asarray([raw_speech] ).T] # Convert audio signals to log mel spectrograms, truncate by time axis __SCREAMING_SNAKE_CASE : Optional[Any] = [ self._np_extract_fbank_features(waveform.squeeze() ).T[: self.spectrogram_length] for waveform in raw_speech ] if isinstance(audio_features[0] , lowerCAmelCase__ ): __SCREAMING_SNAKE_CASE : Optional[Any] = [np.asarray(lowerCAmelCase__ , dtype=np.floataa ) for feature in audio_features] # Create audio attention mask __SCREAMING_SNAKE_CASE : Tuple = max( [ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len for feature in audio_features] ) # The maximum number of audio patches in a batch if return_attention_mask: __SCREAMING_SNAKE_CASE : Dict = [ (ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [1] + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [0] for feature in audio_features ] __SCREAMING_SNAKE_CASE : Optional[int] = np.array(lowerCAmelCase__ ).astype(np.floataa ) # convert into correct format for padding __SCREAMING_SNAKE_CASE : Optional[int] = max_patch_len // self.freq_len * self.patch_size[0] # The maximum audio size in a batch __SCREAMING_SNAKE_CASE : List[str] = np.ones([len(lowerCAmelCase__ ), 1, max_time_len, self.feature_size] ).astype(np.floataa ) __SCREAMING_SNAKE_CASE : Union[str, Any] = padded_audio_features * self.padding_value for i in range(len(lowerCAmelCase__ ) ): __SCREAMING_SNAKE_CASE : Dict = audio_features[i] __SCREAMING_SNAKE_CASE : str = feature # return as BatchFeature if return_attention_mask: __SCREAMING_SNAKE_CASE : Dict = {'''audio_values''': padded_audio_features, '''audio_mask''': audio_mask} else: __SCREAMING_SNAKE_CASE : List[str] = {'''audio_values''': padded_audio_features} __SCREAMING_SNAKE_CASE : Any = BatchFeature(data=lowerCAmelCase__ , tensor_type=lowerCAmelCase__ ) return encoded_inputs
9
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) _SCREAMING_SNAKE_CASE = logging.getLogger(__name__) @dataclass class SCREAMING_SNAKE_CASE_ : __magic_name__: str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) __magic_name__: Optional[str] = field( default=snake_case_ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) __magic_name__: Optional[str] = field( default=snake_case_ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) __magic_name__: Optional[str] = field( default=snake_case_ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) __magic_name__: bool = field(default=snake_case_ , metadata={"help": "Whether tp freeze the encoder."} ) __magic_name__: bool = field(default=snake_case_ , metadata={"help": "Whether to freeze the embeddings."} ) @dataclass class SCREAMING_SNAKE_CASE_ : __magic_name__: str = field( metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."} ) __magic_name__: Optional[str] = field( default="summarization" , metadata={"help": "Task name, summarization (or summarization_{dataset} for pegasus) or translation"} , ) __magic_name__: Optional[int] = field( default=1024 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) __magic_name__: Optional[int] = field( default=128 , metadata={ "help": ( "The maximum total sequence length for target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) __magic_name__: Optional[int] = field( default=142 , metadata={ "help": ( "The maximum total sequence length for validation target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded. " "This argument is also used to override the ``max_length`` param of ``model.generate``, which is used " "during ``evaluate`` and ``predict``." ) } , ) __magic_name__: Optional[int] = field( default=142 , metadata={ "help": ( "The maximum total sequence length for test target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) __magic_name__: Optional[int] = field(default=-1 , metadata={"help": "# training examples. -1 means use all."} ) __magic_name__: Optional[int] = field(default=-1 , metadata={"help": "# validation examples. -1 means use all."} ) __magic_name__: Optional[int] = field(default=-1 , metadata={"help": "# test examples. -1 means use all."} ) __magic_name__: Optional[str] = field(default=snake_case_ , metadata={"help": "Source language id for translation."} ) __magic_name__: Optional[str] = field(default=snake_case_ , metadata={"help": "Target language id for translation."} ) __magic_name__: Optional[int] = field(default=snake_case_ , metadata={"help": "# num_beams to use for evaluation."} ) __magic_name__: bool = field( default=snake_case_ , metadata={"help": "If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined."} , ) def SCREAMING_SNAKE_CASE__ ( __a , __a , __a ): logger.info(f"""***** {split} metrics *****""" ) for key in sorted(metrics.keys() ): logger.info(f""" {key} = {metrics[key]}""" ) save_json(__a , os.path.join(__a , f"""{split}_results.json""" ) ) def SCREAMING_SNAKE_CASE__ ( ): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. snake_case_ : Any = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. snake_case_ ,snake_case_ ,snake_case_ : List[Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: snake_case_ ,snake_case_ ,snake_case_ : List[str] = parser.parse_args_into_dataclasses() check_output_dir(__a ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( 'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('Training/evaluation parameters %s' , __a ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. snake_case_ : Tuple = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) snake_case_ : Any = ('encoder_layerdrop', 'decoder_layerdrop', 'dropout', 'attention_dropout') for p in extra_model_params: if getattr(__a , __a , __a ): assert hasattr(__a , __a ), f"""({config.__class__.__name__}) doesn't have a `{p}` attribute""" setattr(__a , __a , getattr(__a , __a ) ) snake_case_ : Tuple = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) snake_case_ : Any = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf='.ckpt' in model_args.model_name_or_path , config=__a , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(__a , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: snake_case_ : Any = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(__a , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(__a , __a ): snake_case_ : int = tokenizer.lang_code_to_id[data_args.tgt_lang] else: snake_case_ : int = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(__a ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) snake_case_ : List[Any] = SeqaSeqDataset # Get datasets snake_case_ : List[Any] = ( dataset_class( __a , type_path='train' , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '' , ) if training_args.do_train else None ) snake_case_ : List[str] = ( dataset_class( __a , type_path='val' , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '' , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) snake_case_ : List[Any] = ( dataset_class( __a , type_path='test' , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '' , ) if training_args.do_predict else None ) # Initialize our Trainer snake_case_ : Any = ( build_compute_metrics_fn(data_args.task , __a ) if training_args.predict_with_generate else None ) snake_case_ : List[str] = SeqaSeqTrainer( model=__a , args=__a , data_args=__a , train_dataset=__a , eval_dataset=__a , data_collator=SeqaSeqDataCollator( __a , __a , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=__a , tokenizer=__a , ) snake_case_ : Optional[int] = {} # Training if training_args.do_train: logger.info('*** Train ***' ) snake_case_ : Any = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) snake_case_ : Tuple = train_result.metrics snake_case_ : List[str] = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics('train' , __a , training_args.output_dir ) all_metrics.update(__a ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , 'trainer_state.json' ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info('*** Evaluate ***' ) snake_case_ : List[Any] = trainer.evaluate(metric_key_prefix='val' ) snake_case_ : str = data_args.n_val snake_case_ : Union[str, Any] = round(metrics['val_loss'] , 4 ) if trainer.is_world_process_zero(): handle_metrics('val' , __a , training_args.output_dir ) all_metrics.update(__a ) if training_args.do_predict: logger.info('*** Predict ***' ) snake_case_ : Dict = trainer.predict(test_dataset=__a , metric_key_prefix='test' ) snake_case_ : Union[str, Any] = test_output.metrics snake_case_ : int = data_args.n_test if trainer.is_world_process_zero(): snake_case_ : List[str] = round(metrics['test_loss'] , 4 ) handle_metrics('test' , __a , training_args.output_dir ) all_metrics.update(__a ) if training_args.predict_with_generate: snake_case_ : Any = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=__a , clean_up_tokenization_spaces=__a ) snake_case_ : Any = lmap(str.strip , __a ) write_txt_file(__a , os.path.join(training_args.output_dir , 'test_generations.txt' ) ) if trainer.is_world_process_zero(): save_json(__a , os.path.join(training_args.output_dir , 'all_results.json' ) ) return all_metrics def SCREAMING_SNAKE_CASE__ ( __a ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
327
0
from itertools import permutations def __UpperCamelCase ( lowerCAmelCase__ : tuple ): if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False __a : Union[str, Any] = [7, 1_1, 1_3, 1_7] for i, test in enumerate(lowerCAmelCase__ ): if (num[i + 4] * 1_0_0 + num[i + 5] * 1_0 + num[i + 6]) % test != 0: return False return True def __UpperCamelCase ( lowerCAmelCase__ : int = 1_0 ): return sum( int(''''''.join(map(lowerCAmelCase__ , lowerCAmelCase__ ) ) ) for num in permutations(range(lowerCAmelCase__ ) ) if is_substring_divisible(lowerCAmelCase__ ) ) if __name__ == "__main__": print(F"""{solution() = }""")
90
import collections import inspect import unittest from transformers import FocalNetConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, ) from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class UpperCamelCase__ : def __init__(self : Optional[Any] , snake_case_ : Union[str, Any] , snake_case_ : Optional[Any]=1_3 , snake_case_ : str=3_2 , snake_case_ : Any=2 , snake_case_ : Union[str, Any]=3 , snake_case_ : int=1_6 , snake_case_ : Optional[int]=[3_2, 6_4, 1_2_8] , snake_case_ : str=[1, 2, 1] , snake_case_ : str=[2, 2, 4] , snake_case_ : List[str]=2 , snake_case_ : List[str]=2.0 , snake_case_ : List[Any]=True , snake_case_ : Tuple=0.0 , snake_case_ : Optional[Any]=0.0 , snake_case_ : int=0.1 , snake_case_ : Optional[int]="gelu" , snake_case_ : List[str]=False , snake_case_ : Optional[int]=True , snake_case_ : Optional[int]=0.02 , snake_case_ : List[str]=1E-5 , snake_case_ : List[Any]=True , snake_case_ : int=None , snake_case_ : List[Any]=True , snake_case_ : Optional[Any]=1_0 , snake_case_ : Union[str, Any]=8 , snake_case_ : Optional[Any]=["stage1", "stage2"] , snake_case_ : List[Any]=[1, 2] , ): __a : Tuple = parent __a : str = batch_size __a : Any = image_size __a : List[Any] = patch_size __a : List[Any] = num_channels __a : List[str] = embed_dim __a : str = hidden_sizes __a : Any = depths __a : List[str] = num_heads __a : Any = window_size __a : List[str] = mlp_ratio __a : Optional[int] = qkv_bias __a : Any = hidden_dropout_prob __a : List[str] = attention_probs_dropout_prob __a : str = drop_path_rate __a : Optional[Any] = hidden_act __a : Optional[int] = use_absolute_embeddings __a : List[str] = patch_norm __a : int = layer_norm_eps __a : Optional[Any] = initializer_range __a : List[str] = is_training __a : Dict = scope __a : Optional[Any] = use_labels __a : Union[str, Any] = type_sequence_label_size __a : Optional[int] = encoder_stride __a : str = out_features __a : Optional[int] = out_indices def lowerCAmelCase (self : Dict ): __a : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : Dict = None if self.use_labels: __a : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a : List[str] = self.get_config() return config, pixel_values, labels def lowerCAmelCase (self : Optional[Any] ): return FocalNetConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , hidden_sizes=self.hidden_sizes , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def lowerCAmelCase (self : Dict , snake_case_ : int , snake_case_ : Tuple , snake_case_ : str ): __a : int = FocalNetModel(config=snake_case_ ) model.to(snake_case_ ) model.eval() __a : Dict = model(snake_case_ ) __a : Union[str, Any] = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) __a : Dict = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def lowerCAmelCase (self : Tuple , snake_case_ : Any , snake_case_ : Union[str, Any] , snake_case_ : Optional[int] ): __a : List[str] = FocalNetBackbone(config=snake_case_ ) model.to(snake_case_ ) model.eval() __a : List[str] = model(snake_case_ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.image_size, 8, 8] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[:-1] ) # verify backbone works with out_features=None __a : Union[str, Any] = None __a : Tuple = FocalNetBackbone(config=snake_case_ ) model.to(snake_case_ ) model.eval() __a : int = model(snake_case_ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.image_size * 2, 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def lowerCAmelCase (self : Optional[Any] , snake_case_ : Optional[int] , snake_case_ : Dict , snake_case_ : Optional[Any] ): __a : List[str] = FocalNetForMaskedImageModeling(config=snake_case_ ) model.to(snake_case_ ) model.eval() __a : int = model(snake_case_ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __a : str = 1 __a : Optional[Any] = FocalNetForMaskedImageModeling(snake_case_ ) model.to(snake_case_ ) model.eval() __a : Any = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __a : Union[str, Any] = model(snake_case_ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def lowerCAmelCase (self : Union[str, Any] , snake_case_ : List[Any] , snake_case_ : Any , snake_case_ : int ): __a : Dict = self.type_sequence_label_size __a : Optional[Any] = FocalNetForImageClassification(snake_case_ ) model.to(snake_case_ ) model.eval() __a : Union[str, Any] = model(snake_case_ , labels=snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __a : Optional[int] = 1 __a : str = FocalNetForImageClassification(snake_case_ ) model.to(snake_case_ ) model.eval() __a : str = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __a : List[Any] = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def lowerCAmelCase (self : List[Any] ): __a : Any = self.prepare_config_and_inputs() __a , __a , __a : Any = config_and_inputs __a : Tuple = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class UpperCamelCase__ ( __lowercase ,__lowercase ,unittest.TestCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = ( ( FocalNetModel, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetBackbone, ) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE : Optional[Any] = ( {"feature-extraction": FocalNetModel, "image-classification": FocalNetForImageClassification} if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE : str = False _SCREAMING_SNAKE_CASE : str = False _SCREAMING_SNAKE_CASE : Optional[Any] = False _SCREAMING_SNAKE_CASE : Any = False _SCREAMING_SNAKE_CASE : Dict = False def lowerCAmelCase (self : List[Any] ): __a : Union[str, Any] = FocalNetModelTester(self ) __a : Dict = ConfigTester(self , config_class=snake_case_ , embed_dim=3_7 , has_text_modality=snake_case_ ) def lowerCAmelCase (self : Any ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowerCAmelCase (self : Dict ): return def lowerCAmelCase (self : Dict ): __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case_ ) def lowerCAmelCase (self : Tuple ): __a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*snake_case_ ) def lowerCAmelCase (self : Any ): __a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*snake_case_ ) def lowerCAmelCase (self : Optional[int] ): __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case_ ) @unittest.skip(reason='''FocalNet does not use inputs_embeds''' ) def lowerCAmelCase (self : Optional[Any] ): pass @unittest.skip(reason='''FocalNet does not use feedforward chunking''' ) def lowerCAmelCase (self : str ): pass def lowerCAmelCase (self : Tuple ): __a , __a : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: __a : int = model_class(snake_case_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __a : List[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case_ , nn.Linear ) ) def lowerCAmelCase (self : Optional[int] ): __a , __a : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: __a : str = model_class(snake_case_ ) __a : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a : Dict = [*signature.parameters.keys()] __a : str = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , snake_case_ ) def lowerCAmelCase (self : Tuple , snake_case_ : Tuple , snake_case_ : Dict , snake_case_ : Any , snake_case_ : Optional[Any] ): __a : Any = model_class(snake_case_ ) model.to(snake_case_ ) model.eval() with torch.no_grad(): __a : Dict = model(**self._prepare_for_class(snake_case_ , snake_case_ ) ) __a : Union[str, Any] = outputs.hidden_states __a : Dict = getattr( self.model_tester , '''expected_num_hidden_layers''' , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(snake_case_ ) , snake_case_ ) # FocalNet has a different seq_length __a : int = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) __a : Dict = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) __a : Optional[Any] = outputs.reshaped_hidden_states self.assertEqual(len(snake_case_ ) , snake_case_ ) __a , __a , __a , __a : List[Any] = reshaped_hidden_states[0].shape __a : List[str] = ( reshaped_hidden_states[0].view(snake_case_ , snake_case_ , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def lowerCAmelCase (self : Optional[int] ): __a , __a : Dict = self.model_tester.prepare_config_and_inputs_for_common() __a : Dict = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes[:-1]: __a : Any = True self.check_hidden_states_output(snake_case_ , snake_case_ , snake_case_ , snake_case_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a : Optional[int] = True self.check_hidden_states_output(snake_case_ , snake_case_ , snake_case_ , snake_case_ ) def lowerCAmelCase (self : List[Any] ): __a , __a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() __a : List[str] = 3 __a : Optional[int] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) __a : List[str] = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) __a : List[Any] = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) __a : Union[str, Any] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes[:-1]: __a : int = True self.check_hidden_states_output(snake_case_ , snake_case_ , snake_case_ , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a : List[str] = True self.check_hidden_states_output(snake_case_ , snake_case_ , snake_case_ , (padded_height, padded_width) ) @slow def lowerCAmelCase (self : str ): for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : Dict = FocalNetModel.from_pretrained(snake_case_ ) self.assertIsNotNone(snake_case_ ) def lowerCAmelCase (self : List[Any] ): __a , __a : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() __a : Optional[int] = _config_zero_init(snake_case_ ) for model_class in self.all_model_classes: __a : str = model_class(config=snake_case_ ) for name, param in model.named_parameters(): if "embeddings" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=f"Parameter {name} of model {model_class} seems not properly initialized" , ) @require_vision @require_torch class UpperCamelCase__ ( unittest.TestCase ): @cached_property def lowerCAmelCase (self : str ): # TODO update organization return AutoImageProcessor.from_pretrained('''microsoft/focalnet-tiny''' ) if is_vision_available() else None @slow def lowerCAmelCase (self : str ): __a : int = FocalNetForImageClassification.from_pretrained('''microsoft/focalnet-tiny''' ).to(snake_case_ ) __a : Optional[Any] = self.default_image_processor __a : Dict = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) __a : Optional[Any] = image_processor(images=snake_case_ , return_tensors='''pt''' ).to(snake_case_ ) # forward pass with torch.no_grad(): __a : Any = model(**snake_case_ ) # verify the logits __a : List[Any] = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , snake_case_ ) __a : Union[str, Any] = torch.tensor([0.2166, -0.4368, 0.2191] ).to(snake_case_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , snake_case_ , atol=1E-4 ) ) self.assertTrue(outputs.logits.argmax(dim=-1 ).item() , 2_8_1 ) @require_torch class UpperCamelCase__ ( __lowercase ,unittest.TestCase ): _SCREAMING_SNAKE_CASE : Tuple = (FocalNetBackbone,) if is_torch_available() else () _SCREAMING_SNAKE_CASE : int = FocalNetConfig _SCREAMING_SNAKE_CASE : Any = False def lowerCAmelCase (self : Tuple ): __a : Union[str, Any] = FocalNetModelTester(self )
90
1
"""simple docstring""" import tempfile import numpy as np import torch from transformers import AutoTokenizer, TaEncoderModel from diffusers import DDPMScheduler, UNetaDConditionModel from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.pipelines.deepfloyd_if import IFWatermarker from diffusers.utils.testing_utils import torch_device from ..test_pipelines_common import to_np class __lowerCAmelCase : '''simple docstring''' def __UpperCAmelCase ( self ): torch.manual_seed(0 ) __a = TaEncoderModel.from_pretrained('''hf-internal-testing/tiny-random-t5''' ) torch.manual_seed(0 ) __a = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-t5''' ) torch.manual_seed(0 ) __a = UNetaDConditionModel( sample_size=32 , layers_per_block=1 , block_out_channels=[32, 64] , down_block_types=[ '''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D''', ] , mid_block_type='''UNetMidBlock2DSimpleCrossAttn''' , up_block_types=['''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''] , in_channels=3 , out_channels=6 , cross_attention_dim=32 , encoder_hid_dim=32 , attention_head_dim=8 , addition_embed_type='''text''' , addition_embed_type_num_heads=2 , cross_attention_norm='''group_norm''' , resnet_time_scale_shift='''scale_shift''' , act_fn='''gelu''' , ) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) __a = DDPMScheduler( num_train_timesteps=1_000 , beta_schedule='''squaredcos_cap_v2''' , beta_start=0.0001 , beta_end=0.02 , thresholding=_a , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type='''epsilon''' , variance_type='''learned_range''' , ) torch.manual_seed(0 ) __a = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def __UpperCAmelCase ( self ): torch.manual_seed(0 ) __a = TaEncoderModel.from_pretrained('''hf-internal-testing/tiny-random-t5''' ) torch.manual_seed(0 ) __a = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-t5''' ) torch.manual_seed(0 ) __a = UNetaDConditionModel( sample_size=32 , layers_per_block=[1, 2] , block_out_channels=[32, 64] , down_block_types=[ '''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D''', ] , mid_block_type='''UNetMidBlock2DSimpleCrossAttn''' , up_block_types=['''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''] , in_channels=6 , out_channels=6 , cross_attention_dim=32 , encoder_hid_dim=32 , attention_head_dim=8 , addition_embed_type='''text''' , addition_embed_type_num_heads=2 , cross_attention_norm='''group_norm''' , resnet_time_scale_shift='''scale_shift''' , act_fn='''gelu''' , class_embed_type='''timestep''' , mid_block_scale_factor=1.414 , time_embedding_act_fn='''gelu''' , time_embedding_dim=32 , ) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) __a = DDPMScheduler( num_train_timesteps=1_000 , beta_schedule='''squaredcos_cap_v2''' , beta_start=0.0001 , beta_end=0.02 , thresholding=_a , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type='''epsilon''' , variance_type='''learned_range''' , ) torch.manual_seed(0 ) __a = DDPMScheduler( num_train_timesteps=1_000 , beta_schedule='''squaredcos_cap_v2''' , beta_start=0.0001 , beta_end=0.02 , ) torch.manual_seed(0 ) __a = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "image_noising_scheduler": image_noising_scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def __UpperCAmelCase ( self ): __a = self.get_dummy_components() __a = self.pipeline_class(**_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) __a = self.get_dummy_inputs(_a ) __a = inputs['''prompt'''] __a = inputs['''generator'''] __a = inputs['''num_inference_steps'''] __a = inputs['''output_type'''] if "image" in inputs: __a = inputs['''image'''] else: __a = None if "mask_image" in inputs: __a = inputs['''mask_image'''] else: __a = None if "original_image" in inputs: __a = inputs['''original_image'''] else: __a = None __a , __a = pipe.encode_prompt(_a ) # inputs with prompt converted to embeddings __a = { '''prompt_embeds''': prompt_embeds, '''negative_prompt_embeds''': negative_prompt_embeds, '''generator''': generator, '''num_inference_steps''': num_inference_steps, '''output_type''': output_type, } if image is not None: __a = image if mask_image is not None: __a = mask_image if original_image is not None: __a = original_image # set all optional components to None for optional_component in pipe._optional_components: setattr(_a , _a , _a ) __a = pipe(**_a )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(_a ) __a = self.pipeline_class.from_pretrained(_a ) pipe_loaded.to(_a ) pipe_loaded.set_progress_bar_config(disable=_a ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests for optional_component in pipe._optional_components: self.assertTrue( getattr(_a , _a ) is None , f'''`{optional_component}` did not stay set to None after loading.''' , ) __a = self.get_dummy_inputs(_a ) __a = inputs['''generator'''] __a = inputs['''num_inference_steps'''] __a = inputs['''output_type'''] # inputs with prompt converted to embeddings __a = { '''prompt_embeds''': prompt_embeds, '''negative_prompt_embeds''': negative_prompt_embeds, '''generator''': generator, '''num_inference_steps''': num_inference_steps, '''output_type''': output_type, } if image is not None: __a = image if mask_image is not None: __a = mask_image if original_image is not None: __a = original_image __a = pipe_loaded(**_a )[0] __a = np.abs(to_np(_a ) - to_np(_a ) ).max() self.assertLess(_a , 1E-4 ) def __UpperCAmelCase ( self ): __a = self.get_dummy_components() __a = self.pipeline_class(**_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) __a = self.get_dummy_inputs(_a ) __a = pipe(**_a )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(_a ) __a = self.pipeline_class.from_pretrained(_a ) pipe_loaded.to(_a ) pipe_loaded.set_progress_bar_config(disable=_a ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests __a = self.get_dummy_inputs(_a ) __a = pipe_loaded(**_a )[0] __a = np.abs(to_np(_a ) - to_np(_a ) ).max() self.assertLess(_a , 1E-4 )
45
"""simple docstring""" # flake8: noqa # Lint as: python3 _UpperCAmelCase = [ """VerificationMode""", """Version""", """disable_progress_bar""", """enable_progress_bar""", """is_progress_bar_enabled""", """experimental""", ] from .info_utils import VerificationMode from .logging import disable_progress_bar, enable_progress_bar, is_progress_bar_enabled from .version import Version from .experimental import experimental
173
0
"""simple docstring""" UpperCAmelCase : Optional[Any] = 'Tobias Carryer' from time import time class SCREAMING_SNAKE_CASE__ : def __init__( self : List[Any] , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Tuple=int(time())): # noqa: B008 """simple docstring""" lowercase_ = multiplier lowercase_ = increment lowercase_ = modulo lowercase_ = seed def _UpperCAmelCase ( self : Any): """simple docstring""" lowercase_ = (self.multiplier * self.seed + self.increment) % self.modulo return self.seed if __name__ == "__main__": # Show the LCG in action. UpperCAmelCase : str = LinearCongruentialGenerator(166_4525, 10_1390_4223, 2 << 31) while True: print(lcg.next_number())
355
"""simple docstring""" from __future__ import annotations import numpy as np def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> tuple[np.ndarray, np.ndarray]: '''simple docstring''' lowercase_ , lowercase_ = np.shape(__lowerCAmelCase ) if rows != columns: lowercase_ = ( """'table' has to be of square shaped array but got a """ F'''{rows}x{columns} array:\n{table}''' ) raise ValueError(__lowerCAmelCase ) lowercase_ = np.zeros((rows, columns) ) lowercase_ = np.zeros((rows, columns) ) for i in range(__lowerCAmelCase ): for j in range(__lowerCAmelCase ): lowercase_ = sum(lower[i][k] * upper[k][j] for k in range(__lowerCAmelCase ) ) if upper[j][j] == 0: raise ArithmeticError("""No LU decomposition exists""" ) lowercase_ = (table[i][j] - total) / upper[j][j] lowercase_ = 1 for j in range(__lowerCAmelCase , __lowerCAmelCase ): lowercase_ = sum(lower[i][k] * upper[k][j] for k in range(__lowerCAmelCase ) ) lowercase_ = table[i][j] - total return lower, upper if __name__ == "__main__": import doctest doctest.testmod()
313
0
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ): return len(set(SCREAMING_SNAKE_CASE ) ) == len(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
186
'''simple docstring''' # Copyright 2022 The HuggingFace Team and The OpenBMB 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. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _SCREAMING_SNAKE_CASE : List[str] = { "configuration_cpmant": ["CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP", "CpmAntConfig"], "tokenization_cpmant": ["CpmAntTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Any = [ "CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST", "CpmAntForCausalLM", "CpmAntModel", "CpmAntPreTrainedModel", ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
0
'''simple docstring''' from collections import UserDict from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax UpperCamelCase_ : Union[str, Any] = logging.get_logger(__name__) @add_end_docstrings(__lowerCAmelCase ) class _a ( __lowerCAmelCase ): def __init__( self ,**_SCREAMING_SNAKE_CASE ) -> Any: super().__init__(**_SCREAMING_SNAKE_CASE ) requires_backends(self ,"vision" ) self.check_model_type( TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if self.framework == "tf" else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING ) def __call__( self ,_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE ) -> Optional[Any]: return super().__call__(_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE ) def _lowercase ( self ,**_SCREAMING_SNAKE_CASE ) -> Optional[Any]: _snake_case = {} if "candidate_labels" in kwargs: _snake_case = kwargs["candidate_labels"] if "hypothesis_template" in kwargs: _snake_case = kwargs["hypothesis_template"] return preprocess_params, {}, {} def _lowercase ( self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE=None ,_SCREAMING_SNAKE_CASE="This is a photo of {}." ) -> Union[str, Any]: _snake_case = load_image(_SCREAMING_SNAKE_CASE ) _snake_case = self.image_processor(images=[image] ,return_tensors=self.framework ) _snake_case = candidate_labels _snake_case = [hypothesis_template.format(_SCREAMING_SNAKE_CASE ) for x in candidate_labels] _snake_case = self.tokenizer(_SCREAMING_SNAKE_CASE ,return_tensors=self.framework ,padding=_SCREAMING_SNAKE_CASE ) _snake_case = [text_inputs] return inputs def _lowercase ( self ,_SCREAMING_SNAKE_CASE ) -> Dict: _snake_case = model_inputs.pop("candidate_labels" ) _snake_case = model_inputs.pop("text_inputs" ) if isinstance(text_inputs[0] ,_SCREAMING_SNAKE_CASE ): _snake_case = text_inputs[0] else: # Batching case. _snake_case = text_inputs[0][0] _snake_case = self.model(**_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE ) _snake_case = { "candidate_labels": candidate_labels, "logits": outputs.logits_per_image, } return model_outputs def _lowercase ( self ,_SCREAMING_SNAKE_CASE ) -> Dict: _snake_case = model_outputs.pop("candidate_labels" ) _snake_case = model_outputs["logits"][0] if self.framework == "pt": _snake_case = logits.softmax(dim=-1 ).squeeze(-1 ) _snake_case = probs.tolist() if not isinstance(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ): _snake_case = [scores] elif self.framework == "tf": _snake_case = stable_softmax(_SCREAMING_SNAKE_CASE ,axis=-1 ) _snake_case = probs.numpy().tolist() else: raise ValueError(f"""Unsupported framework: {self.framework}""" ) _snake_case = [ {"score": score, "label": candidate_label} for score, candidate_label in sorted(zip(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) ,key=lambda _SCREAMING_SNAKE_CASE : -x[0] ) ] return result
366
'''simple docstring''' import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase_ : List[str] = get_tests_dir('''fixtures/test_sentencepiece.model''') if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right UpperCamelCase_ : Optional[Any] = 250004 UpperCamelCase_ : Union[str, Any] = 250020 @require_sentencepiece @require_tokenizers class _a ( __lowerCAmelCase , unittest.TestCase ): SCREAMING_SNAKE_CASE_ : Optional[int] = MBartTokenizer SCREAMING_SNAKE_CASE_ : List[str] = MBartTokenizerFast SCREAMING_SNAKE_CASE_ : Union[str, Any] = True SCREAMING_SNAKE_CASE_ : List[Any] = True def _lowercase ( self ) -> Optional[Any]: super().setUp() # We have a SentencePiece fixture for testing _snake_case = MBartTokenizer(_SCREAMING_SNAKE_CASE ,keep_accents=_SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def _lowercase ( self ) -> Dict: _snake_case = MBartTokenizer(_SCREAMING_SNAKE_CASE ,keep_accents=_SCREAMING_SNAKE_CASE ) _snake_case = tokenizer.tokenize("This is a test" ) self.assertListEqual(_SCREAMING_SNAKE_CASE ,["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE ) ,[value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] ,) _snake_case = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( _SCREAMING_SNAKE_CASE ,[ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] ,) _snake_case = tokenizer.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE ) self.assertListEqual( _SCREAMING_SNAKE_CASE ,[ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] ,) _snake_case = tokenizer.convert_ids_to_tokens(_SCREAMING_SNAKE_CASE ) self.assertListEqual( _SCREAMING_SNAKE_CASE ,[ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] ,) def _lowercase ( self ) -> List[str]: if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return _snake_case = (self.rust_tokenizer_class, "hf-internal-testing/tiny-random-mbart", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): _snake_case = self.rust_tokenizer_class.from_pretrained(_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE ) _snake_case = self.tokenizer_class.from_pretrained(_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE ) _snake_case = tempfile.mkdtemp() _snake_case = tokenizer_r.save_pretrained(_SCREAMING_SNAKE_CASE ) _snake_case = tokenizer_p.save_pretrained(_SCREAMING_SNAKE_CASE ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files ) ) _snake_case = tuple(f for f in tokenizer_r_files if "tokenizer.json" not in f ) self.assertSequenceEqual(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way _snake_case = tokenizer_r.from_pretrained(_SCREAMING_SNAKE_CASE ) _snake_case = tokenizer_p.from_pretrained(_SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(_SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=True _snake_case = tempfile.mkdtemp() _snake_case = tokenizer_r.save_pretrained(_SCREAMING_SNAKE_CASE ,legacy_format=_SCREAMING_SNAKE_CASE ) _snake_case = tokenizer_p.save_pretrained(_SCREAMING_SNAKE_CASE ) # Checks it save with the same files self.assertSequenceEqual(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way _snake_case = tokenizer_r.from_pretrained(_SCREAMING_SNAKE_CASE ) _snake_case = tokenizer_p.from_pretrained(_SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) ) shutil.rmtree(_SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=False _snake_case = tempfile.mkdtemp() _snake_case = tokenizer_r.save_pretrained(_SCREAMING_SNAKE_CASE ,legacy_format=_SCREAMING_SNAKE_CASE ) _snake_case = tokenizer_p.save_pretrained(_SCREAMING_SNAKE_CASE ) # Checks it saved the tokenizer.json file self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way _snake_case = tokenizer_r.from_pretrained(_SCREAMING_SNAKE_CASE ) _snake_case = tokenizer_p.from_pretrained(_SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) ) shutil.rmtree(_SCREAMING_SNAKE_CASE ) @require_torch @require_sentencepiece @require_tokenizers class _a ( unittest.TestCase ): SCREAMING_SNAKE_CASE_ : Optional[Any] = """facebook/mbart-large-en-ro""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [ """ UN Chief Says There Is No Military Solution in Syria""", """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.""", ] SCREAMING_SNAKE_CASE_ : Dict = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", """Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei""" """ pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor""" """ face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""", ] SCREAMING_SNAKE_CASE_ : Optional[int] = [82_74, 12_78_73, 2_59_16, 7, 86_22, 20_71, 4_38, 6_74_85, 53, 18_78_95, 23, 5_17_12, 2, EN_CODE] @classmethod def _lowercase ( cls ) -> List[str]: _snake_case = MBartTokenizer.from_pretrained( cls.checkpoint_name ,src_lang="en_XX" ,tgt_lang="ro_RO" ) _snake_case = 1 return cls def _lowercase ( self ) -> Dict: self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ar_AR"] ,250_001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["en_EN"] ,250_004 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ro_RO"] ,250_020 ) def _lowercase ( self ) -> Tuple: _snake_case = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens ,_SCREAMING_SNAKE_CASE ) def _lowercase ( self ) -> Optional[int]: self.assertIn(_SCREAMING_SNAKE_CASE ,self.tokenizer.all_special_ids ) _snake_case = [RO_CODE, 884, 9_019, 96, 9, 916, 86_792, 36, 18_743, 15_596, 5, 2] _snake_case = self.tokenizer.decode(_SCREAMING_SNAKE_CASE ,skip_special_tokens=_SCREAMING_SNAKE_CASE ) _snake_case = self.tokenizer.decode(generated_ids[1:] ,skip_special_tokens=_SCREAMING_SNAKE_CASE ) self.assertEqual(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) self.assertNotIn(self.tokenizer.eos_token ,_SCREAMING_SNAKE_CASE ) def _lowercase ( self ) -> List[Any]: _snake_case = ["this is gunna be a long sentence " * 20] assert isinstance(src_text[0] ,_SCREAMING_SNAKE_CASE ) _snake_case = 10 _snake_case = self.tokenizer(_SCREAMING_SNAKE_CASE ,max_length=_SCREAMING_SNAKE_CASE ,truncation=_SCREAMING_SNAKE_CASE ).input_ids[0] self.assertEqual(ids[-2] ,2 ) self.assertEqual(ids[-1] ,_SCREAMING_SNAKE_CASE ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) ,_SCREAMING_SNAKE_CASE ) def _lowercase ( self ) -> Optional[int]: self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["<mask>", "ar_AR"] ) ,[250_026, 250_001] ) def _lowercase ( self ) -> str: _snake_case = tempfile.mkdtemp() _snake_case = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(_SCREAMING_SNAKE_CASE ) _snake_case = MBartTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids ,_SCREAMING_SNAKE_CASE ) @require_torch def _lowercase ( self ) -> Dict: _snake_case = self.tokenizer(self.src_text ,text_target=self.tgt_text ,padding=_SCREAMING_SNAKE_CASE ,return_tensors="pt" ) _snake_case = shift_tokens_right(batch["labels"] ,self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE] assert batch.decoder_input_ids[1][0].tolist() == RO_CODE assert batch.decoder_input_ids[1][-1] == 2 assert batch.labels[1][-2:].tolist() == [2, RO_CODE] @require_torch def _lowercase ( self ) -> Optional[int]: _snake_case = self.tokenizer( self.src_text ,text_target=self.tgt_text ,padding=_SCREAMING_SNAKE_CASE ,truncation=_SCREAMING_SNAKE_CASE ,max_length=len(self.expected_src_tokens ) ,return_tensors="pt" ,) _snake_case = shift_tokens_right(batch["labels"] ,self.tokenizer.pad_token_id ) self.assertIsInstance(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) self.assertEqual((2, 14) ,batch.input_ids.shape ) self.assertEqual((2, 14) ,batch.attention_mask.shape ) _snake_case = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens ,_SCREAMING_SNAKE_CASE ) self.assertEqual(2 ,batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens ,[] ) self.assertEqual(self.tokenizer.suffix_tokens ,[self.tokenizer.eos_token_id, EN_CODE] ) def _lowercase ( self ) -> str: _snake_case = self.tokenizer(self.src_text ,padding=_SCREAMING_SNAKE_CASE ,truncation=_SCREAMING_SNAKE_CASE ,max_length=3 ,return_tensors="pt" ) _snake_case = self.tokenizer( text_target=self.tgt_text ,padding=_SCREAMING_SNAKE_CASE ,truncation=_SCREAMING_SNAKE_CASE ,max_length=10 ,return_tensors="pt" ) _snake_case = targets["input_ids"] _snake_case = shift_tokens_right(_SCREAMING_SNAKE_CASE ,self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] ,3 ) self.assertEqual(batch.decoder_input_ids.shape[1] ,10 ) @require_torch def _lowercase ( self ) -> Any: _snake_case = self.tokenizer._build_translation_inputs( "A test" ,return_tensors="pt" ,src_lang="en_XX" ,tgt_lang="ar_AR" ) self.assertEqual( nested_simplify(_SCREAMING_SNAKE_CASE ) ,{ # A, test, EOS, en_XX "input_ids": [[62, 3_034, 2, 250_004]], "attention_mask": [[1, 1, 1, 1]], # ar_AR "forced_bos_token_id": 250_001, } ,)
142
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _a : 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: _a : Any= [ "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: _a : Any= [ "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 _a : Any= _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
172
"""simple docstring""" import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _a : Optional[int]= logging.get_logger(__name__) _a : Dict= {"vocab_file": "spiece.model"} _a : int= { "vocab_file": { "albert-base-v1": "https://huggingface.co/albert-base-v1/resolve/main/spiece.model", "albert-large-v1": "https://huggingface.co/albert-large-v1/resolve/main/spiece.model", "albert-xlarge-v1": "https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model", "albert-xxlarge-v1": "https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model", "albert-base-v2": "https://huggingface.co/albert-base-v2/resolve/main/spiece.model", "albert-large-v2": "https://huggingface.co/albert-large-v2/resolve/main/spiece.model", "albert-xlarge-v2": "https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model", "albert-xxlarge-v2": "https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model", } } _a : int= { "albert-base-v1": 512, "albert-large-v1": 512, "albert-xlarge-v1": 512, "albert-xxlarge-v1": 512, "albert-base-v2": 512, "albert-large-v2": 512, "albert-xlarge-v2": 512, "albert-xxlarge-v2": 512, } _a : Optional[Any]= "▁" class UpperCamelCase ( lowercase ): UpperCAmelCase : Optional[Any] = VOCAB_FILES_NAMES UpperCAmelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__(self : Optional[Any] , _A : List[str] , _A : int=True , _A : Optional[int]=True , _A : Any=False , _A : str="[CLS]" , _A : Dict="[SEP]" , _A : Any="<unk>" , _A : List[Any]="[SEP]" , _A : Any="<pad>" , _A : List[str]="[CLS]" , _A : int="[MASK]" , _A : Optional[Dict[str, Any]] = None , **_A : List[str] , ) -> None: # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __snake_case : Dict = ( AddedToken(_A , lstrip=_A , rstrip=_A , normalized=_A) if isinstance(_A , _A) else mask_token ) __snake_case : List[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=_A , remove_space=_A , keep_accents=_A , bos_token=_A , eos_token=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , sp_model_kwargs=self.sp_model_kwargs , **_A , ) __snake_case : Optional[int] = do_lower_case __snake_case : Any = remove_space __snake_case : Any = keep_accents __snake_case : Dict = vocab_file __snake_case : int = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(_A) @property def _lowercase (self : str) -> Optional[Any]: return len(self.sp_model) def _lowercase (self : Dict) -> List[str]: __snake_case : int = {self.convert_ids_to_tokens(_A): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__(self : Optional[int]) -> int: __snake_case : List[Any] = self.__dict__.copy() __snake_case : Any = None return state def __setstate__(self : Union[str, Any] , _A : Optional[Any]) -> int: __snake_case : str = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs'): __snake_case : Optional[int] = {} __snake_case : Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def _lowercase (self : Tuple , _A : int) -> int: if self.remove_space: __snake_case : int = ' '.join(inputs.strip().split()) else: __snake_case : str = inputs __snake_case : Optional[int] = outputs.replace('``' , '"').replace('\'\'' , '"') if not self.keep_accents: __snake_case : Tuple = unicodedata.normalize('NFKD' , _A) __snake_case : Optional[Any] = ''.join([c for c in outputs if not unicodedata.combining(_A)]) if self.do_lower_case: __snake_case : Union[str, Any] = outputs.lower() return outputs def _lowercase (self : Any , _A : str) -> List[str]: __snake_case : Union[str, Any] = self.preprocess_text(_A) __snake_case : Optional[Any] = self.sp_model.encode(_A , out_type=_A) __snake_case : Tuple = [] for piece in pieces: if len(_A) > 1 and piece[-1] == str(',') and piece[-2].isdigit(): __snake_case : Tuple = self.sp_model.EncodeAsPieces(piece[:-1].replace(_A , '')) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0]) == 1: __snake_case : Any = cur_pieces[1:] else: __snake_case : Optional[int] = cur_pieces[0][1:] cur_pieces.append(piece[-1]) new_pieces.extend(_A) else: new_pieces.append(_A) return new_pieces def _lowercase (self : Optional[Any] , _A : List[str]) -> int: return self.sp_model.PieceToId(_A) def _lowercase (self : Optional[int] , _A : Tuple) -> Union[str, Any]: return self.sp_model.IdToPiece(_A) def _lowercase (self : Union[str, Any] , _A : Union[str, Any]) -> Dict: __snake_case : Any = [] __snake_case : Dict = '' __snake_case : Optional[int] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_A) + token __snake_case : List[str] = True __snake_case : int = [] else: current_sub_tokens.append(_A) __snake_case : int = False out_string += self.sp_model.decode(_A) return out_string.strip() def _lowercase (self : List[Any] , _A : List[int] , _A : Optional[List[int]] = None) -> List[int]: __snake_case : Dict = [self.sep_token_id] __snake_case : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def _lowercase (self : Tuple , _A : List[int] , _A : Optional[List[int]] = None , _A : bool = False) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_A , token_ids_a=_A , already_has_special_tokens=_A) if token_ids_a is not None: return [1] + ([0] * len(_A)) + [1] + ([0] * len(_A)) + [1] return [1] + ([0] * len(_A)) + [1] def _lowercase (self : str , _A : List[int] , _A : Optional[List[int]] = None) -> List[int]: __snake_case : int = [self.sep_token_id] __snake_case : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def _lowercase (self : Optional[Any] , _A : str , _A : Optional[str] = None) -> Tuple[str]: if not os.path.isdir(_A): logger.error(f"Vocabulary path ({save_directory}) should be a directory") return __snake_case : Optional[Any] = os.path.join( _A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(_A) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file , _A) elif not os.path.isfile(self.vocab_file): with open(_A , 'wb') as fi: __snake_case : Optional[Any] = self.sp_model.serialized_model_proto() fi.write(_A) return (out_vocab_file,)
172
1
from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar __UpperCAmelCase = TypeVar("T") class UpperCamelCase__ ( Generic[T] ): """simple docstring""" UpperCAmelCase_ =42 # Cache store of keys UpperCAmelCase_ =42 # References of the keys in cache UpperCAmelCase_ =10 # Maximum capacity of cache def __init__( self , _A ) -> None: SCREAMING_SNAKE_CASE_ = deque() SCREAMING_SNAKE_CASE_ = set() if not n: SCREAMING_SNAKE_CASE_ = sys.maxsize elif n < 0: raise ValueError('''n should be an integer greater than 0.''' ) else: SCREAMING_SNAKE_CASE_ = n def _UpperCamelCase ( self , _A ) -> None: if x not in self.key_reference: if len(self.dq_store ) == LRUCache._MAX_CAPACITY: SCREAMING_SNAKE_CASE_ = self.dq_store.pop() self.key_reference.remove(lowerCamelCase__ ) else: self.dq_store.remove(lowerCamelCase__ ) self.dq_store.appendleft(lowerCamelCase__ ) self.key_reference.add(lowerCamelCase__ ) def _UpperCamelCase ( self ) -> None: for k in self.dq_store: print(lowerCamelCase__ ) def __repr__( self ) -> str: return F'''LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}''' if __name__ == "__main__": import doctest doctest.testmod() __UpperCAmelCase = LRUCache(4) lru_cache.refer("A") lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer("A") lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
357
import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.testing_utils import require_tensorflow_text, require_tf, slow if is_tf_available(): import tensorflow as tf if is_tensorflow_text_available(): from transformers.models.bert import TFBertTokenizer __UpperCAmelCase = ["bert-base-uncased", "bert-base-cased"] __UpperCAmelCase = "hf-internal-testing/tiny-bert-tf-only" if is_tf_available(): class UpperCamelCase__ ( tf.keras.Model ): """simple docstring""" def __init__( self , _A ) -> int: super().__init__() SCREAMING_SNAKE_CASE_ = tokenizer SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained(_A ) SCREAMING_SNAKE_CASE_ = TFAutoModel.from_config(_A ) def _UpperCamelCase ( self , _A ) -> Optional[Any]: SCREAMING_SNAKE_CASE_ = self.tokenizer(_A ) SCREAMING_SNAKE_CASE_ = self.bert(**_A ) return out["pooler_output"] @require_tf @require_tensorflow_text class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def _UpperCamelCase ( self ) -> Optional[Any]: super().setUp() SCREAMING_SNAKE_CASE_ = [ BertTokenizer.from_pretrained(_A ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2) ] # repeat for when fast_bert_tokenizer=false SCREAMING_SNAKE_CASE_ = [TFBertTokenizer.from_pretrained(_A ) for checkpoint in TOKENIZER_CHECKPOINTS] + [ TFBertTokenizer.from_pretrained(_A , use_fast_bert_tokenizer=_A ) for checkpoint in TOKENIZER_CHECKPOINTS ] assert len(self.tokenizers ) == len(self.tf_tokenizers ) SCREAMING_SNAKE_CASE_ = [ '''This is a straightforward English test sentence.''', '''This one has some weird characters\rto\nsee\r\nif those\u00E9break things.''', '''Now we\'re going to add some Chinese: 一 二 三 一二三''', '''And some much more rare Chinese: 齉 堃 齉堃''', '''Je vais aussi écrire en français pour tester les accents''', '''Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ''', ] SCREAMING_SNAKE_CASE_ = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def _UpperCamelCase ( self ) -> str: for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in (self.test_sentences, self.paired_sentences): SCREAMING_SNAKE_CASE_ = tokenizer(_A , return_tensors='''tf''' , padding='''longest''' ) SCREAMING_SNAKE_CASE_ = tf_tokenizer(_A ) for key in python_outputs.keys(): self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) ) self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa ) == tf_outputs[key] ) ) @slow def _UpperCamelCase ( self ) -> Dict: for tf_tokenizer in self.tf_tokenizers: SCREAMING_SNAKE_CASE_ = tf_tokenizer(self.paired_sentences ) SCREAMING_SNAKE_CASE_ = tf_tokenizer( text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , ) for key in merged_outputs.keys(): self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa ) == separated_outputs[key] ) ) @slow def _UpperCamelCase ( self ) -> int: for tf_tokenizer in self.tf_tokenizers: SCREAMING_SNAKE_CASE_ = tf.function(_A ) for test_inputs in (self.test_sentences, self.paired_sentences): SCREAMING_SNAKE_CASE_ = tf.constant(_A ) SCREAMING_SNAKE_CASE_ = compiled_tokenizer(_A ) SCREAMING_SNAKE_CASE_ = tf_tokenizer(_A ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def _UpperCamelCase ( self ) -> List[str]: for tf_tokenizer in self.tf_tokenizers: SCREAMING_SNAKE_CASE_ = ModelToSave(tokenizer=_A ) SCREAMING_SNAKE_CASE_ = tf.convert_to_tensor(self.test_sentences ) SCREAMING_SNAKE_CASE_ = model(_A ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: SCREAMING_SNAKE_CASE_ = Path(_A ) / '''saved.model''' model.save(_A ) SCREAMING_SNAKE_CASE_ = tf.keras.models.load_model(_A ) SCREAMING_SNAKE_CASE_ = loaded_model(_A ) # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) , 1E-5 )
257
0
import json import os from typing import Dict, List, Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } a_ = { 'vocab_file': { 'facebook/blenderbot_small-90M': 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json' }, 'merges_file': { 'facebook/blenderbot_small-90M': 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt' }, 'tokenizer_config_file': { 'facebook/blenderbot_small-90M': ( 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json' ) }, } a_ = {'facebook/blenderbot_small-90M': 512} def __lowercase ( lowerCamelCase : Optional[Any] ): UpperCamelCase_ : int = set() UpperCamelCase_ : str = word[0] for char in word[1:]: pairs.add((prev_char, char) ) UpperCamelCase_ : Optional[Any] = char UpperCamelCase_ : Dict = set(snake_case_ ) return pairs class _lowercase ( A__ ): lowercase = VOCAB_FILES_NAMES lowercase = PRETRAINED_VOCAB_FILES_MAP lowercase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase = ['input_ids', 'attention_mask'] def __init__( self : Union[str, Any] , snake_case : str , snake_case : Tuple , snake_case : Optional[int]="__start__" , snake_case : List[Any]="__end__" , snake_case : Optional[int]="__unk__" , snake_case : str="__null__" , **snake_case : int , ) -> int: """simple docstring""" super().__init__(unk_token=lowerCamelCase_ , bos_token=lowerCamelCase_ , eos_token=lowerCamelCase_ , pad_token=lowerCamelCase_ , **lowerCamelCase_ ) with open(lowerCamelCase_ , encoding='utf-8' ) as vocab_handle: UpperCamelCase_ : Union[str, Any] = json.load(lowerCamelCase_ ) UpperCamelCase_ : Tuple = {v: k for k, v in self.encoder.items()} with open(lowerCamelCase_ , encoding='utf-8' ) as merges_handle: UpperCamelCase_ : int = merges_handle.read().split('\n' )[1:-1] UpperCamelCase_ : Optional[int] = [tuple(merge.split() ) for merge in merges] UpperCamelCase_ : int = dict(zip(lowerCamelCase_ , range(len(lowerCamelCase_ ) ) ) ) UpperCamelCase_ : Optional[Any] = {} @property def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Dict: """simple docstring""" return len(self.encoder ) def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Optional[int]: """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def SCREAMING_SNAKE_CASE__ ( self : str , snake_case : str ) -> str: """simple docstring""" if token in self.cache: return self.cache[token] UpperCamelCase_ : List[Any] = re.sub('([.,!?()])' , R' \1' , lowerCamelCase_ ) UpperCamelCase_ : Any = re.sub('(\')' , R' \1 ' , lowerCamelCase_ ) UpperCamelCase_ : Any = re.sub(R'\s{2,}' , ' ' , lowerCamelCase_ ) if "\n" in token: UpperCamelCase_ : Any = token.replace('\n' , ' __newln__' ) UpperCamelCase_ : List[Any] = token.split(' ' ) UpperCamelCase_ : str = [] for token in tokens: if not len(lowerCamelCase_ ): continue UpperCamelCase_ : Any = token.lower() UpperCamelCase_ : Optional[Any] = tuple(lowerCamelCase_ ) UpperCamelCase_ : int = tuple(list(word[:-1] ) + [word[-1] + '</w>'] ) UpperCamelCase_ : Any = get_pairs(lowerCamelCase_ ) if not pairs: words.append(lowerCamelCase_ ) continue while True: UpperCamelCase_ : Optional[int] = min(lowerCamelCase_ , key=lambda snake_case : self.bpe_ranks.get(lowerCamelCase_ , float('inf' ) ) ) if bigram not in self.bpe_ranks: break UpperCamelCase_ : Dict = bigram UpperCamelCase_ : Union[str, Any] = [] UpperCamelCase_ : List[Any] = 0 while i < len(lowerCamelCase_ ): try: UpperCamelCase_ : int = word.index(lowerCamelCase_ , lowerCamelCase_ ) new_word.extend(word[i:j] ) UpperCamelCase_ : Union[str, Any] = j except ValueError: new_word.extend(word[i:] ) break if word[i] == first and i < len(lowerCamelCase_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 UpperCamelCase_ : List[Any] = tuple(lowerCamelCase_ ) UpperCamelCase_ : Optional[Any] = new_word if len(lowerCamelCase_ ) == 1: break else: UpperCamelCase_ : Tuple = get_pairs(lowerCamelCase_ ) UpperCamelCase_ : str = '@@ '.join(lowerCamelCase_ ) UpperCamelCase_ : Optional[Any] = word[:-4] UpperCamelCase_ : Any = word words.append(lowerCamelCase_ ) return " ".join(lowerCamelCase_ ) def SCREAMING_SNAKE_CASE__ ( self : Dict , snake_case : str ) -> str: """simple docstring""" UpperCamelCase_ : Optional[Any] = [] UpperCamelCase_ : str = re.findall(R'\S+\n?' , lowerCamelCase_ ) for token in words: split_tokens.extend(list(self.bpe(lowerCamelCase_ ).split(' ' ) ) ) return split_tokens def SCREAMING_SNAKE_CASE__ ( self : List[Any] , snake_case : str ) -> Any: """simple docstring""" UpperCamelCase_ : Optional[Any] = token.lower() return self.encoder.get(lowerCamelCase_ , self.encoder.get(self.unk_token ) ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] , snake_case : int ) -> Union[str, Any]: """simple docstring""" return self.decoder.get(lowerCamelCase_ , self.unk_token ) def SCREAMING_SNAKE_CASE__ ( self : int , snake_case : List[str] ) -> int: """simple docstring""" UpperCamelCase_ : int = ' '.join(lowerCamelCase_ ).replace('@@ ' , '' ).strip() return out_string def SCREAMING_SNAKE_CASE__ ( self : int , snake_case : str , snake_case : Optional[str] = None ) -> int: """simple docstring""" if not os.path.isdir(lowerCamelCase_ ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return UpperCamelCase_ : str = os.path.join( lowerCamelCase_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) UpperCamelCase_ : Union[str, Any] = os.path.join( lowerCamelCase_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] ) with open(lowerCamelCase_ , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=lowerCamelCase_ , ensure_ascii=lowerCamelCase_ ) + '\n' ) UpperCamelCase_ : Any = 0 with open(lowerCamelCase_ , 'w' , encoding='utf-8' ) as writer: writer.write('#version: 0.2\n' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda snake_case : kv[1] ): if index != token_index: logger.warning( f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive." ' Please check that the tokenizer is not corrupted!' ) UpperCamelCase_ : int = token_index writer.write(' '.join(lowerCamelCase_ ) + '\n' ) index += 1 return vocab_file, merge_file
175
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input lowerCAmelCase = """Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine""" def lowerCAmelCase_ ( ) ->Tuple: lowerCamelCase__ : Dict =_ask_options( 'In which compute environment are you running?' , ['This machine', 'AWS (Amazon SageMaker)'] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: lowerCamelCase__ : int =get_sagemaker_input() else: lowerCamelCase__ : List[str] =get_cluster_input() return config def lowerCAmelCase_ ( snake_case_ : List[Any]=None ) ->List[str]: if subparsers is not None: lowerCamelCase__ : Union[str, Any] =subparsers.add_parser('config' , description=snake_case_ ) else: lowerCamelCase__ : Tuple =argparse.ArgumentParser('Accelerate config command' , description=snake_case_ ) parser.add_argument( '--config_file' , default=snake_case_ , help=( 'The path to use to store the config file. Will default to a file named default_config.yaml in the cache ' 'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ' 'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ' 'with \'huggingface\'.' ) , ) if subparsers is not None: parser.set_defaults(func=snake_case_ ) return parser def lowerCAmelCase_ ( snake_case_ : str ) ->List[Any]: lowerCamelCase__ : Optional[int] =get_user_input() if args.config_file is not None: lowerCamelCase__ : Dict =args.config_file else: if not os.path.isdir(snake_case_ ): os.makedirs(snake_case_ ) lowerCamelCase__ : Optional[Any] =default_yaml_config_file if config_file.endswith('.json' ): config.to_json_file(snake_case_ ) else: config.to_yaml_file(snake_case_ ) print(f"""accelerate configuration saved at {config_file}""" ) def lowerCAmelCase_ ( ) ->Optional[Any]: lowerCamelCase__ : Tuple =config_command_parser() lowerCamelCase__ : Tuple =parser.parse_args() config_command(snake_case_ ) if __name__ == "__main__": main()
126
0
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase = { '''configuration_trajectory_transformer''': [ '''TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TrajectoryTransformerConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase = [ '''TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TrajectoryTransformerModel''', '''TrajectoryTransformerPreTrainedModel''', '''load_tf_weights_in_trajectory_transformer''', ] if TYPE_CHECKING: from .configuration_trajectory_transformer import ( TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TrajectoryTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trajectory_transformer import ( TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TrajectoryTransformerModel, TrajectoryTransformerPreTrainedModel, load_tf_weights_in_trajectory_transformer, ) else: import sys lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
304
from typing import Any import numpy as np def _lowerCamelCase( lowercase__ ) -> bool: '''simple docstring''' return np.array_equal(lowercase__ , matrix.conjugate().T ) def _lowerCamelCase( lowercase__ , lowercase__ ) -> Any: '''simple docstring''' __lowercase= v.conjugate().T __lowercase= v_star.dot(lowercase__ ) assert isinstance(lowercase__ , np.ndarray ) return (v_star_dot.dot(lowercase__ )) / (v_star.dot(lowercase__ )) def _lowerCamelCase( ) -> None: '''simple docstring''' __lowercase= np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]] ) __lowercase= np.array([[1], [2], [3]] ) assert is_hermitian(lowercase__ ), F'{a} is not hermitian.' print(rayleigh_quotient(lowercase__ , lowercase__ ) ) __lowercase= np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] ) assert is_hermitian(lowercase__ ), F'{a} is not hermitian.' assert rayleigh_quotient(lowercase__ , lowercase__ ) == float(3 ) if __name__ == "__main__": import doctest doctest.testmod() tests()
304
1
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase : Dict = logging.get_logger(__name__) lowerCamelCase : List[Any] = { "ut/deta": "https://huggingface.co/ut/deta/resolve/main/config.json", } class A__ ( A__ ): A__ = 'deta' A__ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : Tuple , _a : Optional[int]=None , _a : int=900 , _a : Optional[Any]=2048 , _a : int=6 , _a : Tuple=2048 , _a : Optional[int]=8 , _a : Any=6 , _a : str=1024 , _a : int=8 , _a : int=0.0 , _a : Optional[Any]=True , _a : Tuple="relu" , _a : Union[str, Any]=256 , _a : Tuple=0.1 , _a : str=0.0 , _a : Dict=0.0 , _a : Tuple=0.02 , _a : Union[str, Any]=1.0 , _a : Any=True , _a : Tuple=False , _a : List[Any]="sine" , _a : str=5 , _a : List[Any]=4 , _a : str=4 , _a : Union[str, Any]=True , _a : Optional[int]=300 , _a : Dict=True , _a : List[Any]=True , _a : List[Any]=1 , _a : List[str]=5 , _a : int=2 , _a : Dict=1 , _a : str=1 , _a : Optional[Any]=5 , _a : Union[str, Any]=2 , _a : List[str]=0.1 , _a : List[Any]=0.25 , **_a : Union[str, Any] , ) -> List[str]: '''simple docstring''' if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) _SCREAMING_SNAKE_CASE =CONFIG_MAPPING['resnet'](out_features=['stage2', 'stage3', 'stage4'] ) else: if isinstance(_a , _a ): _SCREAMING_SNAKE_CASE =backbone_config.pop('model_type' ) _SCREAMING_SNAKE_CASE =CONFIG_MAPPING[backbone_model_type] _SCREAMING_SNAKE_CASE =config_class.from_dict(_a ) _SCREAMING_SNAKE_CASE =backbone_config _SCREAMING_SNAKE_CASE =num_queries _SCREAMING_SNAKE_CASE =max_position_embeddings _SCREAMING_SNAKE_CASE =d_model _SCREAMING_SNAKE_CASE =encoder_ffn_dim _SCREAMING_SNAKE_CASE =encoder_layers _SCREAMING_SNAKE_CASE =encoder_attention_heads _SCREAMING_SNAKE_CASE =decoder_ffn_dim _SCREAMING_SNAKE_CASE =decoder_layers _SCREAMING_SNAKE_CASE =decoder_attention_heads _SCREAMING_SNAKE_CASE =dropout _SCREAMING_SNAKE_CASE =attention_dropout _SCREAMING_SNAKE_CASE =activation_dropout _SCREAMING_SNAKE_CASE =activation_function _SCREAMING_SNAKE_CASE =init_std _SCREAMING_SNAKE_CASE =init_xavier_std _SCREAMING_SNAKE_CASE =encoder_layerdrop _SCREAMING_SNAKE_CASE =auxiliary_loss _SCREAMING_SNAKE_CASE =position_embedding_type # deformable attributes _SCREAMING_SNAKE_CASE =num_feature_levels _SCREAMING_SNAKE_CASE =encoder_n_points _SCREAMING_SNAKE_CASE =decoder_n_points _SCREAMING_SNAKE_CASE =two_stage _SCREAMING_SNAKE_CASE =two_stage_num_proposals _SCREAMING_SNAKE_CASE =with_box_refine _SCREAMING_SNAKE_CASE =assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError('If two_stage is True, with_box_refine must be True.' ) # Hungarian matcher _SCREAMING_SNAKE_CASE =class_cost _SCREAMING_SNAKE_CASE =bbox_cost _SCREAMING_SNAKE_CASE =giou_cost # Loss coefficients _SCREAMING_SNAKE_CASE =mask_loss_coefficient _SCREAMING_SNAKE_CASE =dice_loss_coefficient _SCREAMING_SNAKE_CASE =bbox_loss_coefficient _SCREAMING_SNAKE_CASE =giou_loss_coefficient _SCREAMING_SNAKE_CASE =eos_coefficient _SCREAMING_SNAKE_CASE =focal_alpha super().__init__(is_encoder_decoder=_a , **_a ) @property def A ( self : Dict ) -> int: '''simple docstring''' return self.encoder_attention_heads @property def A ( self : List[Any] ) -> int: '''simple docstring''' return self.d_model def A ( self : Optional[int] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =copy.deepcopy(self.__dict__ ) _SCREAMING_SNAKE_CASE =self.backbone_config.to_dict() _SCREAMING_SNAKE_CASE =self.__class__.model_type return output
47
'''simple docstring''' from __future__ import annotations from decimal import Decimal from numpy import array def __lowerCAmelCase ( UpperCamelCase__ ) -> list[list[float]]: __lowerCamelCase = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(UpperCamelCase__ ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2: # Calculate the determinant of the matrix __lowerCamelCase = float( d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) ) if determinant == 0: raise ValueError('''This matrix has no inverse.''' ) # Creates a copy of the matrix with swapped positions of the elements __lowerCamelCase = [[0.0, 0.0], [0.0, 0.0]] __lowerCamelCase , __lowerCamelCase = matrix[1][1], matrix[0][0] __lowerCamelCase , __lowerCamelCase = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(UpperCamelCase__ ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(UpperCamelCase__ ) == 3 and len(matrix[0] ) == 3 and len(matrix[1] ) == 3 and len(matrix[2] ) == 3 ): # Calculate the determinant of the matrix using Sarrus rule __lowerCamelCase = float( ( (d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] )) + (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] )) + (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] )) ) - ( (d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] )) + (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] )) + (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] )) ) ) if determinant == 0: raise ValueError('''This matrix has no inverse.''' ) # Creating cofactor matrix __lowerCamelCase = [ [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], ] __lowerCamelCase = (d(matrix[1][1] ) * d(matrix[2][2] )) - ( d(matrix[1][2] ) * d(matrix[2][1] ) ) __lowerCamelCase = -( (d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] )) ) __lowerCamelCase = (d(matrix[1][0] ) * d(matrix[2][1] )) - ( d(matrix[1][1] ) * d(matrix[2][0] ) ) __lowerCamelCase = -( (d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] )) ) __lowerCamelCase = (d(matrix[0][0] ) * d(matrix[2][2] )) - ( d(matrix[0][2] ) * d(matrix[2][0] ) ) __lowerCamelCase = -( (d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] )) ) __lowerCamelCase = (d(matrix[0][1] ) * d(matrix[1][2] )) - ( d(matrix[0][2] ) * d(matrix[1][1] ) ) __lowerCamelCase = -( (d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] )) ) __lowerCamelCase = (d(matrix[0][0] ) * d(matrix[1][1] )) - ( d(matrix[0][1] ) * d(matrix[1][0] ) ) # Transpose the cofactor matrix (Adjoint matrix) __lowerCamelCase = array(UpperCamelCase__ ) for i in range(3 ): for j in range(3 ): __lowerCamelCase = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix __lowerCamelCase = array(UpperCamelCase__ ) for i in range(3 ): for j in range(3 ): inverse_matrix[i][j] /= d(UpperCamelCase__ ) # Calculate the inverse of the matrix return [[float(d(UpperCamelCase__ ) ) or 0.0 for n in row] for row in inverse_matrix] raise ValueError('''Please provide a matrix of size 2x2 or 3x3.''' )
67
0
'''simple docstring''' from __future__ import annotations import unittest from transformers import EsmConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers.models.esm.modeling_tf_esm import ( TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, TFEsmModel, ) class UpperCamelCase : """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase_ : int , ): """simple docstring""" a : Optional[int] = parent a : Dict = 1_3 a : int = 7 a : Optional[int] = True a : Tuple = True a : Optional[Any] = True a : Optional[int] = 9_9 a : Tuple = 3_2 a : Any = 2 a : Optional[int] = 4 a : str = 3_7 a : str = 'gelu' a : Any = 0.1 a : List[str] = 0.1 a : Optional[int] = 5_1_2 a : Union[str, Any] = 1_6 a : Optional[Any] = 2 a : Optional[Any] = 0.02 a : Dict = 3 a : Optional[int] = 4 a : Tuple = None def SCREAMING_SNAKE_CASE_ ( self : Any): """simple docstring""" a : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) a : Union[str, Any] = None if self.use_input_mask: a : Tuple = random_attention_mask([self.batch_size, self.seq_length]) a : int = None a : List[str] = None a : int = None if self.use_labels: a : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size) a : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) a : int = ids_tensor([self.batch_size] , self.num_choices) a : Dict = EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , pad_token_id=1 , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE_ ( self : Optional[int]): """simple docstring""" ( a ) : List[Any] = self.prepare_config_and_inputs() a : str = True a : Any = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) a : str = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) return ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def SCREAMING_SNAKE_CASE_ ( self : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Any , UpperCAmelCase_ : str): """simple docstring""" a : Optional[Any] = TFEsmModel(config=UpperCAmelCase_) a : int = {'input_ids': input_ids, 'attention_mask': input_mask} a : Dict = model(UpperCAmelCase_) a : Union[str, Any] = [input_ids, input_mask] a : Any = model(UpperCAmelCase_) a : List[Any] = model(UpperCAmelCase_) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE_ ( self : str , UpperCAmelCase_ : str , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any] , ): """simple docstring""" a : Tuple = True a : Optional[Any] = TFEsmModel(config=UpperCAmelCase_) a : str = { 'input_ids': input_ids, 'attention_mask': input_mask, 'encoder_hidden_states': encoder_hidden_states, 'encoder_attention_mask': encoder_attention_mask, } a : Tuple = model(UpperCAmelCase_) a : Union[str, Any] = [input_ids, input_mask] a : str = model(UpperCAmelCase_ , encoder_hidden_states=UpperCAmelCase_) # Also check the case where encoder outputs are not passed a : List[str] = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE_ ( self : str , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Dict): """simple docstring""" a : Optional[int] = TFEsmForMaskedLM(config=UpperCAmelCase_) a : List[Any] = model([input_ids, input_mask]) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE_ ( self : List[str] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple): """simple docstring""" a : Dict = self.num_labels a : Dict = TFEsmForTokenClassification(config=UpperCAmelCase_) a : Union[str, Any] = {'input_ids': input_ids, 'attention_mask': input_mask} a : List[Any] = model(UpperCAmelCase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any]): """simple docstring""" a : Any = self.prepare_config_and_inputs() ( a ) : str = config_and_inputs a : List[str] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class UpperCamelCase ( a_ , a_ , unittest.TestCase ): """simple docstring""" A : Any = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) A : Tuple = ( { "feature-extraction": TFEsmModel, "fill-mask": TFEsmForMaskedLM, "text-classification": TFEsmForSequenceClassification, "token-classification": TFEsmForTokenClassification, "zero-shot": TFEsmForSequenceClassification, } if is_tf_available() else {} ) A : Dict = False A : Dict = False def SCREAMING_SNAKE_CASE_ ( self : Dict): """simple docstring""" a : List[Any] = TFEsmModelTester(self) a : int = ConfigTester(self , config_class=UpperCAmelCase_ , hidden_size=3_7) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any]): """simple docstring""" self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self : int): """simple docstring""" a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ ( self : List[str]): """simple docstring""" a : str = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ ( self : Dict): """simple docstring""" a : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ ( self : List[str]): """simple docstring""" a : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase_) @slow def SCREAMING_SNAKE_CASE_ ( self : Optional[Any]): """simple docstring""" for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : str = TFEsmModel.from_pretrained(UpperCAmelCase_) self.assertIsNotNone(UpperCAmelCase_) @unittest.skip('Protein models do not support embedding resizing.') def SCREAMING_SNAKE_CASE_ ( self : Tuple): """simple docstring""" pass @unittest.skip('Protein models do not support embedding resizing.') def SCREAMING_SNAKE_CASE_ ( self : Dict): """simple docstring""" pass def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any]): """simple docstring""" a : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a : Any = model_class(UpperCAmelCase_) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer) if model_class is TFEsmForMaskedLM: # Output embedding test differs from the main test because they're a matrix, not a layer a : Union[str, Any] = model.get_bias() assert isinstance(UpperCAmelCase_ , UpperCAmelCase_) for k, v in name.items(): assert isinstance(UpperCAmelCase_ , tf.Variable) else: a : int = model.get_output_embeddings() assert x is None a : Tuple = model.get_bias() assert name is None @require_tf class UpperCamelCase ( unittest.TestCase ): """simple docstring""" @slow def SCREAMING_SNAKE_CASE_ ( self : Dict): """simple docstring""" a : Dict = TFEsmForMaskedLM.from_pretrained('facebook/esm2_t6_8M_UR50D') a : Dict = tf.constant([[0, 1, 2, 3, 4, 5]]) a : List[str] = model(UpperCAmelCase_)[0] a : Union[str, Any] = [1, 6, 3_3] self.assertEqual(list(output.numpy().shape) , UpperCAmelCase_) # compare the actual values for a slice. a : Any = tf.constant( [ [ [8.92_15_18, -10.58_98_14, -6.4_67_13_07], [-6.3_96_71_56, -13.91_13_77, -1.1_21_19_15], [-7.78_12_47, -13.95_15_57, -3.74_05_92], ] ]) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-2)) @slow def SCREAMING_SNAKE_CASE_ ( self : Tuple): """simple docstring""" a : Union[str, Any] = TFEsmModel.from_pretrained('facebook/esm2_t6_8M_UR50D') a : Tuple = tf.constant([[0, 6, 4, 1_3, 5, 4, 1_6, 1_2, 1_1, 7, 2]]) a : Any = model(UpperCAmelCase_)[0] # compare the actual values for a slice. a : Dict = tf.constant( [ [ [0.14_44_30_92, 0.54_12_53_27, 0.3_24_77_39], [0.30_34_04_84, 0.00_52_66_76, 0.31_07_77_22], [0.32_27_80_43, -0.24_98_70_96, 0.3_41_46_28], ] ]) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4))
364
'''simple docstring''' import logging from transformers.configuration_utils import PretrainedConfig UpperCamelCase : Optional[Any] = logging.getLogger(__name__) class UpperCamelCase ( a_ ): """simple docstring""" A : Tuple = "masked_bert" def __init__( self : Tuple , UpperCAmelCase_ : List[Any]=3_0_5_2_2 , UpperCAmelCase_ : str=7_6_8 , UpperCAmelCase_ : Optional[Any]=1_2 , UpperCAmelCase_ : Optional[int]=1_2 , UpperCAmelCase_ : Union[str, Any]=3_0_7_2 , UpperCAmelCase_ : Union[str, Any]="gelu" , UpperCAmelCase_ : Optional[Any]=0.1 , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : Optional[int]=5_1_2 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : str=0.02 , UpperCAmelCase_ : Optional[Any]=1e-12 , UpperCAmelCase_ : Dict=0 , UpperCAmelCase_ : Dict="topK" , UpperCAmelCase_ : str="constant" , UpperCAmelCase_ : Optional[Any]=0.0 , **UpperCAmelCase_ : Optional[Any] , ): """simple docstring""" super().__init__(pad_token_id=UpperCAmelCase_ , **UpperCAmelCase_) a : Union[str, Any] = vocab_size a : List[Any] = hidden_size a : List[str] = num_hidden_layers a : Any = num_attention_heads a : Optional[Any] = hidden_act a : str = intermediate_size a : Dict = hidden_dropout_prob a : Any = attention_probs_dropout_prob a : Any = max_position_embeddings a : Dict = type_vocab_size a : List[str] = initializer_range a : int = layer_norm_eps a : Dict = pruning_method a : List[str] = mask_init a : Union[str, Any] = mask_scale
345
0
"""simple docstring""" import heapq def _snake_case ( UpperCAmelCase_ : dict ): A__ = [] # 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(UpperCAmelCase_ , [-1 * len(UpperCAmelCase_ ), (key, value)] ) # chosen_vertices = set of chosen vertices A__ = set() # while queue isn't empty and there are still edges # (queue[0][0] is the rank of the node with max rank) while queue and queue[0][0] != 0: # extract vertex with max rank from queue and add it to chosen_vertices A__ = heapq.heappop(UpperCAmelCase_ )[1][0] chosen_vertices.add(UpperCAmelCase_ ) # Remove all arcs adjacent to argmax for elem in queue: # if v haven't adjacent node, skip if elem[0] == 0: continue # if argmax is reachable from elem # remove argmax from elem's adjacent list and update his rank if argmax in elem[1][1]: A__ = elem[1][1].index(UpperCAmelCase_ ) del elem[1][1][index] elem[0] += 1 # re-order the queue heapq.heapify(UpperCAmelCase_ ) return chosen_vertices if __name__ == "__main__": import doctest doctest.testmod() SCREAMING_SNAKE_CASE_ : Optional[Any] = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} print(f"""Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}""")
335
"""simple docstring""" import unittest import torch from torch import nn from diffusers.models.activations import get_activation class a ( unittest.TestCase ): """simple docstring""" def UpperCamelCase ( self: str ): """simple docstring""" A__ = get_activation("""swish""" ) self.assertIsInstance(UpperCamelCase , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def UpperCamelCase ( self: Any ): """simple docstring""" A__ = get_activation("""silu""" ) self.assertIsInstance(UpperCamelCase , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def UpperCamelCase ( self: Optional[int] ): """simple docstring""" A__ = get_activation("""mish""" ) self.assertIsInstance(UpperCamelCase , nn.Mish ) self.assertEqual(act(torch.tensor(-2_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def UpperCamelCase ( self: Any ): """simple docstring""" A__ = get_activation("""gelu""" ) self.assertIsInstance(UpperCamelCase , nn.GELU ) self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
335
1
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 _UpperCAmelCase = transforms.Compose( [ transforms.Resize((2_5_6, 2_5_6)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def lowerCAmelCase_ ( UpperCamelCase_ ) -> List[Any]: if isinstance(UpperCamelCase_ , torch.Tensor ): return image elif isinstance(UpperCamelCase_ , PIL.Image.Image ): UpperCamelCase_ = [image] UpperCamelCase_ = [trans(img.convert("RGB" ) ) for img in image] UpperCamelCase_ = torch.stack(UpperCamelCase_ ) return image class _UpperCamelCase ( lowerCAmelCase_ ): def __init__( self: List[Any] , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: Dict ) -> str: """simple docstring""" super().__init__() # make sure scheduler can always be converted to DDIM UpperCamelCase_ = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE ) def lowercase ( self: List[str] , _SCREAMING_SNAKE_CASE: Dict ) -> Optional[Any]: """simple docstring""" if strength < 0 or strength > 1: raise ValueError(f'''The value of strength should in [0.0, 1.0] but is {strength}''' ) def lowercase ( self: str , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: List[str] ) -> int: """simple docstring""" UpperCamelCase_ = min(int(num_inference_steps * strength ) , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = max(num_inference_steps - init_timestep , 0 ) UpperCamelCase_ = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def lowercase ( self: Tuple , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Tuple , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: Optional[int]=None ) -> List[Any]: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , (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(_SCREAMING_SNAKE_CASE )}''' ) UpperCamelCase_ = image.to(device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and len(_SCREAMING_SNAKE_CASE ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(_SCREAMING_SNAKE_CASE )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) UpperCamelCase_ = init_latents.shape UpperCamelCase_ = randn_tensor(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ) # get latents print("add noise to latents at timestep" , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.scheduler.add_noise(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = init_latents return latents @torch.no_grad() def __call__( self: Dict , _SCREAMING_SNAKE_CASE: Union[torch.FloatTensor, PIL.Image.Image] = None , _SCREAMING_SNAKE_CASE: float = 0.8 , _SCREAMING_SNAKE_CASE: int = 1 , _SCREAMING_SNAKE_CASE: Optional[Union[torch.Generator, List[torch.Generator]]] = None , _SCREAMING_SNAKE_CASE: float = 0.0 , _SCREAMING_SNAKE_CASE: int = 50 , _SCREAMING_SNAKE_CASE: Optional[bool] = None , _SCREAMING_SNAKE_CASE: Optional[str] = "pil" , _SCREAMING_SNAKE_CASE: bool = True , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" self.check_inputs(_SCREAMING_SNAKE_CASE ) # 2. Preprocess image UpperCamelCase_ = preprocess(_SCREAMING_SNAKE_CASE ) # 3. set timesteps self.scheduler.set_timesteps(_SCREAMING_SNAKE_CASE , device=self.device ) UpperCamelCase_ , UpperCamelCase_ = self.get_timesteps(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.device ) UpperCamelCase_ = timesteps[:1].repeat(_SCREAMING_SNAKE_CASE ) # 4. Prepare latent variables UpperCamelCase_ = self.prepare_latents(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.unet.dtype , self.device , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = latents # 5. Denoising loop for t in self.progress_bar(_SCREAMING_SNAKE_CASE ): # 1. predict noise model_output UpperCamelCase_ = self.unet(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).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_ = self.scheduler.step( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , use_clipped_model_output=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , ).prev_sample UpperCamelCase_ = (image / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase_ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCamelCase_ = self.numpy_to_pil(_SCREAMING_SNAKE_CASE ) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=_SCREAMING_SNAKE_CASE )
328
import requests from bsa import BeautifulSoup def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ ) -> str: UpperCamelCase_ = BeautifulSoup(requests.get(UpperCamelCase_ , params=UpperCamelCase_ ).content , "html.parser" ) UpperCamelCase_ = soup.find("div" , attrs={"class": "gs_ri"} ) UpperCamelCase_ = div.find("div" , attrs={"class": "gs_fl"} ).find_all("a" ) return anchors[2].get_text() if __name__ == "__main__": _UpperCAmelCase = { 'title': ( 'Precisely geometry controlled microsupercapacitors for ultrahigh areal ' 'capacitance, volumetric capacitance, and energy density' ), 'journal': 'Chem. Mater.', 'volume': 3_0, 'pages': '3979-3990', 'year': 2_0_1_8, 'hl': 'en', } print(get_citation('https://scholar.google.com/scholar_lookup', params=params))
328
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaPriorEmbaEmbPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __lowerCamelCase ( A__ , unittest.TestCase ): '''simple docstring''' a_ : Optional[int] = KandinskyVaaControlnetImgaImgPipeline a_ : str = ["""image_embeds""", """negative_image_embeds""", """image""", """hint"""] a_ : List[str] = ["""image_embeds""", """negative_image_embeds""", """image""", """hint"""] a_ : Union[str, Any] = [ """generator""", """height""", """width""", """strength""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] a_ : int = False @property def lowerCamelCase ( self : List[Any] ): return 32 @property def lowerCamelCase ( self : List[str] ): return 32 @property def lowerCamelCase ( self : Optional[Any] ): return self.time_input_dim @property def lowerCamelCase ( self : List[str] ): return self.time_input_dim * 4 @property def lowerCamelCase ( self : Optional[int] ): return 1_00 @property def lowerCamelCase ( self : Optional[int] ): torch.manual_seed(0 ) lowerCAmelCase_ : int = { "in_channels": 8, # Out channels is double in channels because predicts mean and variance "out_channels": 8, "addition_embed_type": "image_hint", "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"), "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"), "mid_block_type": "UNetMidBlock2DSimpleCrossAttn", "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "layers_per_block": 1, "encoder_hid_dim": self.text_embedder_hidden_size, "encoder_hid_dim_type": "image_proj", "cross_attention_dim": self.cross_attention_dim, "attention_head_dim": 4, "resnet_time_scale_shift": "scale_shift", "class_embed_type": None, } lowerCAmelCase_ : Dict = UNetaDConditionModel(**a_ ) return model @property def lowerCamelCase ( self : List[str] ): return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def lowerCamelCase ( self : int ): torch.manual_seed(0 ) lowerCAmelCase_ : int = VQModel(**self.dummy_movq_kwargs ) return model def lowerCamelCase ( self : Dict ): lowerCAmelCase_ : Any = self.dummy_unet lowerCAmelCase_ : Tuple = self.dummy_movq lowerCAmelCase_ : Any = { "num_train_timesteps": 10_00, "beta_schedule": "linear", "beta_start": 0.00085, "beta_end": 0.012, "clip_sample": False, "set_alpha_to_one": False, "steps_offset": 0, "prediction_type": "epsilon", "thresholding": False, } lowerCAmelCase_ : Dict = DDIMScheduler(**a_ ) lowerCAmelCase_ : Optional[int] = { "unet": unet, "scheduler": scheduler, "movq": movq, } return components def lowerCamelCase ( self : str , a_ : Dict , a_ : str=0 ): lowerCAmelCase_ : Dict = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(a_ ) ).to(a_ ) lowerCAmelCase_ : Dict = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( a_ ) # create init_image lowerCAmelCase_ : List[str] = floats_tensor((1, 3, 64, 64) , rng=random.Random(a_ ) ).to(a_ ) lowerCAmelCase_ : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowerCAmelCase_ : Optional[Any] = Image.fromarray(np.uinta(a_ ) ).convert("RGB" ).resize((2_56, 2_56) ) # create hint lowerCAmelCase_ : List[str] = floats_tensor((1, 3, 64, 64) , rng=random.Random(a_ ) ).to(a_ ) if str(a_ ).startswith("mps" ): lowerCAmelCase_ : Union[str, Any] = torch.manual_seed(a_ ) else: lowerCAmelCase_ : Dict = torch.Generator(device=a_ ).manual_seed(a_ ) lowerCAmelCase_ : str = { "image": init_image, "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "hint": hint, "generator": generator, "height": 64, "width": 64, "num_inference_steps": 10, "guidance_scale": 7.0, "strength": 0.2, "output_type": "np", } return inputs def lowerCamelCase ( self : Tuple ): lowerCAmelCase_ : Optional[Any] = "cpu" lowerCAmelCase_ : Any = self.get_dummy_components() lowerCAmelCase_ : Optional[int] = self.pipeline_class(**a_ ) lowerCAmelCase_ : str = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) lowerCAmelCase_ : Any = pipe(**self.get_dummy_inputs(a_ ) ) lowerCAmelCase_ : str = output.images lowerCAmelCase_ : List[Any] = pipe( **self.get_dummy_inputs(a_ ) , return_dict=a_ , )[0] lowerCAmelCase_ : Tuple = image[0, -3:, -3:, -1] lowerCAmelCase_ : Any = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowerCAmelCase_ : Dict = np.array( [0.54985034, 0.55509365, 0.52561504, 0.5570494, 0.5593818, 0.5263979, 0.50285643, 0.5069846, 0.51196736] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), f''' expected_slice {expected_slice}, but got {image_slice.flatten()}''' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), f''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}''' @slow @require_torch_gpu class __lowerCamelCase ( unittest.TestCase ): '''simple docstring''' def lowerCamelCase ( self : int ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase ( self : int ): lowerCAmelCase_ : Optional[int] = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinskyv22/kandinskyv22_controlnet_img2img_robotcat_fp16.npy" ) lowerCAmelCase_ : List[Any] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/cat.png" ) lowerCAmelCase_ : List[str] = init_image.resize((5_12, 5_12) ) lowerCAmelCase_ : Any = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinskyv22/hint_image_cat.png" ) lowerCAmelCase_ : Dict = torch.from_numpy(np.array(a_ ) ).float() / 255.0 lowerCAmelCase_ : Optional[int] = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) lowerCAmelCase_ : Any = "A robot, 4k photo" lowerCAmelCase_ : Union[str, Any] = KandinskyVaaPriorEmbaEmbPipeline.from_pretrained( "kandinsky-community/kandinsky-2-2-prior" , torch_dtype=torch.floataa ) pipe_prior.to(a_ ) lowerCAmelCase_ : Optional[int] = KandinskyVaaControlnetImgaImgPipeline.from_pretrained( "kandinsky-community/kandinsky-2-2-controlnet-depth" , torch_dtype=torch.floataa ) lowerCAmelCase_ : List[Any] = pipeline.to(a_ ) pipeline.set_progress_bar_config(disable=a_ ) lowerCAmelCase_ : Optional[Any] = torch.Generator(device="cpu" ).manual_seed(0 ) lowerCAmelCase_ , lowerCAmelCase_ : List[Any] = pipe_prior( a_ , image=a_ , strength=0.85 , generator=a_ , negative_prompt="" , ).to_tuple() lowerCAmelCase_ : List[Any] = pipeline( image=a_ , image_embeds=a_ , negative_image_embeds=a_ , hint=a_ , generator=a_ , num_inference_steps=1_00 , height=5_12 , width=5_12 , strength=0.5 , output_type="np" , ) lowerCAmelCase_ : Dict = output.images[0] assert image.shape == (5_12, 5_12, 3) assert_mean_pixel_difference(a_ , a_ )
241
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class __lowerCamelCase ( A__ ): '''simple docstring''' a_ : str = ["""image_processor""", """tokenizer"""] a_ : List[str] = """ViTImageProcessor""" a_ : List[str] = ("""CLIPTokenizer""", """CLIPTokenizerFast""") def __init__( self : List[str] , a_ : str=None , a_ : Dict=None , **a_ : List[Any] ): lowerCAmelCase_ : int = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , a_ , ) lowerCAmelCase_ : Union[str, Any] = kwargs.pop("feature_extractor" ) lowerCAmelCase_ : Dict = 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__(a_ , a_ ) def __call__( self : Union[str, Any] , a_ : Any=None , a_ : Dict=None , a_ : List[str]=None , a_ : str=None , **a_ : Any ): if text is None and visual_prompt is None and images is None: raise ValueError("You have to specify either text, visual prompt or images." ) if text is not None and visual_prompt is not None: raise ValueError("You have to specify exactly one type of prompt. Either text or visual prompt." ) if text is not None: lowerCAmelCase_ : Optional[Any] = self.tokenizer(a_ , return_tensors=a_ , **a_ ) if visual_prompt is not None: lowerCAmelCase_ : Optional[Any] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if images is not None: lowerCAmelCase_ : List[str] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if visual_prompt is not None and images is not None: lowerCAmelCase_ : Union[str, Any] = { "pixel_values": image_features.pixel_values, "conditional_pixel_values": prompt_features.pixel_values, } return encoding elif text is not None and images is not None: lowerCAmelCase_ : Optional[int] = image_features.pixel_values return encoding elif text is not None: return encoding elif visual_prompt is not None: lowerCAmelCase_ : Dict = { "conditional_pixel_values": prompt_features.pixel_values, } return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def lowerCamelCase ( self : Optional[int] , *a_ : Optional[Any] , **a_ : List[str] ): return self.tokenizer.batch_decode(*a_ , **a_ ) def lowerCamelCase ( self : Optional[Any] , *a_ : Tuple , **a_ : Tuple ): return self.tokenizer.decode(*a_ , **a_ ) @property def lowerCamelCase ( self : List[Any] ): warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , a_ , ) return self.image_processor_class @property def lowerCamelCase ( self : Dict ): warnings.warn( "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , a_ , ) return self.image_processor
241
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowercase : List[str] ={ "configuration_electra": ["ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP", "ElectraConfig", "ElectraOnnxConfig"], "tokenization_electra": ["ElectraTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : int =["ElectraTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Dict =[ "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: _lowercase : Union[str, Any] =[ "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: _lowercase : Tuple =[ "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 _lowercase : Optional[int] =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
357
def lowerCAmelCase_ ( _lowercase : int) -> int: """simple docstring""" if not isinstance(_lowercase , _lowercase): raise TypeError("""only integers accepted as input""") else: a__ : Any = str(abs(_lowercase)) a__ : str = [list(_lowercase) for char in range(len(_lowercase))] for index in range(len(_lowercase)): num_transpositions[index].pop(_lowercase) return max( int("""""".join(list(_lowercase))) for transposition in num_transpositions) if __name__ == "__main__": __import__("doctest").testmod()
266
0
'''simple docstring''' def __lowerCamelCase ( lowerCAmelCase_ = "The quick brown fox jumps over the lazy dog" , ) -> bool: _a : Dict = set() # Replace all the whitespace in our sentence _a : Union[str, Any] = input_str.replace(' ' , '' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(lowerCAmelCase_ ) == 26 def __lowerCamelCase ( lowerCAmelCase_ = "The quick brown fox jumps over the lazy dog" , ) -> bool: _a : str = [False] * 26 for char in input_str: if char.islower(): _a : List[str] = True elif char.isupper(): _a : str = True return all(lowerCAmelCase_ ) def __lowerCamelCase ( lowerCAmelCase_ = "The quick brown fox jumps over the lazy dog" , ) -> bool: return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def __lowerCamelCase ( ) -> None: from timeit import timeit _a : List[Any] = 'from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest' print(timeit('is_pangram()' , setup=lowerCAmelCase_ ) ) print(timeit('is_pangram_faster()' , setup=lowerCAmelCase_ ) ) print(timeit('is_pangram_fastest()' , setup=lowerCAmelCase_ ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
89
'''simple docstring''' import copy import json import os import tempfile from transformers import is_torch_available from .test_configuration_utils import config_common_kwargs class lowerCAmelCase_ ( __magic_name__ ): def __init__( self , _lowerCAmelCase , _lowerCAmelCase=None , _lowerCAmelCase=True , _lowerCAmelCase=None , **_lowerCAmelCase ) -> Optional[int]: _lowerCAmelCase = parent _lowerCAmelCase = config_class _lowerCAmelCase = has_text_modality _lowerCAmelCase = kwargs _lowerCAmelCase = common_properties def _snake_case ( self ) -> int: _lowerCAmelCase = self.config_class(**self.inputs_dict ) _lowerCAmelCase = ( ["hidden_size", "num_attention_heads", "num_hidden_layers"] if self.common_properties is None else self.common_properties ) # Add common fields for text models if self.has_text_modality: common_properties.extend(["vocab_size"] ) # Test that config has the common properties as getters for prop in common_properties: self.parent.assertTrue(hasattr(_lowerCAmelCase , _lowerCAmelCase ) , msg=f'''`{prop}` does not exist''' ) # Test that config has the common properties as setter for idx, name in enumerate(_lowerCAmelCase ): try: setattr(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) self.parent.assertEqual( getattr(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase , msg=f'''`{name} value {idx} expected, but was {getattr(_lowerCAmelCase , _lowerCAmelCase )}''' ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass # Test if config class can be called with Config(prop_name=..) for idx, name in enumerate(_lowerCAmelCase ): try: _lowerCAmelCase = self.config_class(**{name: idx} ) self.parent.assertEqual( getattr(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase , msg=f'''`{name} value {idx} expected, but was {getattr(_lowerCAmelCase , _lowerCAmelCase )}''' ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass def _snake_case ( self ) -> Optional[int]: _lowerCAmelCase = self.config_class(**self.inputs_dict ) _lowerCAmelCase = json.loads(config.to_json_string() ) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key] , _lowerCAmelCase ) def _snake_case ( self ) -> Union[str, Any]: _lowerCAmelCase = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: _lowerCAmelCase = os.path.join(_lowerCAmelCase , "config.json" ) config_first.to_json_file(_lowerCAmelCase ) _lowerCAmelCase = self.config_class.from_json_file(_lowerCAmelCase ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _snake_case ( self ) -> str: _lowerCAmelCase = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(_lowerCAmelCase ) _lowerCAmelCase = self.config_class.from_pretrained(_lowerCAmelCase ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _snake_case ( self ) -> Dict: _lowerCAmelCase = self.config_class(**self.inputs_dict ) _lowerCAmelCase = "test" with tempfile.TemporaryDirectory() as tmpdirname: _lowerCAmelCase = os.path.join(_lowerCAmelCase , _lowerCAmelCase ) config_first.save_pretrained(_lowerCAmelCase ) _lowerCAmelCase = self.config_class.from_pretrained(_lowerCAmelCase , subfolder=_lowerCAmelCase ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _snake_case ( self ) -> Optional[Any]: _lowerCAmelCase = self.config_class(**self.inputs_dict , num_labels=5 ) self.parent.assertEqual(len(config.idalabel ) , 5 ) self.parent.assertEqual(len(config.labelaid ) , 5 ) _lowerCAmelCase = 3 self.parent.assertEqual(len(config.idalabel ) , 3 ) self.parent.assertEqual(len(config.labelaid ) , 3 ) def _snake_case ( self ) -> List[Any]: if self.config_class.is_composition: return _lowerCAmelCase = self.config_class() self.parent.assertIsNotNone(_lowerCAmelCase ) def _snake_case ( self ) -> str: _lowerCAmelCase = copy.deepcopy(_lowerCAmelCase ) _lowerCAmelCase = self.config_class(**_lowerCAmelCase ) _lowerCAmelCase = [] for key, value in config_common_kwargs.items(): if key == "torch_dtype": if not is_torch_available(): continue else: import torch if config.torch_dtype != torch.floataa: wrong_values.append(("torch_dtype", config.torch_dtype, torch.floataa) ) elif getattr(_lowerCAmelCase , _lowerCAmelCase ) != value: wrong_values.append((key, getattr(_lowerCAmelCase , _lowerCAmelCase ), value) ) if len(_lowerCAmelCase ) > 0: _lowerCAmelCase = "\n".join([f'''- {v[0]}: got {v[1]} instead of {v[2]}''' for v in wrong_values] ) raise ValueError(f'''The following keys were not properly set in the config:\n{errors}''' ) def _snake_case ( self ) -> List[str]: self.create_and_test_config_common_properties() self.create_and_test_config_to_json_string() self.create_and_test_config_to_json_file() self.create_and_test_config_from_and_save_pretrained() self.create_and_test_config_from_and_save_pretrained_subfolder() self.create_and_test_config_with_num_labels() self.check_config_can_be_init_without_params() self.check_config_arguments_init()
158
0
import argparse import os from pathlib import Path from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_params _SCREAMING_SNAKE_CASE : str = [ # replace left string with right string to get the relevant state_dict key (identical state dict to bart) ['''memory_attention''', '''encoder_attn'''], ['''attention''', '''attn'''], ['''/''', '''.'''], ['''.LayerNorm.gamma''', '''_layer_norm.weight'''], ['''.LayerNorm.beta''', '''_layer_norm.bias'''], ['''r.layer_''', '''r.layers.'''], ['''output_proj''', '''out_proj'''], ['''ffn.dense_1.''', '''fc2.'''], ['''ffn.dense.''', '''fc1.'''], ['''ffn_layer_norm''', '''final_layer_norm'''], ['''kernel''', '''weight'''], ['''encoder_layer_norm.''', '''encoder.layer_norm.'''], ['''decoder_layer_norm.''', '''decoder.layer_norm.'''], ['''embeddings.weights''', '''shared.weight'''], ] def UpperCAmelCase_ ( _A ): '''simple docstring''' for pegasus_name, hf_name in PATTERNS: SCREAMING_SNAKE_CASE__ = k.replace(_A , _A ) return k def UpperCAmelCase_ ( _A , _A ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = DEFAULTS.copy() cfg_kwargs.update(_A ) SCREAMING_SNAKE_CASE__ = PegasusConfig(**_A ) SCREAMING_SNAKE_CASE__ = PegasusForConditionalGeneration(_A ) SCREAMING_SNAKE_CASE__ = torch_model.model.state_dict() SCREAMING_SNAKE_CASE__ = {} for k, v in tf_weights.items(): SCREAMING_SNAKE_CASE__ = rename_state_dict_key(_A ) if new_k not in sd: raise ValueError(F'''could not find new key {new_k} in state dict. (converted from {k})''' ) if "dense" in k or "proj" in new_k: SCREAMING_SNAKE_CASE__ = v.T SCREAMING_SNAKE_CASE__ = torch.tensor(_A , dtype=sd[new_k].dtype ) assert v.shape == sd[new_k].shape, F'''{new_k}, {k}, {v.shape}, {sd[new_k].shape}''' # make sure embedding.padding_idx is respected SCREAMING_SNAKE_CASE__ = torch.zeros_like(mapping['''shared.weight'''][cfg.pad_token_id + 1] ) SCREAMING_SNAKE_CASE__ = mapping['''shared.weight'''] SCREAMING_SNAKE_CASE__ = mapping['''shared.weight'''] SCREAMING_SNAKE_CASE__ = {k: torch.zeros_like(_A ) for k, v in sd.items() if k.endswith('''bias''' ) and k not in mapping} mapping.update(**_A ) SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ = torch_model.model.load_state_dict(_A , strict=_A ) SCREAMING_SNAKE_CASE__ = [ k for k in missing if k not in ['''encoder.embed_positions.weight''', '''decoder.embed_positions.weight'''] ] assert unexpected_missing == [], F'''no matches found for the following torch keys {unexpected_missing}''' assert extra == [], F'''no matches found for the following tf keys {extra}''' return torch_model def UpperCAmelCase_ ( _A="./ckpt/aeslc/model.ckpt-32000" ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = tf.train.list_variables(_A ) SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = ['''Adafactor''', '''global_step'''] for name, shape in tqdm(_A , desc='''converting tf checkpoint to dict''' ): SCREAMING_SNAKE_CASE__ = any(pat in name for pat in ignore_name ) if skip_key: continue SCREAMING_SNAKE_CASE__ = tf.train.load_variable(_A , _A ) SCREAMING_SNAKE_CASE__ = array return tf_weights def UpperCAmelCase_ ( _A , _A ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = Path(_A ).parent.name SCREAMING_SNAKE_CASE__ = task_specific_params[F'''summarization_{dataset}''']['''max_position_embeddings'''] SCREAMING_SNAKE_CASE__ = PegasusTokenizer.from_pretrained('''sshleifer/pegasus''' , model_max_length=_A ) assert tok.model_max_length == desired_max_model_length tok.save_pretrained(_A ) # convert model SCREAMING_SNAKE_CASE__ = get_tf_weights_as_numpy(_A ) SCREAMING_SNAKE_CASE__ = task_specific_params[F'''summarization_{dataset}'''] if dataset == "large": SCREAMING_SNAKE_CASE__ = task_specific_params SCREAMING_SNAKE_CASE__ = convert_pegasus(_A , _A ) torch_model.save_pretrained(_A ) SCREAMING_SNAKE_CASE__ = torch_model.state_dict() sd.pop('''model.decoder.embed_positions.weight''' ) sd.pop('''model.encoder.embed_positions.weight''' ) torch.save(_A , Path(_A ) / '''pytorch_model.bin''' ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument('''tf_ckpt_path''', type=str, help='''passed to tf.train.list_variables''') parser.add_argument('''save_dir''', default=None, type=str, help='''Path to the output PyTorch model.''') _SCREAMING_SNAKE_CASE : Optional[Any] = parser.parse_args() if args.save_dir is None: _SCREAMING_SNAKE_CASE : Optional[Any] = Path(args.tf_ckpt_path).parent.name _SCREAMING_SNAKE_CASE : List[Any] = os.path.join('''pegasus''', dataset) convert_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir)
218
import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def UpperCAmelCase_ ( _A , _A ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = args.log_outputs SCREAMING_SNAKE_CASE__ = '''_'''.join(args.dataset.split('''/''' ) + [args.config, args.split] ) # load metric SCREAMING_SNAKE_CASE__ = load_metric('''wer''' ) SCREAMING_SNAKE_CASE__ = load_metric('''cer''' ) # compute metrics SCREAMING_SNAKE_CASE__ = wer.compute(references=result['''target'''] , predictions=result['''prediction'''] ) SCREAMING_SNAKE_CASE__ = cer.compute(references=result['''target'''] , predictions=result['''prediction'''] ) # print & log results SCREAMING_SNAKE_CASE__ = F'''WER: {wer_result}\nCER: {cer_result}''' print(_A ) with open(F'''{dataset_id}_eval_results.txt''' , '''w''' ) as f: f.write(_A ) # log all results in text file. Possibly interesting for analysis if log_outputs is not None: SCREAMING_SNAKE_CASE__ = F'''log_{dataset_id}_predictions.txt''' SCREAMING_SNAKE_CASE__ = F'''log_{dataset_id}_targets.txt''' with open(_A , '''w''' ) as p, open(_A , '''w''' ) as t: # mapping function to write output def write_to_file(_A , _A ): p.write(F'''{i}''' + '''\n''' ) p.write(batch['''prediction'''] + '''\n''' ) t.write(F'''{i}''' + '''\n''' ) t.write(batch['''target'''] + '''\n''' ) result.map(_A , with_indices=_A ) def UpperCAmelCase_ ( _A ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = '''[,?.!\-\;\:"“%‘”�—’…–]''' # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training SCREAMING_SNAKE_CASE__ = re.sub(_A , '''''' , text.lower() ) # In addition, we can normalize the target text, e.g. removing new lines characters etc... # note that order is important here! SCREAMING_SNAKE_CASE__ = ['''\n\n''', '''\n''', ''' ''', ''' '''] for t in token_sequences_to_ignore: SCREAMING_SNAKE_CASE__ = ''' '''.join(text.split(_A ) ) return text def UpperCAmelCase_ ( _A ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = load_dataset(args.dataset , args.config , split=args.split , use_auth_token=_A ) # for testing: only process the first two examples as a test # dataset = dataset.select(range(10)) # load processor SCREAMING_SNAKE_CASE__ = AutoFeatureExtractor.from_pretrained(args.model_id ) SCREAMING_SNAKE_CASE__ = feature_extractor.sampling_rate # resample audio SCREAMING_SNAKE_CASE__ = dataset.cast_column('''audio''' , Audio(sampling_rate=_A ) ) # load eval pipeline if args.device is None: SCREAMING_SNAKE_CASE__ = 0 if torch.cuda.is_available() else -1 SCREAMING_SNAKE_CASE__ = pipeline('''automatic-speech-recognition''' , model=args.model_id , device=args.device ) # map function to decode audio def map_to_pred(_A ): SCREAMING_SNAKE_CASE__ = asr( batch['''audio''']['''array'''] , chunk_length_s=args.chunk_length_s , stride_length_s=args.stride_length_s ) SCREAMING_SNAKE_CASE__ = prediction['''text'''] SCREAMING_SNAKE_CASE__ = normalize_text(batch['''sentence'''] ) return batch # run inference on all examples SCREAMING_SNAKE_CASE__ = dataset.map(_A , remove_columns=dataset.column_names ) # compute and log_results # do not change function below log_results(_A , _A ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE : List[str] = argparse.ArgumentParser() parser.add_argument( '''--model_id''', type=str, required=True, help='''Model identifier. Should be loadable with 🤗 Transformers''' ) parser.add_argument( '''--dataset''', type=str, required=True, help='''Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets''', ) parser.add_argument( '''--config''', type=str, required=True, help='''Config of the dataset. *E.g.* `\'en\'` for Common Voice''' ) parser.add_argument('''--split''', type=str, required=True, help='''Split of the dataset. *E.g.* `\'test\'`''') parser.add_argument( '''--chunk_length_s''', type=float, default=None, help='''Chunk length in seconds. Defaults to 5 seconds.''' ) parser.add_argument( '''--stride_length_s''', type=float, default=None, help='''Stride of the audio chunks. Defaults to 1 second.''' ) parser.add_argument( '''--log_outputs''', action='''store_true''', help='''If defined, write outputs to log file for analysis.''' ) parser.add_argument( '''--device''', type=int, default=None, help='''The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.''', ) _SCREAMING_SNAKE_CASE : List[Any] = parser.parse_args() main(args)
218
1
'''simple docstring''' import io import os import unicodedata from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = '''▁''' UpperCAmelCase = {'''vocab_file''': '''vocab.txt''', '''sentencepiece_model_ckpt''': '''sentencepiece.bpe.model'''} UpperCAmelCase = { '''sentencepiece_model_file''': '''sentencepiece.bpe.model''', '''vocab_file''': '''vocab.txt''', } UpperCAmelCase = { '''vocab_file''': { '''ernie-m-base''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt''', '''ernie-m-large''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt''', }, '''sentencepiece_model_file''': { '''ernie-m-base''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model''', '''ernie-m-large''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model''', }, } UpperCAmelCase = { '''ernie-m-base''': 514, '''ernie-m-large''': 514, } UpperCAmelCase = { '''ernie-m-base''': {'''do_lower_case''': False}, '''ernie-m-large''': {'''do_lower_case''': False}, } class lowerCAmelCase ( A ): lowerCAmelCase_ = ["input_ids"] lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_INIT_CONFIGURATION lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = RESOURCE_FILES_NAMES def __init__( self : Any , __lowercase : int , __lowercase : List[str]=None , __lowercase : str=False , __lowercase : Union[str, Any]="utf8" , __lowercase : Optional[int]="[UNK]" , __lowercase : int="[SEP]" , __lowercase : Dict="[PAD]" , __lowercase : Tuple="[CLS]" , __lowercase : str="[MASK]" , __lowercase : Optional[Dict[str, Any]] = None , **__lowercase : int , ): """simple docstring""" __lowercase ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=__lowercase , unk_token=__lowercase , sep_token=__lowercase , pad_token=__lowercase , cls_token=__lowercase , mask_token=__lowercase , vocab_file=__lowercase , encoding=__lowercase , sp_model_kwargs=self.sp_model_kwargs , **__lowercase , ) __lowercase =do_lower_case __lowercase =sentencepiece_model_ckpt __lowercase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__lowercase ) # to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning if vocab_file is not None: __lowercase =self.load_vocab(filepath=__lowercase ) else: __lowercase ={self.sp_model.id_to_piece(__lowercase ): id for id in range(self.sp_model.get_piece_size() )} __lowercase ={v: k for k, v in self.vocab.items()} def snake_case ( self : List[str] , __lowercase : str ): """simple docstring""" if text is None: return None __lowercase =self.tokenize(__lowercase ) __lowercase , __lowercase ='', [] for i, ch in enumerate(__lowercase ): if ch in self.SP_CHAR_MAPPING: __lowercase =self.SP_CHAR_MAPPING.get(__lowercase ) else: __lowercase =unicodedata.normalize('NFKC' , __lowercase ) if self.is_whitespace(__lowercase ): continue normalized_text += ch char_mapping.extend([i] * len(__lowercase ) ) __lowercase , __lowercase , __lowercase =normalized_text, [], 0 if self.do_lower_case: __lowercase =text.lower() for token in split_tokens: if token[:1] == "▁": __lowercase =token[1:] __lowercase =text[offset:].index(__lowercase ) + offset __lowercase =start + len(__lowercase ) token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1) ) __lowercase =end return token_mapping @property def snake_case ( self : int ): """simple docstring""" return len(self.vocab ) def snake_case ( self : List[Any] ): """simple docstring""" return dict(self.vocab , **self.added_tokens_encoder ) def __getstate__( self : Tuple ): """simple docstring""" __lowercase =self.__dict__.copy() __lowercase =None return state def __setstate__( self : List[Any] , __lowercase : Union[str, Any] ): """simple docstring""" __lowercase =d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __lowercase ={} __lowercase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.sentencepiece_model_ckpt ) def snake_case ( self : str , __lowercase : Dict ): """simple docstring""" return "".join((self.SP_CHAR_MAPPING.get(__lowercase , __lowercase ) for c in text) ) def snake_case ( self : Dict , __lowercase : Optional[Any] , __lowercase : str=False , __lowercase : Optional[int]=64 , __lowercase : Tuple=0.1 ): """simple docstring""" if self.sp_model_kwargs.get('enable_sampling' ) is True: __lowercase =True if self.sp_model_kwargs.get('alpha' ) is not None: __lowercase =self.sp_model_kwargs.get('alpha' ) if self.sp_model_kwargs.get('nbest_size' ) is not None: __lowercase =self.sp_model_kwargs.get('nbest_size' ) if not enable_sampling: __lowercase =self.sp_model.EncodeAsPieces(__lowercase ) else: __lowercase =self.sp_model.SampleEncodeAsPieces(__lowercase , __lowercase , __lowercase ) __lowercase =[] for pi, piece in enumerate(__lowercase ): if piece == SPIECE_UNDERLINE: if not pieces[pi + 1].startswith(__lowercase ) and pi != 0: new_pieces.append(__lowercase ) continue else: continue __lowercase =0 for i, chunk in enumerate(__lowercase ): if chunk == SPIECE_UNDERLINE: continue if self.is_ch_char(__lowercase ) or self.is_punct(__lowercase ): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) new_pieces.append(__lowercase ) __lowercase =i + 1 elif chunk.isdigit() and i > 0 and not piece[i - 1].isdigit(): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) __lowercase =i elif not chunk.isdigit() and i > 0 and piece[i - 1].isdigit(): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) __lowercase =i if len(__lowercase ) > lst_i: new_pieces.append(piece[lst_i:] ) return new_pieces def snake_case ( self : Optional[Any] , __lowercase : Dict ): """simple docstring""" __lowercase =''.join(__lowercase ).replace(__lowercase , ' ' ).strip() return out_string def snake_case ( self : List[Any] , __lowercase : Dict ): """simple docstring""" __lowercase =self.convert_ids_to_tokens(__lowercase ) __lowercase =''.join(__lowercase ).replace(__lowercase , ' ' ).strip() return out_string def snake_case ( self : Tuple , __lowercase : List[Any] ): """simple docstring""" return self.vocab.get(__lowercase , self.vocab.get(self.unk_token ) ) def snake_case ( self : int , __lowercase : Union[str, Any] ): """simple docstring""" return self.reverse_vocab.get(__lowercase , self.unk_token ) def snake_case ( self : Optional[Any] , __lowercase : Union[str, Any] , __lowercase : Union[str, Any]=None ): """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __lowercase =[self.cls_token_id] __lowercase =[self.sep_token_id] return _cls + token_ids_a + _sep + _sep + token_ids_a + _sep def snake_case ( self : Optional[int] , __lowercase : Tuple , __lowercase : Optional[Any]=None ): """simple docstring""" if offset_mapping_a is None: return [(0, 0)] + offset_mapping_a + [(0, 0)] return [(0, 0)] + offset_mapping_a + [(0, 0), (0, 0)] + offset_mapping_a + [(0, 0)] def snake_case ( self : int , __lowercase : int , __lowercase : Union[str, Any]=None , __lowercase : Union[str, Any]=False ): """simple docstring""" if already_has_special_tokens: if token_ids_a is not None: raise ValueError( 'You should not supply a second sequence if the provided sequence of ' 'ids is already formatted with special tokens for the model.' ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(__lowercase )) + [1, 1] + ([0] * len(__lowercase )) + [1] return [1] + ([0] * len(__lowercase )) + [1] def snake_case ( self : int , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ): """simple docstring""" if token_ids_a is None: # [CLS] X [SEP] return (len(__lowercase ) + 2) * [0] # [CLS] A [SEP] [SEP] B [SEP] return [0] * (len(__lowercase ) + 1) + [1] * (len(__lowercase ) + 3) def snake_case ( self : Union[str, Any] , __lowercase : Tuple ): """simple docstring""" if "\u4e00" <= char <= "\u9fff": return True return False def snake_case ( self : Optional[Any] , __lowercase : str ): """simple docstring""" if ("a" <= char <= "z") or ("A" <= char <= "Z"): return True return False def snake_case ( self : Any , __lowercase : List[Any] ): """simple docstring""" if char in ",;:.?!~,;:。?!《》【】": return True return False def snake_case ( self : Optional[Any] , __lowercase : int ): """simple docstring""" if char == " " or char == "\t" or char == "\n" or char == "\r": return True if len(__lowercase ) == 1: __lowercase =unicodedata.category(__lowercase ) if cat == "Zs": return True return False def snake_case ( self : Union[str, Any] , __lowercase : Any ): """simple docstring""" __lowercase ={} with io.open(__lowercase , 'r' , encoding='utf-8' ) as f: for index, line in enumerate(__lowercase ): __lowercase =line.rstrip('\n' ) __lowercase =int(__lowercase ) return token_to_idx def snake_case ( self : Dict , __lowercase : str , __lowercase : Optional[str] = None ): """simple docstring""" __lowercase =0 if os.path.isdir(__lowercase ): __lowercase =os.path.join( __lowercase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) else: __lowercase =(filename_prefix + '-' if filename_prefix else '') + save_directory with open(__lowercase , 'w' , encoding='utf-8' ) as writer: for token, token_index in sorted(self.vocab.items() , key=lambda __lowercase : kv[1] ): if index != token_index: logger.warning( f'''Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.''' ' Please check that the vocabulary is not corrupted!' ) __lowercase =token_index writer.write(token + '\n' ) index += 1 __lowercase =os.path.join(__lowercase , 'sentencepiece.bpe.model' ) with open(__lowercase , 'wb' ) as fi: __lowercase =self.sp_model.serialized_model_proto() fi.write(__lowercase ) return (vocab_file,)
141
'''simple docstring''' import unittest from transformers import AutoConfig, AutoTokenizer, BertConfig, TensorType, is_flax_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, slow if is_flax_available(): import jax from transformers.models.auto.modeling_flax_auto import FlaxAutoModel from transformers.models.bert.modeling_flax_bert import FlaxBertModel from transformers.models.roberta.modeling_flax_roberta import FlaxRobertaModel @require_flax class lowerCAmelCase ( unittest.TestCase ): @slow def snake_case ( self : Optional[int] ): """simple docstring""" for model_name in ["bert-base-cased", "bert-large-uncased"]: with self.subTest(__lowercase ): __lowercase =AutoConfig.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) __lowercase =FlaxAutoModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) @slow def snake_case ( self : Optional[Any] ): """simple docstring""" for model_name in ["roberta-base", "roberta-large"]: with self.subTest(__lowercase ): __lowercase =AutoConfig.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) __lowercase =FlaxAutoModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) self.assertIsInstance(__lowercase , __lowercase ) @slow def snake_case ( self : Optional[int] ): """simple docstring""" for model_name in ["bert-base-cased", "bert-large-uncased"]: __lowercase =AutoTokenizer.from_pretrained(__lowercase ) __lowercase =FlaxBertModel.from_pretrained(__lowercase ) __lowercase =tokenizer('Do you support jax jitted function?' , return_tensors=TensorType.JAX ) @jax.jit def eval(**__lowercase : Optional[Any] ): return model(**__lowercase ) eval(**__lowercase ).block_until_ready() @slow def snake_case ( self : List[Any] ): """simple docstring""" for model_name in ["roberta-base", "roberta-large"]: __lowercase =AutoTokenizer.from_pretrained(__lowercase ) __lowercase =FlaxRobertaModel.from_pretrained(__lowercase ) __lowercase =tokenizer('Do you support jax jitted function?' , return_tensors=TensorType.JAX ) @jax.jit def eval(**__lowercase : Dict ): return model(**__lowercase ) eval(**__lowercase ).block_until_ready() def snake_case ( self : Any ): """simple docstring""" with self.assertRaisesRegex( __lowercase , 'bert-base is not a local folder and is not a valid model identifier' ): __lowercase =FlaxAutoModel.from_pretrained('bert-base' ) def snake_case ( self : Optional[Any] ): """simple docstring""" with self.assertRaisesRegex( __lowercase , r'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)' ): __lowercase =FlaxAutoModel.from_pretrained(__lowercase , revision='aaaaaa' ) def snake_case ( self : Optional[Any] ): """simple docstring""" with self.assertRaisesRegex( __lowercase , 'hf-internal-testing/config-no-model does not appear to have a file named flax_model.msgpack' , ): __lowercase =FlaxAutoModel.from_pretrained('hf-internal-testing/config-no-model' ) def snake_case ( self : Any ): """simple docstring""" with self.assertRaisesRegex(__lowercase , 'Use `from_pt=True` to load this model' ): __lowercase =FlaxAutoModel.from_pretrained('hf-internal-testing/tiny-bert-pt-only' )
141
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) __magic_name__ = { "configuration_deberta": ["DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP", "DebertaConfig", "DebertaOnnxConfig"], "tokenization_deberta": ["DebertaTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ["DebertaTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ "DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "DebertaForMaskedLM", "DebertaForQuestionAnswering", "DebertaForSequenceClassification", "DebertaForTokenClassification", "DebertaModel", "DebertaPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ "TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "TFDebertaForMaskedLM", "TFDebertaForQuestionAnswering", "TFDebertaForSequenceClassification", "TFDebertaForTokenClassification", "TFDebertaModel", "TFDebertaPreTrainedModel", ] if TYPE_CHECKING: from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig from .tokenization_deberta import DebertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_deberta_fast import DebertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deberta import ( DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, DebertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deberta import ( TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFDebertaForMaskedLM, TFDebertaForQuestionAnswering, TFDebertaForSequenceClassification, TFDebertaForTokenClassification, TFDebertaModel, TFDebertaPreTrainedModel, ) else: import sys __magic_name__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
367
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast 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 __magic_name__ = get_tests_dir("fixtures/test_sentencepiece_no_bos.model") @require_sentencepiece @require_tokenizers class lowercase ( A__ , unittest.TestCase ): '''simple docstring''' __SCREAMING_SNAKE_CASE = PegasusTokenizer __SCREAMING_SNAKE_CASE = PegasusTokenizerFast __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True def snake_case_ ( self ) -> Optional[Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing UpperCAmelCase = PegasusTokenizer(_snake_case ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def snake_case_ ( self ) -> Dict: """simple docstring""" return PegasusTokenizer.from_pretrained('''google/pegasus-large''' ) def snake_case_ ( self , **_snake_case ) -> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **_snake_case ) def snake_case_ ( self , _snake_case ) -> Any: """simple docstring""" return ("This is a test", "This is a test") def snake_case_ ( self ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase = '''</s>''' UpperCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_snake_case ) , _snake_case ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_snake_case ) , _snake_case ) def snake_case_ ( self ) -> str: """simple docstring""" UpperCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<pad>''' ) self.assertEqual(vocab_keys[1] , '''</s>''' ) self.assertEqual(vocab_keys[-1] , '''v''' ) self.assertEqual(len(_snake_case ) , 1103 ) def snake_case_ ( self ) -> Union[str, Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def snake_case_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) UpperCAmelCase = self.tokenizer_class.from_pretrained(self.tmpdirname ) UpperCAmelCase = ( '''Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important''' ''' </s> <pad> <pad> <pad>''' ) UpperCAmelCase = rust_tokenizer([raw_input_str] , return_tensors=_snake_case , add_special_tokens=_snake_case ).input_ids[0] UpperCAmelCase = py_tokenizer([raw_input_str] , return_tensors=_snake_case , add_special_tokens=_snake_case ).input_ids[0] self.assertListEqual(_snake_case , _snake_case ) def snake_case_ ( self ) -> Tuple: """simple docstring""" UpperCAmelCase = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word UpperCAmelCase = '''<mask_1> To ensure a <mask_2> flow of bank resolutions.''' UpperCAmelCase = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] UpperCAmelCase = tokenizer([raw_input_str] , return_tensors=_snake_case ).input_ids[0] self.assertListEqual(_snake_case , _snake_case ) def snake_case_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 UpperCAmelCase = '''To ensure a smooth flow of bank resolutions.''' UpperCAmelCase = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] UpperCAmelCase = tokenizer([raw_input_str] , return_tensors=_snake_case ).input_ids[0] self.assertListEqual(_snake_case , _snake_case ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def snake_case_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase = ['''This is going to be way too long.''' * 150, '''short example'''] UpperCAmelCase = ['''not super long but more than 5 tokens''', '''tiny'''] UpperCAmelCase = self._large_tokenizer(_snake_case , padding=_snake_case , truncation=_snake_case , return_tensors='''pt''' ) UpperCAmelCase = self._large_tokenizer( text_target=_snake_case , max_length=5 , padding=_snake_case , truncation=_snake_case , return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(_snake_case ) == 2 # input_ids, attention_mask. @slow def snake_case_ ( self ) -> List[str]: """simple docstring""" # fmt: off UpperCAmelCase = {'''input_ids''': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 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], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 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]], '''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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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=_snake_case , model_name='''google/bigbird-pegasus-large-arxiv''' , revision='''ba85d0851d708441f91440d509690f1ab6353415''' , ) @require_sentencepiece @require_tokenizers class lowercase ( A__ , unittest.TestCase ): '''simple docstring''' __SCREAMING_SNAKE_CASE = PegasusTokenizer __SCREAMING_SNAKE_CASE = PegasusTokenizerFast __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True def snake_case_ ( self ) -> int: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing UpperCAmelCase = PegasusTokenizer(_snake_case , offset=0 , mask_token_sent=_snake_case , mask_token='''[MASK]''' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def snake_case_ ( self ) -> Dict: """simple docstring""" return PegasusTokenizer.from_pretrained('''google/bigbird-pegasus-large-arxiv''' ) def snake_case_ ( self , **_snake_case ) -> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **_snake_case ) def snake_case_ ( self , _snake_case ) -> List[str]: """simple docstring""" return ("This is a test", "This is a test") def snake_case_ ( self ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) UpperCAmelCase = self.tokenizer_class.from_pretrained(self.tmpdirname ) UpperCAmelCase = ( '''Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>''' ''' <pad> <pad> <pad>''' ) UpperCAmelCase = rust_tokenizer([raw_input_str] , return_tensors=_snake_case , add_special_tokens=_snake_case ).input_ids[0] UpperCAmelCase = py_tokenizer([raw_input_str] , return_tensors=_snake_case , add_special_tokens=_snake_case ).input_ids[0] self.assertListEqual(_snake_case , _snake_case ) @require_torch def snake_case_ ( self ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = ['''This is going to be way too long.''' * 1000, '''short example'''] UpperCAmelCase = ['''not super long but more than 5 tokens''', '''tiny'''] UpperCAmelCase = self._large_tokenizer(_snake_case , padding=_snake_case , truncation=_snake_case , return_tensors='''pt''' ) UpperCAmelCase = self._large_tokenizer( text_target=_snake_case , max_length=5 , padding=_snake_case , truncation=_snake_case , return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(_snake_case ) == 2 # input_ids, attention_mask. def snake_case_ ( self ) -> Any: """simple docstring""" UpperCAmelCase = ( '''This is an example string that is used to test the original TF implementation against the HF''' ''' implementation''' ) UpperCAmelCase = self._large_tokenizer(_snake_case ).input_ids self.assertListEqual( _snake_case , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
152
0
import logging from transformers.configuration_utils import PretrainedConfig lowercase : Union[str, Any] = logging.getLogger(__name__) class A__ ( __UpperCAmelCase ): """simple docstring""" __A : int = '''masked_bert''' def __init__( self , lowercase=3_0522 , lowercase=768 , lowercase=12 , lowercase=12 , lowercase=3072 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=512 , lowercase=2 , lowercase=0.02 , lowercase=1e-12 , lowercase=0 , lowercase="topK" , lowercase="constant" , lowercase=0.0 , **lowercase , ) -> Optional[Any]: '''simple docstring''' super().__init__(pad_token_id=lowercase , **lowercase) a__ : Optional[Any] = vocab_size a__ : Union[str, Any] = hidden_size a__ : Optional[int] = num_hidden_layers a__ : List[Any] = num_attention_heads a__ : Optional[Any] = hidden_act a__ : List[Any] = intermediate_size a__ : Optional[int] = hidden_dropout_prob a__ : List[Any] = attention_probs_dropout_prob a__ : Optional[int] = max_position_embeddings a__ : Optional[int] = type_vocab_size a__ : List[Any] = initializer_range a__ : List[str] = layer_norm_eps a__ : Optional[int] = pruning_method a__ : int = mask_init a__ : List[str] = mask_scale
99
"""simple docstring""" def A ( snake_case__ = 10_00 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 1, 1 SCREAMING_SNAKE_CASE__ = 2 while True: SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = fa + fa SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = fa, f index += 1 for _ in str(snake_case__ ): i += 1 if i == n: break return index if __name__ == "__main__": print(solution(int(str(input()).strip())))
165
0
"""simple docstring""" def lowercase ( a__ : int , a__ : int ) -> int: while b: _UpperCamelCase , _UpperCamelCase = b, a % b return a def lowercase ( a__ : int , a__ : int ) -> int: return a if b == 0 else euclidean_gcd_recursive(a__ , a % b ) def lowercase ( ) -> Optional[int]: print(F'''euclidean_gcd(3, 5) = {euclidean_gcd(3 , 5 )}''' ) print(F'''euclidean_gcd(5, 3) = {euclidean_gcd(5 , 3 )}''' ) print(F'''euclidean_gcd(1, 3) = {euclidean_gcd(1 , 3 )}''' ) print(F'''euclidean_gcd(3, 6) = {euclidean_gcd(3 , 6 )}''' ) print(F'''euclidean_gcd(6, 3) = {euclidean_gcd(6 , 3 )}''' ) print(F'''euclidean_gcd_recursive(3, 5) = {euclidean_gcd_recursive(3 , 5 )}''' ) print(F'''euclidean_gcd_recursive(5, 3) = {euclidean_gcd_recursive(5 , 3 )}''' ) print(F'''euclidean_gcd_recursive(1, 3) = {euclidean_gcd_recursive(1 , 3 )}''' ) print(F'''euclidean_gcd_recursive(3, 6) = {euclidean_gcd_recursive(3 , 6 )}''' ) print(F'''euclidean_gcd_recursive(6, 3) = {euclidean_gcd_recursive(6 , 3 )}''' ) if __name__ == "__main__": main()
54
"""simple docstring""" from __future__ import annotations from PIL import Image # Define glider example UpperCAmelCase = [ [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [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], ] # Define blinker example UpperCAmelCase = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] def lowercase ( a__ : list[list[int]] ) -> list[list[int]]: _UpperCamelCase = [] for i in range(len(a__ ) ): _UpperCamelCase = [] for j in range(len(cells[i] ) ): # Get the number of live neighbours _UpperCamelCase = 0 if i > 0 and j > 0: neighbour_count += cells[i - 1][j - 1] if i > 0: neighbour_count += cells[i - 1][j] if i > 0 and j < len(cells[i] ) - 1: neighbour_count += cells[i - 1][j + 1] if j > 0: neighbour_count += cells[i][j - 1] if j < len(cells[i] ) - 1: neighbour_count += cells[i][j + 1] if i < len(a__ ) - 1 and j > 0: neighbour_count += cells[i + 1][j - 1] if i < len(a__ ) - 1: neighbour_count += cells[i + 1][j] if i < len(a__ ) - 1 and j < len(cells[i] ) - 1: neighbour_count += cells[i + 1][j + 1] # Rules of the game of life (excerpt from Wikipedia): # 1. Any live cell with two or three live neighbours survives. # 2. Any dead cell with three live neighbours becomes a live cell. # 3. All other live cells die in the next generation. # Similarly, all other dead cells stay dead. _UpperCamelCase = cells[i][j] == 1 if ( (alive and 2 <= neighbour_count <= 3) or not alive and neighbour_count == 3 ): next_generation_row.append(1 ) else: next_generation_row.append(0 ) next_generation.append(a__ ) return next_generation def lowercase ( a__ : list[list[int]] , a__ : int ) -> list[Image.Image]: _UpperCamelCase = [] for _ in range(a__ ): # Create output image _UpperCamelCase = Image.new('''RGB''' , (len(cells[0] ), len(a__ )) ) _UpperCamelCase = img.load() # Save cells to image for x in range(len(a__ ) ): for y in range(len(cells[0] ) ): _UpperCamelCase = 255 - cells[y][x] * 255 _UpperCamelCase = (colour, colour, colour) # Save image images.append(a__ ) _UpperCamelCase = new_generation(a__ ) return images if __name__ == "__main__": UpperCAmelCase = generate_images(GLIDER, 16) images[0].save("""out.gif""", save_all=True, append_images=images[1:])
54
1
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCamelCase : Any = logging.get_logger(__name__) lowerCamelCase : int = '''▁''' lowerCamelCase : Tuple = {'''vocab_file''': '''spiece.model'''} lowerCamelCase : Optional[int] = { '''vocab_file''': { '''google/reformer-crime-and-punishment''': ( '''https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model''' ) } } lowerCamelCase : int = { '''google/reformer-crime-and-punishment''': 52_42_88, } class lowerCAmelCase ( __a ): '''simple docstring''' _A : Tuple = VOCAB_FILES_NAMES _A : List[str] = PRETRAINED_VOCAB_FILES_MAP _A : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A : str = ['''input_ids''', '''attention_mask'''] def __init__( self : Any , __a : List[Any] , __a : Optional[int]="</s>" , __a : List[Any]="<unk>" , __a : Dict=[] , __a : Optional[Dict[str, Any]] = None , **__a : List[Any] , ) -> None: """simple docstring""" __lowercase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=__a , unk_token=__a , additional_special_tokens=__a , sp_model_kwargs=self.sp_model_kwargs , **__a , ) __lowercase : Optional[int] = vocab_file __lowercase : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__a ) @property def lowerCAmelCase ( self : Dict ) -> str: """simple docstring""" return self.sp_model.get_piece_size() def lowerCAmelCase ( self : str ) -> Dict[str, int]: """simple docstring""" __lowercase : Dict = {self.convert_ids_to_tokens(__a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Dict ) -> Optional[Any]: """simple docstring""" __lowercase : int = self.__dict__.copy() __lowercase : Optional[int] = None return state def __setstate__( self : List[Any] , __a : int ) -> Optional[int]: """simple docstring""" __lowercase : Dict = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): __lowercase : List[Any] = {} __lowercase : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCAmelCase ( self : Union[str, Any] , __a : str ) -> List[str]: """simple docstring""" return self.sp_model.encode(__a , out_type=__a ) def lowerCAmelCase ( self : Optional[int] , __a : List[Any] ) -> Union[str, Any]: """simple docstring""" return self.sp_model.piece_to_id(__a ) def lowerCAmelCase ( self : Optional[int] , __a : Dict ) -> List[Any]: """simple docstring""" if index < self.sp_model.get_piece_size(): __lowercase : Optional[Any] = self.sp_model.IdToPiece(__a ) return token def lowerCAmelCase ( self : Optional[int] , __a : Tuple ) -> int: """simple docstring""" __lowercase : Tuple = [] __lowercase : Optional[int] = """""" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(__a ) + token __lowercase : Any = [] else: current_sub_tokens.append(__a ) out_string += self.sp_model.decode(__a ) return out_string.strip() def lowerCAmelCase ( self : Union[str, Any] , __a : str , __a : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(__a ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return __lowercase : Optional[int] = os.path.join( __a , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __a ) elif not os.path.isfile(self.vocab_file ): with open(__a , """wb""" ) as fi: __lowercase : str = self.sp_model.serialized_model_proto() fi.write(__a ) return (out_vocab_file,)
233
lowerCamelCase : Dict = '''0.21.0''' from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
233
1
from __future__ import annotations import collections import pprint from pathlib import Path def __lowercase ( _UpperCamelCase ) ->str: """simple docstring""" return "".join(sorted(_UpperCamelCase ) ) def __lowercase ( _UpperCamelCase ) ->list[str]: """simple docstring""" return word_by_signature[signature(_UpperCamelCase )] __a = Path(__file__).parent.joinpath('''words.txt''').read_text(encoding='''utf-8''') __a = sorted({word.strip().lower() for word in data.splitlines()}) __a = collections.defaultdict(list) for word in word_list: word_by_signature[signature(word)].append(word) if __name__ == "__main__": __a = {word: anagram(word) for word in word_list if len(anagram(word)) > 1} with open('''anagrams.txt''', '''w''') as file: file.write('''all_anagrams = \n ''') file.write(pprint.pformat(all_anagrams))
173
import os import shutil import sys import tempfile import unittest from pathlib import Path import pytest import transformers from transformers import ( BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoTokenizer, BertConfig, BertTokenizer, BertTokenizerFast, CTRLTokenizer, GPTaTokenizer, GPTaTokenizerFast, PreTrainedTokenizerFast, RobertaTokenizer, RobertaTokenizerFast, is_tokenizers_available, ) from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig from transformers.models.auto.tokenization_auto import ( TOKENIZER_MAPPING, get_tokenizer_config, tokenizer_class_from_name, ) from transformers.models.roberta.configuration_roberta import RobertaConfig from transformers.testing_utils import ( DUMMY_DIFF_TOKENIZER_IDENTIFIER, DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tokenizers, slow, ) sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __lowerCamelCase ( self ): lowercase : int = 0 @slow def __lowerCamelCase ( self ): for model_name in (x for x in BERT_PRETRAINED_CONFIG_ARCHIVE_MAP.keys() if "japanese" not in x): lowercase : Optional[Any] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , (BertTokenizer, BertTokenizerFast) ) self.assertGreater(len(SCREAMING_SNAKE_CASE__ ) , 0 ) for model_name in GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP.keys(): lowercase : str = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , (GPTaTokenizer, GPTaTokenizerFast) ) self.assertGreater(len(SCREAMING_SNAKE_CASE__ ) , 0 ) def __lowerCamelCase ( self ): lowercase : Tuple = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 12 ) def __lowerCamelCase ( self ): lowercase : Any = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , (RobertaTokenizer, RobertaTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 20 ) def __lowerCamelCase ( self ): lowercase : Union[str, Any] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Check that tokenizer_type ≠ model_type lowercase : Optional[int] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , config=SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 12 ) def __lowerCamelCase ( self ): with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy('''./tests/fixtures/vocab.txt''' , os.path.join(SCREAMING_SNAKE_CASE__ , '''vocab.txt''' ) ) lowercase : Tuple = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , tokenizer_type='''bert''' , use_fast=SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy('''./tests/fixtures/vocab.json''' , os.path.join(SCREAMING_SNAKE_CASE__ , '''vocab.json''' ) ) shutil.copy('''./tests/fixtures/merges.txt''' , os.path.join(SCREAMING_SNAKE_CASE__ , '''merges.txt''' ) ) lowercase : Any = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , tokenizer_type='''gpt2''' , use_fast=SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @require_tokenizers def __lowerCamelCase ( self ): with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy('''./tests/fixtures/vocab.txt''' , os.path.join(SCREAMING_SNAKE_CASE__ , '''vocab.txt''' ) ) lowercase : Dict = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , tokenizer_type='''bert''' ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy('''./tests/fixtures/vocab.json''' , os.path.join(SCREAMING_SNAKE_CASE__ , '''vocab.json''' ) ) shutil.copy('''./tests/fixtures/merges.txt''' , os.path.join(SCREAMING_SNAKE_CASE__ , '''merges.txt''' ) ) lowercase : int = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , tokenizer_type='''gpt2''' ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCamelCase ( self ): with pytest.raises(SCREAMING_SNAKE_CASE__ ): AutoTokenizer.from_pretrained('''./''' , tokenizer_type='''xxx''' ) @require_tokenizers def __lowerCamelCase ( self ): for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: lowercase : Union[str, Any] = tokenizer_class.from_pretrained('''wietsedv/bert-base-dutch-cased''' ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , (BertTokenizer, BertTokenizerFast) ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(tokenizer.basic_tokenizer.do_lower_case , SCREAMING_SNAKE_CASE__ ) else: self.assertEqual(tokenizer.do_lower_case , SCREAMING_SNAKE_CASE__ ) self.assertEqual(tokenizer.model_max_length , 512 ) @require_tokenizers def __lowerCamelCase ( self ): for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: with self.assertRaisesRegex( SCREAMING_SNAKE_CASE__ , '''julien-c/herlolip-not-exists is not a local folder and is not a valid model identifier''' , ): lowercase : str = tokenizer_class.from_pretrained('''julien-c/herlolip-not-exists''' ) def __lowerCamelCase ( self ): # tests: https://github.com/huggingface/transformers/pull/13251 # 1. models with `-`, e.g. xlm-roberta -> xlm_roberta # 2. models that don't remap 1-1 from model-name to model file, e.g., openai-gpt -> openai lowercase : Any = TOKENIZER_MAPPING.values() lowercase : Tuple = [] for slow_tok, fast_tok in tokenizers: if slow_tok is not None: tokenizer_names.append(slow_tok.__name__ ) if fast_tok is not None: tokenizer_names.append(fast_tok.__name__ ) for tokenizer_name in tokenizer_names: # must find the right class tokenizer_class_from_name(SCREAMING_SNAKE_CASE__ ) @require_tokenizers def __lowerCamelCase ( self ): self.assertIsInstance(AutoTokenizer.from_pretrained('''bert-base-cased''' , use_fast=SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(AutoTokenizer.from_pretrained('''bert-base-cased''' ) , SCREAMING_SNAKE_CASE__ ) @require_tokenizers def __lowerCamelCase ( self ): lowercase : Optional[Any] = AutoTokenizer.from_pretrained('''distilbert-base-uncased''' , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowercase : List[Any] = '''Hello, world. How are you?''' lowercase : Any = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertEqual('''[UNK]''' , tokens[0] ) lowercase : Optional[Any] = AutoTokenizer.from_pretrained('''microsoft/mpnet-base''' , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowercase : List[str] = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertEqual('''[UNK]''' , tokens[0] ) @require_tokenizers def __lowerCamelCase ( self ): lowercase : int = AutoTokenizer.from_pretrained('''robot-test/dummy-tokenizer-fast-with-model-config''' ) self.assertEqual(type(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(tokenizer.model_max_length , 512 ) self.assertEqual(tokenizer.vocab_size , 30000 ) self.assertEqual(tokenizer.unk_token , '''[UNK]''' ) self.assertEqual(tokenizer.padding_side , '''right''' ) self.assertEqual(tokenizer.truncation_side , '''right''' ) def __lowerCamelCase ( self ): lowercase : Tuple = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , (BertTokenizer, BertTokenizerFast) ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) lowercase : Any = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , tokenizer.__class__ ) self.assertEqual(tokenizera.vocab_size , 12 ) def __lowerCamelCase ( self ): lowercase : Union[str, Any] = AutoTokenizer.from_pretrained('''ctrl''' ) # There is no fast CTRL so this always gives us a slow tokenizer. self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCamelCase ( self ): # Check we can load the tokenizer config of an online model. lowercase : Optional[Any] = get_tokenizer_config('''bert-base-cased''' ) lowercase : str = config.pop('''_commit_hash''' , SCREAMING_SNAKE_CASE__ ) # If we ever update bert-base-cased tokenizer config, this dict here will need to be updated. self.assertEqual(SCREAMING_SNAKE_CASE__ , {'''do_lower_case''': False} ) # This model does not have a tokenizer_config so we get back an empty dict. lowercase : Union[str, Any] = get_tokenizer_config(SCREAMING_SNAKE_CASE__ ) self.assertDictEqual(SCREAMING_SNAKE_CASE__ , {} ) # A tokenizer saved with `save_pretrained` always creates a tokenizer config. lowercase : str = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) lowercase : Tuple = get_tokenizer_config(SCREAMING_SNAKE_CASE__ ) # Check the class of the tokenizer was properly saved (note that it always saves the slow class). self.assertEqual(config['''tokenizer_class'''] , '''BertTokenizer''' ) def __lowerCamelCase ( self ): try: AutoConfig.register('''custom''' , SCREAMING_SNAKE_CASE__ ) AutoTokenizer.register(SCREAMING_SNAKE_CASE__ , slow_tokenizer_class=SCREAMING_SNAKE_CASE__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(SCREAMING_SNAKE_CASE__ ): AutoTokenizer.register(SCREAMING_SNAKE_CASE__ , slow_tokenizer_class=SCREAMING_SNAKE_CASE__ ) lowercase : int = CustomTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) lowercase : str = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] @require_tokenizers def __lowerCamelCase ( self ): try: AutoConfig.register('''custom''' , SCREAMING_SNAKE_CASE__ ) # Can register in two steps AutoTokenizer.register(SCREAMING_SNAKE_CASE__ , slow_tokenizer_class=SCREAMING_SNAKE_CASE__ ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, None) ) AutoTokenizer.register(SCREAMING_SNAKE_CASE__ , fast_tokenizer_class=SCREAMING_SNAKE_CASE__ ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) ) del TOKENIZER_MAPPING._extra_content[CustomConfig] # Can register in one step AutoTokenizer.register( SCREAMING_SNAKE_CASE__ , slow_tokenizer_class=SCREAMING_SNAKE_CASE__ , fast_tokenizer_class=SCREAMING_SNAKE_CASE__ ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(SCREAMING_SNAKE_CASE__ ): AutoTokenizer.register(SCREAMING_SNAKE_CASE__ , fast_tokenizer_class=SCREAMING_SNAKE_CASE__ ) # We pass through a bert tokenizer fast cause there is no converter slow to fast for our new toknizer # and that model does not have a tokenizer.json with tempfile.TemporaryDirectory() as tmp_dir: lowercase : Union[str, Any] = BertTokenizerFast.from_pretrained(SCREAMING_SNAKE_CASE__ ) bert_tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) lowercase : List[Any] = CustomTokenizerFast.from_pretrained(SCREAMING_SNAKE_CASE__ ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) lowercase : Tuple = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowercase : Optional[int] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , use_fast=SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] def __lowerCamelCase ( self ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(SCREAMING_SNAKE_CASE__ ): lowercase : List[Any] = AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(SCREAMING_SNAKE_CASE__ ): lowercase : str = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=SCREAMING_SNAKE_CASE__ ) lowercase : Dict = AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=SCREAMING_SNAKE_CASE__ ) self.assertTrue(tokenizer.special_attribute_present ) # Test tokenizer can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) lowercase : List[str] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , trust_remote_code=SCREAMING_SNAKE_CASE__ ) self.assertTrue(reloaded_tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) # Test we can also load the slow version lowercase : int = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=SCREAMING_SNAKE_CASE__ , use_fast=SCREAMING_SNAKE_CASE__ ) self.assertTrue(tokenizer.special_attribute_present ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) # Test tokenizer can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) lowercase : Tuple = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , trust_remote_code=SCREAMING_SNAKE_CASE__ , use_fast=SCREAMING_SNAKE_CASE__ ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , '''NewTokenizer''' ) self.assertTrue(reloaded_tokenizer.special_attribute_present ) else: self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , '''NewTokenizer''' ) @require_tokenizers def __lowerCamelCase ( self ): class __SCREAMING_SNAKE_CASE ( A__ ): A : str = False class __SCREAMING_SNAKE_CASE ( A__ ): A : Dict = NewTokenizer A : Optional[int] = False try: AutoConfig.register('''custom''' , SCREAMING_SNAKE_CASE__ ) AutoTokenizer.register(SCREAMING_SNAKE_CASE__ , slow_tokenizer_class=SCREAMING_SNAKE_CASE__ ) AutoTokenizer.register(SCREAMING_SNAKE_CASE__ , fast_tokenizer_class=SCREAMING_SNAKE_CASE__ ) # If remote code is not set, the default is to use local lowercase : Union[str, Any] = AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer''' ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) self.assertFalse(tokenizer.special_attribute_present ) lowercase : Union[str, Any] = AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer''' , use_fast=SCREAMING_SNAKE_CASE__ ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) self.assertFalse(tokenizer.special_attribute_present ) # If remote code is disabled, we load the local one. lowercase : Tuple = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=SCREAMING_SNAKE_CASE__ ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) self.assertFalse(tokenizer.special_attribute_present ) lowercase : List[str] = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=SCREAMING_SNAKE_CASE__ , use_fast=SCREAMING_SNAKE_CASE__ ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) self.assertFalse(tokenizer.special_attribute_present ) # If remote is enabled, we load from the Hub lowercase : Any = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=SCREAMING_SNAKE_CASE__ ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) self.assertTrue(tokenizer.special_attribute_present ) lowercase : List[Any] = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=SCREAMING_SNAKE_CASE__ , use_fast=SCREAMING_SNAKE_CASE__ ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) self.assertTrue(tokenizer.special_attribute_present ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] def __lowerCamelCase ( self ): lowercase : Dict = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer_legacy''' , trust_remote_code=SCREAMING_SNAKE_CASE__ ) self.assertTrue(tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) # Test we can also load the slow version lowercase : int = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer_legacy''' , trust_remote_code=SCREAMING_SNAKE_CASE__ , use_fast=SCREAMING_SNAKE_CASE__ ) self.assertTrue(tokenizer.special_attribute_present ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) else: self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) def __lowerCamelCase ( self ): with self.assertRaisesRegex( SCREAMING_SNAKE_CASE__ , '''bert-base is not a local folder and is not a valid model identifier''' ): lowercase : List[Any] = AutoTokenizer.from_pretrained('''bert-base''' ) def __lowerCamelCase ( self ): with self.assertRaisesRegex( SCREAMING_SNAKE_CASE__ , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): lowercase : Optional[int] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , revision='''aaaaaa''' ) def __lowerCamelCase ( self ): # Make sure we have cached the tokenizer. lowercase : Optional[Any] = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) with RequestCounter() as counter: lowercase : List[Any] = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 )
173
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __a = { 'configuration_git': ['GIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GitConfig', 'GitVisionConfig'], 'processing_git': ['GitProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a = [ 'GIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'GitForCausalLM', 'GitModel', 'GitPreTrainedModel', 'GitVisionModel', ] if TYPE_CHECKING: from .configuration_git import GIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GitConfig, GitVisionConfig from .processing_git import GitProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_git import ( GIT_PRETRAINED_MODEL_ARCHIVE_LIST, GitForCausalLM, GitModel, GitPreTrainedModel, GitVisionModel, ) else: import sys __a = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
30
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 a ( snake_case__: int , snake_case__: Tuple , snake_case__: Dict , snake_case__: Dict , snake_case__: List[Any] , snake_case__: int , snake_case__: List[Any] , snake_case__: Optional[int] , snake_case__: str , snake_case__: Union[str, Any] , snake_case__: List[str] , snake_case__: int , ): '''simple docstring''' lowercase_ = { '''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_ = input_paths_and_base_extractors[compression_format] if input_path is None: lowercase_ = 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(snake_case__ ) assert base_extractor.is_extractable(snake_case__ ) lowercase_ = tmp_path / ('''extracted''' if is_archive else '''extracted.txt''') base_extractor.extract(snake_case__ , 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_ = file_path.read_text(encoding='''utf-8''' ) else: lowercase_ = output_path.read_text(encoding='''utf-8''' ) lowercase_ = 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 a ( snake_case__: List[Any] , snake_case__: int , snake_case__: Optional[int] , snake_case__: Union[str, Any] , snake_case__: List[Any] , snake_case__: Tuple , snake_case__: Optional[int] , snake_case__: List[str] , snake_case__: Union[str, Any] , snake_case__: Tuple , snake_case__: int , snake_case__: Optional[int] , ): '''simple docstring''' lowercase_ = { '''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_ = input_paths[compression_format] if input_path is None: lowercase_ = 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(snake_case__ ) lowercase_ = Extractor.infer_extractor_format(snake_case__ ) assert extractor_format is not None lowercase_ = tmp_path / ('''extracted''' if is_archive else '''extracted.txt''') Extractor.extract(snake_case__ , snake_case__ , 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_ = file_path.read_text(encoding='''utf-8''' ) else: lowercase_ = output_path.read_text(encoding='''utf-8''' ) lowercase_ = text_file.read_text(encoding='''utf-8''' ) assert extracted_file_content == expected_file_content @pytest.fixture def a ( snake_case__: Union[str, Any] , snake_case__: List[Any] ): '''simple docstring''' import tarfile lowercase_ = tmp_path / '''data_dot_dot''' directory.mkdir() lowercase_ = directory / '''tar_file_with_dot_dot.tar''' with tarfile.TarFile(snake_case__ , '''w''' ) as f: f.add(snake_case__ , arcname=os.path.join('''..''' , text_file.name ) ) return path @pytest.fixture def a ( snake_case__: int ): '''simple docstring''' import tarfile lowercase_ = tmp_path / '''data_sym_link''' directory.mkdir() lowercase_ = directory / '''tar_file_with_sym_link.tar''' os.symlink('''..''' , directory / '''subdir''' , target_is_directory=snake_case__ ) with tarfile.TarFile(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 a ( snake_case__: List[Any] , snake_case__: Optional[int] , snake_case__: List[str] , snake_case__: List[str] , snake_case__: int , snake_case__: Optional[Any] ): '''simple docstring''' lowercase_ = { '''tar_file_with_dot_dot''': tar_file_with_dot_dot, '''tar_file_with_sym_link''': tar_file_with_sym_link, } lowercase_ = insecure_tar_files[insecure_tar_file] lowercase_ = tmp_path / '''extracted''' TarExtractor.extract(snake_case__ , snake_case__ ) assert caplog.text for record in caplog.records: assert record.levelname == "ERROR" assert error_log in record.msg def a ( snake_case__: Optional[int] ): '''simple docstring''' # We should have less false positives than zipfile.is_zipfile # We do that by checking only the magic number lowercase_ = tmpdir / '''not_a_zip_file''' # From: https://github.com/python/cpython/pull/5053 lowercase_ = ( 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(snake_case__ ) assert zipfile.is_zipfile(str(snake_case__ ) ) # is a false positive for `zipfile` assert not ZipExtractor.is_extractable(snake_case__ ) # but we're right
30
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _snake_case : List[str] = {"configuration_ibert": ["IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "IBertConfig", "IBertOnnxConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : Union[str, Any] = [ "IBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "IBertForMaskedLM", "IBertForMultipleChoice", "IBertForQuestionAnswering", "IBertForSequenceClassification", "IBertForTokenClassification", "IBertModel", "IBertPreTrainedModel", ] if TYPE_CHECKING: from .configuration_ibert import IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, IBertConfig, IBertOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ibert import ( IBERT_PRETRAINED_MODEL_ARCHIVE_LIST, IBertForMaskedLM, IBertForMultipleChoice, IBertForQuestionAnswering, IBertForSequenceClassification, IBertForTokenClassification, IBertModel, IBertPreTrainedModel, ) else: import sys _snake_case : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
134
def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): if index == r: for j in range(__lowerCamelCase ): print(data[j] , end=" " ) print(" " ) return # When no more elements are there to put in data[] if i >= n: return # current is included, put next at next location __snake_case : Union[str, Any] = arr[i] combination_util(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , index + 1 , __lowerCamelCase , i + 1 ) # current is excluded, replace it with # next (Note that i+1 is passed, but # index is not changed) combination_util(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , i + 1 ) # The main function that prints all combinations # of size r in arr[] of size n. This function # mainly uses combinationUtil() def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): # A temporary array to store all combination one by one __snake_case : Union[str, Any] = [0] * r # Print all combination using temporary array 'data[]' combination_util(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , 0 , __lowerCamelCase , 0 ) if __name__ == "__main__": # Driver code to check the function above _snake_case : List[str] = [10, 20, 30, 40, 50] print_combination(arr, len(arr), 3) # This code is contributed by Ambuj sahu
134
1
'''simple docstring''' # Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING import numpy as np import pyarrow as pa from .. import config from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import torch class __lowerCAmelCase ( TensorFormatter[Mapping, 'torch.Tensor', Mapping] ): """simple docstring""" def __init__( self : Tuple , lowerCAmelCase__ : Union[str, Any]=None , **lowerCAmelCase__ : Optional[Any] ) -> Dict: '''simple docstring''' super().__init__(features=SCREAMING_SNAKE_CASE_ ) _UpperCamelCase = torch_tensor_kwargs import torch # noqa import torch at initialization def snake_case__ ( self : Tuple , lowerCAmelCase__ : Any ) -> str: '''simple docstring''' import torch if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and column: if all( isinstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return torch.stack(SCREAMING_SNAKE_CASE_ ) return column def snake_case__ ( self : Optional[Any] , lowerCAmelCase__ : List[Any] ) -> Dict: '''simple docstring''' import torch if isinstance(SCREAMING_SNAKE_CASE_ , (str, bytes, type(SCREAMING_SNAKE_CASE_ )) ): return value elif isinstance(SCREAMING_SNAKE_CASE_ , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() _UpperCamelCase = {} if isinstance(SCREAMING_SNAKE_CASE_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): _UpperCamelCase = {"""dtype""": torch.intaa} elif isinstance(SCREAMING_SNAKE_CASE_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): _UpperCamelCase = {"""dtype""": torch.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(SCREAMING_SNAKE_CASE_ , PIL.Image.Image ): _UpperCamelCase = np.asarray(SCREAMING_SNAKE_CASE_ ) return torch.tensor(SCREAMING_SNAKE_CASE_ , **{**default_dtype, **self.torch_tensor_kwargs} ) def snake_case__ ( self : Dict , lowerCAmelCase__ : str ) -> int: '''simple docstring''' import torch # support for torch, tf, jax etc. if hasattr(SCREAMING_SNAKE_CASE_ , '''__array__''' ) and not isinstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ): _UpperCamelCase = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ): if data_struct.dtype == object: # torch tensors cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(SCREAMING_SNAKE_CASE_ ) for substruct in data_struct] ) elif isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ): return self._consolidate([self.recursive_tensorize(SCREAMING_SNAKE_CASE_ ) for substruct in data_struct] ) return self._tensorize(SCREAMING_SNAKE_CASE_ ) def snake_case__ ( self : List[Any] , lowerCAmelCase__ : Union[str, Any] ) -> Tuple: '''simple docstring''' return map_nested(self._recursive_tensorize , SCREAMING_SNAKE_CASE_ , map_list=SCREAMING_SNAKE_CASE_ ) def snake_case__ ( self : Union[str, Any] , lowerCAmelCase__ : Optional[Any] ) -> Mapping: '''simple docstring''' _UpperCamelCase = self.numpy_arrow_extractor().extract_row(SCREAMING_SNAKE_CASE_ ) _UpperCamelCase = self.python_features_decoder.decode_row(SCREAMING_SNAKE_CASE_ ) return self.recursive_tensorize(SCREAMING_SNAKE_CASE_ ) def snake_case__ ( self : Dict , lowerCAmelCase__ : Any ) -> "torch.Tensor": '''simple docstring''' _UpperCamelCase = self.numpy_arrow_extractor().extract_column(SCREAMING_SNAKE_CASE_ ) _UpperCamelCase = self.python_features_decoder.decode_column(SCREAMING_SNAKE_CASE_ , pa_table.column_names[0] ) _UpperCamelCase = self.recursive_tensorize(SCREAMING_SNAKE_CASE_ ) _UpperCamelCase = self._consolidate(SCREAMING_SNAKE_CASE_ ) return column def snake_case__ ( self : List[str] , lowerCAmelCase__ : str ) -> Mapping: '''simple docstring''' _UpperCamelCase = self.numpy_arrow_extractor().extract_batch(SCREAMING_SNAKE_CASE_ ) _UpperCamelCase = self.python_features_decoder.decode_batch(SCREAMING_SNAKE_CASE_ ) _UpperCamelCase = self.recursive_tensorize(SCREAMING_SNAKE_CASE_ ) for column_name in batch: _UpperCamelCase = self._consolidate(batch[column_name] ) return batch
324
a : Optional[int] = 9.8_0_6_6_5 def lowerCAmelCase_ (lowerCAmelCase__: float , lowerCAmelCase__: float , lowerCAmelCase__: float = g ): """simple docstring""" if fluid_density <= 0: raise ValueError("""Impossible fluid density""" ) if volume < 0: raise ValueError("""Impossible Object volume""" ) if gravity <= 0: raise ValueError("""Impossible Gravity""" ) return fluid_density * gravity * volume if __name__ == "__main__": import doctest # run doctest doctest.testmod()
147
0
'''simple docstring''' import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def A (__lowerCamelCase :int = 8 ): _lowerCAmelCase = ascii_letters + digits + punctuation return "".join(secrets.choice(__lowerCamelCase ) for _ in range(__lowerCamelCase ) ) def A (__lowerCamelCase :str , __lowerCamelCase :int ): # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(__lowerCamelCase ) _lowerCAmelCase = i // 3 _lowerCAmelCase = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) _lowerCAmelCase = ( chars_incl + random(__lowerCamelCase , quotient + remainder ) + random(__lowerCamelCase , __lowerCamelCase ) + random(__lowerCamelCase , __lowerCamelCase ) ) _lowerCAmelCase = list(__lowerCamelCase ) shuffle(__lowerCamelCase ) return "".join(__lowerCamelCase ) # random is a generalised function for letters, characters and numbers def A (__lowerCamelCase :str , __lowerCamelCase :int ): return "".join(secrets.choice(__lowerCamelCase ) for _ in range(__lowerCamelCase ) ) def A (__lowerCamelCase :List[str] , __lowerCamelCase :List[str] ): pass # Put your code here... def A (__lowerCamelCase :Dict , __lowerCamelCase :int ): pass # Put your code here... def A (__lowerCamelCase :Dict , __lowerCamelCase :Dict ): pass # Put your code here... def A (__lowerCamelCase :str , __lowerCamelCase :int = 8 ): if len(__lowerCamelCase ) < min_length: # Your Password must be at least 8 characters long return False _lowerCAmelCase = any(char in ascii_uppercase for char in password ) _lowerCAmelCase = any(char in ascii_lowercase for char in password ) _lowerCAmelCase = any(char in digits for char in password ) _lowerCAmelCase = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def A (): _lowerCAmelCase = int(input("""Please indicate the max length of your password: """ ).strip() ) _lowerCAmelCase = input( """Please indicate the characters that must be in your password: """ ).strip() print("""Password generated:""" , password_generator(__lowerCamelCase ) ) print( """Alternative Password generated:""" , alternative_password_generator(__lowerCamelCase , __lowerCamelCase ) , ) print("""[If you are thinking of using this passsword, You better save it.]""" ) if __name__ == "__main__": main()
229
'''simple docstring''' from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxCrossAttnUpBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, FlaxUpBlockaD, ) @flax.struct.dataclass class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' _lowercase : jnp.ndarray @flax_register_to_config class UpperCAmelCase_ ( nn.Module , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): '''simple docstring''' _lowercase : int = 3_2 _lowercase : int = 4 _lowercase : int = 4 _lowercase : Tuple[str] = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) _lowercase : Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D") _lowercase : Union[bool, Tuple[bool]] = False _lowercase : Tuple[int] = (3_2_0, 6_4_0, 1_2_8_0, 1_2_8_0) _lowercase : int = 2 _lowercase : Union[int, Tuple[int]] = 8 _lowercase : Optional[Union[int, Tuple[int]]] = None _lowercase : int = 1_2_8_0 _lowercase : float = 0.0 _lowercase : bool = False _lowercase : jnp.dtype = jnp.floataa _lowercase : bool = True _lowercase : int = 0 _lowercase : bool = False def _lowercase ( self , _lowercase ): """simple docstring""" _lowerCAmelCase = (1, self.in_channels, self.sample_size, self.sample_size) _lowerCAmelCase = jnp.zeros(_lowercase , dtype=jnp.floataa ) _lowerCAmelCase = jnp.ones((1,) , dtype=jnp.intaa ) _lowerCAmelCase = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) _lowerCAmelCase , _lowerCAmelCase = jax.random.split(_lowercase ) _lowerCAmelCase = {"""params""": params_rng, """dropout""": dropout_rng} return self.init(_lowercase , _lowercase , _lowercase , _lowercase )["params"] def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = self.block_out_channels _lowerCAmelCase = block_out_channels[0] * 4 if self.num_attention_heads is not None: raise ValueError( """At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19.""" ) # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. _lowerCAmelCase = self.num_attention_heads or self.attention_head_dim # input _lowerCAmelCase = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time _lowerCAmelCase = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) _lowerCAmelCase = FlaxTimestepEmbedding(_lowercase , dtype=self.dtype ) _lowerCAmelCase = self.only_cross_attention if isinstance(_lowercase , _lowercase ): _lowerCAmelCase = (only_cross_attention,) * len(self.down_block_types ) if isinstance(_lowercase , _lowercase ): _lowerCAmelCase = (num_attention_heads,) * len(self.down_block_types ) # down _lowerCAmelCase = [] _lowerCAmelCase = block_out_channels[0] for i, down_block_type in enumerate(self.down_block_types ): _lowerCAmelCase = output_channel _lowerCAmelCase = block_out_channels[i] _lowerCAmelCase = i == len(_lowercase ) - 1 if down_block_type == "CrossAttnDownBlock2D": _lowerCAmelCase = FlaxCrossAttnDownBlockaD( in_channels=_lowercase , out_channels=_lowercase , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: _lowerCAmelCase = FlaxDownBlockaD( in_channels=_lowercase , out_channels=_lowercase , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(_lowercase ) _lowerCAmelCase = down_blocks # mid _lowerCAmelCase = FlaxUNetMidBlockaDCrossAttn( in_channels=block_out_channels[-1] , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) # up _lowerCAmelCase = [] _lowerCAmelCase = list(reversed(_lowercase ) ) _lowerCAmelCase = list(reversed(_lowercase ) ) _lowerCAmelCase = list(reversed(_lowercase ) ) _lowerCAmelCase = reversed_block_out_channels[0] for i, up_block_type in enumerate(self.up_block_types ): _lowerCAmelCase = output_channel _lowerCAmelCase = reversed_block_out_channels[i] _lowerCAmelCase = reversed_block_out_channels[min(i + 1 , len(_lowercase ) - 1 )] _lowerCAmelCase = i == len(_lowercase ) - 1 if up_block_type == "CrossAttnUpBlock2D": _lowerCAmelCase = FlaxCrossAttnUpBlockaD( in_channels=_lowercase , out_channels=_lowercase , prev_output_channel=_lowercase , num_layers=self.layers_per_block + 1 , num_attention_heads=reversed_num_attention_heads[i] , add_upsample=not is_final_block , dropout=self.dropout , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: _lowerCAmelCase = FlaxUpBlockaD( in_channels=_lowercase , out_channels=_lowercase , prev_output_channel=_lowercase , num_layers=self.layers_per_block + 1 , add_upsample=not is_final_block , dropout=self.dropout , dtype=self.dtype , ) up_blocks.append(_lowercase ) _lowerCAmelCase = output_channel _lowerCAmelCase = up_blocks # out _lowerCAmelCase = nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) _lowerCAmelCase = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self , _lowercase , _lowercase , _lowercase , _lowercase=None , _lowercase=None , _lowercase = True , _lowercase = False , ): """simple docstring""" if not isinstance(_lowercase , jnp.ndarray ): _lowerCAmelCase = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(_lowercase , jnp.ndarray ) and len(timesteps.shape ) == 0: _lowerCAmelCase = timesteps.astype(dtype=jnp.floataa ) _lowerCAmelCase = jnp.expand_dims(_lowercase , 0 ) _lowerCAmelCase = self.time_proj(_lowercase ) _lowerCAmelCase = self.time_embedding(_lowercase ) # 2. pre-process _lowerCAmelCase = jnp.transpose(_lowercase , (0, 2, 3, 1) ) _lowerCAmelCase = self.conv_in(_lowercase ) # 3. down _lowerCAmelCase = (sample,) for down_block in self.down_blocks: if isinstance(_lowercase , _lowercase ): _lowerCAmelCase , _lowerCAmelCase = down_block(_lowercase , _lowercase , _lowercase , deterministic=not train ) else: _lowerCAmelCase , _lowerCAmelCase = down_block(_lowercase , _lowercase , deterministic=not train ) down_block_res_samples += res_samples if down_block_additional_residuals is not None: _lowerCAmelCase = () for down_block_res_sample, down_block_additional_residual in zip( _lowercase , _lowercase ): down_block_res_sample += down_block_additional_residual new_down_block_res_samples += (down_block_res_sample,) _lowerCAmelCase = new_down_block_res_samples # 4. mid _lowerCAmelCase = self.mid_block(_lowercase , _lowercase , _lowercase , deterministic=not train ) if mid_block_additional_residual is not None: sample += mid_block_additional_residual # 5. up for up_block in self.up_blocks: _lowerCAmelCase = down_block_res_samples[-(self.layers_per_block + 1) :] _lowerCAmelCase = down_block_res_samples[: -(self.layers_per_block + 1)] if isinstance(_lowercase , _lowercase ): _lowerCAmelCase = up_block( _lowercase , temb=_lowercase , encoder_hidden_states=_lowercase , res_hidden_states_tuple=_lowercase , deterministic=not train , ) else: _lowerCAmelCase = up_block(_lowercase , temb=_lowercase , res_hidden_states_tuple=_lowercase , deterministic=not train ) # 6. post-process _lowerCAmelCase = self.conv_norm_out(_lowercase ) _lowerCAmelCase = nn.silu(_lowercase ) _lowerCAmelCase = self.conv_out(_lowercase ) _lowerCAmelCase = jnp.transpose(_lowercase , (0, 3, 1, 2) ) if not return_dict: return (sample,) return FlaxUNetaDConditionOutput(sample=_lowercase )
229
1
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL SCREAMING_SNAKE_CASE = logging.get_logger(__name__) class UpperCAmelCase_ ( A_ ): lowercase__ = ['''pixel_values'''] def __init__( self : Optional[Any] , snake_case_ : bool = True , snake_case_ : Dict[str, int] = None , snake_case_ : int = 0.9 , snake_case_ : PILImageResampling = PILImageResampling.BICUBIC , snake_case_ : bool = True , snake_case_ : Dict[str, int] = None , snake_case_ : Union[int, float] = 1 / 255 , snake_case_ : bool = True , snake_case_ : bool = True , snake_case_ : Optional[Union[float, List[float]]] = None , snake_case_ : Optional[Union[float, List[float]]] = None , **snake_case_ : str , ) -> None: '''simple docstring''' super().__init__(**snake_case_ ) A__ = size if size is not None else {"shortest_edge": 224} A__ = get_size_dict(snake_case_ , default_to_square=snake_case_ ) A__ = crop_size if crop_size is not None else {"height": 224, "width": 224} A__ = get_size_dict(snake_case_ , param_name="crop_size" ) A__ = do_resize A__ = size A__ = crop_pct A__ = resample A__ = do_center_crop A__ = crop_size A__ = do_rescale A__ = rescale_factor A__ = do_normalize A__ = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN A__ = image_std if image_std is not None else IMAGENET_DEFAULT_STD def __magic_name__ ( self : Optional[int] , snake_case_ : np.ndarray , snake_case_ : Dict[str, int] , snake_case_ : Optional[float] = None , snake_case_ : PILImageResampling = PILImageResampling.BICUBIC , snake_case_ : Optional[Union[str, ChannelDimension]] = None , **snake_case_ : List[Any] , ) -> np.ndarray: '''simple docstring''' A__ = get_size_dict(snake_case_ , default_to_square=snake_case_ ) if "shortest_edge" not in size and ("height" not in size or "width" not in size): raise ValueError(F"""size must contain 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}""" ) if crop_pct is not None: if "shortest_edge" in size: A__ = int(size["shortest_edge"] / crop_pct ) elif "height" in size and "width" in size: if size["height"] == size["width"]: A__ = int(size["height"] / crop_pct ) else: A__ = (int(size["height"] / crop_pct ), int(size["width"] / crop_pct )) else: raise ValueError("Invalid size for resize: {}".format(snake_case_ ) ) A__ = get_resize_output_image_size(snake_case_ , size=snake_case_ , default_to_square=snake_case_ ) else: if "shortest_edge" in size: A__ = get_resize_output_image_size(snake_case_ , size=size["shortest_edge"] , default_to_square=snake_case_ ) elif "height" in size and "width" in size: A__ = (size["height"], size["width"]) else: raise ValueError("Invalid size for resize: {}".format(snake_case_ ) ) return resize(snake_case_ , size=snake_case_ , resample=snake_case_ , data_format=snake_case_ , **snake_case_ ) def __magic_name__ ( self : Union[str, Any] , snake_case_ : np.ndarray , snake_case_ : Dict[str, int] , snake_case_ : Optional[Union[str, ChannelDimension]] = None , **snake_case_ : List[str] , ) -> np.ndarray: '''simple docstring''' A__ = get_size_dict(snake_case_ ) if "height" not in size or "width" not in size: raise ValueError(F"""size must contain 'height' and 'width' as keys. Got {size.keys()}""" ) return center_crop(snake_case_ , size=(size["height"], size["width"]) , data_format=snake_case_ , **snake_case_ ) def __magic_name__ ( self : List[str] , snake_case_ : np.ndarray , snake_case_ : Union[int, float] , snake_case_ : Optional[Union[str, ChannelDimension]] = None , **snake_case_ : Dict , ) -> Dict: '''simple docstring''' return rescale(snake_case_ , scale=snake_case_ , data_format=snake_case_ , **snake_case_ ) def __magic_name__ ( self : List[Any] , snake_case_ : np.ndarray , snake_case_ : Union[float, List[float]] , snake_case_ : Union[float, List[float]] , snake_case_ : Optional[Union[str, ChannelDimension]] = None , **snake_case_ : Optional[int] , ) -> np.ndarray: '''simple docstring''' return normalize(snake_case_ , mean=snake_case_ , std=snake_case_ , data_format=snake_case_ , **snake_case_ ) def __magic_name__ ( self : Optional[int] , snake_case_ : ImageInput , snake_case_ : bool = None , snake_case_ : Dict[str, int] = None , snake_case_ : int = None , snake_case_ : PILImageResampling = None , snake_case_ : bool = None , snake_case_ : Dict[str, int] = None , snake_case_ : bool = None , snake_case_ : float = None , snake_case_ : bool = None , snake_case_ : Optional[Union[float, List[float]]] = None , snake_case_ : Optional[Union[float, List[float]]] = None , snake_case_ : Optional[Union[str, TensorType]] = None , snake_case_ : ChannelDimension = ChannelDimension.FIRST , **snake_case_ : Union[str, Any] , ) -> PIL.Image.Image: '''simple docstring''' A__ = do_resize if do_resize is not None else self.do_resize A__ = crop_pct if crop_pct is not None else self.crop_pct A__ = resample if resample is not None else self.resample A__ = do_center_crop if do_center_crop is not None else self.do_center_crop A__ = do_rescale if do_rescale is not None else self.do_rescale A__ = rescale_factor if rescale_factor is not None else self.rescale_factor A__ = do_normalize if do_normalize is not None else self.do_normalize A__ = image_mean if image_mean is not None else self.image_mean A__ = image_std if image_std is not None else self.image_std A__ = size if size is not None else self.size A__ = get_size_dict(snake_case_ , default_to_square=snake_case_ ) A__ = crop_size if crop_size is not None else self.crop_size A__ = get_size_dict(snake_case_ , param_name="crop_size" ) A__ = make_list_of_images(snake_case_ ) if not valid_images(snake_case_ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_center_crop and crop_pct is None: raise ValueError("Crop_pct must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. A__ = [to_numpy_array(snake_case_ ) for image in images] if do_resize: A__ = [self.resize(image=snake_case_ , size=snake_case_ , crop_pct=snake_case_ , resample=snake_case_ ) for image in images] if do_center_crop: A__ = [self.center_crop(image=snake_case_ , size=snake_case_ ) for image in images] if do_rescale: A__ = [self.rescale(image=snake_case_ , scale=snake_case_ ) for image in images] if do_normalize: A__ = [self.normalize(image=snake_case_ , mean=snake_case_ , std=snake_case_ ) for image in images] A__ = [to_channel_dimension_format(snake_case_ , snake_case_ ) for image in images] A__ = {"pixel_values": images} return BatchFeature(data=snake_case_ , tensor_type=snake_case_ )
247
"""simple docstring""" import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy SCREAMING_SNAKE_CASE = logging.getLogger(__name__) def _SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ = None , lowercase_ = None , lowercase_ = None , lowercase_ = None , lowercase_ = None , lowercase_ = False , ) -> List[Any]: A__ = bnb_quantization_config.load_in_abit A__ = bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( "You have a version of `bitsandbytes` that is not compatible with 8bit quantization," " make sure you have the latest version of `bitsandbytes` installed." ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( "You have a version of `bitsandbytes` that is not compatible with 4bit quantization," "make sure you have the latest version of `bitsandbytes` installed." ) A__ = [] # custom device map if isinstance(lowercase_ , lowercase_ ) and len(device_map.keys() ) > 1: A__ = [key for key, value in device_map.items() if value in ["disk", "cpu"]] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: A__ = get_keys_to_not_convert(lowercase_ ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(lowercase_ ) A__ = bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: A__ = [] A__ = bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(lowercase_ ) # compatibility with peft A__ = load_in_abit A__ = load_in_abit A__ = get_parameter_device(lowercase_ ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( "It is not recommended to quantize a loaded model. " "The model should be instantiated under the `init_empty_weights` context manager." ) A__ = replace_with_bnb_layers(lowercase_ , lowercase_ , modules_to_not_convert=lowercase_ ) # convert param to the right dtype A__ = bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: A__ = name.replace(".weight" , "" ).replace(".bias" , "" ) A__ = getattr(lowercase_ , lowercase_ , lowercase_ ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(lowercase_ ): param.to(lowercase_ ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info( f"""The model device type is {model_device.type}. However, cuda is needed for quantization.""" "We move the model to cuda." ) return model elif weights_location is None: raise RuntimeError( f"""`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} """ ) else: with init_empty_weights(): A__ = replace_with_bnb_layers( lowercase_ , lowercase_ , modules_to_not_convert=lowercase_ ) A__ = get_quantized_model_device_map( lowercase_ , lowercase_ , lowercase_ , max_memory=lowercase_ , no_split_module_classes=lowercase_ , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): A__ = True A__ = any(x in list(device_map.values() ) for x in ["cpu", "disk"] ) load_checkpoint_in_model( lowercase_ , lowercase_ , lowercase_ , dtype=bnb_quantization_config.torch_dtype , offload_folder=lowercase_ , offload_state_dict=lowercase_ , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(lowercase_ , device_map=lowercase_ , offload_dir=lowercase_ ) def _SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_=None , lowercase_=None , lowercase_=None ) -> List[str]: if device_map is None: if torch.cuda.is_available(): A__ = {"": torch.cuda.current_device()} else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info("The device_map was not initialized." "Setting device_map to `{'':torch.cuda.current_device()}`." ) if isinstance(lowercase_ , lowercase_ ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or " "'sequential'." ) A__ = {} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) A__ = {} A__ = special_dtypes A__ = no_split_module_classes A__ = bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": A__ = get_balanced_memory( lowercase_ , low_zero=(device_map == "balanced_low_0") , max_memory=lowercase_ , **lowercase_ , ) A__ = max_memory A__ = infer_auto_device_map(lowercase_ , **lowercase_ ) if isinstance(lowercase_ , lowercase_ ): # check if don't have any quantized module on the cpu A__ = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules A__ = { key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( "\n Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n these modules in `torch_dtype`, you need to pass a custom `device_map` to\n `load_and_quantize_model`. Check\n https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n for more details.\n " ) else: logger.info( "Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit" ) del device_map_without_some_modules return device_map def _SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_=None , lowercase_=None ) -> Optional[int]: if modules_to_not_convert is None: A__ = [] A__, A__ = _replace_with_bnb_layers( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) if not has_been_replaced: logger.warning( "You are loading your model in 8bit or 4bit but no linear modules were found in your model." " this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers." " Please double check your model architecture, or submit an issue on github if you think this is" " a bug." ) return model def _SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_=None , lowercase_=None , ) -> Optional[int]: A__ = False for name, module in model.named_children(): if current_key_name is None: A__ = [] current_key_name.append(lowercase_ ) if isinstance(lowercase_ , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` A__ = ".".join(lowercase_ ) A__ = True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: A__ = False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: A__ = bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=lowercase_ , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: A__ = bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError("load_in_8bit and load_in_4bit can't be both False" ) A__ = module.weight.data if module.bias is not None: A__ = module.bias.data bnb_module.requires_grad_(lowercase_ ) setattr(lowercase_ , lowercase_ , lowercase_ ) A__ = True if len(list(module.children() ) ) > 0: A__, A__ = _replace_with_bnb_layers( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) A__ = has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def _SCREAMING_SNAKE_CASE ( lowercase_ ) -> str: # Create a copy of the model with init_empty_weights(): A__ = deepcopy(lowercase_ ) # this has 0 cost since it is done inside `init_empty_weights` context manager` A__ = find_tied_parameters(lowercase_ ) # For compatibility with Accelerate < 0.18 if isinstance(lowercase_ , lowercase_ ): A__ = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: A__ = sum(lowercase_ , [] ) A__ = len(lowercase_ ) > 0 # Check if it is a base model A__ = False if hasattr(lowercase_ , "base_model_prefix" ): A__ = not hasattr(lowercase_ , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head A__ = list(model.named_children() ) A__ = [list_modules[-1][0]] # add last module together with tied weights A__ = set(lowercase_ ) - set(lowercase_ ) A__ = list(set(lowercase_ ) ) + list(lowercase_ ) # remove ".weight" from the keys A__ = [".weight", ".bias"] A__ = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: A__ = name.replace(lowercase_ , "" ) filtered_module_names.append(lowercase_ ) return filtered_module_names def _SCREAMING_SNAKE_CASE ( lowercase_ ) -> Dict: for m in model.modules(): if isinstance(lowercase_ , bnb.nn.Linearabit ): return True return False def _SCREAMING_SNAKE_CASE ( lowercase_ ) -> List[Any]: return next(parameter.parameters() ).device def _SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ) -> Union[str, Any]: # if it is not quantized, we quantize and offload the quantized weights and the SCB stats if fpaa_statistics is None: set_module_tensor_to_device(lowercase_ , lowercase_ , 0 , dtype=lowercase_ , value=lowercase_ ) A__ = param_name A__ = model if "." in tensor_name: A__ = tensor_name.split("." ) for split in splits[:-1]: A__ = getattr(lowercase_ , lowercase_ ) if new_module is None: raise ValueError(f"""{module} has no attribute {split}.""" ) A__ = new_module A__ = splits[-1] # offload weights A__ = False offload_weight(module._parameters[tensor_name] , lowercase_ , lowercase_ , index=lowercase_ ) if hasattr(module._parameters[tensor_name] , "SCB" ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace("weight" , "SCB" ) , lowercase_ , index=lowercase_ , ) else: offload_weight(lowercase_ , lowercase_ , lowercase_ , index=lowercase_ ) offload_weight(lowercase_ , param_name.replace("weight" , "SCB" ) , lowercase_ , index=lowercase_ ) set_module_tensor_to_device(lowercase_ , lowercase_ , "meta" , dtype=lowercase_ , value=torch.empty(*param.size() ) )
247
1
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCAmelCase :Optional[int] = logging.get_logger(__name__) _lowerCAmelCase :List[str] = { 'BAAI/AltCLIP': 'https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json', # See all AltCLIP models at https://huggingface.co/models?filter=altclip } class _UpperCAmelCase ( a ): '''simple docstring''' a__ : Optional[Any] ='''altclip_text_model''' def __init__( self , A=2_5_0_0_0_2 , A=1_0_2_4 , A=2_4 , A=1_6 , A=4_0_9_6 , A="gelu" , A=0.1 , A=0.1 , A=5_1_4 , A=1 , A=0.02 , A=0.02 , A=1E-05 , A=1 , A=0 , A=2 , A="absolute" , A=True , A=7_6_8 , **A , ) -> int: super().__init__(pad_token_id=A , bos_token_id=A , eos_token_id=A , **A ) _UpperCAmelCase : Dict = vocab_size _UpperCAmelCase : str = hidden_size _UpperCAmelCase : List[Any] = num_hidden_layers _UpperCAmelCase : Union[str, Any] = num_attention_heads _UpperCAmelCase : int = hidden_act _UpperCAmelCase : Union[str, Any] = intermediate_size _UpperCAmelCase : Any = hidden_dropout_prob _UpperCAmelCase : Union[str, Any] = attention_probs_dropout_prob _UpperCAmelCase : Optional[int] = max_position_embeddings _UpperCAmelCase : List[Any] = type_vocab_size _UpperCAmelCase : List[str] = initializer_range _UpperCAmelCase : Dict = initializer_factor _UpperCAmelCase : Optional[Any] = layer_norm_eps _UpperCAmelCase : Dict = position_embedding_type _UpperCAmelCase : str = use_cache _UpperCAmelCase : int = project_dim class _UpperCAmelCase ( a ): '''simple docstring''' a__ : Tuple ='''altclip_vision_model''' def __init__( self , A=7_6_8 , A=3_0_7_2 , A=5_1_2 , A=1_2 , A=1_2 , A=3 , A=2_2_4 , A=3_2 , A="quick_gelu" , A=1E-5 , A=0.0 , A=0.02 , A=1.0 , **A , ) -> List[Any]: super().__init__(**A ) _UpperCAmelCase : Optional[int] = hidden_size _UpperCAmelCase : str = intermediate_size _UpperCAmelCase : List[Any] = projection_dim _UpperCAmelCase : Tuple = num_hidden_layers _UpperCAmelCase : Optional[int] = num_attention_heads _UpperCAmelCase : Union[str, Any] = num_channels _UpperCAmelCase : Any = patch_size _UpperCAmelCase : List[Any] = image_size _UpperCAmelCase : List[Any] = initializer_range _UpperCAmelCase : str = initializer_factor _UpperCAmelCase : Optional[Any] = attention_dropout _UpperCAmelCase : int = layer_norm_eps _UpperCAmelCase : Optional[Any] = hidden_act @classmethod def __lowerCAmelCase ( cls , A , **A ) -> "PretrainedConfig": cls._set_token_in_kwargs(A ) _UpperCAmelCase : List[str] = cls.get_config_dict(A , **A ) # get the vision config dict if we are loading from AltCLIPConfig if config_dict.get('''model_type''' ) == "altclip": _UpperCAmelCase : int = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A , **A ) class _UpperCAmelCase ( a ): '''simple docstring''' a__ : Dict ='''altclip''' a__ : Tuple =True def __init__( self , A=None , A=None , A=7_6_8 , A=2.6_592 , **A ) -> Any: # If `_config_dict` exist, we use them for the backward compatibility. # We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot # of confusion!). _UpperCAmelCase : List[Any] = kwargs.pop('''text_config_dict''' , A ) _UpperCAmelCase : Optional[int] = kwargs.pop('''vision_config_dict''' , A ) super().__init__(**A ) # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`. if text_config_dict is not None: if text_config is None: _UpperCAmelCase : Any = {} # This is the complete result when using `text_config_dict`. _UpperCAmelCase : Dict = AltCLIPTextConfig(**A ).to_dict() # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different. for key, value in _text_config_dict.items(): if key in text_config and value != text_config[key] and key not in ["transformers_version"]: # If specified in `text_config_dict` if key in text_config_dict: _UpperCAmelCase : List[Any] = ( f'`{key}` is found in both `text_config_dict` and `text_config` but with different values. ' f'The value `text_config_dict["{key}"]` will be used instead.' ) # If inferred from default argument values (just to be super careful) else: _UpperCAmelCase : Optional[Any] = ( f'`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The ' f'value `text_config["{key}"]` will be overriden.' ) logger.warning(A ) # Update all values in `text_config` with the ones in `_text_config_dict`. text_config.update(_text_config_dict ) if vision_config_dict is not None: if vision_config is None: _UpperCAmelCase : Union[str, Any] = {} # This is the complete result when using `vision_config_dict`. _UpperCAmelCase : Any = AltCLIPVisionConfig(**A ).to_dict() # convert keys to string instead of integer if "id2label" in _vision_config_dict: _UpperCAmelCase : Optional[int] = { str(A ): value for key, value in _vision_config_dict['''id2label'''].items() } # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different. for key, value in _vision_config_dict.items(): if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]: # If specified in `vision_config_dict` if key in vision_config_dict: _UpperCAmelCase : List[str] = ( f'`{key}` is found in both `vision_config_dict` and `vision_config` but with different ' f'values. The value `vision_config_dict["{key}"]` will be used instead.' ) # If inferred from default argument values (just to be super careful) else: _UpperCAmelCase : List[Any] = ( f'`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. ' f'The value `vision_config["{key}"]` will be overriden.' ) logger.warning(A ) # Update all values in `vision_config` with the ones in `_vision_config_dict`. vision_config.update(_vision_config_dict ) if text_config is None: _UpperCAmelCase : Union[str, Any] = {} logger.info('''`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values.''' ) if vision_config is None: _UpperCAmelCase : Union[str, Any] = {} logger.info('''`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values.''' ) _UpperCAmelCase : Any = AltCLIPTextConfig(**A ) _UpperCAmelCase : Any = AltCLIPVisionConfig(**A ) _UpperCAmelCase : str = projection_dim _UpperCAmelCase : str = logit_scale_init_value _UpperCAmelCase : Tuple = 1.0 @classmethod def __lowerCAmelCase ( cls , A , A , **A ) -> Any: return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **A ) def __lowerCAmelCase ( self ) -> Any: _UpperCAmelCase : Optional[int] = copy.deepcopy(self.__dict__ ) _UpperCAmelCase : Union[str, Any] = self.text_config.to_dict() _UpperCAmelCase : Union[str, Any] = self.vision_config.to_dict() _UpperCAmelCase : Optional[int] = self.__class__.model_type return output
362
"""simple docstring""" import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class _UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self ) -> Any: _UpperCAmelCase : List[str] = torch.tensor([-1_0_0, -1, -0.1, 0, 0.1, 1.0, 1_0_0] ) _UpperCAmelCase : Optional[Any] = get_activation('''gelu''' ) self.assertTrue(torch.allclose(gelu_python(A ) , torch_builtin(A ) ) ) self.assertFalse(torch.allclose(gelu_python(A ) , gelu_new(A ) ) ) def __lowerCAmelCase ( self ) -> str: _UpperCAmelCase : Union[str, Any] = torch.tensor([-1_0_0, -1, -0.1, 0, 0.1, 1.0, 1_0_0] ) _UpperCAmelCase : Tuple = get_activation('''gelu''' ) _UpperCAmelCase : int = get_activation('''gelu_10''' ) _UpperCAmelCase : Optional[int] = torch_builtin(A ) _UpperCAmelCase : Optional[int] = geluaa(A ) _UpperCAmelCase : Optional[Any] = torch.where(y_gelu_aa < 10.0 , 1 , 0 ) self.assertTrue(torch.max(A ).item() == 10.0 ) self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) ) def __lowerCAmelCase ( self ) -> Optional[Any]: get_activation('''gelu''' ) get_activation('''gelu_10''' ) get_activation('''gelu_fast''' ) get_activation('''gelu_new''' ) get_activation('''gelu_python''' ) get_activation('''gelu_pytorch_tanh''' ) get_activation('''linear''' ) get_activation('''mish''' ) get_activation('''quick_gelu''' ) get_activation('''relu''' ) get_activation('''sigmoid''' ) get_activation('''silu''' ) get_activation('''swish''' ) get_activation('''tanh''' ) with self.assertRaises(A ): get_activation('''bogus''' ) with self.assertRaises(A ): get_activation(A ) def __lowerCAmelCase ( self ) -> Tuple: _UpperCAmelCase : Dict = get_activation('''gelu''' ) _UpperCAmelCase : List[Any] = 1 _UpperCAmelCase : int = get_activation('''gelu''' ) self.assertEqual(acta.a , 1 ) with self.assertRaises(A ): _UpperCAmelCase : Any = acta.a
68
0
import inspect import unittest from math import floor from transformers import CvtConfig 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 transformers import CvtForImageClassification, CvtModel from transformers.models.cvt.modeling_cvt import CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' def snake_case__ ( self : List[str] ): """simple docstring""" snake_case_ = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__lowercase , "embed_dim" ) ) self.parent.assertTrue(hasattr(__lowercase , "num_heads" ) ) class UpperCAmelCase : '''simple docstring''' def __init__( self : Dict , __lowercase : Dict , __lowercase : str=13 , __lowercase : List[Any]=64 , __lowercase : Any=3 , __lowercase : Optional[int]=[16, 48, 96] , __lowercase : List[Any]=[1, 3, 6] , __lowercase : int=[1, 2, 10] , __lowercase : Union[str, Any]=[7, 3, 3] , __lowercase : Dict=[4, 2, 2] , __lowercase : str=[2, 1, 1] , __lowercase : List[str]=[2, 2, 2] , __lowercase : Union[str, Any]=[False, False, True] , __lowercase : str=[0.0, 0.0, 0.0] , __lowercase : List[str]=0.02 , __lowercase : Union[str, Any]=1E-12 , __lowercase : Dict=True , __lowercase : Any=True , __lowercase : str=2 , ): """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = image_size snake_case_ = patch_sizes snake_case_ = patch_stride snake_case_ = patch_padding snake_case_ = is_training snake_case_ = use_labels snake_case_ = num_labels snake_case_ = num_channels snake_case_ = embed_dim snake_case_ = num_heads snake_case_ = stride_kv snake_case_ = depth snake_case_ = cls_token snake_case_ = attention_drop_rate snake_case_ = initializer_range snake_case_ = layer_norm_eps def snake_case__ ( self : Optional[Any] ): """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.num_labels ) snake_case_ = self.get_config() return config, pixel_values, labels def snake_case__ ( self : str ): """simple docstring""" 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 : str , __lowercase : Tuple , __lowercase : Tuple , __lowercase : Any ): """simple docstring""" snake_case_ = CvtModel(config=__lowercase ) model.to(__lowercase ) model.eval() snake_case_ = model(__lowercase ) snake_case_ = (self.image_size, self.image_size) snake_case_ , snake_case_ = image_size[0], image_size[1] for i in range(len(self.depth ) ): snake_case_ = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) snake_case_ = 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 : Any , __lowercase : int , __lowercase : List[str] , __lowercase : int ): """simple docstring""" snake_case_ = self.num_labels snake_case_ = CvtForImageClassification(__lowercase ) model.to(__lowercase ) model.eval() snake_case_ = model(__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def snake_case__ ( self : List[str] ): """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 UpperCAmelCase ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase_ = (CvtModel, CvtForImageClassification) if is_torch_available() else () lowerCAmelCase_ = ( {'''feature-extraction''': CvtModel, '''image-classification''': CvtForImageClassification} if is_torch_available() else {} ) lowerCAmelCase_ = False lowerCAmelCase_ = False lowerCAmelCase_ = False lowerCAmelCase_ = False lowerCAmelCase_ = False def snake_case__ ( self : Dict ): """simple docstring""" snake_case_ = CvtModelTester(self ) snake_case_ = ConfigTester(self , config_class=__lowercase , has_text_modality=__lowercase , hidden_size=37 ) def snake_case__ ( self : Optional[Any] ): """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def snake_case__ ( self : Optional[int] ): """simple docstring""" return @unittest.skip(reason="Cvt does not output attentions" ) def snake_case__ ( self : str ): """simple docstring""" pass @unittest.skip(reason="Cvt does not use inputs_embeds" ) def snake_case__ ( self : Union[str, Any] ): """simple docstring""" pass @unittest.skip(reason="Cvt does not support input and output embeddings" ) def snake_case__ ( self : List[str] ): """simple docstring""" pass def snake_case__ ( self : Tuple ): """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(__lowercase ) 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] , __lowercase ) def snake_case__ ( self : Tuple ): """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase ) def snake_case__ ( self : Tuple ): """simple docstring""" def check_hidden_states_output(__lowercase : str , __lowercase : Tuple , __lowercase : str ): snake_case_ = model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): snake_case_ = model(**self._prepare_for_class(__lowercase , __lowercase ) ) snake_case_ = outputs.hidden_states snake_case_ = len(self.model_tester.depth ) self.assertEqual(len(__lowercase ) , __lowercase ) # 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, ] , ) snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ = True check_hidden_states_output(__lowercase , __lowercase , __lowercase ) def snake_case__ ( self : List[str] ): """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowercase ) @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def snake_case__ ( self : List[Any] ): """simple docstring""" pass @slow def snake_case__ ( self : Any ): """simple docstring""" for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = CvtModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) def lowerCamelCase__ ( ): '''simple docstring''' snake_case_ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def snake_case__ ( self : Any ): """simple docstring""" return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def snake_case__ ( self : Union[str, Any] ): """simple docstring""" snake_case_ = CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(__lowercase ) snake_case_ = self.default_image_processor snake_case_ = prepare_img() snake_case_ = image_processor(images=__lowercase , return_tensors="pt" ).to(__lowercase ) # forward pass with torch.no_grad(): snake_case_ = model(**__lowercase ) # verify the logits snake_case_ = torch.Size((1, 10_00) ) self.assertEqual(outputs.logits.shape , __lowercase ) snake_case_ = torch.tensor([0.9285, 0.9015, -0.3150] ).to(__lowercase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowercase , atol=1E-4 ) )
187
import json import os import re import unittest from transformers import CodeGenTokenizer, CodeGenTokenizerFast from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase_ = CodeGenTokenizer lowerCAmelCase_ = CodeGenTokenizerFast lowerCAmelCase_ = True lowerCAmelCase_ = {'''add_prefix_space''': True} lowerCAmelCase_ = False def snake_case__ ( self : List[Any] ): """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt snake_case_ = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", "<|endoftext|>", ] snake_case_ = dict(zip(__lowercase , range(len(__lowercase ) ) ) ) snake_case_ = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] snake_case_ = {"unk_token": "<unk>"} snake_case_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) snake_case_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(__lowercase ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(__lowercase ) ) def snake_case__ ( self : Union[str, Any] , **__lowercase : List[str] ): """simple docstring""" kwargs.update(self.special_tokens_map ) return CodeGenTokenizer.from_pretrained(self.tmpdirname , **__lowercase ) def snake_case__ ( self : Optional[Any] , **__lowercase : Union[str, Any] ): """simple docstring""" kwargs.update(self.special_tokens_map ) return CodeGenTokenizerFast.from_pretrained(self.tmpdirname , **__lowercase ) def snake_case__ ( self : Optional[int] , __lowercase : List[str] ): """simple docstring""" snake_case_ = "lower newer" snake_case_ = "lower newer" return input_text, output_text def snake_case__ ( self : Optional[Any] ): """simple docstring""" snake_case_ = CodeGenTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) snake_case_ = "lower newer" snake_case_ = ["\u0120low", "er", "\u0120", "n", "e", "w", "er"] snake_case_ = tokenizer.tokenize(__lowercase , add_prefix_space=__lowercase ) self.assertListEqual(__lowercase , __lowercase ) snake_case_ = tokens + [tokenizer.unk_token] snake_case_ = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowercase ) , __lowercase ) def snake_case__ ( self : Optional[int] ): """simple docstring""" if not self.test_rust_tokenizer: return snake_case_ = self.get_tokenizer() snake_case_ = self.get_rust_tokenizer(add_prefix_space=__lowercase ) snake_case_ = "lower newer" # Testing tokenization snake_case_ = tokenizer.tokenize(__lowercase , add_prefix_space=__lowercase ) snake_case_ = rust_tokenizer.tokenize(__lowercase ) self.assertListEqual(__lowercase , __lowercase ) # Testing conversion to ids without special tokens snake_case_ = tokenizer.encode(__lowercase , add_special_tokens=__lowercase , add_prefix_space=__lowercase ) snake_case_ = rust_tokenizer.encode(__lowercase , add_special_tokens=__lowercase ) self.assertListEqual(__lowercase , __lowercase ) # Testing conversion to ids with special tokens snake_case_ = self.get_rust_tokenizer(add_prefix_space=__lowercase ) snake_case_ = tokenizer.encode(__lowercase , add_prefix_space=__lowercase ) snake_case_ = rust_tokenizer.encode(__lowercase ) self.assertListEqual(__lowercase , __lowercase ) # Testing the unknown token snake_case_ = tokens + [rust_tokenizer.unk_token] snake_case_ = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(__lowercase ) , __lowercase ) def snake_case__ ( self : Any , *__lowercase : Union[str, Any] , **__lowercase : Tuple ): """simple docstring""" pass def snake_case__ ( self : int , __lowercase : str=15 ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): snake_case_ = self.rust_tokenizer_class.from_pretrained(__lowercase , **__lowercase ) # Simple input snake_case_ = "This is a simple input" snake_case_ = ["This is a simple input 1", "This is a simple input 2"] snake_case_ = ("This is a simple input", "This is a pair") snake_case_ = [ ("This is a simple input 1", "This is a simple input 2"), ("This is a simple pair 1", "This is a simple pair 2"), ] # Simple input tests self.assertRaises(__lowercase , tokenizer_r.encode , __lowercase , max_length=__lowercase , padding="max_length" ) # Simple input self.assertRaises(__lowercase , tokenizer_r.encode_plus , __lowercase , max_length=__lowercase , padding="max_length" ) # Simple input self.assertRaises( __lowercase , tokenizer_r.batch_encode_plus , __lowercase , max_length=__lowercase , padding="max_length" , ) # Pair input self.assertRaises(__lowercase , tokenizer_r.encode , __lowercase , max_length=__lowercase , padding="max_length" ) # Pair input self.assertRaises(__lowercase , tokenizer_r.encode_plus , __lowercase , max_length=__lowercase , padding="max_length" ) # Pair input self.assertRaises( __lowercase , tokenizer_r.batch_encode_plus , __lowercase , max_length=__lowercase , padding="max_length" , ) def snake_case__ ( self : str ): """simple docstring""" snake_case_ = CodeGenTokenizer.from_pretrained(self.tmpdirname , pad_token="<pad>" ) # Simple input snake_case_ = "This is a simple input" snake_case_ = ["This is a simple input looooooooong", "This is a simple input"] snake_case_ = ("This is a simple input", "This is a pair") snake_case_ = [ ("This is a simple input loooooong", "This is a simple input"), ("This is a simple pair loooooong", "This is a simple pair"), ] snake_case_ = tokenizer.pad_token_id snake_case_ = tokenizer(__lowercase , padding="max_length" , max_length=30 , return_tensors="np" ) snake_case_ = tokenizer(__lowercase , padding=__lowercase , truncate=__lowercase , return_tensors="np" ) snake_case_ = tokenizer(*__lowercase , padding="max_length" , max_length=60 , return_tensors="np" ) snake_case_ = tokenizer(__lowercase , padding=__lowercase , truncate=__lowercase , return_tensors="np" ) # s # test single string max_length padding self.assertEqual(out_s["input_ids"].shape[-1] , 30 ) self.assertTrue(pad_token_id in out_s["input_ids"] ) self.assertTrue(0 in out_s["attention_mask"] ) # s2 # test automatic padding self.assertEqual(out_sa["input_ids"].shape[-1] , 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa["input_ids"][0] ) self.assertFalse(0 in out_sa["attention_mask"][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa["input_ids"][1] ) self.assertTrue(0 in out_sa["attention_mask"][1] ) # p # test single pair max_length padding self.assertEqual(out_p["input_ids"].shape[-1] , 60 ) self.assertTrue(pad_token_id in out_p["input_ids"] ) self.assertTrue(0 in out_p["attention_mask"] ) # p2 # test automatic padding pair self.assertEqual(out_pa["input_ids"].shape[-1] , 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa["input_ids"][0] ) self.assertFalse(0 in out_pa["attention_mask"][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa["input_ids"][1] ) self.assertTrue(0 in out_pa["attention_mask"][1] ) def snake_case__ ( self : Tuple ): """simple docstring""" snake_case_ = "$$$" snake_case_ = CodeGenTokenizer.from_pretrained(self.tmpdirname , bos_token=__lowercase , add_bos_token=__lowercase ) snake_case_ = "This is a simple input" snake_case_ = ["This is a simple input 1", "This is a simple input 2"] snake_case_ = tokenizer.bos_token_id snake_case_ = tokenizer(__lowercase ) snake_case_ = tokenizer(__lowercase ) self.assertEqual(out_s.input_ids[0] , __lowercase ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) snake_case_ = tokenizer.decode(out_s.input_ids ) snake_case_ = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , __lowercase ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) @slow def snake_case__ ( self : Tuple ): """simple docstring""" snake_case_ = CodeGenTokenizer.from_pretrained("Salesforce/codegen-350M-mono" ) snake_case_ = "\nif len_a > len_b:\n result = a\nelse:\n result = b\n\n\n\n#" snake_case_ = "\nif len_a > len_b: result = a\nelse: result = b" snake_case_ = tokenizer.encode(__lowercase ) snake_case_ = ["^#", re.escape("<|endoftext|>" ), "^'''", "^\"\"\"", "\n\n\n"] snake_case_ = tokenizer.decode(__lowercase , truncate_before_pattern=__lowercase ) self.assertEqual(__lowercase , __lowercase ) def snake_case__ ( self : Dict ): """simple docstring""" pass
187
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A ={ 'configuration_table_transformer': [ 'TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TableTransformerConfig', 'TableTransformerOnnxConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A =[ 'TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TableTransformerForObjectDetection', 'TableTransformerModel', 'TableTransformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TableTransformerConfig, TableTransformerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TableTransformerForObjectDetection, TableTransformerModel, TableTransformerPreTrainedModel, ) else: import sys __A =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
283
'''simple docstring''' from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class _snake_case : lowerCAmelCase :str = PegasusConfig lowerCAmelCase :Optional[int] = {} lowerCAmelCase :Dict = '''gelu''' def __init__( self , _lowerCamelCase , _lowerCamelCase=13 , _lowerCamelCase=7 , _lowerCamelCase=True , _lowerCamelCase=False , _lowerCamelCase=99 , _lowerCamelCase=32 , _lowerCamelCase=2 , _lowerCamelCase=4 , _lowerCamelCase=37 , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=40 , _lowerCamelCase=2 , _lowerCamelCase=1 , _lowerCamelCase=0 , ): UpperCAmelCase__ : Union[str, Any] = parent UpperCAmelCase__ : Any = batch_size UpperCAmelCase__ : Union[str, Any] = seq_length UpperCAmelCase__ : str = is_training UpperCAmelCase__ : Dict = use_labels UpperCAmelCase__ : Optional[int] = vocab_size UpperCAmelCase__ : int = hidden_size UpperCAmelCase__ : Union[str, Any] = num_hidden_layers UpperCAmelCase__ : str = num_attention_heads UpperCAmelCase__ : Any = intermediate_size UpperCAmelCase__ : int = hidden_dropout_prob UpperCAmelCase__ : Optional[Any] = attention_probs_dropout_prob UpperCAmelCase__ : List[str] = max_position_embeddings UpperCAmelCase__ : Union[str, Any] = eos_token_id UpperCAmelCase__ : Any = pad_token_id UpperCAmelCase__ : Dict = bos_token_id def snake_case__ ( self): UpperCAmelCase__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size) UpperCAmelCase__ : str = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size) , 1) UpperCAmelCase__ : Union[str, Any] = tf.concat([input_ids, eos_tensor] , axis=1) UpperCAmelCase__ : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) UpperCAmelCase__ : Any = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) UpperCAmelCase__ : Union[str, Any] = prepare_pegasus_inputs_dict(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase) return config, inputs_dict def snake_case__ ( self , _lowerCamelCase , _lowerCamelCase): UpperCAmelCase__ : Optional[int] = TFPegasusModel(config=_lowerCamelCase).get_decoder() UpperCAmelCase__ : Optional[int] = inputs_dict["""input_ids"""] UpperCAmelCase__ : Any = input_ids[:1, :] UpperCAmelCase__ : List[str] = inputs_dict["""attention_mask"""][:1, :] UpperCAmelCase__ : int = inputs_dict["""head_mask"""] UpperCAmelCase__ : int = 1 # first forward pass UpperCAmelCase__ : int = model(_lowerCamelCase , attention_mask=_lowerCamelCase , head_mask=_lowerCamelCase , use_cache=_lowerCamelCase) UpperCAmelCase__ , UpperCAmelCase__ : List[str] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids UpperCAmelCase__ : int = ids_tensor((self.batch_size, 3) , config.vocab_size) UpperCAmelCase__ : int = tf.cast(ids_tensor((self.batch_size, 3) , 2) , tf.inta) # append to next input_ids and UpperCAmelCase__ : Tuple = tf.concat([input_ids, next_tokens] , axis=-1) UpperCAmelCase__ : str = tf.concat([attention_mask, next_attn_mask] , axis=-1) UpperCAmelCase__ : Union[str, Any] = model(_lowerCamelCase , attention_mask=_lowerCamelCase)[0] UpperCAmelCase__ : Any = model(_lowerCamelCase , attention_mask=_lowerCamelCase , past_key_values=_lowerCamelCase)[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1]) # select random slice UpperCAmelCase__ : Optional[Any] = int(ids_tensor((1,) , output_from_past.shape[-1])) UpperCAmelCase__ : int = output_from_no_past[:, -3:, random_slice_idx] UpperCAmelCase__ : List[str] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_lowerCamelCase , _lowerCamelCase , rtol=1e-3) def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__=None , ): if attention_mask is None: UpperCAmelCase__ : Any = tf.cast(tf.math.not_equal(UpperCamelCase__ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: UpperCAmelCase__ : Optional[int] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: UpperCAmelCase__ : Tuple = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: UpperCAmelCase__ : Dict = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: UpperCAmelCase__ : Tuple = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class _snake_case ( a__ , a__ , unittest.TestCase ): lowerCAmelCase :str = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () lowerCAmelCase :Any = (TFPegasusForConditionalGeneration,) if is_tf_available() else () lowerCAmelCase :List[str] = ( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) lowerCAmelCase :int = True lowerCAmelCase :Optional[int] = False lowerCAmelCase :Dict = False def snake_case__ ( self): UpperCAmelCase__ : List[str] = TFPegasusModelTester(self) UpperCAmelCase__ : Dict = ConfigTester(self , config_class=_lowerCamelCase) def snake_case__ ( self): self.config_tester.run_common_tests() def snake_case__ ( self): UpperCAmelCase__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_lowerCamelCase) @require_sentencepiece @require_tokenizers @require_tf class _snake_case ( unittest.TestCase ): lowerCAmelCase :Dict = [ ''' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.''', ''' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ''', ] lowerCAmelCase :Any = [ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers lowerCAmelCase :Tuple = '''google/pegasus-xsum''' @cached_property def snake_case__ ( self): return AutoTokenizer.from_pretrained(self.model_name) @cached_property def snake_case__ ( self): UpperCAmelCase__ : List[Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name) return model def snake_case__ ( self , **_lowerCamelCase): UpperCAmelCase__ : Dict = self.translate_src_text(**_lowerCamelCase) assert self.expected_text == generated_words def snake_case__ ( self , **_lowerCamelCase): UpperCAmelCase__ : List[Any] = self.tokenizer(self.src_text , **_lowerCamelCase , padding=_lowerCamelCase , return_tensors="""tf""") UpperCAmelCase__ : Dict = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=_lowerCamelCase , ) UpperCAmelCase__ : Optional[Any] = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=_lowerCamelCase) return generated_words @slow def snake_case__ ( self): self._assert_generated_batch_equal_expected()
283
1
import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL a =logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Tuple[int, int]: def constraint_to_multiple_of(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=0 , lowerCamelCase__=None ): __lowerCamelCase : Dict = round(val / multiple ) * multiple if max_val is not None and x > max_val: __lowerCamelCase : Dict = math.floor(val / multiple ) * multiple if x < min_val: __lowerCamelCase : Optional[int] = math.ceil(val / multiple ) * multiple return x __lowerCamelCase : Tuple = (output_size, output_size) if isinstance(lowerCamelCase__ , lowerCamelCase__ ) else output_size __lowerCamelCase , __lowerCamelCase : Optional[Any] = get_image_size(lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase : Tuple = output_size # determine new height and width __lowerCamelCase : Any = output_height / input_height __lowerCamelCase : int = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width __lowerCamelCase : str = scale_width else: # fit height __lowerCamelCase : Optional[int] = scale_height __lowerCamelCase : Union[str, Any] = constraint_to_multiple_of(scale_height * input_height , multiple=lowerCamelCase__ ) __lowerCamelCase : Any = constraint_to_multiple_of(scale_width * input_width , multiple=lowerCamelCase__ ) return (new_height, new_width) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : str = ['''pixel_values'''] def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Dict[str, int] = None ,SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : int = 1 ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Union[int, float] = 1 / 2_5_5 ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None ,SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None ,**SCREAMING_SNAKE_CASE__ : List[str] ,): super().__init__(**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = size if size is not None else {'height': 3_8_4, 'width': 3_8_4} __lowerCamelCase : str = get_size_dict(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = do_resize __lowerCamelCase : Optional[Any] = size __lowerCamelCase : Optional[Any] = keep_aspect_ratio __lowerCamelCase : List[Any] = ensure_multiple_of __lowerCamelCase : Any = resample __lowerCamelCase : Union[str, Any] = do_rescale __lowerCamelCase : Tuple = rescale_factor __lowerCamelCase : List[Any] = do_normalize __lowerCamelCase : Optional[Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __lowerCamelCase : List[str] = image_std if image_std is not None else IMAGENET_STANDARD_STD def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : np.ndarray ,SCREAMING_SNAKE_CASE__ : Dict[str, int] ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : int = 1 ,SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None ,**SCREAMING_SNAKE_CASE__ : Any ,): __lowerCamelCase : Tuple = get_size_dict(SCREAMING_SNAKE_CASE__) if "height" not in size or "width" not in size: raise ValueError(F"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}") __lowerCamelCase : Tuple = get_resize_output_image_size( SCREAMING_SNAKE_CASE__ ,output_size=(size['height'], size['width']) ,keep_aspect_ratio=SCREAMING_SNAKE_CASE__ ,multiple=SCREAMING_SNAKE_CASE__ ,) return resize(SCREAMING_SNAKE_CASE__ ,size=SCREAMING_SNAKE_CASE__ ,resample=SCREAMING_SNAKE_CASE__ ,data_format=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : np.ndarray ,SCREAMING_SNAKE_CASE__ : Union[int, float] ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None ,**SCREAMING_SNAKE_CASE__ : Optional[int] ,): return rescale(SCREAMING_SNAKE_CASE__ ,scale=SCREAMING_SNAKE_CASE__ ,data_format=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : np.ndarray ,SCREAMING_SNAKE_CASE__ : Union[float, List[float]] ,SCREAMING_SNAKE_CASE__ : Union[float, List[float]] ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None ,**SCREAMING_SNAKE_CASE__ : str ,): return normalize(SCREAMING_SNAKE_CASE__ ,mean=SCREAMING_SNAKE_CASE__ ,std=SCREAMING_SNAKE_CASE__ ,data_format=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : ImageInput ,SCREAMING_SNAKE_CASE__ : bool = None ,SCREAMING_SNAKE_CASE__ : int = None ,SCREAMING_SNAKE_CASE__ : bool = None ,SCREAMING_SNAKE_CASE__ : int = None ,SCREAMING_SNAKE_CASE__ : PILImageResampling = None ,SCREAMING_SNAKE_CASE__ : bool = None ,SCREAMING_SNAKE_CASE__ : float = None ,SCREAMING_SNAKE_CASE__ : bool = None ,SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None ,SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None ,SCREAMING_SNAKE_CASE__ : ChannelDimension = ChannelDimension.FIRST ,**SCREAMING_SNAKE_CASE__ : Union[str, Any] ,): __lowerCamelCase : List[Any] = do_resize if do_resize is not None else self.do_resize __lowerCamelCase : Tuple = size if size is not None else self.size __lowerCamelCase : Dict = get_size_dict(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio __lowerCamelCase : Dict = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of __lowerCamelCase : Optional[int] = resample if resample is not None else self.resample __lowerCamelCase : Optional[Any] = do_rescale if do_rescale is not None else self.do_rescale __lowerCamelCase : int = rescale_factor if rescale_factor is not None else self.rescale_factor __lowerCamelCase : int = do_normalize if do_normalize is not None else self.do_normalize __lowerCamelCase : List[Any] = image_mean if image_mean is not None else self.image_mean __lowerCamelCase : Dict = image_std if image_std is not None else self.image_std __lowerCamelCase : Tuple = make_list_of_images(SCREAMING_SNAKE_CASE__) if not valid_images(SCREAMING_SNAKE_CASE__): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.') if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.') if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.') if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.') # All transformations expect numpy arrays. __lowerCamelCase : Dict = [to_numpy_array(SCREAMING_SNAKE_CASE__) for image in images] if do_resize: __lowerCamelCase : Union[str, Any] = [self.resize(image=SCREAMING_SNAKE_CASE__ ,size=SCREAMING_SNAKE_CASE__ ,resample=SCREAMING_SNAKE_CASE__) for image in images] if do_rescale: __lowerCamelCase : Union[str, Any] = [self.rescale(image=SCREAMING_SNAKE_CASE__ ,scale=SCREAMING_SNAKE_CASE__) for image in images] if do_normalize: __lowerCamelCase : Dict = [self.normalize(image=SCREAMING_SNAKE_CASE__ ,mean=SCREAMING_SNAKE_CASE__ ,std=SCREAMING_SNAKE_CASE__) for image in images] __lowerCamelCase : Optional[int] = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) for image in images] __lowerCamelCase : Union[str, Any] = {'pixel_values': images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ ,tensor_type=SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : List[Tuple] = None): __lowerCamelCase : Union[str, Any] = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(SCREAMING_SNAKE_CASE__) != len(SCREAMING_SNAKE_CASE__): raise ValueError( 'Make sure that you pass in as many target sizes as the batch dimension of the logits') if is_torch_tensor(SCREAMING_SNAKE_CASE__): __lowerCamelCase : List[str] = target_sizes.numpy() __lowerCamelCase : Any = [] for idx in range(len(SCREAMING_SNAKE_CASE__)): __lowerCamelCase : Tuple = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0) ,size=target_sizes[idx] ,mode='bilinear' ,align_corners=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = resized_logits[0].argmax(dim=0) semantic_segmentation.append(SCREAMING_SNAKE_CASE__) else: __lowerCamelCase : List[Any] = logits.argmax(dim=1) __lowerCamelCase : List[Any] = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])] return semantic_segmentation
73
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : List[Any] = '''AutoImageProcessor''' _UpperCAmelCase : Dict = '''AutoTokenizer''' def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : List[Any]=None ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : List[str] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' ,SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Union[str, Any] = kwargs.pop('feature_extractor') __lowerCamelCase : Dict = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.') if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.') super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.image_processor __lowerCamelCase : Optional[int] = False def __call__( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = kwargs.pop('images' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = kwargs.pop('text' ,SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__) > 0: __lowerCamelCase : int = args[0] __lowerCamelCase : List[str] = args[1:] if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.') if images is not None: __lowerCamelCase : Optional[int] = self.image_processor(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None: __lowerCamelCase : List[Any] = self.tokenizer(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : Optional[Any] = encodings['input_ids'] return inputs def lowerCAmelCase ( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any] ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : Any): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @contextmanager def lowerCAmelCase ( self : Tuple): warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your images inputs, or in a separate call.') __lowerCamelCase : List[Any] = True __lowerCamelCase : str = self.tokenizer yield __lowerCamelCase : Tuple = self.image_processor __lowerCamelCase : Tuple = False def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int=False ,SCREAMING_SNAKE_CASE__ : List[Any]=None): if added_vocab is None: __lowerCamelCase : str = self.tokenizer.get_added_vocab() __lowerCamelCase : Union[str, Any] = {} while tokens: __lowerCamelCase : Tuple = re.search(R'<s_(.*?)>' ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if start_token is None: break __lowerCamelCase : Dict = start_token.group(1) __lowerCamelCase : List[str] = re.search(RF"</s_{key}>" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) __lowerCamelCase : Optional[int] = start_token.group() if end_token is None: __lowerCamelCase : List[Any] = tokens.replace(SCREAMING_SNAKE_CASE__ ,'') else: __lowerCamelCase : Tuple = end_token.group() __lowerCamelCase : int = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = re.search(F"{start_token_escaped}(.*?){end_token_escaped}" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if content is not None: __lowerCamelCase : List[Any] = content.group(1).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node __lowerCamelCase : str = self.tokenajson(SCREAMING_SNAKE_CASE__ ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if value: if len(SCREAMING_SNAKE_CASE__) == 1: __lowerCamelCase : Tuple = value[0] __lowerCamelCase : int = value else: # leaf nodes __lowerCamelCase : Tuple = [] for leaf in content.split(R'<sep/>'): __lowerCamelCase : List[Any] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": __lowerCamelCase : str = leaf[1:-2] # for categorical special tokens output[key].append(SCREAMING_SNAKE_CASE__) if len(output[key]) == 1: __lowerCamelCase : Dict = output[key][0] __lowerCamelCase : Dict = tokens[tokens.find(SCREAMING_SNAKE_CASE__) + len(SCREAMING_SNAKE_CASE__) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def lowerCAmelCase ( self : List[str]): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor_class @property def lowerCAmelCase ( self : List[Any]): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor
73
1
"""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_model_parallelism.py", "model_name_or_path": "roberta-large", "instance_type": "ml.p3dn.24xlarge", "results": {"train_runtime": 1_6_0_0, "eval_accuracy": 0.3, "eval_loss": 1.2}, }, { "framework": "pytorch", "script": "run_glue.py", "model_name_or_path": "roberta-large", "instance_type": "ml.p3dn.24xlarge", "results": {"train_runtime": 1_6_0_0, "eval_accuracy": 0.3, "eval_loss": 1.2}, }, ] ) class UpperCamelCase ( unittest.TestCase ): def a_ ( self) -> Dict: 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=lowerCAmelCase__, ) assert hasattr(self, 'env') def a_ ( self, lowerCAmelCase__) -> str: # configuration for running training on smdistributed Model Parallel snake_case_ = { 'enabled': True, 'processes_per_host': 8, } snake_case_ = { 'enabled': True, 'parameters': { 'microbatches': 4, 'placement_strategy': 'spread', 'pipeline': 'interleaved', 'optimize': 'speed', 'partitions': 4, 'ddp': True, }, } snake_case_ = {'smdistributed': {'modelparallel': smp_options}, 'mpi': mpi_options} snake_case_ = 'trainer' if self.script == 'run_glue.py' else 'smtrainer' # 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=f'{self.env.base_job_name}-{instance_count}-smp-{name_extension}', instance_count=lowerCAmelCase__, instance_type=self.instance_type, debugger_hook_config=lowerCAmelCase__, hyperparameters={ **self.env.hyperparameters, 'model_name_or_path': self.model_name_or_path, 'max_steps': 500, }, metric_definitions=self.env.metric_definitions, distribution=lowerCAmelCase__, py_version='py36', ) def a_ ( self, lowerCAmelCase__) -> List[str]: TrainingJobAnalytics(lowerCAmelCase__).export_csv(f'{self.env.test_path}/{job_name}_metrics.csv') @parameterized.expand([(1,)]) def a_ ( self, lowerCAmelCase__) -> int: # create estimator snake_case_ = self.create_estimator(lowerCAmelCase__) # run training estimator.fit() # result dataframe snake_case_ = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() # extract kpis snake_case_ = list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value']) snake_case_ = list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value']) # get train time from SageMaker job, this includes starting, preprocessing, stopping snake_case_ = ( Session().describe_training_job(estimator.latest_training_job.name).get('TrainingTimeInSeconds', 99_9999) ) # 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}, lowerCAmelCase__)
312
"""simple docstring""" from __future__ import annotations import math def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> int: if depth < 0: raise ValueError('Depth cannot be less than 0' ) if len(UpperCAmelCase ) == 0: raise ValueError('Scores cannot be empty' ) if depth == height: return scores[node_index] if is_max: return max( minimax(depth + 1 , node_index * 2 , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) , minimax(depth + 1 , node_index * 2 + 1 , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) , ) return min( minimax(depth + 1 , node_index * 2 , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) , minimax(depth + 1 , node_index * 2 + 1 , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) , ) def UpperCAmelCase ( ) -> None: snake_case_ = [90, 23, 6, 33, 21, 65, 123, 34423] snake_case_ = math.log(len(UpperCAmelCase ) , 2 ) print('Optimal value : ' , end='' ) print(minimax(0 , 0 , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
312
1
import os import time from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features __snake_case : Dict =logging.get_logger(__name__) __snake_case : str =list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys()) __snake_case : Optional[int] =tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class lowerCamelCase__ : '''simple docstring''' snake_case_ =field( default=lowerCamelCase__ , metadata={"""help""": """Model type selected in the list: """ + """, """.join(lowerCamelCase__)}) snake_case_ =field( default=lowerCamelCase__ , metadata={"""help""": """The input data dir. Should contain the .json files for the SQuAD task."""}) snake_case_ =field( default=128 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) snake_case_ =field( default=128 , metadata={"""help""": """When splitting up a long document into chunks, how much stride to take between chunks."""} , ) snake_case_ =field( default=64 , metadata={ """help""": ( """The maximum number of tokens for the question. Questions longer than this will """ """be truncated to this length.""" ) } , ) snake_case_ =field( default=30 , metadata={ """help""": ( """The maximum length of an answer that can be generated. This is needed because the start """ """and end predictions are not conditioned on one another.""" ) } , ) snake_case_ =field( default=lowerCamelCase__ , metadata={"""help""": """Overwrite the cached training and evaluation sets"""}) snake_case_ =field( default=lowerCamelCase__ , metadata={"""help""": """If true, the SQuAD examples contain some that do not have an answer."""}) snake_case_ =field( default=0.0 , metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}) snake_case_ =field( default=20 , metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}) snake_case_ =field( default=0 , metadata={ """help""": ( """language id of input for language-specific xlm models (see""" """ tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)""" ) } , ) snake_case_ =field(default=1 , metadata={"""help""": """multiple threads for converting example to features"""}) class lowerCamelCase__ ( lowerCamelCase__): '''simple docstring''' snake_case_ ="""train""" snake_case_ ="""dev""" class lowerCamelCase__ ( lowerCamelCase__): '''simple docstring''' snake_case_ =42 snake_case_ =42 snake_case_ =42 snake_case_ =42 def __init__(self ,__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase = None ,__lowerCamelCase = Split.train ,__lowerCamelCase = False ,__lowerCamelCase = None ,__lowerCamelCase = "pt" ,) -> Optional[int]: """simple docstring""" lowerCAmelCase__ : List[Any] = args lowerCAmelCase__ : Union[str, Any] = is_language_sensitive lowerCAmelCase__ : List[Any] = SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor() if isinstance(__lowerCamelCase ,__lowerCamelCase ): try: lowerCAmelCase__ : Any = Split[mode] except KeyError: raise KeyError('''mode is not a valid split name''' ) lowerCAmelCase__ : Dict = mode # Load data features from cache or dataset file lowerCAmelCase__ : Any = '''v2''' if args.version_2_with_negative else '''v1''' lowerCAmelCase__ : Union[str, Any] = os.path.join( cache_dir if cache_dir is not None else args.data_dir ,f"""cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}""" ,) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. lowerCAmelCase__ : Any = cached_features_file + '''.lock''' with FileLock(__lowerCamelCase ): if os.path.exists(__lowerCamelCase ) and not args.overwrite_cache: lowerCAmelCase__ : List[Any] = time.time() lowerCAmelCase__ : List[str] = torch.load(__lowerCamelCase ) # Legacy cache files have only features, while new cache files # will have dataset and examples also. lowerCAmelCase__ : str = self.old_features['''features'''] lowerCAmelCase__ : Dict = self.old_features.get('''dataset''' ,__lowerCamelCase ) lowerCAmelCase__ : List[Any] = self.old_features.get('''examples''' ,__lowerCamelCase ) logger.info( f"""Loading features from cached file {cached_features_file} [took %.3f s]""" ,time.time() - start ) if self.dataset is None or self.examples is None: logger.warning( f"""Deleting cached file {cached_features_file} will allow dataset and examples to be cached in""" ''' future run''' ) else: if mode == Split.dev: lowerCAmelCase__ : str = self.processor.get_dev_examples(args.data_dir ) else: lowerCAmelCase__ : int = self.processor.get_train_examples(args.data_dir ) lowerCAmelCase__ , lowerCAmelCase__ : List[Any] = squad_convert_examples_to_features( examples=self.examples ,tokenizer=__lowerCamelCase ,max_seq_length=args.max_seq_length ,doc_stride=args.doc_stride ,max_query_length=args.max_query_length ,is_training=mode == Split.train ,threads=args.threads ,return_dataset=__lowerCamelCase ,) lowerCAmelCase__ : str = time.time() torch.save( {'''features''': self.features, '''dataset''': self.dataset, '''examples''': self.examples} ,__lowerCamelCase ,) # ^ This seems to take a lot of time so I want to investigate why and how we can improve. logger.info( f"""Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]""" ) def __len__(self ) -> str: """simple docstring""" return len(self.features ) def __getitem__(self ,__lowerCamelCase ) -> Dict[str, torch.Tensor]: """simple docstring""" lowerCAmelCase__ : Optional[int] = self.features[i] lowerCAmelCase__ : str = torch.tensor(feature.input_ids ,dtype=torch.long ) lowerCAmelCase__ : List[Any] = torch.tensor(feature.attention_mask ,dtype=torch.long ) lowerCAmelCase__ : Union[str, Any] = torch.tensor(feature.token_type_ids ,dtype=torch.long ) lowerCAmelCase__ : Any = torch.tensor(feature.cls_index ,dtype=torch.long ) lowerCAmelCase__ : Union[str, Any] = torch.tensor(feature.p_mask ,dtype=torch.float ) lowerCAmelCase__ : Union[str, Any] = torch.tensor(feature.is_impossible ,dtype=torch.float ) lowerCAmelCase__ : str = { '''input_ids''': input_ids, '''attention_mask''': attention_mask, '''token_type_ids''': token_type_ids, } if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]: del inputs["token_type_ids"] if self.args.model_type in ["xlnet", "xlm"]: inputs.update({'''cls_index''': cls_index, '''p_mask''': p_mask} ) if self.args.version_2_with_negative: inputs.update({'''is_impossible''': is_impossible} ) if self.is_language_sensitive: inputs.update({'''langs''': (torch.ones(input_ids.shape ,dtype=torch.intaa ) * self.args.lang_id)} ) if self.mode == Split.train: lowerCAmelCase__ : Optional[Any] = torch.tensor(feature.start_position ,dtype=torch.long ) lowerCAmelCase__ : Dict = torch.tensor(feature.end_position ,dtype=torch.long ) inputs.update({'''start_positions''': start_positions, '''end_positions''': end_positions} ) return inputs
129
from jiwer import compute_measures import datasets __snake_case : Dict ='\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n' __snake_case : Optional[Any] ='\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.\n\nThis problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.\n\nWord error rate can then be computed as:\n\nWER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n' __snake_case : Any ='\nCompute WER score of transcribed segments against references.\n\nArgs:\n references: List of references for each speech input.\n predictions: List of transcriptions to score.\n concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n (float): the word error rate\n\nExamples:\n\n >>> predictions = ["this is the prediction", "there is an other sample"]\n >>> references = ["this is the reference", "there is another one"]\n >>> wer = datasets.load_metric("wer")\n >>> wer_score = wer.compute(predictions=predictions, references=references)\n >>> print(wer_score)\n 0.5\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class lowerCamelCase__ ( datasets.Metric): '''simple docstring''' def lowerCAmelCase__ (self ) -> Optional[int]: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { '''predictions''': datasets.Value('''string''' ,id='''sequence''' ), '''references''': datasets.Value('''string''' ,id='''sequence''' ), } ) ,codebase_urls=['''https://github.com/jitsi/jiwer/'''] ,reference_urls=[ '''https://en.wikipedia.org/wiki/Word_error_rate''', ] ,) def lowerCAmelCase__ (self ,__lowerCamelCase=None ,__lowerCamelCase=None ,__lowerCamelCase=False ) -> Any: """simple docstring""" if concatenate_texts: return compute_measures(__lowerCamelCase ,__lowerCamelCase )["wer"] else: lowerCAmelCase__ : str = 0 lowerCAmelCase__ : Tuple = 0 for prediction, reference in zip(__lowerCamelCase ,__lowerCamelCase ): lowerCAmelCase__ : Dict = compute_measures(__lowerCamelCase ,__lowerCamelCase ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
129
1
import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all feature extractors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...feature_extraction_utils import FeatureExtractionMixin from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) snake_case : int = logging.get_logger(__name__) snake_case : int = OrderedDict( [ ("audio-spectrogram-transformer", "ASTFeatureExtractor"), ("beit", "BeitFeatureExtractor"), ("chinese_clip", "ChineseCLIPFeatureExtractor"), ("clap", "ClapFeatureExtractor"), ("clip", "CLIPFeatureExtractor"), ("clipseg", "ViTFeatureExtractor"), ("conditional_detr", "ConditionalDetrFeatureExtractor"), ("convnext", "ConvNextFeatureExtractor"), ("cvt", "ConvNextFeatureExtractor"), ("data2vec-audio", "Wav2Vec2FeatureExtractor"), ("data2vec-vision", "BeitFeatureExtractor"), ("deformable_detr", "DeformableDetrFeatureExtractor"), ("deit", "DeiTFeatureExtractor"), ("detr", "DetrFeatureExtractor"), ("dinat", "ViTFeatureExtractor"), ("donut-swin", "DonutFeatureExtractor"), ("dpt", "DPTFeatureExtractor"), ("encodec", "EncodecFeatureExtractor"), ("flava", "FlavaFeatureExtractor"), ("glpn", "GLPNFeatureExtractor"), ("groupvit", "CLIPFeatureExtractor"), ("hubert", "Wav2Vec2FeatureExtractor"), ("imagegpt", "ImageGPTFeatureExtractor"), ("layoutlmv2", "LayoutLMv2FeatureExtractor"), ("layoutlmv3", "LayoutLMv3FeatureExtractor"), ("levit", "LevitFeatureExtractor"), ("maskformer", "MaskFormerFeatureExtractor"), ("mctct", "MCTCTFeatureExtractor"), ("mobilenet_v1", "MobileNetV1FeatureExtractor"), ("mobilenet_v2", "MobileNetV2FeatureExtractor"), ("mobilevit", "MobileViTFeatureExtractor"), ("nat", "ViTFeatureExtractor"), ("owlvit", "OwlViTFeatureExtractor"), ("perceiver", "PerceiverFeatureExtractor"), ("poolformer", "PoolFormerFeatureExtractor"), ("regnet", "ConvNextFeatureExtractor"), ("resnet", "ConvNextFeatureExtractor"), ("segformer", "SegformerFeatureExtractor"), ("sew", "Wav2Vec2FeatureExtractor"), ("sew-d", "Wav2Vec2FeatureExtractor"), ("speech_to_text", "Speech2TextFeatureExtractor"), ("speecht5", "SpeechT5FeatureExtractor"), ("swiftformer", "ViTFeatureExtractor"), ("swin", "ViTFeatureExtractor"), ("swinv2", "ViTFeatureExtractor"), ("table-transformer", "DetrFeatureExtractor"), ("timesformer", "VideoMAEFeatureExtractor"), ("tvlt", "TvltFeatureExtractor"), ("unispeech", "Wav2Vec2FeatureExtractor"), ("unispeech-sat", "Wav2Vec2FeatureExtractor"), ("van", "ConvNextFeatureExtractor"), ("videomae", "VideoMAEFeatureExtractor"), ("vilt", "ViltFeatureExtractor"), ("vit", "ViTFeatureExtractor"), ("vit_mae", "ViTFeatureExtractor"), ("vit_msn", "ViTFeatureExtractor"), ("wav2vec2", "Wav2Vec2FeatureExtractor"), ("wav2vec2-conformer", "Wav2Vec2FeatureExtractor"), ("wavlm", "Wav2Vec2FeatureExtractor"), ("whisper", "WhisperFeatureExtractor"), ("xclip", "CLIPFeatureExtractor"), ("yolos", "YolosFeatureExtractor"), ] ) snake_case : Dict = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES) def lowerCAmelCase_ ( _snake_case : str ) -> List[str]: '''simple docstring''' for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items(): if class_name in extractors: __magic_name__ : Optional[int] = model_type_to_module_name(_snake_case ) __magic_name__ : Union[str, Any] = importlib.import_module(F'''.{module_name}''' , "transformers.models" ) try: return getattr(_snake_case , _snake_case ) except AttributeError: continue for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items(): if getattr(_snake_case , "__name__" , _snake_case ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. __magic_name__ : Union[str, Any] = importlib.import_module("transformers" ) if hasattr(_snake_case , _snake_case ): return getattr(_snake_case , _snake_case ) return None def lowerCAmelCase_ ( _snake_case : Union[str, os.PathLike] , _snake_case : Optional[Union[str, os.PathLike]] = None , _snake_case : bool = False , _snake_case : bool = False , _snake_case : Optional[Dict[str, str]] = None , _snake_case : Optional[Union[bool, str]] = None , _snake_case : Optional[str] = None , _snake_case : bool = False , **_snake_case : int , ) -> Union[str, Any]: '''simple docstring''' __magic_name__ : List[Any] = get_file_from_repo( _snake_case , _snake_case , cache_dir=_snake_case , force_download=_snake_case , resume_download=_snake_case , proxies=_snake_case , use_auth_token=_snake_case , revision=_snake_case , local_files_only=_snake_case , ) if resolved_config_file is None: logger.info( "Could not locate the feature extractor configuration file, will try to use the model config instead." ) return {} with open(_snake_case , encoding="utf-8" ) as reader: return json.load(_snake_case ) class _snake_case : def __init__( self ): raise EnvironmentError( "AutoFeatureExtractor is designed to be instantiated " "using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method." ) @classmethod @replace_list_option_in_docstrings(_a ) def SCREAMING_SNAKE_CASE ( cls , _a , **_a ): __magic_name__ : Optional[Any] = kwargs.pop("config" , _a ) __magic_name__ : List[Any] = kwargs.pop("trust_remote_code" , _a ) __magic_name__ : List[Any] = True __magic_name__ : List[Any] = FeatureExtractionMixin.get_feature_extractor_dict(_a , **_a ) __magic_name__ : Optional[Any] = config_dict.get("feature_extractor_type" , _a ) __magic_name__ : Tuple = None if "AutoFeatureExtractor" in config_dict.get("auto_map" , {} ): __magic_name__ : int = config_dict["auto_map"]["AutoFeatureExtractor"] # If we don't find the feature extractor class in the feature extractor config, let's try the model config. if feature_extractor_class is None and feature_extractor_auto_map is None: if not isinstance(_a , _a ): __magic_name__ : Dict = AutoConfig.from_pretrained(_a , **_a ) # It could be in `config.feature_extractor_type`` __magic_name__ : Union[str, Any] = getattr(_a , "feature_extractor_type" , _a ) if hasattr(_a , "auto_map" ) and "AutoFeatureExtractor" in config.auto_map: __magic_name__ : Tuple = config.auto_map["AutoFeatureExtractor"] if feature_extractor_class is not None: __magic_name__ : List[str] = feature_extractor_class_from_name(_a ) __magic_name__ : Dict = feature_extractor_auto_map is not None __magic_name__ : str = feature_extractor_class is not None or type(_a ) in FEATURE_EXTRACTOR_MAPPING __magic_name__ : Dict = resolve_trust_remote_code( _a , _a , _a , _a ) if has_remote_code and trust_remote_code: __magic_name__ : Union[str, Any] = get_class_from_dynamic_module( _a , _a , **_a ) __magic_name__ : Union[str, Any] = kwargs.pop("code_revision" , _a ) if os.path.isdir(_a ): feature_extractor_class.register_for_auto_class() return feature_extractor_class.from_dict(_a , **_a ) elif feature_extractor_class is not None: return feature_extractor_class.from_dict(_a , **_a ) # Last try: we use the FEATURE_EXTRACTOR_MAPPING. elif type(_a ) in FEATURE_EXTRACTOR_MAPPING: __magic_name__ : Dict = FEATURE_EXTRACTOR_MAPPING[type(_a )] return feature_extractor_class.from_dict(_a , **_a ) raise ValueError( f'''Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a ''' f'''`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following ''' f'''`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys() )}''' ) @staticmethod def SCREAMING_SNAKE_CASE ( _a , _a ): FEATURE_EXTRACTOR_MAPPING.register(_a , _a )
366
# coding=utf-8 # Copyright 2020 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 sys import transformers snake_case : Any = "3" print("Python version:", sys.version) print("transformers version:", transformers.__version__) 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()) print("NCCL version:", torch.cuda.nccl.version()) except ImportError: print("Torch version:", None) try: import deepspeed print("DeepSpeed version:", deepspeed.__version__) except ImportError: print("DeepSpeed version:", None) try: import tensorflow as tf print("TensorFlow version:", tf.__version__) print("TF GPUs available:", bool(tf.config.list_physical_devices("GPU"))) print("Number of TF GPUs available:", len(tf.config.list_physical_devices("GPU"))) except ImportError: print("TensorFlow version:", None)
41
0
from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class __lowerCAmelCase ( __magic_name__ ): """simple docstring""" snake_case_ = ['''vqvae'''] def __init__( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ) -> Optional[Any]: '''simple docstring''' super().__init__() self.register_modules(unet=lowerCamelCase__ , scheduler=lowerCamelCase__ , mel=lowerCamelCase__ , vqvae=lowerCamelCase__ ) def lowercase_ ( self ) -> int: '''simple docstring''' return 50 if isinstance(self.scheduler , lowerCamelCase__ ) else 1_000 @torch.no_grad() def __call__( self , lowerCamelCase__ = 1 , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = 0 , lowerCamelCase__ = 0 , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = 0 , lowerCamelCase__ = 0 , lowerCamelCase__ = None , lowerCamelCase__ = 0 , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__=True , ) -> Union[ Union[AudioPipelineOutput, ImagePipelineOutput], Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]], ]: '''simple docstring''' __lowerCamelCase = steps or self.get_default_steps() self.scheduler.set_timesteps(lowerCamelCase__ ) __lowerCamelCase = step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: __lowerCamelCase = (self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: __lowerCamelCase = randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) , generator=lowerCamelCase__ , device=self.device , ) __lowerCamelCase = noise __lowerCamelCase = None if audio_file is not None or raw_audio is not None: self.mel.load_audio(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase = self.mel.audio_slice_to_image(lowerCamelCase__ ) __lowerCamelCase = np.frombuffer(input_image.tobytes() , dtype='uint8' ).reshape( (input_image.height, input_image.width) ) __lowerCamelCase = (input_image / 255) * 2 - 1 __lowerCamelCase = torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device ) if self.vqvae is not None: __lowerCamelCase = self.vqvae.encode(torch.unsqueeze(lowerCamelCase__ , 0 ) ).latent_dist.sample( generator=lowerCamelCase__ )[0] __lowerCamelCase = self.vqvae.config.scaling_factor * input_images if start_step > 0: __lowerCamelCase = self.scheduler.add_noise(lowerCamelCase__ , lowerCamelCase__ , self.scheduler.timesteps[start_step - 1] ) __lowerCamelCase = ( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) __lowerCamelCase = int(mask_start_secs * pixels_per_second ) __lowerCamelCase = int(mask_end_secs * pixels_per_second ) __lowerCamelCase = self.scheduler.add_noise(lowerCamelCase__ , lowerCamelCase__ , torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet , lowerCamelCase__ ): __lowerCamelCase = self.unet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ )['sample'] else: __lowerCamelCase = self.unet(lowerCamelCase__ , lowerCamelCase__ )['sample'] if isinstance(self.scheduler , lowerCamelCase__ ): __lowerCamelCase = self.scheduler.step( model_output=lowerCamelCase__ , timestep=lowerCamelCase__ , sample=lowerCamelCase__ , eta=lowerCamelCase__ , generator=lowerCamelCase__ , )['prev_sample'] else: __lowerCamelCase = self.scheduler.step( model_output=lowerCamelCase__ , timestep=lowerCamelCase__ , sample=lowerCamelCase__ , generator=lowerCamelCase__ , )['prev_sample'] if mask is not None: if mask_start > 0: __lowerCamelCase = mask[:, step, :, :mask_start] if mask_end > 0: __lowerCamelCase = mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance __lowerCamelCase = 1 / self.vqvae.config.scaling_factor * images __lowerCamelCase = self.vqvae.decode(lowerCamelCase__ )['sample'] __lowerCamelCase = (images / 2 + 0.5).clamp(0 , 1 ) __lowerCamelCase = images.cpu().permute(0 , 2 , 3 , 1 ).numpy() __lowerCamelCase = (images * 255).round().astype('uint8' ) __lowerCamelCase = list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(lowerCamelCase__ , mode='RGB' ).convert('L' ) for _ in images) ) __lowerCamelCase = [self.mel.image_to_audio(lowerCamelCase__ ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(lowerCamelCase__ )[:, np.newaxis, :] ) , **ImagePipelineOutput(lowerCamelCase__ ) ) @torch.no_grad() def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ = 50 ) -> np.ndarray: '''simple docstring''' assert isinstance(self.scheduler , lowerCamelCase__ ) self.scheduler.set_timesteps(lowerCamelCase__ ) __lowerCamelCase = np.array( [np.frombuffer(image.tobytes() , dtype='uint8' ).reshape((1, image.height, image.width) ) for image in images] ) __lowerCamelCase = (sample / 255) * 2 - 1 __lowerCamelCase = torch.Tensor(lowerCamelCase__ ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ): __lowerCamelCase = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps __lowerCamelCase = self.scheduler.alphas_cumprod[t] __lowerCamelCase = ( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) __lowerCamelCase = 1 - alpha_prod_t __lowerCamelCase = self.unet(lowerCamelCase__ , lowerCamelCase__ )['sample'] __lowerCamelCase = (1 - alpha_prod_t_prev) ** 0.5 * model_output __lowerCamelCase = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) __lowerCamelCase = sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def lowercase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> torch.Tensor: '''simple docstring''' __lowerCamelCase = acos(torch.dot(torch.flatten(lowerCamelCase__ ) , torch.flatten(lowerCamelCase__ ) ) / torch.norm(lowerCamelCase__ ) / torch.norm(lowerCamelCase__ ) ) return sin((1 - alpha) * theta ) * xa / sin(lowerCamelCase__ ) + sin(alpha * theta ) * xa / sin(lowerCamelCase__ )
90
'''simple docstring''' import os from math import logaa def __lowerCamelCase ( __snake_case : str = "base_exp.txt" ) -> int: """simple docstring""" A__ : float =0 A__ : Optional[int] =0 for i, line in enumerate(open(os.path.join(os.path.dirname(__snake_case ), __snake_case ) ) ): A__ , A__ : Union[str, Any] =list(map(__snake_case, line.split(""",""" ) ) ) if x * logaa(__snake_case ) > largest: A__ : List[str] =x * logaa(__snake_case ) A__ : Any =i + 1 return result if __name__ == "__main__": print(solution())
134
0
"""simple docstring""" import logging import math import os from dataclasses import dataclass, field from glob import glob from typing import Optional from torch.utils.data import ConcatDataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_WITH_LM_HEAD_MAPPING, AutoConfig, AutoModelWithLMHead, AutoTokenizer, DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, DataCollatorForWholeWordMask, HfArgumentParser, LineByLineTextDataset, LineByLineWithRefDataset, PreTrainedTokenizer, TextDataset, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process _A = logging.getLogger(__name__) _A = list(MODEL_WITH_LM_HEAD_MAPPING.keys()) _A = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class lowerCamelCase : '''simple docstring''' SCREAMING_SNAKE_CASE = field( default=UpperCAmelCase__ , metadata={ 'help': ( 'The model checkpoint for weights initialization. Leave None if you want to train a model from' ' scratch.' ) } , ) SCREAMING_SNAKE_CASE = field( default=UpperCAmelCase__ , metadata={'help': 'If training from scratch, pass a model type from the list: ' + ', '.join(UpperCAmelCase__ )} , ) SCREAMING_SNAKE_CASE = field( default=UpperCAmelCase__ , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) SCREAMING_SNAKE_CASE = field( default=UpperCAmelCase__ , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) SCREAMING_SNAKE_CASE = field( default=UpperCAmelCase__ , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) @dataclass class lowerCamelCase : '''simple docstring''' SCREAMING_SNAKE_CASE = field( default=UpperCAmelCase__ , metadata={'help': 'The input training data file (a text file).'} ) SCREAMING_SNAKE_CASE = field( default=UpperCAmelCase__ , metadata={ 'help': ( 'The input training data files (multiple files in glob format). ' 'Very often splitting large files to smaller files can prevent tokenizer going out of memory' ) } , ) SCREAMING_SNAKE_CASE = field( default=UpperCAmelCase__ , metadata={'help': 'An optional input evaluation data file to evaluate the perplexity on (a text file).'} , ) SCREAMING_SNAKE_CASE = field( default=UpperCAmelCase__ , metadata={'help': 'An optional input train ref data file for whole word mask in Chinese.'} , ) SCREAMING_SNAKE_CASE = field( default=UpperCAmelCase__ , metadata={'help': 'An optional input eval ref data file for whole word mask in Chinese.'} , ) SCREAMING_SNAKE_CASE = field( default=UpperCAmelCase__ , metadata={'help': 'Whether distinct lines of text in the dataset are to be handled as distinct sequences.'} , ) SCREAMING_SNAKE_CASE = field( default=UpperCAmelCase__ , metadata={'help': 'Train with masked-language modeling loss instead of language modeling.'} ) SCREAMING_SNAKE_CASE = field(default=UpperCAmelCase__ , metadata={'help': 'Whether ot not to use whole word mask.'} ) SCREAMING_SNAKE_CASE = field( default=0.15 , metadata={'help': 'Ratio of tokens to mask for masked language modeling loss'} ) SCREAMING_SNAKE_CASE = field( default=1 / 6 , metadata={ 'help': ( 'Ratio of length of a span of masked tokens to surrounding context length for permutation language' ' modeling.' ) } , ) SCREAMING_SNAKE_CASE = field( default=5 , metadata={'help': 'Maximum length of a span of masked tokens for permutation language modeling.'} ) SCREAMING_SNAKE_CASE = field( default=-1 , metadata={ 'help': ( 'Optional input sequence length after tokenization.' 'The training dataset will be truncated in block of this size for training.' 'Default to the model max input length for single sentence inputs (take into account special tokens).' ) } , ) SCREAMING_SNAKE_CASE = field( default=UpperCAmelCase__ , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) def a__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = False , lowerCAmelCase = None , ) -> Dict: def _dataset(lowerCAmelCase , lowerCAmelCase=None ): if args.line_by_line: if ref_path is not None: if not args.whole_word_mask or not args.mlm: raise ValueError("""You need to set world whole masking and mlm to True for Chinese Whole Word Mask""" ) return LineByLineWithRefDataset( tokenizer=lowerCAmelCase , file_path=lowerCAmelCase , block_size=args.block_size , ref_path=lowerCAmelCase , ) return LineByLineTextDataset(tokenizer=lowerCAmelCase , file_path=lowerCAmelCase , block_size=args.block_size ) else: return TextDataset( tokenizer=lowerCAmelCase , file_path=lowerCAmelCase , block_size=args.block_size , overwrite_cache=args.overwrite_cache , cache_dir=lowerCAmelCase , ) if evaluate: return _dataset(args.eval_data_file , args.eval_ref_file ) elif args.train_data_files: return ConcatDataset([_dataset(lowerCAmelCase ) for f in glob(args.train_data_files )] ) else: return _dataset(args.train_data_file , args.train_ref_file ) def a__ ( ) -> Any: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. UpperCAmelCase__ : Any = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) UpperCAmelCase__ : List[str] = parser.parse_args_into_dataclasses() if data_args.eval_data_file is None and training_args.do_eval: raise ValueError( """Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file """ """or remove the --do_eval argument.""" ) if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" """ --overwrite_output_dir to overcome.""" ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( """Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s""" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , 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""" , lowerCAmelCase ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. if model_args.config_name: UpperCAmelCase__ : Optional[int] = AutoConfig.from_pretrained(model_args.config_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: UpperCAmelCase__ : Tuple = AutoConfig.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir ) else: UpperCAmelCase__ : Dict = CONFIG_MAPPING[model_args.model_type]() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.tokenizer_name: UpperCAmelCase__ : Any = AutoTokenizer.from_pretrained(model_args.tokenizer_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: UpperCAmelCase__ : str = AutoTokenizer.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir ) else: raise ValueError( """You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another""" """ script, save it,and load it from here, using --tokenizer_name""" ) if model_args.model_name_or_path: UpperCAmelCase__ : List[str] = AutoModelWithLMHead.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=lowerCAmelCase , cache_dir=model_args.cache_dir , ) else: logger.info("""Training new model from scratch""" ) UpperCAmelCase__ : Optional[Any] = AutoModelWithLMHead.from_config(lowerCAmelCase ) model.resize_token_embeddings(len(lowerCAmelCase ) ) if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm: raise ValueError( """BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the""" """--mlm flag (masked language modeling).""" ) if data_args.block_size <= 0: UpperCAmelCase__ : Any = tokenizer.max_len # Our input block size will be the max possible for the model else: UpperCAmelCase__ : List[str] = min(data_args.block_size , tokenizer.max_len ) # Get datasets UpperCAmelCase__ : Optional[Any] = ( get_dataset(lowerCAmelCase , tokenizer=lowerCAmelCase , cache_dir=model_args.cache_dir ) if training_args.do_train else None ) UpperCAmelCase__ : Tuple = ( get_dataset(lowerCAmelCase , tokenizer=lowerCAmelCase , evaluate=lowerCAmelCase , cache_dir=model_args.cache_dir ) if training_args.do_eval else None ) if config.model_type == "xlnet": UpperCAmelCase__ : Optional[int] = DataCollatorForPermutationLanguageModeling( tokenizer=lowerCAmelCase , plm_probability=data_args.plm_probability , max_span_length=data_args.max_span_length , ) else: if data_args.mlm and data_args.whole_word_mask: UpperCAmelCase__ : List[str] = DataCollatorForWholeWordMask( tokenizer=lowerCAmelCase , mlm_probability=data_args.mlm_probability ) else: UpperCAmelCase__ : int = DataCollatorForLanguageModeling( tokenizer=lowerCAmelCase , mlm=data_args.mlm , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer UpperCAmelCase__ : int = Trainer( model=lowerCAmelCase , args=lowerCAmelCase , data_collator=lowerCAmelCase , train_dataset=lowerCAmelCase , eval_dataset=lowerCAmelCase , prediction_loss_only=lowerCAmelCase , ) # Training if training_args.do_train: UpperCAmelCase__ : List[Any] = ( model_args.model_name_or_path if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ) else None ) trainer.train(model_path=lowerCAmelCase ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation UpperCAmelCase__ : Any = {} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) UpperCAmelCase__ : Tuple = trainer.evaluate() UpperCAmelCase__ : str = math.exp(eval_output["""eval_loss"""] ) UpperCAmelCase__ : Tuple = {"""perplexity""": perplexity} UpperCAmelCase__ : int = os.path.join(training_args.output_dir , """eval_results_lm.txt""" ) if trainer.is_world_master(): with open(lowerCAmelCase , """w""" ) as writer: logger.info("""***** Eval results *****""" ) for key in sorted(result.keys() ): logger.info(""" %s = %s""" , lowerCAmelCase , str(result[key] ) ) writer.write("""%s = %s\n""" % (key, str(result[key] )) ) results.update(lowerCAmelCase ) return results def a__ ( lowerCAmelCase ) -> List[str]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
360
"""simple docstring""" import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class lowerCamelCase ( lowerCAmelCase__ ): '''simple docstring''' def __init__(self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = dataset UpperCAmelCase__ : Union[str, Any] = process UpperCAmelCase__ : List[Any] = params def __len__(self ): """simple docstring""" return len(self.dataset ) def __getitem__(self , _lowerCamelCase ): """simple docstring""" UpperCAmelCase__ : int = self.dataset[i] UpperCAmelCase__ : Any = self.process(_lowerCamelCase , **self.params ) return processed class lowerCamelCase ( lowerCAmelCase__ ): '''simple docstring''' def __init__(self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=None ): """simple docstring""" UpperCAmelCase__ : Tuple = loader UpperCAmelCase__ : int = infer UpperCAmelCase__ : Optional[Any] = params if loader_batch_size == 1: # Let's spare some time by deactivating altogether UpperCAmelCase__ : Tuple = None UpperCAmelCase__ : Any = loader_batch_size # Internal bookkeeping UpperCAmelCase__ : Tuple = None UpperCAmelCase__ : Union[str, Any] = None def __len__(self ): """simple docstring""" return len(self.loader ) def __iter__(self ): """simple docstring""" UpperCAmelCase__ : List[str] = iter(self.loader ) return self def _a (self ): """simple docstring""" if isinstance(self._loader_batch_data , torch.Tensor ): # Batch data is simple tensor, just fetch the slice UpperCAmelCase__ : Optional[int] = self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) UpperCAmelCase__ : List[str] = {} for k, element in self._loader_batch_data.items(): if isinstance(_lowerCamelCase , _lowerCamelCase ): # Convert ModelOutput to tuple first UpperCAmelCase__ : List[Any] = element.to_tuple() if isinstance(element[0] , torch.Tensor ): UpperCAmelCase__ : str = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): UpperCAmelCase__ : List[str] = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(_lowerCamelCase , _lowerCamelCase ): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0] , torch.Tensor ): UpperCAmelCase__ : Optional[Any] = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): UpperCAmelCase__ : int = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if element is None: # This can happen for optional data that get passed around UpperCAmelCase__ : str = None elif isinstance(element[self._loader_batch_index] , torch.Tensor ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers UpperCAmelCase__ : Tuple = element[self._loader_batch_index].unsqueeze(0 ) elif isinstance(element[self._loader_batch_index] , np.ndarray ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers UpperCAmelCase__ : Dict = np.expand_dims(element[self._loader_batch_index] , 0 ) else: # This is typically a list, so no need to `unsqueeze`. UpperCAmelCase__ : Optional[Any] = element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 UpperCAmelCase__ : Union[str, Any] = self._loader_batch_data.__class__(_lowerCamelCase ) self._loader_batch_index += 1 return result def _a (self ): """simple docstring""" if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch UpperCAmelCase__ : str = next(self.iterator ) UpperCAmelCase__ : Union[str, Any] = self.infer(_lowerCamelCase , **self.params ) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(_lowerCamelCase , torch.Tensor ): UpperCAmelCase__ : List[Any] = processed else: UpperCAmelCase__ : List[str] = list(processed.keys() )[0] UpperCAmelCase__ : List[str] = processed[key] if isinstance(_lowerCamelCase , _lowerCamelCase ): UpperCAmelCase__ : Any = len(_lowerCamelCase ) else: UpperCAmelCase__ : Union[str, Any] = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. UpperCAmelCase__ : Optional[int] = observed_batch_size # Setting internal index to unwrap the batch UpperCAmelCase__ : List[Any] = processed UpperCAmelCase__ : Optional[int] = 0 return self.loader_batch_item() else: # We're not unrolling batches return processed class lowerCamelCase ( lowerCAmelCase__ ): '''simple docstring''' def __init__(self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=None ): """simple docstring""" super().__init__(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def __iter__(self ): """simple docstring""" UpperCAmelCase__ : Tuple = iter(self.loader ) UpperCAmelCase__ : List[Any] = None return self def _a (self ): """simple docstring""" if self.subiterator is None: UpperCAmelCase__ : Optional[Any] = self.infer(next(self.iterator ) , **self.params ) try: # Try to return next item UpperCAmelCase__ : List[str] = next(self.subiterator ) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators UpperCAmelCase__ : Optional[Any] = self.infer(next(self.iterator ) , **self.params ) UpperCAmelCase__ : List[str] = next(self.subiterator ) return processed class lowerCamelCase ( lowerCAmelCase__ ): '''simple docstring''' def __iter__(self ): """simple docstring""" UpperCAmelCase__ : str = iter(self.loader ) return self def _a (self ): """simple docstring""" UpperCAmelCase__ : Optional[int] = False UpperCAmelCase__ : List[str] = [] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: UpperCAmelCase__ : List[Any] = self.loader_batch_item() UpperCAmelCase__ : Dict = item.pop("""is_last""" ) accumulator.append(_lowerCamelCase ) if is_last: return accumulator while not is_last: UpperCAmelCase__ : List[str] = self.infer(next(self.iterator ) , **self.params ) if self.loader_batch_size is not None: if isinstance(_lowerCamelCase , torch.Tensor ): UpperCAmelCase__ : Dict = processed else: UpperCAmelCase__ : List[Any] = list(processed.keys() )[0] UpperCAmelCase__ : List[Any] = processed[key] if isinstance(_lowerCamelCase , _lowerCamelCase ): UpperCAmelCase__ : int = len(_lowerCamelCase ) else: UpperCAmelCase__ : List[Any] = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. UpperCAmelCase__ : str = observed_batch_size UpperCAmelCase__ : Union[str, Any] = processed UpperCAmelCase__ : List[Any] = 0 while self._loader_batch_index < self.loader_batch_size: UpperCAmelCase__ : Union[str, Any] = self.loader_batch_item() UpperCAmelCase__ : int = item.pop("""is_last""" ) accumulator.append(_lowerCamelCase ) if is_last: return accumulator else: UpperCAmelCase__ : Any = processed UpperCAmelCase__ : Any = item.pop("""is_last""" ) accumulator.append(_lowerCamelCase ) return accumulator class lowerCamelCase ( lowerCAmelCase__ ): '''simple docstring''' def __init__(self , _lowerCamelCase , _lowerCamelCase ): """simple docstring""" UpperCAmelCase__ : List[Any] = dataset UpperCAmelCase__ : Union[str, Any] = key def __len__(self ): """simple docstring""" return len(self.dataset ) def __getitem__(self , _lowerCamelCase ): """simple docstring""" return self.dataset[i][self.key] class lowerCamelCase ( lowerCAmelCase__ ): '''simple docstring''' def __init__(self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): """simple docstring""" UpperCAmelCase__ : int = dataset UpperCAmelCase__ : Any = keya UpperCAmelCase__ : str = keya def __len__(self ): """simple docstring""" return len(self.dataset ) def __getitem__(self , _lowerCamelCase ): """simple docstring""" return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
166
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available snake_case : List[Any] = { '''configuration_conditional_detr''': [ '''CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ConditionalDetrConfig''', '''ConditionalDetrOnnxConfig''', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case : str = ['''ConditionalDetrFeatureExtractor'''] snake_case : List[str] = ['''ConditionalDetrImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case : str = [ '''CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ConditionalDetrForObjectDetection''', '''ConditionalDetrForSegmentation''', '''ConditionalDetrModel''', '''ConditionalDetrPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, ConditionalDetrConfig, ConditionalDetrOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_conditional_detr import ConditionalDetrFeatureExtractor from .image_processing_conditional_detr import ConditionalDetrImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST, ConditionalDetrForObjectDetection, ConditionalDetrForSegmentation, ConditionalDetrModel, ConditionalDetrPreTrainedModel, ) else: import sys snake_case : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
94
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging snake_case : Dict = logging.get_logger(__name__) snake_case : Tuple = '''▁''' snake_case : Any = {'''vocab_file''': '''sentencepiece.bpe.model'''} snake_case : Tuple = { '''vocab_file''': { '''xlm-roberta-base''': '''https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model''', '''xlm-roberta-large''': '''https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model''', '''xlm-roberta-large-finetuned-conll02-dutch''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model''' ), '''xlm-roberta-large-finetuned-conll02-spanish''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model''' ), '''xlm-roberta-large-finetuned-conll03-english''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model''' ), '''xlm-roberta-large-finetuned-conll03-german''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model''' ), } } snake_case : int = { '''xlm-roberta-base''': 5_12, '''xlm-roberta-large''': 5_12, '''xlm-roberta-large-finetuned-conll02-dutch''': 5_12, '''xlm-roberta-large-finetuned-conll02-spanish''': 5_12, '''xlm-roberta-large-finetuned-conll03-english''': 5_12, '''xlm-roberta-large-finetuned-conll03-german''': 5_12, } class _snake_case ( _snake_case ): SCREAMING_SNAKE_CASE__ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ = ['input_ids', 'attention_mask'] def __init__( self , _lowerCamelCase , _lowerCamelCase="<s>" , _lowerCamelCase="</s>" , _lowerCamelCase="</s>" , _lowerCamelCase="<s>" , _lowerCamelCase="<unk>" , _lowerCamelCase="<pad>" , _lowerCamelCase="<mask>" , _lowerCamelCase = None , **_lowerCamelCase , ): # Mask token behave like a normal word, i.e. include the space before it a :Optional[int] = AddedToken(_lowerCamelCase , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else mask_token a :int = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , sep_token=_lowerCamelCase , cls_token=_lowerCamelCase , pad_token=_lowerCamelCase , mask_token=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **_lowerCamelCase , ) a :Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_lowerCamelCase ) ) a :str = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token a :Tuple = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab a :List[str] = 1 a :Dict = len(self.sp_model ) + self.fairseq_offset a :List[Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ): a :List[str] = self.__dict__.copy() a :Optional[int] = None a :int = self.sp_model.serialized_model_proto() return state def __setstate__( self , _lowerCamelCase ): a :Union[str, Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a :Union[str, Any] = {} a :Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a :List[Any] = [self.cls_token_id] a :Dict = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) if token_ids_a is None: return [1] + ([0] * len(_lowerCamelCase )) + [1] return [1] + ([0] * len(_lowerCamelCase )) + [1, 1] + ([0] * len(_lowerCamelCase )) + [1] def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase = None ): a :int = [self.sep_token_id] a :int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def SCREAMING_SNAKE_CASE__ ( self ): return len(self.sp_model ) + self.fairseq_offset + 1 # Add the <mask> token def SCREAMING_SNAKE_CASE__ ( self ): a :Any = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase ): return self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] a :Optional[Any] = self.sp_model.PieceToId(_lowerCamelCase ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase ): if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase ): a :Tuple = ''''''.join(_lowerCamelCase ).replace(_lowerCamelCase , ''' ''' ).strip() return out_string def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase = None ): if not os.path.isdir(_lowerCamelCase ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return a :int = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: a :List[Any] = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
94
1
import os def SCREAMING_SNAKE_CASE__ ( ) -> Tuple: with open(os.path.dirname(lowercase ) + """/p022_names.txt""" ) as file: snake_case : Optional[int] = str(file.readlines()[0] ) snake_case : int = names.replace("""\"""" ,"""""" ).split(""",""" ) names.sort() snake_case : Any = 0 snake_case : Tuple = 0 for i, name in enumerate(lowercase ): for letter in name: name_score += ord(lowercase ) - 64 total_score += (i + 1) * name_score snake_case : List[Any] = 0 return total_score if __name__ == "__main__": print(solution())
176
from math import pow def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ,lowercase ,lowercase ,lowercase ,) -> tuple[int, int]: if current_sum == needed_sum: # If the sum of the powers is equal to needed_sum, then we have a solution. solutions_count += 1 return current_sum, solutions_count snake_case : Union[str, Any] = int(pow(lowercase ,lowercase ) ) if current_sum + i_to_n <= needed_sum: # If the sum of the powers is less than needed_sum, then continue adding powers. current_sum += i_to_n snake_case , snake_case : List[Any] = backtrack( lowercase ,lowercase ,current_number + 1 ,lowercase ,lowercase ) current_sum -= i_to_n if i_to_n < needed_sum: # If the power of i is less than needed_sum, then try with the next power. snake_case , snake_case : str = backtrack( lowercase ,lowercase ,current_number + 1 ,lowercase ,lowercase ) return current_sum, solutions_count def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ) -> int: if not (1 <= needed_sum <= 1000 and 2 <= power <= 10): raise ValueError( """Invalid input\n""" """needed_sum must be between 1 and 1000, power between 2 and 10.""" ) return backtrack(lowercase ,lowercase ,1 ,0 ,0 )[1] # Return the solutions_count if __name__ == "__main__": import doctest doctest.testmod()
176
1
from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class snake_case_ ( __A ): '''simple docstring''' def __init__( self : int , _UpperCamelCase : pyspark.sql.DataFrame , _UpperCamelCase : Optional[NamedSplit] = None , _UpperCamelCase : Optional[Features] = None , _UpperCamelCase : bool = True , _UpperCamelCase : str = None , _UpperCamelCase : bool = False , _UpperCamelCase : str = None , _UpperCamelCase : bool = True , _UpperCamelCase : str = "arrow" , **_UpperCamelCase : Tuple , ) ->str: super().__init__( split=_UpperCamelCase , features=_UpperCamelCase , cache_dir=_UpperCamelCase , keep_in_memory=_UpperCamelCase , streaming=_UpperCamelCase , **_UpperCamelCase , ) snake_case_ = load_from_cache_file snake_case_ = file_format snake_case_ = Spark( df=_UpperCamelCase , features=_UpperCamelCase , cache_dir=_UpperCamelCase , working_dir=_UpperCamelCase , **_UpperCamelCase , ) def snake_case__( self : int ) ->Tuple: if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) snake_case_ = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=_UpperCamelCase , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
8
from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class snake_case_ ( __A ): '''simple docstring''' def __init__( self : int , _UpperCamelCase : pyspark.sql.DataFrame , _UpperCamelCase : Optional[NamedSplit] = None , _UpperCamelCase : Optional[Features] = None , _UpperCamelCase : bool = True , _UpperCamelCase : str = None , _UpperCamelCase : bool = False , _UpperCamelCase : str = None , _UpperCamelCase : bool = True , _UpperCamelCase : str = "arrow" , **_UpperCamelCase : Tuple , ) ->str: super().__init__( split=_UpperCamelCase , features=_UpperCamelCase , cache_dir=_UpperCamelCase , keep_in_memory=_UpperCamelCase , streaming=_UpperCamelCase , **_UpperCamelCase , ) snake_case_ = load_from_cache_file snake_case_ = file_format snake_case_ = Spark( df=_UpperCamelCase , features=_UpperCamelCase , cache_dir=_UpperCamelCase , working_dir=_UpperCamelCase , **_UpperCamelCase , ) def snake_case__( self : int ) ->Tuple: if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) snake_case_ = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=_UpperCamelCase , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
8
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) a_ : Optional[int] = { 'configuration_perceiver': ['PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PerceiverConfig', 'PerceiverOnnxConfig'], 'tokenization_perceiver': ['PerceiverTokenizer'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = ['PerceiverFeatureExtractor'] a_ : Optional[int] = ['PerceiverImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Tuple = [ 'PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST', 'PerceiverForImageClassificationConvProcessing', 'PerceiverForImageClassificationFourier', 'PerceiverForImageClassificationLearned', 'PerceiverForMaskedLM', 'PerceiverForMultimodalAutoencoding', 'PerceiverForOpticalFlow', 'PerceiverForSequenceClassification', 'PerceiverLayer', 'PerceiverModel', 'PerceiverPreTrainedModel', ] if TYPE_CHECKING: from .configuration_perceiver import PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP, PerceiverConfig, PerceiverOnnxConfig from .tokenization_perceiver import PerceiverTokenizer try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_perceiver import PerceiverFeatureExtractor from .image_processing_perceiver import PerceiverImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_perceiver import ( PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST, PerceiverForImageClassificationConvProcessing, PerceiverForImageClassificationFourier, PerceiverForImageClassificationLearned, PerceiverForMaskedLM, PerceiverForMultimodalAutoencoding, PerceiverForOpticalFlow, PerceiverForSequenceClassification, PerceiverLayer, PerceiverModel, PerceiverPreTrainedModel, ) else: import sys a_ : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
327
import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline @require_flax class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: with tempfile.TemporaryDirectory() as tmpdirname: # pipeline has Flax weights SCREAMING_SNAKE_CASE = FlaxDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=a , cache_dir=a) SCREAMING_SNAKE_CASE = [t[-1] for t in os.walk(os.path.join(a , os.listdir(a)[0] , 'snapshots'))] SCREAMING_SNAKE_CASE = [item for sublist in all_root_files for item in sublist] # None of the downloaded files should be a PyTorch file even if we have some here: # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin assert not any(f.endswith('.bin') for f in files) @slow @require_flax class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 4 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 64, 64, 3) if jax.device_count() == 8: assert np.abs(np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 4.1_51_47_45) < 1E-3 assert np.abs(np.abs(a , dtype=np.floataa).sum() - 4_99_47.8_75) < 5E-1 SCREAMING_SNAKE_CASE = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:]))) assert len(a) == num_samples def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='flax' , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.05_65_24_01)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_38_38_08.2)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.04_00_39_06)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_37_35_16.75)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.04_00_39_06)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_37_35_16.75)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = FlaxDDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , set_alpha_to_one=a , steps_offset=1 , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , scheduler=a , safety_checker=a , ) SCREAMING_SNAKE_CASE = scheduler.create_state() SCREAMING_SNAKE_CASE = scheduler_state SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.0_45_04_39_45)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_34_76_93.5)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = jax.random.split(jax.random.PRNGKey(0) , a) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a , ) SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) SCREAMING_SNAKE_CASE = images[2, 0, 256, 10:17, 1] # With memory efficient attention SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a , use_memory_efficient_attention=a , ) SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , jit=a).images assert images_eff.shape == (num_samples, 1, 512, 512, 3) SCREAMING_SNAKE_CASE = images[2, 0, 256, 10:17, 1] # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum` # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now. assert abs(slice_eff - slice).max() < 1E-2
327
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available A_ : Optional[Any] = { 'configuration_bridgetower': [ 'BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BridgeTowerConfig', 'BridgeTowerTextConfig', 'BridgeTowerVisionConfig', ], 'processing_bridgetower': ['BridgeTowerProcessor'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Optional[int] = ['BridgeTowerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : List[Any] = [ 'BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST', 'BridgeTowerForContrastiveLearning', 'BridgeTowerForImageAndTextRetrieval', 'BridgeTowerForMaskedLM', 'BridgeTowerModel', 'BridgeTowerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_bridgetower import ( BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP, BridgeTowerConfig, BridgeTowerTextConfig, BridgeTowerVisionConfig, ) from .processing_bridgetower import BridgeTowerProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_bridgetower import BridgeTowerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bridgetower import ( BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST, BridgeTowerForContrastiveLearning, BridgeTowerForImageAndTextRetrieval, BridgeTowerForMaskedLM, BridgeTowerModel, BridgeTowerPreTrainedModel, ) else: import sys A_ : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure)
192
def UpperCamelCase (lowercase_: int = 10 ) -> str: if not isinstance(lowercase_ , lowercase_ ) or n < 0: raise ValueError("""Invalid input""" ) A__ : List[str] = 10**n A__ : Any = 28433 * (pow(2 , 7830457 , lowercase_ )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(f'''{solution(10) = }''')
192
1
'''simple docstring''' from __future__ import annotations from random import random from typing import Generic, TypeVar a_ : Optional[Any] = TypeVar("KT") a_ : List[str] = TypeVar("VT") class a ( Generic[KT, VT] ): def __init__( self , __magic_name__ = "root" , __magic_name__ = None ) -> Any: _a = key _a = value _a = [] def __repr__( self ) -> str: return f'Node({self.key}: {self.value})' @property def __UpperCAmelCase ( self ) -> int: return len(self.forward ) class a ( Generic[KT, VT] ): def __init__( self , __magic_name__ = 0.5 , __magic_name__ = 16 ) -> Tuple: _a = Node[KT, VT]() _a = 0 _a = p _a = max_level def __str__( self ) -> str: _a = list(self ) if len(__magic_name__ ) == 0: return f'SkipList(level={self.level})' _a = max((len(str(__magic_name__ ) ) for item in items) , default=4 ) _a = max(__magic_name__ , 4 ) + 4 _a = self.head _a = [] _a = node.forward.copy() lines.append(f'[{node.key}]'.ljust(__magic_name__ , '-' ) + '* ' * len(__magic_name__ ) ) lines.append(' ' * label_size + '| ' * len(__magic_name__ ) ) while len(node.forward ) != 0: _a = node.forward[0] lines.append( f'[{node.key}]'.ljust(__magic_name__ , '-' ) + ' '.join(str(n.key ) if n.key == node.key else '|' for n in forwards ) ) lines.append(' ' * label_size + '| ' * len(__magic_name__ ) ) _a = node.forward lines.append('None'.ljust(__magic_name__ ) + '* ' * len(__magic_name__ ) ) return f'SkipList(level={self.level})\n' + "\n".join(__magic_name__ ) def __iter__( self ) -> Union[str, Any]: _a = self.head while len(node.forward ) != 0: yield node.forward[0].key _a = node.forward[0] def __UpperCAmelCase ( self ) -> int: _a = 1 while random() < self.p and level < self.max_level: level += 1 return level def __UpperCAmelCase ( self , __magic_name__ ) -> tuple[Node[KT, VT] | None, list[Node[KT, VT]]]: _a = [] _a = self.head for i in reversed(range(self.level ) ): # i < node.level - When node level is lesser than `i` decrement `i`. # node.forward[i].key < key - Jumping to node with key value higher # or equal to searched key would result # in skipping searched key. while i < node.level and node.forward[i].key < key: _a = node.forward[i] # Each leftmost node (relative to searched node) will potentially have to # be updated. update_vector.append(__magic_name__ ) update_vector.reverse() # Note that we were inserting values in reverse order. # len(node.forward) != 0 - If current node doesn't contain any further # references then searched key is not present. # node.forward[0].key == key - Next node key should be equal to search key # if key is present. if len(node.forward ) != 0 and node.forward[0].key == key: return node.forward[0], update_vector else: return None, update_vector def __UpperCAmelCase ( self , __magic_name__ ) -> str: _a , _a = self._locate_node(__magic_name__ ) if node is not None: for i, update_node in enumerate(__magic_name__ ): # Remove or replace all references to removed node. if update_node.level > i and update_node.forward[i].key == key: if node.level > i: _a = node.forward[i] else: _a = update_node.forward[:i] def __UpperCAmelCase ( self , __magic_name__ , __magic_name__ ) -> Optional[Any]: _a , _a = self._locate_node(__magic_name__ ) if node is not None: _a = value else: _a = self.random_level() if level > self.level: # After level increase we have to add additional nodes to head. for _ in range(self.level - 1 , __magic_name__ ): update_vector.append(self.head ) _a = level _a = Node(__magic_name__ , __magic_name__ ) for i, update_node in enumerate(update_vector[:level] ): # Change references to pass through new node. if update_node.level > i: new_node.forward.append(update_node.forward[i] ) if update_node.level < i + 1: update_node.forward.append(__magic_name__ ) else: _a = new_node def __UpperCAmelCase ( self , __magic_name__ ) -> VT | None: _a , _a = self._locate_node(__magic_name__ ) if node is not None: return node.value return None def _A () -> Optional[int]: '''simple docstring''' _a = SkipList() skip_list.insert('Key1' , 3 ) skip_list.insert('Key2' , 12 ) skip_list.insert('Key3' , 41 ) skip_list.insert('Key4' , -19 ) _a = skip_list.head _a = {} while node.level != 0: _a = node.forward[0] _a = node.value assert len(lowerCAmelCase__ ) == 4 assert all_values["Key1"] == 3 assert all_values["Key2"] == 12 assert all_values["Key3"] == 41 assert all_values["Key4"] == -19 def _A () -> Union[str, Any]: '''simple docstring''' _a = SkipList() skip_list.insert('Key1' , 10 ) skip_list.insert('Key1' , 12 ) skip_list.insert('Key5' , 7 ) skip_list.insert('Key7' , 10 ) skip_list.insert('Key10' , 5 ) skip_list.insert('Key7' , 7 ) skip_list.insert('Key5' , 5 ) skip_list.insert('Key10' , 10 ) _a = skip_list.head _a = {} while node.level != 0: _a = node.forward[0] _a = node.value if len(lowerCAmelCase__ ) != 4: print() assert len(lowerCAmelCase__ ) == 4 assert all_values["Key1"] == 12 assert all_values["Key7"] == 7 assert all_values["Key5"] == 5 assert all_values["Key10"] == 10 def _A () -> List[str]: '''simple docstring''' _a = SkipList() assert skip_list.find('Some key' ) is None def _A () -> Any: '''simple docstring''' _a = SkipList() skip_list.insert('Key2' , 20 ) assert skip_list.find('Key2' ) == 20 skip_list.insert('Some Key' , 10 ) skip_list.insert('Key2' , 8 ) skip_list.insert('V' , 13 ) assert skip_list.find('Y' ) is None assert skip_list.find('Key2' ) == 8 assert skip_list.find('Some Key' ) == 10 assert skip_list.find('V' ) == 13 def _A () -> Dict: '''simple docstring''' _a = SkipList() skip_list.delete('Some key' ) assert len(skip_list.head.forward ) == 0 def _A () -> Any: '''simple docstring''' _a = SkipList() skip_list.insert('Key1' , 12 ) skip_list.insert('V' , 13 ) skip_list.insert('X' , 14 ) skip_list.insert('Key2' , 15 ) skip_list.delete('V' ) skip_list.delete('Key2' ) assert skip_list.find('V' ) is None assert skip_list.find('Key2' ) is None def _A () -> Any: '''simple docstring''' _a = SkipList() skip_list.insert('Key1' , 12 ) skip_list.insert('V' , 13 ) skip_list.insert('X' , 14 ) skip_list.insert('Key2' , 15 ) skip_list.delete('V' ) assert skip_list.find('V' ) is None assert skip_list.find('X' ) == 14 assert skip_list.find('Key1' ) == 12 assert skip_list.find('Key2' ) == 15 skip_list.delete('X' ) assert skip_list.find('V' ) is None assert skip_list.find('X' ) is None assert skip_list.find('Key1' ) == 12 assert skip_list.find('Key2' ) == 15 skip_list.delete('Key1' ) assert skip_list.find('V' ) is None assert skip_list.find('X' ) is None assert skip_list.find('Key1' ) is None assert skip_list.find('Key2' ) == 15 skip_list.delete('Key2' ) assert skip_list.find('V' ) is None assert skip_list.find('X' ) is None assert skip_list.find('Key1' ) is None assert skip_list.find('Key2' ) is None def _A () -> List[Any]: '''simple docstring''' _a = SkipList() skip_list.insert('Key1' , 12 ) skip_list.insert('V' , 13 ) skip_list.insert('X' , 1_42 ) skip_list.insert('Key2' , 15 ) skip_list.delete('X' ) def traverse_keys(lowerCAmelCase__ :Any ): yield node.key for forward_node in node.forward: yield from traverse_keys(lowerCAmelCase__ ) assert len(set(traverse_keys(skip_list.head ) ) ) == 4 def _A () -> Any: '''simple docstring''' def is_sorted(lowerCAmelCase__ :int ): return all(next_item >= item for item, next_item in zip(lowerCAmelCase__ , lst[1:] ) ) _a = SkipList() for i in range(10 ): skip_list.insert(lowerCAmelCase__ , lowerCAmelCase__ ) assert is_sorted(list(lowerCAmelCase__ ) ) skip_list.delete(5 ) skip_list.delete(8 ) skip_list.delete(2 ) assert is_sorted(list(lowerCAmelCase__ ) ) skip_list.insert(-12 , -12 ) skip_list.insert(77 , 77 ) assert is_sorted(list(lowerCAmelCase__ ) ) def _A () -> int: '''simple docstring''' for _ in range(1_00 ): # Repeat test 100 times due to the probabilistic nature of skip list # random values == random bugs test_insert() test_insert_overrides_existing_value() test_searching_empty_list_returns_none() test_search() test_deleting_item_from_empty_list_do_nothing() test_deleted_items_are_not_founded_by_find_method() test_delete_removes_only_given_key() test_delete_doesnt_leave_dead_nodes() test_iter_always_yields_sorted_values() def _A () -> str: '''simple docstring''' _a = SkipList() skip_list.insert(2 , '2' ) skip_list.insert(4 , '4' ) skip_list.insert(6 , '4' ) skip_list.insert(4 , '5' ) skip_list.insert(8 , '4' ) skip_list.insert(9 , '4' ) skip_list.delete(4 ) print(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod() main()
104
'''simple docstring''' import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoImageProcessor, ViTImageProcessor from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_image_processing import CustomImageProcessor # noqa E402 a_ : Tuple = get_tests_dir("fixtures") class a ( unittest.TestCase ): def __UpperCAmelCase ( self ) -> str: # A mock response for an HTTP head request to emulate server down _a = mock.Mock() _a = 5_00 _a = {} _a = HTTPError _a = {} # Download this model to make sure it's in the cache. _a = ViTImageProcessor.from_pretrained('hf-internal-testing/tiny-random-vit' ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch('requests.Session.request' , return_value=__magic_name__ ) as mock_head: _a = ViTImageProcessor.from_pretrained('hf-internal-testing/tiny-random-vit' ) # This check we did call the fake head request mock_head.assert_called() def __UpperCAmelCase ( self ) -> Optional[int]: # This test is for deprecated behavior and can be removed in v5 _a = ViTImageProcessor.from_pretrained( 'https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json' ) def __UpperCAmelCase ( self ) -> Dict: with self.assertRaises(__magic_name__ ): # config is in subfolder, the following should not work without specifying the subfolder _a = AutoImageProcessor.from_pretrained('hf-internal-testing/stable-diffusion-all-variants' ) _a = AutoImageProcessor.from_pretrained( 'hf-internal-testing/stable-diffusion-all-variants' , subfolder='feature_extractor' ) self.assertIsNotNone(__magic_name__ ) @is_staging_test class a ( unittest.TestCase ): @classmethod def __UpperCAmelCase ( cls ) -> Dict: _a = TOKEN HfFolder.save_token(__magic_name__ ) @classmethod def __UpperCAmelCase ( cls ) -> List[Any]: try: delete_repo(token=cls._token , repo_id='test-image-processor' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='valid_org/test-image-processor-org' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='test-dynamic-image-processor' ) except HTTPError: pass def __UpperCAmelCase ( self ) -> str: _a = ViTImageProcessor.from_pretrained(__magic_name__ ) image_processor.push_to_hub('test-image-processor' , use_auth_token=self._token ) _a = ViTImageProcessor.from_pretrained(f'{USER}/test-image-processor' ) for k, v in image_processor.__dict__.items(): self.assertEqual(__magic_name__ , getattr(__magic_name__ , __magic_name__ ) ) # Reset repo delete_repo(token=self._token , repo_id='test-image-processor' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( __magic_name__ , repo_id='test-image-processor' , push_to_hub=__magic_name__ , use_auth_token=self._token ) _a = ViTImageProcessor.from_pretrained(f'{USER}/test-image-processor' ) for k, v in image_processor.__dict__.items(): self.assertEqual(__magic_name__ , getattr(__magic_name__ , __magic_name__ ) ) def __UpperCAmelCase ( self ) -> Optional[Any]: _a = ViTImageProcessor.from_pretrained(__magic_name__ ) image_processor.push_to_hub('valid_org/test-image-processor' , use_auth_token=self._token ) _a = ViTImageProcessor.from_pretrained('valid_org/test-image-processor' ) for k, v in image_processor.__dict__.items(): self.assertEqual(__magic_name__ , getattr(__magic_name__ , __magic_name__ ) ) # Reset repo delete_repo(token=self._token , repo_id='valid_org/test-image-processor' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( __magic_name__ , repo_id='valid_org/test-image-processor-org' , push_to_hub=__magic_name__ , use_auth_token=self._token ) _a = ViTImageProcessor.from_pretrained('valid_org/test-image-processor-org' ) for k, v in image_processor.__dict__.items(): self.assertEqual(__magic_name__ , getattr(__magic_name__ , __magic_name__ ) ) def __UpperCAmelCase ( self ) -> Any: CustomImageProcessor.register_for_auto_class() _a = CustomImageProcessor.from_pretrained(__magic_name__ ) image_processor.push_to_hub('test-dynamic-image-processor' , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( image_processor.auto_map , {'AutoImageProcessor': 'custom_image_processing.CustomImageProcessor'} , ) _a = AutoImageProcessor.from_pretrained( f'{USER}/test-dynamic-image-processor' , trust_remote_code=__magic_name__ ) # Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module self.assertEqual(new_image_processor.__class__.__name__ , 'CustomImageProcessor' )
104
1
import math def lowerCAmelCase ( lowerCAmelCase_ )-> Union[str, Any]: lowerCAmelCase_ : Any = 0 lowerCAmelCase_ : List[Any] = 0 while num > 0: lowerCAmelCase_ : str = num % 8 lowerCAmelCase_ : Tuple = octal + (remainder * math.floor(math.pow(10 , snake_case__ ) )) counter += 1 lowerCAmelCase_ : List[str] = math.floor(num / 8 ) # basically /= 8 without remainder if any # This formatting removes trailing '.0' from `octal`. return f"""0o{int(snake_case__ )}""" def lowerCAmelCase ( )-> List[str]: print('''\n2 in octal is:''' ) print(decimal_to_octal(2 ) ) # = 2 print('''\n8 in octal is:''' ) print(decimal_to_octal(8 ) ) # = 10 print('''\n65 in octal is:''' ) print(decimal_to_octal(65 ) ) # = 101 print('''\n216 in octal is:''' ) print(decimal_to_octal(216 ) ) # = 330 print('''\n512 in octal is:''' ) print(decimal_to_octal(512 ) ) # = 1000 print('''\n''' ) if __name__ == "__main__": main()
262
"""simple docstring""" import copy from collections import OrderedDict from typing import Dict, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING A_ : Optional[Any] = logging.get_logger(__name__) A_ : Optional[Any] = { "facebook/detr-resnet-50": "https://huggingface.co/facebook/detr-resnet-50/resolve/main/config.json", # See all DETR models at https://huggingface.co/models?filter=detr } class lowerCamelCase (A__ ): lowerCamelCase__ : Dict = 'detr' lowerCamelCase__ : Union[str, Any] = ['past_key_values'] lowerCamelCase__ : Tuple = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : Optional[int] , __UpperCAmelCase : Any=True , __UpperCAmelCase : Union[str, Any]=None , __UpperCAmelCase : Optional[int]=3 , __UpperCAmelCase : int=1_0_0 , __UpperCAmelCase : Optional[Any]=6 , __UpperCAmelCase : List[str]=2_0_4_8 , __UpperCAmelCase : List[str]=8 , __UpperCAmelCase : Optional[int]=6 , __UpperCAmelCase : Dict=2_0_4_8 , __UpperCAmelCase : List[str]=8 , __UpperCAmelCase : Union[str, Any]=0.0 , __UpperCAmelCase : Dict=0.0 , __UpperCAmelCase : Optional[Any]=True , __UpperCAmelCase : Any="relu" , __UpperCAmelCase : Dict=2_5_6 , __UpperCAmelCase : List[str]=0.1 , __UpperCAmelCase : int=0.0 , __UpperCAmelCase : str=0.0 , __UpperCAmelCase : Optional[int]=0.02 , __UpperCAmelCase : Optional[int]=1.0 , __UpperCAmelCase : Dict=False , __UpperCAmelCase : str="sine" , __UpperCAmelCase : str="resnet50" , __UpperCAmelCase : List[Any]=True , __UpperCAmelCase : int=False , __UpperCAmelCase : Tuple=1 , __UpperCAmelCase : Optional[Any]=5 , __UpperCAmelCase : Tuple=2 , __UpperCAmelCase : Optional[Any]=1 , __UpperCAmelCase : Union[str, Any]=1 , __UpperCAmelCase : Union[str, Any]=5 , __UpperCAmelCase : Any=2 , __UpperCAmelCase : List[str]=0.1 , **__UpperCAmelCase : Dict , ) -> Optional[int]: if backbone_config is not None and use_timm_backbone: raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`.""" ) if not use_timm_backbone: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) SCREAMING_SNAKE_CASE__ = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(__UpperCAmelCase , __UpperCAmelCase ): SCREAMING_SNAKE_CASE__ = backbone_config.get("""model_type""" ) SCREAMING_SNAKE_CASE__ = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE__ = config_class.from_dict(__UpperCAmelCase ) # set timm attributes to None SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None, None, None SCREAMING_SNAKE_CASE__ = use_timm_backbone SCREAMING_SNAKE_CASE__ = backbone_config SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = num_queries SCREAMING_SNAKE_CASE__ = d_model SCREAMING_SNAKE_CASE__ = encoder_ffn_dim SCREAMING_SNAKE_CASE__ = encoder_layers SCREAMING_SNAKE_CASE__ = encoder_attention_heads SCREAMING_SNAKE_CASE__ = decoder_ffn_dim SCREAMING_SNAKE_CASE__ = decoder_layers SCREAMING_SNAKE_CASE__ = decoder_attention_heads SCREAMING_SNAKE_CASE__ = dropout SCREAMING_SNAKE_CASE__ = attention_dropout SCREAMING_SNAKE_CASE__ = activation_dropout SCREAMING_SNAKE_CASE__ = activation_function SCREAMING_SNAKE_CASE__ = init_std SCREAMING_SNAKE_CASE__ = init_xavier_std SCREAMING_SNAKE_CASE__ = encoder_layerdrop SCREAMING_SNAKE_CASE__ = decoder_layerdrop SCREAMING_SNAKE_CASE__ = encoder_layers SCREAMING_SNAKE_CASE__ = auxiliary_loss SCREAMING_SNAKE_CASE__ = position_embedding_type SCREAMING_SNAKE_CASE__ = backbone SCREAMING_SNAKE_CASE__ = use_pretrained_backbone SCREAMING_SNAKE_CASE__ = dilation # Hungarian matcher SCREAMING_SNAKE_CASE__ = class_cost SCREAMING_SNAKE_CASE__ = bbox_cost SCREAMING_SNAKE_CASE__ = giou_cost # Loss coefficients SCREAMING_SNAKE_CASE__ = mask_loss_coefficient SCREAMING_SNAKE_CASE__ = dice_loss_coefficient SCREAMING_SNAKE_CASE__ = bbox_loss_coefficient SCREAMING_SNAKE_CASE__ = giou_loss_coefficient SCREAMING_SNAKE_CASE__ = eos_coefficient super().__init__(is_encoder_decoder=__UpperCAmelCase , **__UpperCAmelCase ) @property def SCREAMING_SNAKE_CASE ( self : str ) -> int: return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: return self.d_model @classmethod def SCREAMING_SNAKE_CASE ( cls : str , __UpperCAmelCase : PretrainedConfig , **__UpperCAmelCase : Dict ) -> List[Any]: return cls(backbone_config=__UpperCAmelCase , **__UpperCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict[str, any]: SCREAMING_SNAKE_CASE__ = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: SCREAMING_SNAKE_CASE__ = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE__ = self.__class__.model_type return output class lowerCamelCase (A__ ): lowerCamelCase__ : Union[str, Any] = version.parse('1.11' ) @property def SCREAMING_SNAKE_CASE ( self : str ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def SCREAMING_SNAKE_CASE ( self : str ) -> float: return 1e-5 @property def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: return 1_2
165
0
from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def UpperCAmelCase ( a_ ) -> List[str]: """simple docstring""" if not is_accelerate_available(): return method __A = version.parse(accelerate.__version__ ).base_version if version.parse(a_ ) < version.parse("0.17.0" ): return method def wrapper(self , *a_ , **a_ ): if hasattr(self , "_hf_hook" ) and hasattr(self._hf_hook , "pre_forward" ): self._hf_hook.pre_forward(self ) return method(self , *a_ , **a_ ) return wrapper
124
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Value from .base import TaskTemplate @dataclass(frozen=__SCREAMING_SNAKE_CASE ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = field(default="text-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) snake_case_ = Features({"text": Value("string" )} ) snake_case_ = Features({"labels": ClassLabel} ) snake_case_ = "text" snake_case_ = "labels" def UpperCamelCase_ ( self : Optional[Any] ,A : Dict ): if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] ,A ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) __A = copy.deepcopy(self ) __A = self.label_schema.copy() __A = features[self.label_column] __A = label_schema return task_template @property def UpperCamelCase_ ( self : Dict ): return { self.text_column: "text", self.label_column: "labels", }
124
1
"""simple docstring""" from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE): snake_case__ = '''EncodecFeatureExtractor''' snake_case__ = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self : int , __UpperCamelCase : List[Any] , __UpperCamelCase : Union[str, Any] ) -> Optional[Any]: super().__init__(__UpperCamelCase , __UpperCamelCase ) _UpperCamelCase = self.feature_extractor _UpperCamelCase = False def _UpperCamelCase ( self : Dict , __UpperCamelCase : List[Any]=None , __UpperCamelCase : Optional[Any]=None , __UpperCamelCase : Tuple=True ) -> List[str]: return self.tokenizer.get_decoder_prompt_ids(task=__UpperCamelCase , language=__UpperCamelCase , no_timestamps=__UpperCamelCase ) def __call__( self : List[str] , *__UpperCamelCase : int , **__UpperCamelCase : Optional[int] ) -> List[str]: # For backward compatibility if self._in_target_context_manager: return self.current_processor(*__UpperCamelCase , **__UpperCamelCase ) _UpperCamelCase = kwargs.pop('''audio''' , __UpperCamelCase ) _UpperCamelCase = kwargs.pop('''sampling_rate''' , __UpperCamelCase ) _UpperCamelCase = kwargs.pop('''text''' , __UpperCamelCase ) if len(__UpperCamelCase ) > 0: _UpperCamelCase = args[0] _UpperCamelCase = args[1:] if audio is None and text is None: raise ValueError('''You need to specify either an `audio` or `text` input to process.''' ) if text is not None: _UpperCamelCase = self.tokenizer(__UpperCamelCase , **__UpperCamelCase ) if audio is not None: _UpperCamelCase = self.feature_extractor(__UpperCamelCase , *__UpperCamelCase , sampling_rate=__UpperCamelCase , **__UpperCamelCase ) if audio is None: return inputs elif text is None: return audio_inputs else: _UpperCamelCase = audio_inputs['''input_values'''] if "padding_mask" in audio_inputs: _UpperCamelCase = audio_inputs['''padding_mask'''] return inputs def _UpperCamelCase ( self : Tuple , *__UpperCamelCase : Dict , **__UpperCamelCase : List[Any] ) -> List[Any]: _UpperCamelCase = kwargs.pop('''audio''' , __UpperCamelCase ) _UpperCamelCase = kwargs.pop('''padding_mask''' , __UpperCamelCase ) if len(__UpperCamelCase ) > 0: _UpperCamelCase = args[0] _UpperCamelCase = args[1:] if audio_values is not None: return self._decode_audio(__UpperCamelCase , padding_mask=__UpperCamelCase ) else: return self.tokenizer.batch_decode(*__UpperCamelCase , **__UpperCamelCase ) def _UpperCamelCase ( self : Optional[Any] , *__UpperCamelCase : Union[str, Any] , **__UpperCamelCase : Tuple ) -> str: return self.tokenizer.decode(*__UpperCamelCase , **__UpperCamelCase ) def _UpperCamelCase ( self : Dict , __UpperCamelCase : Dict , __UpperCamelCase : int = None ) -> List[np.ndarray]: _UpperCamelCase = to_numpy(__UpperCamelCase ) _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = audio_values.shape if padding_mask is None: return list(__UpperCamelCase ) _UpperCamelCase = to_numpy(__UpperCamelCase ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) _UpperCamelCase = seq_len - padding_mask.shape[-1] _UpperCamelCase = 1 - self.feature_extractor.padding_value _UpperCamelCase = np.pad(__UpperCamelCase , ((0, 0), (0, difference)) , '''constant''' , constant_values=__UpperCamelCase ) _UpperCamelCase = audio_values.tolist() for i in range(__UpperCamelCase ): _UpperCamelCase = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] _UpperCamelCase = sliced_audio.reshape(__UpperCamelCase , -1 ) return audio_values
256
'''simple docstring''' def _A (lowerCAmelCase__ :int , lowerCAmelCase__ :int ) -> int: '''simple docstring''' return int(input_a == input_a == 0 ) def _A () -> None: '''simple docstring''' print('Truth Table of NOR Gate:' ) print('| Input 1 | Input 2 | Output |' ) print(f'| 0 | 0 | {nor_gate(0 , 0 )} |' ) print(f'| 0 | 1 | {nor_gate(0 , 1 )} |' ) print(f'| 1 | 0 | {nor_gate(1 , 0 )} |' ) print(f'| 1 | 1 | {nor_gate(1 , 1 )} |' ) if __name__ == "__main__": import doctest doctest.testmod() main()
168
0
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase : Dict = logging.get_logger(__name__) UpperCAmelCase : Union[str, Any] = { 'Salesforce/instruct-blip-flan-t5': 'https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json', } class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "instructblip_vision_model" def __init__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : List[str]=1_408 , __SCREAMING_SNAKE_CASE : Any=6_144 , __SCREAMING_SNAKE_CASE : List[Any]=39 , __SCREAMING_SNAKE_CASE : str=16 , __SCREAMING_SNAKE_CASE : Dict=224 , __SCREAMING_SNAKE_CASE : int=14 , __SCREAMING_SNAKE_CASE : Dict="gelu" , __SCREAMING_SNAKE_CASE : str=1E-6 , __SCREAMING_SNAKE_CASE : Optional[int]=0.0 , __SCREAMING_SNAKE_CASE : Optional[Any]=1E-10 , __SCREAMING_SNAKE_CASE : Dict=True , **__SCREAMING_SNAKE_CASE : List[Any] , ) -> List[str]: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = attention_dropout __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = qkv_bias @classmethod def UpperCAmelCase__ ( cls : List[str] , __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the vision config dict if we are loading from InstructBlipConfig if config_dict.get("""model_type""" ) == "instructblip": __SCREAMING_SNAKE_CASE = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "instructblip_qformer" def __init__( self : int , __SCREAMING_SNAKE_CASE : Dict=30_522 , __SCREAMING_SNAKE_CASE : Any=768 , __SCREAMING_SNAKE_CASE : Union[str, Any]=12 , __SCREAMING_SNAKE_CASE : Optional[Any]=12 , __SCREAMING_SNAKE_CASE : Tuple=3_072 , __SCREAMING_SNAKE_CASE : Optional[int]="gelu" , __SCREAMING_SNAKE_CASE : int=0.1 , __SCREAMING_SNAKE_CASE : str=0.1 , __SCREAMING_SNAKE_CASE : int=512 , __SCREAMING_SNAKE_CASE : List[str]=0.02 , __SCREAMING_SNAKE_CASE : Union[str, Any]=1E-12 , __SCREAMING_SNAKE_CASE : Tuple=0 , __SCREAMING_SNAKE_CASE : Tuple="absolute" , __SCREAMING_SNAKE_CASE : Optional[int]=2 , __SCREAMING_SNAKE_CASE : Optional[int]=1_408 , **__SCREAMING_SNAKE_CASE : Tuple , ) -> Optional[int]: """simple docstring""" super().__init__(pad_token_id=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = position_embedding_type __SCREAMING_SNAKE_CASE = cross_attention_frequency __SCREAMING_SNAKE_CASE = encoder_hidden_size @classmethod def UpperCAmelCase__ ( cls : List[str] , __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , **__SCREAMING_SNAKE_CASE : str ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the qformer config dict if we are loading from InstructBlipConfig if config_dict.get("""model_type""" ) == "instructblip": __SCREAMING_SNAKE_CASE = config_dict["""qformer_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "instructblip" lowerCAmelCase__ = True def __init__( self : Any , __SCREAMING_SNAKE_CASE : Any=None , __SCREAMING_SNAKE_CASE : int=None , __SCREAMING_SNAKE_CASE : Any=None , __SCREAMING_SNAKE_CASE : List[Any]=32 , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> Optional[int]: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) if vision_config is None: __SCREAMING_SNAKE_CASE = {} logger.info("""vision_config is None. initializing the InstructBlipVisionConfig with default values.""" ) if qformer_config is None: __SCREAMING_SNAKE_CASE = {} logger.info("""qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.""" ) if text_config is None: __SCREAMING_SNAKE_CASE = {} logger.info("""text_config is None. Initializing the text config with default values (`OPTConfig`).""" ) __SCREAMING_SNAKE_CASE = InstructBlipVisionConfig(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = InstructBlipQFormerConfig(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = text_config["""model_type"""] if """model_type""" in text_config else """opt""" __SCREAMING_SNAKE_CASE = CONFIG_MAPPING[text_model_type](**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.text_config.tie_word_embeddings __SCREAMING_SNAKE_CASE = self.text_config.is_encoder_decoder __SCREAMING_SNAKE_CASE = num_query_tokens __SCREAMING_SNAKE_CASE = self.vision_config.hidden_size __SCREAMING_SNAKE_CASE = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES __SCREAMING_SNAKE_CASE = 1.0 __SCREAMING_SNAKE_CASE = 0.02 @classmethod def UpperCAmelCase__ ( cls : List[str] , __SCREAMING_SNAKE_CASE : InstructBlipVisionConfig , __SCREAMING_SNAKE_CASE : InstructBlipQFormerConfig , __SCREAMING_SNAKE_CASE : PretrainedConfig , **__SCREAMING_SNAKE_CASE : Dict , ) -> Optional[Any]: """simple docstring""" return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **__SCREAMING_SNAKE_CASE , ) def UpperCAmelCase__ ( self : str ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = copy.deepcopy(self.__dict__ ) __SCREAMING_SNAKE_CASE = self.vision_config.to_dict() __SCREAMING_SNAKE_CASE = self.qformer_config.to_dict() __SCREAMING_SNAKE_CASE = self.text_config.to_dict() __SCREAMING_SNAKE_CASE = self.__class__.model_type return output
367
'''simple docstring''' from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING UpperCAmelCase : Union[str, Any] = logging.get_logger(__name__) @add_end_docstrings(a ) class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Optional[Any] , *__SCREAMING_SNAKE_CASE : Union[str, Any] , **__SCREAMING_SNAKE_CASE : str ) -> Any: """simple docstring""" super().__init__(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) requires_backends(self , """vision""" ) self.check_model_type( TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == """tf""" else MODEL_FOR_VISION_2_SEQ_MAPPING ) def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Optional[Any]=None , __SCREAMING_SNAKE_CASE : Any=None ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = {} if prompt is not None: __SCREAMING_SNAKE_CASE = prompt if generate_kwargs is not None: __SCREAMING_SNAKE_CASE = generate_kwargs if max_new_tokens is not None: if "generate_kwargs" not in forward_kwargs: __SCREAMING_SNAKE_CASE = {} if "max_new_tokens" in forward_kwargs["generate_kwargs"]: raise ValueError( """'max_new_tokens' is defined twice, once in 'generate_kwargs' and once as a direct parameter,""" """ please use only one""" ) __SCREAMING_SNAKE_CASE = max_new_tokens return preprocess_params, forward_kwargs, {} def __call__( self : int , __SCREAMING_SNAKE_CASE : Union[str, List[str], "Image.Image", List["Image.Image"]] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> int: """simple docstring""" return super().__call__(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image(__SCREAMING_SNAKE_CASE ) if prompt is not None: if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise ValueError( f'Received an invalid text input, got - {type(__SCREAMING_SNAKE_CASE )} - but expected a single string. ' """Note also that one single text can be provided for conditional image to text generation.""" ) __SCREAMING_SNAKE_CASE = self.model.config.model_type if model_type == "git": __SCREAMING_SNAKE_CASE = self.image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors=self.framework ) __SCREAMING_SNAKE_CASE = self.tokenizer(text=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ).input_ids __SCREAMING_SNAKE_CASE = [self.tokenizer.cls_token_id] + input_ids __SCREAMING_SNAKE_CASE = torch.tensor(__SCREAMING_SNAKE_CASE ).unsqueeze(0 ) model_inputs.update({"""input_ids""": input_ids} ) elif model_type == "pix2struct": __SCREAMING_SNAKE_CASE = self.image_processor(images=__SCREAMING_SNAKE_CASE , header_text=__SCREAMING_SNAKE_CASE , return_tensors=self.framework ) elif model_type != "vision-encoder-decoder": # vision-encoder-decoder does not support conditional generation __SCREAMING_SNAKE_CASE = self.image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors=self.framework ) __SCREAMING_SNAKE_CASE = self.tokenizer(__SCREAMING_SNAKE_CASE , return_tensors=self.framework ) model_inputs.update(__SCREAMING_SNAKE_CASE ) else: raise ValueError(f'Model type {model_type} does not support conditional text generation' ) else: __SCREAMING_SNAKE_CASE = self.image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors=self.framework ) if self.model.config.model_type == "git" and prompt is None: __SCREAMING_SNAKE_CASE = None return model_inputs def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : List[Any]=None ) -> List[str]: """simple docstring""" if ( "input_ids" in model_inputs and isinstance(model_inputs["""input_ids"""] , __SCREAMING_SNAKE_CASE ) and all(x is None for x in model_inputs["""input_ids"""] ) ): __SCREAMING_SNAKE_CASE = None if generate_kwargs is None: __SCREAMING_SNAKE_CASE = {} # FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py` # parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas # the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name` # in the `_prepare_model_inputs` method. __SCREAMING_SNAKE_CASE = model_inputs.pop(self.model.main_input_name ) __SCREAMING_SNAKE_CASE = self.model.generate(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) return model_outputs def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = [] for output_ids in model_outputs: __SCREAMING_SNAKE_CASE = { """generated_text""": self.tokenizer.decode( __SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE , ) } records.append(__SCREAMING_SNAKE_CASE ) return records
331
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_lxmert import LxmertTokenizer __lowerCAmelCase : Dict ={'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} __lowerCAmelCase : List[str] ={ 'vocab_file': { 'unc-nlp/lxmert-base-uncased': 'https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/vocab.txt', }, 'tokenizer_file': { 'unc-nlp/lxmert-base-uncased': ( 'https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/tokenizer.json' ), }, } __lowerCAmelCase : List[str] ={ 'unc-nlp/lxmert-base-uncased': 5_1_2, } __lowerCAmelCase : Any ={ 'unc-nlp/lxmert-base-uncased': {'do_lower_case': True}, } class _lowercase ( A__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ : Tuple = PRETRAINED_INIT_CONFIGURATION SCREAMING_SNAKE_CASE__ : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ : List[str] = LxmertTokenizer def __init__( self :int , lowerCAmelCase__ :Dict=None , lowerCAmelCase__ :Optional[Any]=None , lowerCAmelCase__ :Any=True , lowerCAmelCase__ :str="[UNK]" , lowerCAmelCase__ :Optional[int]="[SEP]" , lowerCAmelCase__ :str="[PAD]" , lowerCAmelCase__ :Optional[Any]="[CLS]" , lowerCAmelCase__ :List[Any]="[MASK]" , lowerCAmelCase__ :Union[str, Any]=True , lowerCAmelCase__ :List[Any]=None , **lowerCAmelCase__ :str , ) -> Dict: super().__init__( lowerCAmelCase__ , tokenizer_file=lowerCAmelCase__ , do_lower_case=lowerCAmelCase__ , unk_token=lowerCAmelCase__ , sep_token=lowerCAmelCase__ , pad_token=lowerCAmelCase__ , cls_token=lowerCAmelCase__ , mask_token=lowerCAmelCase__ , tokenize_chinese_chars=lowerCAmelCase__ , strip_accents=lowerCAmelCase__ , **lowerCAmelCase__ , ) __SCREAMING_SNAKE_CASE : Any = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , lowerCAmelCase__ ) != do_lower_case or normalizer_state.get('''strip_accents''' , lowerCAmelCase__ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , lowerCAmelCase__ ) != tokenize_chinese_chars ): __SCREAMING_SNAKE_CASE : str = getattr(lowerCAmelCase__ , normalizer_state.pop('''type''' ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = do_lower_case __SCREAMING_SNAKE_CASE : Dict = strip_accents __SCREAMING_SNAKE_CASE : List[str] = tokenize_chinese_chars __SCREAMING_SNAKE_CASE : Union[str, Any] = normalizer_class(**lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : List[Any] = do_lower_case def __magic_name__( self :Union[str, Any] , lowerCAmelCase__ :Optional[Any] , lowerCAmelCase__ :List[str]=None ) -> List[str]: __SCREAMING_SNAKE_CASE : Optional[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __magic_name__( self :Dict , lowerCAmelCase__ :List[int] , lowerCAmelCase__ :Optional[List[int]] = None ) -> List[int]: __SCREAMING_SNAKE_CASE : Optional[int] = [self.sep_token_id] __SCREAMING_SNAKE_CASE : 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 ) * [0] + len(token_ids_a + sep ) * [1] def __magic_name__( self :List[str] , lowerCAmelCase__ :str , lowerCAmelCase__ :Optional[str] = None ) -> Tuple[str]: __SCREAMING_SNAKE_CASE : Dict = self._tokenizer.model.save(lowerCAmelCase__ , name=lowerCAmelCase__ ) return tuple(lowerCAmelCase__ )
9
from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class _lowercase ( A__ ): '''simple docstring''' def __init__( self :int , lowerCAmelCase__ :NestedDataStructureLike[PathLike] , lowerCAmelCase__ :Optional[NamedSplit] = None , lowerCAmelCase__ :Optional[Features] = None , lowerCAmelCase__ :str = None , lowerCAmelCase__ :bool = False , lowerCAmelCase__ :bool = False , lowerCAmelCase__ :Optional[int] = None , **lowerCAmelCase__ :Optional[int] , ) -> Tuple: super().__init__( lowerCAmelCase__ , split=lowerCAmelCase__ , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , keep_in_memory=lowerCAmelCase__ , streaming=lowerCAmelCase__ , num_proc=lowerCAmelCase__ , **lowerCAmelCase__ , ) __SCREAMING_SNAKE_CASE : List[str] = path_or_paths if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else {self.split: path_or_paths} __SCREAMING_SNAKE_CASE : int = Text( cache_dir=lowerCAmelCase__ , data_files=lowerCAmelCase__ , features=lowerCAmelCase__ , **lowerCAmelCase__ , ) def __magic_name__( self :Dict ) -> Tuple: # Build iterable dataset if self.streaming: __SCREAMING_SNAKE_CASE : int = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: __SCREAMING_SNAKE_CASE : List[str] = None __SCREAMING_SNAKE_CASE : str = None __SCREAMING_SNAKE_CASE : Dict = None __SCREAMING_SNAKE_CASE : Tuple = None self.builder.download_and_prepare( download_config=lowerCAmelCase__ , download_mode=lowerCAmelCase__ , verification_mode=lowerCAmelCase__ , base_path=lowerCAmelCase__ , num_proc=self.num_proc , ) __SCREAMING_SNAKE_CASE : Optional[int] = self.builder.as_dataset( split=self.split , verification_mode=lowerCAmelCase__ , in_memory=self.keep_in_memory ) return dataset
9
1
def _lowercase ( _UpperCAmelCase ) -> List[str]: for i in range(0 , __snake_case ): for _ in range(0 , n - i - 1 ): # printing spaces print(""" """ , end="""""" ) for _ in range(0 , i + 1 ): # printing stars print("""* """ , end="""""" ) print() def _lowercase ( _UpperCAmelCase ) -> Optional[Any]: for i in range(__snake_case , 0 , -1 ): for _ in range(__snake_case , 0 , -1 ): # printing stars print("""* """ , end="""""" ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(""" """ , end="""""" ) def _lowercase ( _UpperCAmelCase ) -> Optional[Any]: if n <= 0: print(""" ... .... nothing printing :(""" ) return floyd(__snake_case ) # upper half reverse_floyd(__snake_case ) # lower half if __name__ == "__main__": print(r'''| /\ | |- | |- |--| |\ /| |-''') print(r'''|/ \| |- |_ |_ |__| | \/ | |_''') UpperCAmelCase__ : Optional[int] =1 while K: UpperCAmelCase__ : Dict =int(input('''enter the number and , and see the magic : ''')) print() pretty_print(user_number) UpperCAmelCase__ : int =int(input('''press 0 to exit... and 1 to continue...''')) print('''Good Bye...''')
362
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging UpperCAmelCase__ : List[Any] =logging.get_logger(__name__) UpperCAmelCase__ : Dict ={'''vocab_file''': '''spiece.model'''} UpperCAmelCase__ : Dict ={ '''vocab_file''': { '''xlnet-base-cased''': '''https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model''', '''xlnet-large-cased''': '''https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model''', } } UpperCAmelCase__ : List[str] ={ '''xlnet-base-cased''': None, '''xlnet-large-cased''': None, } # Segments (not really needed) UpperCAmelCase__ : Any =0 UpperCAmelCase__ : List[Any] =1 UpperCAmelCase__ : Union[str, Any] =2 UpperCAmelCase__ : Tuple =3 UpperCAmelCase__ : int =4 class __A ( a ): __A = VOCAB_FILES_NAMES __A = PRETRAINED_VOCAB_FILES_MAP __A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __A = """left""" def __init__( self , UpperCAmelCase_ , UpperCAmelCase_=False , UpperCAmelCase_=True , UpperCAmelCase_=False , UpperCAmelCase_="<s>" , UpperCAmelCase_="</s>" , UpperCAmelCase_="<unk>" , UpperCAmelCase_="<sep>" , UpperCAmelCase_="<pad>" , UpperCAmelCase_="<cls>" , UpperCAmelCase_="<mask>" , UpperCAmelCase_=["<eop>", "<eod>"] , UpperCAmelCase_ = None , **UpperCAmelCase_ , ): # Mask token behave like a normal word, i.e. include the space before it lowerCamelCase =AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else mask_token lowerCamelCase ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=UpperCAmelCase_ , remove_space=UpperCAmelCase_ , keep_accents=UpperCAmelCase_ , bos_token=UpperCAmelCase_ , eos_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , additional_special_tokens=UpperCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **UpperCAmelCase_ , ) lowerCamelCase =3 lowerCamelCase =do_lower_case lowerCamelCase =remove_space lowerCamelCase =keep_accents lowerCamelCase =vocab_file lowerCamelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCAmelCase_ ) @property def _snake_case ( self ): return len(self.sp_model ) def _snake_case ( self ): lowerCamelCase ={self.convert_ids_to_tokens(UpperCAmelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): lowerCamelCase =self.__dict__.copy() lowerCamelCase =None return state def __setstate__( self , UpperCAmelCase_ ): lowerCamelCase =d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): lowerCamelCase ={} lowerCamelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _snake_case ( self , UpperCAmelCase_ ): if self.remove_space: lowerCamelCase =""" """.join(inputs.strip().split() ) else: lowerCamelCase =inputs lowerCamelCase =outputs.replace("""``""" , """\"""" ).replace("""''""" , """\"""" ) if not self.keep_accents: lowerCamelCase =unicodedata.normalize("""NFKD""" , UpperCAmelCase_ ) lowerCamelCase ="""""".join([c for c in outputs if not unicodedata.combining(UpperCAmelCase_ )] ) if self.do_lower_case: lowerCamelCase =outputs.lower() return outputs def _snake_case ( self , UpperCAmelCase_ ): lowerCamelCase =self.preprocess_text(UpperCAmelCase_ ) lowerCamelCase =self.sp_model.encode(UpperCAmelCase_ , out_type=UpperCAmelCase_ ) lowerCamelCase =[] for piece in pieces: if len(UpperCAmelCase_ ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): lowerCamelCase =self.sp_model.EncodeAsPieces(piece[:-1].replace(UpperCAmelCase_ , """""" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: lowerCamelCase =cur_pieces[1:] else: lowerCamelCase =cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(UpperCAmelCase_ ) else: new_pieces.append(UpperCAmelCase_ ) return new_pieces def _snake_case ( self , UpperCAmelCase_ ): return self.sp_model.PieceToId(UpperCAmelCase_ ) def _snake_case ( self , UpperCAmelCase_ ): return self.sp_model.IdToPiece(UpperCAmelCase_ ) def _snake_case ( self , UpperCAmelCase_ ): lowerCamelCase ="""""".join(UpperCAmelCase_ ).replace(UpperCAmelCase_ , """ """ ).strip() return out_string def _snake_case ( self , UpperCAmelCase_ , UpperCAmelCase_ = False , UpperCAmelCase_ = None , UpperCAmelCase_ = True , **UpperCAmelCase_ , ): lowerCamelCase =kwargs.pop("""use_source_tokenizer""" , UpperCAmelCase_ ) lowerCamelCase =self.convert_ids_to_tokens(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 lowerCamelCase =[] lowerCamelCase =[] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(UpperCAmelCase_ ) ) lowerCamelCase =[] sub_texts.append(UpperCAmelCase_ ) else: current_sub_text.append(UpperCAmelCase_ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(UpperCAmelCase_ ) ) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens lowerCamelCase ="""""".join(UpperCAmelCase_ ) lowerCamelCase =( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: lowerCamelCase =self.clean_up_tokenization(UpperCAmelCase_ ) return clean_text else: return text def _snake_case ( self , UpperCAmelCase_ , UpperCAmelCase_ = None ): lowerCamelCase =[self.sep_token_id] lowerCamelCase =[self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _snake_case ( self , UpperCAmelCase_ , UpperCAmelCase_ = None , UpperCAmelCase_ = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase_ , token_ids_a=UpperCAmelCase_ , already_has_special_tokens=UpperCAmelCase_ ) if token_ids_a is not None: return ([0] * len(UpperCAmelCase_ )) + [1] + ([0] * len(UpperCAmelCase_ )) + [1, 1] return ([0] * len(UpperCAmelCase_ )) + [1, 1] def _snake_case ( self , UpperCAmelCase_ , UpperCAmelCase_ = None ): lowerCamelCase =[self.sep_token_id] lowerCamelCase =[2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def _snake_case ( self , UpperCAmelCase_ , UpperCAmelCase_ = None ): if not os.path.isdir(UpperCAmelCase_ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return lowerCamelCase =os.path.join( UpperCAmelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCAmelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCAmelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCAmelCase_ , """wb""" ) as fi: lowerCamelCase =self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase_ ) return (out_vocab_file,)
262
0
def _UpperCAmelCase ( snake_case , snake_case ): """simple docstring""" _lowerCAmelCase = [1] for i in range(2 , snake_case ): factorials.append(factorials[-1] * i ) assert 0 <= k < factorials[-1] * n, "k out of bounds" _lowerCAmelCase = [] _lowerCAmelCase = list(range(snake_case ) ) # Find permutation while factorials: _lowerCAmelCase = factorials.pop() _lowerCAmelCase , _lowerCAmelCase = divmod(snake_case , snake_case ) permutation.append(elements[number] ) elements.remove(elements[number] ) permutation.append(elements[0] ) return permutation if __name__ == "__main__": import doctest doctest.testmod()
82
def _UpperCAmelCase ( snake_case ): """simple docstring""" _lowerCAmelCase = 1 for i in range(1 , num + 1 ): fact *= i return fact def _UpperCAmelCase ( snake_case ): """simple docstring""" _lowerCAmelCase = 0 while number > 0: _lowerCAmelCase = number % 10 sum_of_digits += last_digit _lowerCAmelCase = number // 10 # Removing the last_digit from the given number return sum_of_digits def _UpperCAmelCase ( snake_case = 1_00 ): """simple docstring""" _lowerCAmelCase = factorial(snake_case ) _lowerCAmelCase = split_and_add(snake_case ) return result if __name__ == "__main__": print(solution(int(input("""Enter the Number: """).strip())))
82
1
import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class lowerCAmelCase_ : '''simple docstring''' def __init__( self , _UpperCAmelCase , _UpperCAmelCase=99 , _UpperCAmelCase=13 , _UpperCAmelCase=7 , _UpperCAmelCase=9 , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=False , _UpperCAmelCase=32 , _UpperCAmelCase=5 , _UpperCAmelCase=4 , _UpperCAmelCase=37 , _UpperCAmelCase=8 , _UpperCAmelCase=0.1 , _UpperCAmelCase=0.002 , _UpperCAmelCase=1 , _UpperCAmelCase=0 , _UpperCAmelCase=0 , _UpperCAmelCase=None , _UpperCAmelCase=None , ): snake_case_ = parent snake_case_ = batch_size snake_case_ = encoder_seq_length snake_case_ = decoder_seq_length # For common tests snake_case_ = self.decoder_seq_length snake_case_ = is_training snake_case_ = use_attention_mask snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = d_ff snake_case_ = relative_attention_num_buckets snake_case_ = dropout_rate snake_case_ = initializer_factor snake_case_ = eos_token_id snake_case_ = pad_token_id snake_case_ = decoder_start_token_id snake_case_ = None snake_case_ = decoder_layers def UpperCamelCase__ ( self ): return TaConfig.from_pretrained('''google/umt5-base''' ) def UpperCamelCase__ ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=None , ): if attention_mask is None: snake_case_ = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: snake_case_ = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: snake_case_ = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=_UpperCAmelCase ) if decoder_head_mask is None: snake_case_ = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=_UpperCAmelCase ) if cross_attn_head_mask is None: snake_case_ = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=_UpperCAmelCase ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } def UpperCamelCase__ ( self ): snake_case_ = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) snake_case_ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input snake_case_ = input_ids.clamp(self.pad_token_id + 1 ) snake_case_ = decoder_input_ids.clamp(self.pad_token_id + 1 ) snake_case_ = self.get_config() snake_case_ = config.num_attention_heads snake_case_ = self.prepare_inputs_dict(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) return config, input_dict def UpperCamelCase__ ( self ): snake_case_ , snake_case_ = self.prepare_config_and_inputs() return config, inputs_dict def UpperCamelCase__ ( self ): return TaConfig( vocab_size=1_66 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def UpperCamelCase__ ( self ): return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def UpperCamelCase__ ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ): snake_case_ = UMTaModel(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() snake_case_ = model( input_ids=_UpperCAmelCase , decoder_input_ids=_UpperCAmelCase , attention_mask=_UpperCAmelCase , decoder_attention_mask=_UpperCAmelCase , ) snake_case_ = model(input_ids=_UpperCAmelCase , decoder_input_ids=_UpperCAmelCase ) snake_case_ = result.last_hidden_state snake_case_ = result.past_key_values snake_case_ = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(_UpperCAmelCase ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def UpperCamelCase__ ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ): snake_case_ = UMTaModel(config=_UpperCAmelCase ).get_decoder().to(_UpperCAmelCase ).eval() # first forward pass snake_case_ = model(_UpperCAmelCase , use_cache=_UpperCAmelCase ) snake_case_ = model(_UpperCAmelCase ) snake_case_ = model(_UpperCAmelCase , use_cache=_UpperCAmelCase ) self.parent.assertTrue(len(_UpperCAmelCase ) == len(_UpperCAmelCase ) ) self.parent.assertTrue(len(_UpperCAmelCase ) == len(_UpperCAmelCase ) + 1 ) snake_case_ , snake_case_ = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids snake_case_ = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and snake_case_ = torch.cat([input_ids, next_tokens] , dim=-1 ) snake_case_ = model(_UpperCAmelCase )['''last_hidden_state'''] snake_case_ = model(_UpperCAmelCase , past_key_values=_UpperCAmelCase )['''last_hidden_state'''] # select random slice snake_case_ = ids_tensor((1,) , output_from_past.shape[-1] ).item() snake_case_ = output_from_no_past[:, -1, random_slice_idx].detach() snake_case_ = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(_UpperCAmelCase , _UpperCAmelCase , atol=1E-3 ) ) def UpperCamelCase__ ( self , _UpperCAmelCase , _UpperCAmelCase , ): snake_case_ = UMTaModel(config=_UpperCAmelCase ).to(_UpperCAmelCase ).half().eval() snake_case_ = model(**_UpperCAmelCase )['''last_hidden_state'''] self.parent.assertFalse(torch.isnan(_UpperCAmelCase ).any().item() ) @require_torch class lowerCAmelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): '''simple docstring''' __snake_case = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) __snake_case = (UMTaForConditionalGeneration,) if is_torch_available() else () __snake_case = ( { "conversational": UMTaForConditionalGeneration, "feature-extraction": UMTaModel, "summarization": UMTaForConditionalGeneration, "text2text-generation": UMTaForConditionalGeneration, "translation": UMTaForConditionalGeneration, "question-answering": UMTaForQuestionAnswering, } if is_torch_available() else {} ) __snake_case = True __snake_case = False __snake_case = False __snake_case = True __snake_case = True # The small UMT5 model needs higher percentages for CPU/MP tests __snake_case = [0.8, 0.9] def UpperCamelCase__ ( self ): snake_case_ = UMTaModelTester(self ) @unittest.skip('''Test has a segmentation fault on torch 1.8.0''' ) def UpperCamelCase__ ( self ): snake_case_ = self.model_tester.prepare_config_and_inputs() snake_case_ = UMTaModel(config_and_inputs[0] ).to(_UpperCAmelCase ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( _UpperCAmelCase , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , F'''{tmpdirname}/t5_test.onnx''' , export_params=_UpperCAmelCase , opset_version=9 , input_names=['''input_ids''', '''decoder_input_ids'''] , ) @unittest.skipIf(torch_device == '''cpu''' , '''Cant do half precision''' ) def UpperCamelCase__ ( self ): snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*_UpperCAmelCase ) def UpperCamelCase__ ( self ): snake_case_ = ['''encoder_attentions''', '''decoder_attentions''', '''cross_attentions'''] snake_case_ = self.model_tester.prepare_config_and_inputs() snake_case_ = config_and_inputs[0] snake_case_ = UMTaForConditionalGeneration(_UpperCAmelCase ).eval() model.to(_UpperCAmelCase ) snake_case_ = { '''head_mask''': torch.zeros(config.num_layers , config.num_heads , device=_UpperCAmelCase ), '''decoder_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=_UpperCAmelCase ), '''cross_attn_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=_UpperCAmelCase ), } for attn_name, (name, mask) in zip(_UpperCAmelCase , head_masking.items() ): snake_case_ = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": snake_case_ = torch.ones( config.num_decoder_layers , config.num_heads , device=_UpperCAmelCase ) snake_case_ = model.generate( config_and_inputs[1]['''input_ids'''] , num_beams=1 , max_length=3 , output_attentions=_UpperCAmelCase , return_dict_in_generate=_UpperCAmelCase , **_UpperCAmelCase , ) # We check the state of decoder_attentions and cross_attentions just from the last step snake_case_ = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip('''Does not work on the tiny model as we keep hitting edge cases.''' ) def UpperCamelCase__ ( self ): pass @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow @unittest.skip( '''Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged''' ) def UpperCamelCase__ ( self ): snake_case_ = UMTaForConditionalGeneration.from_pretrained('''google/umt5-small''' , return_dict=_UpperCAmelCase ).to(_UpperCAmelCase ) snake_case_ = AutoTokenizer.from_pretrained('''google/umt5-small''' , use_fast=_UpperCAmelCase , legacy=_UpperCAmelCase ) snake_case_ = [ '''Bonjour monsieur <extra_id_0> bien <extra_id_1>.''', '''No se como puedo <extra_id_0>.''', '''This is the reason why we <extra_id_0> them.''', '''The <extra_id_0> walks in <extra_id_1>, seats''', '''A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.''', ] snake_case_ = tokenizer(_UpperCAmelCase , return_tensors='''pt''' , padding=_UpperCAmelCase ).input_ids # fmt: off snake_case_ = torch.tensor( [ [ 3_85_30, 21_07_03, 25_62_99, 14_10, 25_62_98, 2_74, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 8_26, 3_21, 6_71, 2_59_22, 25_62_99, 2_74, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 14_60, 3_39, 3_12, 1_90_14, 1_06_20, 7_58, 25_62_99, 23_55,2_74, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 5_17, 25_62_99, 1_48_69, 2_81, 3_01, 25_62_98, 2_75, 11_99_83,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 3_20, 25_62_99, 1_48_69, 2_81, 22_34, 2_89, 22_75, 3_33,6_13_91, 2_89, 25_62_98, 5_43, 25_62_97, 16_87_14, 3_29, 25_62_96,2_74, 1], ] ) # fmt: on torch.testing.assert_allclose(_UpperCAmelCase , _UpperCAmelCase ) snake_case_ = model.generate(input_ids.to(_UpperCAmelCase ) ) snake_case_ = [ '''<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>''', '''<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', ] snake_case_ = tokenizer.batch_decode(_UpperCAmelCase ) self.assertEqual(_UpperCAmelCase , _UpperCAmelCase )
365
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): '''simple docstring''' __snake_case = StableDiffusionInpaintPipeline __snake_case = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS __snake_case = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS __snake_case = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess __snake_case = frozenset([] ) def UpperCamelCase__ ( self ): torch.manual_seed(0 ) snake_case_ = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=_UpperCAmelCase , ) snake_case_ = PNDMScheduler(skip_prk_steps=_UpperCAmelCase ) torch.manual_seed(0 ) snake_case_ = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , sample_size=1_28 , ) torch.manual_seed(0 ) snake_case_ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , hidden_act='''gelu''' , projection_dim=5_12 , ) snake_case_ = CLIPTextModel(_UpperCAmelCase ) snake_case_ = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) snake_case_ = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def UpperCamelCase__ ( self , _UpperCAmelCase , _UpperCAmelCase=0 ): # TODO: use tensor inputs instead of PIL, this is here just to leave the old expected_slices untouched snake_case_ = floats_tensor((1, 3, 32, 32) , rng=random.Random(_UpperCAmelCase ) ).to(_UpperCAmelCase ) snake_case_ = image.cpu().permute(0 , 2 , 3 , 1 )[0] snake_case_ = Image.fromarray(np.uinta(_UpperCAmelCase ) ).convert('''RGB''' ).resize((64, 64) ) snake_case_ = Image.fromarray(np.uinta(image + 4 ) ).convert('''RGB''' ).resize((64, 64) ) if str(_UpperCAmelCase ).startswith('''mps''' ): snake_case_ = torch.manual_seed(_UpperCAmelCase ) else: snake_case_ = torch.Generator(device=_UpperCAmelCase ).manual_seed(_UpperCAmelCase ) snake_case_ = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': init_image, '''mask_image''': mask_image, '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def UpperCamelCase__ ( self ): snake_case_ = '''cpu''' # ensure determinism for the device-dependent torch.Generator snake_case_ = self.get_dummy_components() snake_case_ = StableDiffusionInpaintPipeline(**_UpperCAmelCase ) snake_case_ = sd_pipe.to(_UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase ) snake_case_ = self.get_dummy_inputs(_UpperCAmelCase ) snake_case_ = sd_pipe(**_UpperCAmelCase ).images snake_case_ = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case_ = np.array([0.4_727, 0.5_735, 0.3_941, 0.5_446, 0.5_926, 0.4_394, 0.5_062, 0.4_654, 0.4_476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCamelCase__ ( self ): super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ ( self ): snake_case_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''' ) snake_case_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' ) snake_case_ = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint''' '''/yellow_cat_sitting_on_a_park_bench.npy''' ) snake_case_ = '''stabilityai/stable-diffusion-2-inpainting''' snake_case_ = StableDiffusionInpaintPipeline.from_pretrained(_UpperCAmelCase , safety_checker=_UpperCAmelCase ) pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) pipe.enable_attention_slicing() snake_case_ = '''Face of a yellow cat, high resolution, sitting on a park bench''' snake_case_ = torch.manual_seed(0 ) snake_case_ = pipe( prompt=_UpperCAmelCase , image=_UpperCAmelCase , mask_image=_UpperCAmelCase , generator=_UpperCAmelCase , output_type='''np''' , ) snake_case_ = output.images[0] assert image.shape == (5_12, 5_12, 3) assert np.abs(expected_image - image ).max() < 9E-3 def UpperCamelCase__ ( self ): snake_case_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''' ) snake_case_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' ) snake_case_ = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint''' '''/yellow_cat_sitting_on_a_park_bench_fp16.npy''' ) snake_case_ = '''stabilityai/stable-diffusion-2-inpainting''' snake_case_ = StableDiffusionInpaintPipeline.from_pretrained( _UpperCAmelCase , torch_dtype=torch.floataa , safety_checker=_UpperCAmelCase , ) pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) pipe.enable_attention_slicing() snake_case_ = '''Face of a yellow cat, high resolution, sitting on a park bench''' snake_case_ = torch.manual_seed(0 ) snake_case_ = pipe( prompt=_UpperCAmelCase , image=_UpperCAmelCase , mask_image=_UpperCAmelCase , generator=_UpperCAmelCase , output_type='''np''' , ) snake_case_ = output.images[0] assert image.shape == (5_12, 5_12, 3) assert np.abs(expected_image - image ).max() < 5E-1 def UpperCamelCase__ ( self ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() snake_case_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''' ) snake_case_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' ) snake_case_ = '''stabilityai/stable-diffusion-2-inpainting''' snake_case_ = PNDMScheduler.from_pretrained(_UpperCAmelCase , subfolder='''scheduler''' ) snake_case_ = StableDiffusionInpaintPipeline.from_pretrained( _UpperCAmelCase , safety_checker=_UpperCAmelCase , scheduler=_UpperCAmelCase , torch_dtype=torch.floataa , ) pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() snake_case_ = '''Face of a yellow cat, high resolution, sitting on a park bench''' snake_case_ = torch.manual_seed(0 ) snake_case_ = pipe( prompt=_UpperCAmelCase , image=_UpperCAmelCase , mask_image=_UpperCAmelCase , generator=_UpperCAmelCase , num_inference_steps=2 , output_type='''np''' , ) snake_case_ = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
267
0
import importlib.metadata from typing import Union from packaging.version import Version, parse from .constants import STR_OPERATION_TO_FUNC lowercase : Optional[int] = parse(importlib.metadata.version("""torch""")) def A_ ( A__ , A__ , A__ ) -> Any: if operation not in STR_OPERATION_TO_FUNC.keys(): raise ValueError(F'`operation` must be one of {list(STR_OPERATION_TO_FUNC.keys() )}, received {operation}' ) a__ : Tuple = STR_OPERATION_TO_FUNC[operation] if isinstance(A__ , A__ ): a__ : Any = parse(importlib.metadata.version(A__ ) ) return operation(A__ , parse(A__ ) ) def A_ ( A__ , A__ ) -> Optional[int]: return compare_versions(A__ , A__ , A__ )
99
import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() lowercase : Any = logging.get_logger(__name__) def A_ ( A__ ) -> List[str]: a__ : Union[str, Any] = torch.load(A__ , map_location='cpu' ) if "model" in sd.keys(): a__ : Tuple = torch.load(A__ , map_location='cpu' )['model'] # pop unnecessary weights a__ : Optional[Any] = [ 'decoder.version', 'decoder.output_projection.weight', ] for key in keys_to_delete: if key in sd: sd.pop(A__ ) a__ : Union[str, Any] = { 'decoder.project_in_dim.weight': 'decoder.project_in.weight', 'decoder.project_out_dim.weight': 'decoder.project_out.weight', 'decoder.layer_norm.weight': 'decoder.final_layer_norm.weight', 'decoder.layer_norm.bias': 'decoder.final_layer_norm.bias', } for old_key, new_key in keys_to_rename.items(): if old_key in sd: a__ : Any = sd.pop(A__ ) a__ : Optional[int] = list(sd.keys() ) for key in keys: if ".qkv_proj." in key: a__ : str = sd[key] # We split QKV in separate Q,K,V a__ : Union[str, Any] = key.replace('.qkv_proj.' , '.q_proj.' ) a__ : int = key.replace('.qkv_proj.' , '.k_proj.' ) a__ : Optional[int] = key.replace('.qkv_proj.' , '.v_proj.' ) a__ : List[Any] = value.shape[0] assert depth % 3 == 0 # `SequeuceParallelTransformerBlock` has QKV weight is separated in K,V,Q despite the naming: # https://cs.github.com/facebookresearch/metaseq/blob/51871bd73cd04c038f239ea2a26db1d7f6b37927/metaseq/modules/sequence_parallel_transformer_layer.py#L97 a__ , a__ , a__ : Any = torch.split(A__ , depth // 3 , dim=0 ) a__ : int = q a__ : List[Any] = k a__ : int = v del sd[key] return sd @torch.no_grad() def A_ ( A__ , A__ , A__=None ) -> Union[str, Any]: a__ : Union[str, Any] = load_checkpoint(A__ ) if config is not None: a__ : List[Any] = OPTConfig.from_pretrained(A__ ) else: a__ : int = OPTConfig() a__ : Optional[int] = OPTModel(A__ ).half().eval() model.load_state_dict(A__ ) # Check results Path(A__ ).mkdir(exist_ok=A__ ) model.save_pretrained(A__ ) if __name__ == "__main__": lowercase : str = argparse.ArgumentParser() # Required parameters parser.add_argument( """--fairseq_path""", type=str, help=( """path to fairseq checkpoint in correct format. You can find all checkpoints in the correct format here:""" """ https://huggingface.co/models?other=opt_metasq""" ), ) parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--hf_config""", default=None, type=str, help="""Define HF config.""") lowercase : Any = parser.parse_args() convert_opt_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, config=args.hf_config)
99
1
import argparse import logging import os import sys import numpy as np import onnxruntime import torch from bart_onnx.generation_onnx import BARTBeamSearchGenerator from bart_onnx.reduce_onnx_size import remove_dup_initializers import transformers from transformers import BartForConditionalGeneration, BartTokenizer logging.basicConfig( format="%(asctime)s | %(levelname)s | %(name)s | [%(filename)s:%(lineno)d] %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=os.environ.get("LOGLEVEL", "INFO").upper(), stream=sys.stdout, ) __UpperCAmelCase : Tuple = logging.getLogger(__name__) __UpperCAmelCase : Dict = {'''facebook/bart-base''': BartForConditionalGeneration} __UpperCAmelCase : Union[str, Any] = {'''facebook/bart-base''': BartTokenizer} def a ( ): """simple docstring""" UpperCamelCase : List[Any] = argparse.ArgumentParser(description='''Export Bart model + Beam Search to ONNX graph.''' ) parser.add_argument( '''--validation_file''' , type=lowercase_ , default=lowercase_ , help='''A csv or a json file containing the validation data.''' ) parser.add_argument( '''--max_length''' , type=lowercase_ , default=5 , help='''The maximum total input sequence length after tokenization.''' , ) parser.add_argument( '''--num_beams''' , type=lowercase_ , default=lowercase_ , help=( '''Number of beams to use for evaluation. This argument will be ''' '''passed to ``model.generate``, which is used during ``evaluate`` and ``predict``.''' ) , ) parser.add_argument( '''--model_name_or_path''' , type=lowercase_ , help='''Path to pretrained model or model identifier from huggingface.co/models.''' , required=lowercase_ , ) parser.add_argument( '''--config_name''' , type=lowercase_ , default=lowercase_ , help='''Pretrained config name or path if not the same as model_name''' , ) parser.add_argument( '''--device''' , type=lowercase_ , default='''cpu''' , help='''Device where the model will be run''' , ) parser.add_argument('''--output_file_path''' , type=lowercase_ , default=lowercase_ , help='''Where to store the final ONNX file.''' ) UpperCamelCase : Dict = parser.parse_args() return args def a ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[Any]="cpu" ): """simple docstring""" UpperCamelCase : Optional[int] = model_dict[model_name].from_pretrained(lowercase_ ).to(lowercase_ ) UpperCamelCase : Any = tokenizer_dict[model_name].from_pretrained(lowercase_ ) if model_name in ["facebook/bart-base"]: UpperCamelCase : List[Any] = 0 UpperCamelCase : List[str] = None UpperCamelCase : int = 0 return huggingface_model, tokenizer def a ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Any ): """simple docstring""" model.eval() UpperCamelCase : str = None UpperCamelCase : Optional[Any] = torch.jit.script(BARTBeamSearchGenerator(lowercase_ ) ) with torch.no_grad(): UpperCamelCase : int = '''My friends are cool but they eat too many carbs.''' UpperCamelCase : Dict = tokenizer([ARTICLE_TO_SUMMARIZE] , max_length=1_0_2_4 , return_tensors='''pt''' ).to(model.device ) UpperCamelCase : int = model.generate( inputs['''input_ids'''] , attention_mask=inputs['''attention_mask'''] , num_beams=lowercase_ , max_length=lowercase_ , early_stopping=lowercase_ , decoder_start_token_id=model.config.decoder_start_token_id , ) torch.onnx.export( lowercase_ , ( inputs['''input_ids'''], inputs['''attention_mask'''], num_beams, max_length, model.config.decoder_start_token_id, ) , lowercase_ , opset_version=1_4 , input_names=['''input_ids''', '''attention_mask''', '''num_beams''', '''max_length''', '''decoder_start_token_id'''] , output_names=['''output_ids'''] , dynamic_axes={ '''input_ids''': {0: '''batch''', 1: '''seq'''}, '''output_ids''': {0: '''batch''', 1: '''seq_out'''}, } , example_outputs=lowercase_ , ) logger.info('''Model exported to {}'''.format(lowercase_ ) ) UpperCamelCase : Tuple = remove_dup_initializers(os.path.abspath(lowercase_ ) ) logger.info('''Deduplicated and optimized model written to {}'''.format(lowercase_ ) ) UpperCamelCase : int = onnxruntime.InferenceSession(lowercase_ ) UpperCamelCase : str = ort_sess.run( lowercase_ , { '''input_ids''': inputs['''input_ids'''].cpu().numpy(), '''attention_mask''': inputs['''attention_mask'''].cpu().numpy(), '''num_beams''': np.array(lowercase_ ), '''max_length''': np.array(lowercase_ ), '''decoder_start_token_id''': np.array(model.config.decoder_start_token_id ), } , ) np.testing.assert_allclose(summary_ids.cpu().numpy() , ort_out[0] , rtol=1E-3 , atol=1E-3 ) logger.info('''Model outputs from torch and ONNX Runtime are similar.''' ) logger.info('''Success.''' ) def a ( ): """simple docstring""" UpperCamelCase : List[Any] = parse_args() UpperCamelCase : Optional[int] = 5 UpperCamelCase : int = 4 # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO , ) logger.setLevel(logging.INFO ) transformers.utils.logging.set_verbosity_error() UpperCamelCase : Dict = torch.device(args.device ) UpperCamelCase , UpperCamelCase : Any = load_model_tokenizer(args.model_name_or_path , lowercase_ ) if model.config.decoder_start_token_id is None: raise ValueError('''Make sure that `config.decoder_start_token_id` is correctly defined''' ) model.to(lowercase_ ) if args.max_length: UpperCamelCase : Union[str, Any] = args.max_length if args.num_beams: UpperCamelCase : Optional[Any] = args.num_beams if args.output_file_path: UpperCamelCase : Any = args.output_file_path else: UpperCamelCase : Dict = '''BART.onnx''' logger.info('''Exporting model to ONNX''' ) export_and_validate_model(lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ) if __name__ == "__main__": main()
357
def a ( SCREAMING_SNAKE_CASE_ : str ): """simple docstring""" return "".join(chr(ord(SCREAMING_SNAKE_CASE_ ) - 3_2 ) if '''a''' <= char <= '''z''' else char for char in word ) if __name__ == "__main__": from doctest import testmod testmod()
315
0
"""simple docstring""" def A ( snake_case :int = 1_0_0_0_0_0_0 ) -> int: __UpperCamelCase = 1 __UpperCamelCase = 1 __UpperCamelCase = {1: 1} for inputa in range(2 , snake_case ): __UpperCamelCase = 0 __UpperCamelCase = inputa while True: if number in counters: counter += counters[number] break if number % 2 == 0: number //= 2 counter += 1 else: __UpperCamelCase = (3 * number) + 1 counter += 1 if inputa not in counters: __UpperCamelCase = counter if counter > pre_counter: __UpperCamelCase = inputa __UpperCamelCase = counter return largest_number if __name__ == "__main__": print(solution(int(input().strip())))
316
"""simple docstring""" # this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys UpperCamelCase : Union[str, Any] = subprocess.check_output("git merge-base main HEAD".split()).decode("utf-8") UpperCamelCase : Any = subprocess.check_output(f'''git diff --name-only {fork_point_sha}'''.split()).decode("utf-8").split() UpperCamelCase : Tuple = "|".join(sys.argv[1:]) UpperCamelCase : Optional[int] = re.compile(Rf'''^({joined_dirs}).*?\.py$''') UpperCamelCase : Optional[Any] = [x for x in modified_files if regex.match(x)] print(" ".join(relevant_modified_files), end="")
316
1
'''simple docstring''' import os def _lowerCamelCase ( ) -> Tuple: with open(os.path.dirname(lowerCAmelCase__ ) + "/grid.txt" ) as f: _a = [] # noqa: E741 for _ in range(20 ): l.append([int(lowerCAmelCase__ ) for x in f.readline().split()] ) _a = 0 # right for i in range(20 ): for j in range(17 ): _a = l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3] if temp > maximum: _a = temp # down for i in range(17 ): for j in range(20 ): _a = l[i][j] * l[i + 1][j] * l[i + 2][j] * l[i + 3][j] if temp > maximum: _a = temp # diagonal 1 for i in range(17 ): for j in range(17 ): _a = l[i][j] * l[i + 1][j + 1] * l[i + 2][j + 2] * l[i + 3][j + 3] if temp > maximum: _a = temp # diagonal 2 for i in range(17 ): for j in range(3 , 20 ): _a = l[i][j] * l[i + 1][j - 1] * l[i + 2][j - 2] * l[i + 3][j - 3] if temp > maximum: _a = temp return maximum if __name__ == "__main__": print(solution())
366
'''simple docstring''' def _lowerCamelCase ( lowercase : int = 6008_5147_5143 ) -> int: try: _a = int(lowercase ) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int." ) if n <= 0: raise ValueError("Parameter n must be greater than or equal to one." ) _a = 2 _a = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 _a = i while n % i == 0: _a = n // i i += 1 return int(lowercase ) if __name__ == "__main__": print(f"""{solution() = }""")
346
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """google/vivit-b-16x2-kinetics400""": ( """https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json""" ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class A__ ( _lowerCamelCase): A_ : List[Any] = 'vivit' def __init__( self , _SCREAMING_SNAKE_CASE=2_24 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=[2, 16, 16] , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=7_68 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=30_72 , _SCREAMING_SNAKE_CASE="gelu_fast" , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=1E-06 , _SCREAMING_SNAKE_CASE=True , **_SCREAMING_SNAKE_CASE , ): __lowerCAmelCase : Dict = hidden_size __lowerCAmelCase : str = num_hidden_layers __lowerCAmelCase : Dict = num_attention_heads __lowerCAmelCase : Tuple = intermediate_size __lowerCAmelCase : Dict = hidden_act __lowerCAmelCase : List[str] = hidden_dropout_prob __lowerCAmelCase : Union[str, Any] = attention_probs_dropout_prob __lowerCAmelCase : Union[str, Any] = initializer_range __lowerCAmelCase : Optional[int] = layer_norm_eps __lowerCAmelCase : Optional[Any] = image_size __lowerCAmelCase : int = num_frames __lowerCAmelCase : Dict = tubelet_size __lowerCAmelCase : Union[str, Any] = num_channels __lowerCAmelCase : List[str] = qkv_bias super().__init__(**_SCREAMING_SNAKE_CASE )
86
"""simple docstring""" from .glue import GlueDataset, GlueDataTrainingArguments from .language_modeling import ( LineByLineTextDataset, LineByLineWithRefDataset, LineByLineWithSOPTextDataset, TextDataset, TextDatasetForNextSentencePrediction, ) from .squad import SquadDataset, SquadDataTrainingArguments
78
0
"""simple docstring""" import importlib import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional, Union import torch from ..utils import BaseOutput UpperCamelCase_ ="""scheduler_config.json""" class _a ( _lowerCAmelCase ): UpperCamelCase = 1 UpperCamelCase = 2 UpperCamelCase = 3 UpperCamelCase = 4 UpperCamelCase = 5 UpperCamelCase = 6 UpperCamelCase = 7 UpperCamelCase = 8 UpperCamelCase = 9 UpperCamelCase = 10 UpperCamelCase = 11 UpperCamelCase = 12 UpperCamelCase = 13 UpperCamelCase = 14 @dataclass class _a ( _lowerCAmelCase ): UpperCamelCase = 42 class _a : UpperCamelCase = SCHEDULER_CONFIG_NAME UpperCamelCase = [] UpperCamelCase = True @classmethod def snake_case ( cls : Any, lowerCAmelCase__ : Dict[str, Any] = None, lowerCAmelCase__ : Optional[str] = None, lowerCAmelCase__ : Dict=False, **lowerCAmelCase__ : Optional[int], ) -> Any: '''simple docstring''' _UpperCamelCase : int = cls.load_config( pretrained_model_name_or_path=lowerCAmelCase__, subfolder=lowerCAmelCase__, return_unused_kwargs=lowerCAmelCase__, return_commit_hash=lowerCAmelCase__, **lowerCAmelCase__, ) return cls.from_config(lowerCAmelCase__, return_unused_kwargs=lowerCAmelCase__, **lowerCAmelCase__ ) def snake_case ( self : Dict, lowerCAmelCase__ : Union[str, os.PathLike], lowerCAmelCase__ : bool = False, **lowerCAmelCase__ : Optional[int] ) -> Tuple: '''simple docstring''' self.save_config(save_directory=lowerCAmelCase__, push_to_hub=lowerCAmelCase__, **lowerCAmelCase__ ) @property def snake_case ( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' return self._get_compatibles() @classmethod def snake_case ( cls : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' _UpperCamelCase : Optional[int] = list(set([cls.__name__] + cls._compatibles ) ) _UpperCamelCase : Optional[int] = importlib.import_module(__name__.split('''.''' )[0] ) _UpperCamelCase : List[str] = [ getattr(lowerCAmelCase__, lowerCAmelCase__ ) for c in compatible_classes_str if hasattr(lowerCAmelCase__, lowerCAmelCase__ ) ] return compatible_classes
355
"""simple docstring""" class _a : def __init__( self : Optional[int], lowerCAmelCase__ : list ) -> None: '''simple docstring''' _UpperCamelCase : Optional[int] = set_counts _UpperCamelCase : Any = max(lowerCAmelCase__ ) _UpperCamelCase : int = len(lowerCAmelCase__ ) _UpperCamelCase : int = [1] * num_sets _UpperCamelCase : List[Any] = list(range(lowerCAmelCase__ ) ) def snake_case ( self : int, lowerCAmelCase__ : int, lowerCAmelCase__ : int ) -> bool: '''simple docstring''' _UpperCamelCase : Optional[Any] = self.get_parent(lowerCAmelCase__ ) _UpperCamelCase : Any = 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] _UpperCamelCase : List[Any] = 0 _UpperCamelCase : str = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 _UpperCamelCase : Union[str, Any] = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] _UpperCamelCase : Tuple = 0 _UpperCamelCase : Optional[Any] = src_parent _UpperCamelCase : int = self.set_counts[src_parent] _UpperCamelCase : Optional[Any] = max(self.max_set, lowerCAmelCase__ ) return True def snake_case ( self : Optional[Any], lowerCAmelCase__ : int ) -> int: '''simple docstring''' if self.parents[disj_set] == disj_set: return disj_set _UpperCamelCase : Union[str, Any] = self.get_parent(self.parents[disj_set] ) return self.parents[disj_set]
128
0
"""simple docstring""" from collections.abc import Iterable from typing import Any class __UpperCamelCase : def __init__( self , lowerCAmelCase__ = None ) -> List[str]: a : Optional[Any] = value a : Node | None = None # Added in order to delete a node easier a : Node | None = None a : Node | None = None def __repr__( self ) -> str: from pprint import pformat if self.left is None and self.right is None: return str(self.value ) return pformat({f"""{self.value}""": (self.left, self.right)} , indent=1 ) class __UpperCamelCase : def __init__( self , lowerCAmelCase__ = None ) -> Tuple: a : Dict = root def __str__( self ) -> str: return str(self.root ) def __a ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> None: if new_children is not None: # reset its kids a : Dict = node.parent if node.parent is not None: # reset its parent if self.is_right(lowerCAmelCase__ ): # If it is the right children a : Any = new_children else: a : Dict = new_children else: a : Any = new_children def __a ( self , lowerCAmelCase__ ) -> bool: if node.parent and node.parent.right: return node == node.parent.right return False def __a ( self ) -> bool: return self.root is None def __a ( self , lowerCAmelCase__ ) -> None: a : int = Node(lowerCAmelCase__ ) # create a new Node if self.empty(): # if Tree is empty a : Union[str, Any] = new_node # set its root else: # Tree is not empty a : Any = self.root # from root if parent_node is None: return while True: # While we don't get to a leaf if value < parent_node.value: # We go left if parent_node.left is None: a : Dict = new_node # We insert the new node in a leaf break else: a : Optional[int] = parent_node.left else: if parent_node.right is None: a : List[str] = new_node break else: a : Tuple = parent_node.right a : Union[str, Any] = parent_node def __a ( self , *lowerCAmelCase__ ) -> None: for value in values: self.__insert(lowerCAmelCase__ ) def __a ( self , lowerCAmelCase__ ) -> Node | None: if self.empty(): raise IndexError("Warning: Tree is empty! please use another." ) else: a : Any = self.root # use lazy evaluation here to avoid NoneType Attribute error while node is not None and node.value is not value: a : Tuple = node.left if value < node.value else node.right return node def __a ( self , lowerCAmelCase__ = None ) -> Node | None: if node is None: if self.root is None: return None a : List[str] = self.root if not self.empty(): while node.right is not None: a : Any = node.right return node def __a ( self , lowerCAmelCase__ = None ) -> Node | None: if node is None: a : str = self.root if self.root is None: return None if not self.empty(): a : Any = self.root while node.left is not None: a : Dict = node.left return node def __a ( self , lowerCAmelCase__ ) -> None: a : List[str] = self.search(lowerCAmelCase__ ) # Look for the node with that label if node is not None: if node.left is None and node.right is None: # If it has no children self.__reassign_nodes(lowerCAmelCase__ , lowerCAmelCase__ ) elif node.left is None: # Has only right children self.__reassign_nodes(lowerCAmelCase__ , node.right ) elif node.right is None: # Has only left children self.__reassign_nodes(lowerCAmelCase__ , node.left ) else: a : Union[str, Any] = self.get_max( node.left ) # Gets the max value of the left branch self.remove(tmp_node.value ) # type: ignore a : List[str] = ( tmp_node.value # type: ignore ) # Assigns the value to the node to delete and keep tree structure def __a ( self , lowerCAmelCase__ ) -> Iterable: if node is not None: yield node # Preorder Traversal yield from self.preorder_traverse(node.left ) yield from self.preorder_traverse(node.right ) def __a ( self , lowerCAmelCase__=None ) -> Any: if traversal_function is None: return self.preorder_traverse(self.root ) else: return traversal_function(self.root ) def __a ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> None: if node: self.inorder(lowerCAmelCase__ , node.left ) arr.append(node.value ) self.inorder(lowerCAmelCase__ , node.right ) def __a ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> int: a : list[int] = [] self.inorder(lowerCAmelCase__ , lowerCAmelCase__ ) # append all values to list using inorder traversal return arr[k - 1] def _SCREAMING_SNAKE_CASE ( _lowercase : Node | None ) ->list[Node]: '''simple docstring''' a : List[str] = [] if curr_node is not None: a : Dict = postorder(curr_node.left ) + postorder(curr_node.right ) + [curr_node] return node_list def _SCREAMING_SNAKE_CASE ( ) ->None: '''simple docstring''' a : Dict = (8, 3, 6, 1, 10, 14, 13, 4, 7) a : Union[str, Any] = BinarySearchTree() for i in testlist: t.insert(_lowercase ) # Prints all the elements of the list in order traversal print(_lowercase ) if t.search(6 ) is not None: print("The value 6 exists" ) else: print("The value 6 doesn't exist" ) if t.search(-1 ) is not None: print("The value -1 exists" ) else: print("The value -1 doesn't exist" ) if not t.empty(): print("Max Value: " , t.get_max().value ) # type: ignore print("Min Value: " , t.get_min().value ) # type: ignore for i in testlist: t.remove(_lowercase ) print(_lowercase ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
105
'''simple docstring''' import sacrebleu as scb from packaging import version from sacrebleu import TER import datasets _lowercase : List[str] = "\\n@inproceedings{snover-etal-2006-study,\n title = \"A Study of Translation Edit Rate with Targeted Human Annotation\",\n author = \"Snover, Matthew and\n Dorr, Bonnie and\n Schwartz, Rich and\n Micciulla, Linnea and\n Makhoul, John\",\n booktitle = \"Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers\",\n month = aug # \" 8-12\",\n year = \"2006\",\n address = \"Cambridge, Massachusetts, USA\",\n publisher = \"Association for Machine Translation in the Americas\",\n url = \"https://aclanthology.org/2006.amta-papers.25\",\n pages = \"223--231\",\n}\n@inproceedings{post-2018-call,\n title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n author = \"Post, Matt\",\n booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n month = oct,\n year = \"2018\",\n address = \"Belgium, Brussels\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W18-6319\",\n pages = \"186--191\",\n}\n" _lowercase : Tuple = "\\nTER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a\nhypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu\n(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found\nhere: https://github.com/jhclark/tercom.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information.\n" _lowercase : Optional[int] = "\nProduces TER scores alongside the number of edits and reference length.\n\nArgs:\n predictions (list of str): The system stream (a sequence of segments).\n references (list of list of str): A list of one or more reference streams (each a sequence of segments).\n normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,\n as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.\n Only applies if `normalized = True`. Defaults to `False`.\n case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.\n\nReturns:\n 'score' (float): TER score (num_edits / sum_ref_lengths * 100)\n 'num_edits' (int): The cumulative number of edits\n 'ref_length' (float): The cumulative average reference length\n\nExamples:\n Example 1:\n >>> predictions = [\"does this sentence match??\",\n ... \"what about this sentence?\",\n ... \"What did the TER metric user say to the developer?\"]\n >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],\n ... [\"Your jokes are...\", \"...TERrible\"]]\n >>> ter = datasets.load_metric(\"ter\")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... case_sensitive=True)\n >>> print(results)\n {'score': 150.0, 'num_edits': 15, 'ref_length': 10.0}\n\n Example 2:\n >>> predictions = [\"does this sentence match??\",\n ... \"what about this sentence?\"]\n >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n >>> ter = datasets.load_metric(\"ter\")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... case_sensitive=True)\n >>> print(results)\n {'score': 62.5, 'num_edits': 5, 'ref_length': 8.0}\n\n Example 3:\n >>> predictions = [\"does this sentence match??\",\n ... \"what about this sentence?\"]\n >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n >>> ter = datasets.load_metric(\"ter\")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... normalized=True,\n ... case_sensitive=True)\n >>> print(results)\n {'score': 57.14285714285714, 'num_edits': 6, 'ref_length': 10.5}\n\n Example 4:\n >>> predictions = [\"does this sentence match??\",\n ... \"what about this sentence?\"]\n >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n >>> ter = datasets.load_metric(\"ter\")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... ignore_punct=True,\n ... case_sensitive=False)\n >>> print(results)\n {'score': 0.0, 'num_edits': 0, 'ref_length': 8.0}\n\n Example 5:\n >>> predictions = [\"does this sentence match??\",\n ... \"what about this sentence?\",\n ... \"What did the TER metric user say to the developer?\"]\n >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],\n ... [\"Your jokes are...\", \"...TERrible\"]]\n >>> ter = datasets.load_metric(\"ter\")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... ignore_punct=True,\n ... case_sensitive=False)\n >>> print(results)\n {'score': 100.0, 'num_edits': 10, 'ref_length': 10.0}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION) class __magic_name__ ( datasets.Metric): def SCREAMING_SNAKE_CASE_ ( self : int ): if version.parse(scb.__version__ ) < version.parse("""1.4.12""" ): raise ImportWarning( """To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n""" """You can install it with `pip install \"sacrebleu>=1.4.12\"`.""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="""http://www.cs.umd.edu/~snover/tercom/""" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Sequence(datasets.Value("""string""" , id="""sequence""" ) , id="""references""" ), } ) , codebase_urls=["""https://github.com/mjpost/sacreBLEU#ter"""] , reference_urls=[ """https://github.com/jhclark/tercom""", ] , ) def SCREAMING_SNAKE_CASE_ ( self : Any , lowercase_ : Any , lowercase_ : Tuple , lowercase_ : bool = False , lowercase_ : bool = False , lowercase_ : bool = False , lowercase_ : bool = False , ): lowercase_ : int = len(references[0] ) if any(len(lowercase_ ) != references_per_prediction for refs in references ): raise ValueError("""Sacrebleu requires the same number of references for each prediction""" ) lowercase_ : Optional[int] = [[refs[i] for refs in references] for i in range(lowercase_ )] lowercase_ : List[str] = TER( normalized=lowercase_ , no_punct=lowercase_ , asian_support=lowercase_ , case_sensitive=lowercase_ , ) lowercase_ : List[str] = sb_ter.corpus_score(lowercase_ , lowercase_ ) return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}
239
0
"""simple docstring""" import unittest import numpy as np from transformers.file_utils import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class a ( unittest.TestCase ): def __init__( self : Optional[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : int=7 , __lowerCAmelCase : Any=3 , __lowerCAmelCase : Dict=18 , __lowerCAmelCase : str=30 , __lowerCAmelCase : List[str]=400 , __lowerCAmelCase : Any=True , __lowerCAmelCase : Tuple=None , __lowerCAmelCase : Tuple=True , __lowerCAmelCase : int=[0.5, 0.5, 0.5] , __lowerCAmelCase : Dict=[0.5, 0.5, 0.5] , ): _UpperCAmelCase = size if size is not None else {"""height""": 18, """width""": 18} _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = image_size _UpperCAmelCase = min_resolution _UpperCAmelCase = max_resolution _UpperCAmelCase = do_resize _UpperCAmelCase = size _UpperCAmelCase = do_normalize _UpperCAmelCase = image_mean _UpperCAmelCase = image_std def lowerCAmelCase_ ( self : Dict ): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class a ( lowerCAmelCase_ , unittest.TestCase ): _snake_case : Union[str, Any] = DPTImageProcessor if is_vision_available() else None def lowerCAmelCase_ ( self : List[Any] ): _UpperCAmelCase = DPTImageProcessingTester(self ) @property def lowerCAmelCase_ ( self : List[str] ): return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase_ ( self : str ): _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowerCAmelCase , """image_mean""" ) ) self.assertTrue(hasattr(__lowerCAmelCase , """image_std""" ) ) self.assertTrue(hasattr(__lowerCAmelCase , """do_normalize""" ) ) self.assertTrue(hasattr(__lowerCAmelCase , """do_resize""" ) ) self.assertTrue(hasattr(__lowerCAmelCase , """size""" ) ) def lowerCAmelCase_ ( self : Union[str, Any] ): _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 18, """width""": 18} ) _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) def lowerCAmelCase_ ( self : Union[str, Any] ): # Initialize image_processing _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(__lowerCAmelCase , Image.Image ) # Test not batched input _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched _UpperCAmelCase = image_processing(__lowerCAmelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) def lowerCAmelCase_ ( self : List[str] ): # Initialize image_processing _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCAmelCase , numpify=__lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(__lowerCAmelCase , np.ndarray ) # Test not batched input _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched _UpperCAmelCase = image_processing(__lowerCAmelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) def lowerCAmelCase_ ( self : str ): # Initialize image_processing _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCAmelCase , torchify=__lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(__lowerCAmelCase , torch.Tensor ) # Test not batched input _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched _UpperCAmelCase = image_processing(__lowerCAmelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , )
30
"""simple docstring""" import string from math import logaa def __UpperCAmelCase ( lowercase ,lowercase ): """simple docstring""" _UpperCAmelCase = document.translate( str.maketrans("""""" ,"""""" ,string.punctuation ) ).replace("""\n""" ,"""""" ) _UpperCAmelCase = document_without_punctuation.split(""" """ ) # word tokenization return len([word for word in tokenize_document if word.lower() == term.lower()] ) def __UpperCAmelCase ( lowercase ,lowercase ): """simple docstring""" _UpperCAmelCase = corpus.lower().translate( str.maketrans("""""" ,"""""" ,string.punctuation ) ) # strip all punctuation and replace it with '' _UpperCAmelCase = corpus_without_punctuation.split("""\n""" ) _UpperCAmelCase = term.lower() return (len([doc for doc in docs if term in doc] ), len(lowercase )) def __UpperCAmelCase ( lowercase ,lowercase ,lowercase=False ): """simple docstring""" if smoothing: if n == 0: raise ValueError("""log10(0) is undefined.""" ) return round(1 + logaa(n / (1 + df) ) ,3 ) if df == 0: raise ZeroDivisionError("""df must be > 0""" ) elif n == 0: raise ValueError("""log10(0) is undefined.""" ) return round(logaa(n / df ) ,3 ) def __UpperCAmelCase ( lowercase ,lowercase ): """simple docstring""" return round(tf * idf ,3 )
30
1
from ...configuration_utils import PretrainedConfig from ...utils import logging A__ = logging.get_logger(__name__) A__ = { """MIT/ast-finetuned-audioset-10-10-0.4593""": ( """https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json""" ), } class __lowerCAmelCase ( lowerCamelCase__ ): __lowerCamelCase = '''audio-spectrogram-transformer''' def __init__( self , _snake_case=768 , _snake_case=12 , _snake_case=12 , _snake_case=3072 , _snake_case="gelu" , _snake_case=0.0 , _snake_case=0.0 , _snake_case=0.02 , _snake_case=1e-12 , _snake_case=16 , _snake_case=True , _snake_case=10 , _snake_case=10 , _snake_case=1024 , _snake_case=128 , **_snake_case , ): """simple docstring""" super().__init__(**_snake_case ) _lowerCAmelCase = hidden_size _lowerCAmelCase = num_hidden_layers _lowerCAmelCase = num_attention_heads _lowerCAmelCase = intermediate_size _lowerCAmelCase = hidden_act _lowerCAmelCase = hidden_dropout_prob _lowerCAmelCase = attention_probs_dropout_prob _lowerCAmelCase = initializer_range _lowerCAmelCase = layer_norm_eps _lowerCAmelCase = patch_size _lowerCAmelCase = qkv_bias _lowerCAmelCase = frequency_stride _lowerCAmelCase = time_stride _lowerCAmelCase = max_length _lowerCAmelCase = num_mel_bins
82
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) lowerCAmelCase__ = """\ Text data. Second line of data.""" lowerCAmelCase__ = """file""" @pytest.fixture(scope="session" ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[Any] ) -> Optional[int]: '''simple docstring''' A__ = tmp_path_factory.mktemp("data" ) / (FILE_PATH + ".zstd") A__ = bytes(SCREAMING_SNAKE_CASE_ , "utf-8" ) with zstd.open(SCREAMING_SNAKE_CASE_ , "wb" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) return path @pytest.fixture def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Any ) -> List[str]: '''simple docstring''' with open(os.path.join(tmpfs.local_root_dir , SCREAMING_SNAKE_CASE_ ) , "w" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) return FILE_PATH @pytest.mark.parametrize("compression_format" , ["gzip", "xz", "zstd"] ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] , SCREAMING_SNAKE_CASE_: Any , SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: Any , SCREAMING_SNAKE_CASE_: Optional[Any] , SCREAMING_SNAKE_CASE_: int ) -> Any: '''simple docstring''' A__ = {"gzip": gz_file, "xz": xz_file, "zstd": zstd_path} A__ = input_paths[compression_format] A__ = tmp_path / "cache" A__ = DownloadConfig(cache_dir=SCREAMING_SNAKE_CASE_ , extract_compressed_file=SCREAMING_SNAKE_CASE_ ) A__ = cached_path(SCREAMING_SNAKE_CASE_ , download_config=SCREAMING_SNAKE_CASE_ ) with open(SCREAMING_SNAKE_CASE_ ) as f: A__ = f.read() with open(SCREAMING_SNAKE_CASE_ ) as f: A__ = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("default_extracted" , [True, False] ) @pytest.mark.parametrize("default_cache_dir" , [True, False] ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] , SCREAMING_SNAKE_CASE_: List[Any] , SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: Tuple , SCREAMING_SNAKE_CASE_: str ) -> Dict: '''simple docstring''' A__ = "custom_cache" A__ = "custom_extracted_dir" A__ = tmp_path / "custom_extracted_path" if default_extracted: A__ = ("downloads" if default_cache_dir else custom_cache_dir, "extracted") else: monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_DIR" , SCREAMING_SNAKE_CASE_ ) monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_PATH" , str(SCREAMING_SNAKE_CASE_ ) ) A__ = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) A__ = xz_file A__ = ( DownloadConfig(extract_compressed_file=SCREAMING_SNAKE_CASE_ ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=SCREAMING_SNAKE_CASE_ ) ) A__ = cached_path(SCREAMING_SNAKE_CASE_ , download_config=SCREAMING_SNAKE_CASE_ ) assert Path(SCREAMING_SNAKE_CASE_ ).parent.parts[-2:] == expected def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] ) -> Optional[int]: '''simple docstring''' A__ = str(Path(SCREAMING_SNAKE_CASE_ ).resolve() ) assert cached_path(SCREAMING_SNAKE_CASE_ ) == text_file # relative path A__ = str(Path(SCREAMING_SNAKE_CASE_ ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(SCREAMING_SNAKE_CASE_ ) == text_file def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Dict ) -> List[str]: '''simple docstring''' A__ = str(tmp_path.resolve() / "__missing_file__.txt" ) with pytest.raises(SCREAMING_SNAKE_CASE_ ): cached_path(SCREAMING_SNAKE_CASE_ ) # relative path A__ = "./__missing_file__.txt" with pytest.raises(SCREAMING_SNAKE_CASE_ ): cached_path(SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str ) -> Union[str, Any]: '''simple docstring''' A__ = get_from_cache(F'tmp://{tmpfs_file}' ) with open(SCREAMING_SNAKE_CASE_ ) as f: A__ = f.read() assert output_file_content == FILE_CONTENT @patch("datasets.config.HF_DATASETS_OFFLINE" , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( ) -> List[Any]: '''simple docstring''' with pytest.raises(SCREAMING_SNAKE_CASE_ ): cached_path("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] ) -> int: '''simple docstring''' A__ = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(SCREAMING_SNAKE_CASE_ ): http_get("https://huggingface.co" , temp_file=SCREAMING_SNAKE_CASE_ ) with pytest.raises(SCREAMING_SNAKE_CASE_ ): http_head("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Dict ) -> List[Any]: '''simple docstring''' A__ = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(SCREAMING_SNAKE_CASE_ ): ftp_get("ftp://huggingface.co" , temp_file=SCREAMING_SNAKE_CASE_ ) with pytest.raises(SCREAMING_SNAKE_CASE_ ): ftp_head("ftp://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Union[str, Any] ) -> str: '''simple docstring''' A__ = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(SCREAMING_SNAKE_CASE_ ): fsspec_get("s3://huggingface.co" , temp_file=SCREAMING_SNAKE_CASE_ ) with pytest.raises(SCREAMING_SNAKE_CASE_ ): fsspec_head("s3://huggingface.co" )
68
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__:List[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:List[str] = { """google/mobilenet_v1_1.0_224""": """https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json""", """google/mobilenet_v1_0.75_192""": """https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json""", # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 } class snake_case__ ( snake_case_ ): _snake_case : Dict = """mobilenet_v1""" def __init__( self , lowerCamelCase=3 , lowerCamelCase=224 , lowerCamelCase=1.0 , lowerCamelCase=8 , lowerCamelCase="relu6" , lowerCamelCase=True , lowerCamelCase=0.999 , lowerCamelCase=0.02 , lowerCamelCase=0.001 , **lowerCamelCase , ): super().__init__(**lowerCamelCase ) if depth_multiplier <= 0: raise ValueError("depth_multiplier must be greater than zero." ) __a = num_channels __a = image_size __a = depth_multiplier __a = min_depth __a = hidden_act __a = tf_padding __a = classifier_dropout_prob __a = initializer_range __a = layer_norm_eps class snake_case__ ( snake_case_ ): _snake_case : int = version.parse("""1.11""" ) @property def a__ ( self ): return OrderedDict([("pixel_values", {0: "batch"})] ) @property def a__ ( self ): if self.task == "image-classification": return OrderedDict([("logits", {0: "batch"})] ) else: return OrderedDict([("last_hidden_state", {0: "batch"}), ("pooler_output", {0: "batch"})] ) @property def a__ ( self ): return 1E-4
353
"""simple docstring""" from __future__ import annotations def _lowerCamelCase( a , a , a , a , a , ): __a = len(a ) # If row is equal to the size of the board it means there are a queen in each row in # the current board (possible_board) if row == n: # We convert the variable possible_board that looks like this: [1, 3, 0, 2] to # this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] boards.append([". " * i + "Q " + ". " * (n - 1 - i) for i in possible_board] ) return # We iterate each column in the row to find all possible results in each row for col in range(a ): # We apply that we learned previously. First we check that in the current board # (possible_board) there are not other same value because if there is it means # that there are a collision in vertical. Then we apply the two formulas we # learned before: # # 45º: y - x = b or 45: row - col = b # 135º: y + x = b or row + col = b. # # And we verify if the results of this two formulas not exist in their variables # respectively. (diagonal_right_collisions, diagonal_left_collisions) # # If any or these are True it means there is a collision so we continue to the # next value in the for loop. if ( col in possible_board or row - col in diagonal_right_collisions or row + col in diagonal_left_collisions ): continue # If it is False we call dfs function again and we update the inputs depth_first_search( [*possible_board, col] , [*diagonal_right_collisions, row - col] , [*diagonal_left_collisions, row + col] , a , a , ) def _lowerCamelCase( a ): __a = [] depth_first_search([] , [] , [] , a , a ) # Print all the boards for board in boards: for column in board: print(a ) print("" ) print(len(a ) , "solutions were found." ) if __name__ == "__main__": import doctest doctest.testmod() n_queens_solution(4)
268
0
from statistics import mean, stdev def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 3 ): A_ : List[str] = min(SCREAMING_SNAKE_CASE ) A_ : Any = max(SCREAMING_SNAKE_CASE ) # normalize data return [round((x - x_min) / (x_max - x_min) , SCREAMING_SNAKE_CASE ) for x in data] def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 3 ): A_ : List[Any] = mean(SCREAMING_SNAKE_CASE ) A_ : List[Any] = stdev(SCREAMING_SNAKE_CASE ) # standardize data return [round((x - mu) / (sigma) , SCREAMING_SNAKE_CASE ) for x in data]
186
from math import isclose, sqrt def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A_ : List[str] = point_y / 4 / point_x A_ : Union[str, Any] = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) A_ : int = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) A_ : List[str] = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 A_ : List[str] = outgoing_gradient**2 + 4 A_ : List[str] = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) A_ : Any = (point_y - outgoing_gradient * point_x) ** 2 - 100 A_ : str = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) A_ : Any = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point A_ : int = x_minus if isclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) else x_plus A_ : Any = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE = 1.4 , SCREAMING_SNAKE_CASE = -9.6 ): A_ : int = 0 A_ : float = first_x_coord A_ : float = first_y_coord A_ : float = (1_0.1 - point_y) / (0.0 - point_x) while not (-0.0_1 <= point_x <= 0.0_1 and point_y > 0): A_ , A_ , A_ : List[str] = next_point(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F'''{solution() = }''')
186
1
import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, PLBartTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin __UpperCAmelCase = get_tests_dir("fixtures/test_sentencepiece.model") if is_torch_available(): from transformers.models.plbart.modeling_plbart import shift_tokens_right __UpperCAmelCase = 5_00_03 __UpperCAmelCase = 5_00_02 @require_sentencepiece @require_tokenizers class UpperCamelCase__ ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ =PLBartTokenizer UpperCAmelCase_ =None UpperCAmelCase_ =False def _UpperCamelCase ( self ) -> Optional[Any]: super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE_ = PLBartTokenizer(_A , language_codes='''base''' , keep_accents=_A ) tokenizer.save_pretrained(self.tmpdirname ) def _UpperCamelCase ( self ) -> int: SCREAMING_SNAKE_CASE_ = PLBartTokenizer(_A , language_codes='''base''' , 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 ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) SCREAMING_SNAKE_CASE_ = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( _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 , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) SCREAMING_SNAKE_CASE_ = tokenizer.convert_ids_to_tokens(_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>''', '''.''', ] , ) SCREAMING_SNAKE_CASE_ = tokenizer.vocab_size SCREAMING_SNAKE_CASE_ = [tokenizer.convert_ids_to_tokens(_A ) for x in range(end - 4 , _A )] self.assertListEqual(_A , ['''__java__''', '''__python__''', '''__en_XX__''', '''<mask>'''] ) SCREAMING_SNAKE_CASE_ = '''java.lang.Exception, python.lang.Exception, javascript, php, ruby, go''' SCREAMING_SNAKE_CASE_ = tokenizer(_A ).input_ids self.assertEqual( tokenizer.decode(_A , skip_special_tokens=_A , clean_up_tokenization_spaces=_A ) , _A , ) def _UpperCamelCase ( self ) -> List[Any]: SCREAMING_SNAKE_CASE_ = PLBartTokenizer(_A , language_codes='''multi''' , 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 ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) SCREAMING_SNAKE_CASE_ = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( _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 , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) SCREAMING_SNAKE_CASE_ = tokenizer.convert_ids_to_tokens(_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>''', '''.''', ] , ) SCREAMING_SNAKE_CASE_ = tokenizer.vocab_size SCREAMING_SNAKE_CASE_ = [tokenizer.convert_ids_to_tokens(_A ) for x in range(end - 7 , _A )] self.assertListEqual( _A , ['''__java__''', '''__python__''', '''__en_XX__''', '''__javascript__''', '''__php__''', '''__ruby__''', '''__go__'''] ) SCREAMING_SNAKE_CASE_ = '''java.lang.Exception, python.lang.Exception, javascript, php, ruby, go''' SCREAMING_SNAKE_CASE_ = tokenizer(_A ).input_ids self.assertEqual( tokenizer.decode(_A , skip_special_tokens=_A , clean_up_tokenization_spaces=_A ) , _A , ) @require_torch @require_sentencepiece @require_tokenizers class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" UpperCAmelCase_ ="uclanlp/plbart-python-en_XX" UpperCAmelCase_ =[ "def maximum(a,b,c):NEW_LINE_INDENTreturn max([a,b,c])", "def sum(a,b,c):NEW_LINE_INDENTreturn sum([a,b,c])", ] UpperCAmelCase_ =[ "Returns the maximum value of a b c.", "Sums the values of a b c.", ] UpperCAmelCase_ =[ 134, 5_452, 33_460, 33_441, 33_463, 33_465, 33_463, 33_449, 988, 20, 33_456, 19, 33_456, 771, 39, 4_258, 889, 3_318, 33_441, 33_463, 33_465, 33_463, 33_449, 2_471, 2, PYTHON_CODE, ] @classmethod def _UpperCamelCase ( cls ) -> List[Any]: SCREAMING_SNAKE_CASE_ = PLBartTokenizer.from_pretrained( cls.checkpoint_name , language_codes='''base''' , src_lang='''python''' , tgt_lang='''en_XX''' ) SCREAMING_SNAKE_CASE_ = 1 return cls def _UpperCamelCase ( self ) -> Optional[int]: self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''__java__'''] , 50001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''__python__'''] , 50002 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''__en_XX__'''] , 50003 ) def _UpperCamelCase ( self ) -> Union[str, Any]: SCREAMING_SNAKE_CASE_ = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , _A ) def _UpperCamelCase ( self ) -> Tuple: self.assertIn(_A , self.tokenizer.all_special_ids ) SCREAMING_SNAKE_CASE_ = [EN_CODE, 9037, 33442, 57, 752, 153, 14, 56, 18, 9, 2] SCREAMING_SNAKE_CASE_ = self.tokenizer.decode(_A , skip_special_tokens=_A ) SCREAMING_SNAKE_CASE_ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=_A ) self.assertEqual(_A , _A ) self.assertNotIn(self.tokenizer.eos_token , _A ) def _UpperCamelCase ( self ) -> Tuple: SCREAMING_SNAKE_CASE_ = ['''def sum(a,b,c):NEW_LINE_INDENTreturn sum([a,b,c])''' * 20] self.assertIsInstance(src_text[0] , _A ) SCREAMING_SNAKE_CASE_ = 10 SCREAMING_SNAKE_CASE_ = self.tokenizer(_A , max_length=_A , truncation=_A ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , _A ) self.assertEqual(len(_A ) , _A ) def _UpperCamelCase ( self ) -> str: self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['''<mask>''', '''__java__'''] ) , [50004, 50001] ) def _UpperCamelCase ( self ) -> Any: SCREAMING_SNAKE_CASE_ = tempfile.mkdtemp() SCREAMING_SNAKE_CASE_ = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(_A ) SCREAMING_SNAKE_CASE_ = PLBartTokenizer.from_pretrained(_A ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , _A ) @require_torch def _UpperCamelCase ( self ) -> int: SCREAMING_SNAKE_CASE_ = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=_A , return_tensors='''pt''' ) SCREAMING_SNAKE_CASE_ = shift_tokens_right(batch['''labels'''] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 self.assertEqual(batch.input_ids[1][-2:].tolist() , [2, PYTHON_CODE] ) self.assertEqual(batch.decoder_input_ids[1][0] , _A ) self.assertEqual(batch.decoder_input_ids[1][-1] , 2 ) self.assertEqual(batch.labels[1][-2:].tolist() , [2, EN_CODE] ) @require_torch def _UpperCamelCase ( self ) -> Tuple: SCREAMING_SNAKE_CASE_ = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=_A , truncation=_A , max_length=len(self.expected_src_tokens ) , return_tensors='''pt''' , ) SCREAMING_SNAKE_CASE_ = shift_tokens_right(batch['''labels'''] , self.tokenizer.pad_token_id ) self.assertIsInstance(_A , _A ) self.assertEqual((2, 26) , batch.input_ids.shape ) self.assertEqual((2, 26) , batch.attention_mask.shape ) SCREAMING_SNAKE_CASE_ = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , _A ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, PYTHON_CODE] ) def _UpperCamelCase ( self ) -> Dict: SCREAMING_SNAKE_CASE_ = self.tokenizer(self.src_text , padding=_A , truncation=_A , max_length=3 , return_tensors='''pt''' ) SCREAMING_SNAKE_CASE_ = self.tokenizer( text_target=self.tgt_text , padding=_A , truncation=_A , max_length=10 , return_tensors='''pt''' ) SCREAMING_SNAKE_CASE_ = targets['''input_ids'''] SCREAMING_SNAKE_CASE_ = shift_tokens_right(_A , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def _UpperCamelCase ( self ) -> List[str]: SCREAMING_SNAKE_CASE_ = self.tokenizer._build_translation_inputs( '''A test''' , return_tensors='''pt''' , src_lang='''en_XX''' , tgt_lang='''java''' ) self.assertEqual( nested_simplify(_A ) , { # A, test, EOS, en_XX '''input_ids''': [[150, 242, 2, 50003]], '''attention_mask''': [[1, 1, 1, 1]], # java '''forced_bos_token_id''': 50001, } , )
257
import datasets from .nmt_bleu import compute_bleu # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py __UpperCAmelCase = "\\n@INPROCEEDINGS{Papineni02bleu:a,\n author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu},\n title = {BLEU: a Method for Automatic Evaluation of Machine Translation},\n booktitle = {},\n year = {2002},\n pages = {311--318}\n}\n@inproceedings{lin-och-2004-orange,\n title = \"{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation\",\n author = \"Lin, Chin-Yew and\n Och, Franz Josef\",\n booktitle = \"{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics\",\n month = \"aug 23{--}aug 27\",\n year = \"2004\",\n address = \"Geneva, Switzerland\",\n publisher = \"COLING\",\n url = \"https://www.aclweb.org/anthology/C04-1072\",\n pages = \"501--507\",\n}\n" __UpperCAmelCase = "\\nBLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another.\nQuality is considered to be the correspondence between a machine's output and that of a human: \"the closer a machine translation is to a professional human translation,\nthe better it is\" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and\nremains one of the most popular automated and inexpensive metrics.\n\nScores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations.\nThose scores are then averaged over the whole corpus to reach an estimate of the translation's overall quality. Intelligibility or grammatical correctness\nare not taken into account[citation needed].\n\nBLEU's output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1\nrepresenting more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the\nreference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional\nreference translations will increase the BLEU score.\n" __UpperCAmelCase = "\nComputes BLEU score of translated segments against one or more references.\nArgs:\n predictions: list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references: list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n max_order: Maximum n-gram order to use when computing BLEU score.\n smooth: Whether or not to apply Lin et al. 2004 smoothing.\nReturns:\n 'bleu': bleu score,\n 'precisions': geometric mean of n-gram precisions,\n 'brevity_penalty': brevity penalty,\n 'length_ratio': ratio of lengths,\n 'translation_length': translation_length,\n 'reference_length': reference_length\nExamples:\n\n >>> predictions = [\n ... [\"hello\", \"there\", \"general\", \"kenobi\"], # tokenized prediction of the first sample\n ... [\"foo\", \"bar\", \"foobar\"] # tokenized prediction of the second sample\n ... ]\n >>> references = [\n ... [[\"hello\", \"there\", \"general\", \"kenobi\"], [\"hello\", \"there\", \"!\"]], # tokenized references for the first sample (2 references)\n ... [[\"foo\", \"bar\", \"foobar\"]] # tokenized references for the second sample (1 reference)\n ... ]\n >>> bleu = datasets.load_metric(\"bleu\")\n >>> results = bleu.compute(predictions=predictions, references=references)\n >>> print(results[\"bleu\"])\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCamelCase__ ( datasets.Metric ): """simple docstring""" def _UpperCamelCase ( self ) -> Optional[int]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''' , id='''token''' ) , id='''sequence''' ), '''references''': datasets.Sequence( datasets.Sequence(datasets.Value('''string''' , id='''token''' ) , id='''sequence''' ) , id='''references''' ), } ) , codebase_urls=['''https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py'''] , reference_urls=[ '''https://en.wikipedia.org/wiki/BLEU''', '''https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213''', ] , ) def _UpperCamelCase ( self , _A , _A , _A=4 , _A=False ) -> List[str]: SCREAMING_SNAKE_CASE_ = compute_bleu( reference_corpus=_A , translation_corpus=_A , max_order=_A , smooth=_A ) ((SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_)) = score return { "bleu": bleu, "precisions": precisions, "brevity_penalty": bp, "length_ratio": ratio, "translation_length": translation_length, "reference_length": reference_length, }
257
1
import argparse import os import re import packaging.version SCREAMING_SNAKE_CASE__ = """examples/""" SCREAMING_SNAKE_CASE__ = { """examples""": (re.compile(r"""^check_min_version\(\"[^\"]+\"\)\s*$""", re.MULTILINE), """check_min_version(\"VERSION\")\n"""), """init""": (re.compile(r"""^__version__\s+=\s+\"([^\"]+)\"\s*$""", re.MULTILINE), """__version__ = \"VERSION\"\n"""), """setup""": (re.compile(r"""^(\s*)version\s*=\s*\"[^\"]+\",""", re.MULTILINE), r"""\1version=\"VERSION\","""), """doc""": (re.compile(r"""^(\s*)release\s*=\s*\"[^\"]+\"$""", re.MULTILINE), """release = \"VERSION\"\n"""), } SCREAMING_SNAKE_CASE__ = { """init""": """src/diffusers/__init__.py""", """setup""": """setup.py""", } SCREAMING_SNAKE_CASE__ = """README.md""" def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : Optional[int] ) -> Optional[int]: with open(SCREAMING_SNAKE_CASE , 'r' , encoding='utf-8' , newline='\n' ) as f: __lowercase = f.read() __lowercase , __lowercase = REPLACE_PATTERNS[pattern] __lowercase = replace.replace('VERSION' , SCREAMING_SNAKE_CASE ) __lowercase = re_pattern.sub(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) with open(SCREAMING_SNAKE_CASE , 'w' , encoding='utf-8' , newline='\n' ) as f: f.write(SCREAMING_SNAKE_CASE ) def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : List[str] ) -> str: for folder, directories, fnames in os.walk(SCREAMING_SNAKE_CASE ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove('research_projects' ) if "legacy" in directories: directories.remove('legacy' ) for fname in fnames: if fname.endswith('.py' ): update_version_in_file(os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE , pattern='examples' ) def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Tuple: for pattern, fname in REPLACE_FILES.items(): update_version_in_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if not patch: update_version_in_examples(SCREAMING_SNAKE_CASE ) def __SCREAMING_SNAKE_CASE ( ) -> int: __lowercase = '🤗 Transformers currently provides the following architectures' __lowercase = '1. Want to contribute a new model?' with open(SCREAMING_SNAKE_CASE , 'r' , encoding='utf-8' , newline='\n' ) as f: __lowercase = f.readlines() # Find the start of the list. __lowercase = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 __lowercase = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith('1.' ): __lowercase = lines[index].replace( 'https://huggingface.co/docs/diffusers/main/model_doc' , 'https://huggingface.co/docs/diffusers/model_doc' , ) index += 1 with open(SCREAMING_SNAKE_CASE , 'w' , encoding='utf-8' , newline='\n' ) as f: f.writelines(SCREAMING_SNAKE_CASE ) def __SCREAMING_SNAKE_CASE ( ) -> int: with open(REPLACE_FILES['init'] , 'r' ) as f: __lowercase = f.read() __lowercase = REPLACE_PATTERNS['init'][0].search(SCREAMING_SNAKE_CASE ).groups()[0] return packaging.version.parse(SCREAMING_SNAKE_CASE ) def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : List[str]=False ) -> Optional[Any]: __lowercase = get_version() if patch and default_version.is_devrelease: raise ValueError('Can\'t create a patch version from the dev branch, checkout a released version!' ) if default_version.is_devrelease: __lowercase = default_version.base_version elif patch: __lowercase = F"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}""" else: __lowercase = F"""{default_version.major}.{default_version.minor + 1}.0""" # Now let's ask nicely if that's the right one. __lowercase = input(F"""Which version are you releasing? [{default_version}]""" ) if len(SCREAMING_SNAKE_CASE ) == 0: __lowercase = default_version print(F"""Updating version to {version}.""" ) global_version_update(SCREAMING_SNAKE_CASE , patch=SCREAMING_SNAKE_CASE ) def __SCREAMING_SNAKE_CASE ( ) -> Dict: __lowercase = get_version() __lowercase = F"""{current_version.major}.{current_version.minor + 1}.0.dev0""" __lowercase = current_version.base_version # Check with the user we got that right. __lowercase = input(F"""Which version are we developing now? [{dev_version}]""" ) if len(SCREAMING_SNAKE_CASE ) == 0: __lowercase = dev_version print(F"""Updating version to {version}.""" ) global_version_update(SCREAMING_SNAKE_CASE ) # print("Cleaning main README, don't forget to run `make fix-copies`.") # clean_main_ref_in_model_list() if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() parser.add_argument("""--post_release""", action="""store_true""", help="""Whether this is pre or post release.""") parser.add_argument("""--patch""", action="""store_true""", help="""Whether or not this is a patch release.""") SCREAMING_SNAKE_CASE__ = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("""Nothing to do after a patch :-)""") else: post_release_work()
325
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision import transforms from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : Optional[int] ) -> Union[str, Any]: __lowercase = [2, 2, 6, 2] if 'tiny' in model_name else [2, 2, 18, 2] __lowercase = True if 'large' in model_name or 'huge' in model_name else False __lowercase = True if 'large' in model_name or 'huge' in model_name else False __lowercase = True if 'large' in model_name or 'huge' in model_name else False if "large" in model_name or "xlarge" in model_name or "huge" in model_name: if "fl3" in model_name: __lowercase = [3, 3, 3, 3] __lowercase = [5, 5, 5, 5] elif "fl4" in model_name: __lowercase = [4, 4, 4, 4] __lowercase = [3, 3, 3, 3] if "tiny" in model_name or "small" in model_name or "base" in model_name: __lowercase = [3, 3, 3, 3] if "lrf" in model_name: __lowercase = [3, 3, 3, 3] else: __lowercase = [2, 2, 2, 2] if "tiny" in model_name: __lowercase = 96 elif "small" in model_name: __lowercase = 96 elif "base" in model_name: __lowercase = 128 elif "large" in model_name: __lowercase = 192 elif "xlarge" in model_name: __lowercase = 256 elif "huge" in model_name: __lowercase = 352 # set label information __lowercase = 'huggingface/label-files' if "large" in model_name or "huge" in model_name: __lowercase = 'imagenet-22k-id2label.json' else: __lowercase = 'imagenet-1k-id2label.json' __lowercase = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , repo_type='dataset' ) , 'r' ) ) __lowercase = {int(SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} __lowercase = {v: k for k, v in idalabel.items()} __lowercase = FocalNetConfig( embed_dim=SCREAMING_SNAKE_CASE , depths=SCREAMING_SNAKE_CASE , focal_levels=SCREAMING_SNAKE_CASE , focal_windows=SCREAMING_SNAKE_CASE , use_conv_embed=SCREAMING_SNAKE_CASE , idalabel=SCREAMING_SNAKE_CASE , labelaid=SCREAMING_SNAKE_CASE , use_post_layernorm=SCREAMING_SNAKE_CASE , use_layerscale=SCREAMING_SNAKE_CASE , ) return config def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : Dict ) -> Dict: if "patch_embed.proj" in name: __lowercase = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: __lowercase = name.replace('patch_embed.norm' , 'embeddings.norm' ) if "layers" in name: __lowercase = 'encoder.' + name if "encoder.layers" in name: __lowercase = name.replace('encoder.layers' , 'encoder.stages' ) if "downsample.proj" in name: __lowercase = name.replace('downsample.proj' , 'downsample.projection' ) if "blocks" in name: __lowercase = name.replace('blocks' , 'layers' ) if "modulation.f.weight" in name or "modulation.f.bias" in name: __lowercase = name.replace('modulation.f' , 'modulation.projection_in' ) if "modulation.h.weight" in name or "modulation.h.bias" in name: __lowercase = name.replace('modulation.h' , 'modulation.projection_context' ) if "modulation.proj.weight" in name or "modulation.proj.bias" in name: __lowercase = name.replace('modulation.proj' , 'modulation.projection_out' ) if name == "norm.weight": __lowercase = 'layernorm.weight' if name == "norm.bias": __lowercase = 'layernorm.bias' if "head" in name: __lowercase = name.replace('head' , 'classifier' ) else: __lowercase = 'focalnet.' + name return name def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> List[str]: # fmt: off __lowercase = { 'focalnet-tiny': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_srf.pth', 'focalnet-tiny-lrf': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_lrf.pth', 'focalnet-small': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_srf.pth', 'focalnet-small-lrf': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_lrf.pth', 'focalnet-base': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_srf.pth', 'focalnet-base-lrf': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_lrf.pth', 'focalnet-large-lrf-fl3': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384.pth', 'focalnet-large-lrf-fl4': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384_fl4.pth', 'focalnet-xlarge-lrf-fl3': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384.pth', 'focalnet-xlarge-lrf-fl4': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384_fl4.pth', } # fmt: on __lowercase = model_name_to_url[model_name] print('Checkpoint URL: ' , SCREAMING_SNAKE_CASE ) __lowercase = torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE , map_location='cpu' )['model'] # rename keys for key in state_dict.copy().keys(): __lowercase = state_dict.pop(SCREAMING_SNAKE_CASE ) __lowercase = val __lowercase = get_focalnet_config(SCREAMING_SNAKE_CASE ) __lowercase = FocalNetForImageClassification(SCREAMING_SNAKE_CASE ) model.eval() # load state dict model.load_state_dict(SCREAMING_SNAKE_CASE ) # verify conversion __lowercase = 'http://images.cocodataset.org/val2017/000000039769.jpg' __lowercase = BitImageProcessor( do_resize=SCREAMING_SNAKE_CASE , size={'shortest_edge': 256} , resample=PILImageResampling.BILINEAR , do_center_crop=SCREAMING_SNAKE_CASE , crop_size=224 , do_normalize=SCREAMING_SNAKE_CASE , image_mean=SCREAMING_SNAKE_CASE , image_std=SCREAMING_SNAKE_CASE , ) __lowercase = Image.open(requests.get(SCREAMING_SNAKE_CASE , stream=SCREAMING_SNAKE_CASE ).raw ) __lowercase = processor(images=SCREAMING_SNAKE_CASE , return_tensors='pt' ) __lowercase = transforms.Compose( [ transforms.Resize(256 ), transforms.CenterCrop(224 ), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ), ] ) __lowercase = image_transforms(SCREAMING_SNAKE_CASE ).unsqueeze(0 ) # verify pixel_values assert torch.allclose(inputs.pixel_values , SCREAMING_SNAKE_CASE , atol=1E-4 ) __lowercase = model(**SCREAMING_SNAKE_CASE ) __lowercase = outputs.logits.argmax(-1 ).item() print('Predicted class:' , model.config.idalabel[predicted_class_idx] ) print('First values of logits:' , outputs.logits[0, :3] ) if model_name == "focalnet-tiny": __lowercase = torch.tensor([0.2_166, -0.4_368, 0.2_191] ) elif model_name == "focalnet-tiny-lrf": __lowercase = torch.tensor([1.1_669, 0.0_125, -0.1_695] ) elif model_name == "focalnet-small": __lowercase = torch.tensor([0.4_917, -0.0_430, 0.1_341] ) elif model_name == "focalnet-small-lrf": __lowercase = torch.tensor([-0.2_588, -0.5_342, -0.2_331] ) elif model_name == "focalnet-base": __lowercase = torch.tensor([-0.1_655, -0.4_090, -0.1_730] ) elif model_name == "focalnet-base-lrf": __lowercase = torch.tensor([0.5_306, -0.0_483, -0.3_928] ) assert torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE , atol=1E-4 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(F"""Saving model and processor of {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(SCREAMING_SNAKE_CASE ) processor.save_pretrained(SCREAMING_SNAKE_CASE ) if push_to_hub: print(F"""Pushing model and processor of {model_name} to the hub...""" ) model.push_to_hub(F"""{model_name}""" ) processor.push_to_hub(F"""{model_name}""" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""focalnet-tiny""", type=str, help="""Name of the FocalNet model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether to push the model and processor to the hub.""", ) SCREAMING_SNAKE_CASE__ = parser.parse_args() convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
325
1
"""simple docstring""" from timeit import timeit _a : Dict= { "MALAYALAM": True, "String": False, "rotor": True, "level": True, "A": True, "BB": True, "ABC": False, "amanaplanacanalpanama": True, # "a man a plan a canal panama" } # Ensure our test data is valid assert all((key == key[::-1]) is value for key, value in test_data.items()) def __UpperCAmelCase ( UpperCAmelCase_ : str ) -> int: '''simple docstring''' __snake_case : Union[str, Any] = 0 __snake_case : Optional[Any] = len(UpperCAmelCase_ ) - 1 while start_i < end_i: if s[start_i] == s[end_i]: start_i += 1 end_i -= 1 else: return False return True def __UpperCAmelCase ( UpperCAmelCase_ : str ) -> Optional[int]: '''simple docstring''' __snake_case : Union[str, Any] = len(UpperCAmelCase_ ) // 2 __snake_case : Tuple = len(UpperCAmelCase_ ) # We need to traverse till half of the length of string # as we can get access of the i'th last element from # i'th index. # eg: [0,1,2,3,4,5] => 4th index can be accessed # with the help of 1st index (i==n-i-1) # where n is length of string return all(s[i] == s[n - i - 1] for i in range(UpperCAmelCase_ ) ) def __UpperCAmelCase ( UpperCAmelCase_ : str ) -> Optional[int]: '''simple docstring''' if len(UpperCAmelCase_ ) <= 2: return True if s[0] == s[len(UpperCAmelCase_ ) - 1]: return is_palindrome_recursive(s[1:-1] ) else: return False def __UpperCAmelCase ( UpperCAmelCase_ : str ) -> str: '''simple docstring''' return s == s[::-1] def __UpperCAmelCase ( UpperCAmelCase_ : str ) -> Optional[int]: '''simple docstring''' __snake_case : Optional[Any] = F"all({name}(key) is value for key, value in test_data.items())" __snake_case : Tuple = F"from __main__ import test_data, {name}" __snake_case : List[str] = 50_00_00 __snake_case : int = timeit(stmt=UpperCAmelCase_ , setup=UpperCAmelCase_ , number=UpperCAmelCase_ ) print(F"{name:<35} finished {number:,} runs in {result:.5f} seconds" ) if __name__ == "__main__": for key, value in test_data.items(): assert is_palindrome(key) is is_palindrome_recursive(key) assert is_palindrome(key) is is_palindrome_slice(key) print(f'''{key:21} {value}''') print("a man a plan a canal panama") # finished 500,000 runs in 0.46793 seconds benchmark_function("is_palindrome_slice") # finished 500,000 runs in 0.85234 seconds benchmark_function("is_palindrome") # finished 500,000 runs in 1.32028 seconds benchmark_function("is_palindrome_recursive") # finished 500,000 runs in 2.08679 seconds benchmark_function("is_palindrome_traversal")
356
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_funnel import FunnelTokenizer _a : Any= logging.get_logger(__name__) _a : str= {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} _a : Optional[Any]= [ "small", "small-base", "medium", "medium-base", "intermediate", "intermediate-base", "large", "large-base", "xlarge", "xlarge-base", ] _a : List[Any]= { "vocab_file": { "funnel-transformer/small": "https://huggingface.co/funnel-transformer/small/resolve/main/vocab.txt", "funnel-transformer/small-base": "https://huggingface.co/funnel-transformer/small-base/resolve/main/vocab.txt", "funnel-transformer/medium": "https://huggingface.co/funnel-transformer/medium/resolve/main/vocab.txt", "funnel-transformer/medium-base": ( "https://huggingface.co/funnel-transformer/medium-base/resolve/main/vocab.txt" ), "funnel-transformer/intermediate": ( "https://huggingface.co/funnel-transformer/intermediate/resolve/main/vocab.txt" ), "funnel-transformer/intermediate-base": ( "https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/vocab.txt" ), "funnel-transformer/large": "https://huggingface.co/funnel-transformer/large/resolve/main/vocab.txt", "funnel-transformer/large-base": "https://huggingface.co/funnel-transformer/large-base/resolve/main/vocab.txt", "funnel-transformer/xlarge": "https://huggingface.co/funnel-transformer/xlarge/resolve/main/vocab.txt", "funnel-transformer/xlarge-base": ( "https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "funnel-transformer/small": "https://huggingface.co/funnel-transformer/small/resolve/main/tokenizer.json", "funnel-transformer/small-base": ( "https://huggingface.co/funnel-transformer/small-base/resolve/main/tokenizer.json" ), "funnel-transformer/medium": "https://huggingface.co/funnel-transformer/medium/resolve/main/tokenizer.json", "funnel-transformer/medium-base": ( "https://huggingface.co/funnel-transformer/medium-base/resolve/main/tokenizer.json" ), "funnel-transformer/intermediate": ( "https://huggingface.co/funnel-transformer/intermediate/resolve/main/tokenizer.json" ), "funnel-transformer/intermediate-base": ( "https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/tokenizer.json" ), "funnel-transformer/large": "https://huggingface.co/funnel-transformer/large/resolve/main/tokenizer.json", "funnel-transformer/large-base": ( "https://huggingface.co/funnel-transformer/large-base/resolve/main/tokenizer.json" ), "funnel-transformer/xlarge": "https://huggingface.co/funnel-transformer/xlarge/resolve/main/tokenizer.json", "funnel-transformer/xlarge-base": ( "https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/tokenizer.json" ), }, } _a : str= {f'''funnel-transformer/{name}''': 512 for name in _model_names} _a : List[Any]= {f'''funnel-transformer/{name}''': {"do_lower_case": True} for name in _model_names} class UpperCamelCase ( lowercase ): UpperCAmelCase : List[str] = VOCAB_FILES_NAMES UpperCAmelCase : Tuple = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase : int = PRETRAINED_INIT_CONFIGURATION UpperCAmelCase : Tuple = FunnelTokenizer UpperCAmelCase : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase : int = 2 def __init__(self : int , _A : Any=None , _A : Union[str, Any]=None , _A : Union[str, Any]=True , _A : List[str]="<unk>" , _A : Any="<sep>" , _A : Dict="<pad>" , _A : Tuple="<cls>" , _A : Dict="<mask>" , _A : Optional[Any]="<s>" , _A : List[Any]="</s>" , _A : Optional[int]=True , _A : Dict=True , _A : Tuple=None , _A : int="##" , **_A : Any , ) -> str: super().__init__( _A , tokenizer_file=_A , do_lower_case=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , bos_token=_A , eos_token=_A , clean_text=_A , tokenize_chinese_chars=_A , strip_accents=_A , wordpieces_prefix=_A , **_A , ) __snake_case : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__()) if ( normalizer_state.get('lowercase' , _A) != do_lower_case or normalizer_state.get('strip_accents' , _A) != strip_accents or normalizer_state.get('handle_chinese_chars' , _A) != tokenize_chinese_chars ): __snake_case : List[str] = getattr(_A , normalizer_state.pop('type')) __snake_case : int = do_lower_case __snake_case : Optional[int] = strip_accents __snake_case : str = tokenize_chinese_chars __snake_case : Optional[int] = normalizer_class(**_A) __snake_case : str = do_lower_case def _lowercase (self : Optional[Any] , _A : Dict , _A : Tuple=None) -> Any: __snake_case : List[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _lowercase (self : str , _A : List[int] , _A : Optional[List[int]] = None) -> List[int]: __snake_case : Union[str, Any] = [self.sep_token_id] __snake_case : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls) * [self.cls_token_type_id] + len(token_ids_a + sep) * [0] return len(cls) * [self.cls_token_type_id] + len(token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def _lowercase (self : Tuple , _A : str , _A : Optional[str] = None) -> Tuple[str]: __snake_case : int = self._tokenizer.model.save(_A , name=_A) return tuple(_A)
95
0
from typing import TYPE_CHECKING from ...utils import _LazyModule lowerCamelCase__ = {"""tokenization_bertweet""": ["""BertweetTokenizer"""]} if TYPE_CHECKING: from .tokenization_bertweet import BertweetTokenizer else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
212
"""simple docstring""" def a__ ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : List[Any] ): '''simple docstring''' if height >= 1: move_tower(height - 1 , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) move_disk(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) move_tower(height - 1 , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def a__ ( SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : Optional[int] ): '''simple docstring''' print("moving disk from" , SCREAMING_SNAKE_CASE , "to" , SCREAMING_SNAKE_CASE ) def a__ ( ): '''simple docstring''' lowerCAmelCase : Optional[int] = int(input("Height of hanoi: " ).strip() ) move_tower(SCREAMING_SNAKE_CASE , "A" , "B" , "C" ) if __name__ == "__main__": main()
108
0
from __future__ import annotations import unittest import numpy as np from transformers import OPTConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import GPTaTokenizer, TFOPTForCausalLM, TFOPTModel def snake_case (__lowercase , __lowercase , __lowercase=None , __lowercase=None ) -> Tuple: '''simple docstring''' if attention_mask is None: _snake_case : List[Any] = tf.cast(tf.math.not_equal(__lowercase , config.pad_token_id ) , tf.inta ) return {"input_ids": input_ids, "attention_mask": attention_mask} @require_tf class lowercase_ : _lowerCamelCase = OPTConfig _lowerCamelCase = {} _lowerCamelCase = 'gelu' def __init__( self , lowercase_ , lowercase_=13 , lowercase_=7 , lowercase_=True , lowercase_=False , lowercase_=99 , lowercase_=16 , lowercase_=2 , lowercase_=4 , lowercase_=4 , lowercase_="gelu" , lowercase_=0.1 , lowercase_=0.1 , lowercase_=20 , lowercase_=2 , lowercase_=1 , lowercase_=0 , lowercase_=16 , lowercase_=16 , ): _snake_case : Dict = parent _snake_case : List[str] = batch_size _snake_case : Optional[Any] = seq_length _snake_case : Dict = is_training _snake_case : List[Any] = use_labels _snake_case : Dict = vocab_size _snake_case : Tuple = hidden_size _snake_case : Optional[int] = num_hidden_layers _snake_case : List[str] = num_attention_heads _snake_case : Tuple = intermediate_size _snake_case : Dict = hidden_act _snake_case : Any = hidden_dropout_prob _snake_case : Optional[int] = attention_probs_dropout_prob _snake_case : Tuple = max_position_embeddings _snake_case : List[Any] = eos_token_id _snake_case : Optional[int] = pad_token_id _snake_case : Dict = bos_token_id _snake_case : List[Any] = embed_dim _snake_case : Optional[int] = word_embed_proj_dim _snake_case : Union[str, Any] = False def UpperCamelCase ( self ): _snake_case : int = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _snake_case : str = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _snake_case : int = tf.concat([input_ids, eos_tensor] , axis=1 ) _snake_case : Optional[Any] = self.config_cls( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , embed_dim=self.embed_dim , word_embed_proj_dim=self.word_embed_proj_dim , is_encoder_decoder=lowercase_ , **self.config_updates , ) _snake_case : Any = prepare_opt_inputs_dict(lowercase_ , lowercase_ ) return config, inputs_dict def UpperCamelCase ( self , lowercase_ , lowercase_ ): _snake_case : Any = TFOPTModel(config=lowercase_ ) _snake_case : int = inputs_dict["input_ids"] _snake_case : Optional[int] = input_ids[:1, :] _snake_case : Any = inputs_dict["attention_mask"][:1, :] _snake_case : List[str] = 1 # first forward pass _snake_case : Union[str, Any] = model(lowercase_ , attention_mask=lowercase_ , use_cache=lowercase_ ) _snake_case ,_snake_case : str = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _snake_case : Dict = ids_tensor((self.batch_size, 3) , config.vocab_size ) _snake_case : Optional[Any] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and _snake_case : int = tf.concat([input_ids, next_tokens] , axis=-1 ) _snake_case : int = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) _snake_case : Optional[Any] = model(lowercase_ , attention_mask=lowercase_ )[0] _snake_case : Optional[int] = model(lowercase_ , attention_mask=lowercase_ , past_key_values=lowercase_ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice _snake_case : int = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) _snake_case : List[str] = output_from_no_past[:, -3:, random_slice_idx] _snake_case : List[Any] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(lowercase_ , lowercase_ , rtol=1e-3 ) @require_tf class lowercase_ ( __snake_case , __snake_case , unittest.TestCase ): _lowerCamelCase = (TFOPTModel, TFOPTForCausalLM) if is_tf_available() else () _lowerCamelCase = (TFOPTForCausalLM,) if is_tf_available() else () _lowerCamelCase = ( {'feature-extraction': TFOPTModel, 'text-generation': TFOPTForCausalLM} if is_tf_available() else {} ) _lowerCamelCase = False _lowerCamelCase = False _lowerCamelCase = False _lowerCamelCase = 10 def UpperCamelCase ( self ): _snake_case : Dict = TFOPTModelTester(self ) _snake_case : Optional[int] = ConfigTester(self , config_class=lowercase_ ) def UpperCamelCase ( self ): self.config_tester.run_common_tests() def UpperCamelCase ( self ): _snake_case : Dict = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*lowercase_ ) def UpperCamelCase ( self ): _snake_case ,_snake_case : str = self.model_tester.prepare_config_and_inputs_for_common() def _get_word_embedding_weight(lowercase_ , lowercase_ ): if hasattr(lowercase_ , "weight" ): return embedding_layer.weight else: # Here we build the word embeddings weights if not exists. # And then we retry to get the attribute once built. model.build() if hasattr(lowercase_ , "weight" ): return embedding_layer.weight else: return None for model_class in self.all_model_classes: for size in [config.vocab_size - 10, config.vocab_size + 10]: # build the embeddings _snake_case : Dict = model_class(config=lowercase_ ) _snake_case : Union[str, Any] = _get_word_embedding_weight(lowercase_ , model.get_input_embeddings() ) _snake_case : Optional[Any] = _get_word_embedding_weight(lowercase_ , model.get_output_embeddings() ) # reshape the embeddings model.resize_token_embeddings(lowercase_ ) _snake_case : int = _get_word_embedding_weight(lowercase_ , model.get_input_embeddings() ) _snake_case : Tuple = _get_word_embedding_weight(lowercase_ , model.get_output_embeddings() ) # check that the resized embeddings size matches the desired size. _snake_case : Any = size if size is not None else config.vocab_size self.assertEqual(new_input_embeddings.shape[0] , lowercase_ ) # check that weights remain the same after resizing _snake_case : Dict = True for pa, pa in zip(old_input_embeddings.value() , new_input_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: _snake_case : Optional[int] = False self.assertTrue(lowercase_ ) if old_output_embeddings is not None and new_output_embeddings is not None: self.assertEqual(new_output_embeddings.shape[0] , lowercase_ ) _snake_case : Optional[int] = True for pa, pa in zip(old_output_embeddings.value() , new_output_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: _snake_case : str = False self.assertTrue(lowercase_ ) def snake_case (__lowercase ) -> Dict: '''simple docstring''' return tf.constant(__lowercase , dtype=tf.intaa ) @require_tf class lowercase_ ( unittest.TestCase ): _lowerCamelCase = 99 def UpperCamelCase ( self ): _snake_case : Any = tf.ones((4, 1) , dtype=tf.intaa ) * 2 _snake_case : Optional[int] = tf.concat([ids_tensor((4, 6) , self.vocab_size - 3 ) + 3, eos_column_vector] , axis=1 ) _snake_case : List[Any] = input_ids.shape[0] _snake_case : List[str] = OPTConfig( vocab_size=self.vocab_size , hidden_size=24 , num_hidden_layers=2 , num_attention_heads=2 , ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size @require_sentencepiece @require_tf class lowercase_ ( unittest.TestCase ): @slow def UpperCamelCase ( self ): _snake_case : Optional[Any] = TFOPTModel.from_pretrained("facebook/opt-350m" ) _snake_case : Optional[Any] = _long_tensor([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] ) _snake_case : Optional[int] = tf.not_equal(lowercase_ , model.config.pad_token_id ) with tf.GradientTape(): _snake_case : List[Any] = model(input_ids=lowercase_ , attention_mask=lowercase_ ).last_hidden_state _snake_case : List[str] = (1, 11, 512) self.assertEqual(output.shape , lowercase_ ) _snake_case : Optional[int] = tf.constant( [[-0.2_873, -1.9_218, -0.3_033], [-1.2_710, -0.1_338, -0.1_902], [0.4_095, 0.1_214, -1.3_121]] ) self.assertTrue(np.allclose(output[:, :3, :3] , lowercase_ , atol=4e-3 ) ) _snake_case : List[Any] = tf.function(lowercase_ , jit_compile=lowercase_ ) _snake_case : Tuple = xla_generate(lowercase_ , lowercase_ )[0] self.assertTrue(np.allclose(output[:, :3, :3] , lowercase_ , atol=4e-2 ) ) @require_tf @slow class lowercase_ ( unittest.TestCase ): def UpperCamelCase ( self ): super().setUp() _snake_case : Optional[int] = "facebook/opt-350m" def UpperCamelCase ( self ): _snake_case : Union[str, Any] = TFOPTForCausalLM.from_pretrained(self.path_model ) _snake_case : Optional[Any] = GPTaTokenizer.from_pretrained(self.path_model ) _snake_case : List[str] = [ "Today is a beautiful day and I want to", "In the city of", "Paris is the capital of France and", "Computers and mobile phones have taken", ] # verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False _snake_case : List[Any] = tokenizer(lowercase_ , return_tensors="tf" , padding=lowercase_ , add_special_tokens=lowercase_ ) _snake_case : List[str] = tf.math.reduce_mean(model(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) _snake_case : Tuple = tf.constant( [ [1.3_851, -13.8_923, -10.5_229, -10.7_533, -0.2_309, -10.2_384, -0.5_365, -9.0_947, -5.1_670], [-4.7_073, -10.6_276, -3.9_415, -21.5_242, -0.2_822, -0.2_822, -0.2_822, -0.2_822, -0.2_822], [0.6_247, -3.4_229, -8.9_179, -1.4_297, -14.1_650, 1.4_146, -9.0_218, -0.2_703, -0.2_703], [6.4_783, -1.9_913, -10.7_926, -2.3_336, 1.5_092, -0.9_974, -6.8_213, 1.3_477, 1.3_477], ] ) self.assertTrue(np.allclose(lowercase_ , lowercase_ , atol=1e-4 ) ) _snake_case : List[Any] = tf.function(lowercase_ , jit_compile=lowercase_ ) _snake_case : Tuple = tf.math.reduce_mean(xla_generate(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) self.assertTrue(np.allclose(lowercase_ , lowercase_ , atol=1e-4 ) ) @require_tf @slow class lowercase_ ( unittest.TestCase ): @property def UpperCamelCase ( self ): return [ "Today is a beautiful day and I want", "In the city of", "Paris is the capital of France and", "Computers and mobile phones have taken", ] def UpperCamelCase ( self ): _snake_case : List[Any] = "facebook/opt-125m" _snake_case : int = [ "Today is a beautiful day and I want to", "In the city of New York, the city", "Paris is the capital of France and the capital", "Computers and mobile phones have taken over the", ] _snake_case : str = [] _snake_case : Any = GPTaTokenizer.from_pretrained(lowercase_ ) _snake_case : List[Any] = TFOPTForCausalLM.from_pretrained(lowercase_ ) for prompt in self.prompts: _snake_case : str = tokenizer(lowercase_ , return_tensors="tf" ).input_ids _snake_case : Any = model.generate(lowercase_ , max_length=10 ) _snake_case : List[str] = tokenizer.batch_decode(lowercase_ , skip_special_tokens=lowercase_ ) predicted_outputs += generated_string self.assertListEqual(lowercase_ , lowercase_ ) def UpperCamelCase ( self ): _snake_case : Optional[int] = "facebook/opt-350m" _snake_case : Dict = GPTaTokenizer.from_pretrained(lowercase_ ) _snake_case : Dict = TFOPTForCausalLM.from_pretrained(lowercase_ ) _snake_case : int = "left" # use different length sentences to test batching _snake_case : Union[str, Any] = [ "Hello, my dog is a little", "Today, I", ] _snake_case : Optional[Any] = tokenizer(lowercase_ , return_tensors="tf" , padding=lowercase_ ) _snake_case : List[Any] = inputs["input_ids"] _snake_case : Union[str, Any] = model.generate(input_ids=lowercase_ , attention_mask=inputs["attention_mask"] ) _snake_case : int = tokenizer(sentences[0] , return_tensors="tf" ).input_ids _snake_case : List[str] = model.generate(input_ids=lowercase_ ) _snake_case : Dict = inputs_non_padded.shape[-1] - tf.math.reduce_sum( tf.cast(inputs["attention_mask"][-1] , tf.intaa ) ) _snake_case : int = tokenizer(sentences[1] , return_tensors="tf" ).input_ids _snake_case : int = model.generate(input_ids=lowercase_ , max_length=model.config.max_length - num_paddings ) _snake_case : Tuple = tokenizer.batch_decode(lowercase_ , skip_special_tokens=lowercase_ ) _snake_case : Dict = tokenizer.decode(output_non_padded[0] , skip_special_tokens=lowercase_ ) _snake_case : Any = tokenizer.decode(output_padded[0] , skip_special_tokens=lowercase_ ) _snake_case : Optional[Any] = [ "Hello, my dog is a little bit of a dork.\nI'm a little bit", "Today, I was in the middle of a conversation with a friend about the", ] self.assertListEqual(lowercase_ , lowercase_ ) self.assertListEqual(lowercase_ , [non_padded_sentence, padded_sentence] ) def UpperCamelCase ( self ): _snake_case : Tuple = "facebook/opt-350m" _snake_case : Optional[int] = [ "Today is a beautiful day and I want to", "In the city of San Francisco, the city", "Paris is the capital of France and the capital", "Computers and mobile phones have taken over the", ] _snake_case : str = [] _snake_case : str = GPTaTokenizer.from_pretrained(lowercase_ ) _snake_case : List[str] = TFOPTForCausalLM.from_pretrained(lowercase_ ) for prompt in self.prompts: _snake_case : Dict = tokenizer(lowercase_ , return_tensors="tf" ).input_ids _snake_case : Any = model.generate(lowercase_ , max_length=10 ) _snake_case : Tuple = tokenizer.batch_decode(lowercase_ , skip_special_tokens=lowercase_ ) predicted_outputs += generated_string self.assertListEqual(lowercase_ , lowercase_ )
284
from __future__ import annotations import unittest import numpy as np from transformers import OPTConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import GPTaTokenizer, TFOPTForCausalLM, TFOPTModel def snake_case (__lowercase , __lowercase , __lowercase=None , __lowercase=None ) -> Tuple: '''simple docstring''' if attention_mask is None: _snake_case : List[Any] = tf.cast(tf.math.not_equal(__lowercase , config.pad_token_id ) , tf.inta ) return {"input_ids": input_ids, "attention_mask": attention_mask} @require_tf class lowercase_ : _lowerCamelCase = OPTConfig _lowerCamelCase = {} _lowerCamelCase = 'gelu' def __init__( self , lowercase_ , lowercase_=13 , lowercase_=7 , lowercase_=True , lowercase_=False , lowercase_=99 , lowercase_=16 , lowercase_=2 , lowercase_=4 , lowercase_=4 , lowercase_="gelu" , lowercase_=0.1 , lowercase_=0.1 , lowercase_=20 , lowercase_=2 , lowercase_=1 , lowercase_=0 , lowercase_=16 , lowercase_=16 , ): _snake_case : Dict = parent _snake_case : List[str] = batch_size _snake_case : Optional[Any] = seq_length _snake_case : Dict = is_training _snake_case : List[Any] = use_labels _snake_case : Dict = vocab_size _snake_case : Tuple = hidden_size _snake_case : Optional[int] = num_hidden_layers _snake_case : List[str] = num_attention_heads _snake_case : Tuple = intermediate_size _snake_case : Dict = hidden_act _snake_case : Any = hidden_dropout_prob _snake_case : Optional[int] = attention_probs_dropout_prob _snake_case : Tuple = max_position_embeddings _snake_case : List[Any] = eos_token_id _snake_case : Optional[int] = pad_token_id _snake_case : Dict = bos_token_id _snake_case : List[Any] = embed_dim _snake_case : Optional[int] = word_embed_proj_dim _snake_case : Union[str, Any] = False def UpperCamelCase ( self ): _snake_case : int = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _snake_case : str = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _snake_case : int = tf.concat([input_ids, eos_tensor] , axis=1 ) _snake_case : Optional[Any] = self.config_cls( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , embed_dim=self.embed_dim , word_embed_proj_dim=self.word_embed_proj_dim , is_encoder_decoder=lowercase_ , **self.config_updates , ) _snake_case : Any = prepare_opt_inputs_dict(lowercase_ , lowercase_ ) return config, inputs_dict def UpperCamelCase ( self , lowercase_ , lowercase_ ): _snake_case : Any = TFOPTModel(config=lowercase_ ) _snake_case : int = inputs_dict["input_ids"] _snake_case : Optional[int] = input_ids[:1, :] _snake_case : Any = inputs_dict["attention_mask"][:1, :] _snake_case : List[str] = 1 # first forward pass _snake_case : Union[str, Any] = model(lowercase_ , attention_mask=lowercase_ , use_cache=lowercase_ ) _snake_case ,_snake_case : str = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _snake_case : Dict = ids_tensor((self.batch_size, 3) , config.vocab_size ) _snake_case : Optional[Any] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and _snake_case : int = tf.concat([input_ids, next_tokens] , axis=-1 ) _snake_case : int = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) _snake_case : Optional[Any] = model(lowercase_ , attention_mask=lowercase_ )[0] _snake_case : Optional[int] = model(lowercase_ , attention_mask=lowercase_ , past_key_values=lowercase_ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice _snake_case : int = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) _snake_case : List[str] = output_from_no_past[:, -3:, random_slice_idx] _snake_case : List[Any] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(lowercase_ , lowercase_ , rtol=1e-3 ) @require_tf class lowercase_ ( __snake_case , __snake_case , unittest.TestCase ): _lowerCamelCase = (TFOPTModel, TFOPTForCausalLM) if is_tf_available() else () _lowerCamelCase = (TFOPTForCausalLM,) if is_tf_available() else () _lowerCamelCase = ( {'feature-extraction': TFOPTModel, 'text-generation': TFOPTForCausalLM} if is_tf_available() else {} ) _lowerCamelCase = False _lowerCamelCase = False _lowerCamelCase = False _lowerCamelCase = 10 def UpperCamelCase ( self ): _snake_case : Dict = TFOPTModelTester(self ) _snake_case : Optional[int] = ConfigTester(self , config_class=lowercase_ ) def UpperCamelCase ( self ): self.config_tester.run_common_tests() def UpperCamelCase ( self ): _snake_case : Dict = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*lowercase_ ) def UpperCamelCase ( self ): _snake_case ,_snake_case : str = self.model_tester.prepare_config_and_inputs_for_common() def _get_word_embedding_weight(lowercase_ , lowercase_ ): if hasattr(lowercase_ , "weight" ): return embedding_layer.weight else: # Here we build the word embeddings weights if not exists. # And then we retry to get the attribute once built. model.build() if hasattr(lowercase_ , "weight" ): return embedding_layer.weight else: return None for model_class in self.all_model_classes: for size in [config.vocab_size - 10, config.vocab_size + 10]: # build the embeddings _snake_case : Dict = model_class(config=lowercase_ ) _snake_case : Union[str, Any] = _get_word_embedding_weight(lowercase_ , model.get_input_embeddings() ) _snake_case : Optional[Any] = _get_word_embedding_weight(lowercase_ , model.get_output_embeddings() ) # reshape the embeddings model.resize_token_embeddings(lowercase_ ) _snake_case : int = _get_word_embedding_weight(lowercase_ , model.get_input_embeddings() ) _snake_case : Tuple = _get_word_embedding_weight(lowercase_ , model.get_output_embeddings() ) # check that the resized embeddings size matches the desired size. _snake_case : Any = size if size is not None else config.vocab_size self.assertEqual(new_input_embeddings.shape[0] , lowercase_ ) # check that weights remain the same after resizing _snake_case : Dict = True for pa, pa in zip(old_input_embeddings.value() , new_input_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: _snake_case : Optional[int] = False self.assertTrue(lowercase_ ) if old_output_embeddings is not None and new_output_embeddings is not None: self.assertEqual(new_output_embeddings.shape[0] , lowercase_ ) _snake_case : Optional[int] = True for pa, pa in zip(old_output_embeddings.value() , new_output_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: _snake_case : str = False self.assertTrue(lowercase_ ) def snake_case (__lowercase ) -> Dict: '''simple docstring''' return tf.constant(__lowercase , dtype=tf.intaa ) @require_tf class lowercase_ ( unittest.TestCase ): _lowerCamelCase = 99 def UpperCamelCase ( self ): _snake_case : Any = tf.ones((4, 1) , dtype=tf.intaa ) * 2 _snake_case : Optional[int] = tf.concat([ids_tensor((4, 6) , self.vocab_size - 3 ) + 3, eos_column_vector] , axis=1 ) _snake_case : List[Any] = input_ids.shape[0] _snake_case : List[str] = OPTConfig( vocab_size=self.vocab_size , hidden_size=24 , num_hidden_layers=2 , num_attention_heads=2 , ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size @require_sentencepiece @require_tf class lowercase_ ( unittest.TestCase ): @slow def UpperCamelCase ( self ): _snake_case : Optional[Any] = TFOPTModel.from_pretrained("facebook/opt-350m" ) _snake_case : Optional[Any] = _long_tensor([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] ) _snake_case : Optional[int] = tf.not_equal(lowercase_ , model.config.pad_token_id ) with tf.GradientTape(): _snake_case : List[Any] = model(input_ids=lowercase_ , attention_mask=lowercase_ ).last_hidden_state _snake_case : List[str] = (1, 11, 512) self.assertEqual(output.shape , lowercase_ ) _snake_case : Optional[int] = tf.constant( [[-0.2_873, -1.9_218, -0.3_033], [-1.2_710, -0.1_338, -0.1_902], [0.4_095, 0.1_214, -1.3_121]] ) self.assertTrue(np.allclose(output[:, :3, :3] , lowercase_ , atol=4e-3 ) ) _snake_case : List[Any] = tf.function(lowercase_ , jit_compile=lowercase_ ) _snake_case : Tuple = xla_generate(lowercase_ , lowercase_ )[0] self.assertTrue(np.allclose(output[:, :3, :3] , lowercase_ , atol=4e-2 ) ) @require_tf @slow class lowercase_ ( unittest.TestCase ): def UpperCamelCase ( self ): super().setUp() _snake_case : Optional[int] = "facebook/opt-350m" def UpperCamelCase ( self ): _snake_case : Union[str, Any] = TFOPTForCausalLM.from_pretrained(self.path_model ) _snake_case : Optional[Any] = GPTaTokenizer.from_pretrained(self.path_model ) _snake_case : List[str] = [ "Today is a beautiful day and I want to", "In the city of", "Paris is the capital of France and", "Computers and mobile phones have taken", ] # verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False _snake_case : List[Any] = tokenizer(lowercase_ , return_tensors="tf" , padding=lowercase_ , add_special_tokens=lowercase_ ) _snake_case : List[str] = tf.math.reduce_mean(model(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) _snake_case : Tuple = tf.constant( [ [1.3_851, -13.8_923, -10.5_229, -10.7_533, -0.2_309, -10.2_384, -0.5_365, -9.0_947, -5.1_670], [-4.7_073, -10.6_276, -3.9_415, -21.5_242, -0.2_822, -0.2_822, -0.2_822, -0.2_822, -0.2_822], [0.6_247, -3.4_229, -8.9_179, -1.4_297, -14.1_650, 1.4_146, -9.0_218, -0.2_703, -0.2_703], [6.4_783, -1.9_913, -10.7_926, -2.3_336, 1.5_092, -0.9_974, -6.8_213, 1.3_477, 1.3_477], ] ) self.assertTrue(np.allclose(lowercase_ , lowercase_ , atol=1e-4 ) ) _snake_case : List[Any] = tf.function(lowercase_ , jit_compile=lowercase_ ) _snake_case : Tuple = tf.math.reduce_mean(xla_generate(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) self.assertTrue(np.allclose(lowercase_ , lowercase_ , atol=1e-4 ) ) @require_tf @slow class lowercase_ ( unittest.TestCase ): @property def UpperCamelCase ( self ): return [ "Today is a beautiful day and I want", "In the city of", "Paris is the capital of France and", "Computers and mobile phones have taken", ] def UpperCamelCase ( self ): _snake_case : List[Any] = "facebook/opt-125m" _snake_case : int = [ "Today is a beautiful day and I want to", "In the city of New York, the city", "Paris is the capital of France and the capital", "Computers and mobile phones have taken over the", ] _snake_case : str = [] _snake_case : Any = GPTaTokenizer.from_pretrained(lowercase_ ) _snake_case : List[Any] = TFOPTForCausalLM.from_pretrained(lowercase_ ) for prompt in self.prompts: _snake_case : str = tokenizer(lowercase_ , return_tensors="tf" ).input_ids _snake_case : Any = model.generate(lowercase_ , max_length=10 ) _snake_case : List[str] = tokenizer.batch_decode(lowercase_ , skip_special_tokens=lowercase_ ) predicted_outputs += generated_string self.assertListEqual(lowercase_ , lowercase_ ) def UpperCamelCase ( self ): _snake_case : Optional[int] = "facebook/opt-350m" _snake_case : Dict = GPTaTokenizer.from_pretrained(lowercase_ ) _snake_case : Dict = TFOPTForCausalLM.from_pretrained(lowercase_ ) _snake_case : int = "left" # use different length sentences to test batching _snake_case : Union[str, Any] = [ "Hello, my dog is a little", "Today, I", ] _snake_case : Optional[Any] = tokenizer(lowercase_ , return_tensors="tf" , padding=lowercase_ ) _snake_case : List[Any] = inputs["input_ids"] _snake_case : Union[str, Any] = model.generate(input_ids=lowercase_ , attention_mask=inputs["attention_mask"] ) _snake_case : int = tokenizer(sentences[0] , return_tensors="tf" ).input_ids _snake_case : List[str] = model.generate(input_ids=lowercase_ ) _snake_case : Dict = inputs_non_padded.shape[-1] - tf.math.reduce_sum( tf.cast(inputs["attention_mask"][-1] , tf.intaa ) ) _snake_case : int = tokenizer(sentences[1] , return_tensors="tf" ).input_ids _snake_case : int = model.generate(input_ids=lowercase_ , max_length=model.config.max_length - num_paddings ) _snake_case : Tuple = tokenizer.batch_decode(lowercase_ , skip_special_tokens=lowercase_ ) _snake_case : Dict = tokenizer.decode(output_non_padded[0] , skip_special_tokens=lowercase_ ) _snake_case : Any = tokenizer.decode(output_padded[0] , skip_special_tokens=lowercase_ ) _snake_case : Optional[Any] = [ "Hello, my dog is a little bit of a dork.\nI'm a little bit", "Today, I was in the middle of a conversation with a friend about the", ] self.assertListEqual(lowercase_ , lowercase_ ) self.assertListEqual(lowercase_ , [non_padded_sentence, padded_sentence] ) def UpperCamelCase ( self ): _snake_case : Tuple = "facebook/opt-350m" _snake_case : Optional[int] = [ "Today is a beautiful day and I want to", "In the city of San Francisco, the city", "Paris is the capital of France and the capital", "Computers and mobile phones have taken over the", ] _snake_case : str = [] _snake_case : str = GPTaTokenizer.from_pretrained(lowercase_ ) _snake_case : List[str] = TFOPTForCausalLM.from_pretrained(lowercase_ ) for prompt in self.prompts: _snake_case : Dict = tokenizer(lowercase_ , return_tensors="tf" ).input_ids _snake_case : Any = model.generate(lowercase_ , max_length=10 ) _snake_case : Tuple = tokenizer.batch_decode(lowercase_ , skip_special_tokens=lowercase_ ) predicted_outputs += generated_string self.assertListEqual(lowercase_ , lowercase_ )
284
1
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class lowerCAmelCase ( unittest.TestCase ): def A_ ( self : List[Any] ) -> str: lowerCamelCase__ : int = tempfile.mkdtemp() # fmt: off lowerCamelCase__ : Optional[Any] = ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on lowerCamelCase__ : int = dict(zip(UpperCAmelCase , range(len(UpperCAmelCase ) ) ) ) lowerCamelCase__ : Any = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] lowerCamelCase__ : List[str] = {'unk_token': '<unk>'} lowerCamelCase__ : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) lowerCamelCase__ : List[str] = 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 ) ) lowerCamelCase__ : Optional[Any] = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], 'image_std': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], } lowerCamelCase__ : int = os.path.join(self.tmpdirname , UpperCAmelCase ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(UpperCAmelCase , UpperCAmelCase ) def A_ ( self : Optional[int] , **UpperCAmelCase : Tuple ) -> Optional[int]: return CLIPTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase ) def A_ ( self : Union[str, Any] , **UpperCAmelCase : Any ) -> str: return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **UpperCAmelCase ) def A_ ( self : str , **UpperCAmelCase : Dict ) -> Optional[int]: return CLIPImageProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase ) def A_ ( self : int ) -> Any: shutil.rmtree(self.tmpdirname ) def A_ ( self : List[str] ) -> str: lowerCamelCase__ : List[str] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] lowerCamelCase__ : List[Any] = [Image.fromarray(np.moveaxis(UpperCAmelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def A_ ( self : int ) -> int: lowerCamelCase__ : str = self.get_tokenizer() lowerCamelCase__ : Optional[Any] = self.get_rust_tokenizer() lowerCamelCase__ : str = self.get_image_processor() lowerCamelCase__ : List[Any] = CLIPProcessor(tokenizer=UpperCAmelCase , image_processor=UpperCAmelCase ) processor_slow.save_pretrained(self.tmpdirname ) lowerCamelCase__ : Dict = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=UpperCAmelCase ) lowerCamelCase__ : Any = CLIPProcessor(tokenizer=UpperCAmelCase , image_processor=UpperCAmelCase ) processor_fast.save_pretrained(self.tmpdirname ) lowerCamelCase__ : Tuple = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , UpperCAmelCase ) self.assertIsInstance(processor_fast.tokenizer , UpperCAmelCase ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , UpperCAmelCase ) self.assertIsInstance(processor_fast.image_processor , UpperCAmelCase ) def A_ ( self : int ) -> Any: lowerCamelCase__ : Any = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) lowerCamelCase__ : Optional[Any] = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) lowerCamelCase__ : Any = self.get_image_processor(do_normalize=UpperCAmelCase , padding_value=1.0 ) lowerCamelCase__ : Any = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=UpperCAmelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , UpperCAmelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , UpperCAmelCase ) def A_ ( self : Any ) -> List[Any]: lowerCamelCase__ : int = self.get_image_processor() lowerCamelCase__ : Union[str, Any] = self.get_tokenizer() lowerCamelCase__ : Dict = CLIPProcessor(tokenizer=UpperCAmelCase , image_processor=UpperCAmelCase ) lowerCamelCase__ : Optional[int] = self.prepare_image_inputs() lowerCamelCase__ : str = image_processor(UpperCAmelCase , return_tensors='np' ) lowerCamelCase__ : Tuple = processor(images=UpperCAmelCase , return_tensors='np' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def A_ ( self : List[str] ) -> Optional[int]: lowerCamelCase__ : List[Any] = self.get_image_processor() lowerCamelCase__ : Any = self.get_tokenizer() lowerCamelCase__ : List[Any] = CLIPProcessor(tokenizer=UpperCAmelCase , image_processor=UpperCAmelCase ) lowerCamelCase__ : Union[str, Any] = 'lower newer' lowerCamelCase__ : Dict = processor(text=UpperCAmelCase ) lowerCamelCase__ : Tuple = tokenizer(UpperCAmelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def A_ ( self : Union[str, Any] ) -> str: lowerCamelCase__ : str = self.get_image_processor() lowerCamelCase__ : Union[str, Any] = self.get_tokenizer() lowerCamelCase__ : Optional[Any] = CLIPProcessor(tokenizer=UpperCAmelCase , image_processor=UpperCAmelCase ) lowerCamelCase__ : Union[str, Any] = 'lower newer' lowerCamelCase__ : Union[str, Any] = self.prepare_image_inputs() lowerCamelCase__ : List[Any] = processor(text=UpperCAmelCase , images=UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(UpperCAmelCase ): processor() def A_ ( self : Optional[Any] ) -> Tuple: lowerCamelCase__ : int = self.get_image_processor() lowerCamelCase__ : Union[str, Any] = self.get_tokenizer() lowerCamelCase__ : Tuple = CLIPProcessor(tokenizer=UpperCAmelCase , image_processor=UpperCAmelCase ) lowerCamelCase__ : List[str] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] lowerCamelCase__ : Optional[Any] = processor.batch_decode(UpperCAmelCase ) lowerCamelCase__ : Optional[int] = tokenizer.batch_decode(UpperCAmelCase ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) def A_ ( self : Optional[int] ) -> Dict: lowerCamelCase__ : Any = self.get_image_processor() lowerCamelCase__ : Tuple = self.get_tokenizer() lowerCamelCase__ : Tuple = CLIPProcessor(tokenizer=UpperCAmelCase , image_processor=UpperCAmelCase ) lowerCamelCase__ : Optional[Any] = 'lower newer' lowerCamelCase__ : List[str] = self.prepare_image_inputs() lowerCamelCase__ : str = processor(text=UpperCAmelCase , images=UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
50
import torch import torch.nn as nn from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: int ) -> int: '''simple docstring''' A__ = nn.functional.normalize(SCREAMING_SNAKE_CASE_ ) A__ = nn.functional.normalize(SCREAMING_SNAKE_CASE_ ) return torch.mm(SCREAMING_SNAKE_CASE_ , normalized_text_embeds.t() ) class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = CLIPConfig __lowerCamelCase = ['CLIPEncoderLayer'] def __init__( self , lowercase ) -> Optional[int]: '''simple docstring''' super().__init__(lowercase ) A__ = CLIPVisionModel(config.vision_config ) A__ = nn.Linear(config.vision_config.hidden_size , config.projection_dim , bias=lowercase ) A__ = nn.Parameter(torch.ones(17 , config.projection_dim ) , requires_grad=lowercase ) A__ = nn.Parameter(torch.ones(3 , config.projection_dim ) , requires_grad=lowercase ) A__ = nn.Parameter(torch.ones(17 ) , requires_grad=lowercase ) A__ = nn.Parameter(torch.ones(3 ) , requires_grad=lowercase ) @torch.no_grad() def UpperCamelCase ( self , lowercase , lowercase ) -> Any: '''simple docstring''' A__ = self.vision_model(lowercase )[1] # pooled_output A__ = self.visual_projection(lowercase ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 A__ = cosine_distance(lowercase , self.special_care_embeds ).cpu().float().numpy() A__ = cosine_distance(lowercase , self.concept_embeds ).cpu().float().numpy() A__ = [] A__ = image_embeds.shape[0] for i in range(lowercase ): A__ = {"special_scores": {}, "special_care": [], "concept_scores": {}, "bad_concepts": []} # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign images A__ = 0.0 for concept_idx in range(len(special_cos_dist[0] ) ): A__ = special_cos_dist[i][concept_idx] A__ = self.special_care_embeds_weights[concept_idx].item() A__ = round(concept_cos - concept_threshold + adjustment , 3 ) if result_img["special_scores"][concept_idx] > 0: result_img["special_care"].append({concept_idx, result_img["special_scores"][concept_idx]} ) A__ = 0.01 for concept_idx in range(len(cos_dist[0] ) ): A__ = cos_dist[i][concept_idx] A__ = self.concept_embeds_weights[concept_idx].item() A__ = round(concept_cos - concept_threshold + adjustment , 3 ) if result_img["concept_scores"][concept_idx] > 0: result_img["bad_concepts"].append(lowercase ) result.append(lowercase ) A__ = [len(res["bad_concepts"] ) > 0 for res in result] return images, has_nsfw_concepts @torch.no_grad() def UpperCamelCase ( self , lowercase , lowercase ) -> Any: '''simple docstring''' A__ = self.vision_model(lowercase )[1] # pooled_output A__ = self.visual_projection(lowercase ) A__ = cosine_distance(lowercase , self.special_care_embeds ) A__ = cosine_distance(lowercase , self.concept_embeds ) # increase this value to create a stronger `nsfw` filter # at the cost of increasing the possibility of filtering benign images A__ = 0.0 A__ = special_cos_dist - self.special_care_embeds_weights + adjustment # special_scores = special_scores.round(decimals=3) A__ = torch.any(special_scores > 0 , dim=1 ) A__ = special_care * 0.01 A__ = special_adjustment.unsqueeze(1 ).expand(-1 , cos_dist.shape[1] ) A__ = (cos_dist - self.concept_embeds_weights) + special_adjustment # concept_scores = concept_scores.round(decimals=3) A__ = torch.any(concept_scores > 0 , dim=1 ) return images, has_nsfw_concepts
68
0
from ...utils import logging from ..ta.modeling_tf_ta import TFTaEncoderModel, TFTaForConditionalGeneration, TFTaModel from .configuration_mta import MTaConfig _A = logging.get_logger(__name__) _A = "T5Config" class lowerCamelCase ( A_ ): UpperCAmelCase__ : str = "mt5" UpperCAmelCase__ : List[str] = MTaConfig class lowerCamelCase ( A_ ): UpperCAmelCase__ : Union[str, Any] = "mt5" UpperCAmelCase__ : Any = MTaConfig class lowerCamelCase ( A_ ): UpperCAmelCase__ : Optional[Any] = "mt5" UpperCAmelCase__ : Dict = MTaConfig
353
from ..utils import DummyObject, requires_backends class lowerCamelCase ( metaclass=A_ ): UpperCAmelCase__ : Union[str, Any] = ["onnx"] def __init__(self : Tuple , *_A : Optional[int] , **_A : Any ) -> Dict: requires_backends(self , ["onnx"] ) @classmethod def UpperCAmelCase(cls : int , *_A : Dict , **_A : List[Any] ) -> Optional[Any]: requires_backends(cls , ["onnx"] ) @classmethod def UpperCAmelCase(cls : Dict , *_A : Tuple , **_A : Optional[Any] ) -> int: requires_backends(cls , ["onnx"] )
137
0
"""simple docstring""" from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig __A = logging.get_logger(__name__) # General docstring __A = "RegNetConfig" # Base docstring __A = "facebook/regnet-y-040" __A = [1, 1088, 7, 7] # Image classification docstring __A = "facebook/regnet-y-040" __A = "tabby, tabby cat" __A = [ "facebook/regnet-y-040", # See all regnet models at https://huggingface.co/models?filter=regnet ] class _lowerCAmelCase ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase = 3 , __UpperCAmelCase = 1 , __UpperCAmelCase = 1 , __UpperCAmelCase = "relu" , **__UpperCAmelCase , ): '''simple docstring''' super().__init__(**__lowercase ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb lowerCAmelCase__ :Dict = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) lowerCAmelCase__ :Union[str, Any] = tf.keras.layers.ConvaD( filters=__lowercase , kernel_size=__lowercase , strides=__lowercase , padding='VALID' , groups=__lowercase , use_bias=__lowercase , name='convolution' , ) lowerCAmelCase__ :Any = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name='normalization' ) lowerCAmelCase__ :int = ACTaFN[activation] if activation is not None else tf.identity def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :str = self.convolution(self.padding(__lowercase ) ) lowerCAmelCase__ :Optional[int] = self.normalization(__lowercase ) lowerCAmelCase__ :Tuple = self.activation(__lowercase ) return hidden_state class _lowerCAmelCase ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , __UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__lowercase ) lowerCAmelCase__ :List[str] = config.num_channels lowerCAmelCase__ :Tuple = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name='embedder' , ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :str = shape_list(__lowercase )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( 'Make sure that the channel dimension of the pixel values match with the one set in the configuration.' ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) lowerCAmelCase__ :Optional[Any] = tf.transpose(__lowercase , perm=(0, 2, 3, 1) ) lowerCAmelCase__ :Any = self.embedder(__lowercase ) return hidden_state class _lowerCAmelCase ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase = 2 , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__lowercase ) lowerCAmelCase__ :List[Any] = tf.keras.layers.ConvaD( filters=__lowercase , kernel_size=1 , strides=__lowercase , use_bias=__lowercase , name='convolution' ) lowerCAmelCase__ :Dict = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name='normalization' ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = False ): '''simple docstring''' return self.normalization(self.convolution(__lowercase ) , training=__lowercase ) class _lowerCAmelCase ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__lowercase ) lowerCAmelCase__ :List[Any] = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__lowercase , name='pooler' ) lowerCAmelCase__ :Dict = [ tf.keras.layers.ConvaD(filters=__lowercase , kernel_size=1 , activation='relu' , name='attention.0' ), tf.keras.layers.ConvaD(filters=__lowercase , kernel_size=1 , activation='sigmoid' , name='attention.2' ), ] def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :str = self.pooler(__lowercase ) for layer_module in self.attention: lowerCAmelCase__ :Tuple = layer_module(__lowercase ) lowerCAmelCase__ :Optional[int] = hidden_state * pooled return hidden_state class _lowerCAmelCase ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = 1 , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__lowercase ) lowerCAmelCase__ :Any = in_channels != out_channels or stride != 1 lowerCAmelCase__ :List[str] = max(1 , out_channels // config.groups_width ) lowerCAmelCase__ :int = ( TFRegNetShortCut(__lowercase , stride=__lowercase , name='shortcut' ) if should_apply_shortcut else tf.keras.layers.Activation('linear' , name='shortcut' ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. lowerCAmelCase__ :Any = [ TFRegNetConvLayer(__lowercase , kernel_size=1 , activation=config.hidden_act , name='layer.0' ), TFRegNetConvLayer( __lowercase , stride=__lowercase , groups=__lowercase , activation=config.hidden_act , name='layer.1' ), TFRegNetConvLayer(__lowercase , kernel_size=1 , activation=__lowercase , name='layer.2' ), ] lowerCAmelCase__ :List[str] = ACTaFN[config.hidden_act] def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = hidden_state for layer_module in self.layers: lowerCAmelCase__ :Optional[Any] = layer_module(__lowercase ) lowerCAmelCase__ :Dict = self.shortcut(__lowercase ) hidden_state += residual lowerCAmelCase__ :int = self.activation(__lowercase ) return hidden_state class _lowerCAmelCase ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = 1 , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__lowercase ) lowerCAmelCase__ :Dict = in_channels != out_channels or stride != 1 lowerCAmelCase__ :str = max(1 , out_channels // config.groups_width ) lowerCAmelCase__ :Optional[Any] = ( TFRegNetShortCut(__lowercase , stride=__lowercase , name='shortcut' ) if should_apply_shortcut else tf.keras.layers.Activation('linear' , name='shortcut' ) ) lowerCAmelCase__ :Optional[int] = [ TFRegNetConvLayer(__lowercase , kernel_size=1 , activation=config.hidden_act , name='layer.0' ), TFRegNetConvLayer( __lowercase , stride=__lowercase , groups=__lowercase , activation=config.hidden_act , name='layer.1' ), TFRegNetSELayer(__lowercase , reduced_channels=int(round(in_channels / 4 ) ) , name='layer.2' ), TFRegNetConvLayer(__lowercase , kernel_size=1 , activation=__lowercase , name='layer.3' ), ] lowerCAmelCase__ :Optional[int] = ACTaFN[config.hidden_act] def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = hidden_state for layer_module in self.layers: lowerCAmelCase__ :List[Any] = layer_module(__lowercase ) lowerCAmelCase__ :List[str] = self.shortcut(__lowercase ) hidden_state += residual lowerCAmelCase__ :List[str] = self.activation(__lowercase ) return hidden_state class _lowerCAmelCase ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = 2 , __UpperCAmelCase = 2 , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__lowercase ) lowerCAmelCase__ :Any = TFRegNetXLayer if config.layer_type == 'x' else TFRegNetYLayer lowerCAmelCase__ :Optional[Any] = [ # downsampling is done in the first layer with stride of 2 layer(__lowercase , __lowercase , __lowercase , stride=__lowercase , name='layers.0' ), *[layer(__lowercase , __lowercase , __lowercase , name=F"layers.{i+1}" ) for i in range(depth - 1 )], ] def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' for layer_module in self.layers: lowerCAmelCase__ :Optional[int] = layer_module(__lowercase ) return hidden_state class _lowerCAmelCase ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , __UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__lowercase ) lowerCAmelCase__ :Any = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( __lowercase , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name='stages.0' , ) ) lowerCAmelCase__ :int = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(__lowercase , config.depths[1:] ) ): self.stages.append(TFRegNetStage(__lowercase , __lowercase , __lowercase , depth=__lowercase , name=F"stages.{i+1}" ) ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = False , __UpperCAmelCase = True ): '''simple docstring''' lowerCAmelCase__ :Tuple = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: lowerCAmelCase__ :int = hidden_states + (hidden_state,) lowerCAmelCase__ :Any = stage_module(__lowercase ) if output_hidden_states: lowerCAmelCase__ :Dict = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=__lowercase , hidden_states=__lowercase ) @keras_serializable class _lowerCAmelCase ( tf.keras.layers.Layer ): """simple docstring""" __magic_name__ :int = RegNetConfig def __init__( self , __UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__lowercase ) lowerCAmelCase__ :Dict = config lowerCAmelCase__ :List[str] = TFRegNetEmbeddings(__lowercase , name='embedder' ) lowerCAmelCase__ :Optional[int] = TFRegNetEncoder(__lowercase , name='encoder' ) lowerCAmelCase__ :str = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__lowercase , name='pooler' ) @unpack_inputs def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = False , ): '''simple docstring''' lowerCAmelCase__ :Dict = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCAmelCase__ :Dict = return_dict if return_dict is not None else self.config.use_return_dict lowerCAmelCase__ :Union[str, Any] = self.embedder(__lowercase , training=__lowercase ) lowerCAmelCase__ :Union[str, Any] = self.encoder( __lowercase , output_hidden_states=__lowercase , return_dict=__lowercase , training=__lowercase ) lowerCAmelCase__ :Optional[Any] = encoder_outputs[0] lowerCAmelCase__ :int = self.pooler(__lowercase ) # Change to NCHW output format have uniformity in the modules lowerCAmelCase__ :Union[str, Any] = tf.transpose(__lowercase , perm=(0, 3, 1, 2) ) lowerCAmelCase__ :str = tf.transpose(__lowercase , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: lowerCAmelCase__ :Union[str, Any] = tuple([tf.transpose(__lowercase , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=__lowercase , pooler_output=__lowercase , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class _lowerCAmelCase ( UpperCAmelCase__ ): """simple docstring""" __magic_name__ :Tuple = RegNetConfig __magic_name__ :Tuple = """regnet""" __magic_name__ :Dict = """pixel_values""" @property def snake_case ( self ): '''simple docstring''' return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_2_4, 2_2_4) , dtype=tf.floataa )} __A = R"\n Parameters:\n This model is a Tensorflow\n [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and\n behavior.\n config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n" __A = R"\n Args:\n pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConveNextImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n" @add_start_docstrings( """The bare RegNet model outputting raw features without any specific head on top.""" , UpperCAmelCase__ , ) class _lowerCAmelCase ( UpperCAmelCase__ ): """simple docstring""" def __init__( self , __UpperCAmelCase , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' super().__init__(__lowercase , *__lowercase , **__lowercase ) lowerCAmelCase__ :str = TFRegNetMainLayer(__lowercase , name='regnet' ) @unpack_inputs @add_start_docstrings_to_model_forward(__lowercase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__lowercase , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase=False , ): '''simple docstring''' lowerCAmelCase__ :Tuple = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCAmelCase__ :int = return_dict if return_dict is not None else self.config.use_return_dict lowerCAmelCase__ :Tuple = self.regnet( pixel_values=__lowercase , output_hidden_states=__lowercase , return_dict=__lowercase , training=__lowercase , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , ) @add_start_docstrings( """ RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. """ , UpperCAmelCase__ , ) class _lowerCAmelCase ( UpperCAmelCase__ , UpperCAmelCase__ ): """simple docstring""" def __init__( self , __UpperCAmelCase , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' super().__init__(__lowercase , *__lowercase , **__lowercase ) lowerCAmelCase__ :List[str] = config.num_labels lowerCAmelCase__ :Optional[int] = TFRegNetMainLayer(__lowercase , name='regnet' ) # classification head lowerCAmelCase__ :str = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name='classifier.1' ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(__lowercase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__lowercase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def snake_case ( self , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase=False , ): '''simple docstring''' lowerCAmelCase__ :int = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCAmelCase__ :List[Any] = return_dict if return_dict is not None else self.config.use_return_dict lowerCAmelCase__ :Union[str, Any] = self.regnet( __lowercase , output_hidden_states=__lowercase , return_dict=__lowercase , training=__lowercase ) lowerCAmelCase__ :int = outputs.pooler_output if return_dict else outputs[1] lowerCAmelCase__ :Optional[Any] = self.classifier[0](__lowercase ) lowerCAmelCase__ :Union[str, Any] = self.classifier[1](__lowercase ) lowerCAmelCase__ :List[Any] = None if labels is None else self.hf_compute_loss(labels=__lowercase , logits=__lowercase ) if not return_dict: lowerCAmelCase__ :List[Any] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=__lowercase , logits=__lowercase , hidden_states=outputs.hidden_states )
293
import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowerCamelCase__ ( _A , _A , _A , _A , _A=True , _A="pt" ): '''simple docstring''' snake_case_ = {"add_prefix_space": True} if isinstance(_A , _A ) and not line.startswith(" " ) else {} snake_case_ = padding_side return tokenizer( [line] , max_length=_A , padding="max_length" if pad_to_max_length else None , truncation=_A , return_tensors=_A , add_special_tokens=_A , **_A , ) def lowerCamelCase__ ( _A , _A , _A=None , ): '''simple docstring''' snake_case_ = input_ids.ne(_A ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : int , __lowercase : List[Any] , __lowercase : Tuple , __lowercase : List[Any] , __lowercase : str , __lowercase : Tuple="train" , __lowercase : List[str]=None , __lowercase : List[Any]=None , __lowercase : Optional[Any]=None , __lowercase : Union[str, Any]="" , ): """simple docstring""" super().__init__() snake_case_ = Path(__lowercase ).joinpath(type_path + ".source" ) snake_case_ = Path(__lowercase ).joinpath(type_path + ".target" ) snake_case_ = self.get_char_lens(self.src_file ) snake_case_ = max_source_length snake_case_ = max_target_length assert min(self.src_lens ) > 0, f"found empty line in {self.src_file}" snake_case_ = tokenizer snake_case_ = prefix if n_obs is not None: snake_case_ = self.src_lens[:n_obs] snake_case_ = src_lang snake_case_ = tgt_lang def __len__( self : List[Any] ): """simple docstring""" return len(self.src_lens ) def __getitem__( self : List[Any] , __lowercase : Dict ): """simple docstring""" snake_case_ = index + 1 # linecache starts at 1 snake_case_ = self.prefix + linecache.getline(str(self.src_file ) , __lowercase ).rstrip("\n" ) snake_case_ = linecache.getline(str(self.tgt_file ) , __lowercase ).rstrip("\n" ) assert source_line, f"empty source line for index {index}" assert tgt_line, f"empty tgt line for index {index}" # Need to add eos token manually for T5 if isinstance(self.tokenizer , __lowercase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right snake_case_ = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , __lowercase ) else self.tokenizer ) snake_case_ = self.tokenizer.generator if isinstance(self.tokenizer , __lowercase ) else self.tokenizer snake_case_ = encode_line(__lowercase , __lowercase , self.max_source_length , "right" ) snake_case_ = encode_line(__lowercase , __lowercase , self.max_target_length , "right" ) snake_case_ = source_inputs["input_ids"].squeeze() snake_case_ = target_inputs["input_ids"].squeeze() snake_case_ = source_inputs["attention_mask"].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def snake_case__ ( __lowercase : Optional[int] ): """simple docstring""" return [len(__lowercase ) for x in Path(__lowercase ).open().readlines()] def snake_case__ ( self : Dict , __lowercase : Union[str, Any] ): """simple docstring""" snake_case_ = torch.stack([x["input_ids"] for x in batch] ) snake_case_ = torch.stack([x["attention_mask"] for x in batch] ) snake_case_ = torch.stack([x["decoder_input_ids"] for x in batch] ) snake_case_ = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , __lowercase ) else self.tokenizer.pad_token_id ) snake_case_ = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , __lowercase ) else self.tokenizer.pad_token_id ) snake_case_ = trim_batch(__lowercase , __lowercase ) snake_case_ , snake_case_ = trim_batch(__lowercase , __lowercase , attention_mask=__lowercase ) snake_case_ = { "input_ids": source_ids, "attention_mask": source_mask, "decoder_input_ids": y, } return batch lowercase__ : str = getLogger(__name__) def lowerCamelCase__ ( _A ): '''simple docstring''' return list(itertools.chain.from_iterable(_A ) ) def lowerCamelCase__ ( _A ): '''simple docstring''' snake_case_ = get_git_info() save_json(_A , os.path.join(_A , "git_log.json" ) ) def lowerCamelCase__ ( _A , _A , _A=4 , **_A ): '''simple docstring''' with open(_A , "w" ) as f: json.dump(_A , _A , indent=_A , **_A ) def lowerCamelCase__ ( _A ): '''simple docstring''' with open(_A ) as f: return json.load(_A ) def lowerCamelCase__ ( ): '''simple docstring''' snake_case_ = git.Repo(search_parent_directories=_A ) snake_case_ = { "repo_id": str(_A ), "repo_sha": str(repo.head.object.hexsha ), "repo_branch": str(repo.active_branch ), "hostname": str(socket.gethostname() ), } return repo_infos def lowerCamelCase__ ( _A , _A ): '''simple docstring''' return list(map(_A , _A ) ) def lowerCamelCase__ ( _A , _A ): '''simple docstring''' with open(_A , "wb" ) as f: return pickle.dump(_A , _A ) def lowerCamelCase__ ( _A ): '''simple docstring''' def remove_articles(_A ): return re.sub(R"\b(a|an|the)\b" , " " , _A ) def white_space_fix(_A ): return " ".join(text.split() ) def remove_punc(_A ): snake_case_ = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(_A ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_A ) ) ) ) def lowerCamelCase__ ( _A , _A ): '''simple docstring''' snake_case_ = normalize_answer(_A ).split() snake_case_ = normalize_answer(_A ).split() snake_case_ = Counter(_A ) & Counter(_A ) snake_case_ = sum(common.values() ) if num_same == 0: return 0 snake_case_ = 1.0 * num_same / len(_A ) snake_case_ = 1.0 * num_same / len(_A ) snake_case_ = (2 * precision * recall) / (precision + recall) return fa def lowerCamelCase__ ( _A , _A ): '''simple docstring''' return normalize_answer(_A ) == normalize_answer(_A ) def lowerCamelCase__ ( _A , _A ): '''simple docstring''' assert len(_A ) == len(_A ) snake_case_ = 0 for hypo, pred in zip(_A , _A ): em += exact_match_score(_A , _A ) if len(_A ) > 0: em /= len(_A ) return {"em": em} def lowerCamelCase__ ( _A ): '''simple docstring''' return model_prefix.startswith("rag" ) def lowerCamelCase__ ( _A , _A , _A ): '''simple docstring''' snake_case_ = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead snake_case_ = "dropout_rate" for p in extra_params: if getattr(_A , _A , _A ): if not hasattr(_A , _A ) and not hasattr(_A , equivalent_param[p] ): logger.info("config doesn't have a `{}` attribute".format(_A ) ) delattr(_A , _A ) continue snake_case_ = p if hasattr(_A , _A ) else equivalent_param[p] setattr(_A , _A , getattr(_A , _A ) ) delattr(_A , _A ) return hparams, config
187
0
import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, pipeline, ) from transformers.testing_utils import ( is_torch_available, require_accelerate, require_bitsandbytes, require_torch, require_torch_gpu, require_torch_multi_gpu, slow, ) def a__ ( A__ ): if model.config.model_type == "gpt2": return model.transformer.h[0].mlp.c_fc return model.transformer.h[0].mlp.dense_ah_to_h if is_torch_available(): import torch import torch.nn as nn class __lowercase (nn.Module ): """simple docstring""" def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ ): """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE_ : str = module SCREAMING_SNAKE_CASE_ : Dict = nn.Sequential( nn.Linear(module.in_features , lowerCAmelCase__ , bias=lowerCAmelCase__ ) , nn.Linear(lowerCAmelCase__ , module.out_features , bias=lowerCAmelCase__ ) , ) SCREAMING_SNAKE_CASE_ : Optional[int] = (2.0 / (5 * min(module.in_features , module.out_features ))) ** 0.5 nn.init.normal_(self.adapter[0].weight , std=lowerCAmelCase__ ) nn.init.zeros_(self.adapter[1].weight ) self.adapter.to(module.weight.device ) def UpperCamelCase__ ( self , lowerCAmelCase__ , *lowerCAmelCase__ , **lowerCAmelCase__ ): """simple docstring""" return self.module(lowerCAmelCase__ , *lowerCAmelCase__ , **lowerCAmelCase__ ) + self.adapter(lowerCAmelCase__ ) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class __lowercase (unittest.TestCase ): """simple docstring""" _UpperCAmelCase = """bigscience/bloom-1b7""" # Constant values _UpperCAmelCase = 2.1_09_65_95_52_69_25_74 _UpperCAmelCase = """Hello my name is""" _UpperCAmelCase = set() EXPECTED_OUTPUTS.add("""Hello my name is John and I am a professional photographer. I""" ) EXPECTED_OUTPUTS.add("""Hello my name is John.\nI am a friend of your father.\n""" ) EXPECTED_OUTPUTS.add("""Hello my name is John Doe, I am a student at the University""" ) _UpperCAmelCase = 1_0 def UpperCamelCase__ ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = AutoTokenizer.from_pretrained(self.model_name ) class __lowercase (__SCREAMING_SNAKE_CASE ): """simple docstring""" def UpperCamelCase__ ( self ): """simple docstring""" super().setUp() # Models and tokenizer SCREAMING_SNAKE_CASE_ : List[str] = AutoModelForCausalLM.from_pretrained( self.model_name , torch_dtype=torch.floataa , device_map='auto' ) SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=lowerCAmelCase__ , device_map='auto' ) def UpperCamelCase__ ( self ): """simple docstring""" del self.model_fpaa del self.model_abit gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = self.model_abit.config self.assertTrue(hasattr(lowerCAmelCase__ , 'quantization_config' ) ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = config.to_dict() SCREAMING_SNAKE_CASE_ : List[Any] = config.to_diff_dict() SCREAMING_SNAKE_CASE_ : Any = config.to_json_string() def UpperCamelCase__ ( self ): """simple docstring""" from bitsandbytes.nn import Paramsabit SCREAMING_SNAKE_CASE_ : List[Any] = self.model_fpaa.get_memory_footprint() SCREAMING_SNAKE_CASE_ : Dict = self.model_abit.get_memory_footprint() self.assertAlmostEqual(mem_fpaa / mem_abit , self.EXPECTED_RELATIVE_DIFFERENCE ) SCREAMING_SNAKE_CASE_ : Any = get_some_linear_layer(self.model_abit ) self.assertTrue(linear.weight.__class__ == Paramsabit ) def UpperCamelCase__ ( self ): """simple docstring""" from transformers import TaPreTrainedModel self.model_fpaa.get_memory_footprint() self.model_abit.get_memory_footprint() for name, module in self.model_abit.named_modules(): if isinstance(lowerCAmelCase__ , torch.nn.Linear ): if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules: # 4-bit parameters are packed in uint8 variables self.assertTrue(module.weight.dtype == torch.uinta ) def UpperCamelCase__ ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = self.tokenizer(self.input_text , return_tensors='pt' ) SCREAMING_SNAKE_CASE_ : str = self.model_abit.generate(input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=1_0 ) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=lowerCAmelCase__ ) , self.EXPECTED_OUTPUTS ) def UpperCamelCase__ ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = BitsAndBytesConfig() SCREAMING_SNAKE_CASE_ : int = True SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=lowerCAmelCase__ , device_map='auto' ) SCREAMING_SNAKE_CASE_ : Tuple = self.tokenizer(self.input_text , return_tensors='pt' ) SCREAMING_SNAKE_CASE_ : int = model_abit_from_config.generate( input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=1_0 ) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=lowerCAmelCase__ ) , self.EXPECTED_OUTPUTS ) def UpperCamelCase__ ( self ): """simple docstring""" with self.assertRaises(lowerCAmelCase__ ), tempfile.TemporaryDirectory() as tmpdirname: self.model_abit.save_pretrained(lowerCAmelCase__ ) def UpperCamelCase__ ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = BitsAndBytesConfig() with self.assertRaises(lowerCAmelCase__ ): SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=lowerCAmelCase__ , load_in_abit=lowerCAmelCase__ , device_map='auto' , bnb_abit_quant_type='nf4' , ) def UpperCamelCase__ ( self ): """simple docstring""" with self.assertRaises(lowerCAmelCase__ ): # Tries with `str` self.model_abit.to('cpu' ) with self.assertRaises(lowerCAmelCase__ ): # Tries with a `dtype`` self.model_abit.to(torch.floataa ) with self.assertRaises(lowerCAmelCase__ ): # Tries with a `device` self.model_abit.to(torch.device('cuda:0' ) ) with self.assertRaises(lowerCAmelCase__ ): # Tries with a `device` self.model_abit.float() with self.assertRaises(lowerCAmelCase__ ): # Tries with a `device` self.model_abit.half() # Test if we did not break anything SCREAMING_SNAKE_CASE_ : Dict = self.tokenizer(self.input_text , return_tensors='pt' ) SCREAMING_SNAKE_CASE_ : List[Any] = self.model_fpaa.to(torch.floataa ) SCREAMING_SNAKE_CASE_ : Any = self.model_fpaa.generate(input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=1_0 ) # Check this does not throw an error SCREAMING_SNAKE_CASE_ : List[str] = self.model_fpaa.to('cpu' ) # Check this does not throw an error SCREAMING_SNAKE_CASE_ : Tuple = self.model_fpaa.half() # Check this does not throw an error SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model_fpaa.float() def UpperCamelCase__ ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = AutoModelForSeqaSeqLM.from_pretrained('t5-small' , load_in_abit=lowerCAmelCase__ , device_map='auto' ) self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa ) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class __lowercase (unittest.TestCase ): """simple docstring""" @classmethod def UpperCamelCase__ ( cls ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = 't5-small' SCREAMING_SNAKE_CASE_ : Optional[int] = 'google/flan-t5-small' # flan-t5 uses dense-act instead of dense-relu-dense SCREAMING_SNAKE_CASE_ : Optional[int] = AutoTokenizer.from_pretrained(cls.model_name ) SCREAMING_SNAKE_CASE_ : List[str] = 'Translate in German: Hello, my dog is cute' def UpperCamelCase__ ( self ): """simple docstring""" gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ ( self ): """simple docstring""" from transformers import TaForConditionalGeneration SCREAMING_SNAKE_CASE_ : int = TaForConditionalGeneration._keep_in_fpaa_modules SCREAMING_SNAKE_CASE_ : Dict = None # test with `t5-small` SCREAMING_SNAKE_CASE_ : int = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=lowerCAmelCase__ , device_map='auto' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) SCREAMING_SNAKE_CASE_ : Dict = model.generate(**lowerCAmelCase__ ) # test with `flan-t5-small` SCREAMING_SNAKE_CASE_ : int = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=lowerCAmelCase__ , device_map='auto' ) SCREAMING_SNAKE_CASE_ : Optional[int] = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) SCREAMING_SNAKE_CASE_ : Dict = model.generate(**lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ : str = modules def UpperCamelCase__ ( self ): """simple docstring""" import bitsandbytes as bnb from transformers import TaForConditionalGeneration # test with `t5-small` SCREAMING_SNAKE_CASE_ : List[str] = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=lowerCAmelCase__ , device_map='auto' ) # there was a bug with decoders - this test checks that it is fixed self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q , bnb.nn.Linearabit ) ) SCREAMING_SNAKE_CASE_ : str = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) SCREAMING_SNAKE_CASE_ : Optional[Any] = model.generate(**lowerCAmelCase__ ) # test with `flan-t5-small` SCREAMING_SNAKE_CASE_ : Union[str, Any] = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=lowerCAmelCase__ , device_map='auto' ) SCREAMING_SNAKE_CASE_ : List[Any] = self.tokenizer(self.input_text , return_tensors='pt' ).to(0 ) SCREAMING_SNAKE_CASE_ : Tuple = model.generate(**lowerCAmelCase__ ) class __lowercase (__SCREAMING_SNAKE_CASE ): """simple docstring""" def UpperCamelCase__ ( self ): """simple docstring""" super().setUp() # model_name SCREAMING_SNAKE_CASE_ : Dict = 'bigscience/bloom-560m' SCREAMING_SNAKE_CASE_ : List[str] = 't5-small' # Different types of model SCREAMING_SNAKE_CASE_ : Optional[Any] = AutoModel.from_pretrained(self.model_name , load_in_abit=lowerCAmelCase__ , device_map='auto' ) # Sequence classification model SCREAMING_SNAKE_CASE_ : Any = AutoModelForSequenceClassification.from_pretrained( self.model_name , load_in_abit=lowerCAmelCase__ , device_map='auto' ) # CausalLM model SCREAMING_SNAKE_CASE_ : str = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=lowerCAmelCase__ , device_map='auto' ) # Seq2seq model SCREAMING_SNAKE_CASE_ : Union[str, Any] = AutoModelForSeqaSeqLM.from_pretrained( self.seq_to_seq_name , load_in_abit=lowerCAmelCase__ , device_map='auto' ) def UpperCamelCase__ ( self ): """simple docstring""" del self.base_model del self.sequence_model del self.model_abit del self.seq_to_seq_model gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ ( self ): """simple docstring""" from bitsandbytes.nn import Paramsabit self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit ) # Other heads should be nn.Parameter self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter ) self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter ) self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter ) class __lowercase (__SCREAMING_SNAKE_CASE ): """simple docstring""" def UpperCamelCase__ ( self ): """simple docstring""" super().setUp() def UpperCamelCase__ ( self ): """simple docstring""" del self.pipe gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = pipeline( 'text-generation' , model=self.model_name , model_kwargs={'device_map': 'auto', 'load_in_4bit': True, 'torch_dtype': torch.floataa} , max_new_tokens=self.MAX_NEW_TOKENS , ) # Real second forward pass SCREAMING_SNAKE_CASE_ : List[Any] = self.pipe(self.input_text ) self.assertIn(pipeline_output[0]['generated_text'] , self.EXPECTED_OUTPUTS ) @require_torch_multi_gpu class __lowercase (__SCREAMING_SNAKE_CASE ): """simple docstring""" def UpperCamelCase__ ( self ): """simple docstring""" super().setUp() def UpperCamelCase__ ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = AutoModelForCausalLM.from_pretrained( self.model_name , load_in_abit=lowerCAmelCase__ , device_map='balanced' ) # Check correct device map self.assertEqual(set(model_parallel.hf_device_map.values() ) , {0, 1} ) # Check that inference pass works on the model SCREAMING_SNAKE_CASE_ : List[Any] = self.tokenizer(self.input_text , return_tensors='pt' ) # Second real batch SCREAMING_SNAKE_CASE_ : Optional[int] = model_parallel.generate(input_ids=encoded_input['input_ids'].to(0 ) , max_new_tokens=1_0 ) self.assertIn(self.tokenizer.decode(output_parallel[0] , skip_special_tokens=lowerCAmelCase__ ) , self.EXPECTED_OUTPUTS ) class __lowercase (__SCREAMING_SNAKE_CASE ): """simple docstring""" def UpperCamelCase__ ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = 'facebook/opt-350m' super().setUp() def UpperCamelCase__ ( self ): """simple docstring""" if version.parse(importlib.metadata.version('bitsandbytes' ) ) < version.parse('0.37.0' ): return # Step 1: freeze all parameters SCREAMING_SNAKE_CASE_ : List[str] = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=lowerCAmelCase__ ) self.assertEqual(set(model.hf_device_map.values() ) , {torch.cuda.current_device()} ) for param in model.parameters(): SCREAMING_SNAKE_CASE_ : List[Any] = False # freeze the model - train adapters later if param.ndim == 1: # cast the small parameters (e.g. layernorm) to fp32 for stability SCREAMING_SNAKE_CASE_ : Dict = param.data.to(torch.floataa ) # Step 2: add adapters for _, module in model.named_modules(): if "OPTAttention" in repr(type(lowerCAmelCase__ ) ): SCREAMING_SNAKE_CASE_ : int = LoRALayer(module.q_proj , rank=1_6 ) SCREAMING_SNAKE_CASE_ : List[Any] = LoRALayer(module.k_proj , rank=1_6 ) SCREAMING_SNAKE_CASE_ : Optional[Any] = LoRALayer(module.v_proj , rank=1_6 ) # Step 3: dummy batch SCREAMING_SNAKE_CASE_ : Tuple = self.tokenizer('Test batch ' , return_tensors='pt' ).to(0 ) # Step 4: Check if the gradient is not None with torch.cuda.amp.autocast(): SCREAMING_SNAKE_CASE_ : List[Any] = model.forward(**lowerCAmelCase__ ) out.logits.norm().backward() for module in model.modules(): if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): self.assertTrue(module.adapter[1].weight.grad is not None ) self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0 ) elif isinstance(lowerCAmelCase__ , nn.Embedding ): self.assertTrue(module.weight.grad is None ) class __lowercase (__SCREAMING_SNAKE_CASE ): """simple docstring""" _UpperCAmelCase = """gpt2-xl""" _UpperCAmelCase = 3.31_91_85_48_54_15_21_87
162
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lowerCAmelCase__ : List[Any] =logging.get_logger(__name__) lowerCAmelCase__ : Tuple ={ 'microsoft/focalnet-tiny': 'https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json', } class __lowercase (__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" _UpperCAmelCase = """focalnet""" def __init__( self , lowerCAmelCase__=2_2_4 , lowerCAmelCase__=4 , lowerCAmelCase__=3 , lowerCAmelCase__=9_6 , lowerCAmelCase__=False , lowerCAmelCase__=[1_9_2, 3_8_4, 7_6_8, 7_6_8] , lowerCAmelCase__=[2, 2, 6, 2] , lowerCAmelCase__=[2, 2, 2, 2] , lowerCAmelCase__=[3, 3, 3, 3] , lowerCAmelCase__="gelu" , lowerCAmelCase__=4.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.1 , lowerCAmelCase__=False , lowerCAmelCase__=1E-4 , lowerCAmelCase__=False , lowerCAmelCase__=False , lowerCAmelCase__=False , lowerCAmelCase__=0.02 , lowerCAmelCase__=1E-5 , lowerCAmelCase__=3_2 , lowerCAmelCase__=None , lowerCAmelCase__=None , **lowerCAmelCase__ , ): """simple docstring""" super().__init__(**lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ : Dict = image_size SCREAMING_SNAKE_CASE_ : str = patch_size SCREAMING_SNAKE_CASE_ : List[Any] = num_channels SCREAMING_SNAKE_CASE_ : Union[str, Any] = embed_dim SCREAMING_SNAKE_CASE_ : Any = use_conv_embed SCREAMING_SNAKE_CASE_ : Dict = hidden_sizes SCREAMING_SNAKE_CASE_ : Any = depths SCREAMING_SNAKE_CASE_ : Optional[Any] = focal_levels SCREAMING_SNAKE_CASE_ : Any = focal_windows SCREAMING_SNAKE_CASE_ : Tuple = hidden_act SCREAMING_SNAKE_CASE_ : Dict = mlp_ratio SCREAMING_SNAKE_CASE_ : Any = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : Tuple = drop_path_rate SCREAMING_SNAKE_CASE_ : List[Any] = use_layerscale SCREAMING_SNAKE_CASE_ : List[Any] = layerscale_value SCREAMING_SNAKE_CASE_ : List[str] = use_post_layernorm SCREAMING_SNAKE_CASE_ : Optional[int] = use_post_layernorm_in_modulation SCREAMING_SNAKE_CASE_ : str = normalize_modulator SCREAMING_SNAKE_CASE_ : List[str] = initializer_range SCREAMING_SNAKE_CASE_ : str = layer_norm_eps SCREAMING_SNAKE_CASE_ : Dict = encoder_stride SCREAMING_SNAKE_CASE_ : Dict = ['stem'] + [F'''stage{idx}''' for idx in range(1 , len(self.depths ) + 1 )] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = get_aligned_output_features_output_indices( out_features=lowerCAmelCase__ , out_indices=lowerCAmelCase__ , stage_names=self.stage_names )
162
1
"""simple docstring""" from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def __lowerCamelCase ( ) -> int: __SCREAMING_SNAKE_CASE :Dict = HfArgumentParser(a_ ) __SCREAMING_SNAKE_CASE :Dict = parser.parse_args_into_dataclasses()[0] __SCREAMING_SNAKE_CASE :int = TensorFlowBenchmark(args=a_ ) try: __SCREAMING_SNAKE_CASE :str = parser.parse_args_into_dataclasses()[0] except ValueError as e: __SCREAMING_SNAKE_CASE :str = '''Arg --no_{0} is no longer used, please use --no-{0} instead.''' __SCREAMING_SNAKE_CASE :List[Any] = ''' '''.join(str(a_ ).split(''' ''' )[:-1] ) __SCREAMING_SNAKE_CASE :List[Any] = '''''' __SCREAMING_SNAKE_CASE :Any = eval(str(a_ ).split(''' ''' )[-1] ) __SCREAMING_SNAKE_CASE :Dict = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(a_ ) if len(a_ ) > 0: __SCREAMING_SNAKE_CASE :Union[str, Any] = full_error_msg + begin_error_msg + str(a_ ) raise ValueError(a_ ) benchmark.run() if __name__ == "__main__": main()
191
"""simple docstring""" from __future__ import annotations import copy import tempfile import unittest from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available from transformers.testing_utils import ( DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tensorflow_probability, require_tf, slow, ) from ..bert.test_modeling_bert import BertModelTester if is_tf_available(): from transformers import ( TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelForTableQuestionAnswering, TFAutoModelForTokenClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFFunnelBaseModel, TFFunnelModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, TFTapasForQuestionAnswering, ) from transformers.models.auto.modeling_tf_auto import ( TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_MAPPING, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST class _SCREAMING_SNAKE_CASE( A ): SCREAMING_SNAKE_CASE_ : int = '''new-model''' if is_tf_available(): class _SCREAMING_SNAKE_CASE( A ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = NewModelConfig @require_tf class _SCREAMING_SNAKE_CASE( unittest.TestCase ): @slow def _UpperCamelCase ( self ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE :Tuple = '''bert-base-cased''' __SCREAMING_SNAKE_CASE :int = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE :List[str] = TFAutoModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) @slow def _UpperCamelCase ( self ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE :Tuple = '''bert-base-cased''' __SCREAMING_SNAKE_CASE :List[str] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE :str = TFAutoModelForPreTraining.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) @slow def _UpperCamelCase ( self ) -> Dict: """simple docstring""" for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE :List[str] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE :Optional[int] = TFAutoModelForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE :Dict = TFAutoModelForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE__ ,output_loading_info=SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) @slow def _UpperCamelCase ( self ) -> int: """simple docstring""" for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE :List[str] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE :Any = TFAutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) @slow def _UpperCamelCase ( self ) -> Optional[int]: """simple docstring""" for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE :Union[str, Any] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE :Tuple = TFAutoModelForMaskedLM.from_pretrained(SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE :Tuple = TFAutoModelForMaskedLM.from_pretrained(SCREAMING_SNAKE_CASE__ ,output_loading_info=SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) @slow def _UpperCamelCase ( self ) -> Dict: """simple docstring""" for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE :Optional[Any] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE :str = TFAutoModelForSeqaSeqLM.from_pretrained(SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE :Optional[int] = TFAutoModelForSeqaSeqLM.from_pretrained(SCREAMING_SNAKE_CASE__ ,output_loading_info=SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) @slow def _UpperCamelCase ( self ) -> Tuple: """simple docstring""" for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE :Optional[int] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE :List[str] = TFAutoModelForSequenceClassification.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) @slow def _UpperCamelCase ( self ) -> Tuple: """simple docstring""" for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE :Optional[int] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE :Optional[Any] = TFAutoModelForQuestionAnswering.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) @slow @require_tensorflow_probability def _UpperCamelCase ( self ) -> int: """simple docstring""" for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]: __SCREAMING_SNAKE_CASE :int = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE :Union[str, Any] = TFAutoModelForTableQuestionAnswering.from_pretrained(SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE :Optional[int] = TFAutoModelForTableQuestionAnswering.from_pretrained( SCREAMING_SNAKE_CASE__ ,output_loading_info=SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE :int = TFAutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) self.assertEqual(model.num_parameters() ,1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=SCREAMING_SNAKE_CASE__ ) ,1_44_10 ) def _UpperCamelCase ( self ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE :Optional[Any] = TFAutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) self.assertEqual(model.num_parameters() ,1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=SCREAMING_SNAKE_CASE__ ) ,1_44_10 ) def _UpperCamelCase ( self ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE :Optional[Any] = TFAutoModel.from_pretrained('''sgugger/funnel-random-tiny''' ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE :str = copy.deepcopy(model.config ) __SCREAMING_SNAKE_CASE :List[str] = ['''FunnelBaseModel'''] __SCREAMING_SNAKE_CASE :int = TFAutoModel.from_config(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE :Union[str, Any] = TFAutoModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ) -> Optional[Any]: """simple docstring""" try: AutoConfig.register('''new-model''' ,SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE :Tuple = [ TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSequenceClassification, TFAutoModelForTokenClassification, ] for auto_class in auto_classes: with self.subTest(auto_class.__name__ ): # Wrong config class will raise an error with self.assertRaises(SCREAMING_SNAKE_CASE__ ): auto_class.register(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) auto_class.register(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(SCREAMING_SNAKE_CASE__ ): auto_class.register(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) # Now that the config is registered, it can be used as any other config with the auto-API __SCREAMING_SNAKE_CASE :Any = BertModelTester(self ).get_config() __SCREAMING_SNAKE_CASE :Dict = NewModelConfig(**tiny_config.to_dict() ) __SCREAMING_SNAKE_CASE :Union[str, Any] = auto_class.from_config(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE :str = auto_class.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"] for mapping in ( TF_MODEL_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, ): if NewModelConfig in mapping._extra_content: del mapping._extra_content[NewModelConfig] def _UpperCamelCase ( self ) -> int: """simple docstring""" with self.assertRaisesRegex( SCREAMING_SNAKE_CASE__ ,'''bert-base is not a local folder and is not a valid model identifier''' ): __SCREAMING_SNAKE_CASE :int = TFAutoModel.from_pretrained('''bert-base''' ) def _UpperCamelCase ( self ) -> Any: """simple docstring""" with self.assertRaisesRegex( SCREAMING_SNAKE_CASE__ ,R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): __SCREAMING_SNAKE_CASE :Union[str, Any] = TFAutoModel.from_pretrained(SCREAMING_SNAKE_CASE__ ,revision='''aaaaaa''' ) def _UpperCamelCase ( self ) -> List[str]: """simple docstring""" with self.assertRaisesRegex( SCREAMING_SNAKE_CASE__ ,'''hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin''' ,): __SCREAMING_SNAKE_CASE :Optional[Any] = TFAutoModel.from_pretrained('''hf-internal-testing/config-no-model''' ) def _UpperCamelCase ( self ) -> List[Any]: """simple docstring""" with self.assertRaisesRegex(SCREAMING_SNAKE_CASE__ ,'''Use `from_pt=True` to load this model''' ): __SCREAMING_SNAKE_CASE :List[str] = TFAutoModel.from_pretrained('''hf-internal-testing/tiny-bert-pt-only''' ) def _UpperCamelCase ( self ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE :int = TFAutoModel.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) with RequestCounter() as counter: __SCREAMING_SNAKE_CASE :int = TFAutoModel.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) self.assertEqual(counter.get_request_count ,0 ) self.assertEqual(counter.head_request_count ,1 ) self.assertEqual(counter.other_request_count ,0 ) # With a sharded checkpoint __SCREAMING_SNAKE_CASE :Dict = TFAutoModel.from_pretrained('''ArthurZ/tiny-random-bert-sharded''' ) with RequestCounter() as counter: __SCREAMING_SNAKE_CASE :Optional[Any] = TFAutoModel.from_pretrained('''ArthurZ/tiny-random-bert-sharded''' ) self.assertEqual(counter.get_request_count ,0 ) self.assertEqual(counter.head_request_count ,1 ) self.assertEqual(counter.other_request_count ,0 )
191
1
from collections.abc import Iterable from typing import Any class lowerCAmelCase__: '''simple docstring''' def __init__( self , __lowerCamelCase = None ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE : List[Any] = value _SCREAMING_SNAKE_CASE : Node | None = None # Added in order to delete a node easier _SCREAMING_SNAKE_CASE : Node | None = None _SCREAMING_SNAKE_CASE : Node | None = None def __repr__( self ) -> str: from pprint import pformat if self.left is None and self.right is None: return str(self.value ) return pformat({F"""{self.value}""": (self.left, self.right)} , indent=1 ) class lowerCAmelCase__: '''simple docstring''' def __init__( self , __lowerCamelCase = None ) -> Dict: _SCREAMING_SNAKE_CASE : Tuple = root def __str__( self ) -> str: return str(self.root ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> None: if new_children is not None: # reset its kids _SCREAMING_SNAKE_CASE : List[str] = node.parent if node.parent is not None: # reset its parent if self.is_right(__lowerCamelCase ): # If it is the right children _SCREAMING_SNAKE_CASE : Union[str, Any] = new_children else: _SCREAMING_SNAKE_CASE : Union[str, Any] = new_children else: _SCREAMING_SNAKE_CASE : int = new_children def UpperCamelCase_ ( self , __lowerCamelCase ) -> bool: if node.parent and node.parent.right: return node == node.parent.right return False def UpperCamelCase_ ( self ) -> bool: return self.root is None def UpperCamelCase_ ( self , __lowerCamelCase ) -> None: _SCREAMING_SNAKE_CASE : Union[str, Any] = Node(__lowerCamelCase ) # create a new Node if self.empty(): # if Tree is empty _SCREAMING_SNAKE_CASE : List[str] = new_node # set its root else: # Tree is not empty _SCREAMING_SNAKE_CASE : Optional[int] = self.root # from root if parent_node is None: return while True: # While we don't get to a leaf if value < parent_node.value: # We go left if parent_node.left is None: _SCREAMING_SNAKE_CASE : int = new_node # We insert the new node in a leaf break else: _SCREAMING_SNAKE_CASE : Optional[int] = parent_node.left else: if parent_node.right is None: _SCREAMING_SNAKE_CASE : Tuple = new_node break else: _SCREAMING_SNAKE_CASE : Union[str, Any] = parent_node.right _SCREAMING_SNAKE_CASE : str = parent_node def UpperCamelCase_ ( self , *__lowerCamelCase ) -> None: for value in values: self.__insert(__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase ) -> Node | None: if self.empty(): raise IndexError("Warning: Tree is empty! please use another." ) else: _SCREAMING_SNAKE_CASE : List[Any] = self.root # use lazy evaluation here to avoid NoneType Attribute error while node is not None and node.value is not value: _SCREAMING_SNAKE_CASE : Dict = node.left if value < node.value else node.right return node def UpperCamelCase_ ( self , __lowerCamelCase = None ) -> Node | None: if node is None: if self.root is None: return None _SCREAMING_SNAKE_CASE : Tuple = self.root if not self.empty(): while node.right is not None: _SCREAMING_SNAKE_CASE : int = node.right return node def UpperCamelCase_ ( self , __lowerCamelCase = None ) -> Node | None: if node is None: _SCREAMING_SNAKE_CASE : List[str] = self.root if self.root is None: return None if not self.empty(): _SCREAMING_SNAKE_CASE : Tuple = self.root while node.left is not None: _SCREAMING_SNAKE_CASE : Dict = node.left return node def UpperCamelCase_ ( self , __lowerCamelCase ) -> None: _SCREAMING_SNAKE_CASE : Optional[int] = self.search(__lowerCamelCase ) # Look for the node with that label if node is not None: if node.left is None and node.right is None: # If it has no children self.__reassign_nodes(__lowerCamelCase , __lowerCamelCase ) elif node.left is None: # Has only right children self.__reassign_nodes(__lowerCamelCase , node.right ) elif node.right is None: # Has only left children self.__reassign_nodes(__lowerCamelCase , node.left ) else: _SCREAMING_SNAKE_CASE : int = self.get_max( node.left ) # Gets the max value of the left branch self.remove(tmp_node.value ) # type: ignore _SCREAMING_SNAKE_CASE : int = ( tmp_node.value # type: ignore ) # Assigns the value to the node to delete and keep tree structure def UpperCamelCase_ ( self , __lowerCamelCase ) -> Iterable: if node is not None: yield node # Preorder Traversal yield from self.preorder_traverse(node.left ) yield from self.preorder_traverse(node.right ) def UpperCamelCase_ ( self , __lowerCamelCase=None ) -> Any: if traversal_function is None: return self.preorder_traverse(self.root ) else: return traversal_function(self.root ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> None: if node: self.inorder(__lowerCamelCase , node.left ) arr.append(node.value ) self.inorder(__lowerCamelCase , node.right ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> int: _SCREAMING_SNAKE_CASE : list[int] = [] self.inorder(__lowerCamelCase , __lowerCamelCase ) # append all values to list using inorder traversal return arr[k - 1] def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : Optional[int] = [] if curr_node is not None: _SCREAMING_SNAKE_CASE : str = postorder(curr_node.left ) + postorder(curr_node.right ) + [curr_node] return node_list def lowerCamelCase__ (): _SCREAMING_SNAKE_CASE : Optional[int] = (8, 3, 6, 1, 10, 14, 13, 4, 7) _SCREAMING_SNAKE_CASE : int = BinarySearchTree() for i in testlist: t.insert(__lowerCamelCase ) # Prints all the elements of the list in order traversal print(__lowerCamelCase ) if t.search(6 ) is not None: print("The value 6 exists" ) else: print("The value 6 doesn't exist" ) if t.search(-1 ) is not None: print("The value -1 exists" ) else: print("The value -1 doesn't exist" ) if not t.empty(): print("Max Value: ", t.get_max().value ) # type: ignore print("Min Value: ", t.get_min().value ) # type: ignore for i in testlist: t.remove(__lowerCamelCase ) print(__lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
369
from math import isqrt, loga def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : List[Any] = [True] * max_number for i in range(2, isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2, __lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = False return [i for i in range(2, __lowerCamelCase ) if is_prime[i]] def lowerCamelCase__ (__lowerCamelCase = 800800, __lowerCamelCase = 800800 ): _SCREAMING_SNAKE_CASE : Optional[int] = degree * loga(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = int(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = calculate_prime_numbers(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : str = 0 _SCREAMING_SNAKE_CASE : int = 0 _SCREAMING_SNAKE_CASE : Dict = len(__lowerCamelCase ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f"{solution() = }")
325
0
"""simple docstring""" def lowerCamelCase__ ( __snake_case ) -> Optional[int]: """simple docstring""" _UpperCamelCase = [] _UpperCamelCase = [] _UpperCamelCase = { '''^''': 3, '''*''': 2, '''/''': 2, '''%''': 2, '''+''': 1, '''-''': 1, } # Priority of each operator _UpperCamelCase = len(__snake_case ) if (len(__snake_case ) > 7) else 7 # Print table header for output print( '''Symbol'''.center(8 ), '''Stack'''.center(__snake_case ), '''Postfix'''.center(__snake_case ), sep=''' | ''', ) print('''-''' * (print_width * 3 + 7) ) for x in infix: if x.isalpha() or x.isdigit(): post_fix.append(__snake_case ) # if x is Alphabet / Digit, add it to Postfix elif x == "(": stack.append(__snake_case ) # if x is "(" push to Stack elif x == ")": # if x is ")" pop stack until "(" is encountered while stack[-1] != "(": post_fix.append(stack.pop() ) # Pop stack & add the content to Postfix stack.pop() else: if len(__snake_case ) == 0: stack.append(__snake_case ) # If stack is empty, push x to stack else: # while priority of x is not > priority of element in the stack while len(__snake_case ) > 0 and priority[x] <= priority[stack[-1]]: post_fix.append(stack.pop() ) # pop stack & add to Postfix stack.append(__snake_case ) # push x to stack print( x.center(8 ), (''''''.join(__snake_case )).ljust(__snake_case ), (''''''.join(__snake_case )).ljust(__snake_case ), sep=''' | ''', ) # Output in tabular format while len(__snake_case ) > 0: # while stack is not empty post_fix.append(stack.pop() ) # pop stack & add to Postfix print( ''' '''.center(8 ), (''''''.join(__snake_case )).ljust(__snake_case ), (''''''.join(__snake_case )).ljust(__snake_case ), sep=''' | ''', ) # Output in tabular format return "".join(__snake_case ) # return Postfix as str def lowerCamelCase__ ( __snake_case ) -> List[str]: """simple docstring""" _UpperCamelCase = list(infix[::-1] ) # reverse the infix equation for i in range(len(__snake_case ) ): if infix[i] == "(": _UpperCamelCase = ''')''' # change "(" to ")" elif infix[i] == ")": _UpperCamelCase = '''(''' # change ")" to "(" return (infix_2_postfix(''''''.join(__snake_case ) ))[ ::-1 ] # call infix_2_postfix on Infix, return reverse of Postfix if __name__ == "__main__": _a = input("""\nEnter an Infix Equation = """) # Input an Infix equation _a = """""".join(Infix.split()) # Remove spaces from the input print("""\n\t""", Infix, """(Infix) -> """, infix_2_prefix(Infix), """(Prefix)""")
194
"""simple docstring""" from graphs.minimum_spanning_tree_kruskal import kruskal def lowerCamelCase__ ( ) -> List[Any]: """simple docstring""" _UpperCamelCase = 9 _UpperCamelCase = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] _UpperCamelCase = kruskal(__snake_case, __snake_case ) _UpperCamelCase = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] assert sorted(__snake_case ) == sorted(__snake_case )
194
1
"""simple docstring""" import heapq as hq import math from collections.abc import Iterator class UpperCamelCase_ : def __init__( self , snake_case__ ) -> Optional[int]: """simple docstring""" UpperCAmelCase = str(id_ ) UpperCAmelCase = None UpperCAmelCase = None UpperCAmelCase = [] UpperCAmelCase = {} # {vertex:distance} def __lt__( self , snake_case__ ) -> Any: """simple docstring""" return self.key < other.key def __repr__( self ) -> Optional[Any]: """simple docstring""" return self.id def UpperCamelCase_ ( self , snake_case__ ) -> int: """simple docstring""" self.neighbors.append(snake_case__ ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ ) -> Any: """simple docstring""" UpperCAmelCase = weight def _lowerCAmelCase ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): '''simple docstring''' graph[a - 1].add_neighbor(graph[b - 1] ) graph[b - 1].add_neighbor(graph[a - 1] ) # add the edges: graph[a - 1].add_edge(graph[b - 1] , lowerCAmelCase ) graph[b - 1].add_edge(graph[a - 1] , lowerCAmelCase ) def _lowerCAmelCase ( lowerCAmelCase , lowerCAmelCase ): '''simple docstring''' UpperCAmelCase = [] for u in graph: UpperCAmelCase = math.inf UpperCAmelCase = None UpperCAmelCase = 0 UpperCAmelCase = graph[:] while q: UpperCAmelCase = min(lowerCAmelCase ) q.remove(lowerCAmelCase ) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): UpperCAmelCase = u UpperCAmelCase = u.edges[v.id] for i in range(1 , len(lowerCAmelCase ) ): a.append((int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) ) return a def _lowerCAmelCase ( lowerCAmelCase , lowerCAmelCase ): '''simple docstring''' for u in graph: UpperCAmelCase = math.inf UpperCAmelCase = None UpperCAmelCase = 0 UpperCAmelCase = list(lowerCAmelCase ) hq.heapify(lowerCAmelCase ) while h: UpperCAmelCase = hq.heappop(lowerCAmelCase ) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): UpperCAmelCase = u UpperCAmelCase = u.edges[v.id] hq.heapify(lowerCAmelCase ) for i in range(1 , len(lowerCAmelCase ) ): yield (int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) def _lowerCAmelCase ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
360
"""simple docstring""" from __future__ import annotations import numpy as np def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' return np.maximum(0 , lowerCAmelCase ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
248
0
from typing import List from .keymap import KEYMAP, get_character def __lowercase ( _UpperCamelCase ) ->int: """simple docstring""" def decorator(_UpperCamelCase ): lowercase : str = getattr(_UpperCamelCase, '''handle_key''', [] ) handle += [key] setattr(_UpperCamelCase, '''handle_key''', _UpperCamelCase ) return func return decorator def __lowercase ( *_UpperCamelCase ) ->Any: """simple docstring""" def decorator(_UpperCamelCase ): lowercase : List[Any] = getattr(_UpperCamelCase, '''handle_key''', [] ) handle += keys setattr(_UpperCamelCase, '''handle_key''', _UpperCamelCase ) return func return decorator class __SCREAMING_SNAKE_CASE ( A__ ): def __new__( cls , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowercase : str = super().__new__(cls , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not hasattr(SCREAMING_SNAKE_CASE__ , '''key_handler''' ): setattr(SCREAMING_SNAKE_CASE__ , '''key_handler''' , {} ) setattr(SCREAMING_SNAKE_CASE__ , '''handle_input''' , KeyHandler.handle_input ) for value in attrs.values(): lowercase : Dict = getattr(SCREAMING_SNAKE_CASE__ , '''handle_key''' , [] ) for key in handled_keys: lowercase : List[Any] = value return new_cls @staticmethod def __lowerCamelCase ( cls ): lowercase : Dict = get_character() if char != KEYMAP["undefined"]: lowercase : Optional[int] = ord(SCREAMING_SNAKE_CASE__ ) lowercase : Optional[Any] = cls.key_handler.get(SCREAMING_SNAKE_CASE__ ) if handler: lowercase : Tuple = char return handler(cls ) else: return None def __lowercase ( cls ) ->Any: """simple docstring""" return KeyHandler(cls.__name__, cls.__bases__, cls.__dict__.copy() )
337
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import torch from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available @dataclass class __SCREAMING_SNAKE_CASE ( A__ ): A : Union[List[np.ndarray], torch.FloatTensor] try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_text_to_video_synth import TextToVideoSDPipeline from .pipeline_text_to_video_synth_imgaimg import VideoToVideoSDPipeline # noqa: F401 from .pipeline_text_to_video_zero import TextToVideoZeroPipeline
337
1
from __future__ import annotations def a_ ( lowerCAmelCase_ : list[float] ): __lowerCAmelCase = 0.00 __lowerCAmelCase = 0 for resistor in resistors: if resistor <= 0: __lowerCAmelCase = F"""Resistor at index {index} has a negative or zero value!""" raise ValueError(lowerCAmelCase_ ) first_sum += 1 / float(lowerCAmelCase_ ) index += 1 return 1 / first_sum def a_ ( lowerCAmelCase_ : list[float] ): __lowerCAmelCase = 0.00 __lowerCAmelCase = 0 for resistor in resistors: sum_r += resistor if resistor < 0: __lowerCAmelCase = F"""Resistor at index {index} has a negative value!""" raise ValueError(lowerCAmelCase_ ) index += 1 return sum_r if __name__ == "__main__": import doctest doctest.testmod()
356
import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class _UpperCAmelCase ( unittest.TestCase ): """simple docstring""" def lowercase ( self : Any ) -> Optional[int]: __lowerCAmelCase = 1_0 def lowercase ( self : int ) -> Union[str, Any]: __lowerCAmelCase = [1, 2, 3, 4] __lowerCAmelCase = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0] self.assertEqual(truncate_or_pad(lowerCAmelCase_ , self.block_size , 0 ) , lowerCAmelCase_ ) def lowercase ( self : Optional[Any] ) -> List[str]: __lowerCAmelCase = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] __lowerCAmelCase = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(lowerCAmelCase_ , self.block_size , 0 ) , lowerCAmelCase_ ) def lowercase ( self : Any ) -> Optional[Any]: __lowerCAmelCase = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0, 1_1, 1_2, 1_3] __lowerCAmelCase = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(lowerCAmelCase_ , self.block_size , 0 ) , lowerCAmelCase_ ) def lowercase ( self : List[str] ) -> Any: __lowerCAmelCase = 'It was the year of Our Lord one thousand seven hundred and\n seventy-five.\n\nSpiritual revelations were conceded to England at that\n favoured period, as at this.' __lowerCAmelCase , __lowerCAmelCase = process_story(lowerCAmelCase_ ) self.assertEqual(lowerCAmelCase_ , [] ) def lowercase ( self : Any ) -> str: __lowerCAmelCase = '' __lowerCAmelCase , __lowerCAmelCase = process_story(lowerCAmelCase_ ) self.assertEqual(lowerCAmelCase_ , [] ) self.assertEqual(lowerCAmelCase_ , [] ) def lowercase ( self : int ) -> int: __lowerCAmelCase = ( 'It was the year of Our Lord one thousand seven hundred and ' 'seventy-five\n\nSpiritual revelations were conceded to England ' 'at that favoured period, as at this.\n@highlight\n\nIt was the best of times' ) __lowerCAmelCase , __lowerCAmelCase = process_story(lowerCAmelCase_ ) __lowerCAmelCase = [ 'It was the year of Our Lord one thousand seven hundred and seventy-five.', 'Spiritual revelations were conceded to England at that favoured period, as at this.', ] self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) __lowerCAmelCase = ['It was the best of times.'] self.assertEqual(lowerCAmelCase_ , lowerCAmelCase_ ) def lowercase ( self : Dict ) -> Any: __lowerCAmelCase = torch.tensor([1, 2, 3, 4] ) __lowerCAmelCase = torch.tensor([1, 1, 1, 1] ) np.testing.assert_array_equal(build_mask(lowerCAmelCase_ , 0 ).numpy() , expected.numpy() ) def lowercase ( self : List[Any] ) -> Optional[int]: __lowerCAmelCase = torch.tensor([1, 2, 3, 4, 2_3, 2_3, 2_3] ) __lowerCAmelCase = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(lowerCAmelCase_ , 2_3 ).numpy() , expected.numpy() ) def lowercase ( self : str ) -> List[Any]: __lowerCAmelCase = torch.tensor([8, 2, 3, 4, 1, 1, 1] ) __lowerCAmelCase = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(lowerCAmelCase_ , 1 ).numpy() , expected.numpy() ) def lowercase ( self : Optional[Any] ) -> Optional[int]: __lowerCAmelCase = 1_0_1 __lowerCAmelCase = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 1_0_1, 5, 6], [1, 1_0_1, 3, 4, 1_0_1, 6]] ) __lowerCAmelCase = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] ) __lowerCAmelCase = compute_token_type_ids(lowerCAmelCase_ , lowerCAmelCase_ ) np.testing.assert_array_equal(lowerCAmelCase_ , lowerCAmelCase_ )
207
0
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING a_ = logging.get_logger(__name__) a_ = { """salesforce/blip2-opt-2.7b""": """https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json""", } class __lowerCAmelCase ( _a ): lowerCAmelCase__ = '''blip_2_vision_model''' def __init__( self , __UpperCAmelCase=1408 , __UpperCAmelCase=6144 , __UpperCAmelCase=39 , __UpperCAmelCase=16 , __UpperCAmelCase=224 , __UpperCAmelCase=14 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.00_001 , __UpperCAmelCase=0.0 , __UpperCAmelCase=1E-1_0 , __UpperCAmelCase=True , **__UpperCAmelCase , ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) __lowerCamelCase = hidden_size __lowerCamelCase = intermediate_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = patch_size __lowerCamelCase = image_size __lowerCamelCase = initializer_range __lowerCamelCase = attention_dropout __lowerCamelCase = layer_norm_eps __lowerCamelCase = hidden_act __lowerCamelCase = qkv_bias @classmethod def lowerCamelCase ( cls , __UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' cls._set_token_in_kwargs(__UpperCAmelCase ) __lowerCamelCase = cls.get_config_dict(__UpperCAmelCase , **__UpperCAmelCase ) # get the vision config dict if we are loading from Blip2Config if config_dict.get('''model_type''' ) == "blip-2": __lowerCamelCase = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(__UpperCAmelCase , **__UpperCAmelCase ) class __lowerCAmelCase ( _a ): lowerCAmelCase__ = '''blip_2_qformer''' def __init__( self , __UpperCAmelCase=30522 , __UpperCAmelCase=768 , __UpperCAmelCase=12 , __UpperCAmelCase=12 , __UpperCAmelCase=3072 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=512 , __UpperCAmelCase=0.02 , __UpperCAmelCase=1E-1_2 , __UpperCAmelCase=0 , __UpperCAmelCase="absolute" , __UpperCAmelCase=2 , __UpperCAmelCase=1408 , **__UpperCAmelCase , ): '''simple docstring''' super().__init__(pad_token_id=__UpperCAmelCase , **__UpperCAmelCase ) __lowerCamelCase = vocab_size __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = hidden_act __lowerCamelCase = intermediate_size __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_probs_dropout_prob __lowerCamelCase = max_position_embeddings __lowerCamelCase = initializer_range __lowerCamelCase = layer_norm_eps __lowerCamelCase = position_embedding_type __lowerCamelCase = cross_attention_frequency __lowerCamelCase = encoder_hidden_size @classmethod def lowerCamelCase ( cls , __UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' cls._set_token_in_kwargs(__UpperCAmelCase ) __lowerCamelCase = cls.get_config_dict(__UpperCAmelCase , **__UpperCAmelCase ) # get the qformer config dict if we are loading from Blip2Config if config_dict.get('''model_type''' ) == "blip-2": __lowerCamelCase = config_dict['''qformer_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(__UpperCAmelCase , **__UpperCAmelCase ) class __lowerCAmelCase ( _a ): lowerCAmelCase__ = '''blip-2''' lowerCAmelCase__ = True def __init__( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=32 , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) if vision_config is None: __lowerCamelCase = {} logger.info('''vision_config is None. initializing the Blip2VisionConfig with default values.''' ) if qformer_config is None: __lowerCamelCase = {} logger.info('''qformer_config is None. Initializing the Blip2QFormerConfig with default values.''' ) if text_config is None: __lowerCamelCase = {} logger.info('''text_config is None. Initializing the text config with default values (`OPTConfig`).''' ) __lowerCamelCase = BlipaVisionConfig(**__UpperCAmelCase ) __lowerCamelCase = BlipaQFormerConfig(**__UpperCAmelCase ) __lowerCamelCase = text_config['''model_type'''] if '''model_type''' in text_config else '''opt''' __lowerCamelCase = CONFIG_MAPPING[text_model_type](**__UpperCAmelCase ) __lowerCamelCase = self.text_config.tie_word_embeddings __lowerCamelCase = self.text_config.is_encoder_decoder __lowerCamelCase = num_query_tokens __lowerCamelCase = self.vision_config.hidden_size __lowerCamelCase = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES __lowerCamelCase = 1.0 __lowerCamelCase = 0.02 @classmethod def lowerCamelCase ( cls , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase , ): '''simple docstring''' return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **__UpperCAmelCase , ) def lowerCamelCase ( self ): '''simple docstring''' __lowerCamelCase = copy.deepcopy(self.__dict__ ) __lowerCamelCase = self.vision_config.to_dict() __lowerCamelCase = self.qformer_config.to_dict() __lowerCamelCase = self.text_config.to_dict() __lowerCamelCase = self.__class__.model_type return output
330
import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_decord, require_tf, require_torch, require_torch_or_tf, require_vision, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf @require_vision @require_decord class __lowerCAmelCase ( unittest.TestCase ): lowerCamelCase_ : Any = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> Dict: '''simple docstring''' snake_case_ : Any = hf_hub_download( repo_id='''nateraw/video-demo''' , filename='''archery.mp4''' , repo_type='''dataset''' ) snake_case_ : List[Any] = VideoClassificationPipeline(model=__magic_name__ , image_processor=__magic_name__ , top_k=2 ) snake_case_ : str = [ example_video_filepath, '''https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4''', ] return video_classifier, examples def lowerCamelCase (self , __magic_name__ , __magic_name__ ) -> Any: '''simple docstring''' for example in examples: snake_case_ : Union[str, Any] = video_classifier(__magic_name__ ) self.assertEqual( __magic_name__ , [ {'''score''': ANY(__magic_name__ ), '''label''': ANY(__magic_name__ )}, {'''score''': ANY(__magic_name__ ), '''label''': ANY(__magic_name__ )}, ] , ) @require_torch def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Any = '''hf-internal-testing/tiny-random-VideoMAEForVideoClassification''' snake_case_ : str = VideoMAEFeatureExtractor( size={'''shortest_edge''': 10} , crop_size={'''height''': 10, '''width''': 10} ) snake_case_ : int = pipeline( '''video-classification''' , model=__magic_name__ , feature_extractor=__magic_name__ , frame_sampling_rate=4 ) snake_case_ : List[str] = hf_hub_download(repo_id='''nateraw/video-demo''' , filename='''archery.mp4''' , repo_type='''dataset''' ) snake_case_ : Union[str, Any] = video_classifier(__magic_name__ , top_k=2 ) self.assertEqual( nested_simplify(__magic_name__ , decimals=4 ) , [{'''score''': 0.5_199, '''label''': '''LABEL_0'''}, {'''score''': 0.4_801, '''label''': '''LABEL_1'''}] , ) snake_case_ : int = video_classifier( [ video_file_path, video_file_path, ] , top_k=2 , ) self.assertEqual( nested_simplify(__magic_name__ , decimals=4 ) , [ [{'''score''': 0.5_199, '''label''': '''LABEL_0'''}, {'''score''': 0.4_801, '''label''': '''LABEL_1'''}], [{'''score''': 0.5_199, '''label''': '''LABEL_0'''}, {'''score''': 0.4_801, '''label''': '''LABEL_1'''}], ] , ) @require_tf def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' pass
279
0
import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class lowercase__ ( _UpperCAmelCase ): def __init__( self : Dict , *UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : int=None , **UpperCAmelCase_ : List[Any] ): super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ ) SCREAMING_SNAKE_CASE__ = eval_examples SCREAMING_SNAKE_CASE__ = post_process_function def A_ ( self : str , UpperCAmelCase_ : Optional[Dataset] = None , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : Optional[List[str]] = None , UpperCAmelCase_ : str = "eval" , **UpperCAmelCase_ : str , ): SCREAMING_SNAKE_CASE__ = gen_kwargs.copy() SCREAMING_SNAKE_CASE__ = ( gen_kwargs['max_length'] if gen_kwargs.get('max_length' ) is not None else self.args.generation_max_length ) SCREAMING_SNAKE_CASE__ = ( gen_kwargs['num_beams'] if gen_kwargs.get('num_beams' ) is not None else self.args.generation_num_beams ) SCREAMING_SNAKE_CASE__ = gen_kwargs SCREAMING_SNAKE_CASE__ = self.eval_dataset if eval_dataset is None else eval_dataset SCREAMING_SNAKE_CASE__ = self.get_eval_dataloader(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE__ = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE__ = self.compute_metrics SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = time.time() SCREAMING_SNAKE_CASE__ = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE__ = eval_loop( UpperCAmelCase_ , description='Evaluation' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=UpperCAmelCase_ , metric_key_prefix=UpperCAmelCase_ , ) finally: SCREAMING_SNAKE_CASE__ = compute_metrics SCREAMING_SNAKE_CASE__ = self.args.eval_batch_size * self.args.world_size if F'{metric_key_prefix}_jit_compilation_time' in output.metrics: start_time += output.metrics[F'{metric_key_prefix}_jit_compilation_time'] output.metrics.update( speed_metrics( UpperCAmelCase_ , UpperCAmelCase_ , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default SCREAMING_SNAKE_CASE__ = self.post_process_function(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE__ = self.compute_metrics(UpperCAmelCase_ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'{metric_key_prefix}_' ): SCREAMING_SNAKE_CASE__ = metrics.pop(UpperCAmelCase_ ) metrics.update(output.metrics ) else: SCREAMING_SNAKE_CASE__ = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(UpperCAmelCase_ ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) SCREAMING_SNAKE_CASE__ = self.callback_handler.on_evaluate(self.args , self.state , self.control , UpperCAmelCase_ ) return metrics def A_ ( self : Any , UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : str = "test" , **UpperCAmelCase_ : Optional[Any] ): SCREAMING_SNAKE_CASE__ = gen_kwargs.copy() SCREAMING_SNAKE_CASE__ = self.get_test_dataloader(UpperCAmelCase_ ) # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE__ = self.compute_metrics SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = time.time() SCREAMING_SNAKE_CASE__ = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE__ = eval_loop( UpperCAmelCase_ , description='Prediction' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=UpperCAmelCase_ , metric_key_prefix=UpperCAmelCase_ , ) finally: SCREAMING_SNAKE_CASE__ = compute_metrics SCREAMING_SNAKE_CASE__ = self.args.eval_batch_size * self.args.world_size if F'{metric_key_prefix}_jit_compilation_time' in output.metrics: start_time += output.metrics[F'{metric_key_prefix}_jit_compilation_time'] output.metrics.update( speed_metrics( UpperCAmelCase_ , UpperCAmelCase_ , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE__ = self.post_process_function(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , 'predict' ) SCREAMING_SNAKE_CASE__ = self.compute_metrics(UpperCAmelCase_ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'{metric_key_prefix}_' ): SCREAMING_SNAKE_CASE__ = metrics.pop(UpperCAmelCase_ ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=UpperCAmelCase_ )
169
import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor __snake_case = logging.get_logger(__name__) class lowercase__ ( _UpperCAmelCase ): def __init__( self : Dict , *UpperCAmelCase_ : int , **UpperCAmelCase_ : List[Any] ): warnings.warn( 'The class LayoutLMv2FeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use LayoutLMv2ImageProcessor instead.' , UpperCAmelCase_ , ) super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ )
169
1
"""simple docstring""" # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __snake_case = { '''configuration_efficientnet''': [ '''EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''EfficientNetConfig''', '''EfficientNetOnnxConfig''', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = ['''EfficientNetImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ '''EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST''', '''EfficientNetForImageClassification''', '''EfficientNetModel''', '''EfficientNetPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_efficientnet import ( EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientNetConfig, EfficientNetOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientnet import EfficientNetImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientnet import ( EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientNetForImageClassification, EfficientNetModel, EfficientNetPreTrainedModel, ) else: import sys __snake_case = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
320
"""simple docstring""" import argparse import json from typing import List from ltp import LTP from transformers.models.bert.tokenization_bert import BertTokenizer def A_ ( _lowerCAmelCase : Dict ): """simple docstring""" if ( (cp >= 0x4e00 and cp <= 0x9fff) or (cp >= 0x3400 and cp <= 0x4dbf) # or (cp >= 0x2_0000 and cp <= 0x2_a6df) # or (cp >= 0x2_a700 and cp <= 0x2_b73f) # or (cp >= 0x2_b740 and cp <= 0x2_b81f) # or (cp >= 0x2_b820 and cp <= 0x2_ceaf) # or (cp >= 0xf900 and cp <= 0xfaff) or (cp >= 0x2_f800 and cp <= 0x2_fa1f) # ): # return True return False def A_ ( _lowerCAmelCase : str ): """simple docstring""" for char in word: _a = ord(_lowerCAmelCase ) if not _is_chinese_char(_lowerCAmelCase ): return 0 return 1 def A_ ( _lowerCAmelCase : List[str] ): """simple docstring""" _a = set() for token in tokens: _a = len(_lowerCAmelCase ) > 1 and is_chinese(_lowerCAmelCase ) if chinese_word: word_set.add(_lowerCAmelCase ) _a = list(_lowerCAmelCase ) return word_list def A_ ( _lowerCAmelCase : List[str], _lowerCAmelCase : set() ): """simple docstring""" if not chinese_word_set: return bert_tokens _a = max([len(_lowerCAmelCase ) for w in chinese_word_set] ) _a = bert_tokens _a , _a = 0, len(_lowerCAmelCase ) while start < end: _a = True if is_chinese(bert_word[start] ): _a = min(end - start, _lowerCAmelCase ) for i in range(_lowerCAmelCase, 1, -1 ): _a = ''''''.join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1, start + i ): _a = '''##''' + bert_word[j] _a = start + i _a = False break if single_word: start += 1 return bert_word def A_ ( _lowerCAmelCase : List[str], _lowerCAmelCase : LTP, _lowerCAmelCase : BertTokenizer ): """simple docstring""" _a = [] for i in range(0, len(_lowerCAmelCase ), 1_00 ): _a = ltp_tokenizer.pipeline(lines[i : i + 1_00], tasks=['''cws'''] ).cws _a = [get_chinese_word(_lowerCAmelCase ) for r in res] ltp_res.extend(_lowerCAmelCase ) assert len(_lowerCAmelCase ) == len(_lowerCAmelCase ) _a = [] for i in range(0, len(_lowerCAmelCase ), 1_00 ): _a = bert_tokenizer(lines[i : i + 1_00], add_special_tokens=_lowerCAmelCase, truncation=_lowerCAmelCase, max_length=5_12 ) bert_res.extend(res['''input_ids'''] ) assert len(_lowerCAmelCase ) == len(_lowerCAmelCase ) _a = [] for input_ids, chinese_word in zip(_lowerCAmelCase, _lowerCAmelCase ): _a = [] for id in input_ids: _a = bert_tokenizer._convert_id_to_token(_lowerCAmelCase ) input_tokens.append(_lowerCAmelCase ) _a = add_sub_symbol(_lowerCAmelCase, _lowerCAmelCase ) _a = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(_lowerCAmelCase ): if token[:2] == "##": _a = token[2:] # save chinese tokens' pos if len(_lowerCAmelCase ) == 1 and _is_chinese_char(ord(_lowerCAmelCase ) ): ref_id.append(_lowerCAmelCase ) ref_ids.append(_lowerCAmelCase ) assert len(_lowerCAmelCase ) == len(_lowerCAmelCase ) return ref_ids def A_ ( _lowerCAmelCase : Any ): """simple docstring""" with open(args.file_name, '''r''', encoding='''utf-8''' ) as f: _a = f.readlines() _a = [line.strip() for line in data if len(_lowerCAmelCase ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' _a = LTP(args.ltp ) # faster in GPU device _a = BertTokenizer.from_pretrained(args.bert ) _a = prepare_ref(_lowerCAmelCase, _lowerCAmelCase, _lowerCAmelCase ) with open(args.save_path, '''w''', encoding='''utf-8''' ) as f: _a = [json.dumps(_lowerCAmelCase ) + '''\n''' for ref in ref_ids] f.writelines(_lowerCAmelCase ) if __name__ == "__main__": __snake_case = argparse.ArgumentParser(description='''prepare_chinese_ref''') parser.add_argument( '''--file_name''', required=False, type=str, default='''./resources/chinese-demo.txt''', help='''file need process, same as training data in lm''', ) parser.add_argument( '''--ltp''', required=False, type=str, default='''./resources/ltp''', help='''resources for LTP tokenizer, usually a path''', ) parser.add_argument( '''--bert''', required=False, type=str, default='''./resources/robert''', help='''resources for Bert tokenizer''', ) parser.add_argument( '''--save_path''', required=False, type=str, default='''./resources/ref.txt''', help='''path to save res''', ) __snake_case = parser.parse_args() main(args)
320
1
def lowerCAmelCase__ ( lowerCamelCase_ : int = 1000): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ : int = 1, 1 lowerCAmelCase__ : Any = 2 while True: lowerCAmelCase__ : Optional[Any] = 0 lowerCAmelCase__ : Any = fa + fa lowerCAmelCase__ , lowerCAmelCase__ : Optional[Any] = fa, f index += 1 for _ in str(lowerCamelCase_): i += 1 if i == n: break return index if __name__ == "__main__": print(solution(int(str(input()).strip())))
94
import unittest import numpy as np from transformers.testing_utils import is_flaky, require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DonutImageProcessor class lowerCamelCase__ ( unittest.TestCase): '''simple docstring''' def __init__(self ,__lowerCamelCase ,__lowerCamelCase=7 ,__lowerCamelCase=3 ,__lowerCamelCase=18 ,__lowerCamelCase=30 ,__lowerCamelCase=4_00 ,__lowerCamelCase=True ,__lowerCamelCase=None ,__lowerCamelCase=True ,__lowerCamelCase=False ,__lowerCamelCase=True ,__lowerCamelCase=True ,__lowerCamelCase=[0.5, 0.5, 0.5] ,__lowerCamelCase=[0.5, 0.5, 0.5] ,) -> Union[str, Any]: """simple docstring""" lowerCAmelCase__ : List[Any] = parent lowerCAmelCase__ : Optional[Any] = batch_size lowerCAmelCase__ : str = num_channels lowerCAmelCase__ : List[str] = image_size lowerCAmelCase__ : List[Any] = min_resolution lowerCAmelCase__ : Union[str, Any] = max_resolution lowerCAmelCase__ : Union[str, Any] = do_resize lowerCAmelCase__ : str = size if size is not None else {'''height''': 18, '''width''': 20} lowerCAmelCase__ : List[str] = do_thumbnail lowerCAmelCase__ : str = do_align_axis lowerCAmelCase__ : Optional[Any] = do_pad lowerCAmelCase__ : Tuple = do_normalize lowerCAmelCase__ : List[Any] = image_mean lowerCAmelCase__ : List[str] = image_std def lowerCAmelCase__ (self ) -> Optional[Any]: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_thumbnail": self.do_thumbnail, "do_align_long_axis": self.do_align_axis, "do_pad": self.do_pad, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class lowerCamelCase__ ( lowerCamelCase__ , unittest.TestCase): '''simple docstring''' snake_case_ =DonutImageProcessor if is_vision_available() else None def lowerCAmelCase__ (self ) -> List[Any]: """simple docstring""" lowerCAmelCase__ : Union[str, Any] = DonutImageProcessingTester(self ) @property def lowerCAmelCase__ (self ) -> Any: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase__ (self ) -> int: """simple docstring""" lowerCAmelCase__ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowerCamelCase ,'''do_resize''' ) ) self.assertTrue(hasattr(__lowerCamelCase ,'''size''' ) ) self.assertTrue(hasattr(__lowerCamelCase ,'''do_thumbnail''' ) ) self.assertTrue(hasattr(__lowerCamelCase ,'''do_align_long_axis''' ) ) self.assertTrue(hasattr(__lowerCamelCase ,'''do_pad''' ) ) self.assertTrue(hasattr(__lowerCamelCase ,'''do_normalize''' ) ) self.assertTrue(hasattr(__lowerCamelCase ,'''image_mean''' ) ) self.assertTrue(hasattr(__lowerCamelCase ,'''image_std''' ) ) def lowerCAmelCase__ (self ) -> Tuple: """simple docstring""" lowerCAmelCase__ : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size ,{'''height''': 18, '''width''': 20} ) lowerCAmelCase__ : int = self.image_processing_class.from_dict(self.image_processor_dict ,size=42 ) self.assertEqual(image_processor.size ,{'''height''': 42, '''width''': 42} ) # Previous config had dimensions in (width, height) order lowerCAmelCase__ : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ,size=(42, 84) ) self.assertEqual(image_processor.size ,{'''height''': 84, '''width''': 42} ) def lowerCAmelCase__ (self ) -> Optional[Any]: """simple docstring""" pass @is_flaky() def lowerCAmelCase__ (self ) -> Optional[Any]: """simple docstring""" lowerCAmelCase__ : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase__ : Dict = prepare_image_inputs(self.image_processor_tester ,equal_resolution=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase ,Image.Image ) # Test not batched input lowerCAmelCase__ : Optional[Any] = image_processing(image_inputs[0] ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) ,) # Test batched lowerCAmelCase__ : Optional[int] = image_processing(__lowerCamelCase ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) ,) @is_flaky() def lowerCAmelCase__ (self ) -> Any: """simple docstring""" lowerCAmelCase__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase__ : Any = prepare_image_inputs(self.image_processor_tester ,equal_resolution=__lowerCamelCase ,numpify=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase ,np.ndarray ) # Test not batched input lowerCAmelCase__ : Union[str, Any] = image_processing(image_inputs[0] ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) ,) # Test batched lowerCAmelCase__ : int = image_processing(__lowerCamelCase ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) ,) @is_flaky() def lowerCAmelCase__ (self ) -> Optional[Any]: """simple docstring""" lowerCAmelCase__ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase__ : int = prepare_image_inputs(self.image_processor_tester ,equal_resolution=__lowerCamelCase ,torchify=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase ,torch.Tensor ) # Test not batched input lowerCAmelCase__ : Any = image_processing(image_inputs[0] ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) ,) # Test batched lowerCAmelCase__ : Dict = image_processing(__lowerCamelCase ,return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) ,)
94
1