






"""simple docstring"""



# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer
from .base import PipelineTool


_UpperCamelCase		:  int						=		{
    'Acehnese Arabic': 'ace_Arab',
    'Acehnese Latin': 'ace_Latn',
    'Mesopotamian Arabic': 'acm_Arab',
    'Ta\'izzi-Adeni Arabic': 'acq_Arab',
    'Tunisian Arabic': 'aeb_Arab',
    'Afrikaans': 'afr_Latn',
    'South Levantine Arabic': 'ajp_Arab',
    'Akan': 'aka_Latn',
    'Amharic': 'amh_Ethi',
    'North Levantine Arabic': 'apc_Arab',
    'Modern Standard Arabic': 'arb_Arab',
    'Modern Standard Arabic Romanized': 'arb_Latn',
    'Najdi Arabic': 'ars_Arab',
    'Moroccan Arabic': 'ary_Arab',
    'Egyptian Arabic': 'arz_Arab',
    'Assamese': 'asm_Beng',
    'Asturian': 'ast_Latn',
    'Awadhi': 'awa_Deva',
    'Central Aymara': 'ayr_Latn',
    'South Azerbaijani': 'azb_Arab',
    'North Azerbaijani': 'azj_Latn',
    'Bashkir': 'bak_Cyrl',
    'Bambara': 'bam_Latn',
    'Balinese': 'ban_Latn',
    'Belarusian': 'bel_Cyrl',
    'Bemba': 'bem_Latn',
    'Bengali': 'ben_Beng',
    'Bhojpuri': 'bho_Deva',
    'Banjar Arabic': 'bjn_Arab',
    'Banjar Latin': 'bjn_Latn',
    'Standard Tibetan': 'bod_Tibt',
    'Bosnian': 'bos_Latn',
    'Buginese': 'bug_Latn',
    'Bulgarian': 'bul_Cyrl',
    'Catalan': 'cat_Latn',
    'Cebuano': 'ceb_Latn',
    'Czech': 'ces_Latn',
    'Chokwe': 'cjk_Latn',
    'Central Kurdish': 'ckb_Arab',
    'Crimean Tatar': 'crh_Latn',
    'Welsh': 'cym_Latn',
    'Danish': 'dan_Latn',
    'German': 'deu_Latn',
    'Southwestern Dinka': 'dik_Latn',
    'Dyula': 'dyu_Latn',
    'Dzongkha': 'dzo_Tibt',
    'Greek': 'ell_Grek',
    'English': 'eng_Latn',
    'Esperanto': 'epo_Latn',
    'Estonian': 'est_Latn',
    'Basque': 'eus_Latn',
    'Ewe': 'ewe_Latn',
    'Faroese': 'fao_Latn',
    'Fijian': 'fij_Latn',
    'Finnish': 'fin_Latn',
    'Fon': 'fon_Latn',
    'French': 'fra_Latn',
    'Friulian': 'fur_Latn',
    'Nigerian Fulfulde': 'fuv_Latn',
    'Scottish Gaelic': 'gla_Latn',
    'Irish': 'gle_Latn',
    'Galician': 'glg_Latn',
    'Guarani': 'grn_Latn',
    'Gujarati': 'guj_Gujr',
    'Haitian Creole': 'hat_Latn',
    'Hausa': 'hau_Latn',
    'Hebrew': 'heb_Hebr',
    'Hindi': 'hin_Deva',
    'Chhattisgarhi': 'hne_Deva',
    'Croatian': 'hrv_Latn',
    'Hungarian': 'hun_Latn',
    'Armenian': 'hye_Armn',
    'Igbo': 'ibo_Latn',
    'Ilocano': 'ilo_Latn',
    'Indonesian': 'ind_Latn',
    'Icelandic': 'isl_Latn',
    'Italian': 'ita_Latn',
    'Javanese': 'jav_Latn',
    'Japanese': 'jpn_Jpan',
    'Kabyle': 'kab_Latn',
    'Jingpho': 'kac_Latn',
    'Kamba': 'kam_Latn',
    'Kannada': 'kan_Knda',
    'Kashmiri Arabic': 'kas_Arab',
    'Kashmiri Devanagari': 'kas_Deva',
    'Georgian': 'kat_Geor',
    'Central Kanuri Arabic': 'knc_Arab',
    'Central Kanuri Latin': 'knc_Latn',
    'Kazakh': 'kaz_Cyrl',
    'Kabiyè': 'kbp_Latn',
    'Kabuverdianu': 'kea_Latn',
    'Khmer': 'khm_Khmr',
    'Kikuyu': 'kik_Latn',
    'Kinyarwanda': 'kin_Latn',
    'Kyrgyz': 'kir_Cyrl',
    'Kimbundu': 'kmb_Latn',
    'Northern Kurdish': 'kmr_Latn',
    'Kikongo': 'kon_Latn',
    'Korean': 'kor_Hang',
    'Lao': 'lao_Laoo',
    'Ligurian': 'lij_Latn',
    'Limburgish': 'lim_Latn',
    'Lingala': 'lin_Latn',
    'Lithuanian': 'lit_Latn',
    'Lombard': 'lmo_Latn',
    'Latgalian': 'ltg_Latn',
    'Luxembourgish': 'ltz_Latn',
    'Luba-Kasai': 'lua_Latn',
    'Ganda': 'lug_Latn',
    'Luo': 'luo_Latn',
    'Mizo': 'lus_Latn',
    'Standard Latvian': 'lvs_Latn',
    'Magahi': 'mag_Deva',
    'Maithili': 'mai_Deva',
    'Malayalam': 'mal_Mlym',
    'Marathi': 'mar_Deva',
    'Minangkabau Arabic ': 'min_Arab',
    'Minangkabau Latin': 'min_Latn',
    'Macedonian': 'mkd_Cyrl',
    'Plateau Malagasy': 'plt_Latn',
    'Maltese': 'mlt_Latn',
    'Meitei Bengali': 'mni_Beng',
    'Halh Mongolian': 'khk_Cyrl',
    'Mossi': 'mos_Latn',
    'Maori': 'mri_Latn',
    'Burmese': 'mya_Mymr',
    'Dutch': 'nld_Latn',
    'Norwegian Nynorsk': 'nno_Latn',
    'Norwegian Bokmål': 'nob_Latn',
    'Nepali': 'npi_Deva',
    'Northern Sotho': 'nso_Latn',
    'Nuer': 'nus_Latn',
    'Nyanja': 'nya_Latn',
    'Occitan': 'oci_Latn',
    'West Central Oromo': 'gaz_Latn',
    'Odia': 'ory_Orya',
    'Pangasinan': 'pag_Latn',
    'Eastern Panjabi': 'pan_Guru',
    'Papiamento': 'pap_Latn',
    'Western Persian': 'pes_Arab',
    'Polish': 'pol_Latn',
    'Portuguese': 'por_Latn',
    'Dari': 'prs_Arab',
    'Southern Pashto': 'pbt_Arab',
    'Ayacucho Quechua': 'quy_Latn',
    'Romanian': 'ron_Latn',
    'Rundi': 'run_Latn',
    'Russian': 'rus_Cyrl',
    'Sango': 'sag_Latn',
    'Sanskrit': 'san_Deva',
    'Santali': 'sat_Olck',
    'Sicilian': 'scn_Latn',
    'Shan': 'shn_Mymr',
    'Sinhala': 'sin_Sinh',
    'Slovak': 'slk_Latn',
    'Slovenian': 'slv_Latn',
    'Samoan': 'smo_Latn',
    'Shona': 'sna_Latn',
    'Sindhi': 'snd_Arab',
    'Somali': 'som_Latn',
    'Southern Sotho': 'sot_Latn',
    'Spanish': 'spa_Latn',
    'Tosk Albanian': 'als_Latn',
    'Sardinian': 'srd_Latn',
    'Serbian': 'srp_Cyrl',
    'Swati': 'ssw_Latn',
    'Sundanese': 'sun_Latn',
    'Swedish': 'swe_Latn',
    'Swahili': 'swh_Latn',
    'Silesian': 'szl_Latn',
    'Tamil': 'tam_Taml',
    'Tatar': 'tat_Cyrl',
    'Telugu': 'tel_Telu',
    'Tajik': 'tgk_Cyrl',
    'Tagalog': 'tgl_Latn',
    'Thai': 'tha_Thai',
    'Tigrinya': 'tir_Ethi',
    'Tamasheq Latin': 'taq_Latn',
    'Tamasheq Tifinagh': 'taq_Tfng',
    'Tok Pisin': 'tpi_Latn',
    'Tswana': 'tsn_Latn',
    'Tsonga': 'tso_Latn',
    'Turkmen': 'tuk_Latn',
    'Tumbuka': 'tum_Latn',
    'Turkish': 'tur_Latn',
    'Twi': 'twi_Latn',
    'Central Atlas Tamazight': 'tzm_Tfng',
    'Uyghur': 'uig_Arab',
    'Ukrainian': 'ukr_Cyrl',
    'Umbundu': 'umb_Latn',
    'Urdu': 'urd_Arab',
    'Northern Uzbek': 'uzn_Latn',
    'Venetian': 'vec_Latn',
    'Vietnamese': 'vie_Latn',
    'Waray': 'war_Latn',
    'Wolof': 'wol_Latn',
    'Xhosa': 'xho_Latn',
    'Eastern Yiddish': 'ydd_Hebr',
    'Yoruba': 'yor_Latn',
    'Yue Chinese': 'yue_Hant',
    'Chinese Simplified': 'zho_Hans',
    'Chinese Traditional': 'zho_Hant',
    'Standard Malay': 'zsm_Latn',
    'Zulu': 'zul_Latn',
}

