Ë
      çiÊu  ã            
       ó$  — d dl 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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.m/Z/m0Z0m1Z1 d dl2m3Z3 d dl4m5Z5 d dl6m7Z7m8Z8 d dl9m:Z:m;Z;m<Z< e
rd dl=m>Z> d dl?m@Z@ eAeBe      ZCeeCeeeDeEgeDf   f   ZF G d„ de'e0«      ZGded   deHdeHfd „ZIdeCd!ed"ededef
d#„ZJdeeC   deHdeHfd$„ZK G d%„ d&e/«      ZLy)'é    N)ÚAbstractContextManagerÚ	ExitStackÚnullcontext)Úpartial)ÚPath)ÚTYPE_CHECKINGÚAnyÚCallableÚLiteralÚOptionalÚUnion)ÚTensor)ÚModule)Ú	Optimizer)Ú
DataLoader)Úoverride)ÚAccelerator)Ú_XLA_AVAILABLE)ÚCheckpointIOÚ	PrecisionÚXLAPrecision)ÚXLAEnvironment)ÚXLACheckpointIO)ÚParallelStrategyÚ_StrategyRegistry)Ú_apply_filter)Ú_XLALauncher)Ú
TBroadcastÚ_BackwardSyncControlÚ_ShardedÚ!_validate_keys_for_strict_loading)Úget_filesystem)Ú
_EmptyInit)Úrank_zero_onlyÚrank_zero_warn)Ú_PATHÚOptimizableÚReduceOp)Ú_LRScheduler©ÚMpDeviceLoaderc                   óÚ  ‡ — e Zd ZdZ	 	 	 	 	 	 	 	 dKdee   deeej                        dee	   dee
   dee   dee   d	ed
   d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dLd„«       ZedLˆ fd„«       Z e	 dMde!dee"   ded   de#e!ee"   ed   f   fd „«       Z$ede!de!fd!„«       Z%ede!ddfd"„«       Z&dMd#ee   de'fd$„Z(ede'fd%„«       Z)ed&e*dd'fd(„«       Z+ed)e"de"fd*„«       Z,ed)e-dedefd+„«       Z.e	 	 dNde!d)e"d,e/e0ef   d-e/e0ef   d.ede1fd/„«       Z2ede!d)e"d0e/e0ef   ddfd1„«       Z3edOd2e1d3ee   d4ede1fd5„«       Z4e	 dPd6e/e1ef   d3ee   d7ee/e5e6f      de1fd8„«       Z7edMd9ee6   d:ededdfd;„«       Z8edQd<e9d=ede9fd>„«       Z:e	 	 dPd?e;d@e<e6e/e!e"ef   f   dAee   dBee<e6e=e6egef   f      ddf
dC„«       Z>d?e?d@e<e6e/e!e"ef   f   dAee   dBee<e6e=e6egef   f      ddf
dD„Z@e	 	 	 dRd?e;d@ee/e!e"e<e6e/e!e"ef   f   f      dEedFee   de<e6ef   f
dG„«       ZAeBedHeCddfdI„«       «       ZDde<fdJ„ZEˆ xZFS )SÚXLAFSDPStrategyaÔ  Strategy for training multiple XLA devices using the
    :func:`torch_xla.distributed.xla_fully_sharded_data_parallel.XlaFullyShardedDataParallel` method.

    .. warning::  This is an :ref:`experimental <versioning:Experimental API>` feature.

    For more information check out https://github.com/pytorch/xla/blob/v2.5.0/docs/fsdp.md

    Args:
        auto_wrap_policy: Same as ``auto_wrap_policy`` parameter in
            :class:`torch_xla.distributed.fsdp.XlaFullyShardedDataParallel`.
            For convenience, this also accepts a set of the layer classes to wrap.
        activation_checkpointing_policy: Used when selecting the modules for
            which you want to enable activation checkpointing. Enabling this can free up a significant amount of memory
            at the cost of speed since activations in these layers need to be recomputed during backpropagation.
            This accepts a set of the layer classes to wrap.

        state_dict_type: The format in which the state of the model and optimizers gets saved into the checkpoint.

            - ``"full"``: The full weights and optimizer states get assembled on rank 0 and saved to a single file.
            - ``"sharded"``: Each rank saves its shard of weights and optimizer states to a file. The checkpoint is
              a folder with files for each shard in the host. Note that TPU VM multihost does not have a shared
              filesystem.

        sequential_save: With this enabled, individual ranks consecutively save their state dictionary shards, reducing
            peak system RAM usage, although it elongates the saving process.
        \**kwargs: See available parameters in :class:`torch_xla.distributed.fsdp.XlaFullyShardedDataParallel`.

    NÚacceleratorÚparallel_devicesÚcheckpoint_ioÚ	precisionÚauto_wrap_policyÚactivation_checkpointing_policyÚstate_dict_type)ÚfullÚshardedÚsequential_saveÚkwargsÚreturnc	                 óì   •— t         st        t        t         «      «      ‚t        ‰
