


'''simple docstring'''



# Copyright 2023 The HuggingFace Inc. 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 copy
import importlib.metadata
import json
import os
from dataclasses import dataclass
from typing import Any, Dict, Union

from packaging import version

from ..utils import is_torch_available, logging


if is_torch_available():
      import torch


A__		:					Any												=  logging.get_logger(__name__)





@dataclass
class    UpperCAmelCase_  :





    """simple docstring"""






    def __init__(							self			,     SCREAMING_SNAKE_CASE_=False			,     SCREAMING_SNAKE_CASE_=False			,     SCREAMING_SNAKE_CASE_=6.0			,     SCREAMING_SNAKE_CASE_=None			,     SCREAMING_SNAKE_CASE_=False			,     SCREAMING_SNAKE_CASE_=False			,     SCREAMING_SNAKE_CASE_=None			,     SCREAMING_SNAKE_CASE_="fp4"			,     SCREAMING_SNAKE_CASE_=False			,     **SCREAMING_SNAKE_CASE_			,     )				->     List[Any]:
         __lowerCamelCase   :	int								=		load_in_abit
         __lowerCamelCase   :	Optional[int]								=		load_in_abit
         __lowerCamelCase   :	Optional[Any]								=		llm_inta_threshold
         __lowerCamelCase   :	int								=		llm_inta_skip_modules
         __lowerCamelCase   :	Optional[int]								=		llm_inta_enable_fpaa_cpu_offload
         __lowerCamelCase   :	List[str]								=		llm_inta_has_fpaa_weight
         __lowerCamelCase   :	Union[str, Any]								=		bnb_abit_quant_type
         __lowerCamelCase   :	List[str]								=		bnb_abit_use_double_quant

         if bnb_abit_compute_dtype is None:
              __lowerCamelCase   :	int								=		torch.floataa
         elif isinstance(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	):
              __lowerCamelCase   :	Tuple								=		getattr(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	)
         elif isinstance(SCREAMING_SNAKE_CASE_			,     torch.dtype	):
              __lowerCamelCase   :	Dict								=		bnb_abit_compute_dtype
         else:
              raise ValueError('bnb_4bit_compute_dtype must be a string or a torch.dtype'	)

         self.post_init()







    def       lowercase_				(							self	)				->     Dict:
         if not isinstance(self.llm_inta_threshold			,     SCREAMING_SNAKE_CASE_	):
              raise ValueError('llm_int8_threshold must be a float'	)

         if self.llm_inta_skip_modules is not None and not isinstance(self.llm_inta_skip_modules			,     SCREAMING_SNAKE_CASE_	):
              raise ValueError('llm_int8_skip_modules must be a list of strings'	)
         if not isinstance(self.llm_inta_enable_fpaa_cpu_offload			,     SCREAMING_SNAKE_CASE_	):
              raise ValueError('llm_int8_enable_fp32_cpu_offload must be a boolean'	)

         if not isinstance(self.llm_inta_has_fpaa_weight			,     SCREAMING_SNAKE_CASE_	):
              raise ValueError('llm_int8_has_fp16_weight must be a boolean'	)

         if self.bnb_abit_compute_dtype is not None and not isinstance(self.bnb_abit_compute_dtype			,     torch.dtype	):
              raise ValueError('bnb_4bit_compute_dtype must be torch.dtype'	)

         if not isinstance(self.bnb_abit_quant_type			,     SCREAMING_SNAKE_CASE_	):
              raise ValueError('bnb_4bit_quant_type must be a string'	)

         if not isinstance(self.bnb_abit_use_double_quant			,     SCREAMING_SNAKE_CASE_	):
              raise ValueError('bnb_4bit_use_double_quant must be a boolean'	)

         if self.load_in_abit and not version.parse(importlib.metadata.version('bitsandbytes'	)	) >= version.parse(
             '0.39.0'	):
              raise ValueError(
                  '4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version'	)







    def       lowercase_				(							self	)				->     Tuple:
         return self.load_in_abit or self.load_in_abit







    def       lowercase_				(							self	)				->     Optional[int]:
         if self.load_in_abit:
              return "llm_int8"
         elif self.load_in_abit and self.bnb_abit_quant_type == "fp4":
              return "fp4"
         elif self.load_in_abit and self.bnb_abit_quant_type == "nf4":
              return "nf4"
         else:
              return None







    @classmethod
    def       lowercase_				(							cls			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     **SCREAMING_SNAKE_CASE_	)				->     str:
         __lowerCamelCase   :	Union[str, Any]								=		cls(**SCREAMING_SNAKE_CASE_	)

         __lowerCamelCase   :	List[str]								=		[]
         for key, value in kwargs.items():
              if hasattr(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	):
                   setattr(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	)
                   to_remove.append(SCREAMING_SNAKE_CASE_	)
         for key in to_remove:
              kwargs.pop(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	)

         if return_unused_kwargs:
              return config, kwargs
         else:
              return config







    def       lowercase_				(							self			,     SCREAMING_SNAKE_CASE_	)				->     str:
         with open(SCREAMING_SNAKE_CASE_			,     'w'			,     encoding='utf-8'	) as writer:
              __lowerCamelCase   :	List[str]								=		self.to_dict()
              __lowerCamelCase   :	Optional[Any]								=		json.dumps(SCREAMING_SNAKE_CASE_			,     indent=2			,     sort_keys=SCREAMING_SNAKE_CASE_	) + '\n'

              writer.write(SCREAMING_SNAKE_CASE_	)







    def       lowercase_				(							self	)				->     Dict[str, Any]:
         __lowerCamelCase   :	Union[str, Any]								=		copy.deepcopy(self.__dict__	)
         __lowerCamelCase   :	Union[str, Any]								=		str(output['bnb_4bit_compute_dtype']	).split('.'	)[1]

         return output







    def __repr__(							self	)				->     Union[str, Any]:
         return f'{self.__class__.__name__} {self.to_json_string()}'







    def       lowercase_				(							self			,     SCREAMING_SNAKE_CASE_ = True	)				->     str:
         if use_diff is True:
              __lowerCamelCase   :	str								=		self.to_diff_dict()
         else:
              __lowerCamelCase   :	List[str]								=		self.to_dict()
         return json.dumps(SCREAMING_SNAKE_CASE_			,     indent=2			,     sort_keys=SCREAMING_SNAKE_CASE_	) + "\n"







    def       lowercase_				(							self	)				->     Dict[str, Any]:
         __lowerCamelCase   :	List[Any]								=		self.to_dict()

         # get the default config dict
         __lowerCamelCase   :	int								=		BitsAndBytesConfig().to_dict()

         __lowerCamelCase   :	str								=		{}

         # only serialize values that differ from the default config
         for key, value in config_dict.items():
              if value != default_config_dict[key]:
                   __lowerCamelCase   :	Optional[int]								=		value

         return serializable_config_dict










