





"""simple docstring"""





from __future__ import annotations

import unittest

import numpy as np

from transformers import LayoutLMConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
							import tensorflow as tf

							from transformers.models.layoutlm.modeling_tf_layoutlm import (
							    TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
							    TFLayoutLMForMaskedLM,
							    TFLayoutLMForQuestionAnswering,
							    TFLayoutLMForSequenceClassification,
							    TFLayoutLMForTokenClassification,
							    TFLayoutLMModel,
							)
class 		SCREAMING_SNAKE_CASE_				:
				"""simple docstring"""




				def __init__(  self	:str    ,     __lowercase	:Any    ,     __lowercase	:Optional[int]=13    ,     __lowercase	:Dict=7    ,     __lowercase	:Optional[Any]=True    ,     __lowercase	:List[Any]=True    ,     __lowercase	:Optional[int]=True    ,     __lowercase	:Optional[int]=True    ,     __lowercase	:Tuple=99    ,     __lowercase	:Optional[Any]=32    ,     __lowercase	:List[str]=2    ,     __lowercase	:int=4    ,     __lowercase	:Any=37    ,     __lowercase	:Dict="gelu"    ,     __lowercase	:Optional[Any]=0.1    ,     __lowercase	:str=0.1    ,     __lowercase	:Optional[Any]=512    ,     __lowercase	:Union[str, Any]=16    ,     __lowercase	:Dict=2    ,     __lowercase	:int=0.02    ,     __lowercase	:List[str]=3    ,     __lowercase	:int=4    ,     __lowercase	:Optional[int]=None    ,     __lowercase	:Tuple=1000    ,     ):
											__lowerCamelCase   :   Union[str, Any]       =parent
											__lowerCamelCase   :   List[str]       =batch_size
											__lowerCamelCase   :   Union[str, Any]       =seq_length
											__lowerCamelCase   :   List[str]       =is_training
											__lowerCamelCase   :   Tuple       =use_input_mask
											__lowerCamelCase   :   Optional[int]       =use_token_type_ids
											__lowerCamelCase   :   Union[str, Any]       =use_labels
											__lowerCamelCase   :   Optional[Any]       =vocab_size
											__lowerCamelCase   :   Dict       =hidden_size
											__lowerCamelCase   :   Optional[Any]       =num_hidden_layers
											__lowerCamelCase   :   Union[str, Any]       =num_attention_heads
											__lowerCamelCase   :   List[Any]       =intermediate_size
											__lowerCamelCase   :   str       =hidden_act
											__lowerCamelCase   :   int       =hidden_dropout_prob
											__lowerCamelCase   :   Any       =attention_probs_dropout_prob
											__lowerCamelCase   :   Dict       =max_position_embeddings
											__lowerCamelCase   :   Any       =type_vocab_size
											__lowerCamelCase   :   Any       =type_sequence_label_size
											__lowerCamelCase   :   Optional[Any]       =initializer_range
											__lowerCamelCase   :   str       =num_labels
											__lowerCamelCase   :   Optional[Any]       =num_choices
											__lowerCamelCase   :   Optional[Any]       =scope
											__lowerCamelCase   :   List[str]       =range_bbox




				def        __lowercase	(  self	:Optional[int]      ):
											__lowerCamelCase   :   List[Any]       =ids_tensor([self.batch_size, self.seq_length]    ,     self.vocab_size      )

											# convert bbox to numpy since TF does not support item assignment
											__lowerCamelCase   :   Tuple       =ids_tensor([self.batch_size, self.seq_length, 4]    ,     self.range_bbox      ).numpy()
											# Ensure that bbox is legal
											for i in range(bbox.shape[0]      ):
																		for j in range(bbox.shape[1]      ):
																									if bbox[i, j, 3] < bbox[i, j, 1]:
																																__lowerCamelCase   :   Any       =bbox[i, j, 3]
																																__lowerCamelCase   :   List[str]       =bbox[i, j, 1]
																																__lowerCamelCase   :   List[Any]       =t
																									if bbox[i, j, 2] < bbox[i, j, 0]:
																																__lowerCamelCase   :   List[Any]       =bbox[i, j, 2]
																																__lowerCamelCase   :   Union[str, Any]       =bbox[i, j, 0]
																																__lowerCamelCase   :   Any       =t
											__lowerCamelCase   :   int       =tf.convert_to_tensor(__lowercase      )

											__lowerCamelCase   :   Union[str, Any]       =None
											if self.use_input_mask:
																		__lowerCamelCase   :   Any       =random_attention_mask([self.batch_size, self.seq_length]      )

											__lowerCamelCase   :   Any       =None
											if self.use_token_type_ids:
																		__lowerCamelCase   :   Optional[Any]       =ids_tensor([self.batch_size, self.seq_length]    ,     self.type_vocab_size      )

											__lowerCamelCase   :   List[str]       =None
											__lowerCamelCase   :   List[str]       =None
											__lowerCamelCase   :   List[Any]       =None
											if self.use_labels:
																		__lowerCamelCase   :   Tuple       =ids_tensor([self.batch_size]    ,     self.type_sequence_label_size      )
																		__lowerCamelCase   :   int       =ids_tensor([self.batch_size, self.seq_length]    ,     self.num_labels      )
																		__lowerCamelCase   :   Dict       =ids_tensor([self.batch_size]    ,     self.num_choices      )

											__lowerCamelCase   :   List[str]       =LayoutLMConfig(
											    vocab_size=self.vocab_size    ,     hidden_size=self.hidden_size    ,     num_hidden_layers=self.num_hidden_layers    ,     num_attention_heads=self.num_attention_heads    ,     intermediate_size=self.intermediate_size    ,     hidden_act=self.hidden_act    ,     hidden_dropout_prob=self.hidden_dropout_prob    ,     attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,     max_position_embeddings=self.max_position_embeddings    ,     type_vocab_size=self.type_vocab_size    ,     initializer_range=self.initializer_range    ,     )

											return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels




				def        __lowercase	(  self	:List[str]    ,     __lowercase	:Optional[Any]    ,     __lowercase	:List[str]    ,     __lowercase	:List[Any]    ,     __lowercase	:Optional[Any]    ,     __lowercase	:str    ,     __lowercase	:str    ,     __lowercase	:Dict    ,     __lowercase	:List[Any]      ):
											__lowerCamelCase   :   Union[str, Any]       =TFLayoutLMModel(config=__lowercase      )

											__lowerCamelCase   :   Tuple       =model(__lowercase    ,     __lowercase    ,     attention_mask=__lowercase    ,     token_type_ids=__lowercase      )
											__lowerCamelCase   :   Optional[Any]       =model(__lowercase    ,     __lowercase    ,     token_type_ids=__lowercase      )
											__lowerCamelCase   :   Any       =model(__lowercase    ,     __lowercase      )
											self.parent.assertEqual(result.last_hidden_state.shape    ,     (self.batch_size, self.seq_length, self.hidden_size)      )
											self.parent.assertEqual(result.pooler_output.shape    ,     (self.batch_size, self.hidden_size)      )




				def        __lowercase	(  self	:List[Any]    ,     __lowercase	:List[str]    ,     __lowercase	:List[Any]    ,     __lowercase	:List[str]    ,     __lowercase	:Optional[Any]    ,     __lowercase	:Union[str, Any]    ,     __lowercase	:List[Any]    ,     __lowercase	:int    ,     __lowercase	:Any      ):
											__lowerCamelCase   :   Tuple       =TFLayoutLMForMaskedLM(config=__lowercase      )

											__lowerCamelCase   :   int       =model(__lowercase    ,     __lowercase    ,     attention_mask=__lowercase    ,     token_type_ids=__lowercase    ,     labels=__lowercase      )
											self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, self.seq_length, self.vocab_size)      )




				def        __lowercase	(  self	:int    ,     __lowercase	:Optional[int]    ,     __lowercase	:List[Any]    ,     __lowercase	:List[str]    ,     __lowercase	:Any    ,     __lowercase	:Tuple    ,     __lowercase	:Optional[int]    ,     __lowercase	:Optional[Any]    ,     __lowercase	:List[str]      ):
											__lowerCamelCase   :   Optional[Any]       =self.num_labels
											__lowerCamelCase   :   Tuple       =TFLayoutLMForSequenceClassification(config=__lowercase      )

											__lowerCamelCase   :   Any       =model(__lowercase    ,     __lowercase    ,     attention_mask=__lowercase    ,     token_type_ids=__lowercase      )
											self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, self.num_labels)      )




				def        __lowercase	(  self	:List[Any]    ,     __lowercase	:Optional[int]    ,     __lowercase	:str    ,     __lowercase	:str    ,     __lowercase	:Any    ,     __lowercase	:Dict    ,     __lowercase	:List[str]    ,     __lowercase	:List[Any]    ,     __lowercase	:Any      ):
											__lowerCamelCase   :   Union[str, Any]       =self.num_labels
											__lowerCamelCase   :   List[Any]       =TFLayoutLMForTokenClassification(config=__lowercase      )

											__lowerCamelCase   :   Optional[int]       =model(__lowercase    ,     __lowercase    ,     attention_mask=__lowercase    ,     token_type_ids=__lowercase    ,     labels=__lowercase      )
											self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, self.seq_length, self.num_labels)      )




				def        __lowercase	(  self	:int    ,     __lowercase	:Optional[int]    ,     __lowercase	:Any    ,     __lowercase	:Tuple    ,     __lowercase	:List[Any]    ,     __lowercase	:List[Any]    ,     __lowercase	:List[Any]    ,     __lowercase	:int    ,     __lowercase	:Any      ):
											__lowerCamelCase   :   List[str]       =TFLayoutLMForQuestionAnswering(config=__lowercase      )

											__lowerCamelCase   :   List[Any]       =model(__lowercase    ,     __lowercase    ,     attention_mask=__lowercase    ,     token_type_ids=__lowercase      )
											self.parent.assertEqual(result.start_logits.shape    ,     (self.batch_size, self.seq_length)      )
											self.parent.assertEqual(result.end_logits.shape    ,     (self.batch_size, self.seq_length)      )




				def        __lowercase	(  self	:List[Any]      ):
											__lowerCamelCase   :   Dict       =self.prepare_config_and_inputs()
											(
											    (
											    __lowerCamelCase
											)     ,    (
											    __lowerCamelCase
											)     ,    (
											    __lowerCamelCase
											)     ,    (
											    __lowerCamelCase
											)     ,    (
											    __lowerCamelCase
											)     ,    (
											    __lowerCamelCase
											)     ,    (
											    __lowerCamelCase
											)     ,    (
											    __lowerCamelCase
											)     ,    
											)   :   Any       =config_and_inputs
											__lowerCamelCase   :   Union[str, Any]       ={
											    '''input_ids''': input_ids,
											    '''bbox''': bbox,
											    '''token_type_ids''': token_type_ids,
											    '''attention_mask''': input_mask,
											}
											return config, inputs_dict

