Skip to content

Commit e9b2384

Browse files
committed
fix: squeeze tuple, tensor clamp bounds, LayerNorm affine/bias, optimizer state_dict, param_groups, MHA dropout, utils vectors
1 parent dd0a0ca commit e9b2384

6 files changed

Lines changed: 371 additions & 44 deletions

File tree

‎python/oxideon/__init__.pyi‎

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -228,17 +228,25 @@ class Adagrad:
228228
class Adam:
229229
"""Adam with optional (coupled, L2) weight decay; use `AdamW` for decoupled decay."""
230230
def __init__(self, params: list[Tensor], lr: float = 1e-3, betas: tuple[float, float] = (0.9, 0.999), eps: float = 1e-8, weight_decay: float = 0.0, amsgrad: bool = False, maximize: bool = False) -> None: ...
231+
def load_state_dict(self, state_dict: dict[str, Any]) -> None: ...
231232
@property
232233
def lr(self) -> float: ...
234+
@property
235+
def param_groups(self) -> list[Any]: ...
233236
def set_learning_rate(self, lr: float) -> None: ...
237+
def state_dict(self) -> dict[str, Any]: ...
234238
def step(self) -> None: ...
235239
def zero_grad(self) -> None: ...
236240

237241
class AdamW:
238242
def __init__(self, params: list[Tensor], lr: float = 1e-3, betas: tuple[float, float] = ..., eps: float = 1e-8, weight_decay: float = 1e-2, amsgrad: bool = False, maximize: bool = False) -> None: ...
243+
def load_state_dict(self, state_dict: dict[str, Any]) -> None: ...
239244
@property
240245
def lr(self) -> float: ...
246+
@property
247+
def param_groups(self) -> list[Any]: ...
241248
def set_learning_rate(self, lr: float) -> None: ...
249+
def state_dict(self) -> dict[str, Any]: ...
242250
def step(self) -> None: ...
243251
def zero_grad(self) -> None: ...
244252

@@ -5000,17 +5008,17 @@ class InformationGeometryEngine:
50005008

50015009
class InstanceNorm1d:
50025010
"""Applies 1D Instance Normalization."""
5003-
def __init__(self, num_features: int, eps: float = 1e-05, momentum: float = 0.1, affine: bool = False) -> None: ...
5011+
def __init__(self, num_features: int, eps: float = 1e-05, momentum: float = 0.1, affine: bool = False, track_running_stats: bool = False) -> None: ...
50045012
def forward(self, x: Any) -> Any: ...
50055013

50065014
class InstanceNorm2d:
50075015
"""Applies 2D Instance Normalization."""
5008-
def __init__(self, num_features: int, eps: float = 1e-05, momentum: float = 0.1, affine: bool = False) -> None: ...
5016+
def __init__(self, num_features: int, eps: float = 1e-05, momentum: float = 0.1, affine: bool = False, track_running_stats: bool = False) -> None: ...
50095017
def forward(self, x: Any) -> Any: ...
50105018

50115019
class InstanceNorm3d:
50125020
"""Applies 3D Instance Normalization."""
5013-
def __init__(self, num_features: int, eps: float = 1e-05, momentum: float = 0.1, affine: bool = False) -> None: ...
5021+
def __init__(self, num_features: int, eps: float = 1e-05, momentum: float = 0.1, affine: bool = False, track_running_stats: bool = False) -> None: ...
50145022
def forward(self, x: Any) -> Any: ...
50155023

50165024
class IntegratedGradients:
@@ -5660,13 +5668,13 @@ class LaxKdvInverseScatteringSoliton:
56605668

