




'''simple docstring'''


import inspect
import unittest

from transformers import ResNetConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch
     from torch import nn

     from transformers import ResNetBackbone, ResNetForImageClassification, ResNetModel
     from transformers.models.resnet.modeling_resnet import RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import AutoImageProcessor






class 						lowerCAmelCase_	:







  '''simple docstring'''

  def __init__( self				:							Any					,  SCREAMING_SNAKE_CASE_				:							str					,  SCREAMING_SNAKE_CASE_				:							Optional[Any]=3					,  SCREAMING_SNAKE_CASE_				:							Optional[Any]=32					,  SCREAMING_SNAKE_CASE_				:							int=3					,  SCREAMING_SNAKE_CASE_				:							str=10					,  SCREAMING_SNAKE_CASE_				:							Union[str, Any]=[10, 20, 30, 40]					,  SCREAMING_SNAKE_CASE_				:							Optional[Any]=[1, 1, 2, 1]					,  SCREAMING_SNAKE_CASE_				:							Any=True					,  SCREAMING_SNAKE_CASE_				:							Union[str, Any]=True					,  SCREAMING_SNAKE_CASE_				:							Any="relu"					,  SCREAMING_SNAKE_CASE_				:							str=3					,  SCREAMING_SNAKE_CASE_				:							List[str]=None					,  SCREAMING_SNAKE_CASE_				:							Optional[Any]=["stage2", "stage3", "stage4"]					,  SCREAMING_SNAKE_CASE_				:							Tuple=[2, 3, 4]					,  )			->		Any:







       '''simple docstring'''



       A:		str          =		parent
       A:		Tuple          =		batch_size
       A:		Tuple          =		image_size
       A:		Optional[int]          =		num_channels
       A:		Tuple          =		embeddings_size
       A:		int          =		hidden_sizes
       A:		Union[str, Any]          =		depths
       A:		int          =		is_training
       A:		Optional[int]          =		use_labels
       A:		Dict          =		hidden_act
       A:		int          =		num_labels
       A:		int          =		scope
       A:		List[str]          =		len(SCREAMING_SNAKE_CASE_	)
       A:		int          =		out_features
       A:		List[str]          =		out_indices



  def 					_snake_case     ( self				:							Any	)			->		str:







       '''simple docstring'''



       A:		Optional[int]          =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

       A:		int          =		None
       if self.use_labels:
            A:		Optional[int]          =		ids_tensor([self.batch_size]					,  self.num_labels	)

       A:		Tuple          =		self.get_config()

       return config, pixel_values, labels



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







       '''simple docstring'''



       return ResNetConfig(
           num_channels=self.num_channels					,  embeddings_size=self.embeddings_size					,  hidden_sizes=self.hidden_sizes					,  depths=self.depths					,  hidden_act=self.hidden_act					,  num_labels=self.num_labels					,  out_features=self.out_features					,  out_indices=self.out_indices					,  )



  def 					_snake_case     ( self				:							str					,  SCREAMING_SNAKE_CASE_				:							List[str]					,  SCREAMING_SNAKE_CASE_				:							Union[str, Any]					,  SCREAMING_SNAKE_CASE_				:							Dict	)			->		List[Any]:







       '''simple docstring'''



       A:		Dict          =		ResNetModel(config=SCREAMING_SNAKE_CASE_	)
       model.to(SCREAMING_SNAKE_CASE_	)
       model.eval()
       A:		Optional[Any]          =		model(SCREAMING_SNAKE_CASE_	)
       # expected last hidden states: B, C, H // 32, W // 32
       self.parent.assertEqual(
           result.last_hidden_state.shape					,  (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)					,  )



  def 					_snake_case     ( self				:							Dict					,  SCREAMING_SNAKE_CASE_				:							List[str]					,  SCREAMING_SNAKE_CASE_				:							Union[str, Any]					,  SCREAMING_SNAKE_CASE_				:							Optional[Any]	)			->		Any:







       '''simple docstring'''



       A:		str          =		self.num_labels
       A:		List[str]          =		ResNetForImageClassification(SCREAMING_SNAKE_CASE_	)
       model.to(SCREAMING_SNAKE_CASE_	)
       model.eval()
       A:		Optional[int]          =		model(SCREAMING_SNAKE_CASE_					,  labels=SCREAMING_SNAKE_CASE_	)
       self.parent.assertEqual(result.logits.shape					,  (self.batch_size, self.num_labels)	)



  def 					_snake_case     ( self				:							List[str]					,  SCREAMING_SNAKE_CASE_				:							Union[str, Any]					,  SCREAMING_SNAKE_CASE_				:							str					,  SCREAMING_SNAKE_CASE_				:							Optional[Any]	)			->		int:







       '''simple docstring'''



       A:		List[Any]          =		ResNetBackbone(config=SCREAMING_SNAKE_CASE_	)
       model.to(SCREAMING_SNAKE_CASE_	)
       model.eval()
       A:		Tuple          =		model(SCREAMING_SNAKE_CASE_	)

       # verify feature maps
       self.parent.assertEqual(len(result.feature_maps	)					,  len(config.out_features	)	)
       self.parent.assertListEqual(list(result.feature_maps[0].shape	)					,  [self.batch_size, self.hidden_sizes[1], 4, 4]	)

       # verify channels
       self.parent.assertEqual(len(model.channels	)					,  len(config.out_features	)	)
       self.parent.assertListEqual(model.channels					,  config.hidden_sizes[1:]	)

       # verify backbone works with out_features=None
       A:		int          =		None
       A:		Any          =		ResNetBackbone(config=SCREAMING_SNAKE_CASE_	)
       model.to(SCREAMING_SNAKE_CASE_	)
       model.eval()
       A:		Dict          =		model(SCREAMING_SNAKE_CASE_	)

       # verify feature maps
       self.parent.assertEqual(len(result.feature_maps	)					,  1	)
       self.parent.assertListEqual(list(result.feature_maps[0].shape	)					,  [self.batch_size, self.hidden_sizes[-1], 1, 1]	)

       # verify channels
       self.parent.assertEqual(len(model.channels	)					,  1	)
       self.parent.assertListEqual(model.channels					,  [config.hidden_sizes[-1]]	)




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







       '''simple docstring'''



       A:		Optional[Any]          =		self.prepare_config_and_inputs()
       A     ,    A     ,    A:		Optional[Any]          =		config_and_inputs
       A:		int          =		{'''pixel_values''': pixel_values}
       return config, inputs_dict






