o
    Ïe[ ã                   @   sÔ  d 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„ Z&dd„ Z'G dd„ de$j(ƒZ(G dd „ d e(ƒZ)G d!d"„ d"e(ej*e$j+ƒZ+dJd$d%„Z,e -e+e,¡ G d&d'„ d'ej.ƒZ/G d(d)„ d)e)e$j0ƒZ0G d*d+„ d+e1ƒZ2G d,d-„ d-e%j3ƒZ4G d.d/„ d/e)ej5e"j6ƒZ7G d0d1„ d1e j8ƒZ9G d2d3„ d3e j8ƒZ:G d4d5„ d5e7e0ƒZ;G d6d7„ d7e j8ƒZ<G d8d9„ d9e7ƒZ=			#dJd:d;„Z>e -e7e>¡ dJd<d=„Z?e -e;e?¡ dJd>d?„Z@e -e0e@¡ dJd@dA„ZAe -e=eA¡ G dBdC„ dCe1ƒZBG dDdE„ dEeBƒZCG dFdG„ dGeBƒZDG dHdI„ dIƒZEdS )Kz0Various classes representing distributed values.é    N)Údevice_util)Údistribute_lib)Údistribution_strategy_context)Úpacked_distributed_variable)Úreduce_util)Úvalues_util)Úcontext)Úcomposite_tensor)Úops)Útensor_util)Ú	type_spec)Ú	array_ops)Úcontrol_flow_ops)Úmath_ops)Úresource_variable_ops)Úvariable_scope)Ú	variables)Úbase)Úsaveable_object)Úcore)Ú
distribute)Útracec                    s®   ˆj tjjkrˆ ˆ ¡ |fi |¤ŽS t ¡ j ¡ sEˆj tjj	kr-ˆj
js-t |¡r-tdƒ‚t|ˆj ˆƒ}t ¡  t ¡ jˆˆ |f|dd�S ‡ ‡fdd„}t ¡ j||f|d�S )zCUpdates variables with ON_WRITE synchronization in replica context.ú³Cannot update non-float variables with tf.VariableAggregation.MEAN aggregation in replica context. Either change the variable dtype to float or update it in cross-replica context.T©ÚargsÚkwargsÚgroupc                    s\   ˆj tjjkrˆjjst|tƒrtdƒ‚| ˆj	ksJ ‚t
 | |ˆj ˆ¡}ˆjˆ |fi |¤ŽS )zCAggregate values and update all variables in cross replica context.r   )ÚaggregationÚvsÚVariableAggregationÚMEANÚdtypeÚis_floatingÚ
isinstanceÚ
PerReplicaÚ
ValueErrorÚdistribute_strategyr   Zapply_aggregationÚ_update_cross_replica)ÚstrategyÚvaluer   Úv©Ú	update_fnÚvar© úSD:\Projects\ConvertPro\env\Lib\site-packages\tensorflow/python/distribute/values.pyÚmerge_fnJ   s   	ÿÿÿz*_on_write_update_replica.<locals>.merge_fn)r   r   )r   r   r   ÚNONEÚ_get_on_device_or_primaryÚ
ds_contextÚget_strategyÚextendedZ_use_merge_callr    r!   r"   r   Ú
is_tf_typer%   Ú!apply_aggregation_replica_contextr   Úmark_as_unsaveableÚget_replica_contextÚ_updateÚ
merge_call)r-   r,   r)   r   Úaggregated_valuer0   r.   r+   r/   Ú_on_write_update_replica,   s4   ÿÿÿÿû	ÿr=   c                    sn   t | tƒr	tdƒ‚t | ¡s| S |tjjkr&‡ fdd„}t 	¡ j
|| fd�S tj |¡}t ¡ j || ¡}|S )zBAggregate `value` to `destinations` as specified by `aggregation`.zDCannot use DistributedValues to update variables in replica context.c                    s   | j j|  |¡d ˆ d�S )Nr   ©Údestinations)r5   Zbroadcast_toZexperimental_local_results)r(   r)   r>   r.   r/   r0   n   s   þz3apply_aggregation_replica_context.<locals>.merge_fn)r   )r#   ÚDistributedValuesÚ	TypeErrorr   r6   r   r   ÚONLY_FIRST_REPLICAr3   r9   r;   r   ÚReduceOpÚfrom_variable_aggregationr4   r5   Ú_replica_ctx_all_reduce)r)   r   r?   r0   Z	reduce_opr<   r.   r>   r/   r7   c   s   
ÿ

ÿr7   c                   @   sX   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zed
d„ ƒZ	edd„ ƒZ
dd„ Zdd„ ZdS )r@   z/Base class for representing distributed values.c                 C   s   t |ƒ| _dS )z+Should only be called by subclass __init__.N©ÚtupleÚ_values)ÚselfÚvaluesr.   r.   r/   Ú__init__   ó   zDistributedValues.__init__c                 C   s"   t  ¡ }|du r|  ¡ S | j| S ©z@Returns the value for the current device or raises a ValueError.N)r   Úget_current_replica_id_as_intÚ_get_cross_replicarH   ©rI   Ú
replica_idr.   r.   r/   Ú_getƒ   s   
zDistributedValues._getc                 C   ó   t dƒ‚)NzoDistributedValues._get_cross_replica should be implemented by sub-classes which support cross-replica accesses.©ÚNotImplementedError©rI   r.   r.   r/   rO   ‹   ó   ÿz$DistributedValues._get_cross_replicac                 C   sR   t  ¡ }|du r$t t ¡ ¡}| jD ]}t |j¡|kr |  S q| jS | j| S )úGReturns value in same replica or device if possible, else the _primary.N)r   rN   r   ÚcanonicalizeÚcurrentrH   ÚdeviceÚ_primary)rI   rQ   Úcurrent_devicer)   r.   r.   r/   r2   �   s   
ÿ
z+DistributedValues._get_on_device_or_primaryc                 C   s
   | j d S )z#Returns a representative component.r   ©rH   rV   r.   r.   r/   r\   �   s   
zDistributedValues._primaryc                 C   s   t dd„ | jD ƒƒS )Nc                 s   ó   � | ]}|j V  qd S ©N)r[   ©Ú.0r*   r.   r.   r/   Ú	<genexpr>¤   ó   € z-DistributedValues._devices.<locals>.<genexpr>rF   rV   r.   r.   r/   Ú_devices¢   s   zDistributedValues._devicesc                 C   ó*   d  dd„ t| jƒD ƒ¡}d| jj|f S )Nú,
c                 s   ó    � | ]\}}d ||f V  qdS )z  %d: %sNr.   ©rb   Úir*   r.   r.   r/   rc   §   ó   € 
ÿz,DistributedValues.__str__.<locals>.<genexpr>ú	%s:{
%s
}©ÚjoinÚ	enumeraterH   Ú	__class__Ú__name__)rI   Z	debug_strr.   r.   r/   Ú__str__¦   ó   
ÿzDistributedValues.__str__c                 C   rf   )Nrg   c                 s   rh   )z  %d: %rNr.   ri   r.   r.   r/   rc   ¬   rk   z-DistributedValues.__repr__.<locals>.<genexpr>rl   rm   )rI   Z
debug_reprr.   r.   r/   Ú__repr__«   rs   zDistributedValues.__repr__N)rq   Ú
__module__Ú__qualname__Ú__doc__rK   rR   rO   r2   Úpropertyr\   re   rr   rt   r.   r.   r.   r/   r@   |   s    

r@   c                       s6  e Zd ZdZ‡ fdd„Zedd„ ƒZdd„ Zdd	„ Zd
d„ Z	dd„ Z
dd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zd d!„ Zd"d#„ Zd$d%„ Zd&d'„ Zd(d)„ Zd*d+„ Zd,d-„ Zd.d/„ Zd0d1„ Zd2d3„ Zd4d5„ ZdId7d8„Zd9d:„ Z d;d<„ Z!d=d>„ Z"d?d@„ Z#dAdB„ Z$dCdD„ Z%dEdF„ Z&dGdH„ Z'‡  Z(S )JÚDistributedDelegatezAA map from device to values; acts as the same type as the values.c                    s>   |  d¡s	|dv rtt| ƒ |¡S |dkrtƒ ‚t|  ¡ |ƒS )NZ_self_)Z_use_resource_variablesZ_attribute_sentinelÚ_distributed_containerrH   )Ú
startswithÚsuperry   Ú__getattr__ÚAttributeErrorÚgetattrrR   ©rI   Úname©rp   r.   r/   r}   ½   s
   
