



"""simple docstring"""







from collections import OrderedDict
from typing import TYPE_CHECKING, Any, List, Mapping, Optional

from packaging import version


if TYPE_CHECKING:
							from ... import PreTrainedTokenizer, TensorType

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import is_torch_available, logging


A    =			logging.get_logger(__name__)

A    =			{
    'bigscience/bloom': 'https://huggingface.co/bigscience/bloom/resolve/main/config.json',
    'bigscience/bloom-560m': 'https://huggingface.co/bigscience/bloom-560m/blob/main/config.json',
    'bigscience/bloom-1b1': 'https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json',
    'bigscience/bloom-1b7': 'https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json',
    'bigscience/bloom-3b': 'https://huggingface.co/bigscience/bloom-3b/blob/main/config.json',
    'bigscience/bloom-7b1': 'https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json',
}






class      UpperCAmelCase__		(      UpperCamelCase     ):
		lowerCAmelCase_       :	List[str] 							=     """bloom"""
		lowerCAmelCase_       :	Any 							=     ["""past_key_values"""]
		lowerCAmelCase_       :	Dict 							=     {
		    """num_hidden_layers""": """n_layer""",
		    """num_attention_heads""": """n_head""",
		}



		def __init__( self  :    str      ,							snake_case  :    Optional[Any]=250_880      ,							snake_case  :    str=64      ,							snake_case  :    Any=2      ,							snake_case  :    Tuple=8      ,							snake_case  :    Optional[int]=1E-5      ,							snake_case  :    Union[str, Any]=0.02      ,							snake_case  :    List[str]=True      ,							snake_case  :    List[str]=1      ,							snake_case  :    Any=2      ,							snake_case  :    Optional[Any]=False      ,							snake_case  :    Union[str, Any]=0.0      ,							snake_case  :    List[Any]=0.0      ,							snake_case  :    List[Any]=1      ,							snake_case  :    str=False      ,							**snake_case  :    Union[str, Any]      ,							)			->						str:






									'''simple docstring'''

									A         =					vocab_size
									# Backward compatibility with n_embed kwarg
									A         =					kwargs.pop('n_embed'      ,							snake_case				)
									A         =					hidden_size if n_embed is None else n_embed
									A         =					n_layer
									A         =					n_head
									A         =					layer_norm_epsilon
									A         =					initializer_range
									A         =					use_cache
									A         =					pretraining_tp
									A         =					apply_residual_connection_post_layernorm
									A         =					hidden_dropout
									A         =					attention_dropout

									A         =					bos_token_id
									A         =					eos_token_id
									A         =					slow_but_exact

									super().__init__(bos_token_id=snake_case      ,							eos_token_id=snake_case      ,							**snake_case				)






class      UpperCAmelCase__		(      UpperCamelCase     ):
		lowerCAmelCase_       :	List[Any] 							=     version.parse("""1.12"""     )



		def __init__( self  :    Any      ,							snake_case  :    PretrainedConfig      ,							snake_case  :    str = "default"      ,							snake_case  :    List[PatchingSpec] = None      ,							snake_case  :    bool = False      ,							)			->						Any:






									'''simple docstring'''

									super().__init__(snake_case      ,							task=snake_case      ,							patching_specs=snake_case      ,							use_past=snake_case				)
									if not getattr(self._config      ,							'pad_token_id'      ,							snake_case				):
																# TODO: how to do that better?
																A         =					0



		@property
		def 					A_		( self  :    Union[str, Any]				)			->						Mapping[str, Mapping[int, str]]:






									'''simple docstring'''

									A         =					OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}}				)
									if self.use_past:
																# BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344
																self.fill_with_past_key_values_(snake_case      ,							direction='inputs'      ,							inverted_values_shape=snake_case				)
																A         =					{0: 'batch', 1: 'past_sequence + sequence'}
									else:
																A         =					{0: 'batch', 1: 'sequence'}

									return common_inputs



		@property
		def 					A_		( self  :    str				)			->						int:






									'''simple docstring'''

									return self._config.n_layer



		@property
		def 					A_		( self  :    Dict				)			->						int:






									'''simple docstring'''

									return self._config.n_head



		@property
		def 					A_		( self  :    str				)			->						float:






									'''simple docstring'''

									return 1E-3



		def 					A_		( self  :    List[Any]      ,							snake_case  :    "PreTrainedTokenizer"      ,							snake_case  :    int = -1      ,							snake_case  :    int = -1      ,							snake_case  :    bool = False      ,							snake_case  :    Optional["TensorType"] = None      ,							)			->						Mapping[str, Any]:






									'''simple docstring'''

									A         =					super(snake_case      ,							self				).generate_dummy_inputs(
									    snake_case      ,							batch_size=snake_case      ,							seq_length=snake_case      ,							is_pair=snake_case      ,							framework=snake_case				)

									# We need to order the input in the way they appears in the forward()
									A         =					OrderedDict({'input_ids': common_inputs['input_ids']}				)

									# Need to add the past_keys
									if self.use_past:
																if not is_torch_available():
																							raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'				)
																else:
																							import torch

																							A      ,  A         =					common_inputs['input_ids'].shape
																							# Not using the same length for past_key_values
																							A         =					seqlen + 2
																							A         =					self._config.hidden_size // self.num_attention_heads
																							A         =					(
																							    batch * self.num_attention_heads,
																							    head_dim,
																							    past_key_values_length,
																							)
																							A         =					(
																							    batch * self.num_attention_heads,
																							    past_key_values_length,
																							    head_dim,
																							)
																							A         =					[
																							    (torch.zeros(snake_case				), torch.zeros(snake_case				)) for _ in range(self.num_layers				)
																							]

									A         =					common_inputs['attention_mask']
									if self.use_past:
																A         =					ordered_inputs['attention_mask'].dtype
																A         =					torch.cat(
																    [ordered_inputs['attention_mask'], torch.ones(snake_case      ,							snake_case      ,							dtype=snake_case				)]      ,							dim=1				)

									return ordered_inputs



		@property
		def 					A_		( self  :    List[Any]				)			->						int:






									'''simple docstring'''

									return 13








