


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







   def __init__(	self						,	UpperCamelCase__						,	UpperCamelCase__=13						,	UpperCamelCase__=7						,	UpperCamelCase__=True						,	UpperCamelCase__=True						,	UpperCamelCase__=True						,	UpperCamelCase__=True						,	UpperCamelCase__=99						,	UpperCamelCase__=32						,	UpperCamelCase__=2						,	UpperCamelCase__=4						,	UpperCamelCase__=37						,	UpperCamelCase__="gelu"						,	UpperCamelCase__=0.1						,	UpperCamelCase__=0.1						,	UpperCamelCase__=512						,	UpperCamelCase__=16						,	UpperCamelCase__=2						,	UpperCamelCase__=0.02						,	UpperCamelCase__=3						,	UpperCamelCase__=4						,	UpperCamelCase__=None						,	UpperCamelCase__=1000						,	)	->		Any:

       '''simple docstring'''




       snake_case    :      Optional[int]      					=    parent
       snake_case    :      int      					=    batch_size
       snake_case    :      List[Any]      					=    seq_length
       snake_case    :      int      					=    is_training
       snake_case    :      str      					=    use_input_mask
       snake_case    :      Optional[int]      					=    use_token_type_ids
       snake_case    :      List[Any]      					=    use_labels
       snake_case    :      str      					=    vocab_size
       snake_case    :      List[str]      					=    hidden_size
       snake_case    :      Any      					=    num_hidden_layers
       snake_case    :      List[str]      					=    num_attention_heads
       snake_case    :      str      					=    intermediate_size
       snake_case    :      str      					=    hidden_act
       snake_case    :      Any      					=    hidden_dropout_prob
       snake_case    :      Optional[int]      					=    attention_probs_dropout_prob
       snake_case    :      Optional[Any]      					=    max_position_embeddings
       snake_case    :      Optional[Any]      					=    type_vocab_size
       snake_case    :      List[Any]      					=    type_sequence_label_size
       snake_case    :      Any      					=    initializer_range
       snake_case    :      Optional[int]      					=    num_labels
       snake_case    :      Union[str, Any]      					=    num_choices
       snake_case    :      Dict      					=    scope
       snake_case    :      Tuple      					=    range_bbox







   def  lowerCamelCase		(	self						)	->		Union[str, Any]:

       '''simple docstring'''




       snake_case    :      Dict      					=    ids_tensor([self.batch_size, self.seq_length]						,	self.vocab_size						)

       # convert bbox to numpy since TF does not support item assignment
       snake_case    :      List[str]      					=    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]:
                   snake_case    :      int      					=    bbox[i, j, 3]
                   snake_case    :      Optional[int]      					=    bbox[i, j, 1]
                   snake_case    :      str      					=    t
               if bbox[i, j, 2] < bbox[i, j, 0]:
                   snake_case    :      List[Any]      					=    bbox[i, j, 2]
                   snake_case    :      Optional[int]      					=    bbox[i, j, 0]
                   snake_case    :      Optional[int]      					=    t
       snake_case    :      Union[str, Any]      					=    tf.convert_to_tensor(UpperCamelCase__						)

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

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

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

       snake_case    :      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  lowerCamelCase		(	self						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						)	->		List[Any]:

       '''simple docstring'''




       snake_case    :      Tuple      					=    TFLayoutLMModel(config=UpperCamelCase__						)

       snake_case    :      Optional[Any]      					=    model(UpperCamelCase__						,	UpperCamelCase__						,	attention_mask=UpperCamelCase__						,	token_type_ids=UpperCamelCase__						)
       snake_case    :      List[Any]      					=    model(UpperCamelCase__						,	UpperCamelCase__						,	token_type_ids=UpperCamelCase__						)
       snake_case    :      Any      					=    model(UpperCamelCase__						,	UpperCamelCase__						)
       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  lowerCamelCase		(	self						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						)	->		str:

       '''simple docstring'''




       snake_case    :      Optional[Any]      					=    TFLayoutLMForMaskedLM(config=UpperCamelCase__						)

       snake_case    :      Optional[Any]      					=    model(UpperCamelCase__						,	UpperCamelCase__						,	attention_mask=UpperCamelCase__						,	token_type_ids=UpperCamelCase__						,	labels=UpperCamelCase__						)
       self.parent.assertEqual(result.logits.shape						,	(self.batch_size, self.seq_length, self.vocab_size)						)







   def  lowerCamelCase		(	self						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						)	->		int:

       '''simple docstring'''




       snake_case    :      Union[str, Any]      					=    self.num_labels
       snake_case    :      Dict      					=    TFLayoutLMForSequenceClassification(config=UpperCamelCase__						)

       snake_case    :      Optional[Any]      					=    model(UpperCamelCase__						,	UpperCamelCase__						,	attention_mask=UpperCamelCase__						,	token_type_ids=UpperCamelCase__						)
       self.parent.assertEqual(result.logits.shape						,	(self.batch_size, self.num_labels)						)







   def  lowerCamelCase		(	self						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						)	->		Optional[Any]:

       '''simple docstring'''




       snake_case    :      Any      					=    self.num_labels
       snake_case    :      List[Any]      					=    TFLayoutLMForTokenClassification(config=UpperCamelCase__						)

       snake_case    :      Optional[Any]      					=    model(UpperCamelCase__						,	UpperCamelCase__						,	attention_mask=UpperCamelCase__						,	token_type_ids=UpperCamelCase__						,	labels=UpperCamelCase__						)
       self.parent.assertEqual(result.logits.shape						,	(self.batch_size, self.seq_length, self.num_labels)						)







   def  lowerCamelCase		(	self						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						)	->		List[Any]:

       '''simple docstring'''




       snake_case    :      str      					=    TFLayoutLMForQuestionAnswering(config=UpperCamelCase__						)

       snake_case    :      Dict      					=    model(UpperCamelCase__						,	UpperCamelCase__						,	attention_mask=UpperCamelCase__						,	token_type_ids=UpperCamelCase__						)
       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  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       snake_case    :      Union[str, Any]      					=    self.prepare_config_and_inputs()
       (
           (
           snake_case
       )					,(
           snake_case
       )					,(
           snake_case
       )					,(
           snake_case
       )					,(
           snake_case
       )					,(
           snake_case
       )					,(
           snake_case
       )					,(
           snake_case
       )					,
       )    :      Any      					=    config_and_inputs
       snake_case    :      List[Any]      					=    {
           "input_ids": input_ids,
           "bbox": bbox,
           "token_type_ids": token_type_ids,
           "attention_mask": input_mask,
       }
       return config, inputs_dict