class        a     (   a_	):
    UpperCAmelCase_ :     List[str]	     ="facebook/nllb-200-distilled-600M"
    UpperCAmelCase_ :     Tuple	     =(
        "This is a tool that translates text from a language to another. It takes three inputs: `text`, which should "
        "be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, "
        "which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in "
        "plain English, such as 'Romanian', or 'Albanian'. It returns the text translated in `tgt_lang`."
    )
    UpperCAmelCase_ :     Tuple	     ="translator"
    UpperCAmelCase_ :     Tuple	     =AutoTokenizer
    UpperCAmelCase_ :     Optional[int]	     =AutoModelForSeqaSeqLM
    UpperCAmelCase_ :     Any	     =LANGUAGE_CODES

    UpperCAmelCase_ :     str	     =["text", "text", "text"]
    UpperCAmelCase_ :     Any	     =["text"]







    def 			UpperCamelCase_      (			self							,		_lowerCamelCase							,		_lowerCamelCase							,		_lowerCamelCase       ):
      if src_lang not in self.lang_to_code:
        raise ValueError(F'{src_lang} is not a supported language.'       )
      if tgt_lang not in self.lang_to_code:
        raise ValueError(F'{tgt_lang} is not a supported language.'       )
      lowercase							    =       self.lang_to_code[src_lang]
      lowercase							    =       self.lang_to_code[tgt_lang]
      return self.pre_processor._build_translation_inputs(
          _lowerCamelCase							,		return_tensors='pt'							,		src_lang=_lowerCamelCase							,		tgt_lang=_lowerCamelCase       )







    def 			UpperCamelCase_      (			self							,		_lowerCamelCase       ):
      return self.model.generate(**_lowerCamelCase       )







    def 			UpperCamelCase_      (			self							,		_lowerCamelCase       ):
      return self.post_processor.decode(outputs[0].tolist()							,		skip_special_tokens=_lowerCamelCase       )










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


