




import os
import random
from pathlib import Path
from typing import List

import numpy as np
import torch
from torch.cuda.amp import GradScaler

from .utils import (
    MODEL_NAME,
    OPTIMIZER_NAME,
    RNG_STATE_NAME,
    SCALER_NAME,
    SCHEDULER_NAME,
    get_pretty_name,
    is_tpu_available,
    is_xpu_available,
    save,
)


if is_tpu_available(check_device=False):
 import torch_xla.core.xla_model as xm

from .logging import get_logger
from .state import PartialState


SCREAMING_SNAKE_CASE_						:					Tuple			   =       get_logger(__name__)
def        __lowerCAmelCase (UpperCAmelCase_   ,    UpperCAmelCase_   ,    UpperCAmelCase_   ,    UpperCAmelCase_   ,    UpperCAmelCase_   ,    UpperCAmelCase_ = None   ,    ):
    # Model states
    for i, state in enumerate(UpperCAmelCase_		):
        a__      =       F"""{MODEL_NAME}.bin""" if i == 0 else F"""{MODEL_NAME}_{i}.bin"""
        a__      =       os.path.join(UpperCAmelCase_   ,    UpperCAmelCase_		)
        save(UpperCAmelCase_   ,    UpperCAmelCase_		)
        logger.info(F"""Model weights saved in {output_model_file}"""		)
    # Optimizer states
    for i, opt in enumerate(UpperCAmelCase_		):
        a__      =       opt.state_dict()
        a__      =       F"""{OPTIMIZER_NAME}.bin""" if i == 0 else F"""{OPTIMIZER_NAME}_{i}.bin"""
        a__      =       os.path.join(UpperCAmelCase_   ,    UpperCAmelCase_		)
        save(UpperCAmelCase_   ,    UpperCAmelCase_		)
        logger.info(F"""Optimizer state saved in {output_optimizer_file}"""		)
    # Scheduler states
    for i, scheduler in enumerate(UpperCAmelCase_		):
        a__      =       scheduler.state_dict()
        a__      =       F"""{SCHEDULER_NAME}.bin""" if i == 0 else F"""{SCHEDULER_NAME}_{i}.bin"""
        a__      =       os.path.join(UpperCAmelCase_   ,    UpperCAmelCase_		)
        save(UpperCAmelCase_   ,    UpperCAmelCase_		)
        logger.info(F"""Scheduler state saved in {output_scheduler_file}"""		)
    # GradScaler state
    if scaler is not None:
        a__      =       scaler.state_dict()
        a__      =       os.path.join(UpperCAmelCase_   ,    UpperCAmelCase_		)
        torch.save(UpperCAmelCase_   ,    UpperCAmelCase_		)
        logger.info(F"""Gradient scaler state saved in {output_scaler_file}"""		)
    # Random number generator states
    a__      =       {}
    a__      =       F"""{RNG_STATE_NAME}_{process_index}.pkl"""
    a__      =       random.getstate()
    a__      =       np.random.get_state()
    a__      =       torch.get_rng_state()
    if is_xpu_available():
        a__      =       torch.xpu.get_rng_state_all()
    else:
        a__      =       torch.cuda.get_rng_state_all()
    if is_tpu_available():
        a__      =       xm.get_rng_state()
    a__      =       os.path.join(UpperCAmelCase_   ,    UpperCAmelCase_		)
    torch.save(UpperCAmelCase_   ,    UpperCAmelCase_		)
    logger.info(F"""Random states saved in {output_states_file}"""		)
    return output_dir
