






"""simple docstring"""



import uuid
from typing import Any, Dict, List, Optional, Union

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
    import tensorflow as tf

if is_torch_available():
    import torch


_UpperCamelCase		:  Union[str, Any]						=		logging.get_logger(__name__)

class        a     :







    def __init__(			self							,		_lowerCamelCase = None							,		_lowerCamelCase = None							,		_lowerCamelCase=None							,		_lowerCamelCase=None       ):
      if not conversation_id:
        lowercase							    =       uuid.uuida()
      if past_user_inputs is None:
        lowercase							    =       []
      if generated_responses is None:
        lowercase							    =       []

      lowercase							    =       conversation_id
      lowercase							    =       past_user_inputs
      lowercase							    =       generated_responses
      lowercase							    =       text







    def __eq__(			self							,		_lowerCamelCase       ):
      if not isinstance(_lowerCamelCase							,		_lowerCamelCase       ):
        return False
      if self.uuid == other.uuid:
        return True
      return (
          self.new_user_input == other.new_user_input
          and self.past_user_inputs == other.past_user_inputs
          and self.generated_responses == other.generated_responses
      )







    def 			UpperCamelCase_      (			self							,		_lowerCamelCase							,		_lowerCamelCase = False       ):
      if self.new_user_input:
        if overwrite:
          logger.warning(
              F'User input added while unprocessed input was existing: "{self.new_user_input}" was overwritten '
              F'with: "{text}".'       )
          lowercase							    =       text
        else:
          logger.warning(
              F'User input added while unprocessed input was existing: "{self.new_user_input}" new input '
              F'ignored: "{text}". Set `overwrite` to True to overwrite unprocessed user input'       )
      else:
        lowercase							    =       text







    def 			UpperCamelCase_      (			self       ):
      if self.new_user_input:
        self.past_user_inputs.append(self.new_user_input       )
      lowercase							    =       None







    def 			UpperCamelCase_      (			self							,		_lowerCamelCase       ):
      self.generated_responses.append(_lowerCamelCase       )







    def 			UpperCamelCase_      (			self       ):
      for user_input, generated_response in zip(self.past_user_inputs							,		self.generated_responses       ):
        yield True, user_input
        yield False, generated_response
      if self.new_user_input:
        yield True, self.new_user_input







    def __repr__(			self       ):
      lowercase							    =       F'Conversation id: {self.uuid} \n'
      for is_user, text in self.iter_texts():
        lowercase							    =       'user' if is_user else 'bot'
        output += F'{name} >> {text} \n'
      return output


@add_end_docstrings(
    a_,				R"\n        min_length_for_response (`int`, *optional*, defaults to 32):\n            The minimum length (in number of tokens) for a response.\n        minimum_tokens (`int`, *optional*, defaults to 10):\n            The minimum length of tokens to leave for a response.\n    ",				)
