

'''simple docstring'''







import argparse
import random

import joblib
import numpy as np
import torch
from igf.igf import (
    SecondaryLearner,
    collect_objective_set,
    compute_perplexity,
    generate_datasets,
    load_gpta,
    recopy_gpta,
    set_seed,
    train_secondary_learner,
)
from torch.utils.data import DataLoader, RandomSampler

from transformers import GPTaLMHeadModel
def       UpperCAmelCase__    (      UpperCAmelCase__=32,       UpperCAmelCase__=10,       UpperCAmelCase__=1_00,       UpperCAmelCase__=10_26,       UpperCAmelCase__=True,       UpperCAmelCase__="data/tokenized_stories_train_wikitext103.jbl",       UpperCAmelCase__="igf_context_pairs.jbl",       )			->			List[str]:
       set_seed(3				)
       # generate train_data and objective_set
       A_					,			A_						=      generate_datasets(
           UpperCAmelCase__,       UpperCAmelCase__,       number=UpperCAmelCase__,       min_len=10_26,       trim=UpperCAmelCase__				)
       # keeps model same across runs
       set_seed(4				)
       # model, lm_optimizer, lm_scheduler = recopy_gpt2(model, device, max_steps) # store original model weights
       # can we train on GPU?
       A_						=      torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu"""				)

       # load pretrained model
       A_						=      load_gpta("""gpt2"""				).to(UpperCAmelCase__				)
       print("""computing perplexity on objective set"""				)
       A_						=      compute_perplexity(UpperCAmelCase__,       UpperCAmelCase__,       UpperCAmelCase__				).item()
       print("""perplexity on objective set:""",       UpperCAmelCase__				)

       # collect igf pairs and save to file demo.jbl
       collect_objective_set(UpperCAmelCase__,       UpperCAmelCase__,       UpperCAmelCase__,       UpperCAmelCase__,       UpperCAmelCase__,       UpperCAmelCase__,       UpperCAmelCase__,       UpperCAmelCase__				)

       # clean up, delete model and data we don't need anymore
       del model, train_data, objective_set
       torch.cuda.empty_cache()
def       UpperCAmelCase__    (      UpperCAmelCase__,       UpperCAmelCase__=15,       UpperCAmelCase__=1_28,       UpperCAmelCase__=1_00,       UpperCAmelCase__="igf_model.pt",       )			->			List[Any]:
       set_seed(42				)

       # Load pre-trained model
       A_						=      GPTaLMHeadModel.from_pretrained("""gpt2"""				)

       # Initialize secondary learner to use embedding weights of model
       A_						=      SecondaryLearner(UpperCAmelCase__				)

       # Train secondary learner
       A_						=      train_secondary_learner(
           UpperCAmelCase__,       UpperCAmelCase__,       max_epochs=UpperCAmelCase__,       batch_size=UpperCAmelCase__,       eval_freq=1_00,       igf_model_path=UpperCAmelCase__,       )

       del model, secondary_learner_train_data
       torch.cuda.empty_cache()

       return secondary_learner
def       UpperCAmelCase__    (      UpperCAmelCase__,       UpperCAmelCase__,       UpperCAmelCase__,       UpperCAmelCase__=32,       UpperCAmelCase__=10_00,       UpperCAmelCase__=16,       UpperCAmelCase__=1.0,       UpperCAmelCase__=recopy_gpta,       UpperCAmelCase__=None,       UpperCAmelCase__=10,       UpperCAmelCase__="gpt2_finetuned.pt",       )			->			Optional[Any]:
       A_						=      torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu"""				)
       A_						=      RandomSampler(UpperCAmelCase__				)
       A_						=      DataLoader(UpperCAmelCase__,       sampler=UpperCAmelCase__				)

       A_						=      max_steps // (len(UpperCAmelCase__				)) + 1
       A_						=      0
       A_						=      torch.zeros((1, context_len),       dtype=torch.long,       device=UpperCAmelCase__				)
       A_					,			A_					,			A_						=      recopy_model(UpperCAmelCase__,       UpperCAmelCase__,       UpperCAmelCase__				)

       model.train()
       if secondary_learner is not None:
              secondary_learner.to(UpperCAmelCase__				)
              secondary_learner.eval()
       A_						=      []
       A_						=      0

       A_						=      []
       A_						=      []

       # Compute the performance of the transformer model at the beginning
       A_						=      compute_perplexity(UpperCAmelCase__,       UpperCAmelCase__,       UpperCAmelCase__				)
       test_perps.append(UpperCAmelCase__				)
       print("""Test perplexity, step""",       UpperCAmelCase__,       """:""",       UpperCAmelCase__				)
       for epoch in range(int(UpperCAmelCase__				)				):
              for step, example in enumerate(UpperCAmelCase__				):
                     torch.cuda.empty_cache()
                     A_						=      random.randint(0,       example.size(2				) - context_len - 1				)
                     A_						=      example[0, 0, start : start + context_len]
                     lm_optimizer.zero_grad()
                     A_						=      model(UpperCAmelCase__,       labels=UpperCAmelCase__				)
                     A_						=      True

                     if secondary_learner is not None:
                            A_						=      secondary_learner.forward(
                                torch.tensor(UpperCAmelCase__,       dtype=torch.long,       device=UpperCAmelCase__				).unsqueeze(0				)				)[0].item()
                            observed_qs.append(float(UpperCAmelCase__				)				)

                            # Here we implement the simple non-constant threshold for the predicted IG(X) value
                            # We will decay the selectivity of our secondary learner filter from
                            # 1 standard deviation above average to 1 below average after 10 batches.

                            if global_step == 10:
                                   A_						=      -1
                            if predicted_q < threshold:
                                   A_						=      False

            # If we passed the filter, add the context to the batch!
                     if do_backprop:
                            contexts.append(np.array(context.cpu()				)				)
                            A_						=      outputs[0]
                            lm_loss.backward()
                            examples += 1

                     del outputs

                     # Once the batch is filled with enough contexts, backprop on the batch.
                     if examples == batch_size:
                            torch.cuda.empty_cache()
                            A_						=      0
                            # Do LM backprop
                            torch.nn.utils.clip_grad_norm_(model.parameters(),       3.0				)
                            lm_optimizer.step()
                            lm_scheduler.step()  # Update learning rate schedule
                            global_step += 1
                            # Compute the performance of the transformer model at this batch
                            if global_step % eval_interval == 0:
                                   A_						=      compute_perplexity(UpperCAmelCase__,       UpperCAmelCase__,       UpperCAmelCase__				)
                                   test_perps.append(UpperCAmelCase__				)

                                   print("""Test perplexity, step""",       UpperCAmelCase__,       """:""",       UpperCAmelCase__				)
            # Break out of the loop after 60 batches
                     if max_steps > 0 and global_step > 60:
                            break
              if max_steps > 0 and global_step > 60:
                     break

    # save finetuned transformer model
       torch.save(model.state_dict(),       UpperCAmelCase__				)
       torch.cuda.empty_cache()
       # Do some cleaning up so we can reinitialize for the next run of this function
       del lm_optimizer
       del lm_scheduler
       return model