| �  ||t        «       ||¬«       t        «       | _        || _        || _	        |	| _
        || _        || _        d| _        y )N)r.   r/   Úcluster_environmentr0   r1   F)r   ÚModuleNotFoundErrorÚstrÚsuperÚ__init__r   Ú_XLAFSDPBackwardSyncControlÚ_backward_sync_controlÚ_auto_wrap_policyÚ _activation_checkpointing_policyÚ_fsdp_kwargsÚ_state_dict_typeÚ_sequential_saveÚ	_launched)Úselfr.   r/   r0   r1   r2   r3   r4   r7   r8   Ú	__class__s             €úy/Volumes/fast/ai/experiments/voice-extract-mac/.venv/lib/python3.12/site-packages/lightning_fabric/strategies/xla_fsdp.pyr?   zXLAFSDPStrategy.__init__T   sy   ø€ õ Ü%¤c¬.Ó&9Ó:Ð:Ü‰ÑØ#Ø-Ü .Ó 0Ø'Øð 	ô 	
ô 'BÓ&CˆÔ#à!1ˆÔØ0OˆÔ-Ø"ˆÔØ /ˆÔØ /ˆÔØˆ�ó    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   )rG   ÚRuntimeErrorÚtorch_xla.core.xla_modelÚcoreÚ	xla_modelÚ
xla_device)rH   Úxms     rJ   Úroot_devicezXLAFSDPStrategy.root_devicer   s)   € ð �~Š~ÜÐgÓhÐhß-Ð-à�}‰}‹ÐrK   c                 óH   — | j                   �t        | j                   «      S dS ©Nr   )r/   Úlen©rH   s    rJ   Únum_processeszXLAFSDPStrategy.num_processes{   s$   € à-1×-BÑ-BÐ-NŒs�4×(Ñ(Ó)ÐUÐTUÐUrK   c                 óZ   — | j                   }|�t        |t        «      sJ ‚|S t        «       S ©N)Ú_checkpoint_ioÚ
isinstancer   ©rH   Úplugins     rJ   r0   zXLAFSDPStrategy.checkpoint_io   s3   € ð ×$Ñ$ˆØÐÜ˜f¤oÔ6Ð6Ð6ØˆMÜÓ Ð rK   Úioc                 óR   — |�t        |t        «      st        d|› �«      ‚|| _        y )NzHThe XLA strategy can only work with the `XLACheckpointIO` plugin, found )r\   r   Ú	TypeErrorr[   )rH   r_   s     rJ   r0   zXLAFSDPStrategy.checkpoint_ioˆ   s/   € ð ˆ>¤*¨R´Ô"AÜÐfÐgiÐfjÐkÓlÐlØ ˆÕrK   c                 ó\   — | j                   }|�t        |t        «      sJ ‚|S t        d«      S )Nz32-true)Ú
_precisionr\   r   r]   s     rJ   r1   zXLAFSDPStrategy.precision�   s3   € ð —‘ˆØÐÜ˜f¤lÔ3Ð3Ð3ØˆMÜ˜IÓ&Ð&rK   c                 óR   — |�t        |t        «      st        d|› �«      ‚|| _        y )NzJThe XLA FSDP strategy can only work with the `XLAPrecision` plugin, found )r\   r   ra   rc   )rH   r1   s     rJ   r1   zXLAFSDPStrategy.precision˜   s/   € ð Ð ¬°I¼|Ô)LÜÐhÐirÐhsÐtÓuÐuØ#ˆ�rK   c                 ó4   •— | j                   r
t        ‰| �  S dS rU   )rG   r>   Úglobal_rank©rH   rI   s    €rJ   rf   zXLAFSDPStrategy.global_rankŸ   s   ø€ ð '+§n¢nŒu‰wÑ"Ð;¸!Ð;rK   c                 ó4   •— | j                   r
t        ‰| �  S dS rU   )rG   r>   Ú
local_rankrg   s    €rJ   ri   zXLAFSDPStrategy.local_rank¤   ó   ø€ ð &*§^¢^Œu‰wÑ!Ð:¸Ð:rK   c                 ó4   •— | j                   r
t        ‰| �  S dS rU   )rG   r>   Ú	node_rankrg   s    €rJ   rl   zXLAFSDPStrategy.node_rank©   s   ø€ ð %)§N¢NŒu‰wÑ Ð9¸Ð9rK   c                 ó4   •— | j                   r
t        ‰| �  S dS )Né   )rG   r>   Ú
world_sizerg   s    €rJ   ro   zXLAFSDPStrategy.world_size®   rj   rK   c                 ó$   — t        | «      | _        y rZ   )r   Ú	_launcherrW   s    rJ   Ú_configure_launcherz#XLAFSDPStrategy._configure_launcher³   s   € ä% dÓ+ˆ�rK   c                 óê   •— | j                   €J ‚t        | j                   «      dk(  r"t        dt        | «      j                  › d�«      ‚d| _        | j                  t        _        t        ‰| �)  «        y )Nrn   zThe zƒ does not support running on a single device with the PjRT runtime. Try using all devices or the `SingleDeviceXLAStrategy` strategyT)r/   rV   ÚNotImplementedErrorÚtypeÚ__name__rG   rf   r$   Úrankr>   Úsetup_environmentrg   s    €rJ   rx   z!XLAFSDPStrategy.setup_environment·   sw   ø€ à×$Ñ$Ð0Ð0Ð0Üˆt×$Ñ$Ó%¨Ò*ô &Ø”t˜D“z×*Ñ*Ð+ð ,Sð Sóð ð
 ˆŒØ"×.Ñ.ŒÔÜ‰Ñ!Õ#rK   ÚmoduleÚ