class        a     (   a_	):







    def __init__(			self							,		*_lowerCamelCase							,		**_lowerCamelCase       ):
      super().__init__(*_lowerCamelCase							,		**_lowerCamelCase       )
      if self.tokenizer.pad_token_id is None:
        lowercase							    =       self.tokenizer.eos_token







    def 			UpperCamelCase_      (			self							,		_lowerCamelCase=None							,		_lowerCamelCase=None							,		_lowerCamelCase=None							,		**_lowerCamelCase       ):
      lowercase							    =       {}
      lowercase							    =       {}
      lowercase							    =       {}

      if min_length_for_response is not None:
        lowercase							    =       min_length_for_response
      if minimum_tokens is not None:
        lowercase							    =       minimum_tokens

      if "max_length" in generate_kwargs:
        lowercase							    =       generate_kwargs['max_length']
        # self.max_length = generate_kwargs.get("max_length", self.model.config.max_length)
      if clean_up_tokenization_spaces is not None:
        lowercase							    =       clean_up_tokenization_spaces

      if generate_kwargs:
        forward_params.update(_lowerCamelCase       )
      return preprocess_params, forward_params, postprocess_params







    def __call__(			self							,		_lowerCamelCase							,		_lowerCamelCase=0							,		**_lowerCamelCase       ):
      lowercase							    =       super().__call__(_lowerCamelCase							,		num_workers=_lowerCamelCase							,		**_lowerCamelCase       )
      if isinstance(_lowerCamelCase							,		_lowerCamelCase       ) and len(_lowerCamelCase       ) == 1:
        return outputs[0]
      return outputs







    def 			UpperCamelCase_      (			self							,		_lowerCamelCase							,		_lowerCamelCase=3_2       ):
      if not isinstance(_lowerCamelCase							,		_lowerCamelCase       ):
        raise ValueError('ConversationalPipeline, expects Conversation as inputs'       )
      if conversation.new_user_input is None:
        raise ValueError(
            F'Conversation with UUID {type(conversation.uuid       )} does not contain new user input to process. '
            'Add user inputs with the conversation\'s `add_user_input` method'       )
      if hasattr(self.tokenizer							,		'_build_conversation_input_ids'       ):
        lowercase							    =       self.tokenizer._build_conversation_input_ids(_lowerCamelCase       )
      else:
        # If the tokenizer cannot handle conversations, we default to only the old version
        lowercase							    =       self._legacy_parse_and_tokenize(_lowerCamelCase       )

      if self.framework == "pt":
        lowercase							    =       torch.LongTensor([input_ids]       )
      elif self.framework == "tf":
        lowercase							    =       tf.constant([input_ids]       )
      return {"input_ids": input_ids, "conversation": conversation}







    def 			UpperCamelCase_      (			self							,		_lowerCamelCase							,		_lowerCamelCase=1_0							,		**_lowerCamelCase       ):
      lowercase							    =       generate_kwargs.get('max_length'							,		self.model.config.max_length       )

      lowercase							    =       model_inputs['input_ids'].shape[1]
      if max_length - minimum_tokens < n:
        logger.warning(F'Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})'       )
        lowercase							    =       max_length - minimum_tokens
        lowercase							    =       model_inputs['input_ids'][:, -trim:]
        if "attention_mask" in model_inputs:
          lowercase							    =       model_inputs['attention_mask'][:, -trim:]
      lowercase							    =       model_inputs.pop('conversation'       )
      lowercase							    =       max_length
      lowercase							    =       self.model.generate(**_lowerCamelCase							,		**_lowerCamelCase       )
      if self.model.config.is_encoder_decoder:
        lowercase							    =       1
      else:
        lowercase							    =       n
      return {"output_ids": output_ids[:, start_position:], "conversation": conversation}







    def 			UpperCamelCase_      (			self							,		_lowerCamelCase							,		_lowerCamelCase=True       ):
      lowercase							    =       model_outputs['output_ids']
      lowercase							    =       self.tokenizer.decode(
          output_ids[0]							,		skip_special_tokens=_lowerCamelCase							,		clean_up_tokenization_spaces=_lowerCamelCase							,		)
      lowercase							    =       model_outputs['conversation']
      conversation.mark_processed()
      conversation.append_response(_lowerCamelCase       )
      return conversation







    def 			UpperCamelCase_      (			self							,		_lowerCamelCase       ):
      lowercase							    =       self.tokenizer.eos_token_id
      lowercase							    =       []
      for is_user, text in conversation.iter_texts():
        if eos_token_id is not None:
          input_ids.extend(self.tokenizer.encode(_lowerCamelCase							,		add_special_tokens=_lowerCamelCase       ) + [eos_token_id]       )
        else:
          input_ids.extend(self.tokenizer.encode(_lowerCamelCase							,		add_special_tokens=_lowerCamelCase       )       )

      if len(_lowerCamelCase       ) > self.tokenizer.model_max_length:
        lowercase							    =       input_ids[-self.tokenizer.model_max_length :]
      return input_ids










"""simple docstring"""



import json
import os
from dataclasses import dataclass
from functools import partial
from typing import Callable

import flax.linen as nn
import jax
import jax.numpy as jnp
import joblib
import optax
import wandb
from flax import jax_utils, struct, traverse_util
from flax.serialization import from_bytes, to_bytes
from flax.training import train_state
from flax.training.common_utils import shard
from tqdm.auto import tqdm

