o
    Oeç,  ã                   @   sR   d dl ZddlmZ ddlmZmZmZ d dlZ										
	ddd„Z	dS )é    Né   )Ústrong_wolfe)Ú_value_and_gradientÚcheck_input_typeÚ&check_initial_inverse_hessian_estimateéd   é2   ç:Œ0âŽyE>r   ç      ð?Úfloat32c                    sº  ˆdvrt d ˆ¡ƒ‚d}t|d|ƒ |du r"tj|jd ˆd�‰ nt|d|ƒ t|ƒ |‰ t | ¡ ¡}t	ˆ|ƒ\}}tj
d	gdd
d�}tj
d	gddd�}tj
d	gddd�}tj
d	gd	d
d�}tj
d	gˆd
d�‰tj
d	gd	d
d�}tj
d	gdd
d�}|jd }tjˆd	 |fˆd�}tjˆd	 |fˆd�}tjˆd	 d	fˆd�}tjˆd	 d	fˆd�‰‡fdd„}‡ ‡‡‡‡‡‡‡‡	f	dd„}tjjj||||||||||||||gd� |||||fS )a  
    Minimizes a differentiable function `func` using the L-BFGS method.
    The L-BFGS is a quasi-Newton method for solving an unconstrained optimization problem over a differentiable function.
    Closely related is the Newton method for minimization. Consider the iterate update formula:

    .. math::
        x_{k+1} = x_{k} + H_k \nabla{f_k}

    If :math:`H_k` is the inverse Hessian of :math:`f` at :math:`x_k`, then it's the Newton method.
    If :math:`H_k` is symmetric and positive definite, used as an approximation of the inverse Hessian, then 
    it's a quasi-Newton. In practice, the approximated Hessians are obtained
    by only using the gradients, over either whole or part of the search 
    history, the former is BFGS, the latter is L-BFGS.

    Reference:
        Jorge Nocedal, Stephen J. Wright, Numerical Optimization, Second Edition, 2006. pp179: Algorithm 7.5 (L-BFGS).

    Args:
        objective_func: the objective function to minimize. ``objective_func`` accepts a 1D Tensor and returns a scalar.
        initial_position (Tensor): the starting point of the iterates, has the same shape with the input of ``objective_func`` . 
        history_size (Scalar): the number of stored vector pairs {si,yi}. Default value: 100.
        max_iters (int, optional): the maximum number of minimization iterations. Default value: 50.
        tolerance_grad (float, optional): terminates if the gradient norm is smaller than this. Currently gradient norm uses inf norm. Default value: 1e-7.
        tolerance_change (float, optional): terminates if the change of function value/position/parameter between two iterations is smaller than this value. Default value: 1e-9.
        initial_inverse_hessian_estimate (Tensor, optional): the initial inverse hessian approximation at initial_position. It must be symmetric and positive definite. If not given, will use an identity matrix of order N, which is size of ``initial_position`` . Default value: None.
        line_search_fn (str, optional): indicate which line search method to use, only support 'strong wolfe' right now. May support 'Hager Zhang' in the futrue. Default value: 'strong wolfe'.
        max_line_search_iters (int, optional): the maximum number of line search iterations. Default value: 50.
        initial_step_length (float, optional): step length used in first iteration of line search. different initial_step_length may cause different optimal result. For methods like Newton and quasi-Newton the initial trial step length should always be 1.0. Default value: 1.0.
        dtype ('float32' | 'float64', optional): data type used in the algorithm, the data type of the input parameter must be consistent with the dtype. Default value: 'float32'.
        name (str, optional): Name for the operation. For more information, please refer to :ref:`api_guide_Name`. Default value: None.

    Returns:
        output(tuple):

            - is_converge (bool): Indicates whether found the minimum within tolerance.
            - num_func_calls (int): number of objective function called.
            - position (Tensor): the position of the last iteration. If the search converged, this value is the argmin of the objective function regrading to the initial position.
            - objective_value (Tensor): objective function value at the `position`.
            - objective_gradient (Tensor): objective function gradient at the `position`.
            
    Examples:
        .. code-block:: python

            import paddle
            
            def func(x):
                return paddle.dot(x, x)

            x0 = paddle.to_tensor([1.3, 2.7])
            results = paddle.incubate.optimizer.functional.minimize_lbfgs(func, x0)
            print("is_converge: ", results[0])
            print("the minimum of func is: ", results[2])
            # is_converge:  is_converge:  Tensor(shape=[1], dtype=bool, place=Place(gpu:0), stop_gradient=True,
            #        [True])
            # the minimum of func is:  Tensor(shape=[2], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [0., 0.])
    )r   Zfloat64zBThe dtype must be 'float32' or 'float64', but the specified is {}.Úminimize_lbfgsÚinitial_positionNr   ©ÚdtypeÚ initial_inverse_hessian_estimater   Úint64©ÚshapeZ
