a
    /Sic%                  	   @   s  d Z ddlZddlZddlZddlZddlmZ ddlmZ ddlm	Z	 ddlm
Z
 ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddl m!Z! ddl"m#Z$ ddl%m&Z& ddl%m'Z' ddl%m(Z( ddl%m)Z) dd l%m*Z* dd!l+m,Z, dd"l-m.Z. e,d#e/ d$Z0e,d%e/ d&Z1i Z2d'd( Z3d)d* Z4G d+d, d,e5Z6d-d. Z7e8e7 d/d0 Z9e.d1g d2d3d4 Z:e9e
_;e:e
_:d5d6 Z<d7d8 Z=d9d: Z>dZd;d<Z?d=d> Z@d[d?d@ZAd\dBdCZBdDdE ZCdFdG ZDdHdI ZEdJdK ZFdLdM ZGdNdO ZHdPdQ ZIejJeFeEeHeIejKejLejMdRZNeOeN dSdT ZPdUdV ZQe.dWdXdWgd2G dYdW dWe5ZRdS )]z2Code for backpropagation using the tape utilities.    N)
pywrap_tfe)backprop_util)context)execute)imperative_grad)tape)composite_tensor)composite_tensor_gradient)constant_op)dtypes)indexed_slices)ops)tensor_shape)tensor_util)	type_spec)	array_ops)	check_ops)control_flow_util)default_gradient)gen_array_ops)gen_math_ops)math_ops)resource_variable_ops)UnconnectedGradients)
tf_logging)_pywrap_utils)nest)tf_contextlib)
tf_inspect)variable_utils)
LazyLoader)	tf_exportpfor_opsz3tensorflow.python.ops.parallel_for.control_flow_opsfunctionz tensorflow.python.eager.functionc                 C   sR   zt | |f W S  ty@   t  t j}t|| |}Y n0 |t | |f< |S N)_op_attr_type_cacheKeyErrorr   ensure_initialized_handler   TFE_OpNameGetAttrType)op_type	attr_nameh	attr_type r.   \/var/www/html/django/DPS/env/lib/python3.9/site-packages/tensorflow/python/eager/backprop.pyop_attr_typeI   s    
r0   c                 C   s   | t tjkrt|S | t tjgkr6dd |D S | t tjkrRt| S | t tjgkrpdd |D S t	
dd |S )Nc                 S   s   g | ]}t |qS r.   )r   as_dtype.0vr.   r.   r/   
<listcomp>^       zmake_attr.<locals>.<listcomp>c                 S   s   g | ]}t | qS r.   )r   as_shapeas_protor2   r.   r.   r/   r5   b   r6   c                 S   s   t | tr|  S | S r$   )
isinstancestrencode)r4   r.   r.   r/   <lambda>d   r6   zmake_attr.<locals>.<lambda>)intr   TF_ATTR_TYPEr   r1   TF_ATTR_SHAPEr   r7   r8   r   map_structure)r-   valuer.   r.   r/   	make_attrT   s    
rB   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	_MockOpz9Pretends to be a tf.Operation for the gradient functions.c                 C   s"   || _ || _|| _|| _|| _d S r$   )attrsinputsoutputstypeskip_input_indices)selfrD   rE   rF   typrH   r.   r.   r/   __init__k   s
    z_MockOp.__init__c                 C   sV   t | j|}tdt| jdD ]*}| j| |krt|| j|d    S qt|d S )Nr         )r0   rG   rangelenrD   rB   r&   )rI   attrrJ   ir.   r.   r/   get_attrr   s
    z_MockOp.get_attrc                 C   s   t dd S )Nztf.GradientTape.gradients() does not support graph control flow operations like tf.cond or tf.while at this time. Use tf.gradients() instead. If you need this feature, please file a feature request at https://github.com/tensorflow/tensorflow/issues/new)NotImplementedErrorrI   r.   r.   r/   _get_control_flow_contexty   s    z!_MockOp._get_control_flow_contextN)__name__
__module____qualname____doc__rK   rR   rU   r.   r.   r.   r/   rC   h   s   rC   c                 C   s   t |||| |}tj| }	|	du r.dg| S t sDtt rd}
|rX|
|d 7 }
t|
  |	|g|R  W  d   S 1 s0    Y  n|	|g|R  S dS )a  Calls the gradient function of the op.

  Args:
    op_name: the name of the op to be differentiated.
    attr_tuple: the attrs, as a tuple.
    num_inputs: the number of inputs to the op.
    inputs: inputs to the original operation.
    outputs: outputs to the original operation.
    out_grads: gradients of the operation wrt its outputs.
    skip_input_indices: a tuple that is passed to the gradient function,
      indicating which inputs to skip calculating the gradient for
    forward_pass_name_scope: the namescope of the op in the forward pass.

  Returns:
    The gradients with respect to the inputs of the function, as a list.
  Nzgradient_tape//)	rC   r   _gradient_registrylookup#executing_eagerly_outside_functionsr   EnableControlFlowV2get_default_graph