optimizersÚ	schedulerr)   c                 óF   — t        dt        | «      j                  › d�«      ‚)z]Returns NotImplementedError since for XLAFSDP optimizer setup must happen after module setup.zThe `z¯` does not support the joint setup of module and optimizer(s). Please do it in this order: Create the model, call `setup_module`, create the optimizer, call `setup_optimizer`.)rt   ru   rv   )rH   ry   rz   r{   s       rJ   Úsetup_module_and_optimizersz+XLAFSDPStrategy.setup_module_and_optimizersÆ   s-   € ô
 "Ø”D˜“J×'Ñ'Ð(ð )'ð 'ó
ð 	
rK   c                 óÈ   ‡— ddl mŠ | j                  «       }t        ˆfd„|j	                  «       D «       «      rd|v rt        d«       |d= t        |‰«      s
 ‰dd|i|¤Ž}|S )Nr   ©ÚXlaFullyShardedDataParallelc              3   ó6   •K  — | ]  }t        |‰«      –— Œ y ­wrZ   )r\   )Ú.0ÚmodÚXLAFSDPs     €rJ   Ú	<genexpr>z/XLAFSDPStrategy.setup_module.<locals>.<genexpr>Ö   s   øè ø€ ÐDÑ3C¨CŒz˜#˜w×'Ñ3Cùs   ƒr2   zoA XLAFSDP `auto_wrap_policy` is set, but at least one submodule is already wrapped. The policy will be ignored.ry   © )Útorch_xla.distributed.fsdpr€   Ú_parse_fsdp_kwargsÚanyÚmodulesr%   r\   )rH   ry   r8   r„   s      @rJ   Úsetup_modulezXLAFSDPStrategy.setup_moduleÑ   sk   ø€ åUà×(Ñ(Ó*ˆÜÓD°6·>±>Ô3CÓDÔDÐI[Ð_eÑIeÜð/ôð Ð)Ð*ä˜& 'Ô*ÙÑ5 FÐ5¨fÑ5ˆFØˆrK   c                  ó   — y rZ   r†   )rH   ry   s     rJ   Úmodule_to_devicez XLAFSDPStrategy.module_to_deviceá   s   € àrK   Ú
empty_initc                 óú   — | j                   j                  «       }| j                  «       }t        «       }|j	                  t        t        |«      ¬«      «       |j	                  |«       |j	                  |«       |S )N)Úenabled)r1   Úmodule_init_contextÚmodule_sharded_contextr   Úenter_contextr#   Úbool)rH   rŽ   Úprecision_init_ctxÚmodule_sharded_ctxÚstacks        rJ   r‘   z#XLAFSDPStrategy.module_init_contextå   sf   € Ø!Ÿ^™^×?Ñ?ÓAÐØ!×8Ñ8Ó:ÐÜ“ˆØ×ÑœJ¬t°JÓ/?Ô@ÔAØ×ÑÐ.Ô/Ø×ÑÐ.Ô/ØˆrK   c                 ó   — t        «       S rZ   )r   rW   s    rJ   r’   z&XLAFSDPStrategy.module_sharded_contextî   s
   € ä‹}ÐrK   Ú
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\   rS   Ú_loaderÚdatasetÚgetattrr›   )rH   r™   r+   s      rJ   Úprocess_dataloaderz"XLAFSDPStrategy.process_dataloaderò   sY   € åHä�j .Ô1àÐá# J°×0@Ñ0@ÓAˆ
à'×/Ñ/×7Ñ7ˆ
ÔÜ#*¨:×+=Ñ+=¸ÐPTÓ#Uˆ
Ô ØÐrK   Ú	optimizerc                 óT   — t        d„ |j                  D «       «      r|S t        d«      ‚)aL  Set up an optimizer for a model wrapped with XLAFSDP.

        This setup method doesn't modify the optimizer or wrap the optimizer. The only thing it currently does is verify
        that the optimizer was created after the model was wrapped with :meth:`setup_module` with a reference to the
        flattened parameters.

        c              3   óJ   K  — | ]  }|d    D ]  }t        |dd«      –— Œ Œ y­w)ÚparamsÚ_is_shardedFN)rŸ   )r‚   ÚgroupÚps      rJ   r…   z2XLAFSDPStrategy.setup_optimizer.<locals>.<genexpr>	  s.   è ø€ ÐmÑ=S°EÐ]bÐckÔ]lÐXYŒw�q˜-¨×/Ð]lÐ/Ñ=Sùs   ‚!#z„The optimizer does not seem to reference any XLAFSDP parameters. HINT: Make sure to create the optimizer after setting up the model.)r‰   Úparam_groupsÚ
ValueError)rH   r¡   s     rJ   Úsetup_optimizerzXLAFSDPStrategy.setup_optimizer   s0   € ô Ñm¸Y×=SÒ=SÓmÔmØÐÜð+ó
ð 	
rK   c                 ó\   —  |j                   di |¤Ž}ddlmc m} |j	                  «        |S )a(  Overrides default tpu optimizer_step since FSDP should not call `torch_xla.core.xla_model.optimizer_step`.
        Performs the actual optimizer step.

        Args:
            optimizer: the optimizer performing the step
            **kwargs: Any extra arguments to ``optimizer.step``

        r   Nr†   )ÚsteprN   rO   rP   Ú	mark_step)rH   r¡   r8   ÚlossrR   s        rJ   Úoptimizer_stepzXLAFSDPStrategy.optimizer_step  s+   € ð ˆy�~‰~Ñ' Ñ'ˆß-Ð-à
