o
    OeF#  ã                   @   sP   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é2   çH¯¼šò×z>ç•Ö&è.>r   ç      ð?Úfloat32c                    s"  ˆdvrt d ˆ¡ƒ‚d}t|d|ƒ tj|jd ˆd�‰ |du r$ˆ }n
t|d|ƒ t|ƒ 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�}‡fdd„}‡ ‡‡‡‡‡‡fdd„}tjjj||||||||||gd� ||||||fS )a  
    Minimizes a differentiable function `func` using the BFGS method.
    The 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. pp140: Algorithm 6.1 (BFGS Method).

    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`` . 
        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`.
            - inverse_hessian_estimate (Tensor): the estimate of inverse hessian 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_bfgs(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_bfgsÚinitial_positionr   ©ÚdtypeNÚ initial_inverse_hessian_estimater   Zint64©ÚshapeZ
fill_valuer   FÚboolc                    s   | ˆ k | @ S )N© )ÚkÚdoneÚis_convergeÚnum_func_callsÚxkÚvalueÚg1ÚHk)Ú	max_itersr   úYD:\Projects\ConvertPro\env\Lib\site-packages\paddle/incubate/optimizer/functional/bfgs.pyÚcondx   s   zminimize_bfgs.<locals>.condc                    sv  t  ||¡ }ˆdkrtˆ||ˆˆd�\}	}}
}ntd ˆ¡ƒ‚||7 }|	| }|
| }|| }|
}t  |d¡}t  |d¡}t  ||¡‰ t jj 	ˆ dk‡fdd„‡ fdd„¡}ˆ|| | 
¡   }ˆ|| | 
¡   }t  t  ||¡|¡|| | 
¡   }| 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   )Úfr   ÚpkÚinitial_step_lengthr   zQCurrently only support line_search_fn = 'strong_wolfe', but the specified is '{}'r   g        c                      s   t jdgdˆ d�S )Nr   g     @�@r   )ÚpaddleÚfullr   r   r   r   Ú<lambda>š   s    z-minimize_bfgs.<locals>.body.<locals>.<lambda>c                      s   dˆ  S )Nr
   r   r   ©Zrhok_invr   r   r%   ›   s    r   )Úp)r#   Úmatmulr   ÚNotImplementedErrorÚformatZ	unsqueezeÚdotÚstaticÚnnr   ÚtZlinalgZnormÚnpÚinfÚassign)r   r   r   r   r   r   r   r   r!   ÚalphaÚg2Zls_func_callsÚskZykZrhokZVk_transposeZVkZgnormZpk_norm)ÚIr   r"   Úline_search_fnÚobjective_funcÚtolerance_changeÚtolerance_gradr&   r   Úbody{   sV   ûþ

ýÿÿþzminimize_bfgs.<locals>.body)r   r:   Z	loop_vars)Ú
ValueErrorr*   r   r#   Úeyer   r   r1   Údetachr   r$   r,   r-   Z
while_loop)r7   r   r   r9   r8   r   r6   Zmax_line_search_itersr"   r   ÚnameZop_namer   r   r   r   r   r   r   r   r   r:   r   )r5   r   r"   r6   r   r7   r8   r9   r   r      s:   Eþÿ
4ýr   )	r   r   r	   Nr   r   r
   r   N)
Únumpyr/   Zline_searchr   Úutilsr   r   r   r#   r   r   r   r   r   Ú<module>   s   ö