56615669
class LayerNorm:
56625670
"""Layer normalization over dimensions (`normalized_shape` is an int or a list/tuple)."""
5663-
def __init__(self, normalized_shape: Any, eps: float = 1e-5) -> None: ...
5671+
def __init__(self, normalized_shape: Any, eps: float = 1e-5, elementwise_affine: bool = True, bias: bool = True) -> None: ...
56645672
def __call__(self, x: Tensor) -> Tensor: ...
56655673
def __repr__(self) -> str: ...
56665674
@property
5667-
def bias(self) -> Tensor: ...
5675+
def bias(self) -> Optional[Tensor]: ...
56685676
@bias.setter
5669-
def bias(self, value: Tensor) -> None: ...
5677+
def bias(self, value: Optional[Tensor]) -> None: ...
56705678
def eval(self) -> None: ...
56715679
def forward(self, x: Tensor) -> Tensor: ...
56725680
def load_state_dict(self, state_dict: dict[str, Any], strict: bool = True) -> dict[str, Any]: ...
@@ -5677,9 +5685,9 @@ class LayerNorm:
56775685
def state_dict(self, prefix: str = "") -> dict[str, Any]: ...
56785686
def train(self, mode: bool = True) -> None: ...
56795687
@property
5680-
def weight(self) -> Tensor: ...
5688+
def weight(self) -> Optional[Tensor]: ...
56815689
@weight.setter
5682-
def weight(self, value: Tensor) -> None: ...
5690+
def weight(self, value: Optional[Tensor]) -> None: ...
56835691
def zero_grad(self) -> None: ...
56845692

56855693
class LazyBatchNorm1d:
@@ -8868,11 +8876,13 @@ class SELU:
88688876
class SGD:
88698877
"""Stochastic gradient descent with optional momentum and L2 weight decay."""
88708878
def __init__(self, params: list[Tensor], lr: float = 1e-2, momentum: float = 0.0, dampening: float = 0.0, weight_decay: float = 0.0, nesterov: bool = False, maximize: bool = False) -> None: ...
8879+
def load_state_dict(self, state_dict: dict[str, Any]) -> None: ...
88718880
@property
88728881
def lr(self) -> float: ...
88738882
@property
88748883
def param_groups(self) -> list[Any]: ...
88758884
def set_learning_rate(self, lr: float) -> None: ...
8885+
def state_dict(self) -> dict[str, Any]: ...
88768886
def step(self) -> None: ...
88778887
def zero_grad(self) -> None: ...
88788888

@@ -12186,13 +12196,13 @@ def chunk(input: Tensor, chunks: int, dim: int = 0) -> Any: ...
1218612196

1218712197
def circular_velocity(m_central: float, r: float, g: float = 1.0) -> float: ...
1218812198

12189-
def clamp(input: Tensor, min: float | None = None, max: float | None = None) -> Tensor: ...
12199+
def clamp(input: Tensor, min: Any = None, max: Any = None) -> Tensor: ...
1219012200

1219112201
def clamp_max(input: Tensor, max: float) -> Tensor: ...
1219212202

1219312203
def clamp_min(input: Tensor, min: float) -> Tensor: ...
1219412204

12195-
def clip(input: Tensor, min: float | None = None, max: float | None = None) -> Tensor: ...
12205+
def clip(input: Tensor, min: Any = None, max: Any = None) -> Tensor: ...
1219612206

1219712207
def clip_grad_norm_(parameters: Any, max_norm: float, norm_type: float = 2.0) -> float: ...
1219812208

