





"""simple docstring"""




import random
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    UNetaDConditionModel,
    VideoToVideoSDPipeline,
)
from diffusers.utils import floats_tensor, is_xformers_available, skip_mps
from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device

from ..pipeline_params import (
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()

@skip_mps
class  _UpperCAmelCase  (   lowerCAmelCase_			,   unittest.TestCase		):



      '''simple docstring'''
      lowercase_      : Union[str, Any]	    =   VideoToVideoSDPipeline
      lowercase_      : Tuple	    =   TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"""video"""}		) - {"""image""", """width""", """height"""}
      lowercase_      : Optional[int]	    =   TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"""video"""}		) - {"""image"""}
      lowercase_      : Dict	    =   PipelineTesterMixin.required_optional_params - {"""latents"""}
      lowercase_      : Optional[Any]	    =   False

      # No `output_type`.
      lowercase_      : Optional[Any]	    =   frozenset(
          [
              """num_inference_steps""",
              """generator""",
              """latents""",
              """return_dict""",
              """callback""",
              """callback_steps""",
          ]		)

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        torch.manual_seed(0  )
        A_  :       List[str]										=  UNetaDConditionModel(
            block_out_channels=(3_2, 6_4, 6_4, 6_4)					,      layers_per_block=2					,      sample_size=3_2					,      in_channels=4					,      out_channels=4					,      down_block_types=('CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'DownBlock3D')					,      up_block_types=('UpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D')					,      cross_attention_dim=3_2					,      attention_head_dim=4					,      )
        A_  :       List[str]										=  DDIMScheduler(
            beta_start=0.0_00_85					,      beta_end=0.0_12					,      beta_schedule='scaled_linear'					,      clip_sample=__snake_case					,      set_alpha_to_one=__snake_case					,      )
        torch.manual_seed(0  )
        A_  :       List[Any]										=  AutoencoderKL(
            block_out_channels=[3_2, 6_4]					,      in_channels=3					,      out_channels=3					,      down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']					,      up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']					,      latent_channels=4					,      sample_size=1_2_8					,      )
        torch.manual_seed(0  )
        A_  :       Tuple										=  CLIPTextConfig(
            bos_token_id=0					,      eos_token_id=2					,      hidden_size=3_2					,      intermediate_size=3_7					,      layer_norm_eps=1E-05					,      num_attention_heads=4					,      num_hidden_layers=5					,      pad_token_id=1					,      vocab_size=1_0_0_0					,      hidden_act='gelu'					,      projection_dim=5_1_2					,      )
        A_  :       Tuple										=  CLIPTextModel(__snake_case  )
        A_  :       Dict										=  CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'  )

        A_  :       List[Any]										=  {
            'unet': unet,
            'scheduler': scheduler,
            'vae': vae,
            'text_encoder': text_encoder,
            'tokenizer': tokenizer,
        }
        return components

      def 					lowerCamelCase_			(     self					,      snake_case_					,      snake_case_=0  ):

        """simple docstring"""

        A_  :       Optional[Any]										=  floats_tensor((1, 3, 3, 3_2, 3_2)					,      rng=random.Random(__snake_case  )  ).to(__snake_case  )

        if str(__snake_case  ).startswith('mps'  ):
          A_  :       Tuple										=  torch.manual_seed(__snake_case  )
        else:
          A_  :       Any										=  torch.Generator(device=__snake_case  ).manual_seed(__snake_case  )
        A_  :       List[Any]										=  {
            'prompt': 'A painting of a squirrel eating a burger',
            'video': video,
            'generator': generator,
            'num_inference_steps': 2,
            'guidance_scale': 6.0,
            'output_type': 'pt',
        }
        return inputs

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       Optional[int]										=  'cpu'  # ensure determinism for the device-dependent torch.Generator
        A_  :       str										=  self.get_dummy_components()
        A_  :       Dict										=  VideoToVideoSDPipeline(**__snake_case  )
        A_  :       Optional[Any]										=  sd_pipe.to(__snake_case  )
        sd_pipe.set_progress_bar_config(disable=__snake_case  )

        A_  :       Optional[Any]										=  self.get_dummy_inputs(__snake_case  )
        A_  :       str										=  'np'
        A_  :       int										=  sd_pipe(**__snake_case  ).frames
        A_  :       Any										=  frames[0][-3:, -3:, -1]

        assert frames[0].shape == (3_2, 3_2, 3)
        A_  :       Tuple										=  np.array([1_0_6, 1_1_7, 1_1_3, 1_7_4, 1_3_7, 1_1_2, 1_4_8, 1_5_1, 1_3_1]  )

        assert np.abs(image_slice.flatten() - expected_slice  ).max() < 1E-2

      @unittest.skipIf(
          torch_device != 'cuda' or not is_xformers_available()					,      reason='XFormers attention is only available with CUDA and `xformers` installed'					,      )
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=__snake_case					,      expected_max_diff=5E-3  )

      @unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.'  )
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        pass

      @unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.'  )
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        pass

      @unittest.skip(reason='`num_images_per_prompt` argument is not supported for this pipeline.'  )
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        pass

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        return super().test_progress_bar()


