

import os
import tempfile
import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch


if is_torch_available():
    import torch
    from torch import nn

    from transformers import (
        Adafactor,
        AdamW,
        get_constant_schedule,
        get_constant_schedule_with_warmup,
        get_cosine_schedule_with_warmup,
        get_cosine_with_hard_restarts_schedule_with_warmup,
        get_inverse_sqrt_schedule,
        get_linear_schedule_with_warmup,
        get_polynomial_decay_schedule_with_warmup,
    )





def 	__a     (      A__			:  str			,  A__			:  Any=10       ):
    SCREAMING_SNAKE_CASE										=   []
    for _ in range(A__       ):
        lrs.append(scheduler.get_lr()[0]       )
        scheduler.step()
    return lrs





def 	__a     (      A__			:  List[Any]			,  A__			:  Optional[Any]=10       ):
    SCREAMING_SNAKE_CASE										=   []
    for step in range(A__       ):
        lrs.append(scheduler.get_lr()[0]       )
        scheduler.step()
        if step == num_steps // 2:
            with tempfile.TemporaryDirectory() as tmpdirname:
                SCREAMING_SNAKE_CASE										=   os.path.join(A__			,  "schedule.bin"       )
                torch.save(scheduler.state_dict()			,  A__       )

                SCREAMING_SNAKE_CASE										=   torch.load(A__       )
                scheduler.load_state_dict(A__       )
    return lrs





@require_torch
class 			_SCREAMING_SNAKE_CASE (   unittest.TestCase		):







   '''simple docstring'''




   def      _snake_case		(       self					:			Optional[int]     , __lowerCamelCase					:			Dict     , __lowerCamelCase					:			Optional[int]     , __lowerCamelCase					:			Tuple			):
       self.assertEqual(len(__lowerCamelCase			)     , len(__lowerCamelCase			)			)
       for a, b in zip(__lowerCamelCase     , __lowerCamelCase			):
           self.assertAlmostEqual(__lowerCamelCase     , __lowerCamelCase     , delta=__lowerCamelCase			)





   def      _snake_case		(       self					:			List[str]			):
       SCREAMING_SNAKE_CASE										=   torch.tensor([0.1, -0.2, -0.1]     , requires_grad=__lowerCamelCase			)
       SCREAMING_SNAKE_CASE										=   torch.tensor([0.4, 0.2, -0.5]			)
       SCREAMING_SNAKE_CASE										=   nn.MSELoss()
       # No warmup, constant schedule, no gradient clipping
       SCREAMING_SNAKE_CASE										=   AdamW(params=[w]     , lr=2e-1     , weight_decay=0.0			)
       for _ in range(100			):
           SCREAMING_SNAKE_CASE										=   criterion(__lowerCamelCase     , __lowerCamelCase			)
           loss.backward()
           optimizer.step()
           w.grad.detach_()  # No zero_grad() function on simple tensors. we do it ourselves.
           w.grad.zero_()
       self.assertListAlmostEqual(w.tolist()     , [0.4, 0.2, -0.5]     , tol=1e-2			)





   def      _snake_case		(       self					:			Optional[int]			):
       SCREAMING_SNAKE_CASE										=   torch.tensor([0.1, -0.2, -0.1]     , requires_grad=__lowerCamelCase			)
       SCREAMING_SNAKE_CASE										=   torch.tensor([0.4, 0.2, -0.5]			)
       SCREAMING_SNAKE_CASE										=   nn.MSELoss()
       # No warmup, constant schedule, no gradient clipping
       SCREAMING_SNAKE_CASE										=   Adafactor(
           params=[w]     , lr=1e-2     , eps=(1e-30, 1e-3)     , clip_threshold=1.0     , decay_rate=-0.8     , betaa=__lowerCamelCase     , weight_decay=0.0     , relative_step=__lowerCamelCase     , scale_parameter=__lowerCamelCase     , warmup_init=__lowerCamelCase     , )
       for _ in range(1000			):
           SCREAMING_SNAKE_CASE										=   criterion(__lowerCamelCase     , __lowerCamelCase			)
           loss.backward()
           optimizer.step()
           w.grad.detach_()  # No zero_grad() function on simple tensors. we do it ourselves.
           w.grad.zero_()
       self.assertListAlmostEqual(w.tolist()     , [0.4, 0.2, -0.5]     , tol=1e-2			)





