
    &Vf%                     d    d Z ddlZddlZddlmZ ddZd Zd Zd Z	d Z
d	 Zd
 Zd Zd Zd ZdS )z!!!DO NOT USE!!!

Distribution related class for JAX backend.

This is just a prototype and we might want to unify it
with other backends in the future.
    N)	jax_utilsc                 t    | r|                                  nd} t          j        |           }d |D             S )a  Return all the available devices based on the device type.

    Note that this should return the global devices in a distributed setting.

    Args:
        device_type: string of `"cpu"`, `"gpu"` or `"tpu"`. Defaults to `"gpu"`
            or `"tpu"` if available when device_type is not provided. Otherwise
            will return the `"cpu"` devices.

    Return:
        List of devices that are available for distribute computation.
    Nbackendc                 0    g | ]}|j          d |j         S ):)platformid).0devices     c/var/www/html/software/conda/lib/python3.11/site-packages/keras/src/backend/jax/distribution_lib.py
<listcomp>z list_devices.<locals>.<listcomp>   s*    GGGv,,,,GGG    )lowerjaxdevices)device_typejax_devicess     r   list_devicesr      sE     *5>+##%%%$K+k222KGG;GGGGr   c                 `    t          |t          j        j                  st	          |          }t           t          j        t          j        j        f          r0 j                            |t           j
                            r S |j        rt          j         |          S |                     j
                  }t          j         fd|                                D             t          |                                                    }t          j         j
        ||          }|S )a  Create a distributed variable for JAX.

    Since JAX doesn't have a variable class, this will just return a `jax.Array`
    with the corresponding layout/sharding specified.

    Note that this function should be used in eager context, not in jitted
    function.

    Args:
        value: the initial value of the variable.
        layout: `TensorLayout` for the created variable, or a
            `jax.sharding.Sharding` instance.

    Returns:
        jax.Array which is the distributed variable.
    )ndimc                      g | ]
}|         S  r   )r   ivalues     r   r   z'distribute_variable.<locals>.<listcomp>A   s    000!U1X000r   )
isinstancer   shardingSharding_to_jax_layoutArraynumpyndarrayis_equivalent_tolenshapeis_fully_addressable
device_putaddressable_devices_indices_mapvalueslistkeys$make_array_from_single_device_arrays)r   layoutmappinglocal_valuesglobal_values   `    r   distribute_variabler1   !   s   " fcl344 (''	39,-  
.
)
)&s5;7G7G
)
H
H " ~eV,,, 88EE~0000w~~//000$w||~~2F2F
 
 ?K
 
 r   c                     t          |t          j        j                  st	          |          }t          j                    r t          j                             |          S |j	        rt          j
         |          S |                     j                  }t          j
         fd|                                D             t          |                                                    }t          j         j        ||          }|S )aq  Distribute the tensor based on the layout.

    Note that this function can be used both in eager context, or within a
    jitted function.

    Args:
        tensor: `jax.Array` that need to be distributed.
        layout: `TensorLayout` for the distribution information, or a
            `jax.sharding.Sharding` instance.

    Returns:
        Distributed value.
    c                      g | ]
}|         S r   r   )r   r   tensors     r   r   z%distribute_tensor.<locals>.<listcomp>e   s    1111VAY111r   )r   r   r   r   r   r   is_in_jax_tracing_scopelaxwith_sharding_constraintr&   r'   r(   r%   r)   r*   r+   r,   )r4   r-   r.   r/   r0   s   `    r   distribute_tensorr8   I   s     fcl344 ('' (** @w//???" ~ff--- 88FF~1111 0 011143G3G
 
 ?L&,
 
 r   c           	          t          |t          j        j                  st	          |          }|j        rt          j         |          S |j        }t          |j	                  } j	        d         }|dk    rot          j
                    }||z  }||z  dk    rt          d| d|           |t          j                    z  }t          j                             |d          }n|dk    rt          |j	                                                  d         }	t          j
                    }
|	|
k     r|} fdt#          |
          D             }nB||	|
