
    
Ng-                        d dl Z d dlZd dlmZmZmZ d dlZd dlm	Z	 de
dee         dee         dee         dee         d	ee         fd
Zde
dee         d	ee         fdZ	 	 d!dee         dee         dee         dee         deee         df         ded	eee         ee         f         fdZde
dee         dee         dee         d	ee         f
dZdej        ded	efdZ	 	 	 	 d"dej        dee         dee         dee         dee         de
deee         df         deee         df         deded	ej        fdZ G d d e	          ZdS )#    N)SequenceTupleUnion)OpRunauto_padinput_spatial_shapekernel_spatial_shapestrides_spatialoutput_spatial_shapereturnc                     t          |          }dg|z  }|pdg|z  }| dv r<t          |          D ]+}||         dz
  ||         z  ||         z   ||         z
  ||<   ,n| dk    r	 |S )Nr      
SAME_UPPER
SAME_LOWERVALIDlenrange)r   r   r	   r
   r   spatial_dims	pad_shapeis           ]/var/www/html/ai-engine/env/lib/python3.11/site-packages/onnx/reference/ops/op_pool_common.pyget_pad_shaper      s     *++Ll"I%;!|);O///|$$ 	 	A%a(1,0BB&q)*%a() aLL	 
W		    r   c                 0   t                    }| dk    r8fdt          |          D             fdt          |          D             z   }nG| dk    r8fdt          |          D             fdt          |          D             z   }n	dg|z  dz  }|S )	Nr   c                 &    g | ]}|         d z  S     .0r   r   s     r   
<listcomp>z)get_pad_with_auto_pad.<locals>.<listcomp>(   s"    ???a	!!???r   c                 8    g | ]}|         |         d z  z
  S r   r    r!   s     r   r#   z)get_pad_with_auto_pad.<locals>.<listcomp>(   s>     C
 C
 C
12IaL9Q<1,,C
 C
 C
r   r   c                 8    g | ]}|         |         d z  z
  S r   r    r!   s     r   r#   z)get_pad_with_auto_pad.<locals>.<listcomp>,   s+    NNNQ	!y|q00NNNr   c                 &    g | ]}|         d z  S r   r    r!   s     r   r#   z)get_pad_with_auto_pad.<locals>.<listcomp>,   s5     R
 R
 R
"#IaLAR
 R
 R
