

from manim import *



class        _UpperCAmelCase (   __lowercase			):
  '''simple docstring'''







  def 	UpperCamelCase       ( self	: List[Any] ):
        A    =				Rectangle(height=0.5		,						width=0.5 )
        A    =				Rectangle(height=0.46		,						width=0.46 ).set_stroke(width=0 )
        A    =				Rectangle(height=0.25		,						width=0.25 )

        A    =				[mem.copy() for i in range(6 )]
        A    =				[mem.copy() for i in range(6 )]
        A    =				VGroup(*UpperCamelCase__ ).arrange(UpperCamelCase__		,						buff=0 )
        A    =				VGroup(*UpperCamelCase__ ).arrange(UpperCamelCase__		,						buff=0 )
        A    =				VGroup(UpperCamelCase__		,						UpperCamelCase__ ).arrange(UpperCamelCase__		,						buff=0 )
        A    =				Text('CPU'		,						font_size=24 )
        A    =				Group(UpperCamelCase__		,						UpperCamelCase__ ).arrange(UpperCamelCase__		,						buff=0.5		,						aligned_edge=UpperCamelCase__ )
        cpu.move_to([-2.5, -0.5, 0] )
        self.add(UpperCamelCase__ )

        A    =				[mem.copy() for i in range(4 )]
        A    =				VGroup(*UpperCamelCase__ ).arrange(UpperCamelCase__		,						buff=0 )
        A    =				Text('GPU'		,						font_size=24 )
        A    =				Group(UpperCamelCase__		,						UpperCamelCase__ ).arrange(UpperCamelCase__		,						buff=0.5		,						aligned_edge=UpperCamelCase__ )
        gpu.move_to([-1, -1, 0] )
        self.add(UpperCamelCase__ )

        A    =				[mem.copy() for i in range(6 )]
        A    =				VGroup(*UpperCamelCase__ ).arrange(UpperCamelCase__		,						buff=0 )

        A    =				Text('Model'		,						font_size=24 )
        A    =				Group(UpperCamelCase__		,						UpperCamelCase__ ).arrange(UpperCamelCase__		,						buff=0.5		,						aligned_edge=UpperCamelCase__ )
        model.move_to([3, -1.0, 0] )
        self.add(UpperCamelCase__ )

        A    =				[]
        A    =				[]

        for i, rect in enumerate(UpperCamelCase__ ):
              rect.set_stroke(UpperCamelCase__ )

              A    =				Rectangle(height=0.46 / 4		,						width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(UpperCamelCase__		,						opacity=0.7 )

              if i == 0:
                    cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT )		,						buff=0.02		,						direction=UpperCamelCase__ )
                    cpu_target.set_x(cpu_target.get_x() + 0.1 )
              elif i == 3:
                    cpu_target.next_to(model_cpu_arr[0]		,						direction=UpperCamelCase__		,						buff=0.0 )
              else:
                    cpu_target.next_to(model_cpu_arr[i - 1]		,						direction=UpperCamelCase__		,						buff=0.0 )
              self.add(UpperCamelCase__ )
              model_cpu_arr.append(UpperCamelCase__ )

        self.add(*UpperCamelCase__		,						*UpperCamelCase__ )

        A    =				[meta_mem.copy() for i in range(6 )]
        A    =				[meta_mem.copy() for i in range(6 )]
        A    =				VGroup(*UpperCamelCase__ ).arrange(UpperCamelCase__		,						buff=0 )
        A    =				VGroup(*UpperCamelCase__ ).arrange(UpperCamelCase__		,						buff=0 )
        A    =				VGroup(UpperCamelCase__		,						UpperCamelCase__ ).arrange(UpperCamelCase__		,						buff=0 )
        A    =				Text('Disk'		,						font_size=24 )
        A    =				Group(UpperCamelCase__		,						UpperCamelCase__ ).arrange(UpperCamelCase__		,						buff=0.5		,						aligned_edge=UpperCamelCase__ )
        disk.move_to([-4.0, -1.25, 0] )
        self.add(UpperCamelCase__		,						UpperCamelCase__ )

        A    =				[]

        for i in range(6 ):
              A    =				fill.copy().set_fill(UpperCamelCase__		,						opacity=0.8 )
              target.move_to(disk_left_col_base[i] ).scale(0.5 )
              cpu_disk_arr.append(UpperCamelCase__ )

        self.add(*UpperCamelCase__ )

        A    =				Square(side_length=2.2 )
        key.move_to([-5, 2, 0] )

        A    =				MarkupText(
            f'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model'''		,						font_size=18		,						)

        key_text.move_to([-5, 2.4, 0] )

        self.add(UpperCamelCase__		,						UpperCamelCase__ )

        A    =				MarkupText(
            f'''<span fgcolor=\'{BLUE}\'>●</span> Checkpoint'''		,						font_size=18		,						)

        blue_text.next_to(UpperCamelCase__		,						DOWN * 2.4		,						aligned_edge=key_text.get_left() )
        self.add(UpperCamelCase__ )

        A    =				MarkupText(f'''The offloaded weights are all sent to the CPU.'''		,						font_size=24 )
        step_a.move_to([2, 2, 0] )

        self.play(Write(UpperCamelCase__		,						run_time=3 ) )

        for i in range(6 ):
              A    =				cpu_disk_arr[i]
              A    =				rect.copy().set_fill(UpperCamelCase__		,						opacity=0.8 ).scale(2.0 )
              cpa.generate_target()
              cpa.target.move_to(model_base[i] )

              if i == 0:
                    rect.set_fill(UpperCamelCase__		,						opacity=0.8 )
                    rect.generate_target()
                    rect.target.move_to(cpu_left_col_base[0] ).scale(2.0 )

                    self.remove(
                        *UpperCamelCase__		,						*UpperCamelCase__		,						)

              else:
                    rect.generate_target()
                    rect.target.move_to(cpu_left_col_base[i] ).scale(2.0 )
              self.play(MoveToTarget(UpperCamelCase__ )		,						MoveToTarget(UpperCamelCase__ )		,						model_base[i].animate.set_stroke(UpperCamelCase__ ) )
        self.play(FadeOut(UpperCamelCase__ ) )

        A    =				MarkupText(
            f'''Finally, hooks are added to each weight in the model\nto transfer the weights from CPU to GPU\n\t\tand back when needed.'''		,						font_size=24		,						)
        step_a.move_to([2, 2, 0] )

        self.play(Write(UpperCamelCase__		,						run_time=3 ) )

        A    =				[]
        A    =				[]
        for i in range(6 ):
              A    =				Arrow(start=UpperCamelCase__		,						end=UpperCamelCase__		,						color=UpperCamelCase__		,						buff=0.5 )
              a.next_to(model_base[i].get_left()		,						UpperCamelCase__		,						buff=0.2 )
              arrows.append(UpperCamelCase__ )
              animations.append(Write(UpperCamelCase__ ) )
        self.play(*UpperCamelCase__ )
        self.wait()






