

# tests directory-specific settings - this file is run automatically
# by pytest before any tests are run

import doctest
import sys
import warnings
from os.path import abspath, dirname, join

import _pytest

from transformers.testing_utils import HfDoctestModule, HfDocTestParser


# allow having multiple repository checkouts and not needing to remember to rerun
# 'pip install -e .[dev]' when switching between checkouts and running tests.
lowerCAmelCase__								=		abspath(join(dirname(__file__), """src"""))
sys.path.insert(1, git_repo_path)

# silence FutureWarning warnings in tests since often we can't act on them until
# they become normal warnings - i.e. the tests still need to test the current functionality
warnings.simplefilter(action="""ignore""", category=FutureWarning)






def 					lowerCamelCase_     (							UpperCAmelCase_							:     Any	)						->				Union[str, Any]:




	'''simple docstring'''




	config.addinivalue_line(
	    'markers'							,       'is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested'	)
	config.addinivalue_line(
	    'markers'							,       'is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested'	)
	config.addinivalue_line('markers'							,       'is_pipeline_test: mark test to run only when pipelines are tested'	)
	config.addinivalue_line('markers'							,       'is_staging_test: mark test to run only in the staging environment'	)
	config.addinivalue_line('markers'							,       'accelerate_tests: mark test that require accelerate'	)
	config.addinivalue_line('markers'							,       'tool_tests: mark the tool tests that are run on their specific schedule'	)






def 					lowerCamelCase_     (							UpperCAmelCase_							:     Optional[int]	)						->				List[Any]:




	'''simple docstring'''




	from transformers.testing_utils import pytest_addoption_shared

	pytest_addoption_shared(UpperCAmelCase_	)






def 					lowerCamelCase_     (							UpperCAmelCase_							:     Any	)						->				List[Any]:




	'''simple docstring'''




	from transformers.testing_utils import pytest_terminal_summary_main

	_UpperCamelCase   :		str			=						terminalreporter.config.getoption('--make-reports'	)
	if make_reports:
		pytest_terminal_summary_main(UpperCAmelCase_							,       id=UpperCAmelCase_	)






def 					lowerCamelCase_     (							UpperCAmelCase_							:     Dict							,       UpperCAmelCase_							:     Dict	)						->				Tuple:




	'''simple docstring'''




	if exitstatus == 5:
		_UpperCamelCase   :		List[Any]			=						0


# Doctest custom flag to ignore output.
lowerCAmelCase__								=		doctest.register_optionflag("""IGNORE_RESULT""")

lowerCAmelCase__								=		doctest.OutputChecker







class 	lowercase    (				_lowercase							):


		"""simple docstring"""




		def 		A__					(				self	,       __snake_case	,       __snake_case	,       __snake_case):
			if IGNORE_RESULT & optionflags:
				return True
			return OutputChecker.check_output(self	,       __snake_case	,       __snake_case	,       __snake_case)

lowerCAmelCase__								=		CustomOutputChecker
lowerCAmelCase__								=		HfDoctestModule







lowerCAmelCase__								=		HfDocTestParser









import argparse
import os

import torch

from diffusers import (
    CMStochasticIterativeScheduler,
    ConsistencyModelPipeline,
    UNetaDModel,
)


lowerCAmelCase__								=		{
    """sample_size""": 3_2,
    """in_channels""": 3,
    """out_channels""": 3,
    """layers_per_block""": 2,
    """num_class_embeds""": 1_0_0_0,
    """block_out_channels""": [3_2, 6_4],
    """attention_head_dim""": 8,
    """down_block_types""": [
        """ResnetDownsampleBlock2D""",
        """AttnDownBlock2D""",
    ],
    """up_block_types""": [
        """AttnUpBlock2D""",
        """ResnetUpsampleBlock2D""",
    ],
    """resnet_time_scale_shift""": """scale_shift""",
    """upsample_type""": """resnet""",
    """downsample_type""": """resnet""",
}