@require_tf
class 		SCREAMING_SNAKE_CASE_				(     snake_case__							,	snake_case__							,	unittest.TestCase ):
				"""simple docstring"""
				__snake_case :							Dict									=		(
				    (
				        TFLayoutLMModel,
				        TFLayoutLMForMaskedLM,
				        TFLayoutLMForTokenClassification,
				        TFLayoutLMForSequenceClassification,
				        TFLayoutLMForQuestionAnswering,
				    )
				    if is_tf_available()
				    else ()
				)
				__snake_case :							Tuple									=		(
				    {
				        """feature-extraction""": TFLayoutLMModel,
				        """fill-mask""": TFLayoutLMForMaskedLM,
				        """text-classification""": TFLayoutLMForSequenceClassification,
				        """token-classification""": TFLayoutLMForTokenClassification,
				        """zero-shot""": TFLayoutLMForSequenceClassification,
				    }
				    if is_tf_available()
				    else {}
				)
				__snake_case :							Union[str, Any]									=		False
				__snake_case :							Optional[Any]									=		True
				__snake_case :							Union[str, Any]									=		10




				def        __lowercase	(  self	:Tuple      ):
											__lowerCamelCase   :   Union[str, Any]       =TFLayoutLMModelTester(self      )
											__lowerCamelCase   :   Any       =ConfigTester(self    ,     config_class=__lowercase    ,     hidden_size=37      )




				def        __lowercase	(  self	:Dict      ):
											self.config_tester.run_common_tests()




				def        __lowercase	(  self	:List[Any]      ):
											__lowerCamelCase   :   Tuple       =self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*__lowercase      )




				def        __lowercase	(  self	:Optional[int]      ):
											__lowerCamelCase   :   List[str]       =self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_masked_lm(*__lowercase      )




				def        __lowercase	(  self	:Dict      ):
											__lowerCamelCase   :   List[Any]       =self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_sequence_classification(*__lowercase      )




				def        __lowercase	(  self	:Dict      ):
											__lowerCamelCase   :   int       =self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_token_classification(*__lowercase      )




				def        __lowercase	(  self	:Optional[Any]      ):
											__lowerCamelCase   :   Dict       =self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_question_answering(*__lowercase      )




				@slow
				def        __lowercase	(  self	:Optional[int]      ):
											for model_name in TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		__lowerCamelCase   :   int       =TFLayoutLMModel.from_pretrained(__lowercase      )
																		self.assertIsNotNone(__lowercase      )




				@unittest.skip('''Onnx compliancy broke with TF 2.10'''      )
				def        __lowercase	(  self	:int      ):
											pass