import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional

import transformers
from transformers import (
    AutoConfig,
    AutoModelForQuestionAnswering,
    AutoTokenizer,
    DataCollatorWithPadding,
    HfArgumentParser,
    SquadDataset,
    Trainer,
    TrainingArguments,
)
from transformers import SquadDataTrainingArguments as DataTrainingArguments
from transformers.trainer_utils import is_main_process


_UpperCAmelCase    	=			logging.getLogger(__name__)



@dataclass
class        _UpperCAmelCase :
  '''simple docstring'''







  SCREAMING_SNAKE_CASE							:				str					      =				field(
      metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}			)
  SCREAMING_SNAKE_CASE							:				Optional[str]					      =				field(
      default=__lowercase     ,				metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''}			)
  SCREAMING_SNAKE_CASE							:				Optional[str]					      =				field(
      default=__lowercase     ,				metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''}			)
  SCREAMING_SNAKE_CASE							:				bool					      =				field(default=__lowercase     ,				metadata={'''help''': '''Set this flag to use fast tokenization.'''}			)
  # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script,
  # or just modify its tokenizer_config.json.
  SCREAMING_SNAKE_CASE							:				Optional[str]					      =				field(
      default=__lowercase     ,				metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}     ,				)


def 			__UpperCamelCase    ()     ->  Tuple:
      # See all possible arguments in src/transformers/training_args.py
      # or by passing the --help flag to this script.
      # We now keep distinct sets of args, for a cleaner separation of concerns.

      A    =				HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)     )

      if len(sys.argv     ) == 2 and sys.argv[1].endswith('.json'     ):
            # If we pass only one argument to the script and it's the path to a json file,
            # let's parse it to get our arguments.
            A ,	A ,	A    =				parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]     )     )
      else:
            A ,	A ,	A    =				parser.parse_args_into_dataclasses()

      if (
          os.path.exists(training_args.output_dir     )
          and os.listdir(training_args.output_dir     )
          and training_args.do_train
          and not training_args.overwrite_output_dir
      ):
            raise ValueError(
                f'''Output directory ({training_args.output_dir}) already exists and is not empty. Use'''
                ' --overwrite_output_dir to overcome.'     )

      # Setup logging
      logging.basicConfig(
          format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',    datefmt='%m/%d/%Y %H:%M:%S',    level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN,    )
      logger.warning(
          'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s',    training_args.local_rank,    training_args.device,    training_args.n_gpu,    bool(training_args.local_rank != -1     ),    training_args.fpaa,    )
      # Set the verbosity to info of the Transformers logger (on main process only):
      if is_main_process(training_args.local_rank     ):
            transformers.utils.logging.set_verbosity_info()
            transformers.utils.logging.enable_default_handler()
            transformers.utils.logging.enable_explicit_format()
      logger.info('Training/evaluation parameters %s',    lowerCAmelCase     )

      # Prepare Question-Answering task
      # Load pretrained model and tokenizer
      #
      # Distributed training:
      # The .from_pretrained methods guarantee that only one local process can concurrently
      # download model & vocab.

      A    =				AutoConfig.from_pretrained(
          model_args.config_name if model_args.config_name else model_args.model_name_or_path,    cache_dir=model_args.cache_dir,    )
      A    =				AutoTokenizer.from_pretrained(
          model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,    cache_dir=model_args.cache_dir,    use_fast=lowerCAmelCase,    )
      A    =				AutoModelForQuestionAnswering.from_pretrained(
          model_args.model_name_or_path,    from_tf=bool('.ckpt' in model_args.model_name_or_path     ),    config=lowerCAmelCase,    cache_dir=model_args.cache_dir,    )

      # Get datasets
      A    =				hasattr(model.config,    'lang2id'     )
      A    =				(
          SquadDataset(
              lowerCAmelCase,    tokenizer=lowerCAmelCase,    is_language_sensitive=lowerCAmelCase,    cache_dir=model_args.cache_dir     )
          if training_args.do_train
          else None
      )
      A    =				(
          SquadDataset(
              lowerCAmelCase,    tokenizer=lowerCAmelCase,    mode='dev',    is_language_sensitive=lowerCAmelCase,    cache_dir=model_args.cache_dir,    )
          if training_args.do_eval
          else None
      )

      # Data collator
      A    =				DataCollatorWithPadding(lowerCAmelCase,    pad_to_multiple_of=8     ) if training_args.fpaa else None

      # Initialize our Trainer
      A    =				Trainer(
          model=lowerCAmelCase,    args=lowerCAmelCase,    train_dataset=lowerCAmelCase,    eval_dataset=lowerCAmelCase,    data_collator=lowerCAmelCase,    )

      # Training
      if training_args.do_train:
            trainer.train(
                model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path     ) else None     )
            trainer.save_model()
            # For convenience, we also re-save the tokenizer to the same directory,
            # so that you can share your model easily on huggingface.co/models =)
            if trainer.is_world_master():
                  tokenizer.save_pretrained(training_args.output_dir     )


def 			__UpperCamelCase    (lowerCAmelCase					:  Tuple     )     ->  List[Any]:
      # For xla_spawn (TPUs)
      main()


if __name__ == "__main__":
  main()



