

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'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging


_SCREAMING_SNAKE_CASE			=						logging.get_logger(__name__)

_SCREAMING_SNAKE_CASE			=						{"openai-gpt": "https://huggingface.co/openai-gpt/resolve/main/config.json"}
class   __UpperCAmelCase				(     lowerCAmelCase				):



					'''simple docstring'''





					_UpperCamelCase							=		"""openai-gpt"""
					_UpperCamelCase							=		{
					    """max_position_embeddings""": """n_positions""",
					    """hidden_size""": """n_embd""",
					    """num_attention_heads""": """n_head""",
					    """num_hidden_layers""": """n_layer""",
					}



					def __init__(	self     :						Any      ,       _lowercase     :						List[Any]=40_478      ,       _lowercase     :						Tuple=512      ,       _lowercase     :						Dict=768      ,       _lowercase     :						List[str]=12      ,       _lowercase     :						Optional[int]=12      ,       _lowercase     :						Tuple="gelu"      ,       _lowercase     :						int=0.1      ,       _lowercase     :						Tuple=0.1      ,       _lowercase     :						Any=0.1      ,       _lowercase     :						List[str]=1E-5      ,       _lowercase     :						str=0.02      ,       _lowercase     :						Optional[Any]="cls_index"      ,       _lowercase     :						int=True      ,       _lowercase     :						str=None      ,       _lowercase     :						Tuple=True      ,       _lowercase     :						List[Any]=0.1      ,       **_lowercase     :						int      ,       )    ->							Optional[int]:
								A_									= vocab_size
								A_									= n_positions
								A_									= n_embd
								A_									= n_layer
								A_									= n_head
								A_									= afn
								A_									= resid_pdrop
								A_									= embd_pdrop
								A_									= attn_pdrop
								A_									= layer_norm_epsilon
								A_									= initializer_range
								A_									= summary_type
								A_									= summary_use_proj
								A_									= summary_activation
								A_									= summary_first_dropout
								A_									= summary_proj_to_labels
								super().__init__(**_lowercase)




