
    ͑i{                       S SK Jr  S SKrS SKJrJrJr  SSKJrJ	r	  SSK	J
r
JrJr  \(       a)  S SKJrJr  S SKJr  S S	KJr   " S
 S\5      r " S S\SS9r/ r\R.                  R0                  r\R2                  r\R6                  r\R:                  rS rS rS r S r!S r" " S S5      r " S S5      r# " S S5      r$ " S S5      r%g)    )annotationsN)TYPE_CHECKINGAny	TypedDict   )core	framework)
cpu_placescuda_places
xpu_places)Graph_Scope)	Optimizer)Programc                  >    \ rS rSr% S\S'   S\S'   S\S'   S\S'   Srg	)
	_CustomOp   str	paddle_op	popart_opdomainintversion N__name__
__module____qualname____firstlineno____annotations____static_attributes__r       T/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/paddle/base/compiler.pyr   r      s    r"   r   c                  8   \ rS rSr% S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S	'   S\S
'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S '   S\S!'   S"\S#'   S$rg%)&_IpuStrategyOptions"   boolis_trainingneed_avg_shardenable_fp16use_no_bias_optimizerenable_distributionscaled_optimizer_state
is_dynamicenable_model_runtime_executorr   num_ipusbatches_per_stepmicro_batch_sizerandom_seedtiles_per_ipunum_buffersfloatavailable_memory_proportionloss_scalingmax_weight_norm
timeout_mslrr   
accl1_type
accl2_type
accl3_typeonnx_dump_pathweight_decay_modeenable_pipeliningenable_gradient_accumulationaccumulation_factorenable_manual_shardr   	custom_opr   Nr   r   r"   r#   r%   r%   "   s    ##!! $$'++%**	&**  !!r"   r%   F)totalc                R    [         R                  " 5       nUR                  U 5        U$ N)r   Place	set_place)placeps     r#   
_place_objrM   J   s    

