



'''simple docstring'''






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:      Tuple		 =		logging.getLogger(__name__)
def    lowerCamelCase__ (		_A				,    _A       ):
  a		:      Optional[Any]       =  np.argmax(_A				,    axis=1       )
  return np.sum(outputs == labels       )
def    lowerCamelCase__ (		_A       ):
  with open(_A				,    encoding='utf_8'       ) as f:
    a		:      Union[str, Any]       =  csv.reader(_A       )
    a		:      Any       =  []
    next(_A       )  # skip the first line
    for line in tqdm(_A       ):
      output.append((' '.join(line[1:5]       ), line[5], line[6], int(line[-1]       ) - 1)       )
  return output
def    lowerCamelCase__ (		_A				,    _A				,    _A				,    _A				,    _A				,    _A       ):
  a		:      str       =  []
  for dataset in encoded_datasets:
    a		:      Optional[int]       =  len(_A       )
    a		:      Optional[int]       =  np.zeros((n_batch, 2, input_len)				,    dtype=np.intaa       )
    a		:      str       =  np.zeros((n_batch, 2)				,    dtype=np.intaa       )
    a		:      Optional[Any]       =  np.full((n_batch, 2, input_len)				,    fill_value=-100				,    dtype=np.intaa       )
    a		:      Dict       =  np.zeros((n_batch,)				,    dtype=np.intaa       )
    for (
        i,
        (story, conta, conta, mc_label),
    ) in enumerate(_A       ):
      a		:      int       =  [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
      a		:      Tuple       =  [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
      a		:      int       =  with_conta
      a		:      Dict       =  with_conta
      a		:      int       =  len(_A       ) - 1
      a		:      Dict       =  len(_A       ) - 1
      a		:      Optional[int]       =  with_conta
      a		:      Dict       =  with_conta
      a		:      int       =  mc_label
    a		:      List[Any]       =  (input_ids, mc_token_ids, lm_labels, mc_labels)
    tensor_datasets.append(tuple(torch.tensor(_A       ) for t in all_inputs       )       )
  return tensor_datasets
def    lowerCamelCase__ (		):
  a		:      Dict       =  argparse.ArgumentParser()
  parser.add_argument('--model_name'				,    type=_A				,    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=_A				,    type=_A				,    required=_A				,    help='The output directory where the model predictions and checkpoints will be written.'				,    )
  parser.add_argument('--train_dataset'				,    type=_A				,    default=''       )
  parser.add_argument('--eval_dataset'				,    type=_A				,    default=''       )
  parser.add_argument('--seed'				,    type=_A				,    default=42       )
  parser.add_argument('--num_train_epochs'				,    type=_A				,    default=3       )
  parser.add_argument('--train_batch_size'				,    type=_A				,    default=8       )
  parser.add_argument('--eval_batch_size'				,    type=_A				,    default=16       )
  parser.add_argument('--adam_epsilon'				,    default=1E-8				,    type=_A				,    help='Epsilon for Adam optimizer.'       )
  parser.add_argument('--max_grad_norm'				,    type=_A				,    default=1       )
  parser.add_argument(
      '--max_steps'				,    default=-1				,    type=_A				,    help=(
          'If > 0: set total number of training                         steps to perform. Override num_train_epochs.'
      )				,    )
  parser.add_argument(
      '--gradient_accumulation_steps'				,    type=_A				,    default=1				,    help='Number of updates steps to accumulate before                        performing a backward/update pass.'				,    )
  parser.add_argument('--learning_rate'				,    type=_A				,    default=6.25E-5       )
  parser.add_argument('--warmup_steps'				,    default=0				,    type=_A				,    help='Linear warmup over warmup_steps.'       )
  parser.add_argument('--lr_schedule'				,    type=_A				,    default='warmup_linear'       )
  parser.add_argument('--weight_decay'				,    type=_A				,    default=0.01       )
  parser.add_argument('--lm_coef'				,    type=_A				,    default=0.9       )
  parser.add_argument('--n_valid'				,    type=_A				,    default=374       )

  parser.add_argument('--server_ip'				,    type=_A				,    default=''				,    help='Can be used for distant debugging.'       )
  parser.add_argument('--server_port'				,    type=_A				,    default=''				,    help='Can be used for distant debugging.'       )
  a		:      Tuple       =  parser.parse_args()
  print(_A       )

  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=_A       )
    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		:      List[str]       =  torch.device('cuda' if torch.cuda.is_available() else 'cpu'       )
  a		:      Any       =  torch.cuda.device_count()
  logger.info('device: {}, n_gpu {}'.format(_A				,    _A       )       )

  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		:      Union[str, Any]       =  ['_start_', '_delimiter_', '_classify_']
  a		:      Union[str, Any]       =  OpenAIGPTTokenizer.from_pretrained(args.model_name       )
  tokenizer.add_tokens(_A       )
  a		:      Tuple       =  tokenizer.convert_tokens_to_ids(_A       )
  a		:      str       =  OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name       )
  model.resize_token_embeddings(len(_A       )       )
  model.to(_A       )

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

  logger.info('Encoding dataset...'       )
  a		:      Dict       =  load_rocstories_dataset(args.train_dataset       )
  a		:      Any       =  load_rocstories_dataset(args.eval_dataset       )
  a		:      Dict       =  (train_dataset, eval_dataset)
  a		:      str       =  tokenize_and_encode(_A       )

  # Compute the max input length for the Transformer
  a		:      List[Any]       =  model.config.n_positions // 2 - 2
  a		:      Dict       =  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		:      List[Any]       =  min(_A				,    model.config.n_positions       )  # Max size of input for the pre-trained model

  # Prepare inputs tensors and dataloaders
  a		:      Tuple       =  pre_process_datasets(_A				,    _A				,    _A				,    *_A       )
  a     ,			a		:      int       =  tensor_datasets[0], tensor_datasets[1]

  a		:      Any       =  TensorDataset(*_A       )
  a		:      Union[str, Any]       =  RandomSampler(_A       )
  a		:      int       =  DataLoader(_A				,    sampler=_A				,    batch_size=args.train_batch_size       )

  a		:      Optional[Any]       =  TensorDataset(*_A       )
  a		:      Union[str, Any]       =  SequentialSampler(_A       )
  a		:      Dict       =  DataLoader(_A				,    sampler=_A				,    batch_size=args.eval_batch_size       )

  # Prepare optimizer
  if args.do_train:
    if args.max_steps > 0:
      a		:      str       =  args.max_steps
      a		:      List[Any]       =  args.max_steps // (len(_A       ) // args.gradient_accumulation_steps) + 1
    else:
      a		:      Optional[Any]       =  len(_A       ) // args.gradient_accumulation_steps * args.num_train_epochs

    a		:      List[Any]       =  list(model.named_parameters()       )
    a		:      Optional[Any]       =  ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
    a		:      List[Any]       =  [
        {
            '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		:      Any       =  AdamW(_A				,    lr=args.learning_rate				,    eps=args.adam_epsilon       )
    a		:      List[str]       =  get_linear_schedule_with_warmup(
        _A				,    num_warmup_steps=args.warmup_steps				,    num_training_steps=_A       )

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

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

    # If we save using the predefined names, we can load using `from_pretrained`
    a		:      Any       =  os.path.join(args.output_dir				,    _A       )
    a		:      int       =  os.path.join(args.output_dir				,    _A       )

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

    # Load a trained model and vocabulary that you have fine-tuned
    a		:      List[Any]       =  OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir       )
    a		:      Optional[int]       =  OpenAIGPTTokenizer.from_pretrained(args.output_dir       )
    model.to(_A       )

  if args.do_eval:
    model.eval()
    a     ,			a		:      Any       =  0, 0
    a     ,			a		:      Tuple       =  0, 0
    for batch in tqdm(_A				,    desc='Evaluating'       ):
      a		:      List[Any]       =  tuple(t.to(_A       ) for t in batch       )
      a     ,			a     ,			a     ,			a		:      str       =  batch
      with torch.no_grad():
        a     ,			a     ,			a     ,			a		:      Optional[Any]       =  model(
            _A				,    mc_token_ids=_A				,    lm_labels=_A				,    mc_labels=_A       )

      a		:      Dict       =  mc_logits.detach().cpu().numpy()
      a		:      Union[str, Any]       =  mc_labels.to('cpu'       ).numpy()
      a		:      List[str]       =  accuracy(_A				,    _A       )

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

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

    a		:      Union[str, Any]       =  eval_loss / nb_eval_steps
    a		:      int       =  eval_accuracy / nb_eval_examples
    a		:      Tuple       =  tr_loss / nb_tr_steps if args.do_train else None
    a		:      Union[str, Any]       =  {'eval_loss': eval_loss, 'eval_accuracy': eval_accuracy, 'train_loss': train_loss}

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


if __name__ == "__main__":
     main()




'''simple docstring'''






import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    StableDiffusionAttendAndExcitePipeline,
    UNetaDConditionModel,
)
from diffusers.utils import load_numpy, skip_mps, slow
from diffusers.utils.testing_utils import require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