@require_tf
class _lowerCAmelCase				(      snake_case_    ,							snake_case_    ,							unittest.TestCase	):
   __UpperCAmelCase :       Any							  =  (
       (
           TFLayoutLMModel,
           TFLayoutLMForMaskedLM,
           TFLayoutLMForTokenClassification,
           TFLayoutLMForSequenceClassification,
           TFLayoutLMForQuestionAnswering,
       )
       if is_tf_available()
       else ()
   )
   __UpperCAmelCase :       List[str]							  =  (
       {
           '''feature-extraction''': TFLayoutLMModel,
           '''fill-mask''': TFLayoutLMForMaskedLM,
           '''text-classification''': TFLayoutLMForSequenceClassification,
           '''token-classification''': TFLayoutLMForTokenClassification,
           '''zero-shot''': TFLayoutLMForSequenceClassification,
       }
       if is_tf_available()
       else {}
   )
   __UpperCAmelCase :       Any							  =  False
   __UpperCAmelCase :       List[Any]							  =  True
   __UpperCAmelCase :       Optional[Any]							  =  10







   def  lowerCamelCase		(	self						)	->		Any:

       '''simple docstring'''




       snake_case    :      List[Any]      					=    TFLayoutLMModelTester(self						)
       snake_case    :      Optional[Any]      					=    ConfigTester(self						,	config_class=UpperCamelCase__						,	hidden_size=37						)







   def  lowerCamelCase		(	self						)	->		Any:

       '''simple docstring'''




       self.config_tester.run_common_tests()







   def  lowerCamelCase		(	self						)	->		List[Any]:

       '''simple docstring'''




       snake_case    :      List[str]      					=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*UpperCamelCase__						)







   def  lowerCamelCase		(	self						)	->		Tuple:

       '''simple docstring'''




       snake_case    :      Dict      					=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase__						)







   def  lowerCamelCase		(	self						)	->		Optional[Any]:

       '''simple docstring'''




       snake_case    :      Tuple      					=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase__						)







   def  lowerCamelCase		(	self						)	->		Tuple:

       '''simple docstring'''




       snake_case    :      Any      					=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_token_classification(*UpperCamelCase__						)







   def  lowerCamelCase		(	self						)	->		Optional[Any]:

       '''simple docstring'''




       snake_case    :      Dict      					=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_question_answering(*UpperCamelCase__						)







   @slow
   def  lowerCamelCase		(	self						)	->		Optional[Any]:

       '''simple docstring'''




       for model_name in TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           snake_case    :      List[Any]      					=    TFLayoutLMModel.from_pretrained(UpperCamelCase__						)
           self.assertIsNotNone(UpperCamelCase__						)







   @unittest.skip("Onnx compliancy broke with TF 2.10"						)
   def  lowerCamelCase		(	self						)	->		List[str]:

       '''simple docstring'''




       pass