def 					lowerCAmelCase_      (   ):


							'''simple docstring'''







							__lowerCamelCase   :   List[str]       =tf.convert_to_tensor([[101,1019,1014,1016,1037,12849,4747,1004,14246,2278,5439,4524,5002,2930,2193,2930,4341,3208,1005,1055,2171,2848,11300,3531,102],[101,4070,4034,7020,1024,3058,1015,1013,2861,1013,6070,19274,2772,6205,27814,16147,16147,4343,2047,10283,10969,14389,1012,2338,102]] )  # noqa: E231
							__lowerCamelCase   :   Optional[Any]       =tf.convert_to_tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],] )  # noqa: E231
							__lowerCamelCase   :   Union[str, Any]       =tf.convert_to_tensor([[[0,0,0,0],[423,237,440,251],[427,272,441,287],[419,115,437,129],[961,885,992,912],[256,38,330,58],[256,38,330,58],[336,42,353,57],[360,39,401,56],[360,39,401,56],[411,39,471,59],[479,41,528,59],[533,39,630,60],[67,113,134,131],[141,115,209,132],[68,149,133,166],[141,149,187,164],[195,148,287,165],[195,148,287,165],[195,148,287,165],[295,148,349,165],[441,149,492,166],[497,149,546,164],[64,201,125,218],[1000,1000,1000,1000]],[[0,0,0,0],[662,150,754,166],[665,199,742,211],[519,213,554,228],[519,213,554,228],[134,433,187,454],[130,467,204,480],[130,467,204,480],[130,467,204,480],[130,467,204,480],[130,467,204,480],[314,469,376,482],[504,684,582,706],[941,825,973,900],[941,825,973,900],[941,825,973,900],[941,825,973,900],[610,749,652,765],[130,659,168,672],[176,657,237,672],[238,657,312,672],[443,653,628,672],[443,653,628,672],[716,301,825,317],[1000,1000,1000,1000]]] )  # noqa: E231
							__lowerCamelCase   :   Union[str, Any]       =tf.convert_to_tensor([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]] )  # noqa: E231
							# these are sequence labels (i.e. at the token level)
							__lowerCamelCase   :   Tuple       =tf.convert_to_tensor([[-100,10,10,10,9,1,-100,7,7,-100,7,7,4,2,5,2,8,8,-100,-100,5,0,3,2,-100],[-100,12,12,12,-100,12,10,-100,-100,-100,-100,10,12,9,-100,-100,-100,10,10,10,9,12,-100,10,-100]] )  # noqa: E231
							# fmt: on

							return input_ids, attention_mask, bbox, token_type_ids, labels