lowerCAmelCase__								=		{
    """sample_size""": 6_4,
    """in_channels""": 3,
    """out_channels""": 3,
    """layers_per_block""": 3,
    """num_class_embeds""": 1_0_0_0,
    """block_out_channels""": [1_9_2, 1_9_2 * 2, 1_9_2 * 3, 1_9_2 * 4],
    """attention_head_dim""": 6_4,
    """down_block_types""": [
        """ResnetDownsampleBlock2D""",
        """AttnDownBlock2D""",
        """AttnDownBlock2D""",
        """AttnDownBlock2D""",
    ],
    """up_block_types""": [
        """AttnUpBlock2D""",
        """AttnUpBlock2D""",
        """AttnUpBlock2D""",
        """ResnetUpsampleBlock2D""",
    ],
    """resnet_time_scale_shift""": """scale_shift""",
    """upsample_type""": """resnet""",
    """downsample_type""": """resnet""",
}

lowerCAmelCase__								=		{
    """sample_size""": 2_5_6,
    """in_channels""": 3,
    """out_channels""": 3,
    """layers_per_block""": 2,
    """num_class_embeds""": None,
    """block_out_channels""": [2_5_6, 2_5_6, 2_5_6 * 2, 2_5_6 * 2, 2_5_6 * 4, 2_5_6 * 4],
    """attention_head_dim""": 6_4,
    """down_block_types""": [
        """ResnetDownsampleBlock2D""",
        """ResnetDownsampleBlock2D""",
        """ResnetDownsampleBlock2D""",
        """AttnDownBlock2D""",
        """AttnDownBlock2D""",
        """AttnDownBlock2D""",
    ],
    """up_block_types""": [
        """AttnUpBlock2D""",
        """AttnUpBlock2D""",
        """AttnUpBlock2D""",
        """ResnetUpsampleBlock2D""",
        """ResnetUpsampleBlock2D""",
        """ResnetUpsampleBlock2D""",
    ],
    """resnet_time_scale_shift""": """default""",
    """upsample_type""": """resnet""",
    """downsample_type""": """resnet""",
}

lowerCAmelCase__								=		{
    """num_train_timesteps""": 4_0,
    """sigma_min""": 0.0_02,
    """sigma_max""": 80.0,
}

lowerCAmelCase__								=		{
    """num_train_timesteps""": 2_0_1,
    """sigma_min""": 0.0_02,
    """sigma_max""": 80.0,
}

lowerCAmelCase__								=		{
    """num_train_timesteps""": 1_5_1,
    """sigma_min""": 0.0_02,
    """sigma_max""": 80.0,
}






def 					lowerCamelCase_     (							UpperCAmelCase_							:     int	)						->				List[str]:




	'''simple docstring'''




	if isinstance(UpperCAmelCase_							,       UpperCAmelCase_	):
		return v
	if v.lower() in ("yes", "true", "t", "y", "1"):
		return True
	elif v.lower() in ("no", "false", "f", "n", "0"):
		return False
	else:
		raise argparse.ArgumentTypeError('boolean value expected'	)






def 					lowerCamelCase_     (							UpperCAmelCase_							:     Tuple							,       UpperCAmelCase_							:     Optional[Any]							,       UpperCAmelCase_							:     List[str]							,       UpperCAmelCase_							:     str							,       UpperCAmelCase_							:     Union[str, Any]=False	)						->				str:




	'''simple docstring'''




	_UpperCamelCase   :		Optional[int]			=						checkpoint[F'''{old_prefix}.in_layers.0.weight''']
	_UpperCamelCase   :		str			=						checkpoint[F'''{old_prefix}.in_layers.0.bias''']
	_UpperCamelCase   :		str			=						checkpoint[F'''{old_prefix}.in_layers.2.weight''']
	_UpperCamelCase   :		Union[str, Any]			=						checkpoint[F'''{old_prefix}.in_layers.2.bias''']
	_UpperCamelCase   :		Dict			=						checkpoint[F'''{old_prefix}.emb_layers.1.weight''']
	_UpperCamelCase   :		Optional[int]			=						checkpoint[F'''{old_prefix}.emb_layers.1.bias''']
	_UpperCamelCase   :		Tuple			=						checkpoint[F'''{old_prefix}.out_layers.0.weight''']
	_UpperCamelCase   :		List[Any]			=						checkpoint[F'''{old_prefix}.out_layers.0.bias''']
	_UpperCamelCase   :		Optional[Any]			=						checkpoint[F'''{old_prefix}.out_layers.3.weight''']
	_UpperCamelCase   :		Union[str, Any]			=						checkpoint[F'''{old_prefix}.out_layers.3.bias''']

	if has_skip:
		_UpperCamelCase   :		Tuple			=						checkpoint[F'''{old_prefix}.skip_connection.weight''']
		_UpperCamelCase   :		Optional[int]			=						checkpoint[F'''{old_prefix}.skip_connection.bias''']

	return new_checkpoint






