
    ϑic                         S SK r S SKrS SKrS SKrS SKrS SKJs  Jr	  S SK
Jr  S SKJr  S SKJr  S SKJr  S SKJr  S SKJr  SS	KJr  SS
KJrJrJrJr  / r " S S5      rSS jrSS jrS r S r!S r"S r#S r$S r%S r&g)    N)core)convert_dtype)switch_to_static_graph)PirTranslatedLayer)TranslatedLayer)layers   )logging_utils)func_to_source_codeparse_arg_and_kwargsparse_varargs_name	type_namec                       \ rS rSrSrSS jrS rS r\S 5       r	\S 5       r
S	 rS
 r\S 5       r\S 5       r\S 5       r\S 5       r\S 5       r\S 5       rSrg)FunctionSpec)   z0
Wrapper class for a function for class method.
Nc                 z   [         R                  " U5      (       a7  UR                  U l        [        R
                  " UR                  5      U l        OXl        S U l        Uc  S U l        S U l	        ODU R                  U5      U l        [        R                  R                  U R                  5      U l	        [        U5      u  U l        U l        [#        U5      U l        U R$                  bQ  ['        [)        USS 5      [*        [,        45      (       a*  U =R                  UR                  R.                  -  sl        g g g )N__self__)inspectismethod__func___dygraph_functionweakrefrefr   _class_instance_input_spec_flat_input_spec_verify_input_specpaddleutilsflattenr   
_arg_names_default_kwargsr   varargs_name
isinstancegetattrr   r   _input_args_names)selffunction
input_specs      b/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/paddle/jit/dy2static/function_spec.py__init__FunctionSpec.__init__.   s   H%%%-%6%6D"#*;;x/@/@#AD %-"#'D #D$(D!#66zBD$*LL$8$89I9I$JD! 1EX0N--.x8(ZHj$/01.
 .
 OOx00BBBO	.