name_scope)op_nameZ
attr_tuple
num_inputsrE   rF   Z	out_gradsrH   Zforward_pass_name_scopeZmock_opgrad_fnZgradient_name_scoper.   r.   r/   _gradient_function   s    
0rd   c                   C   s
   t   S r$   )r   TFE_Py_TapeSetIsEmptyr.   r.   r.   r/   _must_record_gradient   s    rf   z__internal__.record_gradient)v1c                 C   s   t | |||t  dS )aF  Explicitly record the gradient for a given op.

  Args:
    op_name: The op name as listed in the `OpDef` for the op.
    inputs: A list of tensor inputs to the op.
    attrs: The op attributes as a flattened list of alternating attribute names
      and attribute values.
    outputs: A list of tensor outputs from the op.
  N)r   TFE_Py_RecordGradientr   get_name_scope)ra   rE   rD   rF   r.   r.   r/   record_gradient   s    rj   c                    s    fdd}|S )a  Returns a function which differentiates f with respect to variables.

  The wrapped function returns the value and the gradient of f when called with
  the same arguments. The gradient is with respect to all trainable TFE
  variables accessed by `f`.

  This function is useful when the exact set of variables to differentiate with
  is not known ahead of time.

  Example:

  ```python
  dense_layer = tf.compat.v1.layers.Dense(1)
  def loss(x, y):
    return tf.reduce_sum(tf.square(dense_layer(x) - y))

  # Obtain the gradient function.
  val_grad_fn = tfe.implicit_value_and_gradients(loss)

  # Invoke the gradient function with concrete values of x and y.
  x = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
  y = tf.constant([[10.0], [20.0]])
  value, grads_and_vars = val_grad_fn(x, y)
  print('Value of loss: %s' % value)

  # Apply the gradients to Variables.
  optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.1)
  optimizer.apply_gradients(grads_and_vars)
  ```

  Args:
    f: function to be differentiated. If `f` returns a scalar, this scalar will
      be differentiated. If `f` returns a tensor or list of tensors, by default
      a scalar will be computed by adding all their values to produce a single
      scalar.

  Returns:
    A function which, when called, returns a tuple pair.
    Its first element is the value to which the function evaluates.
    Its second element is list of (gradient, variable) pairs.

  Raises:
    ValueError: if `f` returns None.
  c               	      s   t  }z4 | i |}|du r0td jW t | nt | 0 | }|s^tddd |D }|D ]}t|ddrptdqpt|t	
||}|tt||fS )	.Computes the gradient of the wrapped function.N\Cannot differentiate a function that returns None; did you forget to return a value from {}?zKNo trainable variables were accessed while the function was being computed.c                 S   s   g | ]
}|j qS r.   )handler2   r.   r.   r/   r5     r6   z:implicit_val_and_grad.<locals>.grad_fn.<locals>.<listcomp>	is_packedFBGradientTape.gradient is not supported on packed EagerTensors yet.)r   push_new_tape
ValueErrorformatrV   pop_tapewatched_variablesgetattrr   r   flattenlistzip)argskwds	this_tapeZend_node	variablessourcessgradfr.   r/   rc      s*    z&implicit_val_and_grad.<locals>.grad_fnr.   r   rc   r.   r   r/   implicit_val_and_grad   s    0r   c                    s    fdd}|S )a  Returns a function which differentiates f with respect to variables.

  The wrapped function returns the gradient of f when called with the same
  arguments. The gradient is with respect to all trainable TFE variables
  accessed by `f`.

  This function is useful when the exact set of variables to differentiate with
  is not known ahead of time.

  Example:

  ```python
  dense_layer = tf.compat.v1.layers.Dense(1)
  def loss(x, y):
    return tf.reduce_sum(tf.square(dense_layer(x) - y))

  # Obtain the gradient function.
  grad_fn = tfe.implicit_gradients(loss)

  # Invoke the gradient function with concrete values of x and y.
  x = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
  y = tf.constant([[10.0], [20.0]])
  grads_and_vars = grad_fn(x, y)

  # Apply the gradients to Variables.
  optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.1)
  optimizer.apply_gradients(grads_and_vars)
  ```

  Args:
    f: function to be differentiated. If `f` returns a scalar, this scalar will
      be differentiated. If `f` returns a tensor or list of tensors, by default
      a scalar will be computed by adding all their values to produce a single
      scalar.

  Returns:
    A function which, when called, returns a list of (gradient, variable) pairs.
  c                     s   t  | i |d S )rk   rM   )r   )ry   rz   r   r.   r/   rc   8  s    zimplicit_grad.<locals>.grad_fnr.   r   r.   r   r/   implicit_grad  s    *r   c              
      s  zt | j W nv ty } z^|du r@tt|W  Y d}~S tdd |D rb|W  Y d}~S td| |f W Y d}~n
