
      i,                        d dl Z d dlmZmZmZmZm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mZmZ d dlmZ d dlmZ d dlmZmZ d dl m!Z! d dl"m#Z# d dl$m%Z% d dl&m'Z'm(Z( erd dl)m*Z*  G d de      Z+y)    N)TYPE_CHECKINGAnyCallableOptionalUnion)Tensor)Module)	Optimizer)
DataLoader)override)Accelerator)_XLA_GREATER_EQUAL_2_1)CheckpointIO	PrecisionXLAPrecision)XLAEnvironment)XLACheckpointIO)ParallelStrategy_StrategyRegistry)_XLALauncher)
TBroadcast)rank_zero_only)_PATHReduceOpMpDeviceLoaderc                       e Zd ZdZ	 	 	 	 	 d2dee   deeej                        dee	   dee
   deddf fd	Zeedej                  fd
              Zedefd       Zeede	fd              Zej&                  edee   ddfd              Zeede
fd              Zej&                  edee   ddfd              Zeedef fd              Zeedef fd              Zeedef fd              Zeedef fd              Zed3d       Zed3 fd       Zededefd       Zededdfd       Zede ddfd       Z!ed4de"dee#   dede"fd        Z$e	 d5d!e%e"e#f   dee#   d"ee%e&e'f      de"fd#       Z(ed6d$ee'   d%e#d&e#ddfd'       Z)ed7d(e*d)ede*fd*       Z+e	 	 d5d+e,d,e-e'e%ee.e#f   f   d-ee#   d.ee-e'e/e'e#gef   f      ddf
 fd/       Z0e1ed0e2ddfd1              Z3 xZ4S )8XLAStrategyzxStrategy for training multiple TPU devices using the :func:`torch_xla.distributed.xla_multiprocessing.spawn`
    method.Nacceleratorparallel_devicescheckpoint_io	precisionsync_module_statesreturnc                 h    t         |   ||t               ||       d | _        d| _        || _        y )N)r   r    cluster_environmentr!   r"   F)super__init__r   _backward_sync_control	_launched_sync_module_states)selfr   r    r!   r"   r#   	__class__s         t/Volumes/fast/ai/experiments/voice-extract-mac/.venv/lib/python3.12/site-packages/lightning/fabric/strategies/xla.pyr(   zXLAStrategy.__init__+   sB     	#- . 0' 	 	
 '+##5     c                 b    | j                   st        d      dd lmc m} |j                         S )NzFAccessing the XLA device before processes have spawned is not allowed.r   )r*   RuntimeErrortorch_xla.core.xla_modelcore	xla_model
