
"""simple docstring"""


import importlib.metadata
import warnings
from copy import deepcopy

from packaging import version

from ..utils import logging
from .import_utils import is_accelerate_available, is_bitsandbytes_available


if is_bitsandbytes_available():
						import bitsandbytes as bnb
						import torch
						import torch.nn as nn

						from ..pytorch_utils import ConvaD

if is_accelerate_available():
						from accelerate import init_empty_weights
						from accelerate.utils import find_tied_parameters

A_    							=					logging.get_logger(__name__)






def  lowercase						(	lowerCAmelCase__	,lowerCAmelCase__	,lowerCAmelCase__	,lowerCAmelCase__=None	,lowerCAmelCase__=None						):
			# Recurse if needed
			if "." in tensor_name:
						lowerCamelCase_					=  tensor_name.split('''.'''						)
						for split in splits[:-1]:
									lowerCamelCase_					=  getattr(lowerCAmelCase__	,lowerCAmelCase__						)
									if new_module is None:
												raise ValueError(f"{module} has no attribute {split}."						)
									lowerCamelCase_					=  new_module
						lowerCamelCase_					=  splits[-1]

			if tensor_name not in module._parameters and tensor_name not in module._buffers:
						raise ValueError(f"{module} does not have a parameter or a buffer named {tensor_name}."						)
			lowerCamelCase_					=  tensor_name in module._buffers
			lowerCamelCase_					=  getattr(lowerCAmelCase__	,lowerCAmelCase__						)

			if old_value.device == torch.device('''meta'''						) and device not in ["meta", torch.device('''meta'''						)] and value is None:
						raise ValueError(f"{tensor_name} is on the meta device, we need a `value` to put in on {device}."						)

			lowerCamelCase_					=  False
			lowerCamelCase_					=  False
			if is_buffer or not is_bitsandbytes_available():
						lowerCamelCase_					=  False
						lowerCamelCase_					=  False
			else:
						lowerCamelCase_					=  hasattr(bnb.nn	,'''Params4bit'''						) and isinstance(module._parameters[tensor_name]	,bnb.nn.Paramsabit						)
						lowerCamelCase_					=  isinstance(module._parameters[tensor_name]	,bnb.nn.IntaParams						)

			if is_abit or is_abit:
						lowerCamelCase_					=  module._parameters[tensor_name]
						if param.device.type != "cuda":
									if value is None:
												lowerCamelCase_					=  old_value.to(lowerCAmelCase__						)
									elif isinstance(lowerCAmelCase__	,torch.Tensor						):
												lowerCamelCase_					=  value.to('''cpu'''						)
												if value.dtype == torch.inta:
															lowerCamelCase_					=  version.parse(importlib.metadata.version('''bitsandbytes'''						)						) > version.parse(
															    '''0.37.2'''						)
															if not is_abit_serializable:
																		raise ValueError(
																		    '''Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. '''
																		    '''Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.'''						)
									else:
												lowerCamelCase_					=  torch.tensor(lowerCAmelCase__	,device='''cpu'''						)

									# Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization.
									# Since weights are saved in the correct "orientation", we skip transposing when loading.
									if issubclass(module.source_cls	,lowerCAmelCase__						) and fpaa_statistics is None:
												lowerCamelCase_					=  new_value.T

									lowerCamelCase_					=  old_value.__dict__
									if is_abit:
												lowerCamelCase_					=  bnb.nn.IntaParams(lowerCAmelCase__	,requires_grad=lowerCAmelCase__	,**lowerCAmelCase__						).to(lowerCAmelCase__						)
									elif is_abit:
												lowerCamelCase_					=  bnb.nn.Paramsabit(lowerCAmelCase__	,requires_grad=lowerCAmelCase__	,**lowerCAmelCase__						).to(lowerCAmelCase__						)

									lowerCamelCase_					=  new_value
									if fpaa_statistics is not None:
												setattr(module.weight	,'''SCB'''	,fpaa_statistics.to(lowerCAmelCase__						)						)

			else:
						if value is None:
									lowerCamelCase_					=  old_value.to(lowerCAmelCase__						)
						elif isinstance(lowerCAmelCase__	,torch.Tensor						):
									lowerCamelCase_					=  value.to(lowerCAmelCase__						)
						else:
									lowerCamelCase_					=  torch.tensor(lowerCAmelCase__	,device=lowerCAmelCase__						)

						if is_buffer:
									lowerCamelCase_					=  new_value
						else:
									lowerCamelCase_					=  nn.Parameter(lowerCAmelCase__	,requires_grad=old_value.requires_grad						)
									lowerCamelCase_					=  new_value