def       UpperCAmelCase__    (      )			->			Optional[Any]:
       A_						=      argparse.ArgumentParser(description="""Fine-tune a transformer model with IGF on a language modeling task"""				)

       # Required parameters
       parser.add_argument(
           """--data_dir""",       default=UpperCAmelCase__,       type=UpperCAmelCase__,       required=UpperCAmelCase__,       help="""The input data dir. Should contain data files for WikiText.""",       )
       parser.add_argument(
           """--model_name_or_path""",       default=UpperCAmelCase__,       type=UpperCAmelCase__,       required=UpperCAmelCase__,       help="""Path to pretrained model or model identifier from huggingface.co/models""",       )
       parser.add_argument(
           """--data_file""",       type=UpperCAmelCase__,       default=UpperCAmelCase__,       help=(
               """A jbl file containing tokenized data which can be split as objective dataset, """
               """train_dataset and test_dataset."""
           ),       )

       parser.add_argument(
           """--igf_data_file""",       type=UpperCAmelCase__,       default=UpperCAmelCase__,       help="""A jbl file containing the context and information gain pairs to train secondary learner.""",       )

       parser.add_argument(
           """--output_dir""",       default=UpperCAmelCase__,       type=UpperCAmelCase__,       required=UpperCAmelCase__,       help="""The output directory where the final fine-tuned model is stored.""",       )

       parser.add_argument(
           """--tokenizer_name""",       default=UpperCAmelCase__,       type=UpperCAmelCase__,       help="""Pretrained tokenizer name or path if not the same as model_name""",       )
       parser.add_argument("""--seed""",       type=UpperCAmelCase__,       default=UpperCAmelCase__,       help="""A seed for reproducible training."""				)

       parser.add_argument(
           """--context_len""",       default=32,       type=UpperCAmelCase__,       help=(
               """The maximum total input sequence length after tokenization. Sequences longer """
               """than this will be truncated, sequences shorter will be padded."""
           ),       )

       parser.add_argument(
           """--size_objective_set""",       default=1_00,       type=UpperCAmelCase__,       help="""number of articles that are long enough to be used as our objective set""",       )
       parser.add_argument(
           """--eval_freq""",       default=1_00,       type=UpperCAmelCase__,       help="""secondary model evaluation is triggered at eval_freq"""				)

       parser.add_argument("""--max_steps""",       default=10_00,       type=UpperCAmelCase__,       help="""To calculate training epochs"""				)

       parser.add_argument(
           """--secondary_learner_batch_size""",       default=1_28,       type=UpperCAmelCase__,       help="""batch size of training data for secondary learner""",       )

       parser.add_argument(
           """--batch_size""",       default=16,       type=UpperCAmelCase__,       help="""batch size of training data of language model(gpt2) """				)

       parser.add_argument(
           """--eval_interval""",       default=10,       type=UpperCAmelCase__,       help=(
               """decay the selectivity of our secondary learner filter from"""
               """1 standard deviation above average to 1 below average after 10 batches"""
           ),       )

       parser.add_argument(
           """--number""",       default=1_00,       type=UpperCAmelCase__,       help="""The number of examples split to be used as objective_set/test_data"""				)

       parser.add_argument(
           """--min_len""",       default=10_26,       type=UpperCAmelCase__,       help="""The minimum length of the article to be used as objective set"""				)

       parser.add_argument(
           """--secondary_learner_max_epochs""",       default=15,       type=UpperCAmelCase__,       help="""number of epochs to train secondary learner"""				)

       parser.add_argument("""--trim""",       default=UpperCAmelCase__,       type=UpperCAmelCase__,       help="""truncate the example if it exceeds context length"""				)

       parser.add_argument(
           """--threshold""",       default=1.0,       type=UpperCAmelCase__,       help=(
               """The threshold value used by secondary learner to filter the train_data and allow only"""
               """ informative data as input to the model"""
           ),       )

       parser.add_argument("""--finetuned_model_name""",       default="""gpt2_finetuned.pt""",       type=UpperCAmelCase__,       help="""finetuned_model_name"""				)

       parser.add_argument(
           """--recopy_model""",       default=UpperCAmelCase__,       type=UpperCAmelCase__,       help="""Reset the model to the original pretrained GPT-2 weights after each iteration""",       )

       # function calls
       # Collecting *n* pairs of context and information gain(X, IG(X)) for training the secondary learner
       generate_n_pairs(
           context_len=32,       max_steps=10,       size_objective_set=1_00,       min_len=10_26,       trim=UpperCAmelCase__,       data_file="""data/tokenized_stories_train_wikitext103.jbl""",       igf_data_file="""igf_context_pairs.jbl""",       )

       # Load train data for secondary learner
       A_						=      joblib.load("""data/IGF_values.jbl"""				)

       # Train secondary learner
       A_						=      training_secondary_learner(
           UpperCAmelCase__,       secondary_learner_max_epochs=15,       secondary_learner_batch_size=1_28,       eval_freq=1_00,       igf_model_path="""igf_model.pt""",       )

       # load pretrained gpt2 model
       A_						=      GPTaLMHeadModel.from_pretrained("""gpt2"""				)
       set_seed(42				)

       # Generate train and test data to train and evaluate gpt2 model
       A_					,			A_						=      generate_datasets(
           context_len=32,       file="""data/tokenized_stories_train_wikitext103.jbl""",       number=1_00,       min_len=10_26,       trim=UpperCAmelCase__				)

       # fine-tuning of the gpt2 model using igf (Information Gain Filtration)
       finetune(
           UpperCAmelCase__,       UpperCAmelCase__,       UpperCAmelCase__,       context_len=32,       max_steps=10_00,       batch_size=16,       threshold=1.0,       recopy_model=UpperCAmelCase__,       secondary_learner=UpperCAmelCase__,       eval_interval=10,       finetuned_model_name="""gpt2_finetuned.pt""",       )


