


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







    """simple docstring"""




    UpperCAmelCase       :							BigBirdConfig
    UpperCAmelCase       :							jnp.dtype	=       jnp.floataa
    UpperCAmelCase       :							bool	=       True






    def 	__snake_case							(					self				:    List[str]):
      super().setup()
      a						:		Optional[Any]      							=			nn.Dense(5				, dtype=self.dtype)






    def __call__(					self				:    List[Any]				, *__UpperCAmelCase				:    Union[str, Any]				, **__UpperCAmelCase				:    Optional[Any]):
      a						:		int      							=			super().__call__(*__UpperCAmelCase				, **__UpperCAmelCase)
      a						:		int      							=			self.cls(outputs[2])
      return outputs[:2] + (cls_out,)






class 						_A  (  _a  ):







    """simple docstring"""




    UpperCAmelCase       :							Union[str, Any]	=       FlaxBigBirdForNaturalQuestionsModule






def      lowercase			(				A_  ,   A_  ,   A_  ,   A_  ,   A_  ,   A_       )->      Union[str, Any]:
  '''simple docstring'''







  def cross_entropy(A_  ,   A_  ,   A_=None       ):
    a						:		List[str]      							=			logits.shape[-1]
    a						:		Dict      							=			(labels[..., None] == jnp.arange(A_       )[None]).astype("f4"       )
    a						:		Optional[int]      							=			jax.nn.log_softmax(A_  ,   axis=-1       )
    a						:		List[str]      							=			-jnp.sum(labels * logits  ,   axis=-1       )
    if reduction is not None:
      a						:		List[Any]      							=			reduction(A_       )
    return loss

  a						:		int      							=			partial(A_  ,   reduction=jnp.mean       )
  a						:		int      							=			cross_entropy(A_  ,   A_       )
  a						:		Optional[Any]      							=			cross_entropy(A_  ,   A_       )
  a						:		List[str]      							=			cross_entropy(A_  ,   A_       )
  return (start_loss + end_loss + pooled_loss) / 3






@dataclass
class 						_A  :







    """simple docstring"""




    UpperCAmelCase       :							str	=       "google/bigbird-roberta-base"
    UpperCAmelCase       :							int	=       3_0_0_0
    UpperCAmelCase       :							int	=       1_0_5_0_0

    UpperCAmelCase       :							int	=       1_2_8
    UpperCAmelCase       :							int	=       3

    UpperCAmelCase       :							int	=       1
    UpperCAmelCase       :							int	=       5

    # tx_args
    UpperCAmelCase       :							float	=       3E-5
    UpperCAmelCase       :							float	=       0.0
    UpperCAmelCase       :							int	=       2_0_0_0_0
    UpperCAmelCase       :							float	=       0.0095

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






    def 	__snake_case							(					self				:    Tuple):
      os.makedirs(self.base_dir				, exist_ok=__UpperCAmelCase)
      a						:		Tuple      							=			os.path.join(self.base_dir				, self.save_dir)
      a						:		Any      							=			self.batch_size_per_device * jax.device_count()