@require_tf
class 		SCREAMING_SNAKE_CASE_				(     unittest.TestCase ):
				"""simple docstring"""




				@slow
				def        __lowercase	(  self	:Tuple      ):
											__lowerCamelCase   :   Any       =TFLayoutLMModel.from_pretrained('''microsoft/layoutlm-base-uncased'''      )

											__lowerCamelCase     ,    __lowerCamelCase     ,    __lowerCamelCase     ,    __lowerCamelCase     ,    __lowerCamelCase   :   Optional[int]       =prepare_layoutlm_batch_inputs()

											# forward pass
											__lowerCamelCase   :   Dict       =model(input_ids=__lowercase    ,     bbox=__lowercase    ,     attention_mask=__lowercase    ,     token_type_ids=__lowercase      )

											# test the sequence output on [0, :3, :3]
											__lowerCamelCase   :   Dict       =tf.convert_to_tensor(
											    [[0.1785, -0.1947, -0.0425], [-0.3254, -0.2807, 0.2553], [-0.5391, -0.3322, 0.3364]]    ,     )

											self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3]    ,     __lowercase    ,     atol=1e-3      )      )

											# test the pooled output on [1, :3]
											__lowerCamelCase   :   Tuple       =tf.convert_to_tensor([-0.6580, -0.0214, 0.8552]      )

											self.assertTrue(np.allclose(outputs.pooler_output[1, :3]    ,     __lowercase    ,     atol=1e-3      )      )




				@slow
				def        __lowercase	(  self	:Dict      ):
											# initialize model with randomly initialized sequence classification head
											__lowerCamelCase   :   Any       =TFLayoutLMForSequenceClassification.from_pretrained('''microsoft/layoutlm-base-uncased'''    ,     num_labels=2      )

											__lowerCamelCase     ,    __lowerCamelCase     ,    __lowerCamelCase     ,    __lowerCamelCase     ,    __lowerCamelCase   :   str       =prepare_layoutlm_batch_inputs()

											# forward pass
											__lowerCamelCase   :   Optional[Any]       =model(
											    input_ids=__lowercase    ,     bbox=__lowercase    ,     attention_mask=__lowercase    ,     token_type_ids=__lowercase    ,     labels=tf.convert_to_tensor([1, 1]      )    ,     )

											# test whether we get a loss as a scalar
											__lowerCamelCase   :   List[str]       =outputs.loss
											__lowerCamelCase   :   int       =(2,)
											self.assertEqual(loss.shape    ,     __lowercase      )

											# test the shape of the logits
											__lowerCamelCase   :   List[str]       =outputs.logits
											__lowerCamelCase   :   List[Any]       =(2, 2)
											self.assertEqual(logits.shape    ,     __lowercase      )




				@slow
				def        __lowercase	(  self	:List[Any]      ):
											# initialize model with randomly initialized token classification head
											__lowerCamelCase   :   Dict       =TFLayoutLMForTokenClassification.from_pretrained('''microsoft/layoutlm-base-uncased'''    ,     num_labels=13      )

											__lowerCamelCase     ,    __lowerCamelCase     ,    __lowerCamelCase     ,    __lowerCamelCase     ,    __lowerCamelCase   :   Union[str, Any]       =prepare_layoutlm_batch_inputs()

											# forward pass
											__lowerCamelCase   :   int       =model(
											    input_ids=__lowercase    ,     bbox=__lowercase    ,     attention_mask=__lowercase    ,     token_type_ids=__lowercase    ,     labels=__lowercase      )

											# test the shape of the logits
											__lowerCamelCase   :   str       =outputs.logits
											__lowerCamelCase   :   List[Any]       =tf.convert_to_tensor((2, 25, 13)      )
											self.assertEqual(logits.shape    ,     __lowercase      )




				@slow
				def        __lowercase	(  self	:int      ):
											# initialize model with randomly initialized token classification head
											__lowerCamelCase   :   Dict       =TFLayoutLMForQuestionAnswering.from_pretrained('''microsoft/layoutlm-base-uncased'''      )

											__lowerCamelCase     ,    __lowerCamelCase     ,    __lowerCamelCase     ,    __lowerCamelCase     ,    __lowerCamelCase   :   int       =prepare_layoutlm_batch_inputs()

											# forward pass
											__lowerCamelCase   :   List[Any]       =model(input_ids=__lowercase    ,     bbox=__lowercase    ,     attention_mask=__lowercase    ,     token_type_ids=__lowercase      )

											# test the shape of the logits
											__lowerCamelCase   :   Optional[int]       =tf.convert_to_tensor((2, 25)      )
											self.assertEqual(outputs.start_logits.shape    ,     __lowercase      )
											self.assertEqual(outputs.end_logits.shape    ,     __lowercase      )