from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering
from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule

class        a     (   a_	):
    UpperCAmelCase_ :     BigBirdConfig
    UpperCAmelCase_ :     jnp.dtype	     =jnp.floataa
    UpperCAmelCase_ :     bool	     =True







    def 			UpperCamelCase_      (			self       ):
      super().setup()
      lowercase							    =       nn.Dense(5							,		dtype=self.dtype       )







    def __call__(			self							,		*_lowerCamelCase							,		**_lowerCamelCase       ):
      lowercase							    =       super().__call__(*_lowerCamelCase							,		**_lowerCamelCase       )
      lowercase							    =       self.cls(outputs[2]       )
      return outputs[:2] + (cls_out,)


class        a     (   a_	):
    UpperCAmelCase_ :     str	     =FlaxBigBirdForNaturalQuestionsModule


def 						_SCREAMING_SNAKE_CASE (    __snake_case			:  Optional[int]		,					__snake_case			:  Dict		,					__snake_case			:  Optional[Any]		,					__snake_case			:  Optional[int]		,					__snake_case			:  Tuple		,					__snake_case			:  Tuple    ):





  '''simple docstring'''





  def cross_entropy(__snake_case			:  Dict		,					__snake_case			:  str		,					__snake_case			:  Any=None    ):
    lowercase							    =       logits.shape[-1]
    lowercase							    =       (labels[..., None] == jnp.arange(__snake_case    )[None]).astype('f4'    )
    lowercase							    =       jax.nn.log_softmax(__snake_case		,					axis=-1    )
    lowercase							    =       -jnp.sum(labels * logits		,					axis=-1    )
    if reduction is not None:
      lowercase							    =       reduction(__snake_case    )
    return loss

  lowercase							    =       partial(__snake_case		,					reduction=jnp.mean    )
  lowercase							    =       cross_entropy(__snake_case		,					__snake_case    )
  lowercase							    =       cross_entropy(__snake_case		,					__snake_case    )
  lowercase							    =       cross_entropy(__snake_case		,					__snake_case    )
  return (start_loss + end_loss + pooled_loss) / 3

@dataclass
class        a     :
    UpperCAmelCase_ :     str	     ="google/bigbird-roberta-base"
    UpperCAmelCase_ :     int	     =3000
    UpperCAmelCase_ :     int	     =1_0500

    UpperCAmelCase_ :     int	     =128
    UpperCAmelCase_ :     int	     =3

    UpperCAmelCase_ :     int	     =1
    UpperCAmelCase_ :     int	     =5

    # tx_args
    UpperCAmelCase_ :     float	     =3e-5
    UpperCAmelCase_ :     float	     =0.0
    UpperCAmelCase_ :     int	     =2_0000
    UpperCAmelCase_ :     float	     =0.00_95

    UpperCAmelCase_ :     str	     ="bigbird-roberta-natural-questions"
    UpperCAmelCase_ :     str	     ="training-expt"
    UpperCAmelCase_ :     str	     ="data/nq-training.jsonl"
    UpperCAmelCase_ :     str	     ="data/nq-validation.jsonl"







    def 			UpperCamelCase_      (			self       ):
      os.makedirs(self.base_dir							,		exist_ok=_lowerCamelCase       )
      lowercase							    =       os.path.join(self.base_dir							,		self.save_dir       )
      lowercase							    =       self.batch_size_per_device * jax.device_count()


