@@ -122,9 +122,14 @@ def relu6(input: _Tensor) -> _Tensor:
122122 return input .clamp (0.0 , 6.0 )
123123
124124
125- def gelu (input : _Tensor ) -> _Tensor :
125+ def gelu (input : _Tensor , approximate : str = "none" ) -> _Tensor :
126126 """Applies Gaussian Error Linear Units function element-wise."""
127- return input .gelu ()
127+ if approximate == "none" :
128+ return input .gelu ()
129+ if approximate == "tanh" :
130+ c = math .sqrt (2.0 / math .pi )
131+ return 0.5 * input * (1.0 + (c * (input + 0.044715 * input .pow (3.0 ))).tanh ())
132+ raise ValueError (f"gelu: approximate must be 'none' or 'tanh', got { approximate !r} " )
128133
129134
130135def silu (input : _Tensor ) -> _Tensor :
@@ -497,33 +502,75 @@ def feature_alpha_dropout(input: _Tensor, p: float = 0.5, training: bool = True)
497502# Convolutions
498503# ---------------------------------------------------------------------------
499504
505+ def _resolve_conv_padding (
506+ padding : Any ,
507+ strides : Sequence [int ],
508+ kernels : Sequence [int ],
509+ dilations : Sequence [int ],
510+ op_name : str ,
511+ ) -> Tuple [Tuple [int , ...], Optional [List [Tuple [int , int ]]]]:
512+ if isinstance (padding , str ):
513+ mode = padding .lower ()
514+ if mode == "valid" :
515+ return tuple (0 for _ in kernels ), None
516+ if mode == "same" :
517+ if any (s != 1 for s in strides ):
518+ raise ValueError (f"{ op_name } : padding='same' is not supported when any stride != 1 (got { tuple (strides )} )" )
519+ sym = []
520+ asym = []
521+ has_asym = False
522+ for k , d in zip (kernels , dilations ):
523+ tot = int (d ) * (int (k ) - 1 )
524+ left = tot // 2
525+ right = tot - left
526+ sym .append (left )
527+ asym .append ((left , right ))
528+ if left != right :
529+ has_asym = True
530+ if has_asym :
531+ return tuple (0 for _ in kernels ), asym
532+ return tuple (sym ), None
533+ raise ValueError (f"{ op_name } : invalid padding string { padding !r} , expected 'same' or 'valid'" )
534+ p_tuple = tuple (int (padding ) for _ in kernels ) if isinstance (padding , int ) else tuple (int (v ) for v in padding )
535+ return p_tuple , None
536+
537+
500538def conv1d (
501539 input : _Tensor ,
502540 weight : _Tensor ,
503541 bias : Optional [_Tensor ] = None ,
504542 stride : int = 1 ,
505- padding : int = 0 ,
543+ padding : Union [ int , str ] = 0 ,
506544 dilation : int = 1 ,
507545 groups : int = 1 ,
508546) -> _Tensor :
509547 """Applies a 1D convolution over an input signal composed of several input planes."""
510- return _native_conv1d (input , weight , bias , stride , padding , dilation , groups )
548+ x = _as_tensor (input )
549+ w = _as_tensor (weight )
550+ p_sym , p_asym = _resolve_conv_padding (padding , (stride ,), (w .shape [2 ],), (dilation ,), "conv1d" )
551+ if p_asym is not None :
552+ x = _diff_pad_nd (x , p_asym )
553+ return _native_conv1d (x , w , bias , stride , p_sym [0 ], dilation , groups )
511554
512555
513556def conv2d (
514557 input : _Tensor ,
515558 weight : _Tensor ,
516559 bias : Optional [_Tensor ] = None ,
517560 stride : Union [int , Tuple [int , int ]] = 1 ,
518- padding : Union [int , Tuple [int , int ]] = 0 ,
561+ padding : Union [int , Tuple [int , int ], str ] = 0 ,
519562 dilation : Union [int , Tuple [int , int ]] = 1 ,
520563 groups : int = 1 ,
521564) -> _Tensor :
522565 """Applies a 2D convolution over an input image composed of several input planes."""
566+ x = _as_tensor (input )
567+ w = _as_tensor (weight )
523568 s = (stride , stride ) if isinstance (stride , int ) else tuple (stride )
524- p = (padding , padding ) if isinstance (padding , int ) else tuple (padding )
525569 d = (dilation , dilation ) if isinstance (dilation , int ) else tuple (dilation )
526- return _native_conv2d (input , weight , bias , s , p , d , groups )
570+ p_sym , p_asym = _resolve_conv_padding (padding , s , (w .shape [2 ], w .shape [3 ]), d , "conv2d" )
571+ if p_asym is not None :
572+ x = _diff_pad_nd (x , p_asym )
573+ return _native_conv2d (x , w , bias , s , p_sym , d , groups )
527574
528575
529576def conv3d (
@@ -565,6 +612,18 @@ def conv3d(
565612 return _wrap (res , like = input )
566613
567614
615+ def _grouped_conv_t_matmul (x_pt : _Tensor , w_pt : _Tensor , groups : int ) -> _Tensor :
616+ """Grouped linear projection [N, C_in] @ [C_in, C_out_per_group] -> [N, C_out_per_group * groups]."""
617+ if groups == 1 :
618+ return x_pt .matmul (w_pt )
619+ n , c_in = int (x_pt .shape [0 ]), int (x_pt .shape [1 ])
620+ c_in_g = c_in // groups
621+ c_out_g = int (w_pt .shape [1 ])
622+ xg = x_pt .reshape ([n , groups , c_in_g ]).transpose (0 , 1 )
623+ wg = w_pt .reshape ([groups , c_in_g , c_out_g ])
624+ return xg .matmul (wg ).transpose (0 , 1 ).reshape ([n , groups * c_out_g ])
625+
626+
568627def conv_transpose1d (
569628 input : _Tensor ,
570629 weight : _Tensor ,
@@ -589,7 +648,7 @@ def conv_transpose1d(
589648 for k in range (K ):
590649 pos = start + k * dilation
591650 if 0 <= pos < L_out :
592- contrib = x [:, :, i ]. matmul ( w [:, :, k ])
651+ contrib = _grouped_conv_t_matmul ( x [:, :, i ], w [:, :, k ], groups )
593652 mask = np .zeros ((L_out ,), dtype = dt )
594653 mask [pos ] = 1
595654 out = out + contrib [:, :, None ] * _from_numpy (mask )
@@ -607,20 +666,21 @@ def conv_transpose2d(
607666 padding : Union [int , Tuple [int , int ]] = 0 ,
608667 output_padding : Union [int , Tuple [int , int ]] = 0 ,
609668 groups : int = 1 ,
610- dilation : int = 1 ,
669+ dilation : Union [ int , Tuple [ int , int ]] = 1 ,
611670) -> _Tensor :
612671 """Applies a 2D transposed convolution operator over an input image."""
613672 # Differentiable masked accumulation (stays in the autograd graph).
614673 s = (stride , stride ) if isinstance (stride , int ) else stride
615674 p = (padding , padding ) if isinstance (padding , int ) else padding
616675 op = (output_padding , output_padding ) if isinstance (output_padding , int ) else output_padding
676+ d = (dilation , dilation ) if isinstance (dilation , int ) else dilation
617677
618678 x = _as_tensor (input )
619679 w = _as_tensor (weight )
620680 N , C_in , H_in , W_in = (int (v ) for v in x .shape )
621681 _ , C_out , kH , kW = (int (v ) for v in w .shape )
622- H_out = (H_in - 1 ) * s [0 ] - 2 * p [0 ] + (kH - 1 ) * dilation + op [0 ] + 1
623- W_out = (W_in - 1 ) * s [1 ] - 2 * p [1 ] + (kW - 1 ) * dilation + op [1 ] + 1
682+ H_out = (H_in - 1 ) * s [0 ] - 2 * p [0 ] + (kH - 1 ) * d [ 0 ] + op [0 ] + 1
683+ W_out = (W_in - 1 ) * s [1 ] - 2 * p [1 ] + (kW - 1 ) * d [ 1 ] + op [1 ] + 1
624684
625685 dt = _to_np (x ).dtype
626686 out = _from_numpy (np .zeros ((N , C_out * groups , H_out , W_out ), dtype = dt ))
@@ -630,10 +690,10 @@ def conv_transpose2d(
630690 w_start = w_idx * s [1 ] - p [1 ]
631691 for kh in range (kH ):
632692 for kw in range (kW ):
633- pos_h = h_start + kh * dilation
634- pos_w = w_start + kw * dilation
693+ pos_h = h_start + kh * d [ 0 ]
694+ pos_w = w_start + kw * d [ 1 ]
635695 if 0 <= pos_h < H_out and 0 <= pos_w < W_out :
636- contrib = x [:, :, h , w_idx ]. matmul ( w [:, :, kh , kw ])
696+ contrib = _grouped_conv_t_matmul ( x [:, :, h , w_idx ], w [:, :, kh , kw ], groups )
637697 mask = np .zeros ((H_out , W_out ), dtype = dt )
638698 mask [pos_h , pos_w ] = 1
639699 out = out + contrib [:, :, None , None ] * _from_numpy (mask )
@@ -679,7 +739,7 @@ def conv_transpose3d(
679739 ph = h_pos + kh * dilation
680740 pw = w_pos + kw * dilation
681741 if 0 <= pd < D_out and 0 <= ph < H_out and 0 <= pw < W_out :
682- contrib = x [:, :, d , h , w_idx ]. matmul ( w [:, :, kd , kh , kw ])
742+ contrib = _grouped_conv_t_matmul ( x [:, :, d , h , w_idx ], w [:, :, kd , kh , kw ], groups )
683743 mask = np .zeros ((D_out , H_out , W_out ), dtype = dt )
684744 mask [pd , ph , pw ] = 1
685745 out = out + contrib [:, :, None , None , None ] * _from_numpy (mask )
0 commit comments