@dataclass
class 						_A  :







    """simple docstring"""




    UpperCAmelCase       :							int
    UpperCAmelCase       :							int	=       4_0_9_6  # no dynamic padding on TPUs






    def __call__(					self				:    Tuple				, __UpperCAmelCase				:    Union[str, Any]):
      a						:		Optional[int]      							=			self.collate_fn(__UpperCAmelCase)
      a						:		Union[str, Any]      							=			jax.tree_util.tree_map(__UpperCAmelCase				, __UpperCAmelCase)
      return batch






    def 	__snake_case							(					self				:    Optional[int]				, __UpperCAmelCase				:    Tuple):
      a							,		a						:		Union[str, Any]      							=			self.fetch_inputs(features["input_ids"])
      a						:		Dict      							=			{
          "input_ids": jnp.array(__UpperCAmelCase				, dtype=jnp.intaa),
          "attention_mask": jnp.array(__UpperCAmelCase				, 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 	__snake_case							(					self				:    List[str]				, __UpperCAmelCase				:    list):
      a						:		Optional[int]      							=			[self._fetch_inputs(__UpperCAmelCase) for ids in input_ids]
      return zip(*__UpperCAmelCase)






    def 	__snake_case							(					self				:    List[Any]				, __UpperCAmelCase				:    list):
      a						:		List[Any]      							=			[1 for _ in range(len(__UpperCAmelCase))]
      while len(__UpperCAmelCase) < self.max_length:
        input_ids.append(self.pad_id)
        attention_mask.append(0)
      return input_ids, attention_mask






def      lowercase			(				A_  ,   A_  ,   A_=None       )->      Tuple:
  '''simple docstring'''







  if seed is not None:
    a						:		Any      							=			dataset.shuffle(seed=A_       )
  for i in range(len(A_       ) // batch_size       ):
    a						:		Union[str, Any]      							=			dataset[i * batch_size : (i + 1) * batch_size]
    yield dict(A_       )


@partial(jax.pmap  ,   axis_name="batch"       )
def      lowercase			(				A_  ,   A_  ,   **A_       )->      List[str]:
  '''simple docstring'''







  def loss_fn(A_       ):
    a						:		Tuple      							=			model_inputs.pop("start_labels"       )
    a						:		List[str]      							=			model_inputs.pop("end_labels"       )
    a						:		Union[str, Any]      							=			model_inputs.pop("pooled_labels"       )

    a						:		Tuple      							=			state.apply_fn(**A_  ,   params=A_  ,   dropout_rng=A_  ,   train=A_       )
    a							,		a							,		a						:		List[Any]      							=			outputs

    return state.loss_fn(
        A_  ,   A_  ,   A_  ,   A_  ,   A_  ,   A_  ,   )

  a							,		a						:		List[str]      							=			jax.random.split(A_       )
  a						:		List[str]      							=			jax.value_and_grad(A_       )
  a							,		a						:		Dict      							=			grad_fn(state.params       )
  a						:		Tuple      							=			jax.lax.pmean({"loss": loss}  ,   axis_name="batch"       )
  a						:		Optional[int]      							=			jax.lax.pmean(A_  ,   "batch"       )

  a						:		List[Any]      							=			state.apply_gradients(grads=A_       )
  return state, metrics, new_drp_rng


@partial(jax.pmap  ,   axis_name="batch"       )
def      lowercase			(				A_  ,   **A_       )->      str:
  '''simple docstring'''







  a						:		Dict      							=			model_inputs.pop("start_labels"       )
  a						:		str      							=			model_inputs.pop("end_labels"       )
  a						:		Any      							=			model_inputs.pop("pooled_labels"       )

  a						:		Any      							=			state.apply_fn(**A_  ,   params=state.params  ,   train=A_       )
  a							,		a							,		a						:		str      							=			outputs

  a						:		Dict      							=			state.loss_fn(A_  ,   A_  ,   A_  ,   A_  ,   A_  ,   A_       )
  a						:		List[str]      							=			jax.lax.pmean({"loss": loss}  ,   axis_name="batch"       )
  return metrics






class 						_A  (  train_state.TrainState  ):







    """simple docstring"""




    UpperCAmelCase       :							Callable	=       struct.field(pytree_node=_a  )






@dataclass
class 						_A  :







    """simple docstring"""




    UpperCAmelCase       :							Args
    UpperCAmelCase       :							Callable
    UpperCAmelCase       :							Callable
    UpperCAmelCase       :							Callable
    UpperCAmelCase       :							Callable
    UpperCAmelCase       :							wandb
    UpperCAmelCase       :							Callable	=       None






    def 	__snake_case							(					self				:    Optional[int]				, __UpperCAmelCase				:    List[str]				, __UpperCAmelCase				:    str				, __UpperCAmelCase				:    int				, __UpperCAmelCase				:    Optional[int]=None):
      a						:		Optional[int]      							=			model.params
      a						:		str      							=			TrainState.create(
          apply_fn=model.__call__				, params=__UpperCAmelCase				, tx=__UpperCAmelCase				, loss_fn=__UpperCAmelCase				, )
      if ckpt_dir is not None:
        a							,		a							,		a							,		a							,		a						:		Optional[Any]      							=			restore_checkpoint(__UpperCAmelCase				, __UpperCAmelCase)
        a						:		Union[str, Any]      							=			{
            "lr": args.lr,
            "init_lr": args.init_lr,
            "warmup_steps": args.warmup_steps,
            "num_train_steps": num_train_steps,
            "weight_decay": args.weight_decay,
        }
        a							,		a						:		List[Any]      							=			build_tx(**__UpperCAmelCase)
        a						:		str      							=			train_state.TrainState(
            step=__UpperCAmelCase				, apply_fn=model.__call__				, params=__UpperCAmelCase				, tx=__UpperCAmelCase				, opt_state=__UpperCAmelCase				, )
        a						:		Union[str, Any]      							=			args
        a						:		Tuple      							=			data_collator
        a						:		Optional[Any]      							=			lr
        a						:		List[str]      							=			params
      a						:		Tuple      							=			jax_utils.replicate(__UpperCAmelCase)
      return state






    def 	__snake_case							(					self				:    Tuple				, __UpperCAmelCase				:    Union[str, Any]				, __UpperCAmelCase				:    str				, __UpperCAmelCase				:    Union[str, Any]):
      a						:		Optional[int]      							=			self.args
      a						:		int      							=			len(__UpperCAmelCase) // args.batch_size

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

            a						:		int      							=			self.evaluate(__UpperCAmelCase				, __UpperCAmelCase)
            a						:		int      							=			{
                "step": state_step.item(),
                "eval_loss": eval_loss.item(),
                "tr_loss": tr_loss,
                "lr": lr.item(),
            }
            tqdm.write(str(__UpperCAmelCase))
            self.logger.log(__UpperCAmelCase				, commit=__UpperCAmelCase)

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






    def 	__snake_case							(					self				:    Optional[int]				, __UpperCAmelCase				:    Optional[Any]				, __UpperCAmelCase				:    List[str]):
      a						:		List[str]      							=			get_batched_dataset(__UpperCAmelCase				, self.args.batch_size)
      a						:		Optional[Any]      							=			len(__UpperCAmelCase) // self.args.batch_size
      a						:		Dict      							=			jnp.array(0				, dtype=jnp.floataa)
      a						:		Any      							=			0
      for batch in tqdm(__UpperCAmelCase				, total=__UpperCAmelCase				, desc="Evaluating ... "):
        a						:		Tuple      							=			self.data_collator(__UpperCAmelCase)
        a						:		List[str]      							=			self.val_step_fn(__UpperCAmelCase				, **__UpperCAmelCase)
        running_loss += jax_utils.unreplicate(metrics["loss"])
        i += 1
      return running_loss / i






    def 	__snake_case							(					self				:    Dict				, __UpperCAmelCase				:    Union[str, Any]				, __UpperCAmelCase				:    Dict):
      a						:		List[str]      							=			jax_utils.unreplicate(__UpperCAmelCase)
      print(f'''SAVING CHECKPOINT IN {save_dir}'''				, end=" ... ")
      self.model_save_fn(__UpperCAmelCase				, params=state.params)
      with open(os.path.join(__UpperCAmelCase				, "opt_state.msgpack")				, "wb") as f:
        f.write(to_bytes(state.opt_state))
      joblib.dump(self.args				, os.path.join(__UpperCAmelCase				, "args.joblib"))
      joblib.dump(self.data_collator				, os.path.join(__UpperCAmelCase				, "data_collator.joblib"))
      with open(os.path.join(__UpperCAmelCase				, "training_state.json")				, "w") as f:
        json.dump({"step": state.step.item()}				, __UpperCAmelCase)
      print("DONE")






def      lowercase			(				A_  ,   A_       )->      Tuple:
  '''simple docstring'''







  print(F'''RESTORING CHECKPOINT FROM {save_dir}'''  ,   end=" ... "       )
  with open(os.path.join(A_  ,   "flax_model.msgpack"       )  ,   "rb"       ) as f:
    a						:		Union[str, Any]      							=			from_bytes(state.params  ,   f.read()       )

  with open(os.path.join(A_  ,   "opt_state.msgpack"       )  ,   "rb"       ) as f:
    a						:		List[str]      							=			from_bytes(state.opt_state  ,   f.read()       )

  a						:		Any      							=			joblib.load(os.path.join(A_  ,   "args.joblib"       )       )
  a						:		Tuple      							=			joblib.load(os.path.join(A_  ,   "data_collator.joblib"       )       )

  with open(os.path.join(A_  ,   "training_state.json"       )  ,   "r"       ) as f:
    a						:		List[Any]      							=			json.load(A_       )
  a						:		Dict      							=			training_state["step"]

  print("DONE"       )
  return params, opt_state, step, args, data_collator


def      lowercase			(				A_  ,   A_  ,   A_  ,   A_       )->      List[str]:
  '''simple docstring'''







  a						:		Optional[Any]      							=			num_train_steps - warmup_steps
  a						:		List[str]      							=			optax.linear_schedule(init_value=A_  ,   end_value=A_  ,   transition_steps=A_       )
  a						:		str      							=			optax.linear_schedule(init_value=A_  ,   end_value=1e-7  ,   transition_steps=A_       )
  a						:		Union[str, Any]      							=			optax.join_schedules(schedules=[warmup_fn, decay_fn]  ,   boundaries=[warmup_steps]       )
  return lr







def      lowercase			(				A_  ,   A_  ,   A_  ,   A_  ,   A_       )->      List[Any]:
  '''simple docstring'''







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

  a						:		Dict      							=			scheduler_fn(A_  ,   A_  ,   A_  ,   A_       )

  a						:		str      							=			optax.adamw(learning_rate=A_  ,   weight_decay=A_  ,   mask=A_       )
  return tx, lr













import json
import os
import unittest

from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import (
    VOCAB_FILES_NAMES,
    GPTSanJapaneseTokenizer,
)
from transformers.testing_utils import require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin







@require_tokenizers
class     __snake_case       (							__lowerCamelCase   ,			unittest.TestCase			):





       '''simple docstring'''







       lowerCAmelCase__      		=     GPTSanJapaneseTokenizer
       lowerCAmelCase__      		=     False
       lowerCAmelCase__      		=     {"""do_clean_text""": False, """add_prefix_space""": False}




       def 							UpperCAmelCase__ (  self :    Union[str, Any]		):
         super().setUp()

         # fmt: off
         __snake_case:						str   =						["""こん""", """こんに""", """にちは""", """ばんは""", """世界,㔺界""", """、""", """。""", """<BR>""", """<SP>""", """<TAB>""", """<URL>""", """<EMAIL>""", """<TEL>""", """<DATE>""", """<PRICE>""", """<BLOCK>""", """<KIGOU>""", """<U2000U2BFF>""", """<|emoji1|>""", """<unk>""", """<|bagoftoken|>""", """<|endoftext|>"""]
         # fmt: on
         __snake_case:						List[Any]   =						{"""emoji""": {"""\ud83d\ude00""": """<|emoji1|>"""}, """emoji_inv""": {"""<|emoji1|>""": """\ud83d\ude00"""}}  # 😀
         __snake_case:						Optional[int]   =						{"""unk_token""": """<unk>"""}

         __snake_case:						Any   =						os.path.join(self.tmpdirname							,				VOCAB_FILES_NAMES["""vocab_file"""]		)
         __snake_case:						int   =						os.path.join(self.tmpdirname							,				VOCAB_FILES_NAMES["""emoji_file"""]		)
         with open(self.vocab_file							,				"""w"""							,				encoding="""utf-8"""		) as vocab_writer:
           vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens]		)		)
         with open(self.emoji_file							,				"""w"""		) as emoji_writer:
           emoji_writer.write(json.dumps(A		)		)




       def 							UpperCAmelCase__ (  self :    Optional[int]							,				**A :    int		):
         kwargs.update(self.special_tokens_map		)
         return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname							,				**A		)




       def 							UpperCAmelCase__ (  self :    Optional[Any]							,				A :    Dict		):
         __snake_case:						Tuple   =						"""こんにちは、世界。 \nこんばんは、㔺界。😀"""
         __snake_case:						str   =						"""こんにちは、世界。 \nこんばんは、世界。😀"""
         return input_text, output_text




       def 							UpperCAmelCase__ (  self :    Optional[int]							,				A :    Optional[int]		):
         __snake_case  ,   __snake_case:						Optional[int]   =						self.get_input_output_texts(A		)
         __snake_case:						Optional[Any]   =						tokenizer.encode(A							,				add_special_tokens=A		)
         __snake_case:						int   =						tokenizer.decode(A							,				clean_up_tokenization_spaces=A		)
         return text, ids




       def 							UpperCAmelCase__ (  self :    int		):
         pass  # TODO add if relevant




       def 							UpperCAmelCase__ (  self :    Dict		):
         pass  # TODO add if relevant




       def 							UpperCAmelCase__ (  self :    Optional[int]		):
         pass  # TODO add if relevant




       def 							UpperCAmelCase__ (  self :    Union[str, Any]		):
         __snake_case:						Dict   =						self.get_tokenizer()

         # Testing tokenization
         __snake_case:						List[str]   =						"""こんにちは、世界。　こんばんは、㔺界。"""
         __snake_case:						Optional[int]   =						["""こん""", """にちは""", """、""", """世界""", """。""", """<SP>""", """こん""", """ばんは""", """、""", """㔺界""", """。"""]
         __snake_case:						Any   =						tokenizer.tokenize(A		)
         self.assertListEqual(A							,				A		)

         # Testing conversion to ids without special tokens
         __snake_case:						str   =						[0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6]
         __snake_case:						str   =						tokenizer.convert_tokens_to_ids(A		)
         self.assertListEqual(A							,				A		)

         # Testing conversion to ids with special tokens
         __snake_case:						Optional[int]   =						tokens + [tokenizer.unk_token]
         __snake_case:						List[str]   =						[0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 19]
         __snake_case:						str   =						tokenizer.convert_tokens_to_ids(A		)
         self.assertListEqual(A							,				A		)




       def 							UpperCAmelCase__ (  self :    str		):
         __snake_case:						Union[str, Any]   =						self.get_tokenizer()

         # Testing tokenization
         __snake_case:						Optional[Any]   =						"""こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。"""
         __snake_case:						Optional[Any]   =						"""こんにちは、、、、世界。こんばんは、、、、世界。"""
         __snake_case:						Union[str, Any]   =						tokenizer.encode(A		)
         __snake_case:						List[Any]   =						tokenizer.decode(A		)
         self.assertEqual(A							,				A		)




       @slow
       def 							UpperCAmelCase__ (  self :    Any		):
         __snake_case:						Dict   =						self.tokenizer_class.from_pretrained("""Tanrei/GPTSAN-japanese"""		)

         # Testing tokenization
         __snake_case:						Any   =						"""こんにちは、世界。"""
         __snake_case:						Tuple   =						"""こんばんは、㔺界。😀"""
         __snake_case:						Optional[Any]   =						"""こんにちは、世界。こんばんは、世界。😀"""
         __snake_case:						int   =						tokenizer.encode(prefix_text + input_text		)
         __snake_case:						Union[str, Any]   =						tokenizer.encode(""""""							,				prefix_text=prefix_text + input_text		)
         __snake_case:						Tuple   =						tokenizer.encode(A							,				prefix_text=A		)
         __snake_case:						Union[str, Any]   =						tokenizer.decode(A		)
         __snake_case:						Dict   =						tokenizer.decode(A		)
         __snake_case:						Optional[Any]   =						tokenizer.decode(A		)
         self.assertEqual(A							,				A		)
         self.assertEqual(A							,				A		)
         self.assertEqual(A							,				A		)




       @slow
       def 							UpperCAmelCase__ (  self :    List[str]		):
         __snake_case:						int   =						self.tokenizer_class.from_pretrained("""Tanrei/GPTSAN-japanese"""		)

         # Testing tokenization
         __snake_case:						Optional[int]   =						"""こんにちは、世界。"""
         __snake_case:						Any   =						"""こんばんは、㔺界。😀"""

         __snake_case:						Optional[int]   =						len(tokenizer.encode(A		)		) - 2
         __snake_case:						str   =						len(tokenizer.encode(A		)		) - 2

         __snake_case:						Dict   =						[1] + [0] * (len_prefix + len_text + 1)
         __snake_case:						str   =						[1] * (len_prefix + len_text + 1) + [0]
         __snake_case:						List[Any]   =						[1] + [1] * (len_prefix) + [0] * (len_text + 1)

         __snake_case:						int   =						tokenizer(prefix_text + input_text		).token_type_ids
         __snake_case:						Optional[int]   =						tokenizer(""""""							,				prefix_text=prefix_text + input_text		).token_type_ids
         __snake_case:						Tuple   =						tokenizer(A							,				prefix_text=A		).token_type_ids
         self.assertListEqual(A							,				A		)
         self.assertListEqual(A							,				A		)
         self.assertListEqual(A							,				A		)




       @slow
       def 							UpperCAmelCase__ (  self :    Dict		):
         __snake_case:						Dict   =						self.tokenizer_class.from_pretrained("""Tanrei/GPTSAN-japanese"""		)

         __snake_case:						int   =						tokenizer.encode("""あンいワ"""		)
         __snake_case:						Optional[int]   =						tokenizer.encode(""""""							,				prefix_text="""あンいワ"""		)
         __snake_case:						List[Any]   =						tokenizer.encode("""いワ"""							,				prefix_text="""あン"""		)

         self.assertEqual(tokenizer.decode(A		)							,				tokenizer.decode(A		)		)
         self.assertEqual(tokenizer.decode(A		)							,				tokenizer.decode(A		)		)
         self.assertNotEqual(A							,				A		)
         self.assertNotEqual(A							,				A		)
         self.assertEqual(x_token_a[1]							,				x_token_a[-1]		)  # SEG token
         self.assertEqual(x_token_a[1]							,				x_token_a[3]		)  # SEG token




       @slow
       def 							UpperCAmelCase__ (  self :    int		):
         __snake_case:						List[str]   =						self.tokenizer_class.from_pretrained("""Tanrei/GPTSAN-japanese"""		)

         __snake_case:						Union[str, Any]   =						[["""武田信玄""", """は、"""], ["""織田信長""", """の配下の、"""]]
         __snake_case:						Optional[int]   =						tokenizer(A							,				padding=A		)
         __snake_case:						int   =						tokenizer.batch_encode_plus(A							,				padding=A		)

         # fmt: off
         __snake_case:						List[str]   =						[[35_993, 8_640, 25_948, 35_998, 30_647, 35_675, 35_999, 35_999], [35_993, 10_382, 9_868, 35_998, 30_646, 9_459, 30_646, 35_675]]
         __snake_case:						int   =						[[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]]
         __snake_case:						Dict   =						[[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]]
         # fmt: on
         self.assertListEqual(x_token.input_ids							,				A		)
         self.assertListEqual(x_token.token_type_ids							,				A		)
         self.assertListEqual(x_token.attention_mask							,				A		)
         self.assertListEqual(x_token_a.input_ids							,				A		)
         self.assertListEqual(x_token_a.token_type_ids							,				A		)
         self.assertListEqual(x_token_a.attention_mask							,				A		)




       def 							UpperCAmelCase__ (  self :    Union[str, Any]		):
         # Intentionally convert some words to accommodate character fluctuations unique to Japanese
         pass






       def 							UpperCAmelCase__ (  self :    List[str]		):
         # tokenizer has no padding token
         pass