"""simple docstring"""





import argparse
from typing import List

import evaluate
import numpy as np
import torch
from datasets import DatasetDict, load_dataset

# New Code #
# We'll be using StratifiedKFold for this example
from sklearn.model_selection import StratifiedKFold
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed

from accelerate import Accelerator, DistributedType


########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing how to perform Cross Validation,
# and builds off the `nlp_example.py` script.
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
#   - single CPU or single GPU
#   - multi GPUS (using PyTorch distributed mode)
#   - (multi) TPUs
#   - fp16 (mixed-precision) or fp32 (normal precision)
#
# To help focus on the differences in the code, building `DataLoaders`
# was refactored into its own function.
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################


_UpperCamelCase					      =   16
_UpperCamelCase					      =   32



def 					lowerCAmelCase_      (   SCREAMING_SNAKE_CASE							:				Accelerator     ,    SCREAMING_SNAKE_CASE							:				DatasetDict     ,    SCREAMING_SNAKE_CASE							:				List[int]     ,    SCREAMING_SNAKE_CASE							:				List[int]     ,    SCREAMING_SNAKE_CASE							:				int = 16 ):


							'''simple docstring'''







							__lowerCamelCase   :   Union[str, Any]       =AutoTokenizer.from_pretrained('''bert-base-cased''' )
							__lowerCamelCase   :   List[str]       =DatasetDict(
							    {
							        '''train''': dataset['''train'''].select(SCREAMING_SNAKE_CASE ),
							        '''validation''': dataset['''train'''].select(SCREAMING_SNAKE_CASE ),
							        '''test''': dataset['''validation'''],
							    } )

							def tokenize_function(SCREAMING_SNAKE_CASE							:				Optional[Any] ):
														# max_length=None => use the model max length (it's actually the default)
														__lowerCamelCase   :   Optional[int]       =tokenizer(examples['''sentence1''']     ,    examples['''sentence2''']     ,    truncation=SCREAMING_SNAKE_CASE     ,    max_length=SCREAMING_SNAKE_CASE )
														return outputs

							# Apply the method we just defined to all the examples in all the splits of the dataset
							# starting with the main process first:
							with accelerator.main_process_first():
														__lowerCamelCase   :   Optional[Any]       =datasets.map(
														    SCREAMING_SNAKE_CASE     ,    batched=SCREAMING_SNAKE_CASE     ,    remove_columns=['''idx''', '''sentence1''', '''sentence2''']     ,    )

							# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
							# transformers library
							__lowerCamelCase   :   Dict       =tokenized_datasets.rename_column('''label'''     ,    '''labels''' )

							def collate_fn(SCREAMING_SNAKE_CASE							:				List[str] ):
														# On TPU it's best to pad everything to the same length or training will be very slow.
														__lowerCamelCase   :   Tuple       =128 if accelerator.distributed_type == DistributedType.TPU else None
														# When using mixed precision we want round multiples of 8/16
														if accelerator.mixed_precision == "fp8":
																					__lowerCamelCase   :   List[str]       =16
														elif accelerator.mixed_precision != "no":
																					__lowerCamelCase   :   Tuple       =8
														else:
																					__lowerCamelCase   :   Optional[int]       =None

														return tokenizer.pad(
														    SCREAMING_SNAKE_CASE     ,    padding='''longest'''     ,    max_length=SCREAMING_SNAKE_CASE     ,    pad_to_multiple_of=SCREAMING_SNAKE_CASE     ,    return_tensors='''pt'''     ,    )

							# Instantiate dataloaders.
							__lowerCamelCase   :   int       =DataLoader(
							    tokenized_datasets['''train''']     ,    shuffle=SCREAMING_SNAKE_CASE     ,    collate_fn=SCREAMING_SNAKE_CASE     ,    batch_size=SCREAMING_SNAKE_CASE )
							__lowerCamelCase   :   Optional[Any]       =DataLoader(
							    tokenized_datasets['''validation''']     ,    shuffle=SCREAMING_SNAKE_CASE     ,    collate_fn=SCREAMING_SNAKE_CASE     ,    batch_size=SCREAMING_SNAKE_CASE )

							__lowerCamelCase   :   Tuple       =DataLoader(
							    tokenized_datasets['''test''']     ,    shuffle=SCREAMING_SNAKE_CASE     ,    collate_fn=SCREAMING_SNAKE_CASE     ,    batch_size=SCREAMING_SNAKE_CASE )

							return train_dataloader, eval_dataloader, test_dataloader