@require_torch
class 			_SCREAMING_SNAKE_CASE (   unittest.TestCase		):







   '''simple docstring'''




   lowerCamelCase__				=      nn.Linear(5_0					,       5_0		) if is_torch_available() else None
   lowerCamelCase__				=      AdamW(m.parameters()					,       lr=10.0		) if is_torch_available() else None
   lowerCamelCase__				=      1_0





   def      _snake_case		(       self					:			Dict     , __lowerCamelCase					:			List[str]     , __lowerCamelCase					:			Optional[Any]     , __lowerCamelCase					:			Tuple     , __lowerCamelCase					:			Any=None			):
       self.assertEqual(len(__lowerCamelCase			)     , len(__lowerCamelCase			)			)
       for a, b in zip(__lowerCamelCase     , __lowerCamelCase			):
           self.assertAlmostEqual(__lowerCamelCase     , __lowerCamelCase     , delta=__lowerCamelCase     , msg=__lowerCamelCase			)





   def      _snake_case		(       self					:			Tuple			):
       SCREAMING_SNAKE_CASE										=   {"num_warmup_steps": 2, "num_training_steps": 10}
       # schedulers doct format
       # function: (sched_args_dict, expected_learning_rates)
       SCREAMING_SNAKE_CASE										=   {
           get_constant_schedule: ({}, [10.0] * self.num_steps),
           get_constant_schedule_with_warmup: (
               {"num_warmup_steps": 4},
               [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0],
           ),
           get_linear_schedule_with_warmup: (
               {**common_kwargs},
               [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25],
           ),
           get_cosine_schedule_with_warmup: (
               {**common_kwargs},
               [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38],
           ),
           get_cosine_with_hard_restarts_schedule_with_warmup: (
               {**common_kwargs, "num_cycles": 2},
               [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46],
           ),
           get_polynomial_decay_schedule_with_warmup: (
               {**common_kwargs, "power": 2.0, "lr_end": 1e-7},
               [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156],
           ),
           get_inverse_sqrt_schedule: (
               {"num_warmup_steps": 2},
               [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714],
           ),
       }

       for scheduler_func, data in scheds.items():
           SCREAMING_SNAKE_CASE							,	SCREAMING_SNAKE_CASE										=   data

           SCREAMING_SNAKE_CASE										=   scheduler_func(self.optimizer     , **__lowerCamelCase			)
           self.assertEqual(len([scheduler.get_lr()[0]]			)     , 1			)
           SCREAMING_SNAKE_CASE										=   unwrap_schedule(__lowerCamelCase     , self.num_steps			)
           self.assertListAlmostEqual(
               __lowerCamelCase     , __lowerCamelCase     , tol=1e-2     , msg=f"failed for {scheduler_func} in normal scheduler"     , )

           SCREAMING_SNAKE_CASE										=   scheduler_func(self.optimizer     , **__lowerCamelCase			)
           if scheduler_func.__name__ != "get_constant_schedule":
               LambdaScheduleWrapper.wrap_scheduler(__lowerCamelCase			)  # wrap to test picklability of the schedule
           SCREAMING_SNAKE_CASE										=   unwrap_and_save_reload_schedule(__lowerCamelCase     , self.num_steps			)
           self.assertListEqual(__lowerCamelCase     , __lowerCamelCase     , msg=f"failed for {scheduler_func} in save and reload"			)





class 			_SCREAMING_SNAKE_CASE :







   '''simple docstring'''




   def __init__(       self					:			str     , __lowerCamelCase					:			List[Any]			):
       SCREAMING_SNAKE_CASE										=   fn





   def __call__(       self					:			List[Any]     , *__lowerCamelCase					:			Optional[Any]     , **__lowerCamelCase					:			List[Any]			):
       return self.fn(*__lowerCamelCase     , **__lowerCamelCase			)





   @classmethod
   def      _snake_case		(       self					:			List[Any]     , __lowerCamelCase					:			Dict			):
       SCREAMING_SNAKE_CASE										=   list(map(self     , scheduler.lr_lambdas			)			)




"""simple docstring"""







import importlib
import inspect
import os
import re


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_config_docstrings.py
A		=						'src/transformers'


# This is to make sure the transformers module imported is the one in the repo.
A		=						importlib.util.spec_from_file_location(
    'transformers',
    os.path.join(PATH_TO_TRANSFORMERS, '__init__.py'),
    submodule_search_locations=[PATH_TO_TRANSFORMERS],
)
A		=						spec.loader.load_module()

A		=						transformers.models.auto.configuration_auto.CONFIG_MAPPING

# Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`.
# For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)`
A		=						re.compile('\[(.+?)\]\((https://huggingface\.co/.+?)\)')


A		=						{
    'CLIPConfigMixin',
    'DecisionTransformerConfigMixin',
    'EncoderDecoderConfigMixin',
    'RagConfigMixin',
    'SpeechEncoderDecoderConfigMixin',
    'VisionEncoderDecoderConfigMixin',
    'VisionTextDualEncoderConfigMixin',
}

def  __SCREAMING_SNAKE_CASE		(			):
						"""simple docstring"""






						snake_case   :			Union[str, Any]						    = []

						for config_class in list(CONFIG_MAPPING.values() ):
												snake_case   :			List[str]						    = False

												# source code of `config_class`
												snake_case   :			Optional[int]						    = inspect.getsource(lowerCamelCase_ )
												snake_case   :			Optional[int]						    = _re_checkpoint.findall(lowerCamelCase_ )

												for checkpoint in checkpoints:
																		# Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link.
																		# For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')`
																		snake_case    ,			snake_case   :			Tuple						    = checkpoint

																		# verify the checkpoint name corresponds to the checkpoint link
																		snake_case   :			Any						    = f'''https://huggingface.co/{ckpt_name}'''
																		if ckpt_link == ckpt_link_from_name:
																								snake_case   :			List[str]						    = True
																								break

												snake_case   :			Any						    = config_class.__name__
												if not checkpoint_found and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK:
																		configs_without_checkpoint.append(lowerCamelCase_ )

						if len(lowerCamelCase_ ) > 0:
												snake_case   :			List[str]						    = "\n".join(sorted(lowerCamelCase_ ) )
												raise ValueError(f'''The following configurations don\'t contain any valid checkpoint:\n{message}''' )


if __name__ == "__main__":
			check_config_docstrings_have_checkpoints()