@require_torch
class 						lowerCAmelCase_	(       UpperCAmelCase_       ,					UpperCAmelCase_       ,					unittest.TestCase							):







  '''simple docstring'''

  UpperCamelCase_			:      Optional[int]										=				(
      (
          ResNetModel,
          ResNetForImageClassification,
          ResNetBackbone,
      )
      if is_torch_available()
      else ()
  )
  UpperCamelCase_			:      List[Any]										=				(
      {"""feature-extraction""": ResNetModel, """image-classification""": ResNetForImageClassification}
      if is_torch_available()
      else {}
  )

  UpperCamelCase_			:      Optional[int]										=				True
  UpperCamelCase_			:      int										=				False
  UpperCamelCase_			:      int										=				False
  UpperCamelCase_			:      Optional[int]										=				False
  UpperCamelCase_			:      Optional[int]										=				False



  def 					_snake_case     ( self				:							Optional[int]	)			->		int:







       '''simple docstring'''



       A:		Union[str, Any]          =		ResNetModelTester(self	)
       A:		Dict          =		ConfigTester(self					,  config_class=SCREAMING_SNAKE_CASE_					,  has_text_modality=SCREAMING_SNAKE_CASE_	)



  def 					_snake_case     ( self				:							int	)			->		List[Any]:







       '''simple docstring'''



       self.create_and_test_config_common_properties()
       self.config_tester.create_and_test_config_to_json_string()
       self.config_tester.create_and_test_config_to_json_file()
       self.config_tester.create_and_test_config_from_and_save_pretrained()
       self.config_tester.create_and_test_config_with_num_labels()
       self.config_tester.check_config_can_be_init_without_params()
       self.config_tester.check_config_arguments_init()



  def 					_snake_case     ( self				:							str	)			->		List[Any]:







       '''simple docstring'''



       return



  @unittest.skip(reason='''ResNet does not use inputs_embeds'''	)
  def 					_snake_case     ( self				:							Optional[int]	)			->		int:







       '''simple docstring'''



       pass



  @unittest.skip(reason='''ResNet does not support input and output embeddings'''	)
  def 					_snake_case     ( self				:							Tuple	)			->		Tuple:







       '''simple docstring'''



       pass



  def 					_snake_case     ( self				:							Optional[Any]	)			->		List[Any]:







       '''simple docstring'''



       A     ,    A:		List[Any]          =		self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
            A:		Any          =		model_class(SCREAMING_SNAKE_CASE_	)
            A:		Dict          =		inspect.signature(model.forward	)
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            A:		Dict          =		[*signature.parameters.keys()]

            A:		str          =		['''pixel_values''']
            self.assertListEqual(arg_names[:1]					,  SCREAMING_SNAKE_CASE_	)



  def 					_snake_case     ( self				:							List[str]	)			->		Dict:







       '''simple docstring'''



       A:		int          =		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_	)



  def 					_snake_case     ( self				:							Tuple	)			->		Tuple:







       '''simple docstring'''



       A:		List[Any]          =		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_backbone(*SCREAMING_SNAKE_CASE_	)



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







       '''simple docstring'''



       A     ,    A:		str          =		self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
            A:		Optional[int]          =		model_class(config=SCREAMING_SNAKE_CASE_	)
            for name, module in model.named_modules():
                 if isinstance(SCREAMING_SNAKE_CASE_					,  (nn.BatchNormad, nn.GroupNorm)	):
                      self.assertTrue(
                          torch.all(module.weight == 1	)					,  msg=f"""Parameter {name} of model {model_class} seems not properly initialized"""					,  )
                      self.assertTrue(
                          torch.all(module.bias == 0	)					,  msg=f"""Parameter {name} of model {model_class} seems not properly initialized"""					,  )



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







       '''simple docstring'''



       def check_hidden_states_output(SCREAMING_SNAKE_CASE_				:							Any					,  SCREAMING_SNAKE_CASE_				:							List[Any]					,  SCREAMING_SNAKE_CASE_				:							Dict	):
            A:		Union[str, Any]          =		model_class(SCREAMING_SNAKE_CASE_	)
            model.to(SCREAMING_SNAKE_CASE_	)
            model.eval()

            with torch.no_grad():
                 A:		int          =		model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_	)	)

            A:		List[Any]          =		outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

            A:		int          =		self.model_tester.num_stages
            self.assertEqual(len(SCREAMING_SNAKE_CASE_	)					,  expected_num_stages + 1	)

            # ResNet's feature maps are of shape (batch_size, num_channels, height, width)
            self.assertListEqual(
                list(hidden_states[0].shape[-2:]	)					,  [self.model_tester.image_size // 4, self.model_tester.image_size // 4]					,  )

       A     ,    A:		Optional[Any]          =		self.model_tester.prepare_config_and_inputs_for_common()
       A:		Union[str, Any]          =		['''basic''', '''bottleneck''']
       for model_class in self.all_model_classes:
            for layer_type in layers_type:
                 A:		Dict          =		layer_type
                 A:		int          =		True
                 check_hidden_states_output(SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_	)

                 # check that output_hidden_states also work using config
                 del inputs_dict["output_hidden_states"]
                 A:		Dict          =		True

                 check_hidden_states_output(SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_	)



  @unittest.skip(reason='''ResNet does not use feedforward chunking'''	)
  def 					_snake_case     ( self				:							str	)			->		Union[str, Any]:







       '''simple docstring'''



       pass



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







       '''simple docstring'''



       A:		List[Any]          =		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_	)




  @slow
  def 					_snake_case     ( self				:							str	)			->		str:







       '''simple docstring'''



       for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            A:		Optional[Any]          =		ResNetModel.from_pretrained(SCREAMING_SNAKE_CASE_	)
            self.assertIsNotNone(SCREAMING_SNAKE_CASE_	)






def 					SCREAMING_SNAKE_CASE(   )			-> Optional[int]:
     A:		Any          =		Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
     return image






@require_torch
@require_vision
class 						lowerCAmelCase_	(       unittest.TestCase							):







  '''simple docstring'''

  @cached_property
  def 					_snake_case     ( self				:							List[str]	)			->		int:







       '''simple docstring'''



       return (
           AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)
           if is_vision_available()
           else None
       )




  @slow
  def 					_snake_case     ( self				:							int	)			->		str:







       '''simple docstring'''



       A:		Dict          =		ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]	).to(SCREAMING_SNAKE_CASE_	)

       A:		Optional[int]          =		self.default_image_processor
       A:		str          =		prepare_img()
       A:		Optional[Any]          =		image_processor(images=SCREAMING_SNAKE_CASE_					,  return_tensors='''pt'''	).to(SCREAMING_SNAKE_CASE_	)

       # forward pass
       with torch.no_grad():
            A:		List[Any]          =		model(**SCREAMING_SNAKE_CASE_	)

       # verify the logits
       A:		Optional[int]          =		torch.Size((1, 10_00)	)
       self.assertEqual(outputs.logits.shape					,  SCREAMING_SNAKE_CASE_	)

       A:		Tuple          =		torch.tensor([-11.1069, -9.7877, -8.3777]	).to(SCREAMING_SNAKE_CASE_	)

       self.assertTrue(torch.allclose(outputs.logits[0, :3]					,  SCREAMING_SNAKE_CASE_					,  atol=1E-4	)	)