zDistributedDelegate.__getattr__c                 C   ó   | j S ©zReturns the per replica values.r^   rV   r.   r.   r/   rJ   ×   ó   zDistributedDelegate.valuesc                 C   ó   |   ¡ S )a  Returns the value for operations for the current device.

    Some implementations, e.g. `TPUMirroredVariable`, are not able to return the
    value type within a replica context. They can, however, return a value that
    can be used by the operations below.
    )rR   rV   r.   r.   r/   Ú_get_as_operandÜ   s   z#DistributedDelegate._get_as_operandc                 C   s   |   ¡ | S r`   ©r‡   ©rI   Úor.   r.   r/   Ú__add__æ   ó   zDistributedDelegate.__add__c                 C   s   ||   ¡  S r`   rˆ   r‰   r.   r.   r/   Ú__radd__é   rŒ   zDistributedDelegate.__radd__c                 C   s   |   ¡ | S r`   rˆ   r‰   r.   r.   r/   Ú__sub__ì   rŒ   zDistributedDelegate.__sub__c                 C   s   ||   ¡  S r`   rˆ   r‰   r.   r.   r/   Ú__rsub__ï   rŒ   zDistributedDelegate.__rsub__c                 C   s   |   ¡ | S r`   rˆ   r‰   r.   r.   r/   Ú__mul__ò   rŒ   zDistributedDelegate.__mul__c                 C   s   ||   ¡  S r`   rˆ   r‰   r.   r.   r/   Ú__rmul__õ   rŒ   zDistributedDelegate.__rmul__c                 C   s   |   ¡ | S r`   rˆ   r‰   r.   r.   r/   Ú__truediv__ø   rŒ   zDistributedDelegate.__truediv__c                 C   s   ||   ¡  S r`   rˆ   r‰   r.   r.   r/   Ú__rtruediv__û   rŒ   z DistributedDelegate.__rtruediv__c                 C   s   |   ¡ | S r`   rˆ   r‰   r.   r.   r/   Ú__floordiv__þ   rŒ   z DistributedDelegate.__floordiv__c                 C   s   ||   ¡  S r`   rˆ   r‰   r.   r.   r/   Ú__rfloordiv__  rŒ   z!DistributedDelegate.__rfloordiv__c                 C   s   |   ¡ | S r`   rˆ   r‰   r.   r.   r/   Ú__mod__  rŒ   zDistributedDelegate.__mod__c                 C   s   ||   ¡  S r`   rˆ   r‰   r.   r.   r/   Ú__rmod__  rŒ   zDistributedDelegate.__rmod__c                 C   s   |   ¡ |k S r`   rˆ   r‰   r.   r.   r/   Ú__lt__
  rŒ   zDistributedDelegate.__lt__c                 C   s   |   ¡ |kS r`   rˆ   r‰   r.   r.   r/   Ú__le__  rŒ   zDistributedDelegate.__le__c                 C   s   |   ¡ |kS r`   rˆ   r‰   r.   r.   r/   Ú__gt__  rŒ   zDistributedDelegate.__gt__c                 C   s   |   ¡ |kS r`   rˆ   r‰   r.   r.   r/   Ú__ge__  rŒ   zDistributedDelegate.__ge__c                 C   s   |   ¡ |@ S r`   rˆ   r‰   r.   r.   r/   Ú__and__  rŒ   zDistributedDelegate.__and__c                 C   s   ||   ¡ @ S r`   rˆ   r‰   r.   r.   r/   Ú__rand__  rŒ   zDistributedDelegate.__rand__c                 C   s   |   ¡ |B S r`   rˆ   r‰   r.   r.   r/   Ú__or__  rŒ   zDistributedDelegate.__or__c                 C   s   ||   ¡ B S r`   rˆ   r‰   r.   r.   r/   Ú__ror__  rŒ   zDistributedDelegate.__ror__c                 C   s   |   ¡ |A S r`   rˆ   r‰   r.   r.   r/   Ú__xor__"  rŒ   zDistributedDelegate.__xor__c                 C   s   ||   ¡ A S r`   rˆ   r‰   r.   r.   r/   Ú__rxor__%  rŒ   zDistributedDelegate.__rxor__c                 C   s   |   ¡ | S r`   rˆ   r‰   r.   r.   r/   Ú__getitem__(  rŒ   zDistributedDelegate.__getitem__Nc                 C   s   t |  ¡ ||ƒS r`   ©Úpowr‡   )rI   rŠ   Zmodulor.   r.   r/   Ú__pow__+  ó   zDistributedDelegate.__pow__c                 C   s   t ||  ¡ ƒS r`   r£   r‰   r.   r.   r/   Ú__rpow__.  ó   zDistributedDelegate.__rpow__c                 C   s
   |   ¡  S r`   rˆ   rV   r.   r.   r/   Ú
__invert__1  ó   
zDistributedDelegate.__invert__c                 C   s
   |   ¡  S r`   rˆ   rV   r.   r.   r/   Ú__neg__4  rª   zDistributedDelegate.__neg__c                 C   s   t |  ¡ ƒS r`   )Úabsr‡   rV   r.   r.   r/   Ú__abs__7  rŒ   zDistributedDelegate.__abs__c                 C   ó(   z|   ¡  |¡W S  ty   t Y S w r`   )r‡   Ú__div__r~   ÚNotImplementedr‰   r.   r.   r/   r¯   :  ó
   þzDistributedDelegate.__div__c                 C   r®   r`   )r‡   Ú__rdiv__r~   r°   r‰   r.   r.   r/   r²   A  r±   zDistributedDelegate.__rdiv__c                 C   r®   r`   )r‡   Ú
__matmul__r~   r°   r‰   r.   r.   r/   r³   H  r±   zDistributedDelegate.__matmul__c                 C   r®   r`   )r‡   Ú__rmatmul__r~   r°   r‰   r.   r.   r/   r´   O  r±   zDistributedDelegate.__rmatmul__r`   ))rq   ru   rv   rw   r}   rx   rJ   r‡   r‹   r�   rŽ   r�   r�   r‘   r’   r“   r”   r•   r–   r—   r˜   r™   rš   r›   rœ   r�   rž   rŸ   r    r¡   r¢   r¥   r§   r©   r«   r­   r¯   r²   r³   r´   Ú__classcell__r.   r.   r‚   r/   ry   º   sL    


ry   c                   @   s(   e Zd ZdZedd„ ƒZedd„ ƒZdS )r$   z2Holds a map from replica to unsynchronized values.c                 C   s   t dd„ | jD ƒŽ S )Nc                 s   s   � | ]}t  |¡V  qd S r`   )r   Ztype_spec_from_valuera   r.   r.   r/   rc   `  s   € z(PerReplica._type_spec.<locals>.<genexpr>)ÚPerReplicaSpecrH   rV   r.   r.   r/   Ú
_type_spec]  s   ÿzPerReplica._type_specc                 C   rƒ   r„   r^   rV   r.   r.   r/   rJ   b  r…   zPerReplica.valuesN)rq   ru   rv   rw   rx   r·   rJ   r.   r.   r.   r/   r$   Y  s    
r$   Fc                 C   sb   ~|dur|  | j¡std |j| jj¡ƒ‚|rtdƒ‚t ¡ s$t ¡ s(tdƒ‚t	 
¡ }| j| S )z&Converts a `PerReplica` to a `Tensor`.NzMIncompatible type conversion requested to type {!r} for variable of type {!r}z5PerReplica doesn't support being used as a reference.z¼It looks like you are using a PerReplica object while not inside a replica context, which is not supported. Try running your op or function inside a replica context by using `strategy.run`)Zis_compatible_withr!   r%   Úformatr�   rU   r3   Úin_cross_replica_contextZhas_strategyr   rN   rJ   )r-   r!   r�   Úas_refrQ   r.   r.   r/   Ú_per_replica_to_tensorh  s   þÿ
r»   c                   @   sN   e Zd ZdZdgZedd„ ƒZdd„ Zdd„ Zed	d
„ ƒZ	dd„ Z
dd„ ZdS )r¶   z&Type specification for a `PerReplica`.Ú_value_specsc                 C   s   t S r`   ©r$   rV   r.   r.   r/   Ú<lambda>…  s    zPerReplicaSpec.<lambda>c                 G   s   t |ƒ| _d S r`   )rG   r¼   )rI   Zvalue_specsr.   r.   r/   rK   ‡  r¨   zPerReplicaSpec.__init__c                 C   rƒ   r`   ©r¼   rV   r.   r.   r/   Ú
_serializeŠ  ó   zPerReplicaSpec._serializec                 C   rƒ   r`   r¿   rV   r.   r.   r/   Ú_component_specs�  ó   zPerReplicaSpec._component_specsc                 C   s(   t  ¡ }|d ur|jdkrtdƒ‚|jS )Né   zJFlattening a PerReplica to components is not supported in replica context.)r3   r9   Znum_replicas_in_syncr%   rH   )rI   r)   Úreplica_contextr.   r.   r/   Ú_to_components‘  s   ÿzPerReplicaSpec._to_componentsc                 C   s   t |ƒS r`   r½   )rI   Ztensor_listr.   r.   r/   Ú_from_components™  ó   zPerReplicaSpec._from_componentsN)rq   ru   rv   rw   Ú	__slots__rx   Z
value_typerK   rÀ   rÂ   rÆ   rÇ   r.   r.   r.   r/   r¶   €  s    
r¶   c                   @   s    e Zd ZdZdd„ Zdd„ ZdS )ÚMirroredz:Holds a map from replica to values which are kept in sync.c                 C   r†   r`   ©r2   rV   r.   r.   r/   rO   £  rÈ   zMirrored._get_cross_replicac                 C   s*   |   ¡ }t|dd ƒ}|rt|ƒr|ƒ S |S )NÚ_as_graph_element)rR   r   Úcallable)rI   ÚobjZconv_fnr.   r.   r/   rÌ   ¦  s
   zMirrored._as_graph_elementN)rq   ru   rv   rw   rO   rÌ   r.   r.   r.   r/   rÊ      s    rÊ   c                   @   s(   e Zd ZdZdd„ Zdd„ Zdd„ ZdS )	ÚDistributedVarOpz'A class that looks like `tf.Operation`.c                 C   s   || _ || _|| _|| _d S r`   )r�   ÚgraphÚ	tracebackÚtype)rI   r�   rÐ   rÑ   Útypr.   r.   r/   rK   ±  s   