def 					lowerCamelCase_     (							UpperCAmelCase_							:     Union[str, Any]							,       UpperCAmelCase_							:     Union[str, Any]							,       UpperCAmelCase_							:     Tuple							,       UpperCAmelCase_							:     Union[str, Any]							,       UpperCAmelCase_							:     Any=None	)						->				int:




	'''simple docstring'''




	_UpperCamelCase	,		_UpperCamelCase	,		_UpperCamelCase   :		Optional[Any]			=						checkpoint[F'''{old_prefix}.qkv.weight'''].chunk(3							,       dim=0	)
	_UpperCamelCase	,		_UpperCamelCase	,		_UpperCamelCase   :		Optional[Any]			=						checkpoint[F'''{old_prefix}.qkv.bias'''].chunk(3							,       dim=0	)

	_UpperCamelCase   :		Dict			=						checkpoint[F'''{old_prefix}.norm.weight''']
	_UpperCamelCase   :		Optional[int]			=						checkpoint[F'''{old_prefix}.norm.bias''']

	_UpperCamelCase   :		List[str]			=						weight_q.squeeze(-1	).squeeze(-1	)
	_UpperCamelCase   :		Dict			=						bias_q.squeeze(-1	).squeeze(-1	)
	_UpperCamelCase   :		Any			=						weight_k.squeeze(-1	).squeeze(-1	)
	_UpperCamelCase   :		List[Any]			=						bias_k.squeeze(-1	).squeeze(-1	)
	_UpperCamelCase   :		Dict			=						weight_v.squeeze(-1	).squeeze(-1	)
	_UpperCamelCase   :		Tuple			=						bias_v.squeeze(-1	).squeeze(-1	)

	_UpperCamelCase   :		Optional[Any]			=						(
	    checkpoint[F'''{old_prefix}.proj_out.weight'''].squeeze(-1	).squeeze(-1	)
	)
	_UpperCamelCase   :		Dict			=						checkpoint[F'''{old_prefix}.proj_out.bias'''].squeeze(-1	).squeeze(-1	)

	return new_checkpoint