def  lowercase						(	lowerCAmelCase__	,lowerCAmelCase__=None	,lowerCAmelCase__=None	,lowerCAmelCase__=None	,lowerCAmelCase__=False						):
			for name, module in model.named_children():
						if current_key_name is None:
									lowerCamelCase_					=  []
						current_key_name.append(lowerCAmelCase__						)

						if (isinstance(lowerCAmelCase__	,nn.Linear						) or isinstance(lowerCAmelCase__	,lowerCAmelCase__						)) and name not in modules_to_not_convert:
									# Check if the current key is not in the `modules_to_not_convert`
									if not any(key in '''.'''.join(lowerCAmelCase__						) for key in modules_to_not_convert						):
												with init_empty_weights():
															if isinstance(lowerCAmelCase__	,lowerCAmelCase__						):
																		lowerCamelCase_		, lowerCamelCase_					=  module.weight.shape
															else:
																		lowerCamelCase_					=  module.in_features
																		lowerCamelCase_					=  module.out_features

															if quantization_config.quantization_method() == "llm_int8":
																		lowerCamelCase_					=  bnb.nn.LinearabitLt(
																		    lowerCAmelCase__	,lowerCAmelCase__	,module.bias is not None	,has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight	,threshold=quantization_config.llm_inta_threshold	,)
																		lowerCamelCase_					=  True
															else:
																		if (
																		    quantization_config.llm_inta_skip_modules is not None
																		    and name in quantization_config.llm_inta_skip_modules
																		):
																					pass
																		else:
																					lowerCamelCase_					=  bnb.nn.Linearabit(
																					    lowerCAmelCase__	,lowerCAmelCase__	,module.bias is not None	,quantization_config.bnb_abit_compute_dtype	,compress_statistics=quantization_config.bnb_abit_use_double_quant	,quant_type=quantization_config.bnb_abit_quant_type	,)
																					lowerCamelCase_					=  True
                    # Store the module class in case we need to transpose the weight later
															lowerCamelCase_					=  type(lowerCAmelCase__						)
															# Force requires grad to False to avoid unexpected errors
															model._modules[name].requires_grad_(lowerCAmelCase__						)
						if len(list(module.children()						)						) > 0:
									lowerCamelCase_		, lowerCamelCase_					=  _replace_with_bnb_linear(
									    lowerCAmelCase__	,lowerCAmelCase__	,lowerCAmelCase__	,lowerCAmelCase__	,has_been_replaced=lowerCAmelCase__	,)
						# Remove the last key for recursion
						current_key_name.pop(-1						)
			return model, has_been_replaced