@require_torch
class 						lowerCAmelCase_	(       UpperCAmelCase_       ,					unittest.TestCase							):







  '''simple docstring'''

  UpperCamelCase_			:      List[Any]										=				(ResNetBackbone,) if is_torch_available() else ()
  UpperCamelCase_			:      Optional[int]										=				False
  UpperCamelCase_			:      Any										=				ResNetConfig



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







       '''simple docstring'''



       A:		List[str]          =		ResNetModelTester(self	)












'''simple docstring'''


import importlib
import importlib.metadata
import os
import warnings
from distutils.util import strtobool
from functools import lru_cache

import torch
from packaging import version
from packaging.version import parse

from .environment import parse_flag_from_env
from .versions import compare_versions, is_torch_version


try:
     import torch_xla.core.xla_model as xm  # noqa: F401

     UpperCamelCase			     =					True
except ImportError:
     UpperCamelCase			     =					False


# Cache this result has it's a C FFI call which can be pretty time-consuming
UpperCamelCase			     =					torch.distributed.is_available()
def 					SCREAMING_SNAKE_CASE(   __lowercase	)			-> Optional[int]:
     # Check we're not importing a "pkg_name" directory somewhere but the actual library by trying to grab the version
     A:		Optional[Any]          =		importlib.util.find_spec(__lowercase	) is not None
     if package_exists:
          try:
               A:		Dict          =		importlib.metadata.metadata(__lowercase	)
               return True
          except importlib.metadata.PackageNotFoundError:
               return False