def        __lowerCAmelCase (UpperCAmelCase_   ,    UpperCAmelCase_   ,    UpperCAmelCase_   ,    UpperCAmelCase_   ,    UpperCAmelCase_   ,    UpperCAmelCase_=None   ,    UpperCAmelCase_=None   ,    **UpperCAmelCase_   ,    ):
    if map_location not in [None, "cpu", "on_device"]:
        raise TypeError(
            """Unsupported optimizer map location passed, please choose one of `None`, `'cpu'`, or `'on_device'`"""		)
    if map_location is None:
        a__      =       """cpu"""
    elif map_location == "on_device":
        a__      =       PartialState().device
    # Model states
    for i, model in enumerate(UpperCAmelCase_		):
        a__      =       F"""{MODEL_NAME}.bin""" if i == 0 else F"""{MODEL_NAME}_{i}.bin"""
        a__      =       os.path.join(UpperCAmelCase_   ,    UpperCAmelCase_		)
        models[i].load_state_dict(torch.load(UpperCAmelCase_   ,    map_location=UpperCAmelCase_		)   ,    **UpperCAmelCase_		)
    logger.info("""All model weights loaded successfully"""		)

    # Optimizer states
    for i, opt in enumerate(UpperCAmelCase_		):
        a__      =       F"""{OPTIMIZER_NAME}.bin""" if i == 0 else F"""{OPTIMIZER_NAME}_{i}.bin"""
        a__      =       os.path.join(UpperCAmelCase_   ,    UpperCAmelCase_		)
        a__      =       torch.load(UpperCAmelCase_   ,    map_location=UpperCAmelCase_		)
        optimizers[i].load_state_dict(UpperCAmelCase_		)
    logger.info("""All optimizer states loaded successfully"""		)

    # Scheduler states
    for i, scheduler in enumerate(UpperCAmelCase_		):
        a__      =       F"""{SCHEDULER_NAME}.bin""" if i == 0 else F"""{SCHEDULER_NAME}_{i}.bin"""
        a__      =       os.path.join(UpperCAmelCase_   ,    UpperCAmelCase_		)
        scheduler.load_state_dict(torch.load(UpperCAmelCase_		)		)
    logger.info("""All scheduler states loaded successfully"""		)

    # GradScaler state
    if scaler is not None:
        a__      =       os.path.join(UpperCAmelCase_   ,    UpperCAmelCase_		)
        scaler.load_state_dict(torch.load(UpperCAmelCase_		)		)
        logger.info("""GradScaler state loaded successfully"""		)

    # Random states
    try:
        a__      =       torch.load(os.path.join(UpperCAmelCase_   ,    F"""{RNG_STATE_NAME}_{process_index}.pkl"""		)		)
        random.setstate(states["""random_state"""]		)
        np.random.set_state(states["""numpy_random_seed"""]		)
        torch.set_rng_state(states["""torch_manual_seed"""]		)
        if is_xpu_available():
            torch.xpu.set_rng_state_all(states["""torch_xpu_manual_seed"""]		)
        else:
            torch.cuda.set_rng_state_all(states["""torch_cuda_manual_seed"""]		)
        if is_tpu_available():
            xm.set_rng_state(states["""xm_seed"""]		)
        logger.info("""All random states loaded successfully"""		)
    except Exception:
        logger.info("""Could not load random states"""		)
def        __lowerCAmelCase (UpperCAmelCase_   ,    UpperCAmelCase_   ,    UpperCAmelCase_ = 0		):
    a__      =       Path(UpperCAmelCase_		) / F"""custom_checkpoint_{index}.pkl"""
    logger.info(F"""Saving the state of {get_pretty_name(UpperCAmelCase_		)} to {save_location}"""		)
    torch.save(obj.state_dict()   ,    UpperCAmelCase_		)







def        __lowerCAmelCase (UpperCAmelCase_   ,    UpperCAmelCase_   ,    UpperCAmelCase_ = 0		):
    a__      =       F"""{path}/custom_checkpoint_{index}.pkl"""
    logger.info(F"""Loading the state of {get_pretty_name(UpperCAmelCase_		)} from {load_location}"""		)
    obj.load_state_dict(torch.load(UpperCAmelCase_   ,    map_location="""cpu"""		)		)












import unittest

from transformers import (
    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    PreTrainedTokenizer,
    is_vision_available,
)
from transformers.pipelines import ImageClassificationPipeline, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_torch_or_tf,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
 from PIL import Image
else:







 class 		__UpperCAmelCase:





      """simple docstring"""



      @staticmethod
      def 				__SCREAMING_SNAKE_CASE		(      *A :       str						,				**A :       int    )			->			Union[str, Any]:






          """simple docstring"""
          pass