def   __lowerCAmelCase						(						)	->						List[str]:


    """simple docstring"""





    snake_case    :      Optional[Any]      					=    tf.convert_to_tensor([[101,1019,1014,1016,1037,1_2849,4747,1004,1_4246,2278,5439,4524,5002,2930,2193,2930,4341,3208,1005,1055,2171,2848,1_1300,3531,102],[101,4070,4034,7020,1024,3058,1015,1013,2861,1013,6070,1_9274,2772,6205,2_7814,1_6147,1_6147,4343,2047,1_0283,1_0969,1_4389,1012,2338,102]] )  # noqa: E231
    snake_case    :      Dict      					=    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
    snake_case    :      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
    snake_case    :      int      					=    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)
    snake_case    :      Optional[Any]      					=    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 _lowerCAmelCase				(      unittest.TestCase	):







   @slow
   def  lowerCamelCase		(	self						)	->		Optional[int]:

       '''simple docstring'''




       snake_case    :      Tuple      					=    TFLayoutLMModel.from_pretrained("microsoft/layoutlm-base-uncased"						)

       snake_case					,snake_case					,snake_case					,snake_case					,snake_case    :      str      					=    prepare_layoutlm_batch_inputs()

       # forward pass
       snake_case    :      List[str]      					=    model(input_ids=UpperCamelCase__						,	bbox=UpperCamelCase__						,	attention_mask=UpperCamelCase__						,	token_type_ids=UpperCamelCase__						)

       # test the sequence output on [0, :3, :3]
       snake_case    :      Tuple      					=    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]						,	UpperCamelCase__						,	atol=1e-3						)						)

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

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







   @slow
   def  lowerCamelCase		(	self						)	->		Optional[Any]:

       '''simple docstring'''




       snake_case    :      List[Any]      					=    TFLayoutLMForSequenceClassification.from_pretrained("microsoft/layoutlm-base-uncased"						,	num_labels=2						)

       snake_case					,snake_case					,snake_case					,snake_case					,snake_case    :      str      					=    prepare_layoutlm_batch_inputs()

       # forward pass
       snake_case    :      Tuple      					=    model(
           input_ids=UpperCamelCase__						,	bbox=UpperCamelCase__						,	attention_mask=UpperCamelCase__						,	token_type_ids=UpperCamelCase__						,	labels=tf.convert_to_tensor([1, 1]						)						,	)

       # test whether we get a loss as a scalar
       snake_case    :      str      					=    outputs.loss
       snake_case    :      Optional[Any]      					=    (2,)
       self.assertEqual(loss.shape						,	UpperCamelCase__						)

       # test the shape of the logits
       snake_case    :      Union[str, Any]      					=    outputs.logits
       snake_case    :      Dict      					=    (2, 2)
       self.assertEqual(logits.shape						,	UpperCamelCase__						)







   @slow
   def  lowerCamelCase		(	self						)	->		Any:

       '''simple docstring'''




       snake_case    :      List[Any]      					=    TFLayoutLMForTokenClassification.from_pretrained("microsoft/layoutlm-base-uncased"						,	num_labels=13						)

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

       # forward pass
       snake_case    :      Optional[Any]      					=    model(
           input_ids=UpperCamelCase__						,	bbox=UpperCamelCase__						,	attention_mask=UpperCamelCase__						,	token_type_ids=UpperCamelCase__						,	labels=UpperCamelCase__						)

       # test the shape of the logits
       snake_case    :      Dict      					=    outputs.logits
       snake_case    :      Any      					=    tf.convert_to_tensor((2, 25, 13)						)
       self.assertEqual(logits.shape						,	UpperCamelCase__						)







   @slow
   def  lowerCamelCase		(	self						)	->		Optional[int]:

       '''simple docstring'''




       snake_case    :      Tuple      					=    TFLayoutLMForQuestionAnswering.from_pretrained("microsoft/layoutlm-base-uncased"						)

       snake_case					,snake_case					,snake_case					,snake_case					,snake_case    :      int      					=    prepare_layoutlm_batch_inputs()

       # forward pass
       snake_case    :      str      					=    model(input_ids=UpperCamelCase__						,	bbox=UpperCamelCase__						,	attention_mask=UpperCamelCase__						,	token_type_ids=UpperCamelCase__						)

       # test the shape of the logits
       snake_case    :      Union[str, Any]      					=    tf.convert_to_tensor((2, 25)						)
       self.assertEqual(outputs.start_logits.shape						,	UpperCamelCase__						)
       self.assertEqual(outputs.end_logits.shape						,	UpperCamelCase__						)