zDistributedVarOp.__init__c                 C   s@   t || jƒst‚| j|jko| j|jko| j|jko| j|jkS r`   )r#   rp   rU   r�   rÐ   rÑ   rÒ   r‰   r.   r.   r/   Ú__eq__·  s   
ÿ
ÿzDistributedVarOp.__eq__c                 C   s   t | j| jt| jƒ| jfƒS r`   )Úhashr�   rÐ   rG   rÑ   rÒ   rV   r.   r.   r/   Ú__hash__½  s   zDistributedVarOp.__hash__N)rq   ru   rv   rw   rK   rÔ   rÖ   r.   r.   r.   r/   rÏ   ®  s
    rÏ   c                   @   sL   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
efdd„Z	d
e
fdd„ZdS )ÚDistributedVariableTraceTypez)TraceType of DistributedVariable objects.c                 C   s    || _ t|j ¡ ƒ|jf| _d S r`   )Údistributed_variablerG   ÚshapeÚas_listr!   Ú
components)rI   rØ   r.   r.   r/   rK   Å  s   
ÿz%DistributedVariableTraceType.__init__c                 C   s   | |kS r`   r.   ©rI   Úotherr.   r.   r/   Úis_subtype_ofÊ  rÈ   z*DistributedVariableTraceType.is_subtype_ofc                    s   t ‡ fdd„|D ƒƒrˆ S d S )Nc                 3   s   � | ]}ˆ |kV  qd S r`   r.   )rb   rÝ   rV   r.   r/   rc   Î  s   € zNDistributedVariableTraceType.most_specific_common_supertype.<locals>.<genexpr>)Úall)rI   Zothersr.   rV   r/   Úmost_specific_common_supertypeÍ  s   z;DistributedVariableTraceType.most_specific_common_supertypec                 C   rƒ   r`   )rØ   rV   r.   r.   r/   Ú_placeholder_valueÐ  rÁ   z/DistributedVariableTraceType._placeholder_valueÚreturnc                 C   s
   t | jƒS r`   )rÕ   rÛ   rV   r.   r.   r/   rÖ   Ó  rª   z%DistributedVariableTraceType.__hash__c                 C   s   t |tƒsdS | j|jkS ©NF)r#   r×   rÛ   rÜ   r.   r.   r/   rÔ   Ö  s   
z#DistributedVariableTraceType.__eq__N)rq   ru   rv   rw   rK   rÞ   rà   rá   ÚintrÖ   ÚboolrÔ   r.   r.   r.   r/   r×   Â  s    r×   c                       sb  e Zd ZdZd{‡ fdd„	Zdd„ Zdd„ Zd{d	d
„Zedd„ ƒZ	dd„ Z
edd„ ƒZedd„ ƒZedd„ ƒZedd„ ƒZedd„ ƒZedd„ ƒZedd„ ƒZedd„ ƒZedd „ ƒZed!d"„ ƒZed#d$„ ƒZed%d&„ ƒZed'd(„ ƒZd{d)d*„Zed+d,„ ƒZd-d.„ Zd/d0„ Zed1d2„ ƒZed3d4„ ƒZed5d6„ ƒZd7d8„ Zd{d9d:„Z ed;d<„ ƒZ!ed=d>„ ƒZ"d?d@„ Z#dAdB„ Z$dCdD„ Z%dEdF„ Z&dGdH„ Z'dIdJ„ Z(d|dMdN„Z)d|dOdP„Z*d|dQdR„Z+d}dSdT„Z,d}dUdV„Z-d}dWdX„Z.d}dYdZ„Z/d}d[d\„Z0d}d]d^„Z1d}d_d`„Z2dadb„ Z3dcdd„ Z4dedf„ Z5dgdh„ Z6didj„ Z7dkdl„ Z8dmdn„ Z9dodp„ Z:d~dqdr„Z;dsdt„ Z<dudv„ Z=edwdx„ ƒZ>dydz„ Z?‡  Z@S )ÚDistributedVariablez&Holds a map from replica to variables.Nc                    sØ   |t jjkr|d jjstdƒ‚|| _|| _tt	| ƒ 
|¡ | jj d¡d | _|D ]}t|tjƒr?t|dƒr?t | ¡|j_q*t | ¡|_q*t ¡ r^t|ddƒr^d| j }tj||d�| _nd | _d| _d | _|| _d S )	Nr   z�creating distributed tf.Variable with aggregation=MEAN and a non-floating dtype is not supported, please use a different aggregation or dtypeú:ÚhandleZ%_enable_packed_variable_in_eager_modeFz
%s/packed/©r�   ) Úvariables_libr   r    r!   r"   r%   Ú_distribute_strategyÚ_aggregationr|   ræ   rK   r\   r�   ÚsplitÚ_common_namer#   r	   ÚCompositeTensorÚhasattrÚweakrefÚrefrè   rz   r
   Z#executing_eagerly_outside_functionsr   ÚpackedZPackedDistributedVariableÚ_packed_varZ_keras_initializedÚ_initializer_opÚ_policy)rI   r(   rJ   r   Ú
var_policyr*   r�   r‚   r.   r/   rK   á  s2   
ÿÿÿ
ÿ

zDistributedVariable.__init__c              
   C   s¬   t  | j¡�/ g }| jD ]!}t |j¡� | t ||¡¡ W d  ƒ n1 s(w   Y  qW d  ƒ n1 s8w   Y  t	| ƒ| j|| j
t | j|¡d�}||t| ƒ< |S )ab  Perform a deepcopy of the `DistributedVariable`.

    Unlike the deepcopy of a regular tf.Variable, this keeps the original
    strategy and devices of the `DistributedVariable`.  To avoid confusion
    with the behavior of deepcopy on a regular `Variable` (which does
    copy into new devices), we only allow a deepcopy of a `DistributedVariable`
    within its originating strategy scope.

    Args:
      memo: The memoization object for `deepcopy`.

    Returns:
      A deep copy of the current `DistributedVariable`.

    Raises:
      RuntimeError: If trying to deepcopy into a different strategy.
    N)r(   rJ   r   r÷   )r3   Úenter_or_assert_strategyrë   rH   r
   r[   ÚappendÚcopyÚdeepcopyrÒ   rì   rö   Úid)rI   ÚmemoÚ
new_valuesr)   Zcopied_variabler.   r.   r/   Ú__deepcopy__  s"   
ÿ€ÿýüz DistributedVariable.__deepcopy__c                 C   s   | j d uo	t ¡  S r`   )rô   r   Úis_saving_non_distributedrV   r.   r.   r/   Ú_use_packed_variable3  s   
ÿz(DistributedVariable._use_packed_variablec                 C   sp   t  ¡ r	| j ¡ S |  ¡ r| j ¡ S | j ¡ }| jdd… D ]
}t || ¡ ¡}qtj|| jd  ¡ |d�}|S )zøIdentifies if all the component variables are initialized.

    Args:
      name: Name of the final `logical_and` op.

    Returns:
      The op that evaluates to True or False depending on if all the
      component variables are initialized.
    rÄ   éÿÿÿÿré   )	r   r   r\   Úis_initializedr  rô   rH   r   Úlogical_and)rI   r�   Úresultr*   r.   r.   r/   r  9  s   



ÿz"DistributedVariable.is_initializedc                 C   s>   t  ¡ r| jjS | jr| j}|S t tdd„ | jD ƒƒ¡}|S )Nc                 s   r_   r`   )Úinitializerra   r.   r.   r/   rc   \  rd   z2DistributedVariable.initializer.<locals>.<genexpr>)	r   r   r\   r  rõ   r   r   rG   rH   )rI   Zinit_opr.   r.   r/   r  R  s   þÿzDistributedVariable.initializerc                 C   ó   |   ¡  ¡ S r`   )r2   Úinitialized_valuerV   r.   r.   r/   r  _  rŒ   z%DistributedVariable.initialized_valuec                 C   ó
   |   ¡ jS r`   )r2   Úinitial_valuerV   r.   r.   r/   r
  b  ó   
