






"""simple docstring"""



def 						lowercase   (    __snake_case    :			str = "mytext.txt"		, __snake_case    :			bool = False     ):
		import socket

		lowercase_			:			List[str]								=       1_2_3_1_2  # Reserve a port for your service.
		lowercase_			:			Dict								=       socket.socket()  # Create a socket object
		lowercase_			:			int								=       socket.gethostname()  # Get local machine name
		sock.bind((host, port)     )  # Bind to the port
		sock.listen(5     )  # Now wait for client connection.

		print('''Server listening....'''     )

		while True:
				lowercase_	, lowercase_			:			int								=       sock.accept()  # Establish connection with client.
				print(F'''Got connection from {addr}'''     )
				lowercase_			:			List[Any]								=       conn.recv(1_0_2_4     )
				print(F'''Server received: {data = }'''     )

				with open(__snake_case		, '''rb'''     ) as in_file:
						lowercase_			:			List[Any]								=       in_file.read(1_0_2_4     )
						while data:
								conn.send(__snake_case     )
								print(F'''Sent {data!r}'''     )
								lowercase_			:			List[Any]								=       in_file.read(1_0_2_4     )

				print('''Done sending'''     )
				conn.close()
				if testing:  # Allow the test to complete
						break

		sock.shutdown(1     )
		sock.close()


if __name__ == "__main__":
						send_file()











"""simple docstring"""



import argparse
import os

import torch
from torchvision.datasets.utils import download_url

from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, TransformeraDModel


__A		:	Union[str, Any]      =		{512: '''DiT-XL-2-512x512.pt''', 256: '''DiT-XL-2-256x256.pt'''}



def 						lowercase   (    __snake_case    :			Optional[int]     ):
		lowercase_			:			Any								=       F'''pretrained_models/{model_name}'''
		if not os.path.isfile(__snake_case     ):
				os.makedirs('''pretrained_models'''		, exist_ok=__snake_case     )
				lowercase_			:			str								=       F'''https://dl.fbaipublicfiles.com/DiT/models/{model_name}'''
				download_url(__snake_case		, '''pretrained_models'''     )
		lowercase_			:			List[str]								=       torch.load(__snake_case		, map_location=lambda __snake_case		, __snake_case     : storage     )
		return model



