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

lowercase			:				str    		=			logging.get_logger(__name__)







def 		lowerCAmelCase_				(   snake_case__		,				snake_case__		,				snake_case__		,				snake_case__=None		,				snake_case__=None						):




    '''simple docstring'''



    if "." in tensor_name:
        A       :   int					=						tensor_name.split('''.'''						)
        for split in splits[:-1]:
            A       :   Optional[Any]					=						getattr(snake_case__		,				snake_case__						)
            if new_module is None:
                raise ValueError(F'{module} has no attribute {split}.'						)
            A       :   int					=						new_module
        A       :   Dict					=						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}.'						)
    A       :   List[str]					=						tensor_name in module._buffers
    A       :   Tuple					=						getattr(snake_case__		,				snake_case__						)

    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}.'						)

    A       :   Optional[int]					=						False
    A       :   Tuple					=						False
    if is_buffer or not is_bitsandbytes_available():
        A       :   List[Any]					=						False
        A       :   Union[str, Any]					=						False
    else:
        A       :   Dict					=						hasattr(bnb.nn		,				'''Params4bit'''						) and isinstance(module._parameters[tensor_name]		,				bnb.nn.Paramsabit						)
        A       :   Dict					=						isinstance(module._parameters[tensor_name]		,				bnb.nn.IntaParams						)

    if is_abit or is_abit:
        A       :   Tuple					=						module._parameters[tensor_name]
        if param.device.type != "cuda":
            if value is None:
                A       :   Union[str, Any]					=						old_value.to(snake_case__						)
            elif isinstance(snake_case__		,				torch.Tensor						):
                A       :   Dict					=						value.to('''cpu'''						)
                if value.dtype == torch.inta:
                    A       :   Optional[int]					=						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:
                A       :   Union[str, Any]					=						torch.tensor(snake_case__		,				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		,				snake_case__						) and fpaa_statistics is None:
                A       :   Optional[Any]					=						new_value.T

            A       :   Any					=						old_value.__dict__
            if is_abit:
                A       :   List[Any]					=						bnb.nn.IntaParams(snake_case__		,				requires_grad=snake_case__		,				**snake_case__						).to(snake_case__						)
            elif is_abit:
                A       :   Optional[int]					=						bnb.nn.Paramsabit(snake_case__		,				requires_grad=snake_case__		,				**snake_case__						).to(snake_case__						)

            A       :   List[Any]					=						new_value
            if fpaa_statistics is not None:
                setattr(module.weight		,				'''SCB'''		,				fpaa_statistics.to(snake_case__						)						)

    else:
        if value is None:
            A       :   Any					=						old_value.to(snake_case__						)
        elif isinstance(snake_case__		,				torch.Tensor						):
            A       :   List[Any]					=						value.to(snake_case__						)
        else:
            A       :   List[Any]					=						torch.tensor(snake_case__		,				device=snake_case__						)

        if is_buffer:
            A       :   Union[str, Any]					=						new_value
        else:
            A       :   List[str]					=						nn.Parameter(snake_case__		,				requires_grad=old_value.requires_grad						)
            A       :   str					=						new_value







def 		lowerCAmelCase_				(   snake_case__		,				snake_case__=None		,				snake_case__=None		,				snake_case__=None		,				snake_case__=False						):




    '''simple docstring'''



    for name, module in model.named_children():
        if current_key_name is None:
            A       :   Any					=						[]
        current_key_name.append(snake_case__						)

        if (isinstance(snake_case__		,				nn.Linear						) or isinstance(snake_case__		,				snake_case__						)) 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(snake_case__						) for key in modules_to_not_convert						):
                with init_empty_weights():
                    if isinstance(snake_case__		,				snake_case__						):
                        A,  A       :   Tuple					=						module.weight.shape
                    else:
                        A       :   Optional[Any]					=						module.in_features
                        A       :   Any					=						module.out_features

                    if quantization_config.quantization_method() == "llm_int8":
                        A       :   Dict					=						bnb.nn.LinearabitLt(
                            snake_case__		,				snake_case__		,				module.bias is not None		,				has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight		,				threshold=quantization_config.llm_inta_threshold		,				)
                        A       :   int					=						True
                    else:
                        if (
                            quantization_config.llm_inta_skip_modules is not None
                            and name in quantization_config.llm_inta_skip_modules
                        ):
                            pass
                        else:
                            A       :   List[Any]					=						bnb.nn.Linearabit(
                                snake_case__		,				snake_case__		,				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		,				)
                            A       :   int					=						True
                    # Store the module class in case we need to transpose the weight later
                    A       :   int					=						type(snake_case__						)
                    # Force requires grad to False to avoid unexpected errors
                    model._modules[name].requires_grad_(snake_case__						)
        if len(list(module.children()						)						) > 0:
            A,  A       :   int					=						_replace_with_bnb_linear(
                snake_case__		,				snake_case__		,				snake_case__		,				snake_case__		,				has_been_replaced=snake_case__		,				)
        # Remove the last key for recursion
        current_key_name.pop(-1						)
    return model, has_been_replaced







