



"""simple docstring"""






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

import torch

from accelerate import PartialState
from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce




def 			snake_case		(		lowerCAmelCase_	)						->				Optional[Any]:
  return (torch.arange(state.num_processes	) + 1.0 + (state.num_processes * state.process_index)).to(state.device	)




def 			snake_case		(		lowerCAmelCase_	)						->				Any:
  _snake_case   	=      create_tensor(lowerCAmelCase_	)
  _snake_case   	=      gather(lowerCAmelCase_	)
  assert gathered_tensor.tolist() == list(range(1  ,						state.num_processes**2 + 1	)	)




def 			snake_case		(		lowerCAmelCase_	)						->				str:
  _snake_case   	=      [state.process_index]
  _snake_case   	=      gather_object(lowerCAmelCase_	)
  assert len(lowerCAmelCase_	) == state.num_processes, f"""{gathered_obj}, {len(lowerCAmelCase_	)} != {state.num_processes}"""
  assert gathered_obj == list(range(state.num_processes	)	), f"""{gathered_obj} != {list(range(state.num_processes	)	)}"""




def 			snake_case		(		lowerCAmelCase_	)						->				Dict:
  _snake_case   	=      create_tensor(lowerCAmelCase_	)
  _snake_case   	=      broadcast(lowerCAmelCase_	)
  assert broadcasted_tensor.shape == torch.Size([state.num_processes]	)
  assert broadcasted_tensor.tolist() == list(range(1  ,						state.num_processes + 1	)	)




def 			snake_case		(		lowerCAmelCase_	)						->				str:
  # We need to pad the tensor with one more element if we are the main process
  # to ensure that we can pad
  if state.is_main_process:
    _snake_case   	=      torch.arange(state.num_processes + 1	).to(state.device	)
  else:
    _snake_case   	=      torch.arange(state.num_processes	).to(state.device	)
  _snake_case   	=      pad_across_processes(lowerCAmelCase_	)
  assert padded_tensor.shape == torch.Size([state.num_processes + 1]	)
  if not state.is_main_process:
    assert padded_tensor.tolist() == list(range(0  ,						state.num_processes	)	) + [0]




def 			snake_case		(		lowerCAmelCase_	)						->				str:
  # For now runs on only two processes
  if state.num_processes != 2:
    return
  _snake_case   	=      create_tensor(lowerCAmelCase_	)
  _snake_case   	=      reduce(lowerCAmelCase_  ,						'''sum'''	)
  _snake_case   	=      torch.tensor([4.0, 6]	).to(state.device	)
  assert torch.allclose(lowerCAmelCase_  ,						lowerCAmelCase_	), f"""{reduced_tensor} != {truth_tensor}"""




def 			snake_case		(		lowerCAmelCase_	)						->				Any:
  # For now runs on only two processes
  if state.num_processes != 2:
    return
  _snake_case   	=      create_tensor(lowerCAmelCase_	)
  _snake_case   	=      reduce(lowerCAmelCase_  ,						'''mean'''	)
  _snake_case   	=      torch.tensor([2.0, 3]	).to(state.device	)
  assert torch.allclose(lowerCAmelCase_  ,						lowerCAmelCase_	), f"""{reduced_tensor} != {truth_tensor}"""




def 			snake_case		(		lowerCAmelCase_	)						->				Dict:
  # For xla_spawn (TPUs)
  main()




def 			snake_case		(		)						->				int:
  _snake_case   	=      PartialState()
  state.print(f"""State: {state}"""	)
  state.print('''testing gather'''	)
  test_gather(lowerCAmelCase_	)
  state.print('''testing gather_object'''	)
  test_gather_object(lowerCAmelCase_	)
  state.print('''testing broadcast'''	)
  test_broadcast(lowerCAmelCase_	)
  state.print('''testing pad_across_processes'''	)
  test_pad_across_processes(lowerCAmelCase_	)
  state.print('''testing reduce_sum'''	)
  test_reduce_sum(lowerCAmelCase_	)
  state.print('''testing reduce_mean'''	)
  test_reduce_mean(lowerCAmelCase_	)