(    c                    [        U R                  5      [        U5      :  a  SU R                  R                   S[        U R                  5       SU R                   S[        U5       SU S3nU(       a.  [        R
                  " US   5      (       a  US-  n[        U5      e[        U5      e[        U5      n[        [        U5      [        U R                  5      5       H  nU R                  U   nXR;   a  UR                  X%   5        X%	 M.  XPR                  ;  a,  [        S	U R                  R                   S
U SU SU S3	5      eUR                  U R                  U   5        M     [        U5      U4$ )a;  
Moves kwargs with default value into arguments list to keep `args` contain the same length
value as function definition.

For example:

    Given function definition: `def foo(x, a=1, b=2)`,
    when calling it by `foo(23)`, the args is `[23]`, kwargs is `{a=1, b=2}`.
    In this function, it will return args with `[23, 1, 2]`, kwargs with `{}`

Args:
    args(tuple): tuple of input arguments value of decorated function.
    kwargs(dict): dict of input keyword arguments value of decorated function.

Return:
    New arguments tuple containing default kwargs value.
zThe decorated function `z` requires z arguments: , but received z with .r   zP
	Maybe the function has more than one decorator, we don't support this for now.`z()` requires `z,` arguments, but not found in input `args`: z and `kwargs`: )lenr!   dygraph_function__name__r   isclassNotImplementedError
ValueErrorlistrangeappendr"   tuple)r'   argskwargs	error_msgiarg_names         r*   unified_args_and_kwargs$FunctionSpec.unified_args_and_kwargsF   s   $ t#d)+243H3H3Q3Q2RR]^abfbqbq^r]ss  AE  AP  AP  @Q  Q`  ad  ei  aj  `k  kq  rv  qw  wx  yIQ00qq	))44 ++Dzs4y#doo"67Aq)H!F,-$#7#77$D11::;>(S  AE  @F  FU  V\  U]  ]^  _  D00:; 8 T{F""r-   c                    / n/ nU R                   b  U(       a%  [        U R                  R                   SU S35      e[	        U5      [	        U R                   5      :  a-  [        S[	        U5       S[	        U R                   5       35      e[        XR                   5      nO}[        XR                  5      nUR                  5        Vs/ s H  nSU-   PM
     nn[        [        UR                  5       5      U5      n[        U5       VVs0 s H
  u  pXWU   _M     nnn[        U R                  U5      nX44$ s  snf s  snnf )a  
Converts input arguments into InputSpec.

1. If specific input_spec, use them to construct feed layers.
2. If input_spec is None, consider all Tensor and Numpy.ndarray as feed layers

Args:
    args(tuple): tuple of input arguments value of function containing default kwargs value.
    kwargs(dict): kwargs arguments received by **kwargs.

Return:
    Same nest structure with args and kwargs by replacing value with InputSpec.
z# got unexpected keyword arguments: z;. Cannot trace the function when `input_spec` is specified.zCRequires len(arguments) >= len(input_spec), but received len(args):z < len(InputSpec): zkwargs.)r   r7   r3   r4   r2   convert_to_input_spec$_replace_to_input_spec_with_new_namer!   keysr8   values	enumeratereplace_spec_empty_name)	r'   r<   r=   args_with_speckwargs_with_speckeykwarg_nameskwargs_list_with_specidxs	            r*   args_to_input_specFunctionSpec.args_to_input_specp   ss    '  ,,5566YZ`Ya  b]  ^  4y3t//00 YZ]^bZcYddwx{  }A  }M  }M  yN  xO  P 
 349I9IJNAooN 7=kkmDms9s?mKD$HV]]_%{%!
 !*& 1  1HC 3// 1    1OO^
 // E s   
D9D>c           	         SSK Jn  [        R                  R	                  U5      n/ n/ n[
        R                  " U5         [        U5       GH9  u  px[        U[        R                  R                  5      (       a  [        USS5      n	[        R                  R                  R                  UR                  =(       d    SU 3UR                  [!        UR"                  5      S9n
Xl        SSKJn  [        X5      (       aO  U" UR*                  U5      n[        R,                  R/                  XR0                  U5      nUR3                  U5        O%UR3                  U
5        OUn
UR3                  U
5        UR3                  U
5        GM<     SSS5        [        R                  R5                  X5      [        R                  R5                  X5      4$ ! , (       d  f       NL= f)	
Constructs feed layer by inputs with InputSpec information for main program.

Args:
    input_with_spec(tuple): input arguments by replacing argument with InputSpec.
    main_program(Program): main program for inserting feed layer.
r   to_placementsstop_gradientFfeed_)nameshapedtypeDistributedInputSpecN)/paddle.distributed.auto_parallel.placement_typerU   r   r   r    	ir_staticprogram_guardrH   r$   static	InputSpecr%   inputdatarX   rY   r   rZ   rV   7paddle.distributed.auto_parallel.static.dist_input_specr\   dims_mapping_pir_opsshard_tensormeshr:   pack_sequence_as)r'   input_with_specmain_programrU   flat_input_specfunction_argsprogram_inputsr?   var_specrV   
feed_valuer\   
placementsdist_feed_values                 r*   pir_to_static_inputs_with_spec+FunctionSpec.pir_to_static_inputs_with_spec   s   	
 !,,..? $$\2(9h(?(?@@$+Hou$MM!'!4!4!9!9%]]9aSk&nn+HNN; ": "J
 0=, "(AA%2$118&
 +1//*F*F&z+ &,,_=%,,Z8!)J!((4%%j1;  : 3@ ||,,
<<((IJ 	JA 32s    E
G
Gc           
      :   [         R                  R                  U5      n/ nUR                  5       n[	        U5       GH<  u  pg[        U[         R                  R                  5      (       a  [        USS5      nUR                  UR                  =(       d    SU 3UR                  UR                  SSUS9n	SSKJn
  SSKJn  [        Xz5      (       a  SS	KJn  U" 5       nU" U	5      nUR&                  UR(                  l        UR,                  UR(                  l        UR(                  R/                  S
5        UR(                  R/                  S5        UR1                  U5        OUn	UR3                  U	5        GM?     [         R                  R5                  X5      $ )rS   rV   FrW   T)rX   rY   rZ   is_dataneed_check_feedrV   r   r[   )DistributedTensor)get_default_distributed_contextprocess_meshre   )r   r   r    global_blockrH   r$   r`   ra   r%   
create_varrX   rY   rZ   rd   r\   3paddle.distributed.auto_parallel.static.dist_tensorrx   4paddle.distributed.auto_parallel.static.dist_contextry   rh   	dist_attrrz   re   mark_annotatedadd_dist_tensor_for_programr:   ri   )r'   rj   rk   rl   inputsblockr?   ro   rV   
feed_layerr\   rx   ry   default_dist_ctxdist_tensors                  r*   to_static_inputs_with_spec'FunctionSpec.to_static_inputs_with_spec   sX    !,,..?))+$_5KA(FMM$;$;<< '/5 I"--!5E!+"..".. $)"/ . 
 h== (G'H$"3J"?K9AK))69A9N9NK))6))88H))88H$@@M%
MM*%G 6J ||,,_EEr-   c                 ~    [        U[        [        45      (       d  [        S[	        U5       S35      e[        U5      $ )z:
Verifies the `input_spec` and its element type is valid.
zBThe type(input_spec) should be one of (tuple, list), but received r0   )r$   r;   r8   	TypeErrorr   )r'   r)   s     r*   r   FunctionSpec._verify_input_spec  sD     *udm44TU^_iUjTkklm  Z  r-   c                     SR                  U R                  R                  SR                  U R                  5      U R
                  5      $ )Nz function: {}({}), input_spec: {},)formatr3   r4   joinr!   r   r'   s    r*   __repr__FunctionSpec.__repr__  s=    188!!**HHT__%
 	
r-   c                 v    U R                   c  g U R                  5       c  [        S5      eU R                  5       $ )NzFThe instance of class has been deleted, please re-create the instance.)r   RuntimeErrorr   s    r*   class_instanceFunctionSpec.class_instance$  sA    '!)X  ##%%r-   c                 ~    U R                   b%  U R                  R                  U R                   5      $ U R                  $ N)r   r   __get__r   s    r*   r3   FunctionSpec.dygraph_function.  s7    *))11$2E2EFF)))r-   c                     U R                   $ r   )r!   r   s    r*   	args_nameFunctionSpec.args_name5  s    r-   c                     U R                   $ r   )r   r   s    r*   r)   FunctionSpec.input_spec9  s    r-   c                     U R                   $ r   )r   r   s    r*   rl   FunctionSpec.flat_input_spec=  s    $$$r-   c                 ,    [        U R                  5      $ r   )r   r3   r   s    r*   codeFunctionSpec.codeA  s    "4#8#899r-   )r!   r   r"   r   r   r   r#   r   )r4   
__module____qualname____firstlineno____doc__r+   rA   rP   r   rs   r   r   r   propertyr   r3   r   r)   rl   r   __static_attributes__ r-   r*   r   r   )   s    C0(#T60p 3J 3Jj 1F 1Ff	!
 & & * *       % % : :r-   r   c                 p   [         R                  " 5       nU b  [        U [        R                  5      (       ab  U(       aL  U R                  5       nU Vs/ s H  o3R                  PM     nn[         R                  " [        XB5      5      nU$ U R                  n U$ [        S[        U 5       35      eU$ s  snf )z}
Returns parameters of decorated layers. If set `include_sublayer` True,
the parameters created in sub layers will be added.
:Type of `layer_instance` should be nn.Layer, but received )collectionsOrderedDictr$   r   Layer
parametersrX   zip_parametersr   r   )layer_instanceinclude_sublayerparamspnamess        r*   get_parametersr   F  s    
 $$&F!nfll33'224)/0A0$00U1CD M (33 M	 LYWeMfLgh  M 1   B3c                 p   [         R                  " 5       nU b  [        U [        R                  5      (       ab  U(       aL  U R                  5       nU Vs/ s H  o3R                  PM     nn[         R                  " [        XB5      5      nU$ U R                  n U$ [        S[        U 5       35      eU$ s  snf )z
Returns Variable buffers of decorated layers. If set `include_sublayer` True,
the Variable buffers created in sub layers will be added.
r   )r   r   r$   r   r   buffersrX   r   _buffersr   r   )r   r   r   bufferr   s        r*   get_buffersr   \  s    
 %%'G!nfll33(0023:;77;%11#e2EF N )11
 N LYWeMfLgh  N <r   c           
         SSK Jn  SSKJn  / n[	        [
        R                  R                  U 5      5       GH  u  pE[        U[        R                  5      (       a2  [
        R                  R                  R                  U5      nSUl        GO[        U[        R                   R"                  5      (       ad  UR                  nUR%                  5       (       a  UR'                  U5      nO)[
        R                  R                  R)                  U5      nXel        GO"[        U[
        R*                  R,                  R.                  [
        R0                  R2                  45      (       a  UR                  nUR%                  5       (       ao  UR5                  5       R6                  nU" UR5                  5       R8                  U5      nU" UR:                  UR<                  UR>                  UUUR@                  S9nO?[
        R                  R                  UR:                  UR<                  UR>                  5      nXel        URC                  U5        GM     [
        R                  RE                  X5      nU$ )Nr   rT   r[   T)rZ   rX   rh   rq   local_shape)#r]   rU   rd   r\   rH   r   r   r    r$   npndarrayr`   ra   
from_numpyrV   r   eagerTensoris_distfrom_dtensorfrom_tensorbase	frameworkVariablepirValuer   rz   re   rY   rZ   rX   _local_shaper:   ri   )	r<   rU   r\   rJ   rO   	input_varrV   rh   rq   s	            r*   _replace_value_with_input_specr   q  s    N#FLL$8$8$>?i,,//::9EI&*I#	4::#4#455%33M  ""0==iH	"MM33??	J	&3#--66

8H8HI
 
 &33M  "" **,99*'')66
 1OO#//") ) 6 6	 #MM33OOY__inn	 '4#i(E @F \\224HNr-   c                    [        U 5      [        U5      :X  d   e[        [        [        U5      S-
  5      5      n/ n[        [        X5      5       GH  u  nu  pVSn[        [        R
                  R                  U5      5       GH  u  p[        U	[        R                  5      (       a1  [        R                  R                  R                  U	5      n
SU
l        O[        U	[        R                  R                   5      (       a<  U	R                  n[        R                  R                  R#                  U	5      n
Xl        O[        U	[        R$                  R&                  R(                  5      (       aR  U	R                  n[        R                  R                  U	R*                  U	R,                  U	R.                  5      n
Xl        OU	n
[        U	[        R                  [        R                  R                   [        R$                  R&                  R(                  45      (       a-  S[        U5      R1                  U5       SU SU 3U
l        US-  nUR3                  U
5        GM     GM     [        R
                  R5                  X5      nU$ )Nr	   r   Tz_jst.r0   )r2   strrH   r   r   r   r    r$   r   r   r`   ra   r   rV   r   r   r   r   r   r   r   rY   rZ   rX   zfillr:   ri   )r<   	arg_namesorder_digitrJ   orderargname_prefixindexrO   origin_inputr   rV   s               r*   rE   rE     s   t9I&&&c#i.1,-.KN%.s4/C%D!!!*6<<+?+?+D!EC,

33"MM33>>|L	*.	'L$***;*;<< , : :"MM33??M	*7'L&++*?*?*H*HII , : :"MM33 &&(:(:L<M<M	 +8'(	JJJJ%%KK))22  $)U)9)9+)F(GqUVW\V]!^	
!!),7 "F &E< \\224HNr-   c                 b  ^ ^ SUU 4S jjn[        T[        [        45      (       a  / nU" T TS5        [        T5       H%  u  pE[	        T U   U5      nUR                  U5        M'     [        T 5      [        T5      :  as  T [        T5      S  Ha  n[        U[        R                  R                  [        R                  45      (       d  M>  [        R                  " S[        U5       S35        Mc     UR                  T [        T5      S 5        U$ [        T[         5      (       aD  0 nU" T TS5        T R#                  5        H"  u  pUT;   a  [	        U	TU   5      X8'   M  XU'   M$     U$ [        T[$        R&                  R(                  5      (       a   [+        T /5      S   n
[        U
[$        R&                  R(                  5      (       d  [-        ST  S35      eTR.                  U
l        [1        TU
5      (       a  TR2                  U
l        U
$ [        R                  " S	T S
U
 S35        U
$ T$ )a(  
Replaces tensor in structured `inputs` by InputSpec in `input_spec`.

Args:
    inputs(list|dict): nested structure list or dict.
    input_spec(list|dict): same nested structure list or dict as inputs.


Return:
    Same structure with inputs by replacing the element with specified InputSpec.
c                   > [        U 5      [        U5      La$  [        S[        U5       S[        U 5       S35      eU(       a<  [        U 5      [        U5      :  a#  [        S[        T5       S[        T5       35      eg g )Nztype(input) should be r/   r0   zBRequires len(inputs) >= len(input_spec), but received len(inputs):z < len(input_spec):)typer   r2   r7   )rb   speccheck_lengthr)   r   s      r*   check_type_and_len1convert_to_input_spec.<locals>.check_type_and_len  s    ;d4j((dODK=PQR  CJT2TUXY_U`Taatux  zD  vE  uF  G  3<r-   TNzThe inputs contain `z` without specifying InputSpec, its shape and dtype will be treated immutable. Please specific InputSpec information in `@to_static` if you expect them as mutable inputs.r   z1Give input spec into a non-tensorable arguments `z`.z;input spec is not compatible with real inputs. input_spec: z , real_spec:  )F)r$   r;   r8   rH   rD   r:   r2   r   r   r   r   r   r
   warnr   extenddictitemsr   r`   ra   r   r   rX   spec_greaterrY   )r   r)   r   rj   r?   r   out_spec
rest_inputrX   rb   	real_specs   ``         r*   rD   rD     s     *udm,,6:t4 ,GA,VAY=H""8, - v;Z($S_%67
j4::+<+<bjj*IJJ!&&.y/D.E Fv v 8 	vc*o&789	J	%	%6:t4!<<>KDz!(=:d+)% ).% * 	J 7 7	8	8T2F8<Q?	)V]]%<%<==CF82N  $	
I..(..IO
  Mj\Yghqgrrst  r-   c                     [        U5      nU S[        U5       n[        U5       H  u  p4X   n[        XE5      X'   M     U$ )a'  
Adds default name according to argument name from decorated function
if without specifying InputSpec.name

The naming rule are as followed:
    1. If InputSpec.name is not None, do nothing.
    2. If each argument `x` corresponds to an InputSpec, using the argument name like `x`
    3. If the arguments `inputs` corresponds to a list(InputSpec), using name like `inputs_0`, `inputs_1`
    4. If the arguments `input_dic` corresponds to a dict(InputSpec), using key as name.

For example:

    # case 1: foo(x, y)
    foo = to_static(foo, input_spec=[InputSpec([None, 10]), InputSpec([None])])
    print([in_var.name for in_var in foo.inputs])  # [x, y]

    # case 2: foo(inputs) where inputs is a list
    foo = to_static(foo, input_spec=[[InputSpec([None, 10]), InputSpec([None])]])
    print([in_var.name for in_var in foo.inputs])  # [inputs_0, inputs_1]

    # case 3: foo(inputs) where inputs is a dict
    foo = to_static(foo, input_spec=[{'x': InputSpec([None, 10]), 'y': InputSpec([None])}])
    print([in_var.name for in_var in foo.inputs])  # [x, y]
N)r8   r2   rH   _replace_spec_name)r   rj   candidate_arg_namesr?   r@   r)   s         r*   rI   rI     sP    2 ?+O#$:c/&:; !45$'
/E 6 r-   c                    [        U[        R                  R                  5      (       a  UR                  c  Xl        U$ [        U[
        [        45      (       a9  / n[        U5       H&  u  p4U  SU 3nUR                  [        XT5      5        M(     U$ [        U[        5      (       a*  0 nUR                  5        H  u  pd[        Xd5      X&'   M     U$ U$ )zD
Replaces InputSpec.name with given `name` while not specifying it.
_)r$   r   r`   ra   rX   r8   r;   rH   r:   r   r   r   )rX   r)   processed_specsr?   r   new_namerL   s          r*   r   r   5  s     *fmm5566??""O	Ju	.	. ,GAq}H""#5h#EF - 	J	%	%#))+IC#5c#@O  ,r-   c                   ^^ [         R                  R                  U 5       Vs/ s H:  n[        U[         R                  R
                  5      (       d  M.  UR                  PM<     nnU[         R                  R                  U5       Vs/ s H:  n[        U[         R                  R
                  5      (       d  M.  UR                  PM<     sn-  nS0 smmUU4S jnU Vs/ s H
  oT" U5      PM     nn[        U5      $ s  snf s  snf s  snf )a  
Generator hash spec with args/kwargs InputSpec names.
Consider the following InputSpecs with same shape/dtype except for name:
  1. [InputSpec([3,3], 'float32', 'x'), InputSpec([3,3], 'float32', 'x')]
  2. [InputSpec([3,3], 'float32', 'x'), InputSpec([3,3], 'float32', 'y')]
Under @to_static, we should generate two different program not just one, because
the former has one input ('x'), but the latter has two input ('x', 'y').
r   c                 .   > U T;  a
  TTU '   TS-  mTU    $ )Nr	   r   )rX   r?   name_idss    r*   to_idx _hash_spec_names.<locals>.to_idxa  s'    xHTNFA~r-   )r   r   r    r$   r`   ra   rX   r;   )	
args_specskwargs_specsr   
spec_namesr   rX   valuer?   r   s	          @@r*   _hash_spec_namesr   L  s     LL((44DdFMM334 			4  
 LL((66DdFMM334 			6 J
 RKAx '11jdVD\jE1<+
 2s   -C=C=	-D:DDc                 B    S nU" U R                   UR                   5      $ )Nc                 |    [        U 5      [        U5      :w  a  g[        X5       H  u  p#US:w  d  M  X#:w  d  M    g   g)NFT)r2   r   )first_shapesecond_shapefirst_nsecond_ns       r*   _shape_greater$spec_greater.<locals>._shape_greatern  s>    {s<00!$[!?G"}!4 "@ r-   )rY   )firstotherr  s      r*   r   r   m  s     %++u{{33r-   )T)'r   r   r   numpyr   r   paddle.pir.corer   r   r^   paddle.basepaddle.base.data_feederr   paddle.base.dygraph.baser   paddle.jit.pir_translated_layerr   paddle.jit.translated_layerr   paddle.nn.layerr    r
   r   r   r   r   r   __all__r   r   r   r   rE   rD   rI   r   r   r   r   r-   r*   <module>r     s         # #  1 ; > 7 "   Z: Z:z,*-`#LHV F.B	4r-   