

import math

lowerCAmelCase							:  Dict   	=						10
lowerCAmelCase							:  Dict   	=						7
lowerCAmelCase							:  Union[str, Any]   	=						BALLS_PER_COLOUR * NUM_COLOURS







def 			A_      (    _UpperCAmelCase = 20    ):
						SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       math.comb(_UpperCAmelCase				,	_UpperCAmelCase    )
						SCREAMING_SNAKE_CASE_: Optional[int]  		=       math.comb(NUM_BALLS - BALLS_PER_COLOUR				,	_UpperCAmelCase    )

						SCREAMING_SNAKE_CASE_: Dict  		=       NUM_COLOURS * (1 - missing_colour / total)

						return f"{result:.9f}"


if __name__ == "__main__":
						print(solution(20))














"""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