def 					SCREAMING_SNAKE_CASE(   )			-> bool:
     return _torch_distributed_available
def 					SCREAMING_SNAKE_CASE(   )			-> Optional[int]:
     try:
          pass
     except ImportError:
          print(
              '''Intel(R) oneCCL Bindings for PyTorch* is required to run DDP on Intel(R) GPUs, but it is not'''
              ''' detected. If you see \"ValueError: Invalid backend: \'ccl\'\" error, please install Intel(R) oneCCL'''
              ''' Bindings for PyTorch*.'''	)
     return (
         importlib.util.find_spec('''torch_ccl'''	) is not None
         or importlib.util.find_spec('''oneccl_bindings_for_pytorch'''	) is not None
     )
def 					SCREAMING_SNAKE_CASE(   )			-> List[str]:
     return importlib.metadata.version('''oneccl_bind_pt'''	)
def 					SCREAMING_SNAKE_CASE(   )			-> Union[str, Any]:
     return _is_package_available('''transformer_engine'''	)
@lru_cache
def 					SCREAMING_SNAKE_CASE(   __lowercase=True	)			-> Union[str, Any]:
     # Due to bugs on the amp series GPUs, we disable torch-xla on them
     if torch.cuda.is_available():
          return False
     if _tpu_available and check_device:
          try:
               # Will raise a RuntimeError if no XLA configuration is found
               A:		Tuple          =		xm.xla_device()
               return True
          except RuntimeError:
               return False
     return _tpu_available