def 					lowerCAmelCase_      (   SCREAMING_SNAKE_CASE							:				Any     ,    SCREAMING_SNAKE_CASE							:				List[Any] ):


							'''simple docstring'''







							__lowerCamelCase   :   Optional[Any]       =[]
							# Download the dataset
							__lowerCamelCase   :   Any       =load_dataset('''glue'''     ,    '''mrpc''' )
							# Create our splits
							__lowerCamelCase   :   Optional[Any]       =StratifiedKFold(n_splits=int(args.num_folds ) )
							# Initialize accelerator
							__lowerCamelCase   :   str       =Accelerator(cpu=args.cpu     ,    mixed_precision=args.mixed_precision )
							# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
							__lowerCamelCase   :   Any       =config['''lr''']
							__lowerCamelCase   :   int       =int(config['''num_epochs'''] )
							__lowerCamelCase   :   Optional[int]       =int(config['''seed'''] )
							__lowerCamelCase   :   Any       =int(config['''batch_size'''] )

							__lowerCamelCase   :   List[str]       =evaluate.load('''glue'''     ,    '''mrpc''' )

							# If the batch size is too big we use gradient accumulation
							__lowerCamelCase   :   List[Any]       =1
							if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
														__lowerCamelCase   :   Optional[Any]       =batch_size // MAX_GPU_BATCH_SIZE
														__lowerCamelCase   :   List[Any]       =MAX_GPU_BATCH_SIZE

							set_seed(SCREAMING_SNAKE_CASE )

							# New Code #
							# Create our folds:
							__lowerCamelCase   :   str       =kfold.split(np.zeros(datasets['''train'''].num_rows )     ,    datasets['''train''']['''label'''] )
							__lowerCamelCase   :   Tuple       =[]
							# Iterate over them
							for i, (train_idxs, valid_idxs) in enumerate(SCREAMING_SNAKE_CASE ):
														__lowerCamelCase     ,    __lowerCamelCase     ,    __lowerCamelCase   :   Any       =get_fold_dataloaders(
														    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    )
														# Instantiate the model (we build the model here so that the seed also control new weights initialization)
														__lowerCamelCase   :   Optional[int]       =AutoModelForSequenceClassification.from_pretrained('''bert-base-cased'''     ,    return_dict=SCREAMING_SNAKE_CASE )

														# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
														# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
														# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
														__lowerCamelCase   :   Optional[Any]       =model.to(accelerator.device )

														# Instantiate optimizer
														__lowerCamelCase   :   Any       =AdamW(params=model.parameters()     ,    lr=SCREAMING_SNAKE_CASE )

														# Instantiate scheduler
														__lowerCamelCase   :   Dict       =get_linear_schedule_with_warmup(
														    optimizer=SCREAMING_SNAKE_CASE     ,    num_warmup_steps=100     ,    num_training_steps=(len(SCREAMING_SNAKE_CASE ) * num_epochs) // gradient_accumulation_steps     ,    )

														# Prepare everything
														# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
														# prepare method.
														__lowerCamelCase     ,    __lowerCamelCase     ,    __lowerCamelCase     ,    __lowerCamelCase     ,    __lowerCamelCase   :   Any       =accelerator.prepare(
														    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE )

														# Now we train the model
														for epoch in range(SCREAMING_SNAKE_CASE ):
																					model.train()
																					for step, batch in enumerate(SCREAMING_SNAKE_CASE ):
																												# We could avoid this line since we set the accelerator with `device_placement=True`.
																												batch.to(accelerator.device )
																												__lowerCamelCase   :   Dict       =model(**SCREAMING_SNAKE_CASE )
																												__lowerCamelCase   :   Optional[Any]       =outputs.loss
																												__lowerCamelCase   :   int       =loss / gradient_accumulation_steps
																												accelerator.backward(SCREAMING_SNAKE_CASE )
																												if step % gradient_accumulation_steps == 0:
																																			optimizer.step()
																																			lr_scheduler.step()
																																			optimizer.zero_grad()

																					model.eval()
																					for step, batch in enumerate(SCREAMING_SNAKE_CASE ):
																												# We could avoid this line since we set the accelerator with `device_placement=True`.
																												batch.to(accelerator.device )
																												with torch.no_grad():
																																			__lowerCamelCase   :   Optional[int]       =model(**SCREAMING_SNAKE_CASE )
																												__lowerCamelCase   :   int       =outputs.logits.argmax(dim=-1 )
																												__lowerCamelCase     ,    __lowerCamelCase   :   Union[str, Any]       =accelerator.gather_for_metrics((predictions, batch['''labels''']) )
																												metric.add_batch(
																												    predictions=SCREAMING_SNAKE_CASE     ,    references=SCREAMING_SNAKE_CASE     ,    )

																					__lowerCamelCase   :   str       =metric.compute()
																					# Use accelerator.print to print only on the main process.
																					accelerator.print(F'epoch {epoch}:'     ,    SCREAMING_SNAKE_CASE )

														# New Code #
														# We also run predictions on the test set at the very end
														__lowerCamelCase   :   Tuple       =[]
														for step, batch in enumerate(SCREAMING_SNAKE_CASE ):
																					# We could avoid this line since we set the accelerator with `device_placement=True`.
																					batch.to(accelerator.device )
																					with torch.no_grad():
																												__lowerCamelCase   :   List[Any]       =model(**SCREAMING_SNAKE_CASE )
																					__lowerCamelCase   :   int       =outputs.logits
																					__lowerCamelCase     ,    __lowerCamelCase   :   Union[str, Any]       =accelerator.gather_for_metrics((predictions, batch['''labels''']) )
																					fold_predictions.append(predictions.cpu() )
																					if i == 0:
																												# We need all of the test predictions
																												test_references.append(references.cpu() )
        # Use accelerator.print to print only on the main process.
														test_predictions.append(torch.cat(SCREAMING_SNAKE_CASE     ,    dim=0 ) )
														# We now need to release all our memory and get rid of the current model, optimizer, etc
														accelerator.free_memory()
							# New Code #
							# Finally we check the accuracy of our folded results:
							__lowerCamelCase   :   Optional[Any]       =torch.cat(SCREAMING_SNAKE_CASE     ,    dim=0 )
							__lowerCamelCase   :   int       =torch.stack(SCREAMING_SNAKE_CASE     ,    dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 )
							__lowerCamelCase   :   Tuple       =metric.compute(predictions=SCREAMING_SNAKE_CASE     ,    references=SCREAMING_SNAKE_CASE )
							accelerator.print('''Average test metrics from all folds:'''     ,    SCREAMING_SNAKE_CASE )



def 					lowerCAmelCase_      (   ):


							'''simple docstring'''







							__lowerCamelCase   :   int       =argparse.ArgumentParser(description='''Simple example of training script.''' )
							parser.add_argument(
							    '''--mixed_precision'''     ,    type=SCREAMING_SNAKE_CASE     ,    default=SCREAMING_SNAKE_CASE     ,    choices=['''no''', '''fp16''', '''bf16''', '''fp8''']     ,    help='''Whether to use mixed precision. Choose'''
							    '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.'''
							    '''and an Nvidia Ampere GPU.'''     ,    )
							parser.add_argument('''--cpu'''     ,    action='''store_true'''     ,    help='''If passed, will train on the CPU.''' )
							# New Code #
							parser.add_argument('''--num_folds'''     ,    type=SCREAMING_SNAKE_CASE     ,    default=3     ,    help='''The number of splits to perform across the dataset''' )
							__lowerCamelCase   :   Any       =parser.parse_args()
							__lowerCamelCase   :   Optional[int]       ={'''lr''': 2E-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16}
							training_function(SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE )


if __name__ == "__main__":
							main()