d}~0 0 |du rʈ stt|S  d dkrtt d S tt S nHtdd |D r fd	d
|D S tdd |D r|S td| dS )zHThe positions of the parameters of f to be differentiated in param_args.Nc                 s   s   | ]}t |tV  qd S r$   r9   r=   r3   xr.   r.   r/   	<genexpr>G  r6   z _get_arg_spec.<locals>.<genexpr>zmEither callable provided is not a function or could not inspect its arguments by name: %s. Original error: %sr   rI   rM   c                 s   s   | ]}t |tjV  qd S r$   )r9   sixstring_typesr   r.   r.   r/   r   S  r6   c                    s   g | ]}  |qS r.   )index)r3   nry   r.   r/   r5   T  r6   z!_get_arg_spec.<locals>.<listcomp>c                 s   s   | ]}t |tV  qd S r$   r   r   r.   r.   r/   r   U  r6   z3params must be all strings or all integers; got %s.)r   getfullargspecry   	TypeErrorrN   rO   allrq   )r   paramsZ
param_argser.   r   r/   _get_arg_spec?  s.    r   c                    s    fdd}|S )a	  Returns a function which differentiates f with respect to params.

  Example:
  ```python
  # f(x, y) = (x ^ 3) * y - x * (y ^ 2)
  # Therefore, the 1st order derivatives are:
  #   df / dx = 3 * (x ^ 2) * y - y ^ 2
  #   df / dy = x ^ 3 - 2 * x * y
  # The 2nd order derivatives with respect to x is:
  #   d^2 f / (dx)^2 = 6 * x * y
  def f(x, y):
    return x * x * x * y - x * y * y

  # Obtain a function that returns 1st order gradients.
  grad_fn = tfe.gradients_function(f)

  x = 2.0
  y = 3.0

  # Invoke the 1st order gradient function.
  x_grad, y_grad = grad_fn(x, y)
  assert x_grad.numpy() == 3 * (2 ** 2) * 3 - 3 ** 2
  assert y_grad.numpy() == (2 ** 3) - 2 * 2 * 3

  # Obtain a function that returns the 2nd order gradient with respect to x.
  gradgrad_fn = tfe.gradients_function(lambda x, y: grad_fn(x, y)[0])

  # Invoke the 2nd order gradient function.
  x_gradgrad = gradgrad_fn(x, y)[0]
  assert x_gradgrad.numpy() == 6 * 2 * 3

  # To obtain a callable that returns the gradient(s) of `f` with respect to a
  # subset of its inputs, use the `params` keyword argument with
  # `gradients_function()`.
  ygrad_fn = tfe.gradients_function(f, params=[1])

  (y_grad,) = ygrad_fn(x, y)
  assert y_grad.numpy() == (2 ** 3) - 2 * 2 * 3
  ```

  Note that only tensors with real or complex dtypes are differentiable.

  Args:
    f: function to be differentiated. If `f` returns a scalar, this scalar will
      be differentiated. If `f` returns a tensor or list of tensors, by default
      a scalar will be computed by adding all their values to produce a single
      scalar. If desired, the tensors can be elementwise multiplied by the
      tensors passed as the `dy` keyword argument to the returned gradient
      function.
    params: list of parameter names of f or list of integers indexing the
      parameters with respect to which we'll differentiate. Passing None
      differentiates with respect to all parameters.

  Returns:
    function which, when called, returns the value of f and the gradient
    of `f` with respect to all of `params`. The function takes an extra optional
    keyword argument `dy`. Setting it allows computation of vector jacobian
    products for vectors other than the vector of ones.

  Raises:
    ValueError: if the params are not all strings or all integers.
  c                     s   t  d| i |\}}|S )z0Computes the gradient of the decorated function.)r   )val_and_grad_function)ry   rz   _r   r   r   r.   r/   	decorated  s    z%gradients_function.<locals>.decoratedr.   r   r   r   r.   r   r/   gradients_function\  s    @r   c                 C   sT   t  }t|D ]@\}}|| v rt|}||v rDt|| ||< q|| q|S )a.  Make each of the parameter_positions in args a unique ops.Tensor object.

  Ensure that each parameter is treated independently.
  For example:

  def f(x, y): return x * y
  g = gradients_function(f)
  one = tf.constant(1.)

  g(one, one) should return [1., 1.]
  (even though the two arguments are the same Tensor object).

  Args:
    parameter_positions: List of indices into args defining the arguments to
      differentiate against.
    args: A list of arguments to the function to be differentiated.

  Returns:
    args, possibly edited in-place.
  )set	enumerater   	tensor_idr   identityadd)parameter_positionsry   r~   rQ   ttidr.   r.   r/   _ensure_unique_tensor_objects  s    