r   r   r   r   )r   r   r   padss    `  r   get_pad_with_auto_padr(   %   s    y>>L<????5+>+>??? C
 C
 C
 C
6;L6I6IC
 C
 C
 
 
\	!	!NNNN%:M:MNNN R
 R
 R
 R
',\':':R
 R
 R
 
 s\!A%Kr   Fr'   	dilations	ceil_modec                 b   dgt          |          z  }| pdgt          |          z  dz  } |pdgt          |          z  }t          |          }|!t          j        |gt          j                  }t	          |          D ]}||         | |         z   | ||z            z   ||         ||         dz
  z  z
  dz
  ||         z  dz   }	|r%t          t          j        |	                    ||<   jt          t          j        |	                    ||<   | dd         }
t	          |          D ]}||         dz
  ||         z  dz   }||         dz
  ||         z  |z   }|||         z
  | |         z
  | ||z            z
  }|dk    r,|
|xx         |dz  z  cc<   |
||z   xx         ||dz  z
  z  cc<   ||
fS )a  Compute output shape according to:
    https://pytorch.org/docs/stable/generated/torch.nn.MaxPool1d.html?highlight=max+pool#torch.nn.MaxPool1d
    Pads are used to calculate output shape. Use output shape in turn to calculate the actual pads
    that are used to pad the input tensor so that computation in pool() will not cause out of bound error.
    Here is the detail. Thinking kernel as a sliding window, its size:
    sw = dilation * (kernel - 1) + 1
    l_out = (l_in + pad[0] + pad[1] - sw) / stride + 1 # (ceiled if ceil_mode is True)
    l_in_required = (l_out - 1) * stride + sw

    l_in_required is used to for computation in pool() which may be larger than padded l_in, because of ceiling.
    as an example, l_in = 3, kernel = 2, stride = 2, dilation = 1, pad = [0, 0], then
    sw = dilation * (kernel - 1) + 1 = 1 * (2 - 1) + 1 = 2
    l_out = ceil((l_in + pad[0] + pad[1] - sw) / stride + 1) = ceil((3 + 0 + 0 - 1 * (2 - 1) - 1) / 2 + 1) = 2
    l_in_required = (l_out - 1) * stride + sw = (2 - 1) * 2 + 2 = 4
    l_in_required (= 4) is not equal to l_in (= 3), so we need to pad the input tensor to l_in_required to make sure that
    the sliding window does not go out-of-bound w.r.t. input tensor. Otherwise pool() will fail.
    r   r   r   Ndtype)r   nponesint64r   intceilfloor)r'   r   r	   r
   r)   r*   r   dimsdimdim_sizepads_spatial_shape_newsliding_window_sizeactual_padded_input_size	extra_pads                 r   !get_output_shape_explicit_paddingr;   4   sL   2 3%8!9!995A30111A5D%G!s3F/G/G)GO"##DGTF"(333	T{{ @ @$3i4#: n 4S 9A =>? 	
 C ! $%%  	@(+BGH,=,=(>(> %%(+BHX,>,>(?(? %%!!!!WT{{ M M3C81<	#NQRR$8$=$A_F
 $
$   %!#&'3i 4#: 	 q=="3'''9>9'''"4#:...)i1n2LL...!777r   c                    |pdgt          |          z  }dgt          |          z  }t          t          |                    D ]z}| dv r-t          j        ||         dz
  ||         z            dz   ||<   3| dk    r3t          j        ||         ||         z
  ||         z            dz   ||<   lt	          d          |S )a  https://www.tensorflow.org/api_docs/python/tf/keras/layers/AveragePooling2D
    output_shape = math.floor((input_shape - 1) / strides) + 1  (SAME)
    output_shape = math.floor((input_shape - pool_size) / strides) + 1 (VALID)
    IMPORTANT: this function assumes ceil_mode is False. In tenforflow, ceil_mode is always False.
    However, ONNX spec allow ceil_mode to be True because ORT does handle the case.
    r   r   r   r   z=auto_pad can only be NOTSET, SAME_UPPER, SAME_LOWER, or VALID)r   r   mathr3   
ValueError)r   r   r	   r
   	out_shaper   s         r   get_output_shape_auto_padr@   u   s    &G!s3F/G/G)GOc-...I3*++,,  333
/2Q6/!:LLMMPQQ aLL   
(+.B1.EE%a()  	 aLL O  
 r   xpc                 n    d}t          j        |           D ]}|t          |          |z  z  }|d|z  z  S )Nr   g      ?)r.   nditerabs)rA   rB   yvs       r   lp_poolrH      sB    	AYq\\  	SVVq[q>r   r   paddedx_shapekernelstridesr?   pooling_typecount_include_padc
                 F  	 t                    dz
  t          j        d         d         gt          |          | j                  }
!t          j        gt          j                  %t          j        dz  gt          j                  nt                    dk    rz  dz  pdgz  	fd}t          j        t          d                   t          d                   gfdt                    D             R  D ]| d         d         f         t          j
        fdt          t          j        fd	t                    D                        D                       }|d
k    rt          j        }n/|dk    rt          j        }n|dk    r|}nt          d| d          |dk    r|dv r ||          |
<    ||t          j        t          j        |                                        |
<   |
S )a]  This function is used to calculate the pooling result of a padded tensor
    padded: the padded tensor
    x_shape: the shape of the original tensor in [N, C, *spatial_shape]
    kernel: the pooling kernel
    strides: the strides
    out_shape: the shape of the output tensor
    pooling_type: the pooling type, can be "AVG", "LPPOOL", or "MAX"
    pads: the padding in an order of head_pad_1, head_pad_2, ..., tail_pad_1, tail_pad_2, ...
    dilations: the dilation
    count_include_pad: whether to include the padding in the calculation of average and lp pooling
    p: the p value for lp pooling
    r   r   r   r,   Nc                 $    t          |           S )N)rH   )rA   rB   s    r   	lp_pool_pzpool.<locals>.lp_pool_p   s    q!}}r   c                     g | ]`}t          t          |d z            |         z   |z            z   d|         dz
  |         z  z   z
  |         z  dz                       aS r   r   )r   r1   )r"   r   r)   rK   r'   spatial_sizerL   rJ   s     r   r#   zpool.<locals>.<listcomp>   s     

 

 

  Aq'"q</01 q	A1==?
 aj! 	 	 

 

 

