


import os
import pickle
import tempfile
import unittest
from typing import Callable, Optional

import numpy as np

from transformers import (
    BatchEncoding,
    BertTokenizer,
    BertTokenizerFast,
    PreTrainedTokenizer,
    PreTrainedTokenizerFast,
    TensorType,
    TokenSpan,
    is_tokenizers_available,
)
from transformers.models.gpta.tokenization_gpta import GPTaTokenizer
from transformers.testing_utils import CaptureStderr, require_flax, require_tf, require_tokenizers, require_torch, slow


if is_tokenizers_available():
			from tokenizers import Tokenizer
			from tokenizers.models import WordPiece



class      snake_case__	(   unittest.TestCase	):
				def 			UpperCamelCase_    (	self  ,   _UpperCAmelCase   ):




										"""simple docstring"""




										__magic_name__					:				Dict				=   list(tokenizer_class.max_model_input_sizes.keys()   )
										for model_name in sa_models[:1]:
																__magic_name__					:				Any				=   tokenizer_class.from_pretrained(_UpperCAmelCase   )
																self.assertIsNotNone(_UpperCAmelCase   )
																self.assertIsInstance(_UpperCAmelCase  ,   _UpperCAmelCase   )
																self.assertIsInstance(_UpperCAmelCase  ,   _UpperCAmelCase   )

																for special_tok in tokenizer.all_special_tokens:
																						self.assertIsInstance(_UpperCAmelCase  ,   _UpperCAmelCase   )
																						__magic_name__					:				Dict				=   tokenizer.convert_tokens_to_ids(_UpperCAmelCase   )
																						self.assertIsInstance(_UpperCAmelCase  ,   _UpperCAmelCase   )
				def 			UpperCamelCase_    (	self  ,   _UpperCAmelCase  ,   _UpperCAmelCase = None   ):




										"""simple docstring"""




										__magic_name__					:				Dict				=   pickle.dumps(_UpperCAmelCase   )
										self.assertIsNotNone(_UpperCAmelCase   )

										__magic_name__					:				Union[str, Any]				=   pickle.loads(_UpperCAmelCase   )

										# Ensure is_fast is correctly restored
										self.assertEqual(be_restored.is_fast  ,   be_original.is_fast   )

										# Ensure encodings are potentially correctly restored
										if be_original.is_fast:
																self.assertIsNotNone(be_restored.encodings   )
										else:
																self.assertIsNone(be_restored.encodings   )

										# Ensure the keys are the same
										for original_v, restored_v in zip(be_original.values()  ,   be_restored.values()   ):
																if equal_op:
																						self.assertTrue(equal_op(_UpperCAmelCase  ,   _UpperCAmelCase   )   )
																else:
																						self.assertEqual(_UpperCAmelCase  ,   _UpperCAmelCase   )
				@slow
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										self.check_tokenizer_from_pretrained(_UpperCAmelCase   )
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										self.assertEqual(TensorType('tf'   )  ,   TensorType.TENSORFLOW   )
										self.assertEqual(TensorType('pt'   )  ,   TensorType.PYTORCH   )
										self.assertEqual(TensorType('np'   )  ,   TensorType.NUMPY   )
				@require_tokenizers
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										import numpy as np

										__magic_name__					:				Any				=   BertTokenizer.from_pretrained('bert-base-cased'   )
										__magic_name__					:				Tuple				=   BertTokenizerFast.from_pretrained('bert-base-cased'   )

										# Python no tensor
										with self.subTest('BatchEncoding (Python, return_tensors=None)'   ):
																self.assert_dump_and_restore(tokenizer_p('Small example to encode'   )   )

										with self.subTest('BatchEncoding (Python, return_tensors=NUMPY)'   ):
																self.assert_dump_and_restore(
																    tokenizer_p('Small example to encode'  ,   return_tensors=TensorType.NUMPY   )  ,   np.array_equal   )

										with self.subTest('BatchEncoding (Rust, return_tensors=None)'   ):
																self.assert_dump_and_restore(tokenizer_r('Small example to encode'   )   )

										with self.subTest('BatchEncoding (Rust, return_tensors=NUMPY)'   ):
																self.assert_dump_and_restore(
																    tokenizer_r('Small example to encode'  ,   return_tensors=TensorType.NUMPY   )  ,   np.array_equal   )
				@require_tf
				@require_tokenizers
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										import tensorflow as tf

										def tf_array_equals(_UpperCAmelCase  ,   _UpperCAmelCase   ):
																return tf.reduce_all(tf.equal(_UpperCAmelCase  ,   _UpperCAmelCase   )   )

										__magic_name__					:				Optional[int]				=   BertTokenizer.from_pretrained('bert-base-cased'   )
										__magic_name__					:				int				=   BertTokenizerFast.from_pretrained('bert-base-cased'   )

										with self.subTest('BatchEncoding (Python, return_tensors=TENSORFLOW)'   ):
																self.assert_dump_and_restore(
																    tokenizer_p('Small example to encode'  ,   return_tensors=TensorType.TENSORFLOW   )  ,   _UpperCAmelCase   )

										with self.subTest('BatchEncoding (Rust, return_tensors=TENSORFLOW)'   ):
																self.assert_dump_and_restore(
																    tokenizer_r('Small example to encode'  ,   return_tensors=TensorType.TENSORFLOW   )  ,   _UpperCAmelCase   )
				@require_torch
				@require_tokenizers
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										import torch

										__magic_name__					:				str				=   BertTokenizer.from_pretrained('bert-base-cased'   )
										__magic_name__					:				Optional[Any]				=   BertTokenizerFast.from_pretrained('bert-base-cased'   )

										with self.subTest('BatchEncoding (Python, return_tensors=PYTORCH)'   ):
																self.assert_dump_and_restore(
																    tokenizer_p('Small example to encode'  ,   return_tensors=TensorType.PYTORCH   )  ,   torch.equal   )

										with self.subTest('BatchEncoding (Rust, return_tensors=PYTORCH)'   ):
																self.assert_dump_and_restore(
																    tokenizer_r('Small example to encode'  ,   return_tensors=TensorType.PYTORCH   )  ,   torch.equal   )
				@require_tokenizers
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										__magic_name__					:				Union[str, Any]				=   BertTokenizer.from_pretrained('bert-base-cased'   )
										__magic_name__					:				Dict				=   BertTokenizerFast.from_pretrained('bert-base-cased'   )

										with self.subTest('Python Tokenizer'   ):
																self.assertFalse(tokenizer_p('Small example to_encode'   ).is_fast   )

										with self.subTest('Rust Tokenizer'   ):
																self.assertTrue(tokenizer_r('Small example to_encode'   ).is_fast   )
				@require_tokenizers
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										__magic_name__					:				Union[str, Any]				=   BertTokenizerFast.from_pretrained('bert-base-cased'   )
										__magic_name__					:				int				=   tokenizer_r(['Test', '\xad', 'test']  ,   is_split_into_words=_UpperCAmelCase   )

										self.assertEqual(encoded.word_to_tokens(0   )  ,   TokenSpan(start=1  ,   end=2   )   )
										self.assertEqual(encoded.word_to_tokens(1   )  ,   _UpperCAmelCase   )
										self.assertEqual(encoded.word_to_tokens(2   )  ,   TokenSpan(start=2  ,   end=3   )   )
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										__magic_name__					:				Tuple				=   BatchEncoding({'inputs': [[1, 2, 3], [4, 5, 6]], 'labels': [0, 1]}   )
										__magic_name__					:				str				=   batch.convert_to_tensors(tensor_type='np'   )
										self.assertEqual(tensor_batch['inputs'].shape  ,   (2, 3)   )
										self.assertEqual(tensor_batch['labels'].shape  ,   (2,)   )
										# test converting the converted
										with CaptureStderr() as cs:
																__magic_name__					:				Tuple				=   batch.convert_to_tensors(tensor_type='np'   )
										self.assertFalse(len(cs.err   )  ,   msg=F"should have no warning, but got {cs.err}"   )

										__magic_name__					:				Optional[Any]				=   BatchEncoding({'inputs': [1, 2, 3], 'labels': 0}   )
										__magic_name__					:				str				=   batch.convert_to_tensors(tensor_type='np'  ,   prepend_batch_axis=_UpperCAmelCase   )
										self.assertEqual(tensor_batch['inputs'].shape  ,   (1, 3)   )
										self.assertEqual(tensor_batch['labels'].shape  ,   (1,)   )
				@require_torch
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										__magic_name__					:				Tuple				=   BatchEncoding({'inputs': [[1, 2, 3], [4, 5, 6]], 'labels': [0, 1]}   )
										__magic_name__					:				int				=   batch.convert_to_tensors(tensor_type='pt'   )
										self.assertEqual(tensor_batch['inputs'].shape  ,   (2, 3)   )
										self.assertEqual(tensor_batch['labels'].shape  ,   (2,)   )
										# test converting the converted
										with CaptureStderr() as cs:
																__magic_name__					:				List[Any]				=   batch.convert_to_tensors(tensor_type='pt'   )
										self.assertFalse(len(cs.err   )  ,   msg=F"should have no warning, but got {cs.err}"   )

										__magic_name__					:				List[str]				=   BatchEncoding({'inputs': [1, 2, 3], 'labels': 0}   )
										__magic_name__					:				int				=   batch.convert_to_tensors(tensor_type='pt'  ,   prepend_batch_axis=_UpperCAmelCase   )
										self.assertEqual(tensor_batch['inputs'].shape  ,   (1, 3)   )
										self.assertEqual(tensor_batch['labels'].shape  ,   (1,)   )
				@require_tf
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										__magic_name__					:				List[str]				=   BatchEncoding({'inputs': [[1, 2, 3], [4, 5, 6]], 'labels': [0, 1]}   )
										__magic_name__					:				Optional[int]				=   batch.convert_to_tensors(tensor_type='tf'   )
										self.assertEqual(tensor_batch['inputs'].shape  ,   (2, 3)   )
										self.assertEqual(tensor_batch['labels'].shape  ,   (2,)   )
										# test converting the converted
										with CaptureStderr() as cs:
																__magic_name__					:				Optional[int]				=   batch.convert_to_tensors(tensor_type='tf'   )
										self.assertFalse(len(cs.err   )  ,   msg=F"should have no warning, but got {cs.err}"   )

										__magic_name__					:				str				=   BatchEncoding({'inputs': [1, 2, 3], 'labels': 0}   )
										__magic_name__					:				Any				=   batch.convert_to_tensors(tensor_type='tf'  ,   prepend_batch_axis=_UpperCAmelCase   )
										self.assertEqual(tensor_batch['inputs'].shape  ,   (1, 3)   )
										self.assertEqual(tensor_batch['labels'].shape  ,   (1,)   )
				@require_flax
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										__magic_name__					:				Optional[int]				=   BatchEncoding({'inputs': [[1, 2, 3], [4, 5, 6]], 'labels': [0, 1]}   )
										__magic_name__					:				str				=   batch.convert_to_tensors(tensor_type='jax'   )
										self.assertEqual(tensor_batch['inputs'].shape  ,   (2, 3)   )
										self.assertEqual(tensor_batch['labels'].shape  ,   (2,)   )
										# test converting the converted
										with CaptureStderr() as cs:
																__magic_name__					:				Union[str, Any]				=   batch.convert_to_tensors(tensor_type='jax'   )
										self.assertFalse(len(cs.err   )  ,   msg=F"should have no warning, but got {cs.err}"   )

										__magic_name__					:				Optional[int]				=   BatchEncoding({'inputs': [1, 2, 3], 'labels': 0}   )
										__magic_name__					:				List[Any]				=   batch.convert_to_tensors(tensor_type='jax'  ,   prepend_batch_axis=_UpperCAmelCase   )
										self.assertEqual(tensor_batch['inputs'].shape  ,   (1, 3)   )
										self.assertEqual(tensor_batch['labels'].shape  ,   (1,)   )
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										__magic_name__					:				Dict				=   [{'input_ids': np.array([0, 1, 2]   )}, {'input_ids': np.array([0, 1, 2, 3]   )}]
										__magic_name__					:				List[str]				=   BertTokenizer.from_pretrained('bert-base-cased'   )

										__magic_name__					:				Tuple				=   tokenizer.pad(_UpperCAmelCase  ,   padding=_UpperCAmelCase   )
										self.assertTrue(isinstance(batch['input_ids']  ,   np.ndarray   )   )
										self.assertEqual(batch['input_ids'].tolist()  ,   [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]   )
										__magic_name__					:				Optional[Any]				=   tokenizer.pad(_UpperCAmelCase  ,   padding=_UpperCAmelCase  ,   return_tensors='np'   )
										self.assertTrue(isinstance(batch['input_ids']  ,   np.ndarray   )   )
										self.assertEqual(batch['input_ids'].tolist()  ,   [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]   )
				@require_torch
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										import torch

										__magic_name__					:				List[str]				=   [{'input_ids': torch.tensor([0, 1, 2]   )}, {'input_ids': torch.tensor([0, 1, 2, 3]   )}]
										__magic_name__					:				str				=   BertTokenizer.from_pretrained('bert-base-cased'   )

										__magic_name__					:				Optional[int]				=   tokenizer.pad(_UpperCAmelCase  ,   padding=_UpperCAmelCase   )
										self.assertTrue(isinstance(batch['input_ids']  ,   torch.Tensor   )   )
										self.assertEqual(batch['input_ids'].tolist()  ,   [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]   )
										__magic_name__					:				List[Any]				=   tokenizer.pad(_UpperCAmelCase  ,   padding=_UpperCAmelCase  ,   return_tensors='pt'   )
										self.assertTrue(isinstance(batch['input_ids']  ,   torch.Tensor   )   )
										self.assertEqual(batch['input_ids'].tolist()  ,   [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]   )
				@require_tf
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										import tensorflow as tf

										__magic_name__					:				Dict				=   [{'input_ids': tf.constant([0, 1, 2]   )}, {'input_ids': tf.constant([0, 1, 2, 3]   )}]
										__magic_name__					:				Union[str, Any]				=   BertTokenizer.from_pretrained('bert-base-cased'   )

										__magic_name__					:				Optional[int]				=   tokenizer.pad(_UpperCAmelCase  ,   padding=_UpperCAmelCase   )
										self.assertTrue(isinstance(batch['input_ids']  ,   tf.Tensor   )   )
										self.assertEqual(batch['input_ids'].numpy().tolist()  ,   [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]   )
										__magic_name__					:				Tuple				=   tokenizer.pad(_UpperCAmelCase  ,   padding=_UpperCAmelCase  ,   return_tensors='tf'   )
										self.assertTrue(isinstance(batch['input_ids']  ,   tf.Tensor   )   )
										self.assertEqual(batch['input_ids'].numpy().tolist()  ,   [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]   )
				@require_tokenizers
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										__magic_name__					:				Tuple				=   Tokenizer(WordPiece(unk_token='[UNK]'   )   )
										PreTrainedTokenizerFast(tokenizer_object=_UpperCAmelCase   )





				@require_tokenizers
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										__magic_name__					:				Dict				=   Tokenizer(WordPiece(unk_token='[UNK]'   )   )
										with tempfile.TemporaryDirectory() as tmpdirname:
																bert_tokenizer.save(os.path.join(_UpperCAmelCase  ,   'tokenizer.json'   )   )
																PreTrainedTokenizerFast(tokenizer_file=os.path.join(_UpperCAmelCase  ,   'tokenizer.json'   )   )