fill_valuer   FÚboolc                    s   | ˆ k | @ S ©N© )ÚkÚdoneÚis_convergeÚnum_func_callsÚvalueÚxkÚg1Úsk_vecÚyk_vecÚrhok_vecÚheadÚtail)Ú	max_itersr   úZD:\Projects\ConvertPro\env\Lib\site-packages\paddle/incubate/optimizer/functional/lbfgs.pyÚcond…   s   zminimize_lbfgs.<locals>.condc                    s  t  |¡}t jdgˆ d  ˆ
¡dd�}‡fdd„}‡‡
‡‡‡fdd„}t jjj||||gd� t  ˆ|¡}t jdgˆd dd�}‡ fd	d„}‡‡
‡‡‡fd
d„}t jjj||||gd� | }ˆdkrqtˆ||ˆˆ	d�\}}}}nt	d 
ˆ¡ƒ‚t  || |¡ || }|| }t  ||¡‰t jj ˆdk‡	fdd„‡fdd„¡}|ˆˆ < |ˆˆ < |ˆˆ < ˆ d ˆ
 ‰ dd„ ‰t jj ˆ ˆk‡‡fdd„d ¡ || }|}| d7 } t jj|tjd�}t jj|tjd�}t  ||ˆk B |ˆk B |¡ t  ||¡ t  ||dkB |¡ | ||||||ˆˆˆˆ ˆgS )Nr   r   r   c                    ó   | ˆ kS r   r   ©ÚiÚq©r"   r   r$   r%   ”   ó   z*minimize_lbfgs.<locals>.body.<locals>.condc                    sF   ˆ|  t  ˆ|  |¡ ˆ | < |ˆ |  ˆ|    }| d  ˆ¡} | |fS ©Nr   ©ÚpaddleÚdotÚmodr'   ©Úai_vecÚhistory_sizer    r   r   r   r$   Úbody—   s   z*minimize_lbfgs.<locals>.body.<locals>.body©r%   r4   Z	loop_varsc                    r&   r   r   )r(   Úr)r!   r   r$   r%   £   r+   c                    sF   ˆ|  t  ˆ|  |¡ }|ˆ|  ˆ |  |   }| d  ˆ¡} | |fS r,   r-   )r(   r6   Úbetar1   r   r$   r4   ¦   s   r   )Úfr   ÚpkÚinitial_step_lengthr   zQCurrently only support line_search_fn = 'strong_wolfe', but the specified is '{}'g        c                      s   t jdgdˆ d�S )Nr   g     @�@r   )r.   Úfullr   r   r   r$   Ú<lambda>Å   s    z.minimize_lbfgs.<locals>.body.<locals>.<lambda>c                      s   dˆ  S )Nr
   r   r   )Úrhok_invr   r$   r<   Æ   ó    c                 S   s   t  | d | ¡ d S r,   )r.   Úassignr*   r   r   r$   Útrue_fnÍ   s   z-minimize_lbfgs.<locals>.body.<locals>.true_fnc                      s   ˆˆ ƒS r   r   r   )r"   r@   r   r$   r<   Ñ   r>   )Úp)r.   r?   r;   r0   ÚstaticÚnnÚ
while_loopÚmatmulr   ÚNotImplementedErrorÚformatr/   r%   ZlinalgZnormÚnpÚinf)r   r   r   r   r   r   r   r   r   r    r!   r"   r)   r(   r%   r4   r6   r9   ÚalphaÚg2Zls_func_callsÚskZykZrhokZgnormZpk_norm)	ÚH0r2   r   r3   r:   Úline_search_fnÚobjective_funcÚtolerance_changeÚtolerance_grad)r!   r=   r    r   r"   r@   r   r$   r4   ‰   sn   
þûþ

ý þþzminimize_lbfgs.<locals>.bodyr5   )Ú
ValueErrorrG   r   r.   Úeyer   r   r?   Údetachr   r;   ZzerosrB   rC   rD   )rO   r   r3   r#   rQ   rP   r   rN   Zmax_line_search_itersr:   r   ÚnameZop_namer   r   r   r   r   r   r   r!   r"   r   r   r   r    r%   r4   r   )
rM   r2   r   r3   r:   rN   r#   rO   rP   rQ   r$   r      sP   Eþÿþ

]
þþr   )
r   r   r	   r	   Nr   r   r
   r   N)
ÚnumpyrH   Zline_searchr   Úutilsr   r   r   r.   r   r   r   r   r$   Ú<module>   s   õ