@is_pipeline_test
@require_torch_or_tf
@require_vision
class 		__UpperCAmelCase(		unittest.TestCase ):





     """simple docstring"""



     __UpperCAmelCase	: Tuple						=    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
     __UpperCAmelCase	: Dict						=    TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING

     def 				__SCREAMING_SNAKE_CASE		(      self :       str						,				A :       Optional[int]						,				A :       Tuple						,				A :       int    )			->			str:






         """simple docstring"""
         a__      =       ImageClassificationPipeline(model=A						,				image_processor=A						,				top_k=2    )
         a__      =       [
             Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""    ),
             """http://images.cocodataset.org/val2017/000000039769.jpg""",
         ]
         return image_classifier, examples

     def 				__SCREAMING_SNAKE_CASE		(      self :       Any						,				A :       List[str]						,				A :       Dict    )			->			Union[str, Any]:






         """simple docstring"""
         a__      =       image_classifier("""./tests/fixtures/tests_samples/COCO/000000039769.png"""    )

         self.assertEqual(
             A						,				[
                 {"""score""": ANY(A    ), """label""": ANY(A    )},
                 {"""score""": ANY(A    ), """label""": ANY(A    )},
             ]						,				)

         import datasets

         a__      =       datasets.load_dataset("""hf-internal-testing/fixtures_image_utils"""						,				"""image"""						,				split="""test"""    )

         # Accepts URL + PIL.Image + lists
         a__      =       image_classifier(
             [
                 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(
             A						,				[
                 [
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                 ],
                 [
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                 ],
                 [
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                 ],
                 [
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                 ],
                 [
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                 ],
             ]						,				)

     @require_torch
     def 				__SCREAMING_SNAKE_CASE		(      self :       Optional[int]    )			->			Optional[Any]:






         """simple docstring"""
         a__      =       """hf-internal-testing/tiny-random-vit"""
         a__      =       pipeline("""image-classification"""						,				model=A    )

         a__      =       image_classifier("""http://images.cocodataset.org/val2017/000000039769.jpg"""    )
         self.assertEqual(
             nested_simplify(A						,				decimals=4    )						,				[{"""label""": """LABEL_1""", """score""": 0.5_7_4}, {"""label""": """LABEL_0""", """score""": 0.4_2_6}]						,				)

         a__      =       image_classifier(
             [
                 """http://images.cocodataset.org/val2017/000000039769.jpg""",
                 """http://images.cocodataset.org/val2017/000000039769.jpg""",
             ]						,				top_k=2						,				)
         self.assertEqual(
             nested_simplify(A						,				decimals=4    )						,				[
                 [{"""label""": """LABEL_1""", """score""": 0.5_7_4}, {"""label""": """LABEL_0""", """score""": 0.4_2_6}],
                 [{"""label""": """LABEL_1""", """score""": 0.5_7_4}, {"""label""": """LABEL_0""", """score""": 0.4_2_6}],
             ]						,				)

     @require_tf
     def 				__SCREAMING_SNAKE_CASE		(      self :       Dict    )			->			str:






         """simple docstring"""
         a__      =       """hf-internal-testing/tiny-random-vit"""
         a__      =       pipeline("""image-classification"""						,				model=A						,				framework="""tf"""    )

         a__      =       image_classifier("""http://images.cocodataset.org/val2017/000000039769.jpg"""    )
         self.assertEqual(
             nested_simplify(A						,				decimals=4    )						,				[{"""label""": """LABEL_1""", """score""": 0.5_7_4}, {"""label""": """LABEL_0""", """score""": 0.4_2_6}]						,				)

         a__      =       image_classifier(
             [
                 """http://images.cocodataset.org/val2017/000000039769.jpg""",
                 """http://images.cocodataset.org/val2017/000000039769.jpg""",
             ]						,				top_k=2						,				)
         self.assertEqual(
             nested_simplify(A						,				decimals=4    )						,				[
                 [{"""label""": """LABEL_1""", """score""": 0.5_7_4}, {"""label""": """LABEL_0""", """score""": 0.4_2_6}],
                 [{"""label""": """LABEL_1""", """score""": 0.5_7_4}, {"""label""": """LABEL_0""", """score""": 0.4_2_6}],
             ]						,				)

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






         """simple docstring"""
         a__      =       PreTrainedTokenizer()

         # Assert that the pipeline can be initialized with a feature extractor that is not in any mapping
         a__      =       pipeline(
             """image-classification"""						,				model="""hf-internal-testing/tiny-random-vit"""						,				tokenizer=A    )

         self.assertIs(image_classifier.tokenizer						,				A    )






     @slow
     @require_torch
     def 				__SCREAMING_SNAKE_CASE		(      self :       Optional[Any]    )			->			Dict:






         """simple docstring"""
         # Perceiver is not tested by `run_pipeline_test` properly.
         # That is because the type of feature_extractor and model preprocessor need to be kept
         # in sync, which is not the case in the current design
         a__      =       pipeline("""image-classification"""						,				model="""deepmind/vision-perceiver-conv"""    )
         a__      =       image_classifier("""http://images.cocodataset.org/val2017/000000039769.jpg"""    )
         self.assertEqual(
             nested_simplify(A						,				decimals=4    )						,				[
                 {"""score""": 0.4_3_8_5, """label""": """tabby, tabby cat"""},
                 {"""score""": 0.3_2_1, """label""": """tiger cat"""},
                 {"""score""": 0.0_5_0_2, """label""": """Egyptian cat"""},
                 {"""score""": 0.0_1_3_7, """label""": """crib, cot"""},
                 {"""score""": 0.0_0_7, """label""": """radiator"""},
             ]						,				)

         a__      =       pipeline("""image-classification"""						,				model="""deepmind/vision-perceiver-fourier"""    )
         a__      =       image_classifier("""http://images.cocodataset.org/val2017/000000039769.jpg"""    )
         self.assertEqual(
             nested_simplify(A						,				decimals=4    )						,				[
                 {"""score""": 0.5_6_5_8, """label""": """tabby, tabby cat"""},
                 {"""score""": 0.1_3_0_9, """label""": """tiger cat"""},
                 {"""score""": 0.0_7_2_2, """label""": """Egyptian cat"""},
                 {"""score""": 0.0_7_0_7, """label""": """remote control, remote"""},
                 {"""score""": 0.0_0_8_2, """label""": """computer keyboard, keypad"""},
             ]						,				)

         a__      =       pipeline("""image-classification"""						,				model="""deepmind/vision-perceiver-learned"""    )
         a__      =       image_classifier("""http://images.cocodataset.org/val2017/000000039769.jpg"""    )
         self.assertEqual(
             nested_simplify(A						,				decimals=4    )						,				[
                 {"""score""": 0.3_0_2_2, """label""": """tabby, tabby cat"""},
                 {"""score""": 0.2_3_6_2, """label""": """Egyptian cat"""},
                 {"""score""": 0.1_8_5_6, """label""": """tiger cat"""},
                 {"""score""": 0.0_3_2_4, """label""": """remote control, remote"""},
                 {"""score""": 0.0_0_9_6, """label""": """quilt, comforter, comfort, puff"""},
             ]						,				)