@slow
@skip_mps
class  _UpperCAmelCase  (   unittest.TestCase		):



      '''simple docstring'''

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       Union[str, Any]										=  VideoToVideoSDPipeline.from_pretrained('cerspense/zeroscope_v2_XL'					,      torch_dtype=torch.floataa  )
        pipe.enable_model_cpu_offload()

        # 10 frames
        A_  :       Dict										=  torch.Generator(device='cpu'  ).manual_seed(0  )
        A_  :       Optional[Any]										=  torch.randn((1, 1_0, 3, 1_0_2_4, 5_7_6)					,      generator=__snake_case  )
        A_  :       List[Any]										=  video.to('cuda'  )

        A_  :       Dict										=  'Spiderman is surfing'

        A_  :       List[str]										=  pipe(__snake_case					,      video=__snake_case					,      generator=__snake_case					,      num_inference_steps=3					,      output_type='pt'  ).frames

        A_  :       Union[str, Any]										=  np.array([-1.0_45_89_84, -1.1_27_92_97, -0.9_66_30_86, -0.91_50_39_06, -0.75_09_76_56]  )
        assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array  ).sum() < 1E-2


import argparse
import csv
import logging
import os
import random

import numpy as np
import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset
from tqdm import tqdm, trange

from transformers import (
    CONFIG_NAME,
    WEIGHTS_NAME,
    AdamW,
    OpenAIGPTDoubleHeadsModel,
    OpenAIGPTTokenizer,
    get_linear_schedule_with_warmup,
)


logging.basicConfig(
    format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO
)
_lowerCAmelCase					:			List[Any]  				=			logging.getLogger(__name__)






def        UpperCamelCase_(							_snake_case   :  Optional[Any]       ,     _snake_case   :  Any	):




			"""simple docstring"""






			__a        =np.argmax(_snake_case       ,     axis=1	)
			return np.sum(outputs == labels	)






def        UpperCamelCase_(							_snake_case   :  List[str]	):




			"""simple docstring"""






			with open(_snake_case       ,     encoding='utf_8'	) as f:
						__a        =csv.reader(_snake_case	)
						__a        =[]
						next(_snake_case	)  # skip the first line
						for line in tqdm(_snake_case	):
									output.append((' '.join(line[1:5]	), line[5], line[6], int(line[-1]	) - 1)	)
			return output