def  lowercase						(	lowerCAmelCase__	,lowerCAmelCase__=None	,lowerCAmelCase__=None	,lowerCAmelCase__=None						):
			lowerCamelCase_					=  ['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert
			lowerCamelCase_		, lowerCamelCase_					=  _replace_with_bnb_linear(
			    lowerCAmelCase__	,lowerCAmelCase__	,lowerCAmelCase__	,lowerCAmelCase__						)

			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.'''
						    ''' Please double check your model architecture, or submit an issue on github if you think this is'''
						    ''' a bug.'''						)

			return model






def  lowercase						(	*lowerCAmelCase__	,**lowerCAmelCase__						):
			warnings.warn(
			    '''`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead'''	,lowerCAmelCase__	,)
			return replace_with_bnb_linear(*lowerCAmelCase__	,**lowerCAmelCase__						)






def  lowercase						(	*lowerCAmelCase__	,**lowerCAmelCase__						):
			warnings.warn(
			    '''`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead'''	,lowerCAmelCase__	,)
			return set_module_quantized_tensor_to_device(*lowerCAmelCase__	,**lowerCAmelCase__						)






def  lowercase						(	lowerCAmelCase__						):
			lowerCamelCase_					=  deepcopy(lowerCAmelCase__						)  # this has 0 cost since it is done inside `init_empty_weights` context manager`
			tied_model.tie_weights()

			lowerCamelCase_					=  find_tied_parameters(lowerCAmelCase__						)
			# For compatibility with Accelerate < 0.18
			if isinstance(lowerCAmelCase__	,lowerCAmelCase__						):
						lowerCamelCase_					=  sum(list(tied_params.values()						)	,[]						) + list(tied_params.keys()						)
			else:
						lowerCamelCase_					=  sum(lowerCAmelCase__	,[]						)
			lowerCamelCase_					=  len(lowerCAmelCase__						) > 0

			# Check if it is a base model
			lowerCamelCase_					=  not hasattr(lowerCAmelCase__	,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
			lowerCamelCase_					=  list(model.named_children()						)
			lowerCamelCase_					=  [list_modules[-1][0]]

			# add last module together with tied weights
			lowerCamelCase_					=  set(lowerCAmelCase__						) - set(lowerCAmelCase__						)
			lowerCamelCase_					=  list(set(lowerCAmelCase__						)						) + list(lowerCAmelCase__						)

			# remove ".weight" from the keys
			lowerCamelCase_					=  ['''.weight''', '''.bias''']
			lowerCamelCase_					=  []
			for name in list_untouched:
						for name_to_remove in names_to_remove:
									if name_to_remove in name:
												lowerCamelCase_					=  name.replace(lowerCAmelCase__	,''''''						)
						filtered_module_names.append(lowerCAmelCase__						)

			return filtered_module_names





"""simple docstring"""


import json
import os
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import BertTokenizer, BertTokenizerFast
from transformers.models.bert.tokenization_bert 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 AlignProcessor, EfficientNetImageProcessor




@require_vision
class  __lowerCamelCase  ( unittest.TestCase			):




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  tempfile.mkdtemp()

							lowerCamelCase_					=  [
							    '''[UNK]''',
							    '''[CLS]''',
							    '''[SEP]''',
							    '''[PAD]''',
							    '''[MASK]''',
							    '''want''',
							    '''##want''',
							    '''##ed''',
							    '''wa''',
							    '''un''',
							    '''runn''',
							    '''##ing''',
							    ''',''',
							    '''low''',
							    '''lowest''',
							]
							lowerCamelCase_					=  os.path.join(self.tmpdirname							,						VOCAB_FILES_NAMES['''vocab_file''']   )
							with open(self.vocab_file							,						'''w'''							,						encoding='''utf-8'''   ) as vocab_writer:
										vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens]   )   )

							lowerCamelCase_					=  {
							    '''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_					=  os.path.join(self.tmpdirname							,						UpperCAmelCase   )
							with open(self.image_processor_file							,						'''w'''							,						encoding='''utf-8'''   ) as fp:
										json.dump(UpperCAmelCase							,						UpperCAmelCase   )




				def        UpperCAmelCase__						(				self							,						**UpperCAmelCase   ):
							return BertTokenizer.from_pretrained(self.tmpdirname							,						**UpperCAmelCase   )




				def        UpperCAmelCase__						(				self							,						**UpperCAmelCase   ):
							return BertTokenizerFast.from_pretrained(self.tmpdirname							,						**UpperCAmelCase   )




				def        UpperCAmelCase__						(				self							,						**UpperCAmelCase   ):
							return EfficientNetImageProcessor.from_pretrained(self.tmpdirname							,						**UpperCAmelCase   )




				def        UpperCAmelCase__						(				self   ):
							shutil.rmtree(self.tmpdirname   )




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  [np.random.randint(255							,						size=(3, 30, 400)							,						dtype=np.uinta   )]
							lowerCamelCase_					=  [Image.fromarray(np.moveaxis(UpperCAmelCase							,						0							,						-1   )   ) for x in image_inputs]
							return image_inputs




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.get_tokenizer()
							lowerCamelCase_					=  self.get_rust_tokenizer()
							lowerCamelCase_					=  self.get_image_processor()

							lowerCamelCase_					=  AlignProcessor(tokenizer=UpperCAmelCase							,						image_processor=UpperCAmelCase   )
							processor_slow.save_pretrained(self.tmpdirname   )
							lowerCamelCase_					=  AlignProcessor.from_pretrained(self.tmpdirname							,						use_fast=UpperCAmelCase   )

							lowerCamelCase_					=  AlignProcessor(tokenizer=UpperCAmelCase							,						image_processor=UpperCAmelCase   )
							processor_fast.save_pretrained(self.tmpdirname   )
							lowerCamelCase_					=  AlignProcessor.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        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  AlignProcessor(tokenizer=self.get_tokenizer()							,						image_processor=self.get_image_processor()   )
							processor.save_pretrained(self.tmpdirname   )

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

							lowerCamelCase_					=  AlignProcessor.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        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.get_image_processor()
							lowerCamelCase_					=  self.get_tokenizer()

							lowerCamelCase_					=  AlignProcessor(tokenizer=UpperCAmelCase							,						image_processor=UpperCAmelCase   )

							lowerCamelCase_					=  self.prepare_image_inputs()

							lowerCamelCase_					=  image_processor(UpperCAmelCase							,						return_tensors='''np'''   )
							lowerCamelCase_					=  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        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.get_image_processor()
							lowerCamelCase_					=  self.get_tokenizer()

							lowerCamelCase_					=  AlignProcessor(tokenizer=UpperCAmelCase							,						image_processor=UpperCAmelCase   )

							lowerCamelCase_					=  '''lower newer'''

							lowerCamelCase_					=  processor(text=UpperCAmelCase   )

							lowerCamelCase_					=  tokenizer(UpperCAmelCase							,						padding='''max_length'''							,						max_length=64   )

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




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.get_image_processor()
							lowerCamelCase_					=  self.get_tokenizer()

							lowerCamelCase_					=  AlignProcessor(tokenizer=UpperCAmelCase							,						image_processor=UpperCAmelCase   )

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

							lowerCamelCase_					=  processor(text=UpperCAmelCase							,						images=UpperCAmelCase   )

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

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




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.get_image_processor()
							lowerCamelCase_					=  self.get_tokenizer()

							lowerCamelCase_					=  AlignProcessor(tokenizer=UpperCAmelCase							,						image_processor=UpperCAmelCase   )

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

							lowerCamelCase_					=  processor.batch_decode(UpperCAmelCase   )
							lowerCamelCase_					=  tokenizer.batch_decode(UpperCAmelCase   )

							self.assertListEqual(UpperCAmelCase							,						UpperCAmelCase   )





				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.get_image_processor()
							lowerCamelCase_					=  self.get_tokenizer()

							lowerCamelCase_					=  AlignProcessor(tokenizer=UpperCAmelCase							,						image_processor=UpperCAmelCase   )

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

							lowerCamelCase_					=  processor(text=UpperCAmelCase							,						images=UpperCAmelCase   )

							self.assertListEqual(list(inputs.keys()   )							,						processor.model_input_names   )