‎python/oxideon/nn.py‎

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1539,6 +1539,8 @@ def forward(
15391539
scores = scores + kpm_t.to_dtype(scores.dtype).reshape([B, 1, 1, S])
15401540

15411541
weights = scores.softmax(-1)
1542+
if self.training and self.dropout_p > 0.0:
1543+
weights = functional.dropout(weights, p=self.dropout_p, training=True)
15421544

15431545
attn_out = weights.matmul(v).transpose(1, 2).reshape([B, L, E])
15441546
out = self.out_proj(attn_out)
@@ -2401,17 +2403,25 @@ def forward(self, x):
24012403

24022404
class InstanceNorm1d(Module):
24032405
"""Applies 1D Instance Normalization."""
2404-
def __init__(self, num_features: int, eps: float = 1e-5, momentum: float = 0.1, affine: bool = False):
2406+
def __init__(self, num_features: int, eps: float = 1e-5, momentum: float = 0.1, affine: bool = False, track_running_stats: bool = False):
24052407
super().__init__()
24062408
self.num_features = num_features
24072409
self.eps = eps
2410+
self.momentum = momentum
24082411
self.affine = affine
2412+
self.track_running_stats = track_running_stats
24092413
if affine:
24102414
self.weight = Parameter(_Tensor.ones([1, num_features, 1]))
24112415
self.bias = Parameter(_Tensor.zeros([1, num_features, 1]))
24122416
else:
24132417
self.weight = None
24142418
self.bias = None
2419+
if track_running_stats:
2420+
self.running_mean = _Tensor.zeros([num_features])
2421+
self.running_var = _Tensor.ones([num_features])
2422+
else:
2423+
self.running_mean = None
2424+
self.running_var = None
24152425

24162426
def forward(self, x):
24172427
from . import functional as F
@@ -2420,17 +2430,25 @@ def forward(self, x):
24202430

24212431
class InstanceNorm2d(Module):
24222432
"""Applies 2D Instance Normalization."""
2423-
def __init__(self, num_features: int, eps: float = 1e-5, momentum: float = 0.1, affine: bool = False):
2433+
def __init__(self, num_features: int, eps: float = 1e-5, momentum: float = 0.1, affine: bool = False, track_running_stats: bool = False):
24242434
super().__init__()
24252435
self.num_features = num_features
24262436
self.eps = eps
2437+
self.momentum = momentum
24272438
self.affine = affine
2439+
self.track_running_stats = track_running_stats
24282440
if affine:
24292441
self.weight = Parameter(_Tensor.ones([1, num_features, 1, 1]))
24302442
self.bias = Parameter(_Tensor.zeros([1, num_features, 1, 1]))
24312443
else:
24322444
self.weight = None
24332445
self.bias = None
2446+
if track_running_stats:
2447+
self.running_mean = _Tensor.zeros([num_features])
2448+
self.running_var = _Tensor.ones([num_features])
2449+
else:
2450+
self.running_mean = None
2451+
self.running_var = None
24342452

24352453
def forward(self, x):
24362454
from . import functional as F
@@ -2439,17 +2457,25 @@ def forward(self, x):
24392457

24402458
class InstanceNorm3d(Module):
24412459
"""Applies 3D Instance Normalization."""
2442-
def __init__(self, num_features: int, eps: float = 1e-5, momentum: float = 0.1, affine: bool = False):
2460+
def __init__(self, num_features: int, eps: float = 1e-5, momentum: float = 0.1, affine: bool = False, track_running_stats: bool = False):
24432461
super().__init__()
24442462
self.num_features = num_features
24452463
self.eps = eps
2464+
self.momentum = momentum
24462465
self.affine = affine
2466+
self.track_running_stats = track_running_stats
24472467
if affine:
24482468
self.weight = Parameter(_Tensor.ones([1, num_features, 1, 1, 1]))
24492469
self.bias = Parameter(_Tensor.zeros([1, num_features, 1, 1, 1]))
24502470
else:
24512471
self.weight = None
24522472
self.bias = None
2473+
if track_running_stats:
2474+
self.running_mean = _Tensor.zeros([num_features])
2475+
self.running_var = _Tensor.ones([num_features])
2476+
else:
2477+
self.running_mean = None
2478+
self.running_var = None
24532479

24542480
def forward(self, x):
24552481
from . import functional as F

‎python/oxideon/primitives.py‎

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1489,11 +1489,9 @@ def norm(
14891489
return linalg.norm(input, ord=p, dim=dim, keepdim=keepdim)
14901490

14911491

1492-
def clamp(input: _Tensor, min: Optional[float] = None, max: Optional[float] = None) -> _Tensor:
1492+
def clamp(input: _Tensor, min: Any = None, max: Any = None) -> _Tensor:
14931493
"""Clamps all elements in input into the range [min, max]."""
1494-
min_val = -1e30 if min is None else float(min)
1495-
max_val = 1e30 if max is None else float(max)
1496-
return input.clamp(min_val, max_val)
1494+
return as_tensor(input).clamp(min=min, max=max)
14971495

14981496

14991497
clip = clamp
@@ -3146,14 +3144,19 @@ def _tensor_squeeze(self, dim=None):
31463144
return orig_squeeze(self)
31473145
# Differentiable path via reshape (stays in the autograd graph).
31483146
s = list(self.shape)
3149-
if not -len(s) <= dim < len(s):
3150-
raise IndexError(
3151-
f"Dimension out of range (expected to be in range of [{-len(s)}, {len(s) - 1}], but got {dim})"
3152-
)
3153-
d = dim if dim >= 0 else len(s) + dim
3154-
if s[d] == 1:
3155-
return self.reshape([v for i, v in enumerate(s) if i != d])
3156-
return self
3147+
dims = list(dim) if isinstance(dim, (tuple, list)) else [dim]
3148+
norm_dims = set()
3149+
for d_raw in dims:
3150+
if not -len(s) <= d_raw < len(s):
3151+
raise IndexError(
3152+
f"Dimension out of range (expected to be in range of [{-len(s)}, {len(s) - 1}], but got {d_raw})"
3153+
)
3154+
d = d_raw if d_raw >= 0 else len(s) + d_raw
3155+
norm_dims.add(d)
3156+
new_shape = [v for i, v in enumerate(s) if not (i in norm_dims and s[i] == 1)]
3157+
if new_shape == s:
3158+
return self
3159+
return self.reshape(new_shape)
31573160
_Tensor.squeeze = _tensor_squeeze
31583161

31593162
# In-place mathematical mutations
@@ -3506,6 +3509,13 @@ def _new_tensor(self, data, dtype=None, device=None):
35063509
def _tensor_clamp(self, min=None, max=None):
35073510
if min is None and max is None:
35083511
return self.clone()
3512+
if isinstance(min, _Tensor) or isinstance(max, _Tensor):
3513+
res = self
3514+
if min is not None:
3515+
res = res.maximum(as_tensor(min))
3516+
if max is not None:
3517+
res = res.minimum(as_tensor(max))
3518+
return res
35093519
min_val = -1e30 if min is None else float(min)
35103520
max_val = 1e30 if max is None else float(max)
35113521
if min_val > max_val or math.isnan(min_val) or math.isnan(max_val):

‎python/oxideon/utils.py‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,27 @@
1616
sys.modules["oxideon.utils.rnn"] = rnn
1717
sys.modules["oxideon.nn.utils.rnn"] = rnn
1818

19-
from .oxideon import manual_seed as _manual_seed
19+
from .oxideon import manual_seed as _manual_seed, cat as _native_cat
20+
from .primitives import no_grad as _no_grad
21+
22+
23+
def parameters_to_vector(parameters):
24+
"""Convert parameters to one flattened 1-D vector (torch.nn.utils.parameters_to_vector)."""
25+
vecs = [p.reshape([-1]) for p in parameters]
26+
if not vecs:
27+
from .oxideon import zeros
28+
return zeros([0])
29+
return _native_cat(vecs, dim=0)
30+
31+
32+
def vector_to_parameters(vec, parameters):
33+
"""Convert one flattened 1-D vector back to the parameter shapes in-place."""
34+
pointer = 0
35+
with _no_grad():
36+
for p in parameters:
37+
num_param = p.numel()
38+
p.copy_(vec[pointer:pointer + num_param].reshape(list(p.shape)))
39+
pointer += num_param
2040

2141

2242
def set_seed(seed: int = 42):

0 commit comments

Comments
 (0)