AKKHr"   c                    U R                  5        Ha  nUR                  5       (       d  M  UR                  5       c  M-  UR                  5       R                  5       R	                  S5      (       d  Ma    g   g)N_gradTF)nodesis_opoptypeendswith)graphnodes     r#   _has_backward_oprW   P   sO    JJLL	%	 ))'22  r"   c                   / n[        U R                  5       R                  5       H(  u  p#UR                  S:X  d  M  UR	                  U5        M*     US S S2    H"  nU R                  5       R                  U5        M$     g )Nfeed)	enumerateglobal_blockopsrS   append
_remove_op)programpop_idxirR   indexs        r#   _prune_feed_opsrd   [   sj    G7//155677fNN1 7 2))%0 r"   c                D   U R                    H  n[        R                  n[        R                  R                  R                  nUR                  5       UR                  ;   d  MW  [        UR                  5       UR                  5          5      [        U5      :X  d  M    g   g)NTF)
r]   r   op_proto_and_checker_makerOpRoleOptimizekOpRoleVarAttrName
attr_namesr   	all_attrskOpRoleAttrName)blockrR   op_makeroptimizes       r#   _has_optimize_oprp   e   s{    ii222299BB&&(BMM9cLLN83356?
]?   r"   c                    U R                  5       nUR                  R                  US 5      nUc  g[        USS5      =(       d    [        USS5      nU(       + $ )NT_is_distributedFis_distributed)r\   varsgetgetattr)r`   var_namerm   varrs   s        r#   _should_broadcast_or_not_existsry   p   s[      "E
**..4
(C
{S"3U; wu@N r"   c                  Z    \ rS rSrSr S     SS jjrS rS rSS jrS r	S	 r
S
 rSrg)CompiledProgram{   a  
:api_attr: Static Graph

The CompiledProgram is used to transform a program or graph for
various optimizations according to the configuration of build_strategy,
for example, the operators' fusion in the computation graph, memory
optimization during the execution of the computation graph, etc.
For more information about build_strategy, please refer to
:code:`paddle.static.BuildStrategy`.

Args:
    program_or_graph (Graph|Program): This argument is the Program or Graph
        being executed.
    build_strategy(BuildStrategy): This argument is used to compile the
        program or graph with the specified options, such as operator's fusion
        in the computational graph and memory optimization during the execution
        of the computational graph. For more information about build_strategy,
        please refer to :code:`paddle.static.BuildStrategy`. The default is None.

Returns:
    CompiledProgram

Example:
    .. code-block:: python

        >>> import numpy
        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> place = paddle.CPUPlace()
        >>> exe = static.Executor(place)

        >>> data = static.data(name='X', shape=[None, 1], dtype='float32')
        >>> hidden = static.nn.fc(x=data, size=10)
        >>> loss = paddle.mean(hidden)
        >>> paddle.optimizer.SGD(learning_rate=0.01).minimize(loss)

        >>> exe.run(static.default_startup_program())
        >>> compiled_prog = static.CompiledProgram(
        ...     static.default_main_program())

        >>> x = numpy.random.random(size=(10, 1)).astype('float32')
        >>> loss_data, = exe.run(compiled_prog,
        ...                     feed={"X": x},
        ...                     fetch_list=[loss.name])
Nc                   [        U[        R                  5      (       a  Xl        S U l        Om[        U[
        R                  5      (       a7  [        U5        [        R                  " UR                  5      U l        Xl        O[        S[        U5       35      eS U l        S U l        S U l        SU l        SU l        S U l        S U l        X l        g )NzYThe type of program_to_graph parameter is wrong, expected Graph or Program, but received F)
isinstancer   r   _graph_programr	   r   rd   desc	TypeErrorrS   _scope_place	_executor	_compiled_is_inference_share_vars_from_places_build_strategy)selfprogram_or_graphbuild_strategys      r#   __init__CompiledProgram.__init__   s    
 &

33*K DM()*;*;<<,-**%5%:%:;DK,Mklp  rB  mC  lD  E  " $-r"   c                    U R                   (       a   S5       e[        [        U[        5      [        U[        5      /5      (       d   eSU l         Xl        U $ )zAdd inference optimize

Args:
    config: instance of `NativeConfig` or `AnalysisConfig` to create predictor
Returns:
    self
z6Already compiled with inference, cannot be recompiled.T)r   anyr~   InferNativeConfigInferAnalysisConfig_infer_config)r   configs     r#   _with_inference_optimize(CompiledProgram._with_inference_optimize   sf     %% 	
D	
% 6#456#67
 
 	
 
 "#r"   c                    [        S5      e)NzFSubclass of CompiledProgram should implement _with_distributed method.)NotImplementedErrorr   s    r#   _with_distributed!CompiledProgram._with_distributed   s    !T
 	
r"   c           	      	   U R                   (       ar  U(       a  [        R                  R                  S5        U R                   R                  c  [        S5      eU R                   R                  R                  5       U l        OUc   S5       e/ U l        [        U[        [        45      (       d   S[        U5       S35       eU R                  c  [        5       U l        U R                  (       a  U R                  R                  S:  ak  U R                  R                   (       aP  U R                  R                   nU R                  R                  [#        U5      :X  d   S5       eX@R                  l        U R                  (       ao  U R                  R&                  U R                  l        U R                  R*                  U R                  l        U R                  R.                  U R                  l        U R                  b  U R                  R2                  (       aw  U R                  R                  [#        U5      -  S:  d   S5       eU R                  R4                  [        R6                  R8                  :X  d   S	5       eS
U R                  l        / U l        U R>                  RA                  5        H  nURC                  5       (       d  M  URE                  5       c  M-  URE                  5       RG                  5       (       d  MR  URE                  5       R                  5       [H        RJ                  RL                  RN                  :w  d  M  URQ                  5       nU R                  c  M  [S        U R                  U5      (       d  M  U R<                  RU                  URQ                  5       5        M     [        [W        [X        U5      5      n[        [[        U R<                  5      5      U l        U R<                  R]                  5         [H        R^                  " 5       (       a  [a        S5      e[H        Rb                  " UU R<                  SU Rd                  U R                  U R                  U R>                  5      $ )Nz*share_vars_from is set, scope is ignored.
zSThe shared Program is not compiled and executed, so there is no variables to share. zLCurrently, The places type can only be list or tuple, but the input type is .r   z5The trainer numbers is not equal to endpoint numbers.z.DGC is not available for single card training.z1DGC only can be used for AllReduce BuildStrategy.FzBCUDA Graph is not allowed to capture when running the first batch.)3r   sysstderrwriter   
ValueErrorlocal_scopes_local_scopesr~   listtuplerS   r   BuildStrategyr   num_trainers_trainers_endpointslentrainers_endpoints_nccl_comm_numnccl_comm_num_use_hierarchical_allreduceuse_hierarchical_allreduce$_hierarchical_allreduce_inter_nranks#hierarchical_allreduce_inter_nranks_enable_dgcreduce_strategyReduceStrategy	AllReducefuse_all_reduce_ops_persistable_varsr   rP   is_varrx   persistabler   VarDescVarTypeRAWnamery   r^   maprM   setsortis_cuda_graph_capturingRuntimeErrorr{   r   )r   places
use_devicescopetpsrV   r   s          r#   _compile_data_parallel&CompiledProgram._compile_data_parallel   sq     

  !NO$$..6 *  "&!6!6!@!@!M!M!OD$(b($!#D&4-00 	
Z[_`f[gZhhij	
0 '#0?D  MM$$11A511--33C''44C@ G@ 7:  3==151M1MD  .99   ; BB   D ==$)B)B''44s6{BQF @F $$44 //99:C CC:
 8=D  4!#KK%%'DHHJ*HHJ**,,HHJOO%)=)=)A)AAyy{MM-7tLL**11$))+> ( c*f-.
 "&c$*@*@&A!B##%''))T  ##""KK  KK
 	
r"   c                B    [         R                  " U R                  5      $ rH   )r   create_paddle_predictorr   r   s    r#   _compile_inference"CompiledProgram._compile_inferenceA  s    ++D,>,>??r"   c                   U R                   (       aV  U(       a  U R                  U:w  a  [        S5      eU(       a+  U R                  R	                  U5      (       d  [        S5      eU $ SU l         Xl        X l        U R
                  (       a  U R                  5       U l        U $ U R                  /U l        [        U R                  [        R                  5      (       a  [        R                  nOJ[        U R                  [        R                  5      (       a  [        R                  nO[        R                   nU R#                  X0R                  U R                  S9U l        U $ )zCompile the program based on the configs.

Args:
    scope: The variables (resources) that are associated with
       this compiled program.
    place: The location that the compiled program will be run on.

Returns:
    self
z,Cannot compile program with different scope.z,Cannot compile program with different place.T)r   r   r   )r   r   r   r   _equalsr   r   r   r   r~   r   	CUDAPlace
DeviceTypeCUDAXPUPlaceXPUCPUr   )r   r   rK   r   s       r#   _compileCompiledProgram._compileD  s     >>- !OPPT[[0077 !OPPK!446DN  !KK=DL$++t~~66'__
DKK77'^^
'^^
!88%[[ 9 DN r"   c                Z   US LnU(       a3  U H,  nUR                  5       UR                  5       :X  a  M'   S5       e   O^[        U[        R                  5      (       a  [	        5       nO4[        U[        R
                  5      (       a  [        5       nO
[        5       nU(       d   S5       eU$ )Nz7Place type not match. You may set wrong type of places.zNo places for execution.)_typer~   r   r   r   r   r   r
   )r   rK   
place_listhas_set_placerL   s        r#   _get_placesCompiledProgram._get_placesj  s    "$.wwyEKKM1 M1  
 %00(]
E4==11'\
'\
555zr"   )r   r   r   r   r   r   r   r   r   r   r   r   r   rH   )r   zGraph | Programr   zBuildStrategy | NonereturnNone)r   r   r   r   __doc__r   r   r   r   r   r   r   r!   r   r"   r#   r{   r{   {   sP    /h 04.). -. 
	.6,

\
|@$Lr"   r{   c                  x    \ rS rSrSr/ rS r\ SS j5       r\S 5       r	\S 5       r
\S 5       r\S	 5       rS
rg)IpuDynamicPatcheri|  z)
Patcher for IPU dynamic2static support.
c                    g rH   r   r   s    r#   r   IpuDynamicPatcher.__init__  s    r"   Nc                ,  ^ ^^^^^^ SSK mSSKJm  SSKJn  SSKJn  TR                  nTR                  nTR                  nTR                  R                  5       mUUUU U4S j5       nT R                  (       a  UR                  SS	9  TR                   H[  n	TR                  U	R                   5      R#                  5       n
U	R%                  5       R#                  5       nU
R'                  U5        M]     U(       a%  US
S  Vs/ s H  oc  M  UR                   PM     snmO!U Vs/ s H  oc  M  UR                   PM     snmU Vs/ s H  oR                   PM     snmT R(                  (       Gaf  U" 5       Tl        T R,                  nUR.                  R1                  5        GH/  u  pUR1                  5        GH  u  nnUR2                  R5                  UR                   SUR6                  UR8                  UR:                  SS9nUR=                  U5      nU" U5         UR2                  R?                  UTR@                  RB                  RE                  SS9S9  SSS5        TRG                  UR                   5      R#                  5       nUR%                  5       R#                  5       nUR'                  U5        UUR.                  U   U'   GM     GM2     UUUUU UU4S j5       nU" 5       nUTl        T$ s  snf s  snf s  snf ! , (       d  f       N= f)z4
Convert the ConcreteProgram to IPUConcreteProgram.
r   N   )backward)switch_to_static_graph)device_guardc                    > TR                   n TR                  U TR                  5        TR                  R	                  TR                  5       5      nTR                  R                  5       nUR                  U5        U $ rH   )main_programgradients_with_optimizer
_optimizerstaticExecutorCPUPlacedefault_startup_programrun)r`   exestartup_programr   concrete_programipu_strategypaddles      r#   append_backward_descHIpuDynamicPatcher.convert_concrete_program.<locals>.append_backward_desc  sf    &33G --g|7N7NO --(():;C$mmCCEOGGO$Nr"   float16)dtyper   T)r   r   r   rS   shapebelong_to_optimizerg        )value)initializerc                   > TR                   (       a  TR                  R                  R                  5       n S1U l        TR                  R                  R                  TR                  U SS9nTR                  R                  R                  TR                  5       TR                  US9  [        TR                  TTS9R                  TT5      nU$ )NcumsumF)use_fp16_guard)to_fp16_var_names)r   r   )r*   r   ampCustomOpListsunsupported_listcast_model_to_fp16r   cast_parameters_to_fp16r   IpuCompiledProgramcompile)	amp_listr  r`   r   	feed_list
fetch_listr   r   r   s	      r#   func_compile@IpuDynamicPatcher.convert_concrete_program.<locals>.func_compile  s    ''!==,,::<-5J)$*MM$5$5$H$H$11#( %I %!
 !!99OO%$11&7 :  ) --) gi,	 
 Nr"   )$r   baser   base.dygraph.baser   base.frameworkr   inputsoutputsr   r   global_scoper*   to
parametersrx   r   
get_tensorr   _share_data_withr(   r   r   _accumulatorsitemshelpercreate_global_variabler   rS   r   _get_device_for_paramset_variable_initializernnr   Constantfind_var)r   r   class_instancer   r   r  r  r   r   param_or_bufferparam_or_buffer_tensor
src_tensorelem	optimizerkv
param_namevar_tmprx   deviceparam_or_lr_tensoroptim_tensorr  r   r   r  r  r   r   s   ``                      @@@@@r#   convert_concrete_program*IpuDynamicPatcher.convert_concrete_program  s    	#>1!(("***::**,		 
 	 ##I.  0::O%*YY$$&jl # )..0;;=J"33J?  ; /5abzNztzNI/5JvtvJI,34GDiiG4
###,@,B)$//I!//557+,779'J#**AA$\\$(%mm$\\%mm,0 B C '<<ZHF%f-!((AA(.		(=(=(F(F&) )G ) B  . */* jl ' $'99;#9#9#;L&77E=@I++A.z:- ,5 82 
 	 	 
 	, $~(4%w OJ4" .-s*   K6K6%K;/K;L <L
Lc                   ^ ^^^^ SSK Jm  SSKJm  SSKJmJmJn  UR                  nUUU UU4S jnX1l        [        R                  R                  USU/5        g)zMonkey patch ProgramCache descriptor to support dynamic2static in IPU.

Args:
    ipu_strategy: The ipu_strategy used in dynamic graph.

Returns:
    None
r   )logging_utils)partial_program_from)MAX_TRACED_PROGRAM_COUNTCacheKeyProgramCachec                  > [        UT5      (       d!  [        S[        U5      R                   35      e[	        U5      nX l        X R                  ;  d  TR                  (       a  X R                  ;   a  T	R                  S5        U R                  (       a"  TR                  (       d  T	R                  S5        U R                  U5      u  p4[        R                  TX1R                  5      nUT
" X1R                  S L5      4U R                  U'   [        U R                  5      nUT:  a  T	R                  SU ST S35        U R                  U   $ )Nz,type(item) should be CacheKey, but received z3ipu_strategy chances detected. Please sync weights.zbdynamic2static on IPU doesn't support multiple caches. Please make suredynamic inputs is not used.zCurrent traced program number: z > `max_tracing_count`:z. Too much cached programs will bring expensive overhead. The reason may be: (1) passing tensors with different shapes, (2) passing python objects instead of tensors.)r~   r   rS   r   hash_recent_key_cachesneed_compilewarn_build_oncer   r0  r#  r   )r   itemitem_idr   _current_tracing_countr6  r5  r   r3  r4  s         r#   patch_getter;IpuDynamicPatcher.patch_program_cache.<locals>.patch_getter  sR   dH-- B4:CVCVBWX  4jG&ll*l.G.Gll*!&&M <<(A(A!&&6 '+&6&6t&<# #4#M#M "24G4G$ 
 %((*=*=T*I)W% ),DLL(9%(+CC!&&9:O9PPg  iA  hB BG G
 <<((r"   __getitem__N)paddle.jit.dy2staticr3  $paddle.jit.dy2static.partial_programr4  'paddle.jit.dy2static.program_translatorr5  r6  r7  rE  r   patcher_cacher^   )r   r7  
old_getterrC  r6  r5  r3  r4  s   `   @@@@r#   patch_program_cache%IpuDynamicPatcher.patch_program_cache  sS     	7M	
 	
 "--
$	) $	)L $0 ''..=*5	
r"   c                   ^ ^ SSK Jn  UR                  mSU U4S jjnX!l        [        R                  R                  UST/5        g )Nr   LRSchedulerc                P   > T" X5        TR                  SU R                  05        g )Nr;   )set_optionslast_lr)r   epochr   old_steps     r#   
patch_step8IpuDynamicPatcher.patch_lr_scheduler.<locals>.patch_step8  s"    T!$$dDLL%9:r"   steprH   )paddle.optimizer.lrrO  rW  r   rI  r^   )r   rO  rU  rT  s   `  @r#   patch_lr_scheduler$IpuDynamicPatcher.patch_lr_scheduler0  s@    3 ##	; 	; &''..VX/NOr"   c                X    [         R                  U 5        [         R                  U 5        g rH   )r   rK  rY  )r   s    r#   register_patch IpuDynamicPatcher.register_patch?  s    --l;,,\:r"   c                 P    [         R                   H  u  pn[        XU5        M     g rH   )r   rI  setattr)modulekeyattrs      r#   release_patchIpuDynamicPatcher.release_patchD  s"    !2!@!@FF& "Ar"   )r:  rH   )r   r   r   r   r   rI  r   staticmethodr0  rK  rY  r\  rc  r!   r   r"   r#   r   r   |  s     M 7;h  h T <
 <
| P P ; ; ' 'r"   r   c                  f   \ rS rSr% SrS\S'   S\S'   S\S'   SS jrSS	 jrSS
 jrSS jr	SS jr
    S         SS jjr    S          S!S jjrS"S#S jjr   S$         S%S jjrS&S jrS'S jrS(S jrS(S jr\S)S j5       r\S*S j5       r\S*S j5       r\S*S j5       rSrg)+IpuStrategyiJ  ar  
Help users precisely control the graph building in :code:`paddle.static.IpuCompiledProgram`.

Returns:
    The IpuStrategy instance.

Examples:
    .. code-block:: python

        >>> # doctest: +REQUIRES(env:IPU)

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> ipu_strategy = static.IpuStrategy()
r'   has_custom_ops	list[str]custom_op_namesr<  c                <   [         R                  " 5       (       aT  [         R                  " 5       U l        SSS.SSS.nU R                  R	                  U5        SU l        / U l        SU l        O[        S5      eSSK	J
n  U" 5       (       a  U R                  5         g g )	Nr   r   )on_chipuse_replicated_tensor_sharding)location_optimizer+accumulation_and_replication_reduction_type4mean_accumulation_and_replication_reduction_strategyFTz\Can not use IpuStrategy in non IPU compiled environment, please re-compile with WITH_IPU=ON.in_dynamic_mode)r   is_compiled_with_ipurg  _ipu_strategyrQ  rh  rj  r<  r   r   rr  r\  )r   default_optionsrr  s      r#   r   IpuStrategy.__init__b  s    $$&&!%!1!1!3D  !67' @AHIO **?;"'D#%D  $Dn  	+! r"   c                .    [         R                  U 5        g)a  
Register patch function to support dynamic to static on IPU. This operation would break the dy2static functionality on CPU.
Use `release_patch` to release the patch.

Examples:
    .. code-block:: python

        >>> # doctest: +REQUIRES(env:IPU)

        >>> import paddle
        >>> import paddle.static as static

        >>> ipu_strategy = static.IpuStrategy()

        >>> ipu_strategy.register_patch()
N)r   r\  r   s    r#   r\  IpuStrategy.register_patchz  s    " 	((.r"   c                ,    [         R                  5         g)a  
Release the registered IPU functions.

Examples:
    .. code-block:: python

        >>> # doctest: +REQUIRES(env:IPU)

        >>> import paddle
        >>> import paddle.static as static

        >>> ipu_strategy = static.IpuStrategy()

        >>> ipu_strategy.release_patch()
N)r   rc  r   s    r#   rc  IpuStrategy.release_patch  s      	'')r"   c                    SSK Jn  U" 5       (       a3  Xl        U R                  U5      nU R                  R                  U5        g[        S5      e)aj  
Set optimizer to ipu_strategy in dynamic mode.

  Args:
      optimizer (Optimizer): Optimizer to be used in training.

  Returns:
      None.

  Examples:
        .. code-block:: python

            >>> # doctest: +REQUIRES(env:IPU)
            >>> import paddle
            >>> import paddle.static as static

            >>> linear = paddle.nn.Linear(10, 10)
            >>> optimizer = paddle.optimizer.SGD(learning_rate=0.01,
            ...                                 parameters=linear.parameters())
            >>> ipu_strategy = static.IpuStrategy()
            >>> ipu_strategy.set_optimizer(optimizer)
r   rq  z,Only needs to set optimizer in dynamic mode.N)r   rr  r   parse_optimizerrt  rQ  r   )r   r(  rr  optimizer_attrss       r#   set_optimizerIpuStrategy.set_optimizer  sE    . 	+'O"229=O**?;MNNr"   c                `   ^ U4S jnU/nSS0nU H  nUR                  U" 5       5        M     U$ )a  
Parse optimizer attributes for IPU dynamic to static support. Currently only support parse lr.

  Args:
      optimizer (Optimizer): Optimizer to be parsed.

  Returns:
      Dict.

  Examples:
        .. code-block:: python

            >>> # doctest: +REQUIRES(env:IPU)

            >>> import paddle
            >>> import paddle.static as static

            >>> linear = paddle.nn.Linear(10, 10)
            >>> optimizer = paddle.optimizer.SGD(learning_rate=0.01,
            ...                                 parameters=linear.parameters())
            >>> ipu_strategy = static.IpuStrategy()
            >>> attrs = ipu_strategy.parse_optimizer(optimizer)
c                    > SSK Jn   [        TR                  [        5      (       a  STR                  0$ [        TR                  U 5      (       a  STR                  5       0$ g )Nr   rN  r;   )rX  rO  r~   _learning_rater6   )rO  r(  s    r#   get_lr+IpuStrategy.parse_optimizer.<locals>.get_lr  sW    7)22E::i6677I44kBBi66899 Cr"   r.   T)update)r   r(  r  attr_fnr}  fns    `    r#   r|  IpuStrategy.parse_optimizer  s;    2	: ('.B""24( r"   c                d    US:X  a  U(       a  [        S5      eUUUUS.nU R                  U5        g)a  
Set graph configuration to the IpuStrategy instance.

Args:
    num_ipus (int, optional): Number of IPU devices. Default 1, which means only use 1 IPU.
    is_training (bool, optional): True is training graph, False is inference graph. Default True, which means is training mode.
    batch_size (int, optional): The batch-size in the graph. Used to make the graph batch-size fixed,
        if the batch-size in the graph is dynamic. Default 1, which means the batch-size would be set 1, if the batch-size is dynamic.
    enable_manual_shard (bool, optional): Enable graph sharding or not. Only if num_ipus > 1, enable_manual_shard is able to be set True.
        Default False, which means disabled.

Returns:
    None.

Examples:
    .. code-block:: python

        >>> # doctest: +REQUIRES(env:IPU)

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> ipu_strategy = static.IpuStrategy()
        >>> ipu_strategy.set_graph_config(num_ipus=1,
        ...                             is_training=True,
        ...                             micro_batch_size=1,
        ...                             enable_manual_shard=False)
r   zAOnly if num_ipus > 1, enable_manual_shard is able to be set True.)r0   r(   r2   rD   N)r   rQ  )r   r0   r(   r2   rD   optionss         r#   set_graph_configIpuStrategy.set_graph_config  sD    J q=0S  !& 0#6	
 	!r"   c                    U R                  S5      nU(       d  U(       a  [        S5      eUUUUS.nU R                  U5        g)a  
Set pipelining configuration to the IpuStrategy instance. Used to optimize the throughput performance.

Args:
    enable_pipelining (bool, optional): Enable data pipelining between subgraphs. Only if enable_manual_shard=True, enable_pipelining is able to be set True.
        Default False, which means disabled.
    batches_per_step (int, optional): Set the batches per run in data pipelining mode. Only if enable_pipelining=True, batches_per_step is able to be set > 1.
        Default 1, which means no data pipelining.
    enable_gradient_accumulation (bool, optional): Enable to accumulate gradients before updating the weights in training mode. Only if enable_pipelining=True,
        enable_gradient_accumulation is able to be set True. Default False, which means no gradient accumulation.
    accumulation_factor (int, optional): Specify the number of micro-batches to accumulate
        before applying the varUpdate. Default 1, which means disable the accumulation.

Returns:
    None.

Examples:
    .. code-block:: python

        >>> # doctest: +REQUIRES(env:IPU)

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> ipu_strategy = static.IpuStrategy()
        >>> ipu_strategy.set_pipelining_config(enable_pipelining=False,
        ...                                     batches_per_step=1,
        ...                                     enable_gradient_accumulation=False,
        ...                                     accumulation_factor=1)
rD   zKOnly if enable_manual_shard=True, enable_pipelining is able to be set True.)rA   r1   rB   rC   N)
get_optionr   rQ  )r   rA   r1   rB   rC   rD   r  s          r#   set_pipelining_config!IpuStrategy.set_pipelining_config  sP    N #oo.CD"'8]  "3 0,H#6	
 	!r"   c                .    SU0nU R                  U5        g)a4  
Set half computation configuration to the IpuStrategy instance. Used to optimize the performance.

Args:
    enable_fp16 (bool, optional): Enable FLOAT16 mode and transform FLOAT32 to FLOAT16. Default False, which means disable FLOAT16 mode.

Returns:
    None.

Examples:
    .. code-block:: python

        >>> # doctest: +REQUIRES(env:IPU)

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> ipu_strategy = static.IpuStrategy()
        >>> ipu_strategy.set_precision_config(enable_fp16=False)
r*   N)rQ  )r   r*   r  s      r#   set_precision_config IpuStrategy.set_precision_configK  s     0 ;
 	!r"   Nc                    Uc  UnUUUUS.nU R                  SU05        U R                  R                  U5        U R                  (       d  SU l        gg)a\  
Add a mapping to use popart custom ops running on the IPU.

Args:
    paddle_op(str): the name of custom op in paddle.

    popart_op(str): the name of custom op in popart.

    domain(str): domain name of custom op in popart.

    version(int): version of custom op in popart.

Returns:
    None.

Examples:
    .. code-block:: python

        >>> # doctest: +REQUIRES(env:IPU)

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> ipu_strategy = static.IpuStrategy()
        >>> ipu_strategy.add_custom_op('paddle_relu', 'popart_relu')
N)r   r   r   r   rE   T)rQ  rj  r^   rh  )r   r   r   r   r   rE   s         r#   add_custom_opIpuStrategy.add_custom_opg  sb    F !I""	
	 	+y12##I."""&D #r"   c                    U R                   R                  U5        S1nUR                  5       U-
  (       a  SU l        gg)a  
Set options from dict.

Args:
    options(dict): dict of options.

Returns:
    None.

Examples:
    .. code-block:: python

        >>> # doctest: +REQUIRES(env:IPU)

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> ipu_strategy = static.IpuStrategy()
        >>> options = {'num_ipus':1, 'enable_fp16': True}
        >>> ipu_strategy.set_options(options)  # type: ignore[arg-type]
r;   TN)rt  rQ  keysr<  )r   r  recompile_white_lists      r#   rQ  IpuStrategy.set_options  s<    0 	&&w/ $v<<>00 $D 1r"   c                >    U R                   R                  U5      S   $ )ax  
Get option.

Args:
    option(str): name of option.

Returns:
    option value.

Examples:
    .. code-block:: python

        >>> # doctest: +REQUIRES(env:IPU)

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> ipu_strategy = static.IpuStrategy()
        >>> num_ipus = ipu_strategy.get_option('num_ipus')
r   )rt  r  )r   options     r#   r  IpuStrategy.get_option  s     . !!,,V4W==r"   c                :    U R                   R                  U5        g)a  
Enable PopART pattern to optimize the graph.

Args:
    pattern(string): the name of the pattern.

Returns:
    None.

Examples:
    .. code-block:: python

        >>> # doctest: +REQUIRES(env:IPU)

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> ipu_strategy = static.IpuStrategy()
        >>> ipu_strategy.enable_pattern("ViewSimplifyPattern")
N)rt  enable_patternr   patterns     r#   r  IpuStrategy.enable_pattern  s    . 	))'2r"   c                :    U R                   R                  U5        g)a  
Disable PopART pattern.

Args:
    pattern(string): the name of the pattern.

Returns:
    None.

Examples:
    .. code-block:: python

        >>> # doctest: +REQUIRES(env:IPU)

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> ipu_strategy = static.IpuStrategy()
        >>> ipu_strategy.disable_pattern("ViewSimplifyPattern")
N)rt  disable_patternr  s     r#   r  IpuStrategy.disable_pattern  s    . 	**73r"   c                $    U R                  S5      $ )z:
Get the number of IPU devices from IpuStrategy instance.
r0   r  r   s    r#   r0   IpuStrategy.num_ipus   s    
 z**r"   c                $    U R                  S5      $ )zE
Get the boolean of training or inference from IpuStrategy instance.
r(   r  r   s    r#   r(   IpuStrategy.is_training      
 }--r"   c                $    U R                  S5      $ )zH
Get the boolean of enable pipelining or not from IpuStrategy instance.
rA   r  r   s    r#   rA   IpuStrategy.enable_pipelining  s    
 233r"   c                $    U R                  S5      $ )zC
Get the boolean of float16 mode or not from IpuStrategy instance.
r*   r  r   s    r#   r*   IpuStrategy.enable_fp16  r  r"   )rt  r   rj  rh  r<  )r   r   )r(  r   r   r   )r(  r   r   r%   )r   Tr   F)
r0   r   r(   r'   r2   r   rD   r'   r   r   )Fr   Fr   )
rA   r'   r1   r   rB   r'   rC   r   r   r   )F)r*   r'   r   r   )Nz
custom.opsr   )
r   r   r   z
str | Noner   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\  rc  r~  r|  r  r  r  r  rQ  r  r  r  propertyr0   r(   rA   r*   r!   r   r"   r#   rg  rg  J  si   & "0/&*$O@%R   !$)/"/" /" 	/"
 "/" 
/"f #( !-2#$2"2" 2" '+	2"
 !2" 
2"h"> !%".'.' .' 	.'
 .' 
.'`%<>23242 + + . . 4 4 . .r"   rg  c                  D    \ rS rSrSr   S       SS jjrS	S jrSrg)
r	  i  a  
The IpuCompiledProgram is used to transform a program to a ipu-target program,
such as forward graph extraction, computing graph transformation, useless scale Ops clean, etc.

Args:
    program(Program, optional): This parameter represents the :code:`Program`
        to be executed. Default is None, which means the program will be set to
        the default program :code:`paddle.static.default_main_program()` .
    scope(Scope, optional): The scope used to run this program, you can switch
        it to different scope. Default is None, which means use the global
        scope :code:`paddle.static.global_scope()` .
    ipu_strategy(IpuStrategy, optional): This argument is used to build the program with the
        specified options, such as half computation, training or inference session, the number of IPUs, etc.
        Default is None, which means build the program based on the default `ipu_strategy`.

Returns:
    IpuCompiledProgram

Example:
    .. code-block:: python

        >>> # doctest: +REQUIRES(env:IPU)

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> a = static.data(name='data', shape=[None, 1], dtype='int32')
        >>> b = a + 1
        >>> main_prog = static.default_main_program()

        >>> ipu_strategy = static.IpuStrategy()
        >>> ipu_strategy.set_graph_config(num_ipus=1, is_training=True, micro_batch_size=1)
        >>> ipu_strategy.set_pipelining_config(enable_pipelining=False, batches_per_step=1, enable_gradient_accumulation=False, accumulation_factor=1)
        >>> ipu_strategy.set_precision_config(enable_fp16=False)

        >>> ipu_compiled_program = static.IpuCompiledProgram(
        ...     main_prog,
        ...     ipu_strategy=ipu_strategy)
Nc                <   [         R                  " 5       (       d  [        S5      eUc  [        R                  " 5       n[        U[        R                  5      (       d  [        S[        U5       35      eXl	        SU l
        Ub  X l        O#SS KnUR                  R                  5       U l        Ub  X0l        O[!        5       U l        UR"                  (       a  [%        UR&                  5      U l        OSU l        [         R*                  R-                  5       U l        g )NzECan not use this function since PaddlePaddle is not compiled with IPUz8The type of program is wrong, expected Program, but got Fr   r   )r   rs  r   r	   default_main_programr~   r   r   rS   r   r   r   r   r   r  rt  rg  rh  r   rj  _custom_op_names
IpuBackendget_instance_backend)r   r`   r   r   r   s        r#   r   IpuCompiledProgram.__init__H  s     ((**W  ?446G'9#4#455J4PW=/Z   K  --446DK#!-!,D&&$'(D(D$ED!$&D!446r"   c                   U R                   R                  U R                  5        U R                   R                  U R                  R                  5        U R
                  R                  5       n/ n[        UR                  5       HS  u  pVUR                  R                  S5        UR                  S:X  d  UR                  S:X  d  MB  UR                  U5        MU     USSS2    H  nUR                  U5        M     S H,  nUR                  U5      (       d  M  UR                  U5        M.     U R
                  R                  R!                  5         ["        R$                  " U R
                  R                  5      U l        U R                  R(                  (       a>  SS/n	U	 H4  n
["        R*                  " U
5      nUR-                  U R&                  5        M6     / S	Qn	U	 HL  n
["        R*                  " U
5      nU
S
:X  a  UR/                  SU5        UR-                  U R&                  5        MN     ["        R*                  " S5      nU R0                  (       a  UR/                  SU R0                  5        UR-                  U R&                  5        / SQn	U	 HX  n
["        R*                  " U
5      nUR/                  SU5        UR/                  SU5        UR-                  U R&                  5        MZ     ["        R*                  " S5      n["        R2                  " 5       nUR5                  SU5        UR-                  U R&                  5        [6        R8                  R;                  U5      n[=        U R
                  S5      (       as  U R
                  R>                  R@                  nU R
                  R>                  Ul        U R
                  R                  5       nURB                  U   UR>                  l"        UR                  5       nU H/  nURG                  U5      nUR                  RI                  S5        M1     [=        US5      (       d  U R
                  Ul%        SU R                  l&        U$ )a  
This interface is used to compile the input Program to a program
to run the model on the ipu.

Args:
    feed_list(list): This parameter represents the input Tensors of the model.

    fetch_list(list): This parameter represents the Tensors that need to be returned
        after the model.

Returns:
    Program

Example:
    .. code-block:: python

        >>> # doctest: +REQUIRES(env:IPU)

        >>> import paddle
        >>> import paddle.static as static

        >>> paddle.enable_static()

        >>> a = static.data(name='data', shape=[None, 1], dtype='int32')
        >>> b = a + 1
        >>> main_prog = static.default_main_program()

        >>> ipu_strategy = static.IpuStrategy()
        >>> ipu_strategy.set_graph_config(num_ipus=1, is_training=True, micro_batch_size=1)
        >>> ipu_strategy.set_pipelining_config(enable_pipelining=False, batches_per_step=1, enable_gradient_accumulation=False, accumulation_factor=1)
        >>> ipu_strategy.set_precision_config(enable_fp16=False)

        >>> program = static.IpuCompiledProgram(
        ...     main_prog,
        ...     ipu_strategy=ipu_strategy).compile([a.name], [b.name])
FrY   fetchNrZ   )rY   r  optimizer_extract_passoptimizer_state_align_pass)forward_graph_extract_passinfer_shape_passavg_shard_passdelete_scale_op_passr  r  popart_canonicalization_pass
custom_ops)ipu_inplace_passipu_graph_builder_passipu_runtime_replacer_passr  graph_to_program_passr`   lr_schedulerorg_program)'r  	set_scoper   set_ipu_strategyrt  r   r\   r[   r]   r   set_is_targetrS   r^   r_   has_var_remove_varflushr   r   r   r(   get_passapplyr   r  ProgramDescset_not_ownedr	   r   _construct_from_deschasattrr  	_var_namert   lr_varrx   set_need_check_feedr  r<  )r   r  r  r\   need_to_remove_op_indexrb   rR   rc   rx   passes	pass_namea_passconvert_passr   r`   lr_var_nameprogram_global_block	feed_namefeed_vars                      r#   r
  IpuCompiledProgram.compiler  sa   J 	,&&t'9'9'G'GH }}113"$|//0EAGG!!%(ww& BGGw$6'..q1 1
 -TrT2E##E* 3 %C##C((((- % 	  "jj!3!34))(,F $	y1T[[) $
  I]]9-F..

;	2LL%	   =>  JJ|T%:%:;T[[!

  I]]9-FJJ{I.JJ|Z0LL%	   }}%<=!""9d34;;'##88>4==.11--44>>K#'==#=#=G   ==557L*6*;*;K*HG  '  '335"I+//	:HMM--e4 # w.."&--G*/'r"   )r  r   r  r   rt  r   r   )NNN)r`   zProgram | Noner   z_Scope | Noner   zIpuStrategy | Noner   r   )r  ri  r  ri  r   r   )r   r   r   r   r   r   r
  r!   r   r"   r#   r	  r	    sE    (X #'#+/	(7(7 (7 )	(7
 
(7T}r"   r	  )&
__future__r   r   typingr   r   r   r   r   r	   r
   r   r   paddle.base.corer   r   paddle.optimizerr   paddle.staticr   r   r%   __all__r{   r   NativeConfigr   AnalysisConfigr   r   rM   rW   rd   rp   ry   r   rg  r	  r   r"   r#   <module>r     s    # 
 0 0  : :.*%I iu @ $$22%% )) __
1~ ~BK' K'\P. P.fR Rr"   