





import flax.linen as nn
import jax.numpy as jnp

from .attention_flax import FlaxTransformeraDModel
from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD
class     __lowerCAmelCase					(   nn.Module			):






       """simple docstring"""
       _snake_case     :					Union[str, Any]						    =   4_2
       _snake_case     :					List[str]						    =   4_2
       _snake_case     :					str						    =   0.0
       _snake_case     :					Tuple						    =   1
       _snake_case     :					Optional[int]						    =   1
       _snake_case     :					Tuple						    =   True
       _snake_case     :					List[str]						    =   False
       _snake_case     :					Any						    =   False
       _snake_case     :					List[str]						    =   False
       _snake_case     :					Any						    =   jnp.floataa





       def snake_case__						(							self       :		Optional[int]					)   ->					Optional[int]:

            '''simple docstring'''




            _UpperCamelCase       =	[]
            _UpperCamelCase       =	[]

            for i in range(self.num_layers					):
                 _UpperCamelCase       =	self.in_channels if i == 0 else self.out_channels

                 _UpperCamelCase       =	FlaxResnetBlockaD(
                     in_channels=lowercase_	,			out_channels=self.out_channels	,			dropout_prob=self.dropout	,			dtype=self.dtype	,			)
                 resnets.append(lowercase_					)

                 _UpperCamelCase       =	FlaxTransformeraDModel(
                     in_channels=self.out_channels	,			n_heads=self.num_attention_heads	,			d_head=self.out_channels // self.num_attention_heads	,			depth=1	,			use_linear_projection=self.use_linear_projection	,			only_cross_attention=self.only_cross_attention	,			use_memory_efficient_attention=self.use_memory_efficient_attention	,			dtype=self.dtype	,			)
                 attentions.append(lowercase_					)

            _UpperCamelCase       =	resnets
            _UpperCamelCase       =	attentions

            if self.add_downsample:
                 _UpperCamelCase       =	FlaxDownsampleaD(self.out_channels	,			dtype=self.dtype					)







       def __call__(							self       :		int	,			lowerCAmelCase__       :		str	,			lowerCAmelCase__       :		List[str]	,			lowerCAmelCase__       :		Union[str, Any]	,			lowerCAmelCase__       :		Union[str, Any]=True					)   ->					Optional[Any]:

            '''simple docstring'''




            _UpperCamelCase       =	()

            for resnet, attn in zip(self.resnets	,			self.attentions					):
                 _UpperCamelCase       =	resnet(lowercase_	,			lowercase_	,			deterministic=lowercase_					)
                 _UpperCamelCase       =	attn(lowercase_	,			lowercase_	,			deterministic=lowercase_					)
                 output_states += (hidden_states,)

            if self.add_downsample:
                 _UpperCamelCase       =	self.downsamplers_a(lowercase_					)
                 output_states += (hidden_states,)

            return hidden_states, output_states

class     __lowerCAmelCase					(   nn.Module			):






       """simple docstring"""
       _snake_case     :					Tuple						    =   4_2
       _snake_case     :					Tuple						    =   4_2
       _snake_case     :					List[Any]						    =   0.0
       _snake_case     :					int						    =   1
       _snake_case     :					List[Any]						    =   True
       _snake_case     :					Tuple						    =   jnp.floataa





       def snake_case__						(							self       :		str					)   ->					Tuple:

            '''simple docstring'''




            _UpperCamelCase       =	[]

            for i in range(self.num_layers					):
                 _UpperCamelCase       =	self.in_channels if i == 0 else self.out_channels

                 _UpperCamelCase       =	FlaxResnetBlockaD(
                     in_channels=lowercase_	,			out_channels=self.out_channels	,			dropout_prob=self.dropout	,			dtype=self.dtype	,			)
                 resnets.append(lowercase_					)
            _UpperCamelCase       =	resnets

            if self.add_downsample:
                 _UpperCamelCase       =	FlaxDownsampleaD(self.out_channels	,			dtype=self.dtype					)







       def __call__(							self       :		Dict	,			lowerCAmelCase__       :		int	,			lowerCAmelCase__       :		Dict	,			lowerCAmelCase__       :		Tuple=True					)   ->					Any:

            '''simple docstring'''




            _UpperCamelCase       =	()

            for resnet in self.resnets:
                 _UpperCamelCase       =	resnet(lowercase_	,			lowercase_	,			deterministic=lowercase_					)
                 output_states += (hidden_states,)

            if self.add_downsample:
                 _UpperCamelCase       =	self.downsamplers_a(lowercase_					)
                 output_states += (hidden_states,)

            return hidden_states, output_states

class     __lowerCAmelCase					(   nn.Module			):






       """simple docstring"""
       _snake_case     :					int						    =   4_2
       _snake_case     :					List[str]						    =   4_2
       _snake_case     :					Optional[Any]						    =   4_2
       _snake_case     :					Union[str, Any]						    =   0.0
       _snake_case     :					Optional[int]						    =   1
       _snake_case     :					List[str]						    =   1
       _snake_case     :					List[Any]						    =   True
       _snake_case     :					Optional[int]						    =   False
       _snake_case     :					List[str]						    =   False
       _snake_case     :					int						    =   False
       _snake_case     :					Any						    =   jnp.floataa





       def snake_case__						(							self       :		int					)   ->					List[str]:

            '''simple docstring'''




            _UpperCamelCase       =	[]
            _UpperCamelCase       =	[]

            for i in range(self.num_layers					):
                 _UpperCamelCase       =	self.in_channels if (i == self.num_layers - 1) else self.out_channels
                 _UpperCamelCase       =	self.prev_output_channel if i == 0 else self.out_channels

                 _UpperCamelCase       =	FlaxResnetBlockaD(
                     in_channels=resnet_in_channels + res_skip_channels	,			out_channels=self.out_channels	,			dropout_prob=self.dropout	,			dtype=self.dtype	,			)
                 resnets.append(lowercase_					)

                 _UpperCamelCase       =	FlaxTransformeraDModel(
                     in_channels=self.out_channels	,			n_heads=self.num_attention_heads	,			d_head=self.out_channels // self.num_attention_heads	,			depth=1	,			use_linear_projection=self.use_linear_projection	,			only_cross_attention=self.only_cross_attention	,			use_memory_efficient_attention=self.use_memory_efficient_attention	,			dtype=self.dtype	,			)
                 attentions.append(lowercase_					)

            _UpperCamelCase       =	resnets
            _UpperCamelCase       =	attentions

            if self.add_upsample:
                 _UpperCamelCase       =	FlaxUpsampleaD(self.out_channels	,			dtype=self.dtype					)







       def __call__(							self       :		Dict	,			lowerCAmelCase__       :		str	,			lowerCAmelCase__       :		int	,			lowerCAmelCase__       :		int	,			lowerCAmelCase__       :		Tuple	,			lowerCAmelCase__       :		int=True					)   ->					Tuple:

            '''simple docstring'''




            for resnet, attn in zip(self.resnets	,			self.attentions					):
                 # pop res hidden states
                 _UpperCamelCase       =	res_hidden_states_tuple[-1]
                 _UpperCamelCase       =	res_hidden_states_tuple[:-1]
                 _UpperCamelCase       =	jnp.concatenate((hidden_states, res_hidden_states)	,			axis=-1					)

                 _UpperCamelCase       =	resnet(lowercase_	,			lowercase_	,			deterministic=lowercase_					)
                 _UpperCamelCase       =	attn(lowercase_	,			lowercase_	,			deterministic=lowercase_					)

            if self.add_upsample:
                 _UpperCamelCase       =	self.upsamplers_a(lowercase_					)

            return hidden_states

class     __lowerCAmelCase					(   nn.Module			):






       """simple docstring"""
       _snake_case     :					int						    =   4_2
       _snake_case     :					Optional[int]						    =   4_2
       _snake_case     :					Dict						    =   4_2
       _snake_case     :					Optional[int]						    =   0.0
       _snake_case     :					List[Any]						    =   1
       _snake_case     :					int						    =   True
       _snake_case     :					List[Any]						    =   jnp.floataa





       def snake_case__						(							self       :		Optional[int]					)   ->					str:

            '''simple docstring'''




            _UpperCamelCase       =	[]

            for i in range(self.num_layers					):
                 _UpperCamelCase       =	self.in_channels if (i == self.num_layers - 1) else self.out_channels
                 _UpperCamelCase       =	self.prev_output_channel if i == 0 else self.out_channels

                 _UpperCamelCase       =	FlaxResnetBlockaD(
                     in_channels=resnet_in_channels + res_skip_channels	,			out_channels=self.out_channels	,			dropout_prob=self.dropout	,			dtype=self.dtype	,			)
                 resnets.append(lowercase_					)

            _UpperCamelCase       =	resnets

            if self.add_upsample:
                 _UpperCamelCase       =	FlaxUpsampleaD(self.out_channels	,			dtype=self.dtype					)







       def __call__(							self       :		Optional[int]	,			lowerCAmelCase__       :		Optional[Any]	,			lowerCAmelCase__       :		Optional[Any]	,			lowerCAmelCase__       :		Union[str, Any]	,			lowerCAmelCase__       :		List[Any]=True					)   ->					int:

            '''simple docstring'''




            for resnet in self.resnets:
                 # pop res hidden states
                 _UpperCamelCase       =	res_hidden_states_tuple[-1]
                 _UpperCamelCase       =	res_hidden_states_tuple[:-1]
                 _UpperCamelCase       =	jnp.concatenate((hidden_states, res_hidden_states)	,			axis=-1					)

                 _UpperCamelCase       =	resnet(lowercase_	,			lowercase_	,			deterministic=lowercase_					)

            if self.add_upsample:
                 _UpperCamelCase       =	self.upsamplers_a(lowercase_					)

            return hidden_states

class     __lowerCAmelCase					(   nn.Module			):






       """simple docstring"""
       _snake_case     :					Optional[int]						    =   4_2
       _snake_case     :					List[Any]						    =   0.0
       _snake_case     :					int						    =   1
       _snake_case     :					Optional[int]						    =   1
       _snake_case     :					Any						    =   False
       _snake_case     :					Optional[Any]						    =   False
       _snake_case     :					Dict						    =   jnp.floataa





       def snake_case__						(							self       :		Optional[int]					)   ->					int:

            '''simple docstring'''




            _UpperCamelCase       =	[
                FlaxResnetBlockaD(
                    in_channels=self.in_channels	,			out_channels=self.in_channels	,			dropout_prob=self.dropout	,			dtype=self.dtype	,			)
            ]

            _UpperCamelCase       =	[]

            for _ in range(self.num_layers					):
                 _UpperCamelCase       =	FlaxTransformeraDModel(
                     in_channels=self.in_channels	,			n_heads=self.num_attention_heads	,			d_head=self.in_channels // self.num_attention_heads	,			depth=1	,			use_linear_projection=self.use_linear_projection	,			use_memory_efficient_attention=self.use_memory_efficient_attention	,			dtype=self.dtype	,			)
                 attentions.append(lowercase_					)

                 _UpperCamelCase       =	FlaxResnetBlockaD(
                     in_channels=self.in_channels	,			out_channels=self.in_channels	,			dropout_prob=self.dropout	,			dtype=self.dtype	,			)
                 resnets.append(lowercase_					)

            _UpperCamelCase       =	resnets
            _UpperCamelCase       =	attentions







       def __call__(							self       :		Optional[Any]	,			lowerCAmelCase__       :		List[str]	,			lowerCAmelCase__       :		List[str]	,			lowerCAmelCase__       :		Dict	,			lowerCAmelCase__       :		str=True					)   ->					Optional[int]:

            '''simple docstring'''




            _UpperCamelCase       =	self.resnets[0](lowercase_	,			lowercase_					)
            for attn, resnet in zip(self.attentions	,			self.resnets[1:]					):
                 _UpperCamelCase       =	attn(lowercase_	,			lowercase_	,			deterministic=lowercase_					)
                 _UpperCamelCase       =	resnet(lowercase_	,			lowercase_	,			deterministic=lowercase_					)

            return hidden_states










'''simple docstring'''

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

import numpy as np
from utils_multiple_choice import MultipleChoiceDataset, Split, processors

import transformers
from transformers import (
    AutoConfig,
    AutoModelForMultipleChoice,
    AutoTokenizer,
    DataCollatorWithPadding,
    EvalPrediction,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import is_main_process


lowercase__						:      Any	=    logging.getLogger(__name__)







def  a__    (    lowercase :					Optional[Any], lowercase :					Tuple				)		->		Any:





     """simple docstring"""

     return (preds == labels).mean()
@dataclass
class     __lowerCAmelCase					:






       """simple docstring"""
       _snake_case     :					str						    =   field(
           metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}			)
       _snake_case     :					Optional[str]						    =   field(
           default=__magic_name__						,						metadata={'help': 'Pretrained config name or path if not the same as model_name'}			)
       _snake_case     :					Optional[str]						    =   field(
           default=__magic_name__						,						metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'}			)
       _snake_case     :					Optional[str]						    =   field(
           default=__magic_name__						,						metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}						,						)

@dataclass
class     __lowerCAmelCase					:






       """simple docstring"""
       _snake_case     :					str						    =   field(metadata={'help': 'The name of the task to train on: ' + ', '.join(processors.keys()			)}			)
       _snake_case     :					str						    =   field(metadata={'help': 'Should contain the data files for the task.'}			)
       _snake_case     :					int						    =   field(
           default=1_2_8						,						metadata={
               'help': (
                   'The maximum total input sequence length after tokenization. Sequences longer '
                   'than this will be truncated, sequences shorter will be padded.'
               )
           }						,						)
       _snake_case     :					bool						    =   field(
           default=__magic_name__						,						metadata={'help': 'Overwrite the cached training and evaluation sets'}			)







def  a__    (    )		->		Optional[Any]:





     """simple docstring"""

     _UpperCamelCase       =	HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)				)
     _UpperCamelCase   ,    _UpperCamelCase   ,    _UpperCamelCase       =	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''', lowercase				)

     # Set seed
     set_seed(training_args.seed				)

     try:
          _UpperCamelCase       =	processors[data_args.task_name]()
          _UpperCamelCase       =	processor.get_labels()
          _UpperCamelCase       =	len(lowercase				)
     except KeyError:
          raise ValueError('''Task not found: %s''' % (data_args.task_name)				)

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

     _UpperCamelCase       =	AutoConfig.from_pretrained(
         model_args.config_name if model_args.config_name else model_args.model_name_or_path, num_labels=lowercase, finetuning_task=data_args.task_name, cache_dir=model_args.cache_dir, )
     _UpperCamelCase       =	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, )
     _UpperCamelCase       =	AutoModelForMultipleChoice.from_pretrained(
         model_args.model_name_or_path, from_tf=bool('''.ckpt''' in model_args.model_name_or_path				), config=lowercase, cache_dir=model_args.cache_dir, )

     # Get datasets
     _UpperCamelCase       =	(
         MultipleChoiceDataset(
             data_dir=data_args.data_dir, tokenizer=lowercase, task=data_args.task_name, max_seq_length=data_args.max_seq_length, overwrite_cache=data_args.overwrite_cache, mode=Split.train, )
         if training_args.do_train
         else None
     )
     _UpperCamelCase       =	(
         MultipleChoiceDataset(
             data_dir=data_args.data_dir, tokenizer=lowercase, task=data_args.task_name, max_seq_length=data_args.max_seq_length, overwrite_cache=data_args.overwrite_cache, mode=Split.dev, )
         if training_args.do_eval
         else None
     )

     def compute_metrics(lowercase :					EvalPrediction				) -> Dict:
          _UpperCamelCase       =	np.argmax(p.predictions, axis=1				)
          return {"acc": simple_accuracy(lowercase, p.label_ids				)}

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

     # Initialize our Trainer
     _UpperCamelCase       =	Trainer(
         model=lowercase, args=lowercase, train_dataset=lowercase, eval_dataset=lowercase, compute_metrics=lowercase, data_collator=lowercase, )

     # 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				)

    # Evaluation
     _UpperCamelCase       =	{}
     if training_args.do_eval:
          logger.info('''*** Evaluate ***'''				)

          _UpperCamelCase       =	trainer.evaluate()

          _UpperCamelCase       =	os.path.join(training_args.output_dir, '''eval_results.txt'''				)
          if trainer.is_world_master():
               with open(lowercase, '''w'''				) as writer:
                    logger.info('''***** Eval results *****'''				)
                    for key, value in result.items():
                         logger.info('''  %s = %s''', lowercase, lowercase				)
                         writer.write('''%s = %s\n''' % (key, value)				)

                    results.update(lowercase				)

     return results







def  a__    (    lowercase :					Tuple				)		->		List[Any]:





     """simple docstring"""

     main()


if __name__ == "__main__":
   main()