�‰ŒØˆrK   Úmax_normÚ	norm_typeÚerror_if_nonfinitec                 óŒ   — | j                   j                  |«       t        |j                  «      sJ ‚|j                  ||¬«      S )zClip gradients by norm.)r°   r±   )r1   Úunscale_gradientsÚcallableÚclip_grad_norm_)rH   ry   r¡   r°   r±   r²   s         rJ   Úclip_gradients_normz#XLAFSDPStrategy.clip_gradients_norm   s@   € ð 	�‰×(Ñ(¨Ô3Ü˜×.Ñ.Ô/Ð/Ð/Ø×%Ñ%¨xÀ9Ð%ÓMÐMrK   Úclip_valc                 ó   — t        d«      ‚)zClip gradients by value.z~XLA's FSDP strategy does not support to clip gradients by value. Consider clipping by norm instead or choose another strategy!)rt   )rH   ry   r¡   r¸   s       rJ   Úclip_gradients_valuez$XLAFSDPStrategy.clip_gradients_value.  s   € ô "ðMó
ð 	
rK   Útensorr¦   Ú
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)rG   r\   r   rt   ru   rv   ÚdimÚ	unsqueezeÚdeviceÚtorS   Útorch_xla.core.functionsrO   Ú	functionsrN   rP   Ú
all_gather)rH   r»   r¦   r¼   Úoriginal_deviceÚxfrR   s          rJ   rÅ   zXLAFSDPStrategy.all_gather6  s¼   € ð �~Š~ØˆMÜ˜&¤&Ô)Ü%Ø”D˜“J×'Ñ'Ð(Ð(\Ð]cÐ\dÐeóð ð �:‰:‹<˜1ÒØ×%Ñ% aÓ(ˆFØ Ÿ-™-ˆØ—‘˜4×+Ñ+Ó,ˆç-Ð-ß-Ð-á*4�—‘˜vÔ&¸"¿-¹-ÈÓ:OˆØ—‘˜?Ó+ˆØˆrK   Ú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)rÁ   )ÚsumÚmeanÚavgzaCurrently, the XLAFSDPStrategy only supports `sum`, `mean`, `avg` for the reduce operation, got: r   Úreduce)rÍ   rÌ   )r\   r   Útorchr»   rS   r(   ÚSUMr=   Úlowerr©   rN   rO   rP   Úmesh_reducerË   ro   )rH   rÈ   r¦   rÉ   Úinvalid_reduce_opÚinvalid_reduce_op_strrR   s          rJ   Ú
all_reducezXLAFSDPStrategy.all_reduceT  sÅ   € ô ˜&¤&Ô)Ü—\‘\ &°×1AÑ1AÔBˆFä& y´(Ó;ÒYÀ	ÌXÏ\É\Ñ@YÐÜ *¨9´cÓ :Ò n¸y¿¹Ó?PÐXnÐ?nÐÙÑ 5ÜðØ�;ð óð ÷ 	.Ð-à—‘ ¨&´#Ó6ˆä�i¤Ô%¨)¯/©/Ó*;¸Ñ*NØ˜dŸo™oÑ-ˆFàˆrK   ÚnameÚargsc                 óZ   — | j                   sy dd lmc m} |€d}|j	                  |«       y )Nr   Ú )rG   rN   rO   rP   Ú
rendezvous)rH   rÖ   r×   r8   rR   s        rJ   ÚbarrierzXLAFSDPStrategy.barrierk  s(   € à�~Š~Øß-Ð-àˆ<àˆDØ
�‰�dÕrK   Ú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   )rÁ   Údtype)Úroot_ordinal)rG   rN   rO   rP   r\   r   r¿   rÀ   rÁ   rÂ   rS   r_   ÚBytesIOrÏ   Úsaver»   Ú	bytearrayÚ	getbufferÚfloatÚcollective_broadcastÚcpuÚbyteÚnumpyÚload)rH   rÜ   rÝ   rR   Ú	is_tensorrÆ   Úbuffers          rJ   Ú	broadcastzXLAFSDPStrategy.broadcastv  s  € à�~Š~ØˆJç-Ð-ä˜s¤FÓ+ˆ	ÙØ�w‰w‹y˜AŠ~Ø—m‘m AÓ&�Ø!Ÿj™jˆOà—&‘&˜×)Ñ)Ó*‰Cô —Z‘Z“\ˆFÜ�J‰J�s˜FÔ#Ü—,‘,Ü˜&×*Ñ*Ó,Ó-°d×6FÑ6FÌeÏkÉkôˆCð ˆeˆØ
×Ñ °#ÐÔ6Ø�!‰fˆáä—Z‘Z §¡£	§¡Ó 0× 6Ñ 6Ó 8Ó9ˆFÜ—*‘*˜VÓ$ˆCð ˆ
ð —&‘&˜Ó)ˆCàˆ
rK   ÚpathÚstateÚstorage_optionsÚfilterc                 óz  — t        | j                  |«      «      }|j                  «       r't        |j	                  «       «      rt        d|› �«      ‚ddlm} |j                  «       D �cg c]  }t        ||«      sŒ|‘Œ }}t        |«      dk(  rt        d«      ‚t        |«      dkD  rt        d«      ‚ddlmc m} |j                  «        | j                   }	|	€J ‚| j"                  rRt%        t        |	«      «      D ]:  }
|
| j&                  k(  r| j)                  ||||«       | j+                  d|
› d	�«       Œ< n| j)                  ||||«       | j,                  d
k(  rÙt/        |dz  «      }d}t        |	«      | j0                  k7  rt3        d|›d|›d�«      ‚ddlm} | j+                  d«       | j6                  rj|j8                  dz  } |||t/        |«      «       | j:                  j=                  |«       t?        |«      jA                  t/        |«      t/        |«      «       | j+                  d«       yyc c}w )aˆ  Save model, optimizer, and other state in the provided checkpoint directory.

        If the user specifies sharded checkpointing, the directory will contain one file per process, with model- and
        optimizer shards stored per file. If the user specifies full checkpointing, the directory will contain a
        consolidated checkpoint combining all of the sharded checkpoints.

        z:The checkpoint directory already exists and is not empty: r   r   a  Could not find a XLAFSDP model in the provided checkpoint state. Please provide the model as part of the state like so: `save_checkpoint(..., state={'model': model, ...})`. Make sure you set up the model (and optimizers if any) through the strategy before saving the checkpoint.rn   zåFound multiple XLAFSDP modules in the given state. Saving checkpoints with FSDP is currently limited to a single model per checkpoint. To save multiple models, call the save method for each model separately with a different path.Nz	wait-for-z-saver5   Ú