@dataclass
class        a     :
    UpperCAmelCase_ :     int
    UpperCAmelCase_ :     int	     =4096  # no dynamic padding on TPUs







    def __call__(			self							,		_lowerCamelCase       ):
      lowercase							    =       self.collate_fn(_lowerCamelCase       )
      lowercase							    =       jax.tree_util.tree_map(_lowerCamelCase							,		_lowerCamelCase       )
      return batch







    def 			UpperCamelCase_      (			self							,		_lowerCamelCase       ):
      lowercase    ,     lowercase							    =       self.fetch_inputs(features['input_ids']       )
      lowercase							    =       {
          'input_ids': jnp.array(_lowerCamelCase							,		dtype=jnp.intaa       ),
          'attention_mask': jnp.array(_lowerCamelCase							,		dtype=jnp.intaa       ),
          'start_labels': jnp.array(features['start_token']							,		dtype=jnp.intaa       ),
          'end_labels': jnp.array(features['end_token']							,		dtype=jnp.intaa       ),
          'pooled_labels': jnp.array(features['category']							,		dtype=jnp.intaa       ),
      }
      return batch







    def 			UpperCamelCase_      (			self							,		_lowerCamelCase       ):
      lowercase							    =       [self._fetch_inputs(_lowerCamelCase       ) for ids in input_ids]
      return zip(*_lowerCamelCase       )







    def 			UpperCamelCase_      (			self							,		_lowerCamelCase       ):
      lowercase							    =       [1 for _ in range(len(_lowerCamelCase       )       )]
      while len(_lowerCamelCase       ) < self.max_length:
        input_ids.append(self.pad_id       )
        attention_mask.append(0       )
      return input_ids, attention_mask