z!DistributedVariable.initial_valuec                 C   ó   | j jS r`   )r\   Ú
constraintrV   r.   r.   r/   r  f  ó   zDistributedVariable.constraintc                 C   r  r`   )r\   rÐ   rV   r.   r.   r/   rÐ   j  r  zDistributedVariable.graphc                 C   rƒ   r`   )rî   rV   r.   r.   r/   Ú_shared_namen  rÃ   z DistributedVariable._shared_namec                 C   r  r`   )r\   Ú
_unique_idrV   r.   r.   r/   r  r  r  zDistributedVariable._unique_idc                 C   r  )z7Lets Optimizers know which graph this variable is from.)r\   Ú
_graph_keyrV   r.   r.   r/   r  v  s   zDistributedVariable._graph_keyc                 C   r  r`   )r\   r�   rV   r.   r.   r/   r�   {  r  zDistributedVariable.namec                 C   r  r`   )r\   r!   rV   r.   r.   r/   r!     r  zDistributedVariable.dtypec                 C   r  r`   )r\   rÙ   rV   r.   r.   r/   rÙ   ƒ  r  zDistributedVariable.shapec                 C   r  r`   )r\   ÚsynchronizationrV   r.   r.   r/   r  ‡  r  z#DistributedVariable.synchronizationc                 C   rƒ   r`   ©rì   rV   r.   r.   r/   r   ‹  rÃ   zDistributedVariable.aggregationc                 C   s   |   ¡ r| jS d S r`   )r  rô   rV   r.   r.   r/   Ú_packed_variable�  s   z$DistributedVariable._packed_variablec                 C   sD   t  ¡ r| jjS t  ¡ }|d u rtdƒ‚|  ¡ r| jjS | j| jS )NztDistributedVariable.handle is not available outside the replica context or a `tf.distribute.Strategy.update()` call.)	r   r   r\   rè   rN   r%   r  rô   rH   rP   r.   r.   r/   rè   •  s   ÿzDistributedVariable.handlec                 C   s   |   ¡  |¡S r`   )r2   Úeval)rI   Úsessionr.   r.   r/   r  £  r¨   zDistributedVariable.evalc                 C   r  r`   )r\   Ú_save_slice_inforV   r.   r.   r/   r  ¦  r  z$DistributedVariable._save_slice_infoc                 C   ó
   | j  ¡ S r`   )r\   Ú_get_save_slice_inforV   r.   r.   r/   r  ª  rª   z(DistributedVariable._get_save_slice_infoc                 C   s   | j D ]}| |¡ qd S r`   )rH   Ú_set_save_slice_info)rI   Zsave_slice_infor*   r.   r.   r/   r  ­  s   
ÿz(DistributedVariable._set_save_slice_infoc                 C   r	  r`   )r2   r[   rV   r.   r.   r/   r[   ±  r  zDistributedVariable.devicec                 C   r  r`   )r\   Ú	trainablerV   r.   r.   r/   r  µ  r  zDistributedVariable.trainablec                 C   rƒ   r`   )rë   rV   r.   r.   r/   r&   ¹  rÃ   z'DistributedVariable.distribute_strategyc                 C   r  r`   )r\   Ú	get_shaperV   r.   r.   r/   r  ½  rª   zDistributedVariable.get_shapec                 C   s   | j j|d�S )N)Úexport_scope)r\   Úto_proto)rI   r  r.   r.   r/   r  À  r¨   zDistributedVariable.to_protoc                 C   sH   t  ¡ r| jjS t ¡ rt| jjj| jjj| jjj	| jjj
ƒS |  ¡ jS r`   )r   r   r\   Úopr3   r¹   rÏ   r�   rÐ   rÑ   rÒ   rR   rV   r.   r.   r/   r  Ã  s   ÿ
zDistributedVariable.opc                 C   r  r`   )r\   Ú_in_graph_moderV   r.   r.   r/   r   Ï  r  z"DistributedVariable._in_graph_modec                 C   s$   |   ¡ r| j | j| ¡S | j| S )z8Returns the value on a device with the given replica_id.)r  rô   Z	on_devicere   rH   rP   r.   r.   r/   Ú_get_replicaÓ  s   
z DistributedVariable._get_replicac                 C   s0   t  ¡ r| jS t  ¡ }|du r|  ¡ S |  |¡S rM   )r   r   r\   rN   rO   r!  rP   r.   r.   r/   rR   Ù  s   
zDistributedVariable._getc                 C   sr   t  ¡ r| jS t  ¡ }|du r4t t ¡ ¡}t| jƒD ]\}}t |j	¡|kr.|  
|¡  S q|  
d¡S |  
|¡S )rX   Nr   )r   r   r\   rN   r   rY   rZ   ro   rH   r[   r!  )rI   rQ   r]   rj   r)   r.   r.   r/   r2   ã  s   ÿ

z-DistributedVariable._get_on_device_or_primaryc                 C   sP   t  ¡ r	| j ¡ S t | j¡� t |  	¡ ¡W  d   ƒ S 1 s!w   Y  d S r`   )
r   r   r\   Ú
read_valuer3   rø   rë   r   ÚidentityrR   rV   r.   r.   r/   r"  ò  s
   
$ÿzDistributedVariable.read_valuec                 C   s0   t  ¡ r	| j ¡ S | jr| j | ¡S |  ¡  ¡ S r`   )r   r   r\   r)   rö   r2   rV   r.   r.   r/   r)   ø  s
   