z  z  }t          j                             |
d          }nt          d|j	                   |f j	        dd	         z   }t          j        ||d
 t'          ||j                  D                       }|S )a  Distribute the input data with the corresponding layout.

    Note that the inputs here is a local worker batch. Within the local worker,
    the data need to be further partitioned to map to the each of the devices.

    Args:
        inputs: `jax.Array` that is already sharded to a local process size.
        layout: `TensorLayout` for the distribution information, or a
            `jax.sharding.Sharding` instance.

    Returns:
        Distributed inputs thats been properly put to local devices.
    r      zThe local batch size z1 is notdivisible by the number of local replicas )axis   c                     g | ]}S r   r   )r   _inputss     r   r   z)distribute_data_input.<locals>.<listcomp>   s    "M"M"Ma6"M"M"Mr   zEOnly 1D or 2D mesh is supported at the moment. Received mesh shape = Nc                 >    g | ]\  }}t          j        ||          S r   )r   r'   )r   batchr   s      r   r   z)distribute_data_input.<locals>.<listcomp>   s8     
 
 
v N5&))
 
 
r   )arrays)r   r   r   r   r   r&   r'   meshr$   r%   local_device_count
ValueErrorprocess_countr!   splitr*   r)   ranger,   zipaddressable_devices)r?   r-   jax_mesh	mesh_rankper_process_batch_size	num_splitper_replica_batch_sizeglobal_batch_sizeper_replica_batchesmesh_batch_dim_sizerD   global_shapeglobal_batch_arrays   `            r   distribute_data_inputrU   m   sJ    fcl344 (''" .~ff--- {HHN##I#\!_A~~ *,,	!79!D!$::a??(>     
 3S5F5H5HH!ioofiaoHH	a #8>#8#8#:#:;;A> 355!333 6"M"M"M"M59K3L3L"M"M"M !7#'99! #&)//* #2 # # 6%-^6 6
 
 	

 &'&,qrr*::LA
 
!$#V%?" "
 
 
	 	 	 r   c                 
   | r\d| v rX|                      d          } |8|t          |           k    r%t          d|  dt          |            d|           | d         }n| }t          j                            |||           d S )N,zThe provided job_addresses z has z jobs, but num_processes is r   )coordinator_addressnum_processes
process_id)rG   r$   rE   r   distributed
initialize)job_addressesrY   rZ   rX   s       r   r\   r\      s     ,-- &++C00 $#m:L:L)L)L#m # #}%%# # # #  
 ,A.+O/#      r   c                  (    t          j                    S )zDReturn the number of processes for the current distribution setting.)r   rF   r   r   r   rY   rY          r   c                  (    t          j                    S )z;Return the current process ID for the distribution setting.)r   process_indexr   r   r   rZ   rZ      r_   r   c                    t          | t          j                  r| S |                     d          \  }}t	          |          }t          j        |          }|t          |          k    rt          d|            ||         S )Nr   r   zUnknown device: )r   r   DevicerG   intr   r$   rE   )	device_idr   indexr   s       r   _to_jax_devicerg      s    )SZ(( "--KJJEk+...GG7I778885>r   c                     | j         j        }d | j                                         D             }t          j        |                              |          }t          j                            || j	                  S )zConvert the DeviceMesh to JAX backend specific Mesh.

    Args:
        device_mesh: DeviceMesh instance to convert.

    Returns:
        A `jax.sharding.Mesh` instance.
    c                 ,    g | ]}t          |          S r   )rg   )r   ds     r   r   z _to_jax_mesh.<locals>.<listcomp>   s     HHHQ~a  HHHr   )
r   r%   flattennparrayreshaper   r   Mesh
axis_names)device_meshr%   r   s      r   _to_jax_meshrr      si     %EHH+*=*E*E*G*GHHHGhw''..G<Wk&<===r   c                     | j         t          d          t          j        j        | j         }t          | j                   }t          j                            ||          S )zConvert the TensorLayout to JAX backend specific Sharding.

    Args:
        tensor_layout: TensorLayout instance to convert.

    Returns:
        A `jax.sharding.NamedSharding` instance.
    NzDCannot create sharding when device mesh is not set for TensorLayout.)rq   rE   r   r   PartitionSpecaxesrr   NamedSharding)tensor_layoutpartition_specrK   s      r   r   r      s`      ( 
 
 	
 \/1CDNM566H<%%h???r   )N)__doc__r   r!   rl   keras.src.utilsr   r   r1   r8   rU   r\   rY   rZ   rg   rr   r   r   r   r   <module>r{      s     


     % % % % % %H H H H$% % %P! ! !HN N Nb  0  
  
  > > >@ @ @ @ @r   