r   c                    s    fdd}|S )aM  Returns a function that computes f and its derivative w.r.t. params.

  Example:
  ```python
  # f(x, y) = (x ^ 3) * y - x * (y ^ 2)
  # Therefore, the 1st order derivatives are:
  #   df / dx = 3 * (x ^ 2) * y - y ^ 2
  #   df / dy = x ^ 3 - 2 * x * y
  def f(x, y):
    return x * x * x * y - x * y * y

  # Obtain a function that returns the function value and the 1st order
  # gradients.
  val_grads_fn = tfe.value_and_gradients_function(f)

  x = 2.0
  y = 3.0

  # Invoke the value-and-gradients function.
  f_val, (x_grad, y_grad) = val_grads_fn(x, y)
  assert f_val.numpy() == (2 ** 3) * 3 - 2 * (3 ** 2)
  assert x_grad.numpy() == 3 * (2 ** 2) * 3 - 3 ** 2
  assert y_grad.numpy() == (2 ** 3) - 2 * 2 * 3

  # To obtain a callable that returns the value of `f` and the gradient(s) of
  # `f` with respect to a subset of its inputs, use the `params` keyword
  # argument with `value_and_gradients_function()`.
  val_ygrad_fn = tfe.value_and_gradients_function(f, params=[1])

  f_val, (y_grad,) = val_ygrad_fn(x, y)
  assert f_val.numpy() == (2 ** 3) * 3 - 2 * (3 ** 2)
  assert y_grad.numpy() == (2 ** 3) - 2 * 2 * 3
  ```

  Args:
    f: function to be differentiated. If `f` returns a scalar, this scalar will
      be differentiated. If `f` returns a tensor or list of tensors, by default
      a scalar will be computed by adding all their values to produce a single
      scalar. If desired, the tensors can be elementwise multiplied by the
      tensors passed as the `dy` keyword argument to the returned gradient
      function.
    params: list of parameter names of f or list of integers indexing the
      parameters with respect to which we'll differentiate. Passing `None`
      differentiates with respect to all parameters.

  Returns:
    function which, when called, returns the value of f and the gradient
    of f with respect to all of `params`. The function takes an extra optional
    keyword argument "dy". Setting it allows computation of vector jacobian
    products for vectors other than the vector of ones.

  Raises:
    ValueError: if the params are not all strings or all integers.
  c                     s>   | dd}|rtdt | i |\}}|||dfS ):Computes the value and gradient of the decorated function.dyNz@Functions to be differentiated cannot receive keyword arguments.r   )poprq   make_vjp)ry   rz   r   valvjpr   r.   r/   r     s
    z(val_and_grad_function.<locals>.decoratedr.   r   r.   r   r/   r     s    8	r   Tc                    s    fdd}|S )a  Returns a function that computes f and its vjp w.r.t.

  params.

  The term "vjp" here is an abbreviation for vector-jacobian product.

  Args:
    f: the function to be differentiated.
    params: the parameters (numbers or names) to differentiate with respect to.
      A value of None will differentiate with respect to all parameters.
    persistent: Boolean controlling whether the VJP function can be re-used.
      Must be True or False.

  Returns:
    A function, which when called, returns a tuple (value, vjp), where:
    - value is the result of calling f.
    - vjp is a function, which takes a vector as an argument and
      returns the product of that vector with the Jacobian of f.
      Providing no argument to vjp is equivalent to providing a
      vector of ones.

    For example,
    ```python
    def f(x):
      return x * x

    wrapped_fn = tfe.make_vjp(f)
    result, vjp = wrapped_fn(tf.constant(3.0))
    # result is 9.0
    vjp()  # the vjp function returns 6.0

  Raises:
    ValueError: if `f` returns None.
  c               	      s  t |  |rJ dtjdzg  fddt| D } t | }  D ]:}t| | ddrjtd| |  t| |  qN|  du rtd		j
t}d
d |D }t|W t nt 0 dfdd	}|fS )r   z3The gradient function can't take keyword arguments.)
persistentc                    s&   g | ]\}}| v rt |n|qS r.   r   convert_to_tensor)r3   rQ   arg)r   r.   r/   r5   4  s   z/make_vjp.<locals>.decorated.<locals>.<listcomp>rn   FzAGradientTape.gradient is not supported on packed EagerTensorsyet.Nrl   c                 S   s   g | ]}t |qS r.   )r   r   r   r.   r.   r/   r5   F  r6   c                    s4   | d urdd t | D } tjt  | dS )Nc                 S   s   g | ]}t |qS r.   r   r   r.   r.   r/   r5   L  r6   z<make_vjp.<locals>.decorated.<locals>.vjp.<locals>.<listcomp>)output_gradients)r   rv   r   r   )resultr}   r{   r.   r/   r   J  s
    z(make_vjp.<locals>.decorated.<locals>.vjp)N)r   r   rp   r   r   ru   rq   appendwatchrr   rV   r   rv   pack_sequence_asrs   )ry   rz   rQ   flat_resultr   r   r   r   )r   r   r}   r{   r/   r   -  s6    


zmake_vjp.<locals>.decoratedr.   )r   r   r   r   r.   r   r/   r   	  s    $%r   c                 C   s`   t | tjsJ t | jtjr"| S t | jtjs4J t| j}t|jt| j	|j	|j
S d S r$   )r9   r   IndexedSlicesvaluesr   Tensorflatten_nested_indexed_slicesr   gatherindicesdense_shape)r   gr.   r.   r/   r   U  s    
r   c                 C   s   t | dk rdS t | dkr$| d S dd | D } tdd | D rNt| S t| } dd | D } ttjd	d | D dd
tjdd | D dd
| d j	}|S )z1Aggregates gradients containing `IndexedSlices`s.rM   Nr   c                 S   s   g | ]}|d ur|qS r$   r.   r3   r   r.   r.   r/   r5   f  r6   z6aggregate_indexed_slices_gradients.<locals>.<listcomp>c                 s   s   | ]}t |tjV  qd S r$   r9   r   r   r   r.   r.   r/   r   i  r6   z5aggregate_indexed_slices_gradients.<locals>.<genexpr>c                 S   s   g | ]}t |qS r.   )r   r   r.   r.   r/   r5   q  r6   c                 S   s   g | ]
}|j qS r.   )r   r   r.   r.   r/   r5   t  r6   axisc                 S   s   g | ]
}|j qS r.   )r   r   r.   r.   r/   r5   u  r6   )
rO   anyr   add_n_as_indexed_slices_listr   r   r   concatr   )gradsZconcat_gradr.   r.   r/   "aggregate_indexed_slices_gradients`  s    

r   c                 C   s^   | sJ dt | dkr | d S tdd | D r<t| S tdd | D sRJ t| S dS )zAggregate gradients from multiple sources.

  Args:
    gradients: A list of 'Tensor' or 'IndexedSlices' gradients.

  Returns:
    If 'gradients' only has 'Tensor', returns an aggregated 'Tensor'.
    Otherwise returns an aggregated 'IndexedSlices'.
  zNo gradients to aggregaterM   r   c                 s   s   | ]}t |tjV  qd S r$   r   r   r.   r.   r/   r     r6   z#_aggregate_grads.<locals>.<genexpr>c                 s   s    | ]}t |tjtjfV  qd S r$   )r9   r   r   r   r   r   r.   r.   r/   r     s   N)rO   r   r   r   r   )	gradientsr.   r.   r/   _aggregate_grads{  s    

r   c                 C   sZ   t | tjr|  }n t | tjr.| j }ntd|du sFd|v rJdS t	t
j|dS )z,The number of elements in the `grad` tensor.z%`grad` not a Tensor or IndexedSlices.Nr   rM   )r9   r   r   _shape_tupler   r   r   rq   	functoolsreduceoperatormul)r   Zshape_tupler.   r.   r/   _num_elements  s    
r   c                 C   s"   t tj|tjdtj| |dS )Ndtype)r   fillr
   constantr   int32)rA   shaper   r.   r.   r/   
_fast_fill  s    r   c                 C   s   |t jks|t jkrdS t }| s4t| |S |j}t	| rN| 
 }n| }|||f}| |}|du rt |jrd}nd}t|| |}| || |S )z>Helper to return (possibly cached) zero tensors in eager mode.NFr   )r   stringresourcer   executing_eagerlyr   zerosdevice_namer   