zDistributedVariable.valuec                 C   s   t  ¡ r
|  ¡  ¡ S tdƒ‚)NzNDistributedVariable.numpy() is only available when eager execution is enabled.)r   Zexecuting_eagerlyr"  ÚnumpyrU   rV   r.   r.   r/   r$  ÿ  s   zDistributedVariable.numpyFTc                 C   óJ   t  ¡ r| j ||||¡S | jr| jj| ||||d�S t j| ||||d�S ©N©Úuse_lockingr�   r"  )r   r   r\   Ú
assign_subrö   Úon_write_assign_sub©rI   r)   r(  r�   r"  r.   r.   r/   r)    ó   û
ÿzDistributedVariable.assign_subc                 C   r%  r&  )r   r   r\   Ú
assign_addrö   Úon_write_assign_addr+  r.   r.   r/   r-    r,  zDistributedVariable.assign_addc                 C   r%  r&  )r   r   r\   Úassignrö   Úon_write_assignr+  r.   r.   r/   r/     r,  zDistributedVariable.assignc                 C   óD   t  ¡ r| j |||¡S | jr| jj| |||d�S t j| |||d�S ©N©r(  r�   )r   r   r\   Úscatter_subrö   ©rI   Úsparse_deltar(  r�   r.   r.   r/   r4  -  ó   ÿÿzDistributedVariable.scatter_subc                 C   r1  r2  )r   r   r\   Úscatter_addrö   r5  r.   r.   r/   r8  6  r7  zDistributedVariable.scatter_addc                 C   r1  r2  )r   r   r\   Úscatter_mulrö   r5  r.   r.   r/   r9  ?  r7  zDistributedVariable.scatter_mulc                 C   r1  r2  )r   r   r\   Úscatter_divrö   r5  r.   r.   r/   r:  H  r7  zDistributedVariable.scatter_divc                 C   r1  r2  )r   r   r\   Úscatter_minrö   r5  r.   r.   r/   r;  Q  r7  zDistributedVariable.scatter_minc                 C   r1  r2  )r   r   r\   Úscatter_maxrö   r5  r.   r.   r/   r<  Z  r7  zDistributedVariable.scatter_maxc                 C   r1  r2  )r   r   r\   Úscatter_updaterö   r5  r.   r.   r/   r=  c  r7  z"DistributedVariable.scatter_updatec                 C   s   t | ƒS r`   )r×   ©rI   Ú_r.   r.   r/   Ú__tf_tracing_type__l  rÈ   z'DistributedVariable.__tf_tracing_type__c                    ó   ˆ j f‡ fdd„	}tj|iS )zØOverrides Trackable method.

    This allows both name-based and object-based save and restore of
    DistributedVariables.

    Returns:
      A dictionary mapping attribute names to `SaveableObject` factories.
    c                    ó   t ˆ ˆ j| ƒS r`   )Ú_DistributedVariableSaveabler\   ré   rV   r.   r/   Ú_saveable_factoryy  r¨   zODistributedVariable._gather_saveables_for_checkpoint.<locals>._saveable_factory©rî   Ú	trackableZVARIABLE_VALUE_KEY©rI   rD  r.   rV   r/   Ú _gather_saveables_for_checkpointo  ó   

z4DistributedVariable._gather_saveables_for_checkpointc                 C   s,   t  ¡ r	| j ¡ S | jr| j | ¡S tdƒ‚)NzÛDistributedVariable._as_graph_element requires a valid VariablePolicy. Please set the policy via the `var_policy` argument in the constructor, or override this method in sub-classes which support cross-replica accesses.)r   r   r\   rÌ   rö   rU   rV   r.   r.   r/   rÌ   ~  s   
ÿz%DistributedVariable._as_graph_elementc                 C   s(   t  ¡ r| jS | jr| j | ¡S tdƒ‚)NzÜDistributedVariable._get_cross_replica requires a valid VariablePolicy. Please set the policy via the `var_policy` argument in the constructor, or override this method in sub-classes which support cross-replica accesses.)r   r   r\   rö   rO   rU   rV   r.   r.   r/   rO   Š  s   ÿz&DistributedVariable._get_cross_replicac                 K   s"   t  ¡  | jjj| ||f|dd�S )ag  Applies updates across replicas.

    Args:
      update_fn: A callable to pass to `strategy.extended.update` to update the
        variable. It should has the same signature as `Variable.assign()`.
      value: value to be passed to `update_fn`.
      **kwargs: remaining arguments to `update_fn`.

    Returns:
      Updated variable or `tf.Operation`.
    Tr   )r   r8   r&   r5   Úupdate©rI   r,   r)   r   r.   r.   r/   r'   –  s   ÿz)DistributedVariable._update_cross_replicac                 K   s&   | j r| j j| ||fi |¤ŽS tdƒ‚)a@  Applies updates in one replica.

    Args:
      update_fn: A callable to update the variable. It should has the same
        signature as `Variable.assign()`.
      value: value to be passed to `update_fn`.
      **kwargs: remaining arguments to `update_fn`.

    Returns:
      Updated variable or `tf.Operation`.
    zÙDistributedVariable._update_replica requires a valid VariablePolicy. Please set the policy via the `var_policy` argument in the constructor, or override this method in sub-classes which support cross-replica accesses.)rö   Ú_update_replicarU   rK  r.   r.   r/   rL  ¦  s
   ÿz#DistributedVariable._update_replicac                 K   sÐ   t  ¡ r|| j|fi |¤ŽS t | j¡�J t ¡ rGt ¡ }|dur6|  	|¡}|||fi |¤ŽW  d  ƒ S | j
||fi |¤ŽW  d  ƒ S t  | j¡ | j||fi |¤ŽW  d  ƒ S 1 saw   Y  dS )aœ  Applies updates depending on the context.

    The method calls `_update_replica` in replica context,
    `_update_cross_replica` in cross replica context, and `update_fn` in update
    context.

    If `read_value` is True, the method returns the updated Variable. If
    `read_value` is False, the method returns the update `tf.Operation`.

    Args:
      update_fn: A callable to pass to `strategy.extended.update` to update the
        variable. It should have the same signature as `Variable.assign()`.
      value: value to be passed to `update_fn`.
      **kwargs: keyword arguments to `update_fn`.

    Returns:
      Updated variable or `tf.Operation`.

    N)r   r   r\   r3   rø   r&   r¹   r   Zget_update_replica_idr!  r'   Zassert_replica_contextrL  )rI   r,   r)   r   Zupdate_replica_idZreplica_valuer.   r.   r/   r:   º  s   
ûú$÷zDistributedVariable._updatec                 C   ó   dS )z6Pass resource_variable_ops.is_resource_variable check.Nr.   rV   r.   r.   r/   Ú _should_act_as_resource_variableÛ  ó   z4DistributedVariable._should_act_as_resource_variablec                 C   sb   t  ¡ rtj| j|||d�S t | j¡� tj|  ¡ |||d�W  d  ƒ S 1 s*w   Y  dS )ú Converts a variable to a tensor.©r!   r�   rº   N)	r   r   r
   Úconvert_to_tensorr\   r3   rø   rë   rR   ©rI   r!   r�   rº   r.   r.   r/   Ú_dense_var_to_tensorß  s   
ÿÿ$ÿz(DistributedVariable._dense_var_to_tensorc                    s¼   ˆ j  |¡\}}‡ fdd„ˆ jD ƒD ])}|j ¡ r+| |¡\}}| |¡ | |¡ q|ˆ j  ||< |ˆ j j ||j< q|ˆ j  |ˆ < |ˆ j j |ˆ < ˆ jdurZ|ˆ j j |ˆ jj< ||fS )zFor implementing `Trackable`.c                    s   g | ]	}|ˆ j kr|‘qS r.   )r\   ra   rV   r.   r/   Ú
<listcomp>í  s    z6DistributedVariable._map_resources.<locals>.<listcomp>N)	r\   Ú_map_resourcesrH   Zexperimental_variable_policyZ_expand_distributed_variablesrJ  rè   rô   Zpacked_handle)rI   Zsave_optionsZobj_mapZresource_mapr*   Z	v_obj_mapZv_resource_mapr.   rV   r/   rV  è  s"   ÿ

ÿz"DistributedVariable._map_resourcesc                 C   s:   t  | ||¡ | jr| j ¡ r| j | ||¡ dS dS dS ©aê  Update a SavedObject proto for the caller.

    If a DistributedVariable object supports this method, it will be called when
    saving with a pre-built `SavedObject` proto representing the object, plus an
    instance of `SaveOptions`. This method is then free to modify that proto
    instance.

    `DistributedVariable` with `AUTO` or `ON_WRITE` synchronization optionally
    write out information about their components to the
    `experimental_distributed_variable_components` field of a
    `SavedVariable` (depending on the `SaveOptions` variable policy).

    Args:
      proto: A pre-built `SavedObject` proto for this object. It is assumed this
        will be a `SavedVariable` instance.
      options: A `SaveOptions` instance.
    N)r   Z(write_object_proto_for_resource_variablerö   Ú_is_mirroredÚ_write_object_proto©rI   ÚprotoÚoptionsr.   r.   r/   rY  þ  s   ÿ
þz'DistributedVariable._write_object_protoc                 C   rM  ©NTr.   rV   r.   r.   r/   Úis_distributed_variable  rO  z+DistributedVariable.is_distributed_variablec                 C   s   |j  | |¡ | S r`   )rÐ   Zcapture_distributed_variable)rI   Zconcrete_functionZinternal_capturer.   r.   r/   Ú#__tf_experimental_restore_capture__  s   z7DistributedVariable.__tf_experimental_restore_capture__r`   ©FNT©FN©NNF)Arq   ru   rv   rw   rK   rÿ   r  r  rx   r  r  r
  r  rÐ   r  r  r  r�   r!   rÙ   r  r   r  rè   r  r  r  r  r[   r  r&   r  r  r  r   r!  rR   r2   r"  r)   r$  r)  r-  r/  r4  r8  r9  r:  r;  r<  r=  r@  rH  rÌ   rO   r'   rL  r:   rN  rT  rV  rY  r^  r_  rµ   r.   r.   r‚   r/   ræ   Ý  s¤    /#




























	
	
	
	
	
		!
	
ræ   c                       ó(   e Zd ZdZ‡ fdd„Zdd„ Z‡  ZS )rC  z8Class for defining how to restore a DistributedVariable.c                    sB   || _ | j jstdƒ‚|j |||¡\}}tt| ƒ |||¡ d S )NzÆThe VariablePolicy of the argument `distributed_variable` must be set to create a _DistributedVariableSaveable. Please set it via the `var_policy` argument in the constructor of DistributedVariable.)Ú_distributed_variablerö   r%   Úget_saveabler|   rC  rK   )rI   rØ   Úprimary_variabler�   ÚtensorÚspecr‚   r.   r/   rK   *  s   ÿÿz%_DistributedVariableSaveable.__init__c                 C   s   |\}| j j | j |¡S ©z*Restore the same value into all variables.)rd  rö   Úget_restore_ops©rI   Zrestored_tensorsZrestored_shapesrg  r.   r.   r/   Úrestore6  s   ÿz$_DistributedVariableSaveable.restore©rq   ru   rv   rw   rK   rl  rµ   r.   r.   r‚   r/   rC  '  s    rC  c                       rc  )Ú_MirroredSaveablez5Class for defining how to restore a MirroredVariable.c                    s2   || _ t | j ||¡\}}tt| ƒ |||¡ d S r`   )Ú_mirrored_variabler   Úget_on_write_saveabler|   rn  rK   )rI   Zmirrored_variablerf  r�   rg  rh  r‚   r.   r/   rK   @  s
   ÿz_MirroredSaveable.__init__c                 C   s   |\}t  | j|¡S ri  )r   Úget_on_write_restore_opsro  rk  r.   r.   r/   rl  F  s   z_MirroredSaveable.restorerm  r.   r.   r‚   r/   rn  =  s    rn  c                       sn   e Zd ZdZdd„ Z‡ fdd„Z‡ fdd„Z‡ fdd	„Zd