lowerCAmelCase:      Any		 =		False

@skip_mps
class 							a__(      lowerCamelCase__	,				lowerCamelCase__	,				lowerCamelCase__	,				unittest.TestCase			):
    lowercase__				=					StableDiffusionAttendAndExcitePipeline
    lowercase__				=					False
    lowercase__				=					TEXT_TO_IMAGE_PARAMS
    lowercase__				=					TEXT_TO_IMAGE_BATCH_PARAMS.union({"""token_indices"""}			)
    lowercase__				=					TEXT_TO_IMAGE_IMAGE_PARAMS
    lowercase__				=					TEXT_TO_IMAGE_IMAGE_PARAMS







    @classmethod
    def     lowercase_ (   cls				:						Union[str, Any]			):
      super().setUpClass()
      torch.use_deterministic_algorithms(__snake_case			)







    @classmethod
    def     lowercase_ (   cls				:						Optional[Any]			):
      super().tearDownClass()
      torch.use_deterministic_algorithms(__snake_case			)







    def     lowercase_ (   self				:						List[Any]			):
      torch.manual_seed(0			)
      a		:      List[Any]       =  UNetaDConditionModel(
          block_out_channels=(32, 64)		,    layers_per_block=1		,    sample_size=32		,    in_channels=4		,    out_channels=4		,    down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')		,    up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')		,    cross_attention_dim=32		,    attention_head_dim=(2, 4)		,    use_linear_projection=__snake_case		,    )
      a		:      Optional[int]       =  DDIMScheduler(
          beta_start=0.00085		,    beta_end=0.012		,    beta_schedule='scaled_linear'		,    clip_sample=__snake_case		,    set_alpha_to_one=__snake_case		,    )
      torch.manual_seed(0			)
      a		:      str       =  AutoencoderKL(
          block_out_channels=[32, 64]		,    in_channels=3		,    out_channels=3		,    down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']		,    up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']		,    latent_channels=4		,    sample_size=1_28		,    )
      torch.manual_seed(0			)
      a		:      str       =  CLIPTextConfig(
          bos_token_id=0		,    eos_token_id=2		,    hidden_size=32		,    intermediate_size=37		,    layer_norm_eps=1e-0_5		,    num_attention_heads=4		,    num_hidden_layers=5		,    pad_token_id=1		,    vocab_size=10_00		,    hidden_act='gelu'		,    projection_dim=5_12		,    )
      a		:      Any       =  CLIPTextModel(__snake_case			)
      a		:      Tuple       =  CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'			)

      a		:      List[str]       =  {
          'unet': unet,
          'scheduler': scheduler,
          'vae': vae,
          'text_encoder': text_encoder,
          'tokenizer': tokenizer,
          'safety_checker': None,
          'feature_extractor': None,
      }

      return components







    def     lowercase_ (   self				:						str		,    __snake_case				:						Tuple		,    __snake_case				:						Optional[int]=0			):
      if str(__snake_case			).startswith('mps'			):
        a		:      Any       =  torch.manual_seed(__snake_case			)
      else:
        a		:      Any       =  torch.Generator(device=__snake_case			).manual_seed(__snake_case			)
      a		:      int       =  {
          'prompt': 'a cat and a frog',
          'token_indices': [2, 5],
          'generator': generator,
          'num_inference_steps': 1,
          'guidance_scale': 6.0,
          'output_type': 'numpy',
          'max_iter_to_alter': 2,
          'thresholds': {0: 0.7},
      }
      return inputs







    def     lowercase_ (   self				:						List[Any]			):
      a		:      Union[str, Any]       =  'cpu'

      a		:      Any       =  self.get_dummy_components()
      a		:      List[str]       =  self.pipeline_class(**__snake_case			)
      pipe.to(__snake_case			)
      pipe.set_progress_bar_config(disable=__snake_case			)

      a		:      Any       =  self.get_dummy_inputs(__snake_case			)
      a		:      int       =  pipe(**__snake_case			).images
      a		:      int       =  image[0, -3:, -3:, -1]

      self.assertEqual(image.shape		,    (1, 64, 64, 3)			)
      a		:      str       =  np.array(
          [0.63905364, 0.62897307, 0.48599017, 0.5133624, 0.5550048, 0.45769516, 0.50326973, 0.5023139, 0.45384496]			)
      a		:      int       =  np.abs(image_slice.flatten() - expected_slice			).max()
      self.assertLessEqual(__snake_case		,    1e-3			)







    def     lowercase_ (   self				:						Dict			):
      super().test_cpu_offload_forward_pass(expected_max_diff=5e-4			)







    def     lowercase_ (   self				:						Tuple			):
      # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
      self._test_inference_batch_consistent(batch_sizes=[1, 2]			)







    def     lowercase_ (   self				:						Union[str, Any]			):
      self._test_inference_batch_single_identical(batch_size=2		,    expected_max_diff=7e-4			)







    def     lowercase_ (   self				:						Tuple			):
      super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3			)







    def     lowercase_ (   self				:						str			):
      super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5e-4			)







    def     lowercase_ (   self				:						Any			):
      super().test_save_load_local(expected_max_difference=5e-4			)







    def     lowercase_ (   self				:						List[Any]			):
      super().test_save_load_optional_components(expected_max_difference=4e-4			)