checkpointz_rank-*-of-*.ptha  Multihost setups do not have a shared filesystem, so the checkpoint shards cannot be consolidated into a single checkpoint after saving them. Please switch to `XLAFSDPStrategy(state_dict_type='sharded')`. TIP: You can consolidate them manually by getting them together into a single directory and running `python -m torch_xla.distributed.fsdp.consolidate_sharded_ckpts --ckpt_prefix z --ckpt_suffix z* --save_path 'path/to/consolidated.ckpt'`.)Ú%consolidate_sharded_model_checkpointsÚbefore_ckpt_consolidationzconsolidated.ckptÚafter_ckpt_consolidation)!r   rí   Úis_dirr‰   ÚiterdirÚFileExistsErrorr‡   r€   Úvaluesr\   rV   r©   rN   rO   rP   r­   r/   rF   Úrangeri   Ú_save_checkpoint_shardrÛ   rE   r=   ro   ÚOSErrorrô   Úis_global_zeroÚparentr0   Úremove_checkpointr"   Úmv)rH   rî   rï   rð   rñ   r„   ry   rŠ   rR   r/   rw   Úckpt_prefixÚckpt_suffixrô   Ú	save_paths                  rJ   Úsave_checkpointzXLAFSDPStrategy.save_checkpoint™  s(  € ô  �D—N‘N 4Ó(Ó)ˆØ�;‰;Œ=œS §¡£Ô0Ü!Ð$^Ð_cÐ^dÐ"eÓfÐfÝUà(-¯©¬ÓV©˜f¼*ÀVÈWÕ:U’6¨ˆÐVÜˆw‹<˜1ÒÜðsóð ô
 ˆw‹<˜!ÒÜðPóð ÷
 	.Ð-ð 	�‰Œà×0Ñ0ÐØÐ+Ð+Ð+Ø× Ò äœcÐ"2Ó3Ö4�Ø˜4Ÿ?™?Ò*Ø×/Ñ/°°e¸_ÈfÔUØ—‘˜y¨¨¨eÐ4Õ5ñ 5ð
 ×'Ñ'¨¨e°_ÀfÔMà× Ñ  FÒ*Ü˜d \Ñ1Ó2ˆKØ,ˆKÜÐ#Ó$¨¯©Ò7Üð[ð \gÐZið jØ#�Ð&PðRóð õ Yà�L‰LÐ4Ô5Ø×"Ò"Ø ŸK™KÐ*=Ñ=�	á5°kÀ;ÔPSÐT]ÓP^Ô_à×"Ñ"×4Ñ4°TÔ:ä˜yÓ)×,Ñ,¬S°«^¼SÀ»YÔGØ�L‰LÐ3Õ4ð1 +ùò; Ws   Á*H8Á<H8c           	      óª  — ddl m} i }|j                  «       D ]z  \  }}t        |t        «      r0t        ||«      r$|j                  «       }	|j                  «       |d<   n#t        |t        «      r|j                  «       }	n|}	t        ||xs i |	|«       Œ| | j                  j                  ||d| j                  d›d| j                  d›d�z  |¬«       y )	Nr   r   Úshard_metadataúcheckpoint_rank-Ú08dú-of-ú.pth)rð   )r‡   r€   Úitemsr\   r   Ú
state_dictÚget_shard_metadatar   r   r0   r  rf   ro   )
rH   rî   rï   rð   rñ   r„   Úconverted_stateÚkeyrÜ   Ú	converteds
             rJ   rü   z&XLAFSDPStrategy._save_checkpoint_shardå  sÌ   € õ 	Và*,ˆØŸ™ž‰HˆC�ä˜#œvÔ&¬:°c¸7Ô+CØŸN™NÓ,�	à47×4JÑ4JÓ4L�Ð 0Ò1Ü˜C¤Ô+ØŸN™NÓ,‘	à�	Ü˜#˜vš|¨¨Y¸ÕHð &ð 	×Ñ×*Ñ*ØØÐ% d×&6Ñ&6°sÐ%;¸4ÀÇÁÐPSÐ?TÐTXÐYÑYØ+ð 	+õ 	