def 					lowerCamelCase_     (							UpperCAmelCase_							:     str							,       UpperCAmelCase_							:     Optional[int]	)						->				Tuple:




	'''simple docstring'''




	_UpperCamelCase   :		Any			=						torch.load(UpperCAmelCase_							,       map_location='cpu'	)
	_UpperCamelCase   :		Union[str, Any]			=						{}

	_UpperCamelCase   :		Optional[int]			=						checkpoint['time_embed.0.weight']
	_UpperCamelCase   :		List[Any]			=						checkpoint['time_embed.0.bias']
	_UpperCamelCase   :		Dict			=						checkpoint['time_embed.2.weight']
	_UpperCamelCase   :		Optional[Any]			=						checkpoint['time_embed.2.bias']

	if unet_config["num_class_embeds"] is not None:
		_UpperCamelCase   :		List[str]			=						checkpoint['label_emb.weight']

	_UpperCamelCase   :		Optional[int]			=						checkpoint['input_blocks.0.0.weight']
	_UpperCamelCase   :		Union[str, Any]			=						checkpoint['input_blocks.0.0.bias']

	_UpperCamelCase   :		Optional[int]			=						unet_config['down_block_types']
	_UpperCamelCase   :		Optional[Any]			=						unet_config['layers_per_block']
	_UpperCamelCase   :		Dict			=						unet_config['attention_head_dim']
	_UpperCamelCase   :		List[str]			=						unet_config['block_out_channels']
	_UpperCamelCase   :		str			=						1
	_UpperCamelCase   :		Optional[int]			=						channels_list[0]

	for i, layer_type in enumerate(UpperCAmelCase_	):
		_UpperCamelCase   :		List[str]			=						channels_list[i]
		_UpperCamelCase   :		str			=						current_channels != prev_channels
		if layer_type == "ResnetDownsampleBlock2D":
			for j in range(UpperCAmelCase_	):
				_UpperCamelCase   :		str			=						F'''down_blocks.{i}.resnets.{j}'''
				_UpperCamelCase   :		List[Any]			=						F'''input_blocks.{current_layer}.0'''
				_UpperCamelCase   :		Any			=						True if j == 0 and downsample_block_has_skip else False
				_UpperCamelCase   :		str			=						convert_resnet(UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_							,       has_skip=UpperCAmelCase_	)
				current_layer += 1

		elif layer_type == "AttnDownBlock2D":
			for j in range(UpperCAmelCase_	):
				_UpperCamelCase   :		List[str]			=						F'''down_blocks.{i}.resnets.{j}'''
				_UpperCamelCase   :		str			=						F'''input_blocks.{current_layer}.0'''
				_UpperCamelCase   :		int			=						True if j == 0 and downsample_block_has_skip else False
				_UpperCamelCase   :		Any			=						convert_resnet(UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_							,       has_skip=UpperCAmelCase_	)
				_UpperCamelCase   :		Dict			=						F'''down_blocks.{i}.attentions.{j}'''
				_UpperCamelCase   :		Optional[int]			=						F'''input_blocks.{current_layer}.1'''
				_UpperCamelCase   :		Dict			=						convert_attention(
				    UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_	)
				current_layer += 1

		if i != len(UpperCAmelCase_	) - 1:
			_UpperCamelCase   :		int			=						F'''down_blocks.{i}.downsamplers.0'''
			_UpperCamelCase   :		Optional[int]			=						F'''input_blocks.{current_layer}.0'''
			_UpperCamelCase   :		List[Any]			=						convert_resnet(UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_	)
			current_layer += 1

		_UpperCamelCase   :		Tuple			=						current_channels

	# hardcoded the mid-block for now
	_UpperCamelCase   :		Any			=						'mid_block.resnets.0'
	_UpperCamelCase   :		Optional[Any]			=						'middle_block.0'
	_UpperCamelCase   :		Tuple			=						convert_resnet(UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_	)
	_UpperCamelCase   :		Optional[Any]			=						'mid_block.attentions.0'
	_UpperCamelCase   :		Tuple			=						'middle_block.1'
	_UpperCamelCase   :		Union[str, Any]			=						convert_attention(UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_	)
	_UpperCamelCase   :		Tuple			=						'mid_block.resnets.1'
	_UpperCamelCase   :		str			=						'middle_block.2'
	_UpperCamelCase   :		List[str]			=						convert_resnet(UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_	)

	_UpperCamelCase   :		List[Any]			=						0
	_UpperCamelCase   :		Optional[int]			=						unet_config['up_block_types']

	for i, layer_type in enumerate(UpperCAmelCase_	):
		if layer_type == "ResnetUpsampleBlock2D":
			for j in range(layers_per_block + 1	):
				_UpperCamelCase   :		Optional[Any]			=						F'''up_blocks.{i}.resnets.{j}'''
				_UpperCamelCase   :		Optional[int]			=						F'''output_blocks.{current_layer}.0'''
				_UpperCamelCase   :		str			=						convert_resnet(UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_							,       has_skip=UpperCAmelCase_	)
				current_layer += 1

			if i != len(UpperCAmelCase_	) - 1:
				_UpperCamelCase   :		List[Any]			=						F'''up_blocks.{i}.upsamplers.0'''
				_UpperCamelCase   :		Dict			=						F'''output_blocks.{current_layer-1}.1'''
				_UpperCamelCase   :		Optional[int]			=						convert_resnet(UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_	)
		elif layer_type == "AttnUpBlock2D":
			for j in range(layers_per_block + 1	):
				_UpperCamelCase   :		str			=						F'''up_blocks.{i}.resnets.{j}'''
				_UpperCamelCase   :		Union[str, Any]			=						F'''output_blocks.{current_layer}.0'''
				_UpperCamelCase   :		Optional[int]			=						convert_resnet(UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_							,       has_skip=UpperCAmelCase_	)
				_UpperCamelCase   :		int			=						F'''up_blocks.{i}.attentions.{j}'''
				_UpperCamelCase   :		List[Any]			=						F'''output_blocks.{current_layer}.1'''
				_UpperCamelCase   :		Optional[int]			=						convert_attention(
				    UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_	)
				current_layer += 1

			if i != len(UpperCAmelCase_	) - 1:
				_UpperCamelCase   :		List[Any]			=						F'''up_blocks.{i}.upsamplers.0'''
				_UpperCamelCase   :		Union[str, Any]			=						F'''output_blocks.{current_layer-1}.2'''
				_UpperCamelCase   :		List[str]			=						convert_resnet(UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_							,       UpperCAmelCase_	)

	_UpperCamelCase   :		List[Any]			=						checkpoint['out.0.weight']
	_UpperCamelCase   :		str			=						checkpoint['out.0.bias']
	_UpperCamelCase   :		int			=						checkpoint['out.2.weight']
	_UpperCamelCase   :		List[Any]			=						checkpoint['out.2.bias']

	return new_checkpoint