d„ Zdd„ Z	dd„ Z
‡ fdd„Zddd„Z‡  ZS )ÚMirroredVariablezDHolds a map from replica to variables whose values are kept in sync.c                 K   s   t | ||fi |¤ŽS r`   )r=   rK  r.   r.   r/   rL  O  s   z MirroredVariable._update_replicac                    ób   t  ¡ r| jj|i |¤ŽS | jtjjkr&| jtjjkr&t	t j
jd| jd�ƒ‚tt| ƒj|i |¤ŽS )Nr;  ©Zop_namer   )r   r   r\   r;  rì   r   r   rB   r1   rU   Úscatter_error_msgr¸   r|   rr  ©rI   r   r   r‚   r.   r/   r;  R  ó   ÿÿzMirroredVariable.scatter_minc                    rs  )Nr<  rt  )r   r   r\   r<  rì   r   r   rB   r1   rU   ru  r¸   r|   rr  rv  r‚   r.   r/   r<  \  rw  zMirroredVariable.scatter_maxc                    rs  )Nr=  rt  )r   r   r\   r=  rì   r   r   rB   r1   rU   ru  r¸   r|   rr  rv  r‚   r.   r/   r=  f  rw  zMirroredVariable.scatter_updatec                 C   s   t  t | ¡¡S r`   )r   r#  rÊ   rO   rV   r.   r.   r/   rO   p  s   z#MirroredVariable._get_cross_replicac                 C   r  r`   ©r2   rÌ   rV   r.   r.   r/   rÌ   u  rŒ   z"MirroredVariable._as_graph_elementc                    rA  )zÕOverrides Trackable method.

    This allows both name-based and object-based save and restore of
    MirroredVariables.

    Returns:
      A dictionary mapping attribute names to `SaveableObject` factories.
    c                    rB  r`   )rn  r\   ré   rV   r.   r/   rD  ‚  r¨   zLMirroredVariable._gather_saveables_for_checkpoint.<locals>._saveable_factoryrE  rG  r.   rV   r/   rH  x  rI  z1MirroredVariable._gather_saveables_for_checkpointc                    s$   t t| ƒ ||¡ t | ||¡ dS rW  )r|   rr  rY  r   Úwrite_object_protorZ  r‚   r.   r/   rY  ‡  s   z$MirroredVariable._write_object_protoNFc                 C   s"   |rt dƒ‚tj|  ¡ |||d�S )rP  z·You may be using variable created under distribute strategy in TF 1.x control flows. Try explicitly converting the variable to Tensor using variable.read_value(), or switch to TF 2.x.rQ  )r%   r
   rR  rR   rS  r.   r.   r/   rT  œ  s   ÿÿz%MirroredVariable._dense_var_to_tensorrb  )rq   ru   rv   rw   rL  r;  r<  r=  rO   rÌ   rH  rY  rT  rµ   r.   r.   r‚   r/   rr  L  s    


rr  c                       rc  )Ú_SyncOnReadSaveablez7Class for defining how to restore a SyncOnReadVariable.c                    s2   || _ t ||j|¡\}}tt| ƒ |||¡ d S r`   )Ú_sync_on_read_variabler   Úget_on_read_saveabler\   r|   rz  rK   )rI   Zsync_on_read_variabler�   rg  rh  r‚   r.   r/   rK   ±  s
   ÿz_SyncOnReadSaveable.__init__c                 C   s   |\}t  | j|| jj¡S ri  )r   Úget_on_read_restore_opsr{  r   rk  r.   r.   r/   rl  ¸  s
   þz_SyncOnReadSaveable.restorerm  r.   r.   r‚   r/   rz  ®  s    rz  c                       sÈ   e Zd ZdZdd„ Z‡ fdd„Zd+‡ fd	d
„	Zd+‡ fdd„	Zd+‡ fdd„	Zdd„ Z	dd„ Z
dd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd „ Z‡ fd!d"„Zd#d$„ Zd%d&„ Zd'd(„ Zd,d)d*„Z‡  ZS )-ÚSyncOnReadVariablezGHolds a map from replica to variables whose values are reduced on save.c                 K   s   ||   ¡ |fi |¤ŽS r`   rË   rK  r.   r.   r/   rL  Ã  ó   z"SyncOnReadVariable._update_replicac                    s>   t  | j¡� tt| ƒ ¡ W  d  ƒ S 1 sw   Y  dS )a  Returns the value of SyncOnReadVariable based on surrounding context.

    If called under a non-default replica-context, returns the corresponding
    variable on that replica.
    If called under default replica-context or cross-replica context, returns
    the synced value.
    N)r3   rø   rë   r|   r~  rR   rV   r‚   r.   r/   rR   Æ  s   $ÿzSyncOnReadVariable._getFNTc                    ó–   t  ¡ r| j ||||¡S t | j¡�. t ¡ r/t  ¡ s/t  	¡  t j
| ||d�W  d   ƒ S tt| ƒ ||||¡W  d   ƒ S 1 sDw   Y  d S ©N©r"  )r   r   r\   r)  r3   rø   rë   r¹   Úin_replica_update_contextr8   Ú on_read_assign_sub_cross_replicar|   r~  r+  r‚   r.   r/   r)  Ó  ó    ÿÿüÿ$øzSyncOnReadVariable.assign_subc                    r€  r�  )r   r   r\   r-  r3   rø   rë   r¹   rƒ  r8   Ú on_read_assign_add_cross_replicar|   r~  r+  r‚   r.   r/   r-  à  r…  zSyncOnReadVariable.assign_addc                    r€  r�  )r   r   r\   r/  r3   rø   rë   r¹   rƒ  r8   Úon_read_assign_cross_replicar|   r~  r+  r‚   r.   r/   r/  í  s   ÿÿüÿ$ùzSyncOnReadVariable.assignc                 C   ó   t d|› d�ƒ‚)Nz:Variables with `synchronization=ON_READ` doesn't support `ú`rT   ©rI   Úmethodr.   r.   r/   Ú_scatter_not_implementedú  s   
ÿz+SyncOnReadVariable._scatter_not_implementedc                 O   ó(   t  ¡ r| jj|i |¤ŽS |  d¡ d S ©Nr4  )r   r   r\   r4  rŒ  rv  r.   r.   r/   r4  þ  ó   zSyncOnReadVariable.scatter_subc                 O   r�  ©Nr8  )r   r   r\   r8  rŒ  rv  r.   r.   r/   r8    r�  zSyncOnReadVariable.scatter_addc                 O   r�  ©Nr9  )r   r   r\   r9  rŒ  rv  r.   r.   r/   r9    r�  zSyncOnReadVariable.scatter_mulc                 O   r�  ©Nr:  )r   r   r\   r:  rŒ  rv  r.   r.   r/   r:    r�  zSyncOnReadVariable.scatter_divc                 O   r�  ©Nr;  )r   r   r\   r;  rŒ  rv  r.   r.   r/   r;    r�  zSyncOnReadVariable.scatter_minc                 O   r�  ©Nr<  )r   r   r\   r<  rŒ  rv  r.   r.   r/   r<    r�  zSyncOnReadVariable.scatter_maxc                 O   r�  ©Nr=  )r   r   r\   r=  rŒ  rv  r.   r.   r/   r=    r�  z!SyncOnReadVariable.scatter_updatec                 C   s®   t  ¡ rtdƒ‚t ¡ r| j ¡ S t  | j¡�6 t  	¡ r@t 
¡ s@| jtjjkr5|  d¡ ¡ W  d   ƒ S |  ¡ W  d   ƒ S |  ¡  ¡ W  d   ƒ S 1 sPw   Y  d S )NzMcall `variable.value()` inside variable_sync_on_read_context is not supportedr   )r3   Ú in_variable_sync_on_read_contextrU   r   r   r\   r)   rø   rë   r¹   rƒ  rì   r   r   rB   r!  rO   r2   rV   r.   r.   r/   r)   !  s"   ÿ
ÿüû
$øzSyncOnReadVariable.valuec                    s   t  ¡ rtdƒ‚tƒ  ¡ S )NzRcall `variable.read_value()` inside variable_sync_on_read_context is not supported)r3   r–  rU   r|   r"  rV   r‚   r.   r/   r"  2  s
   ÿ