xla_device)r,   xms     r.   root_devicezXLAStrategy.root_device>   s)     ~~ghh--}}r/   c                 H    | j                   t        | j                         S dS Nr   )r    lenr,   s    r.   num_processeszXLAStrategy.num_processesG   s$    -1-B-B-Ns4(()UTUUr/   c                 Z    | j                   }|t        |t              sJ |S t               S N)_checkpoint_io
isinstancer   r,   plugins     r.   r!   zXLAStrategy.checkpoint_ioK   s3     $$fo666M  r/   ioc                 R    |t        |t              st        d|       || _        y )NzHThe XLA strategy can only work with the `XLACheckpointIO` plugin, found )r@   r   	TypeErrorr?   )r,   rC   s     r.   r!   zXLAStrategy.checkpoint_ioT   s/     >*R"Afgifjkll r/   c                 \    | j                   }|t        |t              sJ |S t        d      S )Nz32-true)
_precisionr@   r   rA   s     r.   r"   zXLAStrategy.precision[   s3     fl333MI&&r/   c                 R    |t        |t              st        d|       || _        y )NzEThe XLA strategy can only work with the `XLAPrecision` plugin, found )r@   r   rE   rG   )r,   r"   s     r.   r"   zXLAStrategy.precisiond   s/      I|)Lcdmcnopp#r/   c                 4    | j                   r
t        |   S dS r9   )r*   r'   global_rankr,   r-   s    r.   rJ   zXLAStrategy.global_rankk   s     '+nnuw";!;r/   c                 4    | j                   r
t        |   S dS r9   )r*   r'   
local_rankrK   s    r.   rM   zXLAStrategy.local_rankp        &*^^uw!::r/   c                 4    | j                   r
t        |   S dS r9   )r*   r'   	node_rankrK   s    r.   rP   zXLAStrategy.node_ranku   s     %)NNuw 99r/   c                 4    | j                   r
t        |   S dS )N   )r*   r'   
world_sizerK   s    r.   rS   zXLAStrategy.world_sizez   rN   r/   c                 $    t        |       | _        y r>   )r   	_launcherr;   s    r.   _configure_launcherzXLAStrategy._configure_launcher   s    %d+r/   c                     | j                   J t        | j                         dk(  r"t        dt        |       j                   d      d| _        | j                  t        _        t        | )          y )NrR   zThe z does not support running on a single device with the PjRT runtime. Try using all devices or the `SingleDeviceXLAStrategy` strategyT)r    r:   NotImplementedErrortype__name__r*   rJ   r   rankr'   setup_environmentrK   s    r.   r\   zXLAStrategy.setup_environment   sw    $$000t$$%* &tDz**+ ,S S 
 "..!#r/   modulec                 T    | j                   rt        rddlm} nddlm}  ||       |S )Nr   )broadcast_master_param)r+   r   r2   r_   torch_xla.experimental.pjrt)r,   r]   r_   s      r.   setup_modulezXLAStrategy.setup_module   s!    ##%KN"6*r/   c                 :    |j                  | j                         y r>   )tor7   )r,   r]   s     r.   module_to_devicezXLAStrategy.module_to_device   s    		$""#r/   
dataloaderr   c                     ddl m} t        ||      r|S  ||| j                        }|j                  j
                  |_        t        |j                  dd       |_        |S )Nr   r   batch_sampler)%torch_xla.distributed.parallel_loaderr   r@   r7   _loaderdatasetgetattrrg   )r,   re   r   s      r.   process_dataloaderzXLAStrategy.process_dataloader   sY    Hj.1#J0@0@A
'//77
#*:+=+=PT#U
 r/   tensorgroup
sync_gradsc                    | j                   s|S t        |t              s$t        dt	        |       j
                   d|       |j                         dk(  r|j                  d      }|j                  }|j                  | j                        }ddlmc m} ddlmc m} |r|j!                  |      n|j!                  |      }|j                  |      }|S )aC  Function to gather a tensor from several distributed processes.

        Args:
            tensor: tensor to all-gather.
            group: unused.
            sync_grads: flag that allows users to synchronize gradients for the all-gather operation.
        Return:
            A tensor of shape (world_size, ...)

        `z4.all_gather` is only implemented for tensors. Given r   N)r*   r@   r   rX   rY   rZ   dim	unsqueezedevicerc   r7   torch_xla.core.functionsr3   	functionsr2   r4   
all_gather)r,   rm   rn   ro   original_devicexfr6   s          r.   rw   zXLAStrategy.all_gather   s     ~~M&&)%DJ''((\]c\de  ::<1%%a(F --4++,----*4v&"--:O?+r/   output	reduce_opc                    t        |t              s!t        j                  || j                        }t        |t
              xr |t
        j                  k7  }t        |t              xr |j                         dv}|s|rt        d|       dd l