if __name__ == "__main__":
							lowerCAmelCase__								=		argparse.ArgumentParser()

							parser.add_argument("""--unet_path""", default=None, type=str, required=True, help="""Path to the unet.pt to convert.""")
							parser.add_argument(
							    """--dump_path""", default=None, type=str, required=True, help="""Path to output the converted UNet model."""
							)
							parser.add_argument("""--class_cond""", default=True, type=str, help="""Whether the model is class-conditional.""")

							lowerCAmelCase__								=		parser.parse_args()
							lowerCAmelCase__								=		strabool(args.class_cond)

							lowerCAmelCase__								=		os.path.basename(args.unet_path)
							print(f'Checkpoint: {ckpt_name}')

							# Get U-Net config
							if "imagenet64" in ckpt_name:
														lowerCAmelCase__								=		IMAGENET_64_UNET_CONFIG
							elif "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)):
														lowerCAmelCase__								=		LSUN_256_UNET_CONFIG
							elif "test" in ckpt_name:
														lowerCAmelCase__								=		TEST_UNET_CONFIG
							else:
														raise ValueError(f'Checkpoint type {ckpt_name} is not currently supported.')

							if not args.class_cond:
														lowerCAmelCase__								=		None

							lowerCAmelCase__								=		con_pt_to_diffuser(args.unet_path, unet_config)

							lowerCAmelCase__								=		UNetaDModel(**unet_config)
							image_unet.load_state_dict(converted_unet_ckpt)

							# Get scheduler config
							if "cd" in ckpt_name or "test" in ckpt_name:
														lowerCAmelCase__								=		CD_SCHEDULER_CONFIG
							elif "ct" in ckpt_name and "imagenet64" in ckpt_name:
														lowerCAmelCase__								=		CT_IMAGENET_64_SCHEDULER_CONFIG
							elif "ct" in ckpt_name and "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)):
														lowerCAmelCase__								=		CT_LSUN_256_SCHEDULER_CONFIG
							else:
														raise ValueError(f'Checkpoint type {ckpt_name} is not currently supported.')

							lowerCAmelCase__								=		CMStochasticIterativeScheduler(**scheduler_config)

							lowerCAmelCase__								=		ConsistencyModelPipeline(unet=image_unet, scheduler=cm_scheduler)
							consistency_model.save_pretrained(args.dump_path)




