






"""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


__a       :	Optional[Any]             = logging.getLogger(__name__)





def        SCREAMING_SNAKE_CASE       (      lowerCamelCase_ ,     lowerCamelCase_ ,     lowerCamelCase_ = None ,     lowerCamelCase_ = None ,     lowerCamelCase_ = None ,     lowerCamelCase_ = None ,     lowerCamelCase_ = None ,     lowerCamelCase_ = False ,     ):
					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(lowerCamelCase_ ,     lowerCamelCase_) 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(lowerCamelCase_)

					# add cpu modules to skip modules only for 4-bit modules
					if load_in_abit:
										bnb_quantization_config.skip_modules.extend(lowerCamelCase_)
					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(lowerCamelCase_)

					# compatibility with peft
					a__          =  load_in_abit
					a__          =  load_in_abit

					a__          =  get_parameter_device(lowerCamelCase_)
					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(lowerCamelCase_ ,     lowerCamelCase_ ,     modules_to_not_convert=lowerCamelCase_)
										# 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(lowerCamelCase_ ,     lowerCamelCase_ ,     lowerCamelCase_)
																									if param is not None:
																														param.to(torch.floataa)
															elif torch.is_floating_point(lowerCamelCase_):
																				param.to(lowerCamelCase_)
										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(
															    lowerCamelCase_ ,     lowerCamelCase_ ,     modules_to_not_convert=lowerCamelCase_)

										a__          =  get_quantized_model_device_map(
										    lowerCamelCase_ ,     lowerCamelCase_ ,     lowerCamelCase_ ,     max_memory=lowerCamelCase_ ,     no_split_module_classes=lowerCamelCase_ ,     )
										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(
										    lowerCamelCase_ ,     lowerCamelCase_ ,     lowerCamelCase_ ,     dtype=bnb_quantization_config.torch_dtype ,     offload_folder=lowerCamelCase_ ,     offload_state_dict=lowerCamelCase_ ,     keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules ,     offload_abit_bnb=load_in_abit and offload ,     )
										return dispatch_model(lowerCamelCase_ ,     device_map=lowerCamelCase_ ,     offload_dir=lowerCamelCase_)





def        SCREAMING_SNAKE_CASE       (      lowerCamelCase_ ,     lowerCamelCase_ ,     lowerCamelCase_=None ,     lowerCamelCase_=None ,     lowerCamelCase_=None):
					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(lowerCamelCase_ ,     lowerCamelCase_):
										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(
															    lowerCamelCase_ ,     low_zero=(device_map == '''balanced_low_0''') ,     max_memory=lowerCamelCase_ ,     **lowerCamelCase_ ,     )

										a__          =  max_memory
										a__          =  infer_auto_device_map(lowerCamelCase_ ,     **lowerCamelCase_)

					if isinstance(lowerCamelCase_ ,     lowerCamelCase_):
										# 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(
																									    '''
                        Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit
                        the quantized model. If you want to dispatch the model on the CPU or the disk while keeping
                        these modules in `torch_dtype`, you need to pass a custom `device_map` to
                        `load_and_quantize_model`. Check
                        https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk
                        for more details.
                        ''')
																				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       (      lowerCamelCase_ ,     lowerCamelCase_ ,     lowerCamelCase_=None ,     lowerCamelCase_=None):

					if modules_to_not_convert is None:
										a__          =  []

					a__       ,a__          =  _replace_with_bnb_layers(
					    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.'''
										    ''' 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       (      lowerCamelCase_ ,     lowerCamelCase_ ,     lowerCamelCase_=None ,     lowerCamelCase_=None ,     ):
					a__          =  False
					for name, module in model.named_children():
										if current_key_name is None:
															a__          =  []
										current_key_name.append(lowerCamelCase_)
										if isinstance(lowerCamelCase_ ,     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(lowerCamelCase_)
															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=lowerCamelCase_ ,     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_(lowerCamelCase_)
																				setattr(lowerCamelCase_ ,     lowerCamelCase_ ,     lowerCamelCase_)
																				a__          =  True
										if len(list(module.children())) > 0:
															a__       ,a__          =  _replace_with_bnb_layers(
															    lowerCamelCase_ ,     lowerCamelCase_ ,     lowerCamelCase_ ,     lowerCamelCase_)
															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       (      lowerCamelCase_):
					# Create a copy of the model
					with init_empty_weights():
										a__          =  deepcopy(lowerCamelCase_)  # this has 0 cost since it is done inside `init_empty_weights` context manager`

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

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

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

					# 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(lowerCamelCase_ ,     '''''')
										filtered_module_names.append(lowerCamelCase_)

					return filtered_module_names





def        SCREAMING_SNAKE_CASE       (      lowerCamelCase_):
					for m in model.modules():
										if isinstance(lowerCamelCase_ ,     bnb.nn.Linearabit):
															return True
					return False





def        SCREAMING_SNAKE_CASE       (      lowerCamelCase_):
					return next(parameter.parameters()).device





def        SCREAMING_SNAKE_CASE       (      lowerCamelCase_ ,     lowerCamelCase_ ,     lowerCamelCase_ ,     lowerCamelCase_ ,     lowerCamelCase_ ,     lowerCamelCase_ ,     lowerCamelCase_):
					# 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(lowerCamelCase_ ,     lowerCamelCase_ ,     0 ,     dtype=lowerCamelCase_ ,     value=lowerCamelCase_)
										a__          =  param_name
										a__          =  model
										if "." in tensor_name:
															a__          =  tensor_name.split('''.''')
															for split in splits[:-1]:
																				a__          =  getattr(lowerCamelCase_ ,     lowerCamelCase_)
																				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] ,     lowerCamelCase_ ,     lowerCamelCase_ ,     index=lowerCamelCase_)
										if hasattr(module._parameters[tensor_name] ,     '''SCB'''):
															offload_weight(
															    module._parameters[tensor_name].SCB ,     param_name.replace('''weight''' ,     '''SCB''') ,     lowerCamelCase_ ,     index=lowerCamelCase_ ,     )
					else:
										offload_weight(lowerCamelCase_ ,     lowerCamelCase_ ,     lowerCamelCase_ ,     index=lowerCamelCase_)
										offload_weight(lowerCamelCase_ ,     param_name.replace('''weight''' ,     '''SCB''') ,     lowerCamelCase_ ,     index=lowerCamelCase_)

					set_module_tensor_to_device(lowerCamelCase_ ,     lowerCamelCase_ ,     '''meta''' ,     dtype=lowerCamelCase_ ,     value=torch.empty(*param.size()))










"""simple docstring"""







import json
import logging
import os
import sys
from pathlib import Path

import finetune_rag

from transformers.file_utils import is_apex_available
from transformers.testing_utils import (
    TestCasePlus,
    execute_subprocess_async,
    require_ray,
    require_torch_gpu,
    require_torch_multi_gpu,
)


logging.basicConfig(level=logging.DEBUG)
__a       :	Optional[int]             = logging.getLogger()

__a       :	Any             = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)







class        _SCREAMING_SNAKE_CASE						(  __snake_case							):





							"""simple docstring"""





							def  lowercase		(   self:     List[Any]				,		__A:     List[Any]    ):

												'''simple docstring'''

												os.makedirs(__A				,		exist_ok=__A    )
												a__          =  {'''source''': '''What is love ?''', '''target''': '''life'''}
												a__          =  {'''train''': 12, '''val''': 2, '''test''': 2}
												for split in ["train", "test", "val"]:
																	for field in ["source", "target"]:
																						a__          =  '''\n'''.join([contents[field]] * n_lines[split]    )
																						with open(os.path.join(__A				,		F'{split}.{field}'    )				,		'''w'''    ) as f:
																											f.write(__A    )




							def  lowercase		(   self:     Optional[int]				,		__A:     int				,		__A:     str = "pytorch"    ):

												'''simple docstring'''

												a__          =  self.get_auto_remove_tmp_dir()
												a__          =  os.path.join(__A				,		'''output'''    )
												a__          =  os.path.join(__A				,		'''data'''    )
												self._create_dummy_data(data_dir=__A    )

												a__          =  F'\n                --data_dir {data_dir} \\n                --output_dir {output_dir} \\n                --model_name_or_path facebook/rag-sequence-base \\n                --model_type rag_sequence \\n                --do_train \\n                --do_predict \\n                --n_val -1 \\n                --val_check_interval 1.0 \\n                --train_batch_size 2 \\n                --eval_batch_size 1 \\n                --max_source_length 25 \\n                --max_target_length 25 \\n                --val_max_target_length 25 \\n                --test_max_target_length 25 \\n                --label_smoothing 0.1 \\n                --dropout 0.1 \\n                --attention_dropout 0.1 \\n                --weight_decay 0.001 \\n                --adam_epsilon 1e-08 \\n                --max_grad_norm 0.1 \\n                --lr_scheduler polynomial \\n                --learning_rate 3e-04 \\n                --num_train_epochs 1 \\n                --warmup_steps 4 \\n                --gradient_accumulation_steps 1 \\n                --distributed-port 8787 \\n                --use_dummy_dataset 1 \\n                --distributed_retriever {distributed_retriever} \\n            '.split()

												if gpus > 0:
																	testargs.append(F'--gpus={gpus}'    )
																	if is_apex_available():
																						testargs.append('''--fp16'''    )
												else:
																	testargs.append('''--gpus=0'''    )
																	testargs.append('''--distributed_backend=ddp_cpu'''    )
																	testargs.append('''--num_processes=2'''    )

												a__          =  [sys.executable, str(Path(finetune_rag.__file__    ).resolve()    )] + testargs
												execute_subprocess_async(__A				,		env=self.get_env()    )

												a__          =  os.path.join(__A				,		'''metrics.json'''    )
												with open(__A    ) as f:
																	a__          =  json.load(__A    )
												return result




							@require_torch_gpu
							def  lowercase		(   self:     Optional[int]    ):

												'''simple docstring'''

												a__          =  self._run_finetune(gpus=1    )
												self.assertGreaterEqual(result['''test'''][0]['''test_avg_em''']				,		0.2    )




							@require_torch_multi_gpu
							def  lowercase		(   self:     str    ):

												'''simple docstring'''

												a__          =  self._run_finetune(gpus=2    )
												self.assertGreaterEqual(result['''test'''][0]['''test_avg_em''']				,		0.2    )




							@require_torch_gpu
							@require_ray
							def  lowercase		(   self:     Dict    ):

												'''simple docstring'''

												a__          =  self._run_finetune(gpus=1				,		distributed_retriever='''ray'''    )
												self.assertGreaterEqual(result['''test'''][0]['''test_avg_em''']				,		0.2    )





							@require_torch_multi_gpu
							@require_ray
							def  lowercase		(   self:     str    ):

												'''simple docstring'''

												a__          =  self._run_finetune(gpus=1				,		distributed_retriever='''ray'''    )
												self.assertGreaterEqual(result['''test'''][0]['''test_avg_em''']				,		0.2    )