rK   ÚstrictÚweights_onlyc                 ó„  — |st        d|›d�«      ‚t        | j                  |«      «      }t        |t        t
        f«      rt        d«      ‚ddlm} |j                  «       D ��ci c]  \  }}t        ||«      sŒ||“Œ }}}|j                  «       D ��	ci c]  \  }}	t        |	t
        «      sŒ||	“Œ }
}}	| j                  dk(  �r¼|d| j                  d›d	| j                  d›d
�z  }|j                  «       st        dt        |«      ›d�«      ‚t        |«      dk(  rt        d«      ‚t        |«      dkD  rt        d«      ‚t!        |j                  «       «      d   \  }}t#        j$                  |«      }|j'                  |d   |¬«       |
j                  «       D ]  \  }}|j'                  ||   «       Œ |j)                  «       |j)                  «       z
  |
j)                  «       z
  }|j)                  «       |j)                  «       z
  |
j)                  «       z
  }t+        |||¬«       |D ]   }||v sŒ||   ||<   |j-                  |«       Œ" i }t        |«      r|D ]
  }||   ||<   Œ d|v r|j/                  d«       |S | j                  dk(  �r|j                  «       st        dt        |«      ›d�«      ‚t        |
«      dkD  s>t        |j)                  «       |j)                  «       z
  |
j)                  «       z
  «      dkD  rt1        d«       t        |«      dkD  rt        d«      ‚d|vs)t        |d   x}t"        j2                  j                  «      st        d«      ‚t#        j$                  ||¬«      }|j'                  |j/                  d«      |¬«       |S t        d| j                  › �«      ‚c c}}w c c}	}w )a  Given a folder, load the contents from a checkpoint and restore the state of the given objects.

        The strategy currently only supports saving and loading sharded checkpoints which are stored in form of a
        directory of multiple files rather than a single file.

        z0Got `XLAFSDPStrategy.load_checkpoint(..., state=zš)` but a state with at least  a model instance to reload is required. Pass it in like so: `FSDPStrategy.load_checkpoint(..., state={'model': model, ...})`zmLoading a single module or optimizer object from a checkpoint is not supported yet with the XLAFSDP strategy.r   r   r6   r  r	  r
  r  z	The path zv does not point to valid sharded checkpoints. Make sure the path points to a directory with XLAFSDP checkpoint shards.a  Could not find a XLAFSDP model in the provided checkpoint state. Please provide the model as part of the state like so: `load_checkpoint(..., state={'model': model, ...})`. Make sure you set up the model (and optimizers if any) through the strategy before loading the checkpoint.rn   zæFound multiple XLAFSDP modules in the given state. Loading checkpoints with FSDP is currently limited to a single model per checkpoint. To load multiple models, call the load method for each model separately with a different path.Úmodel)r  r  r5   zt does not point to a valid full checkpoint. Make sure the path points to a directory with a full XLAFSDP checkpoint.ztLoading a full checkpoint will only load the full model. The optimizer and any additional metadata are not included.zmFound a XLAFSDP model in the provided checkpoint state. Please provide the model without any XLAFSDP wrapper.zFXLAFSDP only supports a single model instance with 'model' as the key.)r  zUnknown state_dict_type: )r©   r   rí   r\   r   r   rt   r‡   r€   r  rE   rf   ro   Úis_filer=   rV   ÚlistrÏ   rê   Úload_state_dictÚkeysr!   ÚremoveÚpopr%   Únn)rH   rî   rï   r  r  r„   r  ry   rŠ   Úoptimrz   ÚfileÚ_Úsharded_ckptÚopt_keyÚoptÚloaded_metadata_keysÚrequested_metadata_keysÚmetadatar  Ú	full_ckpts                        rJ   Úload_checkpointzXLAFSDPStrategy.load_checkpoint  sÆ  € ñ ÜØBÀ5À)ð LTð Tóð ô �D—N‘N 4Ó(Ó)ˆä�eœf¤iÐ0Ô1Ü%ðCóð õ
 	Và27·+±+´-Ô_±-¡; 3¨Ä:ÈfÐV]ÕC^�3˜‘;°-ˆÑ_Ø38·;±;´=Ôa±=¡Z S¨%ÄJÈuÔV_ÕD`�c˜5‘j°=ˆ
ÑaØ× Ñ  IÓ-ØÐ,¨T×-=Ñ-=¸cÐ,BÀ$ÀtÇÁÐWZÐF[Ð[_Ð`Ñ`ˆDØ—<‘<”>Ü Ø¤ D£	˜}ð -Cð Cóð ô �7‹|˜qÒ Ü ðxóð ô
 �7‹|˜aÒÜ ðTóð ô ˜WŸ]™]›_Ó-¨aÑ0‰IˆAˆvÜ Ÿ:™: dÓ+ˆLà×"Ñ" <°Ñ#8ÀÐ"ÔHØ *× 0Ñ 0Ö 2‘�˜Ø×#Ñ# L°Ñ$9Õ:ð !3ð $0×#4Ñ#4Ó#6¸¿¹»Ñ#GÈ*Ï/É/ÓJ[Ñ#[Ð Ø&+§j¡j£l°W·\±\³^Ñ&CÀjÇoÁoÓFWÑ&WÐ#Ü-Ð.EÐG[ÐdjÕkÛ.�ØÐ.Ò.Ø!-¨cÑ!2�E˜#‘JØ(×/Ñ/°Õ4ð /ð
 ˆHÜÐ'Ô(Û/�CØ$0°Ñ$5�H˜S’Mð 0ð   8Ñ+Ø—‘Ð-Ô.àˆOà× Ñ  FÓ*Ø—<‘<”>Ü Ø¤ D£	˜}ð -Að Aóð ô �:‹ Ò"¤c¨%¯*©*«,¸¿¹»Ñ*GÈ*Ï/É/ÓJ[Ñ*[Ó&\Ð_`Ò&`ÜðSôô �7‹|˜aÒÜ ðMóð ð ˜eÑ#¬:¸uÀW¹~Ð6M°eÌuÏxÉxÏÉÔ+_Ü)Ð*rÓsÐsÜŸ
™
 4°lÔCˆIØ×!Ñ! )§-¡-°Ó"8ÀÐ!ÔHØÐäÐ4°T×5JÑ5JÐ4KÐLÓMÐMùóO `ùÛas   Á&N6Á;N6ÂN<Â/N<Ústrategy_registryc                 ó@   — |j                  d| | j                  ¬«       y )NÚxla_fsdp)Údescription)Úregisterrv   )Úclsr(  s     rJ   Úregister_strategiesz#XLAFSDPStrategy.register_strategiesj  s   € ð 	×"Ñ" :¨sÀÇÁÐ"ÕMrK   c                 óþ   — | j                   j                  «       }| j                  }t        |t        «      r|j                  d|j                  «       t        | j                  |«      }t        | j                  |«      S )NÚcompute_dtype)rD   Úcopyr1   r\   r   Ú
setdefaultÚ_desired_dtypeÚ_auto_wrap_policy_kwargsrB   Ú _activation_checkpointing_kwargsrC   )rH   r8   r1   s      rJ   rˆ   z"XLAFSDPStrategy._parse_fsdp_kwargso  sg   € à×"Ñ"×'Ñ'Ó)ˆØ—N‘Nˆ	Ü�i¤Ô.ð ×Ñ˜o¨y×/GÑ/GÔHÜ)¨$×*@Ñ*@À&ÓIˆÜ/°×0UÑ0UÐW]Ó^Ð^rK   )NNNNNNr6   F)r9   NrZ   )g       @T)NF)NN)r   )NTN)Grv   Ú
__module__Ú__qualname__Ú__doc__r   r   r  rÏ   rÁ   r   r   Ú_POLICYÚ_POLICY_SETr   r”   r	   r?   Úpropertyr   rS   ÚintrX   r0   Úsetterr   r1   r   rf   ri   rl   ro   rr   rx   r   r   Útupler}   r‹   r�   r   r‘   r’   r   r    rª   r'   r¯   r   rå   r   r·   rº   rÅ   r(   r=   rÕ   rÛ   r   rí   r&   Údictr
   r  r   rü   r'  Úclassmethodr   r.  rˆ   Ú__classcell__)rI   s   @rJ   r-   r-   6   sû  ø„ ñð> .2Ø9=Ø37Ø,0Ø.2ØAEØ6?Ø %ñà˜kÑ*ðð # 4¨¯©Ñ#5Ñ6ðð   Ñ0ð	ð
 ˜LÑ)ðð # 7Ñ+ðð *2°+Ñ)>ðð !Ð!2Ñ3ðð ðð ðð 