def 						lowercase   (    __snake_case    :			Optional[int]     ):
		lowercase_			:			Dict								=       download_model(pretrained_models[args.image_size]     )

		lowercase_			:			List[str]								=       state_dict['''x_embedder.proj.weight''']
		lowercase_			:			Tuple								=       state_dict['''x_embedder.proj.bias''']
		state_dict.pop('''x_embedder.proj.weight'''     )
		state_dict.pop('''x_embedder.proj.bias'''     )

		for depth in range(2_8     ):
				lowercase_			:			Optional[int]								=       state_dict[
				    '''t_embedder.mlp.0.weight'''
				]
				lowercase_			:			List[str]								=       state_dict[
				    '''t_embedder.mlp.0.bias'''
				]
				lowercase_			:			Tuple								=       state_dict[
				    '''t_embedder.mlp.2.weight'''
				]
				lowercase_			:			Union[str, Any]								=       state_dict[
				    '''t_embedder.mlp.2.bias'''
				]
				lowercase_			:			Dict								=       state_dict[
				    '''y_embedder.embedding_table.weight'''
				]

				lowercase_			:			List[str]								=       state_dict[
				    F'''blocks.{depth}.adaLN_modulation.1.weight'''
				]
				lowercase_			:			Optional[Any]								=       state_dict[
				    F'''blocks.{depth}.adaLN_modulation.1.bias'''
				]

				lowercase_	, lowercase_	, lowercase_			:			List[Any]								=       torch.chunk(state_dict[F'''blocks.{depth}.attn.qkv.weight''']		, 3		, dim=0     )
				lowercase_	, lowercase_	, lowercase_			:			Optional[int]								=       torch.chunk(state_dict[F'''blocks.{depth}.attn.qkv.bias''']		, 3		, dim=0     )

				lowercase_			:			Union[str, Any]								=       q
				lowercase_			:			Dict								=       q_bias
				lowercase_			:			Dict								=       k
				lowercase_			:			Tuple								=       k_bias
				lowercase_			:			str								=       v
				lowercase_			:			Union[str, Any]								=       v_bias

				lowercase_			:			Optional[Any]								=       state_dict[
				    F'''blocks.{depth}.attn.proj.weight'''
				]
				lowercase_			:			List[Any]								=       state_dict[F'''blocks.{depth}.attn.proj.bias''']

				lowercase_			:			List[Any]								=       state_dict[F'''blocks.{depth}.mlp.fc1.weight''']
				lowercase_			:			Optional[Any]								=       state_dict[F'''blocks.{depth}.mlp.fc1.bias''']
				lowercase_			:			Tuple								=       state_dict[F'''blocks.{depth}.mlp.fc2.weight''']
				lowercase_			:			List[str]								=       state_dict[F'''blocks.{depth}.mlp.fc2.bias''']

				state_dict.pop(F'''blocks.{depth}.attn.qkv.weight'''     )
				state_dict.pop(F'''blocks.{depth}.attn.qkv.bias'''     )
				state_dict.pop(F'''blocks.{depth}.attn.proj.weight'''     )
				state_dict.pop(F'''blocks.{depth}.attn.proj.bias'''     )
				state_dict.pop(F'''blocks.{depth}.mlp.fc1.weight'''     )
				state_dict.pop(F'''blocks.{depth}.mlp.fc1.bias'''     )
				state_dict.pop(F'''blocks.{depth}.mlp.fc2.weight'''     )
				state_dict.pop(F'''blocks.{depth}.mlp.fc2.bias'''     )
				state_dict.pop(F'''blocks.{depth}.adaLN_modulation.1.weight'''     )
				state_dict.pop(F'''blocks.{depth}.adaLN_modulation.1.bias'''     )

		state_dict.pop('''t_embedder.mlp.0.weight'''     )
		state_dict.pop('''t_embedder.mlp.0.bias'''     )
		state_dict.pop('''t_embedder.mlp.2.weight'''     )
		state_dict.pop('''t_embedder.mlp.2.bias'''     )
		state_dict.pop('''y_embedder.embedding_table.weight'''     )

		lowercase_			:			Union[str, Any]								=       state_dict['''final_layer.adaLN_modulation.1.weight''']
		lowercase_			:			Optional[Any]								=       state_dict['''final_layer.adaLN_modulation.1.bias''']
		lowercase_			:			Dict								=       state_dict['''final_layer.linear.weight''']
		lowercase_			:			Union[str, Any]								=       state_dict['''final_layer.linear.bias''']

		state_dict.pop('''final_layer.linear.weight'''     )
		state_dict.pop('''final_layer.linear.bias'''     )
		state_dict.pop('''final_layer.adaLN_modulation.1.weight'''     )
		state_dict.pop('''final_layer.adaLN_modulation.1.bias'''     )

		# DiT XL/2
		lowercase_			:			List[str]								=       TransformeraDModel(
		    sample_size=args.image_size // 8		, num_layers=2_8		, attention_head_dim=7_2		, in_channels=4		, out_channels=8		, patch_size=2		, attention_bias=__snake_case		, num_attention_heads=1_6		, activation_fn='''gelu-approximate'''		, num_embeds_ada_norm=1_0_0_0		, norm_type='''ada_norm_zero'''		, norm_elementwise_affine=__snake_case		, )
		transformer.load_state_dict(__snake_case		, strict=__snake_case     )

		lowercase_			:			Any								=       DDIMScheduler(
		    num_train_timesteps=1_0_0_0		, beta_schedule='''linear'''		, prediction_type='''epsilon'''		, clip_sample=__snake_case		, )

		lowercase_			:			Dict								=       AutoencoderKL.from_pretrained(args.vae_model     )

		lowercase_			:			str								=       DiTPipeline(transformer=__snake_case		, vae=__snake_case		, scheduler=__snake_case     )

		if args.save:
				pipeline.save_pretrained(args.checkpoint_path     )


if __name__ == "__main__":
						__A		:	int      =		argparse.ArgumentParser()

						parser.add_argument(
						    '''--image_size''',
						    default=256,
						    type=int,
						    required=False,
						    help='''Image size of pretrained model, either 256 or 512.''',
						)
						parser.add_argument(
						    '''--vae_model''',
						    default='''stabilityai/sd-vae-ft-ema''',
						    type=str,
						    required=False,
						    help='''Path to pretrained VAE model, either stabilityai/sd-vae-ft-mse or stabilityai/sd-vae-ft-ema.''',
						)
						parser.add_argument(
						    '''--save''', default=True, type=bool, required=False, help='''Whether to save the converted pipeline or not.'''
						)
						parser.add_argument(
						    '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the output pipeline.'''
						)

						__A		:	Union[str, Any]      =		parser.parse_args()
						main(args)