is_tf_typerefzeros_cachegetr1   is_boolr   put)r   r   ctxdeviceZ	shape_key	cache_keycachedrA   r.   r.   r/   _zeros  s$    


r   c                 C   s^   t |}|t jkrd S t s,t| |S |jr8d}nd}| dkrRtj	||dS t
|| |S )NTrM   r.   r   )r   r1   r   r   r   r   onesr   r
   r   r   )r   r   r1   rA   r.   r.   r/   _ones  s    

r   )Znum_elements_fnZaggregate_fnZzeros_fnZones_fnZzeros_like_fnZones_like_fnZgraph_shape_fnc                 C   s   t | r| jS | S )z3Unwrap resource variable/ndarray to return tensors.)r   is_resource_variablerm   )r   r.   r.   r/   _handle_or_self  s    
r   c                 c   sx   t | D ]h}t|s"t|r*|V  q
t|tjrVt	|
|}t|E dH  q
td| dt|jdq
dS )z5Extracts tensors and variables from the input object.NzPassed in object z	 of type z0, not tf.Tensor or tf.Variable or ExtensionType.)r   rv   r   IsTensor
IsVariabler9   r   CompositeTensorr   type_spec_from_value_to_components_extract_tensors_and_variablesrq   rG   rV   )tensorobj
componentsr.   r.   r/   r     s    r   GradientTapezautodiff.GradientTapec                   @   s   e Zd ZdZdddZdd Zdd	 Zd
d Zdd Ze	j
dd Zdd Ze	j
dd Zdd Zdd ZdejfddZejddfddZejddfddZdS ) r   a  Record operations for automatic differentiation.

  Operations are recorded if they are executed within this context manager and
  at least one of their inputs is being "watched".

  Trainable variables (created by `tf.Variable` or `tf.compat.v1.get_variable`,
  where `trainable=True` is default in both cases) are automatically watched.
  Tensors can be manually watched by invoking the `watch` method on this context
  manager.

  For example, consider the function `y = x * x`. The gradient at `x = 3.0` can
  be computed as:

  >>> x = tf.constant(3.0)
  >>> with tf.GradientTape() as g:
  ...   g.watch(x)
  ...   y = x * x
  >>> dy_dx = g.gradient(y, x)
  >>> print(dy_dx)
  tf.Tensor(6.0, shape=(), dtype=float32)

  GradientTapes can be nested to compute higher-order derivatives. For example,

  >>> x = tf.constant(5.0)
  >>> with tf.GradientTape() as g:
  ...   g.watch(x)
  ...   with tf.GradientTape() as gg:
  ...     gg.watch(x)
  ...     y = x * x
  ...   dy_dx = gg.gradient(y, x)  # dy_dx = 2 * x
  >>> d2y_dx2 = g.gradient(dy_dx, x)  # d2y_dx2 = 2
  >>> print(dy_dx)
  tf.Tensor(10.0, shape=(), dtype=float32)
  >>> print(d2y_dx2)
  tf.Tensor(2.0, shape=(), dtype=float32)

  By default, the resources held by a GradientTape are released as soon as
  GradientTape.gradient() method is called. To compute multiple gradients over
  the same computation, create a persistent gradient tape. This allows multiple
  calls to the gradient() method as resources are released when the tape object
  is garbage collected. For example:

  >>> x = tf.constant(3.0)
  >>> with tf.GradientTape(persistent=True) as g:
  ...   g.watch(x)
  ...   y = x * x
  ...   z = y * y
  >>> dz_dx = g.gradient(z, x)  # (4*x^3 at x = 3)
  >>> print(dz_dx)
  tf.Tensor(108.0, shape=(), dtype=float32)
  >>> dy_dx = g.gradient(y, x)
  >>> print(dy_dx)
  tf.Tensor(6.0, shape=(), dtype=float32)

  By default GradientTape will automatically watch any trainable variables that
  are accessed inside the context. If you want fine grained control over which
  variables are watched you can disable automatic tracking by passing
  `watch_accessed_variables=False` to the tape constructor:

  >>> x = tf.Variable(2.0)
  >>> w = tf.Variable(5.0)
  >>> with tf.GradientTape(
  ...     watch_accessed_variables=False, persistent=True) as tape:
  ...   tape.watch(x)
  ...   y = x ** 2  # Gradients will be available for `x`.
  ...   z = w ** 3  # No gradients will be available as `w` isn't being watched.
  >>> dy_dx = tape.gradient(y, x)
  >>> print(dy_dx)
  tf.Tensor(4.0, shape=(), dtype=float32)
  >>> # No gradients will be available as `w` isn't being watched.
  >>> dz_dw = tape.gradient(z, w)
  >>> print(dz_dw)
  None

  Note that when using models you should ensure that your variables exist when
  using `watch_accessed_variables=False`. Otherwise it's quite easy to make your
  first iteration not have any gradients:

  ```python
  a = tf.keras.layers.Dense(32)
  b = tf.keras.layers.Dense(32)

  with tf.GradientTape(watch_accessed_variables=False) as tape:
    tape.watch(a.variables)  # Since `a.build` has not been called at this point
                             # `a.variables` will return an empty list and the
                             # tape will not be watching anything.
    result = b(a(inputs))
    tape.gradient(result, a.variables)  # The result of this computation will be
                                        # a list of `None`s since a's variables
                                        # are not being watched.
  ```

  Note that only tensors with real or complex dtypes are differentiable.
  FTc                 C   s"   d| _ || _|| _d| _d| _dS )a  Creates a new GradientTape.

    Args:
      persistent: Boolean controlling whether a persistent gradient tape
        is created. False by default, which means at most one call can
        be made to the gradient() method on this object.
      watch_accessed_variables: Boolean controlling whether the tape will
        automatically `watch` any (trainable) variables accessed while the tape
        is active. Defaults to True meaning gradients can be requested from any
        result computed in the tape derived from reading a trainable `Variable`.
        If False users must explicitly `watch` any `Variable`s they want to
        request gradients from.
    Nr.   F)_tape_persistent_watch_accessed_variables_watched_variables
