





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

		_lowercase		:     str 					=True
except ImportError:
		_lowercase		:     str 					=False


# Cache this result has it's a C FFI call which can be pretty time-consuming
_lowercase		:     Tuple 					=torch.distributed.is_available()


def 		_SCREAMING_SNAKE_CASE    (   lowerCAmelCase__	):
		lowerCamelCase_  :    Tuple   	=			importlib.util.find_spec(lowerCAmelCase__	) is not None
		if package_exists:
				try:
						lowerCamelCase_  :    Tuple   	=			importlib.metadata.metadata(lowerCAmelCase__	)
						return True
				except importlib.metadata.PackageNotFoundError:
						return False


def 		_SCREAMING_SNAKE_CASE    (   ):
		return _torch_distributed_available


def 		_SCREAMING_SNAKE_CASE    (   ):







		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    (   ):
		return importlib.metadata.version('oneccl_bind_pt'	)


def 		_SCREAMING_SNAKE_CASE    (   ):
		return _is_package_available('transformer_engine'	)


@lru_cache
def 		_SCREAMING_SNAKE_CASE    (   lowerCAmelCase__=True	):







		if torch.cuda.is_available():
				return False
		if _tpu_available and check_device:
				try:
						# Will raise a RuntimeError if no XLA configuration is found
						lowerCamelCase_  :    Optional[Any]   	=			xm.xla_device()
						return True
				except RuntimeError:
						return False
		return _tpu_available


def 		_SCREAMING_SNAKE_CASE    (   ):
		return _is_package_available('deepspeed'	)


def 		_SCREAMING_SNAKE_CASE    (   lowerCAmelCase__=False	):







		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    (   ):
		lowerCamelCase_  :    int   	=			_is_package_available('bitsandbytes'	)
		if package_exists:
				lowerCamelCase_  :    Optional[int]   	=			version.parse(importlib.metadata.version('bitsandbytes'	)	)
				return compare_versions(lowerCAmelCase__       ,'>='       ,'0.39.0'	)
		return False


def 		_SCREAMING_SNAKE_CASE    (   ):
		lowerCamelCase_  :    Dict   	=			_is_package_available('bitsandbytes'	)
		if package_exists:
				lowerCamelCase_  :    Any   	=			version.parse(importlib.metadata.version('bitsandbytes'	)	)
				return compare_versions(lowerCAmelCase__       ,'>='       ,'0.37.2'	)
		return False


def 		_SCREAMING_SNAKE_CASE    (   ):
		return _is_package_available('bitsandbytes'	)


def 		_SCREAMING_SNAKE_CASE    (   ):







		if strtobool(os.environ.get('ACCELERATE_USE_MEGATRON_LM'       ,'False'	)	) == 1:
				lowerCamelCase_  :    Optional[int]   	=			importlib.util.find_spec('megatron'	) is not None
				if package_exists:
						try:
								lowerCamelCase_  :    Tuple   	=			parse(importlib.metadata.version('megatron-lm'	)	)
								return compare_versions(lowerCAmelCase__       ,'>='       ,'2.2.0'	)
						except Exception as e:
								warnings.warn(F"Parse Megatron version failed. Exception:{e}"	)
								return False


def 		_SCREAMING_SNAKE_CASE    (   ):
		return _is_package_available('safetensors'	)


def 		_SCREAMING_SNAKE_CASE    (   ):
		return _is_package_available('transformers'	)


def 		_SCREAMING_SNAKE_CASE    (   ):
		return _is_package_available('datasets'	)


def 		_SCREAMING_SNAKE_CASE    (   ):
		return _is_package_available('aim'	)


def 		_SCREAMING_SNAKE_CASE    (   ):
		return _is_package_available('tensorboard'	) or _is_package_available('tensorboardX'	)


def 		_SCREAMING_SNAKE_CASE    (   ):
		return _is_package_available('wandb'	)


def 		_SCREAMING_SNAKE_CASE    (   ):
		return _is_package_available('comet_ml'	)


def 		_SCREAMING_SNAKE_CASE    (   ):
		return _is_package_available('boto3'	)


def 		_SCREAMING_SNAKE_CASE    (   ):







		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'       ,lowerCAmelCase__	)
				return parse_flag_from_env('ACCELERATE_ENABLE_RICH'       ,lowerCAmelCase__	)
		return False


def 		_SCREAMING_SNAKE_CASE    (   ):
		return _is_package_available('sagemaker'	)


def 		_SCREAMING_SNAKE_CASE    (   ):
		return _is_package_available('tqdm'	)


def 		_SCREAMING_SNAKE_CASE    (   ):
		return _is_package_available('mlflow'	)


def 		_SCREAMING_SNAKE_CASE    (   ):
		return is_torch_version('>='       ,'1.12'	) and torch.backends.mps.is_available() and torch.backends.mps.is_built()


def 		_SCREAMING_SNAKE_CASE    (   ):







		def get_major_and_minor_from_version(lowerCAmelCase__	):
				return str(version.parse(lowerCAmelCase__	).major	) + "." + str(version.parse(lowerCAmelCase__	).minor	)

		lowerCamelCase_  :    Any   	=			importlib.metadata.version('torch'	)
		if importlib.util.find_spec('intel_extension_for_pytorch'	) is None:
				return False
		lowerCamelCase_  :    Optional[Any]   	=			'N/A'
		try:
				lowerCamelCase_  :    Optional[Any]   	=			importlib.metadata.version('intel_extension_for_pytorch'	)
		except importlib.metadata.PackageNotFoundError:
				return False
		lowerCamelCase_  :    List[Any]   	=			get_major_and_minor_from_version(_torch_version	)
		lowerCamelCase_  :    Tuple   	=			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    (   lowerCAmelCase__=False	):







		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
						lowerCamelCase_  :    Tuple   	=			torch.npu.device_count()
						return torch.npu.is_available()
				except RuntimeError:
						return False
		return hasattr(lowerCAmelCase__       ,'npu'	) and torch.npu.is_available()





@lru_cache
def 		_SCREAMING_SNAKE_CASE    (   lowerCAmelCase__=False	):







		if not parse_flag_from_env('ACCELERATE_USE_XPU'       ,default=lowerCAmelCase__	):
				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
						lowerCamelCase_  :    int   	=			torch.xpu.device_count()
						return torch.xpu.is_available()
				except RuntimeError:
						return False
		return hasattr(lowerCAmelCase__       ,'xpu'	) and torch.xpu.is_available()







from __future__ import annotations


def 		_SCREAMING_SNAKE_CASE    (   lowerCAmelCase__	):
		lowerCamelCase_  :    int
		lowerCamelCase_  :    list[str]   	=			list(lowerCAmelCase__	)
		lowerCamelCase_	,			lowerCamelCase_  :    List[str]   	=			_vector[:-1], int(_vector[-1]	)
		lowerCamelCase_  :    list[int]   	=			[int(lowerCAmelCase__	) for digit in __vector]

		vector.reverse()
		for i, digit in enumerate(lowerCAmelCase__	):
				if i & 1 == 0:
						lowerCamelCase_  :    int   	=			digit * 2
						if doubled > 9:
								doubled -= 9
						check_digit += doubled
				else:
						check_digit += digit

		return check_digit % 10 == 0


if __name__ == "__main__":
		import doctest

		doctest.testmod()
		assert is_luhn("""79927398713""")
		assert not is_luhn("""79927398714""")