def 					SCREAMING_SNAKE_CASE(   )			-> List[str]:
     return _is_package_available('''deepspeed'''	)
def 					SCREAMING_SNAKE_CASE(   __lowercase=False	)			-> Any:
     if is_tpu_available():
          return not ignore_tpu
     if torch.cuda.is_available():
          return torch.cuda.is_bfaa_supported()
     if is_npu_available():
          return False
     return True
def 					SCREAMING_SNAKE_CASE(   )			-> str:
     A:		List[str]          =		_is_package_available('''bitsandbytes'''	)
     if package_exists:
          A:		Union[str, Any]          =		version.parse(importlib.metadata.version('''bitsandbytes'''	)	)
          return compare_versions(__lowercase		,				'''>='''		,				'''0.39.0'''	)
     return False
def 					SCREAMING_SNAKE_CASE(   )			-> str:
     A:		int          =		_is_package_available('''bitsandbytes'''	)
     if package_exists:
          A:		Tuple          =		version.parse(importlib.metadata.version('''bitsandbytes'''	)	)
          return compare_versions(__lowercase		,				'''>='''		,				'''0.37.2'''	)
     return False
def 					SCREAMING_SNAKE_CASE(   )			-> int:
     return _is_package_available('''bitsandbytes'''	)
def 					SCREAMING_SNAKE_CASE(   )			-> Optional[int]:
     if strtobool(os.environ.get('''ACCELERATE_USE_MEGATRON_LM'''		,				'''False'''	)	) == 1:
          A:		Any          =		importlib.util.find_spec('''megatron'''	) is not None
          if package_exists:
               try:
                    A:		str          =		parse(importlib.metadata.version('''megatron-lm'''	)	)
                    return compare_versions(__lowercase		,				'''>='''		,				'''2.2.0'''	)
               except Exception as e:
                    warnings.warn(F"""Parse Megatron version failed. Exception:{e}"""	)
                    return False
def 					SCREAMING_SNAKE_CASE(   )			-> Any:
     return _is_package_available('''safetensors'''	)
def 					SCREAMING_SNAKE_CASE(   )			-> Tuple:
     return _is_package_available('''transformers'''	)
def 					SCREAMING_SNAKE_CASE(   )			-> Union[str, Any]:
     return _is_package_available('''datasets'''	)
def 					SCREAMING_SNAKE_CASE(   )			-> Union[str, Any]:
     return _is_package_available('''aim'''	)
def 					SCREAMING_SNAKE_CASE(   )			-> List[Any]:
     return _is_package_available('''tensorboard'''	) or _is_package_available('''tensorboardX'''	)
def 					SCREAMING_SNAKE_CASE(   )			-> Dict:
     return _is_package_available('''wandb'''	)