_recording)rI   r   watch_accessed_variablesr.   r.   r/   rK   S  s
    zGradientTape.__init__c                 C   s   |    | S )zCEnters a context inside which operations are recorded on this tape.)
_push_taperT   r.   r.   r/   	__enter__g  s    zGradientTape.__enter__c                 C   s   | j r|   dS )z>Exits the recording context, no further operations are traced.N)r   	_pop_tape)rI   rJ   rA   	tracebackr.   r.   r/   __exit__l  s    zGradientTape.__exit__c                 C   sD   | j rtd| jdu r.tj| j| jd| _nt| j d| _ dS )z&Pushes a new tape onto the tape stack.zWTape is still recording, This can happen if you try to re-enter an already-active tape.N)r   r   T)r   rq   r   r   rp   r   r   	push_taperT   r.   r.   r/   r   q  s    

zGradientTape._push_tapec                 C   s$   | j stdt| j d| _ d S )NzTape is not recording.F)r   rq   r   rs   r   rT   r.   r.   r/   r   ~  s    zGradientTape._pop_tapec                 c   s8   | j s.z|   dV  W |   q4|   0 ndV  dS )z$Ensures that this tape is recording.N)r   r   r   rT   r.   r.   r/   _ensure_recording  s    zGradientTape._ensure_recordingc                 C   sX   t |D ]J}t|s*ttjdd|j t|drDt	| j
| qt| j
| qdS )zEnsures that `tensor` is being traced by this tape.

    Args:
      tensor: a Tensor/Variable or list of Tensors/Variables.

    Raises:
      ValueError: if it encounters something that is not a tensor.
    zJThe dtype of the watched tensor must be floating (e.g. tf.float32), got %r   rm   N)r   r   IsTrainablelogginglog_first_nWARNr   hasattrr   watch_variabler   r   )rI   r   r   r.   r.   r/   r     s    	

zGradientTape.watchc                 c   s<   | j du rtd|   zdV  W |   n
|   0 dS )a!  Temporarily stops recording operations on this tape.

    Operations executed while this context manager is active will not be
    recorded on the tape. This is useful for reducing the memory used by tracing
    all computations.

    For example:

    >>> x = tf.constant(4.0)
    >>> with tf.GradientTape() as tape:
    ...   with tape.stop_recording():
    ...     y = x ** 2
    >>> dy_dx = tape.gradient(y, x)
    >>> print(dy_dx)
    None

    Yields:
      None
    Raises:
      RuntimeError: if the tape is not currently recording.
    Nz7Trying to stop recording a tape which is not recording.)r   RuntimeErrorr   r   rT   r.   r.   r/   stop_recording  s    
zGradientTape.stop_recordingc                 C   s   |    d| _|   dS )a  Clears all information stored in this tape.

    Equivalent to exiting and reentering the tape context manager with a new
    tape. For example, the two following code blocks are equivalent:

    ```
    with tf.GradientTape() as t:
      loss = loss_fn()
    with tf.GradientTape() as t:
      loss += other_loss_fn()
    t.gradient(loss, ...)  # Only differentiates other_loss_fn, not loss_fn


    # The following is equivalent to the above
    with tf.GradientTape() as t:
      loss = loss_fn()
      t.reset()
      loss += other_loss_fn()
    t.gradient(loss, ...)  # Only differentiates other_loss_fn, not loss_fn
    ```

    This is useful if you don't want to exit the context manager for the tape,
    or can't because the desired reset point is inside a control flow construct:

    ```
    with tf.GradientTape() as t:
      loss = ...
      if loss > k:
        t.reset()
    ```
    N)r   r   r   rT   r.   r.   r/   reset  s     zGradientTape.resetc                 C   s   | j dur| j  | _| jS )z@Returns variables watched by this tape in order of construction.N)r   rt   r   rT   r.   r.   r/   rt     s    