def 						_SCREAMING_SNAKE_CASE (    __snake_case			:  Any		,					__snake_case			:  Tuple		,					__snake_case			:  Optional[Any]=None    ):





  '''simple docstring'''





  if seed is not None:
    lowercase							    =       dataset.shuffle(seed=__snake_case    )
  for i in range(len(__snake_case    ) // batch_size    ):
    lowercase							    =       dataset[i * batch_size : (i + 1) * batch_size]
    yield dict(__snake_case    )
@partial(jax.pmap		,					axis_name='batch'    )
def 						_SCREAMING_SNAKE_CASE (    __snake_case			:  Dict		,					__snake_case			:  List[Any]		,					**__snake_case			:  List[Any]    ):





  '''simple docstring'''





  def loss_fn(__snake_case			:  str    ):
    lowercase							    =       model_inputs.pop('start_labels'    )
    lowercase							    =       model_inputs.pop('end_labels'    )
    lowercase							    =       model_inputs.pop('pooled_labels'    )

    lowercase							    =       state.apply_fn(**__snake_case		,					params=__snake_case		,					dropout_rng=__snake_case		,					train=__snake_case    )
    lowercase    ,     lowercase    ,     lowercase							    =       outputs

    return state.loss_fn(
        __snake_case		,					__snake_case		,					__snake_case		,					__snake_case		,					__snake_case		,					__snake_case		,					)

  lowercase    ,     lowercase							    =       jax.random.split(__snake_case    )
  lowercase							    =       jax.value_and_grad(__snake_case    )
  lowercase    ,     lowercase							    =       grad_fn(state.params    )
  lowercase							    =       jax.lax.pmean({'loss': loss}		,					axis_name='batch'    )
  lowercase							    =       jax.lax.pmean(__snake_case		,					'batch'    )

  lowercase							    =       state.apply_gradients(grads=__snake_case    )
  return state, metrics, new_drp_rng
@partial(jax.pmap		,					axis_name='batch'    )
def 						_SCREAMING_SNAKE_CASE (    __snake_case			:  Optional[int]		,					**__snake_case			:  Dict    ):





  '''simple docstring'''





  lowercase							    =       model_inputs.pop('start_labels'    )
  lowercase							    =       model_inputs.pop('end_labels'    )
  lowercase							    =       model_inputs.pop('pooled_labels'    )

  lowercase							    =       state.apply_fn(**__snake_case		,					params=state.params		,					train=__snake_case    )
  lowercase    ,     lowercase    ,     lowercase							    =       outputs

  lowercase							    =       state.loss_fn(__snake_case		,					__snake_case		,					__snake_case		,					__snake_case		,					__snake_case		,					__snake_case    )
  lowercase							    =       jax.lax.pmean({'loss': loss}		,					axis_name='batch'    )
  return metrics

class        a     (   train_state.TrainState	):
    UpperCAmelCase_ :     Callable	     =struct.field(pytree_node=a_	)


@dataclass
class        a     :
    UpperCAmelCase_ :     Args
    UpperCAmelCase_ :     Callable
    UpperCAmelCase_ :     Callable
    UpperCAmelCase_ :     Callable
    UpperCAmelCase_ :     Callable
    UpperCAmelCase_ :     wandb
    UpperCAmelCase_ :     Callable	     =None







    def 			UpperCamelCase_      (			self							,		_lowerCamelCase							,		_lowerCamelCase							,		_lowerCamelCase							,		_lowerCamelCase=None       ):
      lowercase							    =       model.params
      lowercase							    =       TrainState.create(
          apply_fn=model.__call__							,		params=_lowerCamelCase							,		tx=_lowerCamelCase							,		loss_fn=_lowerCamelCase							,		)
      if ckpt_dir is not None:
        lowercase    ,     lowercase    ,     lowercase    ,     lowercase    ,     lowercase							    =       restore_checkpoint(_lowerCamelCase							,		_lowerCamelCase       )
        lowercase							    =       {
            'lr': args.lr,
            'init_lr': args.init_lr,
            'warmup_steps': args.warmup_steps,
            'num_train_steps': num_train_steps,
            'weight_decay': args.weight_decay,
        }
        lowercase    ,     lowercase							    =       build_tx(**_lowerCamelCase       )
        lowercase							    =       train_state.TrainState(
            step=_lowerCamelCase							,		apply_fn=model.__call__							,		params=_lowerCamelCase							,		tx=_lowerCamelCase							,		opt_state=_lowerCamelCase							,		)
        lowercase							    =       args
        lowercase							    =       data_collator
        lowercase							    =       lr
        lowercase							    =       params
      lowercase							    =       jax_utils.replicate(_lowerCamelCase       )
      return state







    def 			UpperCamelCase_      (			self							,		_lowerCamelCase							,		_lowerCamelCase							,		_lowerCamelCase       ):
      lowercase							    =       self.args
      lowercase							    =       len(_lowerCamelCase       ) // args.batch_size

      lowercase							    =       jax.random.PRNGKey(0       )
      lowercase							    =       jax.random.split(_lowerCamelCase							,		jax.device_count()       )
      for epoch in range(args.max_epochs       ):
        lowercase							    =       jnp.array(0							,		dtype=jnp.floataa       )
        lowercase							    =       get_batched_dataset(_lowerCamelCase							,		args.batch_size							,		seed=_lowerCamelCase       )
        lowercase							    =       0
        for batch in tqdm(_lowerCamelCase							,		total=_lowerCamelCase							,		desc=F'Running EPOCH-{epoch}'       ):
          lowercase							    =       self.data_collator(_lowerCamelCase       )
          lowercase    ,     lowercase    ,     lowercase							    =       self.train_step_fn(_lowerCamelCase							,		_lowerCamelCase							,		**_lowerCamelCase       )
          running_loss += jax_utils.unreplicate(metrics['loss']       )
          i += 1
          if i % args.logging_steps == 0:
            lowercase							    =       jax_utils.unreplicate(state.step       )
            lowercase							    =       running_loss.item() / i
            lowercase							    =       self.scheduler_fn(state_step - 1       )

            lowercase							    =       self.evaluate(_lowerCamelCase							,		_lowerCamelCase       )
            lowercase							    =       {
                'step': state_step.item(),
                'eval_loss': eval_loss.item(),
                'tr_loss': tr_loss,
                'lr': lr.item(),
            }
            tqdm.write(str(_lowerCamelCase       )       )
            self.logger.log(_lowerCamelCase							,		commit=_lowerCamelCase       )

          if i % args.save_steps == 0:
            self.save_checkpoint(args.save_dir + F'-e{epoch}-s{i}'							,		state=_lowerCamelCase       )







    def 			UpperCamelCase_      (			self							,		_lowerCamelCase							,		_lowerCamelCase       ):
      lowercase							    =       get_batched_dataset(_lowerCamelCase							,		self.args.batch_size       )
      lowercase							    =       len(_lowerCamelCase       ) // self.args.batch_size
      lowercase							    =       jnp.array(0							,		dtype=jnp.floataa       )
      lowercase							    =       0
      for batch in tqdm(_lowerCamelCase							,		total=_lowerCamelCase							,		desc='Evaluating ... '       ):
        lowercase							    =       self.data_collator(_lowerCamelCase       )
        lowercase							    =       self.val_step_fn(_lowerCamelCase							,		**_lowerCamelCase       )
        running_loss += jax_utils.unreplicate(metrics['loss']       )
        i += 1
      return running_loss / i







    def 			UpperCamelCase_      (			self							,		_lowerCamelCase							,		_lowerCamelCase       ):
      lowercase							    =       jax_utils.unreplicate(_lowerCamelCase       )
      print(F'SAVING CHECKPOINT IN {save_dir}'							,		end=' ... '       )
      self.model_save_fn(_lowerCamelCase							,		params=state.params       )
      with open(os.path.join(_lowerCamelCase							,		'opt_state.msgpack'       )							,		'wb'       ) as f:
        f.write(to_bytes(state.opt_state       )       )
      joblib.dump(self.args							,		os.path.join(_lowerCamelCase							,		'args.joblib'       )       )
      joblib.dump(self.data_collator							,		os.path.join(_lowerCamelCase							,		'data_collator.joblib'       )       )
      with open(os.path.join(_lowerCamelCase							,		'training_state.json'       )							,		'w'       ) as f:
        json.dump({'step': state.step.item()}							,		_lowerCamelCase       )
      print('DONE'       )


def 						_SCREAMING_SNAKE_CASE (    __snake_case			:  int		,					__snake_case			:  Tuple    ):





  '''simple docstring'''





  print(f'RESTORING CHECKPOINT FROM {save_dir}'		,					end=' ... '    )
  with open(os.path.join(__snake_case		,					'flax_model.msgpack'    )		,					'rb'    ) as f:
    lowercase							    =       from_bytes(state.params		,					f.read()    )

  with open(os.path.join(__snake_case		,					'opt_state.msgpack'    )		,					'rb'    ) as f:
    lowercase							    =       from_bytes(state.opt_state		,					f.read()    )

  lowercase							    =       joblib.load(os.path.join(__snake_case		,					'args.joblib'    )    )
  lowercase							    =       joblib.load(os.path.join(__snake_case		,					'data_collator.joblib'    )    )

  with open(os.path.join(__snake_case		,					'training_state.json'    )		,					'r'    ) as f:
    lowercase							    =       json.load(__snake_case    )
  lowercase							    =       training_state['step']

  print('DONE'    )
  return params, opt_state, step, args, data_collator
def 						_SCREAMING_SNAKE_CASE (    __snake_case			:  int		,					__snake_case			:  str		,					__snake_case			:  Any		,					__snake_case			:  Any    ):





  '''simple docstring'''





  lowercase							    =       num_train_steps - warmup_steps
  lowercase							    =       optax.linear_schedule(init_value=__snake_case		,					end_value=__snake_case		,					transition_steps=__snake_case    )
  lowercase							    =       optax.linear_schedule(init_value=__snake_case		,					end_value=1e-7		,					transition_steps=__snake_case    )
  lowercase							    =       optax.join_schedules(schedules=[warmup_fn, decay_fn]		,					boundaries=[warmup_steps]    )
  return lr



def 						_SCREAMING_SNAKE_CASE (    __snake_case			:  Union[str, Any]		,					__snake_case			:  Union[str, Any]		,					__snake_case			:  List[str]		,					__snake_case			:  str		,					__snake_case			:  Optional[int]    ):





  '''simple docstring'''





  def weight_decay_mask(__snake_case			:  Tuple    ):
    lowercase							    =       traverse_util.flatten_dict(__snake_case    )
    lowercase							    =       {k: (v[-1] != 'bias' and v[-2:] != ('LayerNorm', 'scale')) for k, v in params.items()}
    return traverse_util.unflatten_dict(__snake_case    )

  lowercase							    =       scheduler_fn(__snake_case		,					__snake_case		,					__snake_case		,					__snake_case    )

  lowercase							    =       optax.adamw(learning_rate=__snake_case		,					weight_decay=__snake_case		,					mask=__snake_case    )
  return tx, lr