mc m} |j                  d|t              }t        |t              r!|j                         dv r|| j                  z  }|S )N)rt   )summeanavgz]Currently, the XLAStrategy only supports `sum`, `mean`, `avg` for the reduce operation, got: r   reduce)r   r~   )r@   r   torchrm   r7   r   SUMstrlower
ValueErrorr2   r3   r4   mesh_reducer}   rS   )r,   rz   rn   r{   invalid_reduce_opinvalid_reduce_op_strr6   s          r.   
all_reducezXLAStrategy.all_reduce   s     &&)\\&1A1ABF&y(;Y	X\\@Y *9c : ny?PXn?n 5;   	.-&#6i%)//*;*Ndoo-Fr/   nameargskwargsc                 Z    | j                   sy dd lmc m} |d}|j	                  |       y )Nr    )r*   r2   r3   r4   
rendezvous)r,   r   r   r   r6   s        r.   barrierzXLAStrategy.barrier   s(    ~~--<D
dr/   objsrcc                    | j                   s|S dd lmc m} t	        |t
              }|rL|j                         dk(  r|j                  d      }|j                  }|j                  | j                        }nqt        j                         }t        j                  ||       t        j                  t!        |j#                               | j                  t        j$                        }|g}|j'                  ||       |d   }|sVt        j                  |j)                         j+                         j-                               }t        j.                  |      }|S |j                        }|S )Nr   )rt   dtype)root_ordinal)r*   r2   r3   r4   r@   r   rr   rs   rt   rc   r7   rC   BytesIOr   saverm   	bytearray	getbufferfloatcollective_broadcastcpubytenumpyload)r,   r   r   r6   	is_tensorrx   buffers          r.   	broadcastzXLAStrategy.broadcast   s   ~~J--sF+	wwyA~mmA&!jjO&&))*C ZZ\FJJsF#,,&**,-d6F6FekkC e
#6!fZZ	 0 6 6 89F**V$C 
 &&)C
r/   pathstatestorage_optionsfilterc                 ^    ddl mc m} |j                          t        |   ||||       y)a  Save model, optimizer, and other state as a checkpoint file.

        Args:
            path: A path to where the file(s) should be saved
            state: A dictionary with contents to be saved. If the dict contains modules or optimizers, their
                state-dict will be retrieved and converted automatically.
            storage_options: Additional options for the ``CheckpointIO`` plugin
            filter: An optional dictionary of the same format as ``state`` mapping keys to callables that return a
                boolean indicating whether the given parameter should be saved (``True``) or filtered out (``False``).

        r   N)r   r   )r2   r3   r4   	mark_stepr'   save_checkpoint)r,   r   r   r   r   r6   r-   s         r.   r   zXLAStrategy.save_checkpoint  s-    & 	.- 	e_U[\r/   strategy_registryc                 @    |j                  d| | j                         y )Nxla)description)registerrZ   )clsr   s     r.   register_strategieszXLAStrategy.register_strategies-  s     	""5#3<<"Hr/   )NNNNT)r$   N)NF)NNr>   )r   )5rZ   
__module____qualname____doc__r   r   listr   rt   r   r   boolr(   propertyr   r7   intr<   r!   setterr   r"   r   rJ   rM   rP   rS   rV   r\   r	   ra   rd   r   rl   r   r   rw   r   r   r   r   r   r   r   r   dictr
   r   r   classmethodr   r   __classcell__)r-   s   @r.   r   r   '   s)   
 .29=37,0#'6k*6 #4#566  0	6
 L)6 !6 
6& U\\    Vs V V ! !  ! ! 6 !4 !  !
 '< '  ' $8I#6 $4 $  $
 <S <  < ;C ;  ; :3 :  : ;C ;  ; , , $ $ 	6 	f 	 	 $v $$ $ $ Z <L     RV ci  : swFCK(19#RZ[`aiknan[oRp	 , HSM   PT    Z  c  *    D 
 *.BF]] Cvy#5667] "#	]
 c8S#J,<#==>?] 
] ]2 I4E I$ I  Ir/   r   ),rC   typingr   r   r   r   r   r   r   torch.nnr	   torch.optimr
   torch.utils.datar   typing_extensionsr   lightning.fabric.acceleratorsr   !lightning.fabric.accelerators.xlar   lightning.fabric.pluginsr   r   r   %lightning.fabric.plugins.environmentsr   lightning.fabric.plugins.io.xlar   lightning.fabric.strategiesr   r   )lightning.fabric.strategies.launchers.xlar   $lightning.fabric.strategies.strategyr   $lightning.fabric.utilities.rank_zeror    lightning.fabric.utilities.typesr   r   rh   r   r    r/   r.   <module>r      sZ    
 @ @    ! ' & 5 D J J @ ; K B ; ? <DII" IIr/   