def 					SCREAMING_SNAKE_CASE(   )			-> Optional[Any]:
     return _is_package_available('''comet_ml'''	)
def 					SCREAMING_SNAKE_CASE(   )			-> Any:
     return _is_package_available('''boto3'''	)
def 					SCREAMING_SNAKE_CASE(   )			-> str:
     if _is_package_available('''rich'''	):
          if "ACCELERATE_DISABLE_RICH" in os.environ:
               warnings.warn(
                   '''`ACCELERATE_DISABLE_RICH` is deprecated and will be removed in v0.22.0 and deactivated by default. Please use `ACCELERATE_ENABLE_RICH` if you wish to use `rich`.'''	)
               return not parse_flag_from_env('''ACCELERATE_DISABLE_RICH'''		,				__lowercase	)
          return parse_flag_from_env('''ACCELERATE_ENABLE_RICH'''		,				__lowercase	)
     return False
def 					SCREAMING_SNAKE_CASE(   )			-> int:
     return _is_package_available('''sagemaker'''	)
def 					SCREAMING_SNAKE_CASE(   )			-> Union[str, Any]:
     return _is_package_available('''tqdm'''	)
def 					SCREAMING_SNAKE_CASE(   )			-> str:
     return _is_package_available('''mlflow'''	)
def 					SCREAMING_SNAKE_CASE(   )			-> int:
     return is_torch_version('''>='''		,				'''1.12'''	) and torch.backends.mps.is_available() and torch.backends.mps.is_built()
def 					SCREAMING_SNAKE_CASE(   )			-> str:
     def get_major_and_minor_from_version(__lowercase	):
          return str(version.parse(__lowercase	).major	) + "." + str(version.parse(__lowercase	).minor	)

     A:		int          =		importlib.metadata.version('''torch'''	)
     if importlib.util.find_spec('''intel_extension_for_pytorch'''	) is None:
          return False
     A:		Optional[Any]          =		'''N/A'''
     try:
          A:		List[Any]          =		importlib.metadata.version('''intel_extension_for_pytorch'''	)
     except importlib.metadata.PackageNotFoundError:
          return False
     A:		Optional[int]          =		get_major_and_minor_from_version(_torch_version	)
     A:		List[str]          =		get_major_and_minor_from_version(_ipex_version	)
     if torch_major_and_minor != ipex_major_and_minor:
          warnings.warn(
              F"""Intel Extension for PyTorch {ipex_major_and_minor} needs to work with PyTorch {ipex_major_and_minor}.*,"""
              F""" but PyTorch {_torch_version} is found. Please switch to the matching version and run again."""	)
          return False
     return True
@lru_cache
def 					SCREAMING_SNAKE_CASE(   __lowercase=False	)			-> Optional[Any]:
     if importlib.util.find_spec('''torch'''	) is None or importlib.util.find_spec('''torch_npu'''	) is None:
          return False

     import torch
     import torch_npu  # noqa: F401

     if check_device:
          try:
               # Will raise a RuntimeError if no NPU is found
               A:		Tuple          =		torch.npu.device_count()
               return torch.npu.is_available()
          except RuntimeError:
               return False
     return hasattr(__lowercase		,				'''npu'''	) and torch.npu.is_available()


@lru_cache
def 					SCREAMING_SNAKE_CASE(   __lowercase=False	)			-> Tuple:
     if not parse_flag_from_env('''ACCELERATE_USE_XPU'''		,				default=__lowercase	):
          return False
     if is_ipex_available():
          import torch

          if is_torch_version('''<='''		,				'''1.12'''	):
               return False
     else:
          return False

     import intel_extension_for_pytorch  # noqa: F401

     if check_device:
          try:
               # Will raise a RuntimeError if no XPU  is found
               A:		str          =		torch.xpu.device_count()
               return torch.xpu.is_available()
          except RuntimeError:
               return False
     return hasattr(__lowercase		,				'''xpu'''	) and torch.xpu.is_available()