if __name__ == "__main__":
      main()



'''simple docstring'''







import unittest

import numpy as np
import torch
from torch import nn
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()


class 					A__      (      _snake_case						,						unittest.TestCase			):
    lowercase						=		KandinskyVaaPriorPipeline
    lowercase						=		["prompt"]
    lowercase						=		["prompt", "negative_prompt"]
    lowercase						=		[
        "num_images_per_prompt",
        "generator",
        "num_inference_steps",
        "latents",
        "negative_prompt",
        "guidance_scale",
        "output_type",
        "return_dict",
    ]
    lowercase						=		False



    @property
    def 					snake_case_			(					self       )						->      Any:





           '''simple docstring'''
           return 32



    @property
    def 					snake_case_			(					self       )						->      Optional[int]:





           '''simple docstring'''
           return 32



    @property
    def 					snake_case_			(					self       )						->      Optional[Any]:





           '''simple docstring'''
           return self.time_input_dim



    @property
    def 					snake_case_			(					self       )						->      str:





           '''simple docstring'''
           return self.time_input_dim * 4



    @property
    def 					snake_case_			(					self       )						->      int:





           '''simple docstring'''
           return 100



    @property
    def 					snake_case_			(					self       )						->      Optional[Any]:





           '''simple docstring'''
           A_						=      CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""       )
           return tokenizer



    @property
    def 					snake_case_			(					self       )						->      Union[str, Any]:





           '''simple docstring'''
           torch.manual_seed(0       )
           A_						=      CLIPTextConfig(
               bos_token_id=0		,				eos_token_id=2		,				hidden_size=self.text_embedder_hidden_size		,				projection_dim=self.text_embedder_hidden_size		,				intermediate_size=37		,				layer_norm_eps=1e-0_5		,				num_attention_heads=4		,				num_hidden_layers=5		,				pad_token_id=1		,				vocab_size=1000		,				)
           return CLIPTextModelWithProjection(UpperCamelCase__       )



    @property
    def 					snake_case_			(					self       )						->      Tuple:





           '''simple docstring'''
           torch.manual_seed(0       )

           A_						=      {
               """num_attention_heads""": 2,
               """attention_head_dim""": 12,
               """embedding_dim""": self.text_embedder_hidden_size,
               """num_layers""": 1,
           }

           A_						=      PriorTransformer(**UpperCamelCase__       )
           # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
           A_						=      nn.Parameter(torch.ones(model.clip_std.shape       )       )
           return model



    @property
    def 					snake_case_			(					self       )						->      str:





           '''simple docstring'''
           torch.manual_seed(0       )
           A_						=      CLIPVisionConfig(
               hidden_size=self.text_embedder_hidden_size		,				image_size=224		,				projection_dim=self.text_embedder_hidden_size		,				intermediate_size=37		,				num_attention_heads=4		,				num_channels=3		,				num_hidden_layers=5		,				patch_size=14		,				)

           A_						=      CLIPVisionModelWithProjection(UpperCamelCase__       )
           return model



    @property
    def 					snake_case_			(					self       )						->      str:





           '''simple docstring'''
           A_						=      CLIPImageProcessor(
               crop_size=224		,				do_center_crop=UpperCamelCase__		,				do_normalize=UpperCamelCase__		,				do_resize=UpperCamelCase__		,				image_mean=[0.48145466, 0.4578275, 0.40821073]		,				image_std=[0.26862954, 0.26130258, 0.27577711]		,				resample=3		,				size=224		,				)

           return image_processor



    def 					snake_case_			(					self       )						->      Union[str, Any]:





           '''simple docstring'''
           A_						=      self.dummy_prior
           A_						=      self.dummy_image_encoder
           A_						=      self.dummy_text_encoder
           A_						=      self.dummy_tokenizer
           A_						=      self.dummy_image_processor

           A_						=      UnCLIPScheduler(
               variance_type="""fixed_small_log"""		,				prediction_type="""sample"""		,				num_train_timesteps=1000		,				clip_sample=UpperCamelCase__		,				clip_sample_range=10.0		,				)

           A_						=      {
               """prior""": prior,
               """image_encoder""": image_encoder,
               """text_encoder""": text_encoder,
               """tokenizer""": tokenizer,
               """scheduler""": scheduler,
               """image_processor""": image_processor,
           }

           return components



    def 					snake_case_			(					self		,				UpperCamelCase__		,				UpperCamelCase__=0       )						->      Optional[int]:





           '''simple docstring'''
           if str(UpperCamelCase__       ).startswith("""mps"""       ):
                  A_						=      torch.manual_seed(UpperCamelCase__       )
           else:
                  A_						=      torch.Generator(device=UpperCamelCase__       ).manual_seed(UpperCamelCase__       )
           A_						=      {
               """prompt""": """horse""",
               """generator""": generator,
               """guidance_scale""": 4.0,
               """num_inference_steps""": 2,
               """output_type""": """np""",
           }
           return inputs



    def 					snake_case_			(					self       )						->      List[str]:





           '''simple docstring'''
           A_						=      """cpu"""

           A_						=      self.get_dummy_components()

           A_						=      self.pipeline_class(**UpperCamelCase__       )
           A_						=      pipe.to(UpperCamelCase__       )

           pipe.set_progress_bar_config(disable=UpperCamelCase__       )

           A_						=      pipe(**self.get_dummy_inputs(UpperCamelCase__       )       )
           A_						=      output.image_embeds

           A_						=      pipe(
               **self.get_dummy_inputs(UpperCamelCase__       )		,				return_dict=UpperCamelCase__		,				)[0]

           A_						=      image[0, -10:]
           A_						=      image_from_tuple[0, -10:]

           assert image.shape == (1, 32)

           A_						=      np.array(
               [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156]       )

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



    @skip_mps
    def 					snake_case_			(					self       )						->      int:





           '''simple docstring'''
           A_						=      torch_device == """cpu"""
           A_						=      True
           A_						=      False

           self._test_inference_batch_single_identical(
               test_max_difference=UpperCamelCase__		,				relax_max_difference=UpperCamelCase__		,				test_mean_pixel_difference=UpperCamelCase__		,				)







    @skip_mps
    def 					snake_case_			(					self       )						->      Union[str, Any]:





           '''simple docstring'''
           A_						=      torch_device == """cpu"""
           A_						=      False

           self._test_attention_slicing_forward_pass(
               test_max_difference=UpperCamelCase__		,				test_mean_pixel_difference=UpperCamelCase__		,				)