def 		lowerCAmelCase_				(   snake_case__		,				snake_case__=None		,				snake_case__=None		,				snake_case__=None						):




    '''simple docstring'''



    A       :   Union[str, Any]					=						['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert
    A,  A       :   Optional[Any]					=						_replace_with_bnb_linear(
        snake_case__		,				snake_case__		,				snake_case__		,				snake_case__						)

    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 		lowerCAmelCase_				(   *snake_case__		,				**snake_case__						):




    '''simple docstring'''



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







def 		lowerCAmelCase_				(   *snake_case__		,				**snake_case__						):




    '''simple docstring'''



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







def 		lowerCAmelCase_				(   snake_case__						):




    '''simple docstring'''



    A       :   str					=						deepcopy(snake_case__						)  # this has 0 cost since it is done inside `init_empty_weights` context manager`
    tied_model.tie_weights()

    A       :   List[str]					=						find_tied_parameters(snake_case__						)
    # For compatibility with Accelerate < 0.18
    if isinstance(snake_case__		,				snake_case__						):
        A       :   List[str]					=						sum(list(tied_params.values()						)		,				[]						) + list(tied_params.keys()						)
    else:
        A       :   Tuple					=						sum(snake_case__		,				[]						)
    A       :   Optional[int]					=						len(snake_case__						) > 0

    # Check if it is a base model
    A       :   Dict					=						not hasattr(snake_case__		,				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[str]					=						list(model.named_children()						)
    A       :   List[Any]					=						[list_modules[-1][0]]

    # add last module together with tied weights
    A       :   Union[str, Any]					=						set(snake_case__						) - set(snake_case__						)
    A       :   Optional[int]					=						list(set(snake_case__						)						) + list(snake_case__						)

    # remove ".weight" from the keys
    A       :   List[Any]					=						['''.weight''', '''.bias''']
    A       :   Tuple					=						[]
    for name in list_untouched:
        for name_to_remove in names_to_remove:
            if name_to_remove in name:
                A       :   List[str]					=						name.replace(snake_case__		,				''''''						)
        filtered_module_names.append(snake_case__						)

    return filtered_module_names






'''simple docstring'''




import argparse
import re

import torch
from CLAP import create_model

from transformers import AutoFeatureExtractor, ClapConfig, ClapModel


lowercase			:				Union[str, Any]    		=			{
    'text_branch': 'text_model',
    'audio_branch': 'audio_model.audio_encoder',
    'attn': 'attention.self',
    'self.proj': 'output.dense',
    'attention.self_mask': 'attn_mask',
    'mlp.fc1': 'intermediate.dense',
    'mlp.fc2': 'output.dense',
    'norm1': 'layernorm_before',
    'norm2': 'layernorm_after',
    'bn0': 'batch_norm',
}

lowercase			:				Tuple    		=			AutoFeatureExtractor.from_pretrained('laion/clap-htsat-unfused', truncation='rand_trunc')







def 		lowerCAmelCase_				(   snake_case__		,				snake_case__=False						):




    '''simple docstring'''



    A,  A       :   Tuple					=						create_model(
        '''HTSAT-tiny'''		,				'''roberta'''		,				snake_case__		,				precision='''fp32'''		,				device='''cuda:0''' if torch.cuda.is_available() else '''cpu'''		,				enable_fusion=snake_case__		,				fusion_type='''aff_2d''' if enable_fusion else None		,				)
    return model, model_cfg







def 		lowerCAmelCase_				(   snake_case__						):




    '''simple docstring'''



    A       :   Dict					=						{}

    A       :   str					=						R'''.*sequential.(\d+).*'''
    A       :   Union[str, Any]					=						R'''.*_projection.(\d+).*'''

    for key, value in state_dict.items():
        # check if any key needs to be modified
        for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items():
            if key_to_modify in key:
                A       :   Any					=						key.replace(snake_case__		,				snake_case__						)

        if re.match(snake_case__		,				snake_case__						):
            # replace sequential layers with list
            A       :   Any					=						re.match(snake_case__		,				snake_case__						).group(1						)

            A       :   List[str]					=						key.replace(F'sequential.{sequential_layer}.'		,				F'layers.{int(snake_case__						)//3}.linear.'						)
        elif re.match(snake_case__		,				snake_case__						):
            A       :   Union[str, Any]					=						int(re.match(snake_case__		,				snake_case__						).group(1						)						)

            # Because in CLAP they use `nn.Sequential`...
            A       :   str					=						1 if projecton_layer == 0 else 2

            A       :   Optional[Any]					=						key.replace(F'_projection.{projecton_layer}.'		,				F'_projection.linear{transformers_projection_layer}.'						)

        if "audio" and "qkv" in key:
            # split qkv into query key and value
            A       :   int					=						value
            A       :   List[Any]					=						mixed_qkv.size(0						) // 3

            A       :   Union[str, Any]					=						mixed_qkv[:qkv_dim]
            A       :   Optional[int]					=						mixed_qkv[qkv_dim : qkv_dim * 2]
            A       :   Optional[int]					=						mixed_qkv[qkv_dim * 2 :]

            A       :   Tuple					=						query_layer
            A       :   Union[str, Any]					=						key_layer
            A       :   Optional[int]					=						value_layer
        else:
            A       :   Dict					=						value

    return model_state_dict







def 		lowerCAmelCase_				(   snake_case__		,				snake_case__		,				snake_case__		,				snake_case__=False						):




    '''simple docstring'''



    A,  A       :   int					=						init_clap(snake_case__		,				enable_fusion=snake_case__						)

    clap_model.eval()
    A       :   str					=						clap_model.state_dict()
    A       :   Union[str, Any]					=						rename_state_dict(snake_case__						)

    A       :   Tuple					=						ClapConfig()
    A       :   str					=						enable_fusion
    A       :   str					=						ClapModel(snake_case__						)

    # ignore the spectrogram embedding layer
    model.load_state_dict(snake_case__		,				strict=snake_case__						)

    model.save_pretrained(snake_case__						)
    transformers_config.save_pretrained(snake_case__						)


if __name__ == "__main__":
      lowercase			:				List[str]    		=			argparse.ArgumentParser()
      parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
      parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint')
      parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert')
      parser.add_argument('--enable_fusion', action='store_true', help='Whether to enable fusion or not')
      lowercase			:				Tuple    		=			parser.parse_args()

      convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)