r   c                      g | ]
}|         S r    r    )r"   r   windows     r   r#   zpool.<locals>.<listcomp>   s-        q	  r   c           
          g | ]U}t          |         |d z            z  |         |d z            z  d|         dz
  |         z  z   z   |                   VS rS   )r   )r"   r   r)   rK   shaperL   s     r   r#   zpool.<locals>.<listcomp>   s        !" " '
U1q5\ 9 '
U1q5\ 9#$q	A1'E#E!G )!	   r   AVGMAXLPPOOLzPooling type z% does not support. Should be AVG, MAX>   rY   r[   )r   r.   zeroslistr-   r/   r0   	itertoolsproductr   arrayaveragemaxNotImplementedErrorwhereisnan)rI   rJ   rK   rL   r?   rM   r'   r)   rN   rB   rF   rQ   window_valsfrX   rT   rV   s    ```  `` `    @@@r   poolrh      s   0 w<<!#L
'!*gaj;4	??;6<PPPAG\N"(;;;	|x)*"(;;;	Tal"Q&+!|+G     "gajgaj

 

 

 

 

 

 

 

 

 <((

 

 

   4H 4H& a%(*+h   %       &+<%8%8  
   
 
$ 5  
AAU""AAX%%AA%SSSS   !!|7H'H'Hq~~AeHHqRXrx/D/D.D%E%EFGGAeHHHr   c                   $    e Zd Z	 	 	 	 	 	 	 ddZdS )
CommonPoolNc                    t          j        |          }|dk    s|dk    rt           j        nd}|dv r||dk    s
J d            t          ||j        dd          ||	          }t	          ||dd          ||	|          }t          ||          t                    dz  fdt                    D             }t          j        |ddg|R d|	          }t          ||||	|||||

  
        }|fS t          |dd          ||	||          \  }t                    dz  fd
t                    D             }t          j        |ddg|R d|	          }t          ||||	|||||

  
        }|fS )NrZ   r   )r   r   r   z(ceil_mode is not supported with auto_padr   c                 6    g | ]}|         |z            fS r    r    r"   r   n_dimsr'   s     r   r#   z#CommonPool._run.<locals>.<listcomp>  +    JJJqQa&j!12JJJr   )r   r   constant)modeconstant_valuesc                 6    g | ]}|         |z            fS r    r    rm   s     r   r#   z#CommonPool._run.<locals>.<listcomp>5  ro   r   )r.   rX   nanr@   r   r(   r   r   padrh   r;   )selfrM   rN   rA   r   r*   r)   kernel_shaper'   rL   rB   rJ   pading_valuer?   
pads_shapepads_nprI   rF   rn   s           `         @r   _runzCommonPool._run   s    (1++!-!6!6:Kq:P:PrvvVW<<<!Y!^^^9 &4^^1!'!""+|W I ''!""+|Wi J ):>>DYY!^FJJJJJE&MMJJJGV*'** ,	  F ! A 4K?gabbk<)Y OIt YY!^FJJJJJE&MMJJJGV*'** ,	  F ! A 4Kr   )NNNNNNN)__name__
__module____qualname__r{   r    r   r   rj   rj      sE         
I I I I I Ir   rj   )NF)NNr   r   )r^   r=   typingr   r   r   numpyr.   onnx.reference.op_runr   strr1   r   r(   boolr;   r@   r`   floatrH   ndarrayrh   rj   r    r   r   <module>r      s  
      ) ) ) ) ) ) ) ) ) )     ' ' ' ' ' '!# #3- c]	
 #3- c]   .C HSM hsm    ( -1>8 >8
3->8!#>8 #3->8 c]	>8
 Xc]D()>8 >8 8C=(3-'(>8 >8 >8 >8B""!#" #3-" c]	"
 c]" " " "Jrx C E     (,,0Z ZJZc]Z SMZ c]	Z
 }Z Z t#
$Z Xc]D()Z Z Z ZZ Z Z ZzJ J J J J J J J J Jr   