zGradientTape.watched_variablesNc                 C   s|  | j du rtd| jr8| js(|   nttjdd |du rHtdg }t	
|D ].}t|svttjd|j |t| qVt|}t	
|}g }|D ]B}t|sttjd|j t|dd	rtd
|t| qt|}|dur"t	
t|}t|}dd |D }tj| j |||||d}	| jsT| j  | _d| _ t	t|}t||	}	t	||	}
|
S )a  Computes the gradient using operations recorded in context of this tape.

    Note: Unless you set `persistent=True` a GradientTape can only be used to
    compute one set of gradients (or jacobians).

    In addition to Tensors, gradient also supports RaggedTensors. For example,

    >>> x = tf.ragged.constant([[1.0, 2.0], [3.0]])
    >>> with tf.GradientTape() as g:
    ...   g.watch(x)
    ...   y = x * x
    >>> g.gradient(y, x)
    <tf.RaggedTensor [[2.0, 4.0], [6.0]]>

    Args:
      target: a list or nested structure of Tensors or Variables or
        CompositeTensors to be differentiated.
      sources: a list or nested structure of Tensors or Variables or
        CompositeTensors. `target` will be differentiated against elements in
        `sources`.
      output_gradients: a list of gradients, one for each differentiable
        element of target. Defaults to None.
      unconnected_gradients: a value which can either hold 'none' or 'zero' and
        alters the value which will be returned if the target and sources are
        unconnected. The possible values and effects are detailed in
        'UnconnectedGradients' and it defaults to 'none'.

    Returns:
      a list or nested structure of Tensors (or IndexedSlices, or None, or
      CompositeTensor), one for each element in `sources`. Returned structure
      is the same as the structure of `sources`.

    Raises:
      RuntimeError: If called on a used, non-persistent tape.
      RuntimeError: If called inside the context of the tape.
      TypeError: If the target is a None object.
      ValueError: If the target is a variable or if unconnected gradients is
       called with an unknown value.
    N]A non-persistent GradientTape can only be used to compute one set of gradients (or jacobians)ay  Calling GradientTape.gradient on a persistent tape inside its context is significantly less efficient than calling it outside the context (it causes the gradient ops to be recorded on the tape, leading to increased CPU and memory usage). Only call GradientTape.gradient inside the context if you actually want to trace the gradient in order to compute higher order derivatives.rM   zArgument `target` should be a list or nested structure of Tensors, Variables or CompositeTensors to be differentiated, but received None.zlThe dtype of the target tensor must be floating (e.g. tf.float32) when calling GradientTape.gradient, got %rzlThe dtype of the source tensor must be floating (e.g. tf.float32) when calling GradientTape.gradient, got %rrn   Fro   c                 S   s"   g | ]}|d u rd nt |qS r$   r   r   r.   r.   r/   r5   V  s   z)GradientTape.gradient.<locals>.<listcomp>)r   Zsources_rawunconnected_gradients)r   r  r   r   r   r  r  r  r   r   rv   r   r  vlogr   r   r   r	   get_flat_tensors_for_gradientsru   rq   r   convert_variables_to_tensorsr   rt   r   r@   "replace_flat_tensors_for_gradientsr   )rI   targetr}   r   r  Zflat_targetsr   Zflat_sources_rawflat_sources	flat_gradr   r.   r.   r/   gradient  s    ,





zGradientTape.gradientc              
      s  j du rtdt| j}t}  tdgW d   n1 sX0    Y   fdd}ztjd }	W n  t	y   td }	Y n0 |rzt
j||	|d}
W nH ty
 } z.tttt|d t d	  W Y d}~n
d}~0 0 n8t r(js(td
t
j|jgt  |	|d}
t|
D ]h\}}|durtj|t|dd gdd}t||}t r|| | j ||
|< qNt||
S )aJ	  Computes the jacobian using operations recorded in context of this tape.

    Note: Unless you set `persistent=True` a GradientTape can only be used to
    compute one set of gradients (or jacobians).

    Note: By default the jacobian implementation uses parallel for (pfor), which
    creates a tf.function under the hood for each jacobian call. For better
    performance, and to avoid recompilation and vectorization rewrites on each
    call, enclose GradientTape code in @tf.function.

    See[wikipedia
    article](http://en.wikipedia.org/wiki/jacobian_matrix_and_determinant)
    for the definition of a Jacobian.

    Example usage:

    ```python
    with tf.GradientTape() as g:
      x  = tf.constant([1.0, 2.0])
      g.watch(x)
      y = x * x
    jacobian = g.jacobian(y, x)
    # jacobian value is [[2., 0.], [0., 4.]]
    ```

    Args:
      target: Tensor to be differentiated.
      sources: a list or nested structure of Tensors or Variables. `target`
        will be differentiated against elements in `sources`.
      unconnected_gradients: a value which can either hold 'none' or 'zero' and
        alters the value which will be returned if the target and sources are
        unconnected. The possible values and effects are detailed in
        'UnconnectedGradients' and it defaults to 'none'.
      parallel_iterations: A knob to control how many iterations are dispatched
        in parallel. This knob can be used to control the total memory usage.
      experimental_use_pfor: If true, vectorizes the jacobian computation. Else
        falls back to a sequential while_loop. Vectorization can sometimes fail
        or lead to excessive memory usage. This option can be used to disable
        vectorization in such cases.

    Returns:
      A list or nested structure of Tensors (or None), one for each element in
      `sources`. Returned structure is the same as the structure of `sources`.
      Note if any gradient is sparse (IndexedSlices), jacobian function
      currently makes it dense and returns a Tensor instead. This may change in
      the future.


    Raises:
      RuntimeError: If called on a used, non-persistent tape.
      RuntimeError: If called on a non-persistent tape with eager execution
        enabled and without enabling experimental_use_pfor.
      ValueError: If vectorization of jacobian computation fails.
    Nr  c                    sD      t| }W d    n1 s*0    Y  j| dS )Nr  )r   r   r   r  rQ   yr  rI   r  r  r.   r/   loop_fn  s
    
*z&GradientTape.jacobian.<locals>.loop_fnr   parallel_iterationsz
Encountered an exception while vectorizing the jacobian computation. Vectorization can be disabled by setting experimental_use_pfor to False.rL   zGradientTape must be created with persistent=True to compute the jacobian with eager execution enabled and with  experimental_use_pfor set to False.rM   r   )r   r  r   rv   r   r   r   reshaper=   r   r"   pforrq   r   reraiser:   sysexc_infor   r   r   for_loopr   rO   r   r   	set_shapeconcatenater   )rI   r  r}   r  r  experimental_use_pforZtarget_static_shapetarget_shaper  Ztarget_sizeoutputerrrQ   out	new_shaper.   r  r/   jacobianl  sV    <



,




zGradientTape.jacobianc              
      sL  j du rtdj}|jdu r.td}n
|jd }|dr^jdr^|jd srt	djjf |
 rt|d }| | }	n t}|d }t| }	t}
 Z tt||