"""simple docstring"""







import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers.testing_utils import require_vision
from transformers.utils import is_vision_available


if is_vision_available():
							from PIL import Image

							from transformers import (
							    AutoProcessor,
							    BertTokenizerFast,
							    BlipImageProcessor,
							    GPTaTokenizer,
							    InstructBlipProcessor,
							    PreTrainedTokenizerFast,
							)






@require_vision
class      UpperCAmelCase__		(      unittest.TestCase     ):



		def 					A_		( self  :    Dict				)			->						Dict:






									'''simple docstring'''

									A         =					tempfile.mkdtemp()

									A         =					BlipImageProcessor()
									A         =					GPTaTokenizer.from_pretrained('hf-internal-testing/tiny-random-GPT2Model'				)
									A         =					BertTokenizerFast.from_pretrained('hf-internal-testing/tiny-random-bert'				)

									A         =					InstructBlipProcessor(snake_case      ,							snake_case      ,							snake_case				)

									processor.save_pretrained(self.tmpdirname				)



		def 					A_		( self  :    List[str]      ,							**snake_case  :    str				)			->						Dict:






									'''simple docstring'''

									return AutoProcessor.from_pretrained(self.tmpdirname      ,							**snake_case				).tokenizer



		def 					A_		( self  :    int      ,							**snake_case  :    Optional[Any]				)			->						Any:






									'''simple docstring'''

									return AutoProcessor.from_pretrained(self.tmpdirname      ,							**snake_case				).image_processor



		def 					A_		( self  :    Any      ,							**snake_case  :    Union[str, Any]				)			->						Any:






									'''simple docstring'''

									return AutoProcessor.from_pretrained(self.tmpdirname      ,							**snake_case				).qformer_tokenizer



		def 					A_		( self  :    int				)			->						Union[str, Any]:






									'''simple docstring'''

									shutil.rmtree(self.tmpdirname				)



		def 					A_		( self  :    List[Any]				)			->						Tuple:






									'''simple docstring'''

									A         =					[np.random.randint(255      ,							size=(3, 30, 400)      ,							dtype=np.uinta				)]

									A         =					[Image.fromarray(np.moveaxis(snake_case      ,							0      ,							-1				)				) for x in image_inputs]

									return image_inputs



		def 					A_		( self  :    List[Any]				)			->						Optional[int]:






									'''simple docstring'''

									A         =					InstructBlipProcessor(
									    tokenizer=self.get_tokenizer()      ,							image_processor=self.get_image_processor()      ,							qformer_tokenizer=self.get_qformer_tokenizer()      ,							)
									processor.save_pretrained(self.tmpdirname				)

									A         =					self.get_tokenizer(bos_token='(BOS)'      ,							eos_token='(EOS)'				)
									A         =					self.get_image_processor(do_normalize=snake_case      ,							padding_value=1.0				)

									A         =					InstructBlipProcessor.from_pretrained(
									    self.tmpdirname      ,							bos_token='(BOS)'      ,							eos_token='(EOS)'      ,							do_normalize=snake_case      ,							padding_value=1.0				)

									self.assertEqual(processor.tokenizer.get_vocab()      ,							tokenizer_add_kwargs.get_vocab()				)
									self.assertIsInstance(processor.tokenizer      ,							snake_case				)

									self.assertEqual(processor.image_processor.to_json_string()      ,							image_processor_add_kwargs.to_json_string()				)
									self.assertIsInstance(processor.image_processor      ,							snake_case				)
									self.assertIsInstance(processor.qformer_tokenizer      ,							snake_case				)



		def 					A_		( self  :    Optional[Any]				)			->						Dict:






									'''simple docstring'''

									A         =					self.get_image_processor()
									A         =					self.get_tokenizer()
									A         =					self.get_qformer_tokenizer()

									A         =					InstructBlipProcessor(
									    tokenizer=snake_case      ,							image_processor=snake_case      ,							qformer_tokenizer=snake_case				)

									A         =					self.prepare_image_inputs()

									A         =					image_processor(snake_case      ,							return_tensors='np'				)
									A         =					processor(images=snake_case      ,							return_tensors='np'				)

									for key in input_feat_extract.keys():
																self.assertAlmostEqual(input_feat_extract[key].sum()      ,							input_processor[key].sum()      ,							delta=1E-2				)



		def 					A_		( self  :    Tuple				)			->						List[str]:






									'''simple docstring'''

									A         =					self.get_image_processor()
									A         =					self.get_tokenizer()
									A         =					self.get_qformer_tokenizer()

									A         =					InstructBlipProcessor(
									    tokenizer=snake_case      ,							image_processor=snake_case      ,							qformer_tokenizer=snake_case				)

									A         =					'lower newer'

									A         =					processor(text=snake_case				)

									A         =					tokenizer(snake_case      ,							return_token_type_ids=snake_case				)
									A         =					qformer_tokenizer(snake_case      ,							return_token_type_ids=snake_case				)

									for key in encoded_tokens.keys():
																self.assertListEqual(encoded_tokens[key]      ,							encoded_processor[key]				)

									for key in encoded_tokens_qformer.keys():
																self.assertListEqual(encoded_tokens_qformer[key]      ,							encoded_processor['qformer_' + key]				)



		def 					A_		( self  :    List[Any]				)			->						Optional[int]:






									'''simple docstring'''

									A         =					self.get_image_processor()
									A         =					self.get_tokenizer()
									A         =					self.get_qformer_tokenizer()

									A         =					InstructBlipProcessor(
									    tokenizer=snake_case      ,							image_processor=snake_case      ,							qformer_tokenizer=snake_case				)

									A         =					'lower newer'
									A         =					self.prepare_image_inputs()

									A         =					processor(text=snake_case      ,							images=snake_case				)

									self.assertListEqual(
									    list(inputs.keys()				)      ,							['input_ids', 'attention_mask', 'qformer_input_ids', 'qformer_attention_mask', 'pixel_values']      ,							)

									# test if it raises when no input is passed
									with pytest.raises(snake_case				):
																processor()



		def 					A_		( self  :    Optional[Any]				)			->						List[str]:






									'''simple docstring'''

									A         =					self.get_image_processor()
									A         =					self.get_tokenizer()
									A         =					self.get_qformer_tokenizer()

									A         =					InstructBlipProcessor(
									    tokenizer=snake_case      ,							image_processor=snake_case      ,							qformer_tokenizer=snake_case				)

									A         =					[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

									A         =					processor.batch_decode(snake_case				)
									A         =					tokenizer.batch_decode(snake_case				)

									self.assertListEqual(snake_case      ,							snake_case				)



		def 					A_		( self  :    Tuple				)			->						List[Any]:






									'''simple docstring'''

									A         =					self.get_image_processor()
									A         =					self.get_tokenizer()
									A         =					self.get_qformer_tokenizer()

									A         =					InstructBlipProcessor(
									    tokenizer=snake_case      ,							image_processor=snake_case      ,							qformer_tokenizer=snake_case				)

									A         =					'lower newer'
									A         =					self.prepare_image_inputs()

									A         =					processor(text=snake_case      ,							images=snake_case				)

									self.assertListEqual(
									    list(inputs.keys()				)      ,							['input_ids', 'attention_mask', 'qformer_input_ids', 'qformer_attention_mask', 'pixel_values']      ,							)



