



"""simple docstring"""




# We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation

import warnings

from .state import AcceleratorState, GradientState


warnings.filterwarnings("ignore", category=UserWarning, module="torch.optim.lr_scheduler")






class       UpperCAmelCase_    :



      def __init__(	self	:      Optional[Any]	,      A	:      List[str]	,      A	:      List[str]	,      A	:      bool = True	,      A	:      bool = False		):
           _UpperCAmelCase     :      Dict														=       scheduler
           _UpperCAmelCase     :      str														=       optimizers if isinstance(A	,      (list, tuple)		) else [optimizers]
           _UpperCAmelCase     :      List[str]														=       split_batches
           _UpperCAmelCase     :      Dict														=       step_with_optimizer
           _UpperCAmelCase     :      Tuple														=       GradientState()



      def 		snake_case_   (	self	:      Optional[int]	,      *A	:      List[Any]	,      **A	:      Optional[int]		):
           if not self.step_with_optimizer:
                # No link between scheduler and optimizer -> just step
                self.scheduler.step(*A	,      **A		)
                return

           # Otherwise, first make sure the optimizer was stepped.
           if not self.gradient_state.sync_gradients:
                if self.gradient_state.adjust_scheduler:
                     self.scheduler._step_count += 1
                return

           for opt in self.optimizers:
                if opt.step_was_skipped:
                     return
           if self.split_batches:
                # Split batches -> the training dataloader batch size is not changed so one step per training step
                self.scheduler.step(*A	,      **A		)
           else:
                # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do
                # num_processes steps per training step
                _UpperCAmelCase     :      int														=       AcceleratorState().num_processes
                for _ in range(A		):
                     # Special case when using OneCycle and `drop_last` was not used
                     if hasattr(self.scheduler	,      "total_steps"		):
                          if self.scheduler._step_count <= self.scheduler.total_steps:
                               self.scheduler.step(*A	,      **A		)
                     else:
                          self.scheduler.step(*A	,      **A		)



      def 		snake_case_   (	self	:      Union[str, Any]		):
           return self.scheduler.get_last_lr()



      def 		snake_case_   (	self	:      str		):
           return self.scheduler.state_dict()



      def 		snake_case_   (	self	:      str	,      A	:      Optional[Any]		):
           self.scheduler.load_state_dict(A		)



      def 		snake_case_   (	self	:      Tuple		):
           return self.scheduler.get_lr()



      def 		snake_case_   (	self	:      Optional[int]	,      *A	:      List[str]	,      **A	:      Optional[Any]		):
           return self.scheduler.print_lr(*A	,      **A		)





"""simple docstring"""




import unittest

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

from .test_pipelines_common import ANY


if is_vision_available():
 from PIL import Image
else:






 class       UpperCAmelCase_    :



       @staticmethod
       def 		snake_case_   (	*A	:      Union[str, Any]	,      **A	:      Dict		):
            pass






@is_pipeline_test
@require_vision
class       UpperCAmelCase_    (							unittest.TestCase		):



      @require_torch
      def 		snake_case_   (	self	:      Union[str, Any]		):
           _UpperCAmelCase     :      Union[str, Any]														=       pipeline(
               model="hf-internal-testing/tiny-random-clip-zero-shot-image-classification"	,      )
           _UpperCAmelCase     :      Union[str, Any]														=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"		)
           _UpperCAmelCase     :      Tuple														=       image_classifier(A	,      candidate_labels=["a", "b", "c"]		)

           # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across
           # python and torch versions.
           self.assertIn(
               nested_simplify(A		)	,      [
                   [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "b"}, {"score": 0.333, "label": "c"}],
                   [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "c"}, {"score": 0.333, "label": "b"}],
               ]	,      )

           _UpperCAmelCase     :      str														=       image_classifier([image] * 5	,      candidate_labels=["A", "B", "C"]	,      batch_size=2		)
           self.assertEqual(
               nested_simplify(A		)	,      [
                   [
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                   ],
                   [
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                   ],
                   [
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                   ],
                   [
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                   ],
                   [
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                   ],
               ]	,      )



      @require_tf
      def 		snake_case_   (	self	:      Any		):
           _UpperCAmelCase     :      List[str]														=       pipeline(
               model="hf-internal-testing/tiny-random-clip-zero-shot-image-classification"	,      framework="tf"		)
           _UpperCAmelCase     :      int														=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"		)
           _UpperCAmelCase     :      Union[str, Any]														=       image_classifier(A	,      candidate_labels=["a", "b", "c"]		)

           self.assertEqual(
               nested_simplify(A		)	,      [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "b"}, {"score": 0.333, "label": "c"}]	,      )

           _UpperCAmelCase     :      Optional[Any]														=       image_classifier([image] * 5	,      candidate_labels=["A", "B", "C"]	,      batch_size=2		)
           self.assertEqual(
               nested_simplify(A		)	,      [
                   [
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                   ],
                   [
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                   ],
                   [
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                   ],
                   [
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                   ],
                   [
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                       {"score": 0.333, "label": ANY(A		)},
                   ],
               ]	,      )



      @slow
      @require_torch
      def 		snake_case_   (	self	:      Any		):
           _UpperCAmelCase     :      Optional[Any]														=       pipeline(
               task="zero-shot-image-classification"	,      model="openai/clip-vit-base-patch32"	,      )
           # This is an image of 2 cats with remotes and no planes
           _UpperCAmelCase     :      Dict														=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"		)
           _UpperCAmelCase     :      List[Any]														=       image_classifier(A	,      candidate_labels=["cat", "plane", "remote"]		)

           self.assertEqual(
               nested_simplify(A		)	,      [
                   {"score": 0.511, "label": "remote"},
                   {"score": 0.485, "label": "cat"},
                   {"score": 0.004, "label": "plane"},
               ]	,      )

           _UpperCAmelCase     :      Tuple														=       image_classifier([image] * 5	,      candidate_labels=["cat", "plane", "remote"]	,      batch_size=2		)
           self.assertEqual(
               nested_simplify(A		)	,      [
                   [
                       {"score": 0.511, "label": "remote"},
                       {"score": 0.485, "label": "cat"},
                       {"score": 0.004, "label": "plane"},
                   ],
               ]
               * 5	,      )



      @slow
      @require_tf
      def 		snake_case_   (	self	:      Any		):
           _UpperCAmelCase     :      List[Any]														=       pipeline(
               task="zero-shot-image-classification"	,      model="openai/clip-vit-base-patch32"	,      framework="tf"		)
           # This is an image of 2 cats with remotes and no planes
           _UpperCAmelCase     :      Union[str, Any]														=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"		)
           _UpperCAmelCase     :      Union[str, Any]														=       image_classifier(A	,      candidate_labels=["cat", "plane", "remote"]		)
           self.assertEqual(
               nested_simplify(A		)	,      [
                   {"score": 0.511, "label": "remote"},
                   {"score": 0.485, "label": "cat"},
                   {"score": 0.004, "label": "plane"},
               ]	,      )

           _UpperCAmelCase     :      Union[str, Any]														=       image_classifier([image] * 5	,      candidate_labels=["cat", "plane", "remote"]	,      batch_size=2		)
           self.assertEqual(
               nested_simplify(A		)	,      [
                   [
                       {"score": 0.511, "label": "remote"},
                       {"score": 0.485, "label": "cat"},
                       {"score": 0.004, "label": "plane"},
                   ],
               ]
               * 5	,      )