õð< Øð˜UŸ\™\ò ó ó ðð ðV˜sò Vó ðVð Øð!˜ò !ó ó ð!ð ×ÑØð! ¨Ñ 6ð !¸4ò !ó ó ð!ð
 Øð'˜<ò 'ó ó ð'ð ×ÑØð$ 8¨IÑ#6ð $¸4ò $ó ó ð$ð
 Øð<˜Sô <ó ó ð<ð Øð;˜Cô ;ó ó ð;ð Øð:˜3ô :ó ó ð:ð Øð;˜Cô ;ó ó ð;ð ò,ó ð,ð ô$ó ð$ð àaeñ
Øð
Ø*.¨y©/ð
ØFNÈ~ÑF^ð
à	ˆv�t˜I‘¨°Ñ(@Ð@Ñ	Aò
ó ð
ð ð 6ð ¨fò ó ðð ð vð °$ò ó ðñ¨h°t©nð ÐH^ó ð ðÐ(>ò ó ðð ð¨Zð Ð<Lò ó ðð ð
¨ð 
°yò 
ó ð
ð ð¨ð ¸sð Àsò ó ðð ð (+Ø#'ñNàðNð ðNð ˜˜s˜
Ñ#ð	Nð
 ˜ ˜Ñ$ðNð !ðNð 
òNó ðNð ð
¨6ð 
¸ið 
ÐSXÐY^Ð`cÐYcÑSdð 
Ðimò 
ó ð
ð ñ ð °¸±ð ÐRVð Ðciò ó ðð: àswñØ˜F C˜KÑ(ðØ19¸#±ðØRZÐ[`ÐaiÐknÐanÑ[oÑRpðà	òó ðð, ñ˜H S™Mð ¸ð Èð ÐPTò ó ðð ñ ˜Zð  ¨cð  ¸*ò  ó ð ðD ð
 *.ØBFñI5àðI5ð �C˜˜v y°#Ð5Ñ6Ð6Ñ7ðI5ð " #™ð	I5ð
 ˜˜c 8¨S°#¨J¸Ð,<Ñ#=Ð=Ñ>Ñ?ðI5ð 
òI5ó ðI5ðV
àð
ð �C˜˜v y°#Ð5Ñ6Ð6Ñ7ð
ð " #™ð	
ð
 ˜˜c 8¨S°#¨J¸Ð,<Ñ#=Ð=Ñ>Ñ?ð
ð 
ó
ð8 ð _cØØ'+ñfNàðfNð ˜˜f i°°c¸5ÀÈÐTWÐAWÑ;XÐ6XÑ1YÐYÑZÑ[ðfNð ð	fNð
 ˜t‘nðfNð 
ˆc�3ˆh‰òfNó ðfNðP ØðNÐ4Eð NÈ$ò Nó ó ðNð	_ D÷ 	_rK   r-   Úpolicyr9  r8   r9   c                 ó^   — | €|S t        | t        «      rddlm} t	        || ¬«      } | |d<   |S )Nr   )Útransformer_auto_wrap_policy)Útransformer_layer_clsr2   )r\   ÚsetÚtorch_xla.distributed.fsdp.wraprD  r   )rB  r8   rD  s      rJ   r4  r4  {  s8   € Ø€~ØˆÜ�&œ#ÔÝPô Ð5ÈVÔTˆØ!'€FÐÑØ€MrK   ry   r×   c                 óp   — ddl m} ddl m} t        |t	        | «      «      r ||«      n|} ||g|¢­i |¤ŽS )Nr   r   )Úcheckpoint_module)r‡   r€   rI  r\   r>  )rB  ry   r×   r8   r„   rI  s         rJ   Ú&_activation_checkpointing_auto_wrapperrJ  ‡  s8   € ÝQÝ<ä*4°V¼UÀ6»]Ô*KÑ˜vÔ&ÐQW€FÙ�6Ð+˜DÒ+ FÑ+Ð+rK   c                 ó”   — | s|S d|v rt        d«      ‚t        | t        «      st        d| › d�«      ‚t	        t
        | «      }||d<   |S )NÚauto_wrapper_callablez]You cannot set both `auto_wrapper_callable` and `activation_checkpointing_policy`. Choose onez7`activation_checkpointing_policy` must be a set, found zC. You can try defining and passing `auto_wrapper_callable` instead.)r©   r\   rF  ra   r   rJ  )rB  r8   rL  s      rJ   r5  r5  �  sm   € ÙØˆØ &Ñ(ÜØkó
ð 	
ô �fœcÔ"ÜØEÀfÀXð N8ð 8ó
ð 	
ô $Ô$JÈFÓSÐØ&;€FÐ"Ñ#Ø€MrK   c                   ó*   — e Zd Zedededefd„«       Zy)r@   ry   r�   r9   c                 óÒ   — |s
t        «       S ddlm} t        ||«      s:t	        d| j
                  j                  › d|j
                  j                  › d�«      ‚|j                  «       S )z|Blocks gradient synchronization inside the :class:`~torch_xla.distributed.fsdp.XlaFullyShardedDataParallel`
        wrapper.r   r   zABlocking backward sync is only possible if the module passed to `zE.no_backward_sync` is wrapped in `XlaFullyShardedDataParallel`. Got: Ú.)r   r‡   r€   r\   ra   rI   rv   Úno_sync)rH   ry   r�   r„   s       rJ   Úno_backward_syncz,_XLAFSDPBackwardSyncControl.no_backward_sync¡  sk   € ñ Ü“=Ð ÝUä˜& 'Ô*ÜðØ—^‘^×,Ñ,Ð-ð .Ø×)Ñ)×2Ñ2Ð3°1ð6óð ð
 �~‰~ÓÐrK   N)rv   r6  r7  r   r   r”   r   rQ  r†   rK   rJ   r@   r@      s*   „ Øð  vð  ¸ð  ÐAWò  ó ñ rK   r@   )Mr_   Ú