def        UpperCamelCase_(							_snake_case   :  Union[str, Any]       ,     _snake_case   :  Any       ,     _snake_case   :  Dict       ,     _snake_case   :  Any       ,     _snake_case   :  Union[str, Any]       ,     _snake_case   :  Tuple	):




			"""simple docstring"""






			__a        =[]
			for dataset in encoded_datasets:
						__a        =len(_snake_case	)
						__a        =np.zeros((n_batch, 2, input_len)       ,     dtype=np.intaa	)
						__a        =np.zeros((n_batch, 2)       ,     dtype=np.intaa	)
						__a        =np.full((n_batch, 2, input_len)       ,     fill_value=-100       ,     dtype=np.intaa	)
						__a        =np.zeros((n_batch,)       ,     dtype=np.intaa	)
						for (
						    i,
						    (story, conta, conta, mc_label),
						) in enumerate(_snake_case	):
									__a        =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
									__a        =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
									__a        =with_conta
									__a        =with_conta
									__a        =len(_snake_case	) - 1
									__a        =len(_snake_case	) - 1
									__a        =with_conta
									__a        =with_conta
									__a        =mc_label
						__a        =(input_ids, mc_token_ids, lm_labels, mc_labels)
						tensor_datasets.append(tuple(torch.tensor(_snake_case	) for t in all_inputs	)	)
			return tensor_datasets






