Skip to content

Commit dd0a0ca

Browse files
committed
fix: gelu approximate, conv padding same/valid, grouped ConvTranspose, BatchNorm track_running_stats, ReduceLROnPlateau, Embedding padding_idx
1 parent f292646 commit dd0a0ca

7 files changed

Lines changed: 414 additions & 77 deletions

File tree

‎python/oxideon/__init__.pyi‎

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -766,17 +766,17 @@ class BassSerreGraphOfGroupsEngine:
766766

767767
class BatchNorm1d:
768768
"""1D Batch Normalization over 2D or 3D input."""
769-
def __init__(self, num_features: int, eps: float = 1e-05, momentum: float = 0.1, affine: bool = True) -> None: ...
769+
def __init__(self, num_features: int, eps: float = 1e-05, momentum: float = 0.1, affine: bool = True, track_running_stats: bool = True) -> None: ...
770770
def forward(self, x: Any) -> Any: ...
771771

772772
class BatchNorm2d:
773773
"""2D Batch Normalization over 4D NCHW input."""
774-
def __init__(self, num_features: int, eps: float = 1e-05, momentum: float = 0.1, affine: bool = True) -> None: ...
774+
def __init__(self, num_features: int, eps: float = 1e-05, momentum: float = 0.1, affine: bool = True, track_running_stats: bool = True) -> None: ...
775775
def forward(self, x: Any) -> Any: ...
776776

777777
class BatchNorm3d:
778778
"""3D Batch Normalization over 5D NCDHW input."""
779-
def __init__(self, num_features: int, eps: float = 1e-05, momentum: float = 0.1, affine: bool = True) -> None: ...
779+
def __init__(self, num_features: int, eps: float = 1e-05, momentum: float = 0.1, affine: bool = True, track_running_stats: bool = True) -> None: ...
780780
def forward(self, x: Any) -> Any: ...
781781

782782
class BatchSampler:
@@ -2905,7 +2905,7 @@ class ElsasserGeodynamoCoreEngine:
29052905

29062906
class Embedding:
29072907
"""Lookup table of `num_embeddings` vectors of size `embedding_dim`; the input is an integer tensor of indices."""
2908-
def __init__(self, num_embeddings: int, embedding_dim: int) -> None: ...
2908+
def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None) -> None: ...
29092909
def __call__(self, indices: Tensor) -> Tensor: ...
29102910
@property
29112911
def embedding_dim(self) -> int: ...
@@ -2915,6 +2915,8 @@ class Embedding:
29152915
def named_parameters(self, prefix: str = "") -> list[tuple[str, Tensor]]: ...
29162916
@property
29172917
def num_embeddings(self) -> int: ...
2918+
@property
2919+
def padding_idx(self) -> Optional[int]: ...
29182920
def parameters(self) -> list[Tensor]: ...
29192921
def state_dict(self, prefix: str = "") -> dict[str, Any]: ...
29202922
def train(self, mode: bool = True) -> None: ...
@@ -5682,19 +5684,19 @@ class LayerNorm:
56825684

56835685
class LazyBatchNorm1d:
56845686
"""1D Batch Normalization with lazy initialization of num_features."""
5685-
def __init__(self, eps: float = 1e-05, momentum: float = 0.1, affine: bool = True) -> None: ...
5687+
def __init__(self, eps: float = 1e-05, momentum: float = 0.1, affine: bool = True, track_running_stats: bool = True) -> None: ...
56865688
def forward(self, x: Any) -> Any: ...
56875689
def initialize_parameters(self, input: Any) -> Any: ...
56885690

56895691
class LazyBatchNorm2d:
56905692
"""2D Batch Normalization with lazy initialization of num_features."""
5691-
def __init__(self, eps: float = 1e-05, momentum: float = 0.1, affine: bool = True) -> None: ...
5693+
def __init__(self, eps: float = 1e-05, momentum: float = 0.1, affine: bool = True, track_running_stats: bool = True) -> None: ...
56925694
def forward(self, x: Any) -> Any: ...
56935695
def initialize_parameters(self, input: Any) -> Any: ...
56945696

56955697
class LazyBatchNorm3d:
56965698
"""3D Batch Normalization with lazy initialization of num_features."""
5697-
def __init__(self, eps: float = 1e-05, momentum: float = 0.1, affine: bool = True) -> None: ...
5699+
def __init__(self, eps: float = 1e-05, momentum: float = 0.1, affine: bool = True, track_running_stats: bool = True) -> None: ...
56985700
def forward(self, x: Any) -> Any: ...
56995701
def initialize_parameters(self, input: Any) -> Any: ...
57005702

@@ -8414,6 +8416,7 @@ class ReduceLROnPlateau:
84148416
def __init__(self, optimizer: Any, mode: str = 'min', factor: float = 0.1, patience: int = 10, threshold: float = 0.0001, threshold_mode: str = 'rel', min_lr: float = 0.0) -> None: ...
84158417
def _is_better(self, current: float) -> bool: ...
84168418
def _reduce_lr(self) -> None: ...
8419+
def get_last_lr(self) -> list[float]: ...
84178420
def step(self, metrics: float) -> None: ...
84188421