contextlibr   r   r   Ú	functoolsr   Úpathlibr   Útypingr   r	   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.fsdpr   Ú)lightning_fabric.strategies.launchers.xlar   Ú$lightning_fabric.strategies.strategyr   r   r    r!   Ú#lightning_fabric.utilities.cloud_ior"   Úlightning_fabric.utilities.initr#   Ú$lightning_fabric.utilities.rank_zeror$   r%   Ú lightning_fabric.utilities.typesr&   r'   r(   Útorch.optim.lr_schedulerr)   rœ   r+   rF  ru   r:  r”   r<  r9  r-   r?  r4  rJ  r5  r@   r†   rK   rJ   Ú<module>rh     s&  ðó 
ß EÑ EÝ Ý ß I× Iã Ý Ý Ý !Ý 'Ý &å 5Ý <ß JÑ JÝ @Ý ;ß KÝ :Ý B÷ó õ ?Ý 6ß Oß IÑ IáÝ5ÝDà�$�v‘,Ñ€Ø
�˜X v¨t°SÐ&9¸4Ð&?Ñ@Ð@Ñ
A€ôB	_Ð&¨ô B	_ðJ	 X¨iÑ%8ð 	À$ð 	È4ó 	ð,°;ð ,Èð ,ÐWZð ,Ðfið ,Ðntó ,ð¨X°kÑ-Bð ÈDð ÐUYó ô" Ð"6õ  rK   