if __name__ == "__main__":
     main()







'''simple docstring'''

import hashlib
import unittest

from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available
from transformers.pipelines import DepthEstimationPipeline, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_timm,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_torch_available():
     import torch

if is_vision_available():
     from PIL import Image
else:




     class    lowerCAmelCase       :


      @staticmethod
      def    _A	(    *a__  : str			,							**a__  : List[str]    ):
       '''simple docstring'''

       pass


def        UpperCAmelCase_ (  lowerCamelCase_			):







 """simple docstring"""


 lowerCAmelCase__     :   List[str]     		=	hashlib.mda(image.tobytes()			)
 return m.hexdigest()







@is_pipeline_test
@require_vision
@require_timm
@require_torch
class    lowerCAmelCase       (     unittest.TestCase  ):
 A_				:				List[Any]	=			MODEL_FOR_DEPTH_ESTIMATION_MAPPING


 def    _A	(    self  : List[Any]			,							a__  : int			,							a__  : Dict			,							a__  : Optional[Any]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   List[str]     		=	DepthEstimationPipeline(model=a__			,							image_processor=a__    )
  return depth_estimator, [
      "./tests/fixtures/tests_samples/COCO/000000039769.png",
      "./tests/fixtures/tests_samples/COCO/000000039769.png",
  ]


 def    _A	(    self  : int			,							a__  : Optional[int]			,							a__  : List[Any]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Any     		=	depth_estimator("./tests/fixtures/tests_samples/COCO/000000039769.png"    )
  self.assertEqual({"predicted_depth": ANY(torch.Tensor    ), "depth": ANY(Image.Image    )}			,							a__    )
  import datasets

  lowerCAmelCase__     :   List[str]     		=	datasets.load_dataset("hf-internal-testing/fixtures_image_utils"			,							"image"			,							split="test"    )
  lowerCAmelCase__     :   List[str]     		=	depth_estimator(
      [
          Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"    ),
          "http://images.cocodataset.org/val2017/000000039769.jpg",
          # RGBA
          dataset[0]["file"],
          # LA
          dataset[1]["file"],
          # L
          dataset[2]["file"],
      ]    )
  self.assertEqual(
      [
          {"predicted_depth": ANY(torch.Tensor    ), "depth": ANY(Image.Image    )},
          {"predicted_depth": ANY(torch.Tensor    ), "depth": ANY(Image.Image    )},
          {"predicted_depth": ANY(torch.Tensor    ), "depth": ANY(Image.Image    )},
          {"predicted_depth": ANY(torch.Tensor    ), "depth": ANY(Image.Image    )},
          {"predicted_depth": ANY(torch.Tensor    ), "depth": ANY(Image.Image    )},
      ]			,							a__			,							)


 @require_tf
 @unittest.skip("Depth estimation is not implemented in TF"    )
 def    _A	(    self  : Optional[Any]    ):
  '''simple docstring'''

  pass


 @slow
 @require_torch
 def    _A	(    self  : Any    ):
  '''simple docstring'''

  lowerCAmelCase__     :   str     		=	"Intel/dpt-large"
  lowerCAmelCase__     :   Dict     		=	pipeline("depth-estimation"			,							model=a__    )
  lowerCAmelCase__     :   Any     		=	depth_estimator("http://images.cocodataset.org/val2017/000000039769.jpg"    )
  lowerCAmelCase__     :   Any     		=	hashimage(outputs["depth"]    )

  # This seems flaky.
  # self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977")
  self.assertEqual(nested_simplify(outputs["predicted_depth"].max().item()    )			,							29.304    )
  self.assertEqual(nested_simplify(outputs["predicted_depth"].min().item()    )			,							2.662    )


 @require_torch
 def    _A	(    self  : Any    ):
  '''simple docstring'''

  self.skipTest("There is not hf-internal-testing tiny model for either GLPN nor DPT"    )