'''simple docstring'''



import unittest

import torch

from diffusers import VQModel
from diffusers.utils import floats_tensor, torch_device
from diffusers.utils.testing_utils import enable_full_determinism

from .test_modeling_common import ModelTesterMixin, UNetTesterMixin


enable_full_determinism()





class    UpperCAmelCase_  (_UpperCAmelCase					,		_UpperCAmelCase					,		unittest.TestCase  ):





    """simple docstring"""






    lowerCamelCase  :					Union[str, Any]							     =			VQModel
    lowerCamelCase  :					Union[str, Any]							     =			'sample'







    @property
    def       lowercase_				(							self			,     SCREAMING_SNAKE_CASE_=(32, 32)	)				->     Any:
         __lowerCamelCase   :	Tuple								=		4
         __lowerCamelCase   :	Union[str, Any]								=		3

         __lowerCamelCase   :	List[Any]								=		floats_tensor((batch_size, num_channels) + sizes	).to(SCREAMING_SNAKE_CASE_	)

         return {"sample": image}







    @property
    def       lowercase_				(							self	)				->     Optional[int]:
         return (3, 32, 32)







    @property
    def       lowercase_				(							self	)				->     List[Any]:
         return (3, 32, 32)







    def       lowercase_				(							self	)				->     Optional[int]:
         __lowerCamelCase   :	Optional[Any]								=		{
             'block_out_channels': [32, 64],
             'in_channels': 3,
             'out_channels': 3,
             'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'],
             'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'],
             'latent_channels': 3,
         }
         __lowerCamelCase   :	Union[str, Any]								=		self.dummy_input
         return init_dict, inputs_dict







    def       lowercase_				(							self	)				->     str:
         pass







    def       lowercase_				(							self	)				->     Optional[int]:
         pass







    def       lowercase_				(							self	)				->     Any:
         __lowerCamelCase				,       __lowerCamelCase   :	Union[str, Any]								=		VQModel.from_pretrained('fusing/vqgan-dummy'			,     output_loading_info=SCREAMING_SNAKE_CASE_	)
         self.assertIsNotNone(SCREAMING_SNAKE_CASE_	)
         self.assertEqual(len(loading_info['missing_keys']	)			,     0	)

         model.to(SCREAMING_SNAKE_CASE_	)
         __lowerCamelCase   :	List[Any]								=		model(**self.dummy_input	)

         assert image is not None, "Make sure output is not None"







    def       lowercase_				(							self	)				->     int:
         __lowerCamelCase   :	List[Any]								=		VQModel.from_pretrained('fusing/vqgan-dummy'	)
         model.to(SCREAMING_SNAKE_CASE_	).eval()

         torch.manual_seed(0	)
         if torch.cuda.is_available():
              torch.cuda.manual_seed_all(0	)

         __lowerCamelCase   :	List[str]								=		torch.randn(1			,     model.config.in_channels			,     model.config.sample_size			,     model.config.sample_size	)
         __lowerCamelCase   :	Optional[int]								=		image.to(SCREAMING_SNAKE_CASE_	)
         with torch.no_grad():
              __lowerCamelCase   :	int								=		model(SCREAMING_SNAKE_CASE_	).sample

         __lowerCamelCase   :	List[str]								=		output[0, -1, -3:, -3:].flatten().cpu()
         # fmt: off
         __lowerCamelCase   :	Union[str, Any]								=		torch.tensor([-0.0_1_5_3, -0.4_0_4_4, -0.1_8_8_0, -0.5_1_6_1, -0.2_4_1_8, -0.4_0_7_2, -0.1_6_1_2, -0.0_6_3_3, -0.0_1_4_3]	)
         # fmt: on
         self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     atol=1E-3	)	)