d g  t||	gW d   n1 s0    Y  W d   n1 s(0    Y  d fdd}|rztj||	 d	}W nH t	y } z.tt	t	t|d
 t d  W Y d}~n
d}~0 0 n.t r̈jstdtj|j |	 d	}tj!||
dd gdd}|du rt"|j }|S t||	|dg}t#|g d}t||}|S dS )aK  Computes and stacks per-example jacobians.

    See [wikipedia article](http://en.wikipedia.org/wiki/jacobian_matrix_and_determinant)
    for the definition of a Jacobian. This function is essentially an efficient
    implementation of the following:

    `tf.stack([self.jacobian(y[i], x[i]) for i in range(x.shape[0])])`.

    Note that compared to `GradientTape.jacobian` which computes gradient of
    each output value w.r.t each input value, this function is useful when
    `target[i,...]` is independent of `source[j,...]` for `j != i`. This
    assumption allows more efficient computation as compared to
    `GradientTape.jacobian`. The output, as well as intermediate activations,
    are lower dimensional and avoid a bunch of redundant zeros which would
    result in the jacobian computation given the independence assumption.

    Note: Unless you set `persistent=True` a GradientTape can only be used to
    compute one set of gradients (or jacobians).

    Note: By default the batch_jacobian implementation uses parallel for (pfor),
    which creates a tf.function under the hood for each batch_jacobian call.
    For better performance, and to avoid recompilation and vectorization
    rewrites on each call, enclose GradientTape code in @tf.function.


    Example usage:

    ```python
    with tf.GradientTape() as g:
      x = tf.constant([[1., 2.], [3., 4.]], dtype=tf.float32)
      g.watch(x)
      y = x * x
    batch_jacobian = g.batch_jacobian(y, x)
    # batch_jacobian is [[[2,  0], [0,  4]], [[6,  0], [0,  8]]]
    ```

    Args:
      target: A tensor with rank 2 or higher and with shape [b, y1, ..., y_n].
        `target[i,...]` should only depend on `source[i,...]`.
      source: A tensor with rank 2 or higher and with shape [b, x1, ..., x_m].
      unconnected_gradients: a value which can either hold 'none' or 'zero' and
        alters the value which will be returned if the target and sources are
        unconnected. The possible values and effects are detailed in
        'UnconnectedGradients' and it defaults to 'none'.
      parallel_iterations: A knob to control how many iterations are dispatched
        in parallel. This knob can be used to control the total memory usage.
      experimental_use_pfor: If true, uses pfor for computing the Jacobian. Else
        uses a tf.while_loop.

    Returns:
      A tensor `t` with shape [b, y_1, ..., y_n, x1, ..., x_m] where `t[i, ...]`
      is the jacobian of `target[i, ...]` w.r.t. `source[i, ...]`, i.e. stacked
      per-example jacobians.

    Raises:
      RuntimeError: If called on a used, non-persistent tape.
      RuntimeError: If called on a non-persistent tape with eager execution
        enabled and without enabling experimental_use_pfor.
      ValueError: If vectorization of jacobian computation fails or if first
        dimension of `target` and `source` do not match.
    Nz\A non-persistent GradientTape can only be used tocompute one set of gradients (or jacobians)r   rL   zINeed first dimension of target shape (%s) and source shape (%s) to match.Fc                    sp   r$j s$ d urtdntdd   tj| dd}W d    n1 sV0    Y  j|dS )NziGradientTape must be created with persistent=True to compute the batch_jacobian with parallel_iterations.zPGradientTape must be created with persistent=True to compute the batch_jacobian.TrM   r   r  )r   r  r   r   r   r  r  r  run_oncerI   sourcer  r  r.   r/   r  C  s    

.z,GradientTape.batch_jacobian.<locals>.loop_fnr  z
Encountered an exception while vectorizing the batch_jacobian computation. Vectorization can be disabled by setting experimental_use_pfor to False.zGradientTape must be created with persistent=True to compute the batch_jacobian with eager execution enabled and  with experimental_use_pfor set to False.rM   r   r  )rM   r   rL   )$r   r  r   rankr   	Dimensiondimswith_rank_at_leastis_compatible_withrq   is_fully_definedr=   num_elementsr   sizer   r   control_dependenciesr   assert_equalr  r"   r  r   r  r:   r   r!  r   r   r   r"  r   r   r   	transpose)rI   r  r.  r  r  r%  r&  dim
batch_sizeZtarget_row_sizeZsource_shaper  r'  r(  r*  r.   r,  r/   batch_jacobian  sx    C








P



zGradientTape.batch_jacobian)FT)rV   rW   rX   rY   rK   r   r   r   r   r   contextmanagerr   r   r	  r
  rt   r   NONEr  r+  r<  r.   r.   r.   r/   r     s0   _


$	
}
w)N)N)NT)SrY   r   r   r   r   tensorflow.pythonr   tensorflow.python.eagerr   r   r   r   r   tensorflow.python.frameworkr   r	   r
   r   r   r   r   r   r   tensorflow.python.opsr   r   r   r   r   r   r   r   +tensorflow.python.ops.unconnected_gradientsr   tensorflow.python.platformr   r  tensorflow.python.utilr   r   r   r   r   "tensorflow.python.util.lazy_loaderr     tensorflow.python.util.tf_exportr!   globalsr"   r#   r%   r0   rB   objectrC   rd   TFE_Py_RegisterGradientFunctionrf   rj   must_record_gradientr   r   r   r   r   r   r   r   r   r   r   r   r   r   ZVSpace
zeros_like	ones_liker   Z_default_vspaceTFE_Py_RegisterVSpacer   r   r   r.   r.   r.   r/   <module>   s   #


O1
I 
D
L