zSyncOnReadVariable.read_valuec                 C   sz   | j tjjkr|  d¡S | j tjjkrt ¡  t 	| j
¡� | j
jtj | j ¡| d d�W  d   ƒ S 1 s6w   Y  d S ©Nr   )Zaxis)rì   r   r   rB   r!  ÚSUMr   r8   r3   rø   rë   Úreducer   rC   rD   rV   r.   r.   r/   rO   9  s   
ý$ÿz%SyncOnReadVariable._get_cross_replicac                 C   sn   t  ¡ r	| j ¡ S t | j¡� t ¡ r"t 	|  
¡ ¡W  d   ƒ S W d   ƒ n1 s,w   Y  |  ¡  ¡ S r`   )r   r   r\   rÌ   r3   rø   rë   r¹   r
   rR  rO   rR   rV   r.   r.   r/   rÌ   F  s   
þÿz$SyncOnReadVariable._as_graph_elementc                    rA  )zÙOverrides Trackable method.

    This allows both name-based and object-based save and restore of
    `SyncOnReadVariable`s.

    Returns:
      A dictionary mapping attribute names to `SaveableObject` factories.
    c                    s
   t ˆ | ƒS r`   )rz  ré   rV   r.   r/   rD  Y  rª   zNSyncOnReadVariable._gather_saveables_for_checkpoint.<locals>._saveable_factoryrE  rG  r.   rV   r/   rH  O  rI  z3SyncOnReadVariable._gather_saveables_for_checkpointc                 C   s  t  ¡ rtj| j|||d�S t | j¡�e t ¡ }|durgt 	¡ rg| j
tjjkr;tj|  d¡|||d�W  d  ƒ S | j
tjjkrFt  ¡  |jj tj | j
¡|  ¡  ¡ ¡}tj||||d�W  d  ƒ S tj|  ¡ |||d�W  d  ƒ S 1 s|w   Y  dS )z*Converts a SyncOnReadVariable to a tensor.rQ  Nr   )r   r   r
   rR  r\   r3   rø   rë   r9   r–  rì   r   r   rB   r!  r˜  r8   r(   r5   rE   r   rC   rD   rR   r"  )rI   r!   r�   rº   rÅ   Zreducedr.   r.   r/   rT  ^  s>   
ÿÿÿûÿ
ýÿÿñÿ$îz'SyncOnReadVariable._dense_var_to_tensorr`  rb  )rq   ru   rv   rw   rL  rR   r)  r-  r/  rŒ  r4  r8  r9  r:  r;  r<  r=  r)   r"  rO   rÌ   rH  rT  rµ   r.   r.   r‚   r/   r~  À  s*    	r~  c                 C   ó   | j |||d�S ©NrQ  ©rT  ©r-   r!   r�   rº   r.   r.   r/   Ú"_tensor_conversion_distributed_var|  s   rž  c                 C   rš  r›  rœ  r�  r.   r.   r/   Ú_tensor_conversion_mirroredˆ  r¦   rŸ  c                 C   s   t j|  ¡ |||d�S r›  )r
   rR  rR   )r)   r!   r�   rº   r.   r.   r/   Ú_tensor_conversion_mirrored_val‘  s   ÿr   c                 C   rš  r›  rœ  r�  r.   r.   r/   Ú_tensor_conversion_sync_on_read›  r¦   r¡  c                   @   s@   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Z	dS )ÚVariablePolicya�  Policy defining synchronization and aggregation of a distributed variable.

  Given `synchronization` and `aggregation` parameters set on a `tf.Variable`
  during variable creation within `tf.distribute` scope, `tf.distribute` creates
  an appropriate policy object and assigns it to the distributed variable. All
  variable operations are delegated to the respective policy object.
  c                 C   s
   || _ d S r`   r  )rI   r   r.   r.   r/   rK   ¬  rª   zVariablePolicy.__init__c                 C   rS   )Nz8VariablePolicy.value should be overriden by sub-classes.rT   rV   r.   r.   r/   r)   ¯  rW   zVariablePolicy.valuec                 C   rS   )Nz?VariablePolicy._is_mirrored should be overriden by sub-classes.rT   rV   r.   r.   r/   rX  ³  rW   zVariablePolicy._is_mirroredc                 C   rS   )NzDVariablePolicy._as_graph_element should be overriden by sub-classes.rT   r>  r.   r.   r/   rÌ   ·  rW   z VariablePolicy._as_graph_elementc                 C   rS   )NzEVariablePolicy._get_cross_replica should be overriden by sub-classes.rT   ©rI   r-   r.   r.   r/   rO   »  rW   z!VariablePolicy._get_cross_replicac                 K   rS   )NzBVariablePolicy._update_replica should be overriden by sub-classes.rT   ©rI   r-   r,   r)   r   r.   r.   r/   rL  ¿  rW   zVariablePolicy._update_replicaN)
rq   ru   rv   rw   rK   r)   rX  rÌ   rO   rL  r.   r.   r.   r/   r¢  £  s    r¢  c                   @   s²   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Z				d)dd„Z
			d)dd„Zd)dd„Zdd„ Zdd„ Zdd„ Zdd„ Zdd „ Zd!d"„ Zd#d$„ Zd%d&„ Zd'd(„ ZdS )*ÚOnReadPolicya{  Policy defined for `tf.VariableSynchronization.ON_READ` synchronization.

  This policy is created when `synchronization` is set to
  `tf.VariableSynchronization.ON_READ` and `aggregation` is set to any of the
  values allowed by the `tf.VariableAggregation` enum such as `NONE`, `SUM`,
  `MEAN` or `ONLY_FIRST_REPLICA`when creating a `tf.Variable` in `tf.distribute`
  scope.
  c                 C   rM  rã   r.   rV   r.   r.   r/   rX  Î  ó   zOnReadPolicy._is_mirroredc                 C   sŒ   t  |j¡�6 t  ¡ r/t ¡ s/| jtjj	kr$| 
d¡ ¡ W  d   ƒ S | ¡ W  d   ƒ S | ¡  ¡ W  d   ƒ S 1 s?w   Y  d S )Nr   )r3   rø   r&   r¹   r   rƒ  rì   r   r   rB   r!  r)   rO   r2   r£  r.   r.   r/   r)   Ñ  s   ÿüû
$ùzOnReadPolicy.valuec                 C   s\   t  |j¡� t  ¡ rt | ¡ ¡W  d   ƒ S W d   ƒ n1 s#w   Y  | ¡  ¡ S r`   )	r3   rø   r&   r¹   r
   rR  rO   rR   rÌ   r£  r.   r.   r/   rÌ   Û  s   þÿzOnReadPolicy._as_graph_elementc                 C   sz   | j tjjkr| d¡S | j tjjkrt ¡  t 	|j
¡� |j
jtj | j ¡|d d�W  d   ƒ S 1 s6w   Y  d S r—  )rì   r   r   rB   r!  r˜  r   r8   r3   rø   r&   r™  r   rC   rD   r£  r.   r.   r/   rO   á  s   
ý$ÿzOnReadPolicy._get_cross_replicac                 K   s   ||  ¡ |fi |¤ŽS r`   rË   r¤  r.   r.   r/   rL  ì  r  zOnReadPolicy._update_replicac                 C   rˆ  )Nz#ON_READ variables doesn't support `z` in cross replica contextrT   rŠ  r.   r.   r/   rŒ  ï  r¦   z%OnReadPolicy._scatter_not_implementedFNTc                 C   óz   t  |j¡�- t  ¡ r"t ¡ s"t ¡  tj|||d�W  d  ƒ S tj|||||d�W  d  ƒ S 1 s6w   Y  dS )z%Subtracts a value from this variable.r‚  Nr'  )	r3   rø   r&   r¹   r   rƒ  r8   r„  r*  ©rI   r-   r)   r(  r�   r"  r.   r.   r/   r)  ó  ó"   ÿÿüû$ùzOnReadPolicy.assign_subc                 C   r§  )zAdds a value to this variable.r‚  Nr'  )	r3   rø   r&   r¹   r   rƒ  r8   r†  r.  r¨  r.   r.   r/   r-    r©  zOnReadPolicy.assign_addc                 C   sz   t  |j¡�- t  ¡ r"t ¡ s"t ¡  tj|||d�W  d   ƒ S tj|||||d�W  d   ƒ S 1 s6w   Y  d S )Nr‚  r'  )	r3   rø   r&   r¹   r   rƒ  r8   r‡  r0  r¨  r.   r.   r/   r/    s"   ÿÿüû$ùzOnReadPolicy.assignc                 O   ó   ~~|   d¡ d S rŽ  ©rŒ  rv  r.   r.   r/   r4  ,  ó   zOnReadPolicy.scatter_subc                 O   rª  r�  r«  rv  r.   r.   r/   r8  0  r¬  zOnReadPolicy.scatter_addc                 O   rª  r‘  r«  rv  r.   r.   r/   r9  4  r¬  zOnReadPolicy.scatter_mulc                 O   rª  r’  r«  rv  r.   r.   r/   r:  8  r¬  zOnReadPolicy.scatter_divc                 O   rª  r“  r«  rv  r.   r.   r/   r;  <  r¬  zOnReadPolicy.scatter_minc                 O   rª  r”  r«  rv  r.   r.   r/   r<  @  r¬  zOnReadPolicy.scatter_maxc                 O   rª  r•  r«  rv  r.   r.   r/   r=  D  r¬  zOnReadPolicy.scatter_updatec                 C   ó   t  |||¡S )z0Create a saveable object for the given variable.)r   r|  ©rI   r-   Zprimary_varr�   r.   r.   r/   re  H  rL   zOnReadPolicy.get_saveablec                 C   s   t  ||| j¡S ri  )r   r}  rì   ©rI   r-   rg  r.   r.   r/   rj  L  s   zOnReadPolicy.get_restore_opsr`  )rq   ru   rv   rw   rX  r)   rÌ   rO   rL  rŒ  r)  r-  r/  r4  r8  r9  r:  r;  r<  r=  re  rj  r.   r.   r.   r/   r¥  Ä  s4    	