84198422
class ReduceLROnPlateauCallback:
@@ -10139,7 +10142,7 @@ class SymplecticTopologyEngine:
1013910142

1014010143
class SyncBatchNorm:
1014110144
"""Applies Batch Normalization synchronized across multiple processes."""
10142-
def __init__(self, num_features: int, eps: float = 1e-05, momentum: float = 0.1, affine: bool = True) -> None: ...
10145+
def __init__(self, num_features: int, eps: float = 1e-05, momentum: float = 0.1, affine: bool = True, track_running_stats: bool = True) -> None: ...
1014310146
@classmethod
1014410147
def convert_sync_batchnorm(self, module: Any) -> Any: ...
1014510148

@@ -12233,17 +12236,17 @@ def concordance_index(risk_scores: Tensor, durations: Tensor, events: Tensor) ->
1223312236

1223412237
def confusion_matrix(preds: Any, targets: Any, num_classes: Any = None) -> Any: ...
1223512238

12236-
def conv1d(input: Tensor, weight: Tensor, bias: Tensor | None = None, stride: int = 1, padding: int = 0, dilation: int = 1, groups: int = 1) -> Tensor: ...
12239+
def conv1d(input: Tensor, weight: Tensor, bias: Tensor | None = None, stride: int = 1, padding: int | str = 0, dilation: int = 1, groups: int = 1) -> Tensor: ...
1223712240

12238-
def conv2d(input: Tensor, weight: Tensor, bias: Tensor | None = None, stride: int | tuple[int, int] = 1, padding: int | tuple[int, int] = 0, dilation: int | tuple[int, int] = 1, groups: int = 1) -> Tensor: ...
12241+
def conv2d(input: Tensor, weight: Tensor, bias: Tensor | None = None, stride: int | tuple[int, int] = 1, padding: int | tuple[int, int] | str = 0, dilation: int | tuple[int, int] = 1, groups: int = 1) -> Tensor: ...
1223912242

1224012243
def conv2d_flops(batch: Any, c_in: Any, c_out: Any, kh: Any, kw: Any, h_out: Any, w_out: Any, groups: Any = 1) -> Any: ...
1224112244

1224212245
def conv3d(input: Tensor, weight: Tensor, bias: Tensor | None = None, stride: int | tuple[int, int, int] = 1, padding: int | tuple[int, int, int] = 0, dilation: int = 1, groups: int = 1) -> Tensor: ...
1224312246

1224412247
def conv_transpose1d(input: Tensor, weight: Tensor, bias: Tensor | None = None, stride: int = 1, padding: int = 0, output_padding: int = 0, groups: int = 1, dilation: int = 1) -> Tensor: ...
1224512248

12246-
def conv_transpose2d(input: Tensor, weight: Tensor, bias: Tensor | None = None, stride: int | tuple[int, int] = 1, padding: int | tuple[int, int] = 0, output_padding: int | tuple[int, int] = 0, groups: int = 1, dilation: int = 1) -> Tensor: ...
12249+
def conv_transpose2d(input: Tensor, weight: Tensor, bias: Tensor | None = None, stride: int | tuple[int, int] = 1, padding: int | tuple[int, int] = 0, output_padding: int | tuple[int, int] = 0, groups: int = 1, dilation: int | tuple[int, int] = 1) -> Tensor: ...
1224712250

1224812251
def conv_transpose3d(input: Tensor, weight: Tensor, bias: Tensor | None = None, stride: int = 1, padding: int = 0, output_padding: int = 0, groups: int = 1, dilation: int = 1) -> Tensor: ...
1224912252

@@ -12683,7 +12686,7 @@ def gcd(a: Tensor, b: Tensor) -> Tensor: ...
1268312686

1268412687
def gegenbauer(input: Tensor, n: int, alpha: float) -> Tensor: ...
1268512688

12686-
def gelu(input: Tensor) -> Tensor: ...
12689+
def gelu(input: Tensor, approximate: str = 'none') -> Tensor: ...
1268712690

1268812691
def generalized_entropy_index(y_true: Any, y_pred: Any, alpha: float = 2.0) -> float: ...
1268912692

@@ -13499,7 +13502,7 @@ def scatter_max(src: Tensor, index: Any, dim: int = 0, dim_size: int | None = No
1349913502

1350013503
def scatter_mean(src: Tensor, index: Any, dim: int = 0, dim_size: int | None = None) -> Tensor: ...
1350113504

13502-
def scatter_reduce(x: Tensor, dim: int, index: Tensor, src: Tensor, reduce: str, *, include_self: bool = True) -> Tensor: ...
13505+
def scatter_reduce(x: Tensor, dim: int, index: Tensor, src: Tensor, reduce: str, include_self: bool = True) -> Tensor: ...
1350313506

1350413507
def schedule(wait: int = 0, warmup: int = 0, active: int = 1, repeat: int = 1, skip_first: int = 0) -> Any: ...
1350513508

‎python/oxideon/functional.py‎

Lines changed: 75 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -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

130135
def 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+
500538
def 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

513556
def 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

529576
def 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+
568627
def 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

Comments
 (0)