"""simple docstring"""



import importlib.util
import json
import os
import warnings
from dataclasses import dataclass, field

import torch

from ..training_args import TrainingArguments
from ..utils import cached_property, is_sagemaker_dp_enabled, logging


__snake_case   			=    logging.get_logger(__name__)







def   __lowerCAmelCase						(						)	->						str:


    """simple docstring"""





    snake_case    :      Dict      					=    os.getenv("SM_HP_MP_PARAMETERS"						,							"{}" )
    try:
        # Parse it and check the field "partitions" is included, it is required for model parallel.
        snake_case    :      Optional[int]      					=    json.loads(lowercase )
        if "partitions" not in smp_options:
            return False
    except json.JSONDecodeError:
        return False

    # Get the sagemaker specific framework parameters from mpi_options variable.
    snake_case    :      Optional[int]      					=    os.getenv("SM_FRAMEWORK_PARAMS"						,							"{}" )
    try:
        # Parse it and check the field "sagemaker_distributed_dataparallel_enabled".
        snake_case    :      Any      					=    json.loads(lowercase )
        if not mpi_options.get("sagemaker_mpi_enabled"						,							lowercase ):
            return False
    except json.JSONDecodeError:
        return False
    # Lastly, check if the `smdistributed` module is present.
    return importlib.util.find_spec("smdistributed" ) is not None


if is_sagemaker_model_parallel_available():
  import smdistributed.modelparallel.torch as smp

  smp.init()







@dataclass
class _lowerCAmelCase				(      snake_case_	):
   __UpperCAmelCase :       str							  =  field(
       default=''''''    ,							metadata={'''help''': '''Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer'''}    ,							)







   def  lowerCamelCase		(	self						)	->		List[Any]:

       '''simple docstring'''




       super().__post_init__()
       warnings.warn(
           "`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use "
           "`TrainingArguments` instead."						,	UpperCamelCase__						,	)







   @cached_property
   def  lowerCamelCase		(	self						)	->		"torch.device":

       '''simple docstring'''




       logger.info("PyTorch: setting up devices"						)
       if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1:
           logger.warning(
               "torch.distributed process group is initialized, but local_rank == -1. "
               "In order to use Torch DDP, launch your script with `python -m torch.distributed.launch"						)
       if self.no_cuda:
           snake_case    :      Optional[Any]      					=    torch.device("cpu"						)
           snake_case    :      List[Any]      					=    0
       elif is_sagemaker_model_parallel_available():
           snake_case    :      Tuple      					=    smp.local_rank()
           snake_case    :      int      					=    torch.device("cuda"						,	UpperCamelCase__						)
           snake_case    :      Dict      					=    1
       elif is_sagemaker_dp_enabled():
           import smdistributed.dataparallel.torch.torch_smddp  # noqa: F401

           torch.distributed.init_process_group(backend="smddp"						,	timeout=self.ddp_timeout_delta						)
           snake_case    :      Any      					=    int(os.getenv("SMDATAPARALLEL_LOCAL_RANK"						)						)
           snake_case    :      Optional[Any]      					=    torch.device("cuda"						,	self.local_rank						)
           snake_case    :      str      					=    1
       elif self.local_rank == -1:
           # if n_gpu is > 1 we'll use nn.DataParallel.
           # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0`
           # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will
           # trigger an error that a device index is missing. Index 0 takes into account the
           # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0`
           # will use the first GPU in that env, i.e. GPU#1
           snake_case    :      List[str]      					=    torch.device("cuda:0" if torch.cuda.is_available() else "cpu"						)
           # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at
           # the default value.
           snake_case    :      Optional[Any]      					=    torch.cuda.device_count()
       else:
           # Here, we'll use torch.distributed.
           # Initializes the distributed backend which will take care of synchronizing nodes/GPUs
           if not torch.distributed.is_initialized():
               torch.distributed.init_process_group(backend="nccl"						,	timeout=self.ddp_timeout_delta						)
           snake_case    :      Any      					=    torch.device("cuda"						,	self.local_rank						)
           snake_case    :      Dict      					=    1

       if device.type == "cuda":
           torch.cuda.set_device(UpperCamelCase__						)

       return device







   @property
   def  lowerCamelCase		(	self						)	->		Optional[int]:

       '''simple docstring'''




       if is_sagemaker_model_parallel_available():
           return smp.dp_size()

       return super().world_size







   @property
   def  lowerCamelCase		(	self						)	->		List[str]:

       '''simple docstring'''




       return not is_sagemaker_model_parallel_available()







   @property
   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       return False