û
û
r¥  c                   @   sÀ   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ Zd)dd„Z				d)dd„Z
			d)dd„Zd*dd„Zd*dd„Zd*dd„Zd*dd„Zd*dd„Zd*dd „Zd*d!d"„Zd#d$„ Zd%d&„ Zd'd(„ ZdS )+ÚOnWritePolicyaa  Policy defined for `tf.VariableSynchronization.ON_WRITE` synchronization.

  This policy is created when the following `synchronization` and `aggregation`
  parameters are specified when creating a `tf.Variable` in `tf.distribute`
  scope and `synchronization` is equal to `tf.VariableSynchronization.ON_WRITE`
  or `tf.VariableSynchronization.AUTO`.
  c                 C   rM  r]  r.   rV   r.   r.   r/   rX  Z  r¦  zOnWritePolicy._is_mirroredc                 C   ó   |  ¡  ¡ S r`   )r2   r)   r£  r.   r.   r/   r)   ]  rŒ   zOnWritePolicy.valuec                 C   r±  r`   rx  r£  r.   r.   r/   rÌ   `  rŒ   zOnWritePolicy._as_graph_elementc                 C   s   t  | ¡ ¡S r`   )r   r#  r2   r£  r.   r.   r/   rO   c  s   z OnWritePolicy._get_cross_replicac                 K   s8   |j tjjkr|| ¡ |fi |¤ŽS t|||fi |¤ŽS r`   )r   rê   r   r1   r2   r=   r¤  r.   r.   r/   rL  h  s   zOnWritePolicy._update_replicaFNTc                 C   ó   t j|||||d�S r&  )r   r0  r¨  r.   r.   r/   r/  m  s   
ÿzOnWritePolicy.assignc                 C   r²  r&  )r   r.  r¨  r.   r.   r/   r-  q  ó   
ÿzOnWritePolicy.assign_addc                 C   r²  r&  )r   r*  r¨  r.   r.   r/   r)  z  r³  zOnWritePolicy.assign_subc                 C   ó   t j||||d�S r2  )r   r4  ©rI   r-   r6  r(  r�   r.   r.   r/   r4  ƒ  ó   ÿzOnWritePolicy.scatter_subc                 C   r´  r2  )r   r8  rµ  r.   r.   r/   r8  ‡  r¶  zOnWritePolicy.scatter_addc                 C   r´  r2  )r   r9  rµ  r.   r.   r/   r9  ‹  r¶  zOnWritePolicy.scatter_mulc                 C   r´  r2  )r   r:  rµ  r.   r.   r/   r:  �  r¶  zOnWritePolicy.scatter_divc                 C   óD   | j tjjkr| j tjjkrttjjd| j d�ƒ‚tj	||||d�S )Nr;  rt  r3  )
rì   r   r   rB   r1   rU   r   ru  r¸   r;  rµ  r.   r.   r/   r;  “  ó   ÿÿÿzOnWritePolicy.scatter_minc                 C   r·  )Nr<  rt  r3  )
rì   r   r   rB   r1   rU   r   ru  r¸   r<  rµ  r.   r.   r/   r<  œ  r¸  zOnWritePolicy.scatter_maxc                 C   r·  )Nr=  rt  r3  )
rì   r   r   rB   r1   rU   r   ru  r¸   r=  rµ  r.   r.   r/   r=  ¥  r¸  zOnWritePolicy.scatter_updatec                 C   r­  )z Saveable ops for AUTO variables.)r   rp  r®  r.   r.   r/   re  ®  rL   zOnWritePolicy.get_saveablec                 C   s   t  ||¡S r`   )r   rq  r¯  r.   r.   r/   rj  ²  rŒ   zOnWritePolicy.get_restore_opsc                 C   s   t  |||¡ dS )a  Update a SavedObject proto for the caller.

    If a DistributedVariable object supports this method, it will be called when
    saving with a pre-built `SavedObject` proto representing the object, plus an
    instance of `SaveOptions`. This method is then free to modify that proto
    instance.

    `DistributedVariable` with `AUTO` or `ON_WRITE` synchronization optionally
    write out information about their components to the
    `experimental_distributed_variable_components` field of a
    `SavedVariable` (depending on the `SaveOptions` variable policy).

    Args:
      var : A DistributedVariable object
      proto: A pre-built `SavedObject` proto for this object. It is assumed this
        will be a `SavedVariable` instance.
      options: A `SaveOptions` instance.
    N)r   ry  )rI   r-   r[  r\  r.   r.   r/   rY  µ  s   z!OnWritePolicy._write_object_protor`  ra  )rq   ru   rv   rw   rX  r)   rÌ   rO   rL  r/  r-  r)  r4  r8  r9  r:  r;  r<  r=  re  rj  rY  r.   r.   r.   r/   r°  Q  s4    

û
û
	




	
		r°  c                       s<   e Zd ZdZdd„ Z‡ fdd„Z‡ fdd„Zdd	„ Z‡  ZS )
ÚPerWorkerResourcea  A per-worker CapturableResource class for non-ParameterServer strategy.

  Resources that populate `host_to_resources` should be instances of classes
  subclassing CapturableResource, although currently it's only used and tested
  for StaticHashTable with TPUStrategy.
  c                 C   s$   t j dd¡ d¡ || _|| _d S )Nr¹  ZTPUDistributedLookupTablerÄ   )r   Z'distribution_strategy_input_api_counterZget_cellZincrease_byÚ	_strategyÚ_host_to_resources)rI   r(   Zhost_to_resourcesr.   r.   r/   rK   Ó  s   ÿ
zPerWorkerResource.__init__c                    s&   |dvrt |  ¡ |ƒS tt| ƒ |¡S )N)rK   Ú__getattribute__r»  rº  Úlocal_resource)r   r½  r|   r¹  r¼  r€   r‚   r.   r/   r¼  Ù  s   z"PerWorkerResource.__getattribute__c                    s*   |dvrt |  ¡ ||ƒS tt| ƒ ||¡S )N)rº  r»  )Úsetattrr½  r|   r¹  Ú__setattr__)rI   r�   r)   r‚   r.   r/   r¿  ß  s   zPerWorkerResource.__setattr__c                 C   s<   t  t  ¡ ¡}t  t  |¡¡}| j || jtt| jƒƒ ¡S )z)Returns the resource on the local worker.)r   rY   rZ   Zget_host_for_devicer»  ÚgetÚnextÚiter)rI   r]   Zhost_devicer.   r.   r/   r½  ä  s   ÿþz PerWorkerResource.local_resource)	rq   ru   rv   rw   rK   r¼  r¿  r½  rµ   r.   r.   r‚   r/   r¹  Ë  s    r¹  rb  )Frw   rú   rñ   Ztensorflow.python.distributer   r   r   r3   r   ró   r   r   Ztensorflow.python.eagerr   Ztensorflow.python.frameworkr	   r
   r   r   Ztensorflow.python.opsr   r   r   r   r   r   r   rê   Ztensorflow.python.trackabler   rF  Z!tensorflow.python.training.savingr   Ztensorflow.python.typesr   r   Zds_typesr   r=   r7   r@   ry   rï   r$   r»   Z#register_tensor_conversion_functionZTypeSpecr¶   rÊ   ÚobjectrÏ   Z	TraceTyper×   ÚVariableZTensorræ   ZSaveableObjectrC  rn  rr  rz  r~  rž  rŸ  r   r¡  r¢  r¥  r°  r¹  r.   r.   r.   r/   Ú<module>   s˜   7>  ÿ
 ÿ    Nb >
ýÿ
ÿ
ÿ
ÿ! z