from __future__ import annotations

from typing import Any
def 			__SCREAMING_SNAKE_CASE							(					*lowercase__	:list[list[int]]					)							->	list[list[int]]:
						if all(_check_not_integer(lowercase__					) for m in matrix_s					):
												for i in matrix_s[1:]:
																		_verify_matrix_sizes(matrix_s[0]   ,    lowercase__					)
												return [[sum(lowercase__					) for t in zip(*lowercase__					)] for m in zip(*lowercase__					)]
						raise TypeError('Expected a matrix, got int/list instead'					)
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:list[list[int]]   ,    lowercase__	:list[list[int]]					)							->	list[list[int]]:
						if (
						    _check_not_integer(lowercase__					)
						    and _check_not_integer(lowercase__					)
						    and _verify_matrix_sizes(lowercase__   ,    lowercase__					)
						):
												return [[i - j for i, j in zip(*lowercase__					)] for m in zip(lowercase__   ,    lowercase__					)]
						raise TypeError('Expected a matrix, got int/list instead'					)
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:list[list[int]]   ,    lowercase__	:int | float					)							->	list[list[float]]:
						return [[x * n for x in row] for row in matrix]
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:list[list[int]]   ,    lowercase__	:list[list[int]]					)							->	list[list[int]]:
						if _check_not_integer(lowercase__					) and _check_not_integer(lowercase__					):
												__magic_name__		,			__magic_name__					:				str				=   _verify_matrix_sizes(lowercase__   ,    lowercase__					)

						if cols[0] != rows[1]:
												__magic_name__					:				Union[str, Any]				=   (
												    'Cannot multiply matrix of dimensions '
												    f"({rows[0]},{cols[0]}) and ({rows[1]},{cols[1]})"
												)
												raise ValueError(lowercase__					)
						return [
						    [sum(m * n for m, n in zip(lowercase__   ,    lowercase__					)					) for j in zip(*lowercase__					)] for i in matrix_a
						]
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:int					)							->	list[list[int]]:
						__magic_name__					:				Tuple				=   int(lowercase__					)
						return [[int(row == column					) for column in range(lowercase__					)] for row in range(lowercase__					)]
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:list[list[int]]   ,    lowercase__	:bool = True					)							->	list[list[int]] | map[list[int]]:
						if _check_not_integer(lowercase__					):
												if return_map:
																		return map(lowercase__   ,    zip(*lowercase__					)					)
												else:
																		return list(map(lowercase__   ,    zip(*lowercase__					)					)					)
						raise TypeError('Expected a matrix, got int/list instead'					)
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:list[list[int]]   ,    lowercase__	:int   ,    lowercase__	:int					)							->	list[list[int]]:
						__magic_name__					:				int				=   matrix[:row] + matrix[row + 1 :]
						return [row[:column] + row[column + 1 :] for row in minor]
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:list[list[int]]					)							->	Any:
						if len(lowercase__					) == 1:
												return matrix[0][0]

						return sum(
						    x * determinant(minor(lowercase__   ,    0   ,    lowercase__					)					) * (-1) ** i
						    for i, x in enumerate(matrix[0]					)					)
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:list[list[int]]					)							->	list[list[float]] | None:
						__magic_name__					:				Tuple				=   determinant(lowercase__					)
						if det == 0:
												return None

						__magic_name__					:				Optional[int]				=   [
						    [determinant(minor(lowercase__   ,    lowercase__   ,    lowercase__					)					) for j in range(len(lowercase__					)					)]
						    for i in range(len(lowercase__					)					)
						]

						__magic_name__					:				Optional[Any]				=   [
						    [x * (-1) ** (row + col) for col, x in enumerate(matrix_minor[row]					)]
						    for row in range(len(lowercase__					)					)
						]
						__magic_name__					:				Optional[Any]				=   list(transpose(lowercase__					)					)
						return scalar_multiply(lowercase__   ,    1 / det					)
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:list[list[int]]					)							->	bool:
						return not isinstance(lowercase__   ,    lowercase__					) and not isinstance(matrix[0]   ,    lowercase__					)
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:list[list[int]]					)							->	tuple[int, int]:
						return len(lowercase__					), len(matrix[0]					)
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:list[list[int]]   ,    lowercase__	:list[list[int]]					)							->	tuple[tuple[int, int], tuple[int, int]]:
						__magic_name__					:				str				=   _shape(lowercase__					) + _shape(lowercase__					)
						if shape[0] != shape[3] or shape[1] != shape[2]:
												__magic_name__					:				Optional[Any]				=   (
												    'operands could not be broadcast together with shape '
												    f"({shape[0], shape[1]}), ({shape[2], shape[3]})"
												)
												raise ValueError(lowercase__					)
						return (shape[0], shape[2]), (shape[1], shape[3])
def 			__SCREAMING_SNAKE_CASE							(					)							->	None:
						__magic_name__					:				Dict				=   [[1_2, 1_0], [3, 9]]
						__magic_name__					:				Optional[int]				=   [[3, 4], [7, 4]]
						__magic_name__					:				Optional[Any]				=   [[1_1, 1_2, 1_3, 1_4], [2_1, 2_2, 2_3, 2_4], [3_1, 3_2, 3_3, 3_4], [4_1, 4_2, 4_3, 4_4]]
						__magic_name__					:				List[str]				=   [[3, 0, 2], [2, 0, -2], [0, 1, 1]]
						print(f"Add Operation, {add(lowercase__   ,    lowercase__					) = } \n"					)
						print(
						    f"Multiply Operation, {multiply(lowercase__   ,    lowercase__					) = } \n"   ,    )
						print(f"Identity: {identity(5					)}\n"					)
						print(f"Minor of {matrix_c} = {minor(lowercase__   ,    1   ,    2					)} \n"					)
						print(f"Determinant of {matrix_b} = {determinant(lowercase__					)} \n"					)
						print(f"Inverse of {matrix_d} = {inverse(lowercase__					)}\n"					)


if __name__ == "__main__":
			import doctest

			doctest.testmod()
			main()