@require_torch_gpu
@slow
class 							a__(      unittest.TestCase			):







    @classmethod
    def     lowercase_ (   cls				:						Union[str, Any]			):
      super().setUpClass()
      torch.use_deterministic_algorithms(__snake_case			)







    @classmethod
    def     lowercase_ (   cls				:						Union[str, Any]			):
      super().tearDownClass()
      torch.use_deterministic_algorithms(__snake_case			)







    def     lowercase_ (   self				:						Union[str, Any]			):
      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()







    def     lowercase_ (   self				:						Optional[Any]			):
      a		:      List[Any]       =  torch.manual_seed(51			)

      a		:      Dict       =  StableDiffusionAttendAndExcitePipeline.from_pretrained(
          'CompVis/stable-diffusion-v1-4'		,    safety_checker=__snake_case		,    torch_dtype=torch.floataa			)
      pipe.to('cuda'			)

      a		:      Optional[Any]       =  'a painting of an elephant with glasses'
      a		:      Any       =  [5, 7]

      a		:      Tuple       =  pipe(
          prompt=__snake_case		,    token_indices=__snake_case		,    guidance_scale=7.5		,    generator=__snake_case		,    num_inference_steps=5		,    max_iter_to_alter=5		,    output_type='numpy'		,    ).images[0]

      a		:      str       =  load_numpy(
          'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy'			)
      assert np.abs((expected_image - image).max()			) < 5e-1