def        UpperCamelCase_(							):




			"""simple docstring"""






			__a        =argparse.ArgumentParser()
			parser.add_argument('--model_name'       ,     type=_snake_case       ,     default='openai-gpt'       ,     help='pretrained model name'	)
			parser.add_argument('--do_train'       ,     action='store_true'       ,     help='Whether to run training.'	)
			parser.add_argument('--do_eval'       ,     action='store_true'       ,     help='Whether to run eval on the dev set.'	)
			parser.add_argument(
			    '--output_dir'       ,     default=_snake_case       ,     type=_snake_case       ,     required=_snake_case       ,     help='The output directory where the model predictions and checkpoints will be written.'       ,     )
			parser.add_argument('--train_dataset'       ,     type=_snake_case       ,     default=''	)
			parser.add_argument('--eval_dataset'       ,     type=_snake_case       ,     default=''	)
			parser.add_argument('--seed'       ,     type=_snake_case       ,     default=42	)
			parser.add_argument('--num_train_epochs'       ,     type=_snake_case       ,     default=3	)
			parser.add_argument('--train_batch_size'       ,     type=_snake_case       ,     default=8	)
			parser.add_argument('--eval_batch_size'       ,     type=_snake_case       ,     default=16	)
			parser.add_argument('--adam_epsilon'       ,     default=1e-8       ,     type=_snake_case       ,     help='Epsilon for Adam optimizer.'	)
			parser.add_argument('--max_grad_norm'       ,     type=_snake_case       ,     default=1	)
			parser.add_argument(
			    '--max_steps'       ,     default=-1       ,     type=_snake_case       ,     help=(
			        'If > 0: set total number of training                         steps to perform. Override num_train_epochs.'
			    )       ,     )
			parser.add_argument(
			    '--gradient_accumulation_steps'       ,     type=_snake_case       ,     default=1       ,     help='Number of updates steps to accumulate before                        performing a backward/update pass.'       ,     )
			parser.add_argument('--learning_rate'       ,     type=_snake_case       ,     default=6.2_5e-5	)
			parser.add_argument('--warmup_steps'       ,     default=0       ,     type=_snake_case       ,     help='Linear warmup over warmup_steps.'	)
			parser.add_argument('--lr_schedule'       ,     type=_snake_case       ,     default='warmup_linear'	)
			parser.add_argument('--weight_decay'       ,     type=_snake_case       ,     default=0.01	)
			parser.add_argument('--lm_coef'       ,     type=_snake_case       ,     default=0.9	)
			parser.add_argument('--n_valid'       ,     type=_snake_case       ,     default=374	)

			parser.add_argument('--server_ip'       ,     type=_snake_case       ,     default=''       ,     help='Can be used for distant debugging.'	)
			parser.add_argument('--server_port'       ,     type=_snake_case       ,     default=''       ,     help='Can be used for distant debugging.'	)
			__a        =parser.parse_args()
			print(_snake_case	)

			if args.server_ip and args.server_port:
						# Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
						import ptvsd

						print('Waiting for debugger attach'	)
						ptvsd.enable_attach(address=(args.server_ip, args.server_port)       ,     redirect_output=_snake_case	)
						ptvsd.wait_for_attach()

			random.seed(args.seed	)
			np.random.seed(args.seed	)
			torch.manual_seed(args.seed	)
			torch.cuda.manual_seed_all(args.seed	)

			__a        =torch.device('cuda' if torch.cuda.is_available() else 'cpu'	)
			__a        =torch.cuda.device_count()
			logger.info('device: {}, n_gpu {}'.format(_snake_case       ,     _snake_case	)	)

			if not args.do_train and not args.do_eval:
						raise ValueError('At least one of `do_train` or `do_eval` must be True.'	)

			if not os.path.exists(args.output_dir	):
						os.makedirs(args.output_dir	)

			# Load tokenizer and model
			# This loading functions also add new tokens and embeddings called `special tokens`
			# These new embeddings will be fine-tuned on the RocStories dataset
			__a        =['_start_', '_delimiter_', '_classify_']
			__a        =OpenAIGPTTokenizer.from_pretrained(args.model_name	)
			tokenizer.add_tokens(_snake_case	)
			__a        =tokenizer.convert_tokens_to_ids(_snake_case	)
			__a        =OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name	)
			model.resize_token_embeddings(len(_snake_case	)	)
			model.to(_snake_case	)

			# Load and encode the datasets
			def tokenize_and_encode(_snake_case   :  int	):
						if isinstance(_snake_case       ,     _snake_case	):
									return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(_snake_case	)	)
						elif isinstance(_snake_case       ,     _snake_case	):
									return obj
						return [tokenize_and_encode(_snake_case	) for o in obj]

			logger.info('Encoding dataset...'	)
			__a        =load_rocstories_dataset(args.train_dataset	)
			__a        =load_rocstories_dataset(args.eval_dataset	)
			__a        =(train_dataset, eval_dataset)
			__a        =tokenize_and_encode(_snake_case	)

			# Compute the max input length for the Transformer
			__a        =model.config.n_positions // 2 - 2
			__a        =max(
			    len(story[:max_length]	) + max(len(conta[:max_length]	)       ,     len(conta[:max_length]	)	) + 3
			    for dataset in encoded_datasets
			    for story, conta, conta, _ in dataset	)
			__a        =min(_snake_case       ,     model.config.n_positions	)  # Max size of input for the pre-trained model

			# Prepare inputs tensors and dataloaders
			__a        =pre_process_datasets(_snake_case       ,     _snake_case       ,     _snake_case       ,     *_snake_case	)
			__a      ,    __a        =tensor_datasets[0], tensor_datasets[1]

			__a        =TensorDataset(*_snake_case	)
			__a        =RandomSampler(_snake_case	)
			__a        =DataLoader(_snake_case       ,     sampler=_snake_case       ,     batch_size=args.train_batch_size	)

			__a        =TensorDataset(*_snake_case	)
			__a        =SequentialSampler(_snake_case	)
			__a        =DataLoader(_snake_case       ,     sampler=_snake_case       ,     batch_size=args.eval_batch_size	)

			# Prepare optimizer
			if args.do_train:
						if args.max_steps > 0:
									__a        =args.max_steps
									__a        =args.max_steps // (len(_snake_case	) // args.gradient_accumulation_steps) + 1
						else:
									__a        =len(_snake_case	) // args.gradient_accumulation_steps * args.num_train_epochs

						__a        =list(model.named_parameters()	)
						__a        =['bias', 'LayerNorm.bias', 'LayerNorm.weight']
						__a        =[
						    {
						        'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay	)],
						        'weight_decay': args.weight_decay,
						    },
						    {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay	)], 'weight_decay': 0.0},
						]
						__a        =AdamW(_snake_case       ,     lr=args.learning_rate       ,     eps=args.adam_epsilon	)
						__a        =get_linear_schedule_with_warmup(
						    _snake_case       ,     num_warmup_steps=args.warmup_steps       ,     num_training_steps=_snake_case	)

			if args.do_train:
						__a      ,    __a      ,    __a        =0, 0, None
						model.train()
						for _ in trange(int(args.num_train_epochs	)       ,     desc='Epoch'	):
									__a        =0
									__a        =0
									__a        =tqdm(_snake_case       ,     desc='Training'	)
									for step, batch in enumerate(_snake_case	):
												__a        =tuple(t.to(_snake_case	) for t in batch	)
												__a      ,    __a      ,    __a      ,    __a        =batch
												__a        =model(_snake_case       ,     mc_token_ids=_snake_case       ,     lm_labels=_snake_case       ,     mc_labels=_snake_case	)
												__a        =args.lm_coef * losses[0] + losses[1]
												loss.backward()
												optimizer.step()
												scheduler.step()
												optimizer.zero_grad()
												tr_loss += loss.item()
												__a        =(
												    loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item()
												)
												nb_tr_steps += 1
												__a        ='Training loss: {:.2e} lr: {:.2e}'.format(_snake_case       ,     scheduler.get_lr()[0]	)

    # Save a trained model
			if args.do_train:
						# Save a trained model, configuration and tokenizer
						__a        =model.module if hasattr(_snake_case       ,     'module'	) else model  # Only save the model itself

						# If we save using the predefined names, we can load using `from_pretrained`
						__a        =os.path.join(args.output_dir       ,     _snake_case	)
						__a        =os.path.join(args.output_dir       ,     _snake_case	)

						torch.save(model_to_save.state_dict()       ,     _snake_case	)
						model_to_save.config.to_json_file(_snake_case	)
						tokenizer.save_vocabulary(args.output_dir	)

						# Load a trained model and vocabulary that you have fine-tuned
						__a        =OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir	)
						__a        =OpenAIGPTTokenizer.from_pretrained(args.output_dir	)
						model.to(_snake_case	)

			if args.do_eval:
						model.eval()
						__a      ,    __a        =0, 0
						__a      ,    __a        =0, 0
						for batch in tqdm(_snake_case       ,     desc='Evaluating'	):
									__a        =tuple(t.to(_snake_case	) for t in batch	)
									__a      ,    __a      ,    __a      ,    __a        =batch
									with torch.no_grad():
												__a      ,    __a      ,    __a      ,    __a        =model(
												    _snake_case       ,     mc_token_ids=_snake_case       ,     lm_labels=_snake_case       ,     mc_labels=_snake_case	)

									__a        =mc_logits.detach().cpu().numpy()
									__a        =mc_labels.to('cpu'	).numpy()
									__a        =accuracy(_snake_case       ,     _snake_case	)

									eval_loss += mc_loss.mean().item()
									eval_accuracy += tmp_eval_accuracy

									nb_eval_examples += input_ids.size(0	)
									nb_eval_steps += 1

						__a        =eval_loss / nb_eval_steps
						__a        =eval_accuracy / nb_eval_examples
						__a        =tr_loss / nb_tr_steps if args.do_train else None
						__a        ={'eval_loss': eval_loss, 'eval_accuracy': eval_accuracy, 'train_loss': train_loss}

						__a        =os.path.join(args.output_dir       ,     'eval_results.txt'	)
						with open(_snake_case       ,     'w'	) as writer:
									logger.info('***** Eval results *****'	)
									for key in sorted(result.keys()	):
												logger.info('  %s = %s'       ,     _snake_case       ,     str(result[key]	)	)
												writer.write('%s = %s\n' % (key, str(result[key]	))	)


if __name__ == "__main__":
						main()






