optora 0.0.3__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- optora-0.0.3/LICENSE +21 -0
- optora-0.0.3/PKG-INFO +40 -0
- optora-0.0.3/README.md +9 -0
- optora-0.0.3/optora/__init__.py +13 -0
- optora-0.0.3/optora/_version.py +3 -0
- optora-0.0.3/optora/core/__init__.py +7 -0
- optora-0.0.3/optora/core/objective.py +91 -0
- optora-0.0.3/optora/core/problem.py +49 -0
- optora-0.0.3/optora/core/result.py +39 -0
- optora-0.0.3/optora/solvers/__init__.py +5 -0
- optora-0.0.3/optora/solvers/base.py +44 -0
- optora-0.0.3/optora/solvers/deterministic/__init__.py +6 -0
- optora-0.0.3/optora/solvers/deterministic/bfgs.py +107 -0
- optora-0.0.3/optora/solvers/deterministic/gradient_descent.py +81 -0
- optora-0.0.3/optora/solvers/line_search.py +70 -0
- optora-0.0.3/optora.egg-info/PKG-INFO +40 -0
- optora-0.0.3/optora.egg-info/SOURCES.txt +21 -0
- optora-0.0.3/optora.egg-info/dependency_links.txt +1 -0
- optora-0.0.3/optora.egg-info/requires.txt +12 -0
- optora-0.0.3/optora.egg-info/top_level.txt +1 -0
- optora-0.0.3/pyproject.toml +71 -0
- optora-0.0.3/setup.cfg +4 -0
- optora-0.0.3/tests/test_release_version.py +82 -0
optora-0.0.3/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Optora contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
optora-0.0.3/PKG-INFO
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: optora
|
|
3
|
+
Version: 0.0.3
|
|
4
|
+
Summary: A research-oriented optimization library for deterministic and stochastic methods.
|
|
5
|
+
Author: Optora contributors
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: optimization,stochastic optimization,deterministic optimization,machine learning,scientific computing
|
|
8
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
9
|
+
Classifier: Intended Audience :: Science/Research
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
16
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
17
|
+
Requires-Python: >=3.10
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
Requires-Dist: torch>=2.2
|
|
21
|
+
Provides-Extra: dev
|
|
22
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
23
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
24
|
+
Requires-Dist: ruff>=0.5; extra == "dev"
|
|
25
|
+
Requires-Dist: mypy>=1.10; extra == "dev"
|
|
26
|
+
Requires-Dist: twine>=5; extra == "dev"
|
|
27
|
+
Provides-Extra: docs
|
|
28
|
+
Requires-Dist: zensical>=0.0.11; extra == "docs"
|
|
29
|
+
Requires-Dist: mkdocstrings-python>=1.10; extra == "docs"
|
|
30
|
+
Dynamic: license-file
|
|
31
|
+
|
|
32
|
+
# Optora
|
|
33
|
+
|
|
34
|
+
Optora is an early-stage, GPU-first Python library for composable research
|
|
35
|
+
components in optimization, uncertainty-aware decision-making, and
|
|
36
|
+
transport-based geometry. The first milestone is intentionally small:
|
|
37
|
+
PyTorch-native problem, objective, result, and solver interfaces that can later
|
|
38
|
+
grow into stochastic methods, differentiable programming backends, optimal
|
|
39
|
+
transport, and Bayesian decision geometry.
|
|
40
|
+
|
optora-0.0.3/README.md
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# Optora
|
|
2
|
+
|
|
3
|
+
Optora is an early-stage, GPU-first Python library for composable research
|
|
4
|
+
components in optimization, uncertainty-aware decision-making, and
|
|
5
|
+
transport-based geometry. The first milestone is intentionally small:
|
|
6
|
+
PyTorch-native problem, objective, result, and solver interfaces that can later
|
|
7
|
+
grow into stochastic methods, differentiable programming backends, optimal
|
|
8
|
+
transport, and Bayesian decision geometry.
|
|
9
|
+
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Optora public API."""
|
|
2
|
+
|
|
3
|
+
from optora._version import __version__
|
|
4
|
+
from optora.core.objective import Objective
|
|
5
|
+
from optora.core.problem import UnconstrainedOptimizationProblem
|
|
6
|
+
from optora.core.result import OptimizationResult
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"Objective",
|
|
10
|
+
"OptimizationResult",
|
|
11
|
+
"UnconstrainedOptimizationProblem",
|
|
12
|
+
"__version__",
|
|
13
|
+
]
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Core objective and result abstractions."""
|
|
2
|
+
|
|
3
|
+
from optora.core.objective import Objective
|
|
4
|
+
from optora.core.problem import UnconstrainedOptimizationProblem
|
|
5
|
+
from optora.core.result import OptimizationResult
|
|
6
|
+
|
|
7
|
+
__all__ = ["Objective", "OptimizationResult", "UnconstrainedOptimizationProblem"]
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Objective function wrapper and finite-difference gradients."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable, Sequence
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import TypeAlias
|
|
8
|
+
|
|
9
|
+
import torch
|
|
10
|
+
|
|
11
|
+
Tensor = torch.Tensor
|
|
12
|
+
TensorLike: TypeAlias = (
|
|
13
|
+
torch.Tensor | float | Sequence[float] | Sequence[Sequence[float]]
|
|
14
|
+
)
|
|
15
|
+
ScalarLike: TypeAlias = torch.Tensor | float | int
|
|
16
|
+
ObjectiveFunction = Callable[[Tensor], ScalarLike]
|
|
17
|
+
GradientFunction = Callable[[Tensor], TensorLike]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(slots=True)
|
|
21
|
+
class Objective:
|
|
22
|
+
"""Wrap an objective and optional gradient with evaluation counters.
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
fun: Objective function mapping a point to a scalar value.
|
|
26
|
+
grad: Optional gradient function. If omitted, central finite
|
|
27
|
+
differences are used.
|
|
28
|
+
finite_difference_step: Perturbation size for finite differences.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
fun: ObjectiveFunction
|
|
32
|
+
grad: GradientFunction | None = None
|
|
33
|
+
finite_difference_step: float = 1e-8
|
|
34
|
+
nfev: int = field(default=0, init=False)
|
|
35
|
+
njev: int = field(default=0, init=False)
|
|
36
|
+
|
|
37
|
+
def value(self, x: Tensor) -> Tensor:
|
|
38
|
+
"""Evaluate the objective at ``x`` and increment ``nfev``."""
|
|
39
|
+
self.nfev += 1
|
|
40
|
+
value = self.fun(x)
|
|
41
|
+
if isinstance(value, torch.Tensor):
|
|
42
|
+
result = value.to(device=x.device, dtype=x.dtype)
|
|
43
|
+
else:
|
|
44
|
+
result = torch.as_tensor(value, dtype=x.dtype, device=x.device)
|
|
45
|
+
|
|
46
|
+
if result.numel() != 1:
|
|
47
|
+
shape = tuple(result.shape)
|
|
48
|
+
msg = f"objective function must return a scalar, got shape {shape}"
|
|
49
|
+
raise ValueError(msg)
|
|
50
|
+
return result.reshape(())
|
|
51
|
+
|
|
52
|
+
def gradient(self, x: Tensor) -> Tensor:
|
|
53
|
+
"""Evaluate or approximate the gradient at ``x``."""
|
|
54
|
+
self.njev += 1
|
|
55
|
+
if self.grad is not None:
|
|
56
|
+
value = self.grad(x)
|
|
57
|
+
if isinstance(value, torch.Tensor):
|
|
58
|
+
gradient = value.to(device=x.device, dtype=x.dtype)
|
|
59
|
+
else:
|
|
60
|
+
gradient = torch.as_tensor(value, dtype=x.dtype, device=x.device)
|
|
61
|
+
if gradient.shape != x.shape:
|
|
62
|
+
msg = (
|
|
63
|
+
"gradient shape must match x: "
|
|
64
|
+
f"expected {x.shape}, got {gradient.shape}"
|
|
65
|
+
)
|
|
66
|
+
raise ValueError(msg)
|
|
67
|
+
return gradient
|
|
68
|
+
return self._finite_difference_gradient(x)
|
|
69
|
+
|
|
70
|
+
def _finite_difference_gradient(self, x: Tensor) -> Tensor:
|
|
71
|
+
"""Approximate the gradient with central finite differences."""
|
|
72
|
+
if self.finite_difference_step <= 0.0:
|
|
73
|
+
msg = "finite_difference_step must be positive"
|
|
74
|
+
raise ValueError(msg)
|
|
75
|
+
|
|
76
|
+
gradient = torch.empty_like(x)
|
|
77
|
+
flat_gradient = gradient.reshape(-1)
|
|
78
|
+
flat_x = x.reshape(-1)
|
|
79
|
+
|
|
80
|
+
for index in range(flat_x.numel()):
|
|
81
|
+
x_forward = flat_x.clone()
|
|
82
|
+
x_backward = flat_x.clone()
|
|
83
|
+
x_forward[index] += self.finite_difference_step
|
|
84
|
+
x_backward[index] -= self.finite_difference_step
|
|
85
|
+
forward = self.value(x_forward.reshape(x.shape))
|
|
86
|
+
backward = self.value(x_backward.reshape(x.shape))
|
|
87
|
+
flat_gradient[index] = (forward - backward) / (
|
|
88
|
+
2.0 * self.finite_difference_step
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
return gradient
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Problem abstractions for composable optimization methods."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import TypeAlias
|
|
8
|
+
|
|
9
|
+
import torch
|
|
10
|
+
|
|
11
|
+
from optora.core.objective import Objective
|
|
12
|
+
|
|
13
|
+
Tensor = torch.Tensor
|
|
14
|
+
TensorLike: TypeAlias = (
|
|
15
|
+
torch.Tensor | float | Sequence[float] | Sequence[Sequence[float]]
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(slots=True)
|
|
20
|
+
class UnconstrainedOptimizationProblem:
|
|
21
|
+
"""Finite-dimensional unconstrained optimization problem.
|
|
22
|
+
|
|
23
|
+
The problem object contains the mathematical ingredients required by a
|
|
24
|
+
solver, but does not prescribe a training loop, method registry, or
|
|
25
|
+
workflow.
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
objective: Scalar objective with derivative information.
|
|
29
|
+
initial_point: Initial iterate used by iterative methods.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
objective: Objective
|
|
33
|
+
initial_point: TensorLike
|
|
34
|
+
|
|
35
|
+
def initial_tensor(self) -> Tensor:
|
|
36
|
+
"""Return the initial point as an independent floating-point tensor."""
|
|
37
|
+
if isinstance(self.initial_point, torch.Tensor):
|
|
38
|
+
tensor = self.initial_point
|
|
39
|
+
if not tensor.is_floating_point():
|
|
40
|
+
tensor = tensor.to(dtype=torch.get_default_dtype())
|
|
41
|
+
tensor = tensor.clone()
|
|
42
|
+
else:
|
|
43
|
+
tensor = torch.as_tensor(
|
|
44
|
+
self.initial_point,
|
|
45
|
+
dtype=torch.get_default_dtype(),
|
|
46
|
+
)
|
|
47
|
+
if tensor.ndim == 0:
|
|
48
|
+
return tensor.reshape(1)
|
|
49
|
+
return tensor
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Optimization result container."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import torch
|
|
9
|
+
|
|
10
|
+
Tensor = torch.Tensor
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(slots=True)
|
|
14
|
+
class OptimizationResult:
|
|
15
|
+
"""Result returned by Optora solvers.
|
|
16
|
+
|
|
17
|
+
Attributes:
|
|
18
|
+
x: Final iterate.
|
|
19
|
+
fun: Objective value at ``x`` as a scalar tensor.
|
|
20
|
+
jac: Gradient at ``x`` when available.
|
|
21
|
+
nit: Number of solver iterations.
|
|
22
|
+
nfev: Number of objective evaluations.
|
|
23
|
+
njev: Number of gradient evaluations.
|
|
24
|
+
success: Whether the solver reached its convergence criterion.
|
|
25
|
+
status: Solver-specific integer status code.
|
|
26
|
+
message: Human-readable termination message.
|
|
27
|
+
history: Optional per-iteration diagnostics.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
x: Tensor
|
|
31
|
+
fun: Tensor
|
|
32
|
+
jac: Tensor | None
|
|
33
|
+
nit: int
|
|
34
|
+
nfev: int
|
|
35
|
+
njev: int
|
|
36
|
+
success: bool
|
|
37
|
+
status: int
|
|
38
|
+
message: str
|
|
39
|
+
history: list[dict[str, Any]] = field(default_factory=list)
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Base solver interfaces."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
from optora.core.problem import UnconstrainedOptimizationProblem
|
|
9
|
+
from optora.core.result import OptimizationResult
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(slots=True)
|
|
13
|
+
class Solver(ABC):
|
|
14
|
+
"""Base interface for explicit algorithm components.
|
|
15
|
+
|
|
16
|
+
Solvers are method implementations, not top-level workflows. A researcher
|
|
17
|
+
constructs a problem object, chooses a solver class that corresponds to the
|
|
18
|
+
method under study, and calls ``solve`` explicitly.
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
max_iter: Maximum number of iterations.
|
|
22
|
+
tol: Stationarity tolerance used by the method.
|
|
23
|
+
store_history: Whether to retain per-iteration diagnostics.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
max_iter: int = 1000
|
|
27
|
+
tol: float = 1e-6
|
|
28
|
+
store_history: bool = False
|
|
29
|
+
|
|
30
|
+
def __post_init__(self) -> None:
|
|
31
|
+
"""Validate common solver parameters."""
|
|
32
|
+
if self.max_iter < 0:
|
|
33
|
+
msg = "max_iter must be nonnegative"
|
|
34
|
+
raise ValueError(msg)
|
|
35
|
+
if self.tol <= 0.0:
|
|
36
|
+
msg = "tol must be positive"
|
|
37
|
+
raise ValueError(msg)
|
|
38
|
+
|
|
39
|
+
@abstractmethod
|
|
40
|
+
def solve(
|
|
41
|
+
self,
|
|
42
|
+
problem: UnconstrainedOptimizationProblem,
|
|
43
|
+
) -> OptimizationResult:
|
|
44
|
+
"""Solve an explicit mathematical problem."""
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""BFGS quasi-Newton method."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import torch
|
|
9
|
+
|
|
10
|
+
from optora.core.objective import Objective
|
|
11
|
+
from optora.core.problem import UnconstrainedOptimizationProblem
|
|
12
|
+
from optora.core.result import OptimizationResult
|
|
13
|
+
from optora.solvers.base import Solver
|
|
14
|
+
from optora.solvers.line_search import backtracking_armijo
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(slots=True)
|
|
18
|
+
class BFGS(Solver):
|
|
19
|
+
"""Inverse-Hessian BFGS for smooth unconstrained objectives."""
|
|
20
|
+
|
|
21
|
+
initial_step: float = 1.0
|
|
22
|
+
curvature_tol: float = 1e-12
|
|
23
|
+
|
|
24
|
+
def solve(self, problem: UnconstrainedOptimizationProblem) -> OptimizationResult:
|
|
25
|
+
objective: Objective = problem.objective
|
|
26
|
+
x = problem.initial_tensor()
|
|
27
|
+
n = x.numel()
|
|
28
|
+
inverse_hessian = torch.eye(n, dtype=x.dtype, device=x.device)
|
|
29
|
+
history: list[dict[str, Any]] = []
|
|
30
|
+
|
|
31
|
+
f = objective.value(x)
|
|
32
|
+
grad = objective.gradient(x)
|
|
33
|
+
|
|
34
|
+
for iteration in range(self.max_iter + 1):
|
|
35
|
+
grad_norm = torch.linalg.vector_norm(grad)
|
|
36
|
+
if self.store_history:
|
|
37
|
+
history.append(
|
|
38
|
+
{"iteration": iteration, "fun": f, "grad_norm": grad_norm}
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
if bool((grad_norm <= self.tol).detach().item()):
|
|
42
|
+
return OptimizationResult(
|
|
43
|
+
x=x,
|
|
44
|
+
fun=f,
|
|
45
|
+
jac=grad,
|
|
46
|
+
nit=iteration,
|
|
47
|
+
nfev=objective.nfev,
|
|
48
|
+
njev=objective.njev,
|
|
49
|
+
success=True,
|
|
50
|
+
status=0,
|
|
51
|
+
message="Converged: gradient norm is below tolerance.",
|
|
52
|
+
history=history,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
if iteration == self.max_iter:
|
|
56
|
+
break
|
|
57
|
+
|
|
58
|
+
direction = -(inverse_hessian @ grad.reshape(-1)).reshape(x.shape)
|
|
59
|
+
|
|
60
|
+
is_descent_direction = torch.dot(
|
|
61
|
+
direction.reshape(-1),
|
|
62
|
+
grad.reshape(-1),
|
|
63
|
+
)
|
|
64
|
+
if bool((is_descent_direction >= 0.0).detach().item()):
|
|
65
|
+
direction = -grad
|
|
66
|
+
inverse_hessian = torch.eye(n, dtype=x.dtype, device=x.device)
|
|
67
|
+
|
|
68
|
+
step, f_next = backtracking_armijo(
|
|
69
|
+
objective.value,
|
|
70
|
+
x,
|
|
71
|
+
direction,
|
|
72
|
+
grad,
|
|
73
|
+
initial_step=self.initial_step,
|
|
74
|
+
)
|
|
75
|
+
x_next = x + step * direction
|
|
76
|
+
grad_next = objective.gradient(x_next)
|
|
77
|
+
|
|
78
|
+
s = (x_next - x).reshape(-1)
|
|
79
|
+
y = (grad_next - grad).reshape(-1)
|
|
80
|
+
curvature = torch.dot(y, s)
|
|
81
|
+
|
|
82
|
+
if bool((curvature > self.curvature_tol).detach().item()):
|
|
83
|
+
rho = torch.reciprocal(curvature)
|
|
84
|
+
identity = torch.eye(n, dtype=x.dtype, device=x.device)
|
|
85
|
+
sy = torch.outer(s, y)
|
|
86
|
+
ys = torch.outer(y, s)
|
|
87
|
+
ss = torch.outer(s, s)
|
|
88
|
+
inverse_hessian = (identity - rho * sy) @ inverse_hessian @ (
|
|
89
|
+
identity - rho * ys
|
|
90
|
+
) + rho * ss
|
|
91
|
+
|
|
92
|
+
x = x_next
|
|
93
|
+
f = f_next
|
|
94
|
+
grad = grad_next
|
|
95
|
+
|
|
96
|
+
return OptimizationResult(
|
|
97
|
+
x=x,
|
|
98
|
+
fun=f,
|
|
99
|
+
jac=grad,
|
|
100
|
+
nit=self.max_iter,
|
|
101
|
+
nfev=objective.nfev,
|
|
102
|
+
njev=objective.njev,
|
|
103
|
+
success=False,
|
|
104
|
+
status=1,
|
|
105
|
+
message="Stopped: maximum iterations reached.",
|
|
106
|
+
history=history,
|
|
107
|
+
)
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Gradient descent with optional Armijo backtracking."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import torch
|
|
9
|
+
|
|
10
|
+
from optora.core.objective import Objective
|
|
11
|
+
from optora.core.problem import UnconstrainedOptimizationProblem
|
|
12
|
+
from optora.core.result import OptimizationResult
|
|
13
|
+
from optora.solvers.base import Solver
|
|
14
|
+
from optora.solvers.line_search import backtracking_armijo
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(slots=True)
|
|
18
|
+
class GradientDescent(Solver):
|
|
19
|
+
"""Steepest descent for smooth unconstrained objectives."""
|
|
20
|
+
|
|
21
|
+
step_size: float = 1.0
|
|
22
|
+
line_search: bool = True
|
|
23
|
+
|
|
24
|
+
def solve(self, problem: UnconstrainedOptimizationProblem) -> OptimizationResult:
|
|
25
|
+
objective: Objective = problem.objective
|
|
26
|
+
x = problem.initial_tensor()
|
|
27
|
+
history: list[dict[str, Any]] = []
|
|
28
|
+
f = objective.value(x)
|
|
29
|
+
|
|
30
|
+
for iteration in range(self.max_iter + 1):
|
|
31
|
+
grad = objective.gradient(x)
|
|
32
|
+
grad_norm = torch.linalg.vector_norm(grad)
|
|
33
|
+
|
|
34
|
+
if self.store_history:
|
|
35
|
+
history.append(
|
|
36
|
+
{"iteration": iteration, "fun": f, "grad_norm": grad_norm}
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
if bool((grad_norm <= self.tol).detach().item()):
|
|
40
|
+
return OptimizationResult(
|
|
41
|
+
x=x,
|
|
42
|
+
fun=f,
|
|
43
|
+
jac=grad,
|
|
44
|
+
nit=iteration,
|
|
45
|
+
nfev=objective.nfev,
|
|
46
|
+
njev=objective.njev,
|
|
47
|
+
success=True,
|
|
48
|
+
status=0,
|
|
49
|
+
message="Converged: gradient norm is below tolerance.",
|
|
50
|
+
history=history,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
if iteration == self.max_iter:
|
|
54
|
+
break
|
|
55
|
+
|
|
56
|
+
direction = -grad
|
|
57
|
+
if self.line_search:
|
|
58
|
+
step, f = backtracking_armijo(
|
|
59
|
+
objective.value,
|
|
60
|
+
x,
|
|
61
|
+
direction,
|
|
62
|
+
grad,
|
|
63
|
+
initial_step=self.step_size,
|
|
64
|
+
)
|
|
65
|
+
else:
|
|
66
|
+
step = self.step_size
|
|
67
|
+
f = objective.value(x + step * direction)
|
|
68
|
+
x = x + step * direction
|
|
69
|
+
|
|
70
|
+
return OptimizationResult(
|
|
71
|
+
x=x,
|
|
72
|
+
fun=f,
|
|
73
|
+
jac=objective.gradient(x),
|
|
74
|
+
nit=self.max_iter,
|
|
75
|
+
nfev=objective.nfev,
|
|
76
|
+
njev=objective.njev,
|
|
77
|
+
success=False,
|
|
78
|
+
status=1,
|
|
79
|
+
message="Stopped: maximum iterations reached.",
|
|
80
|
+
history=history,
|
|
81
|
+
)
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Shared line-search routines."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
|
|
7
|
+
import torch
|
|
8
|
+
|
|
9
|
+
Tensor = torch.Tensor
|
|
10
|
+
ValueFunction = Callable[[Tensor], Tensor]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def backtracking_armijo(
|
|
14
|
+
fun: ValueFunction,
|
|
15
|
+
x: Tensor,
|
|
16
|
+
direction: Tensor,
|
|
17
|
+
grad: Tensor,
|
|
18
|
+
*,
|
|
19
|
+
initial_step: float = 1.0,
|
|
20
|
+
contraction: float = 0.5,
|
|
21
|
+
sufficient_decrease: float = 1e-4,
|
|
22
|
+
min_step: float = 1e-12,
|
|
23
|
+
max_iter: int = 50,
|
|
24
|
+
) -> tuple[float, Tensor]:
|
|
25
|
+
"""Find a step satisfying the Armijo sufficient-decrease condition.
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
fun: Objective value function.
|
|
29
|
+
x: Current point.
|
|
30
|
+
direction: Search direction.
|
|
31
|
+
grad: Gradient at ``x``.
|
|
32
|
+
initial_step: Initial trial step length.
|
|
33
|
+
contraction: Multiplicative step contraction factor.
|
|
34
|
+
sufficient_decrease: Armijo condition constant.
|
|
35
|
+
min_step: Smallest trial step allowed before returning the best trial.
|
|
36
|
+
max_iter: Maximum number of backtracking trials.
|
|
37
|
+
|
|
38
|
+
Returns:
|
|
39
|
+
A pair ``(step, value)`` for the accepted trial point.
|
|
40
|
+
|
|
41
|
+
Raises:
|
|
42
|
+
ValueError: If line-search parameters are outside their valid ranges.
|
|
43
|
+
"""
|
|
44
|
+
if initial_step <= 0.0:
|
|
45
|
+
raise ValueError("initial_step must be positive")
|
|
46
|
+
if not 0.0 < contraction < 1.0:
|
|
47
|
+
raise ValueError("contraction must be between 0 and 1")
|
|
48
|
+
if sufficient_decrease <= 0.0:
|
|
49
|
+
raise ValueError("sufficient_decrease must be positive")
|
|
50
|
+
if min_step <= 0.0:
|
|
51
|
+
raise ValueError("min_step must be positive")
|
|
52
|
+
if max_iter < 1:
|
|
53
|
+
raise ValueError("max_iter must be positive")
|
|
54
|
+
|
|
55
|
+
f0 = fun(x)
|
|
56
|
+
directional_derivative = torch.dot(grad.reshape(-1), direction.reshape(-1))
|
|
57
|
+
step = initial_step
|
|
58
|
+
trial_value = f0
|
|
59
|
+
|
|
60
|
+
for _ in range(max_iter):
|
|
61
|
+
trial = x + step * direction
|
|
62
|
+
trial_value = fun(trial)
|
|
63
|
+
sufficient_value = f0 + sufficient_decrease * step * directional_derivative
|
|
64
|
+
if bool((trial_value <= sufficient_value).detach().item()):
|
|
65
|
+
return step, trial_value
|
|
66
|
+
step *= contraction
|
|
67
|
+
if step < min_step:
|
|
68
|
+
break
|
|
69
|
+
|
|
70
|
+
return step, trial_value
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: optora
|
|
3
|
+
Version: 0.0.3
|
|
4
|
+
Summary: A research-oriented optimization library for deterministic and stochastic methods.
|
|
5
|
+
Author: Optora contributors
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: optimization,stochastic optimization,deterministic optimization,machine learning,scientific computing
|
|
8
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
9
|
+
Classifier: Intended Audience :: Science/Research
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
16
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
17
|
+
Requires-Python: >=3.10
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
Requires-Dist: torch>=2.2
|
|
21
|
+
Provides-Extra: dev
|
|
22
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
23
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
24
|
+
Requires-Dist: ruff>=0.5; extra == "dev"
|
|
25
|
+
Requires-Dist: mypy>=1.10; extra == "dev"
|
|
26
|
+
Requires-Dist: twine>=5; extra == "dev"
|
|
27
|
+
Provides-Extra: docs
|
|
28
|
+
Requires-Dist: zensical>=0.0.11; extra == "docs"
|
|
29
|
+
Requires-Dist: mkdocstrings-python>=1.10; extra == "docs"
|
|
30
|
+
Dynamic: license-file
|
|
31
|
+
|
|
32
|
+
# Optora
|
|
33
|
+
|
|
34
|
+
Optora is an early-stage, GPU-first Python library for composable research
|
|
35
|
+
components in optimization, uncertainty-aware decision-making, and
|
|
36
|
+
transport-based geometry. The first milestone is intentionally small:
|
|
37
|
+
PyTorch-native problem, objective, result, and solver interfaces that can later
|
|
38
|
+
grow into stochastic methods, differentiable programming backends, optimal
|
|
39
|
+
transport, and Bayesian decision geometry.
|
|
40
|
+
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
optora/__init__.py
|
|
5
|
+
optora/_version.py
|
|
6
|
+
optora.egg-info/PKG-INFO
|
|
7
|
+
optora.egg-info/SOURCES.txt
|
|
8
|
+
optora.egg-info/dependency_links.txt
|
|
9
|
+
optora.egg-info/requires.txt
|
|
10
|
+
optora.egg-info/top_level.txt
|
|
11
|
+
optora/core/__init__.py
|
|
12
|
+
optora/core/objective.py
|
|
13
|
+
optora/core/problem.py
|
|
14
|
+
optora/core/result.py
|
|
15
|
+
optora/solvers/__init__.py
|
|
16
|
+
optora/solvers/base.py
|
|
17
|
+
optora/solvers/line_search.py
|
|
18
|
+
optora/solvers/deterministic/__init__.py
|
|
19
|
+
optora/solvers/deterministic/bfgs.py
|
|
20
|
+
optora/solvers/deterministic/gradient_descent.py
|
|
21
|
+
tests/test_release_version.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
optora
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=69", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "optora"
|
|
7
|
+
version = "0.0.3"
|
|
8
|
+
description = "A research-oriented optimization library for deterministic and stochastic methods."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [
|
|
14
|
+
{ name = "Optora contributors" }
|
|
15
|
+
]
|
|
16
|
+
keywords = [
|
|
17
|
+
"optimization",
|
|
18
|
+
"stochastic optimization",
|
|
19
|
+
"deterministic optimization",
|
|
20
|
+
"machine learning",
|
|
21
|
+
"scientific computing"
|
|
22
|
+
]
|
|
23
|
+
classifiers = [
|
|
24
|
+
"Development Status :: 2 - Pre-Alpha",
|
|
25
|
+
"Intended Audience :: Science/Research",
|
|
26
|
+
"Intended Audience :: Developers",
|
|
27
|
+
"Programming Language :: Python :: 3",
|
|
28
|
+
"Programming Language :: Python :: 3.10",
|
|
29
|
+
"Programming Language :: Python :: 3.11",
|
|
30
|
+
"Programming Language :: Python :: 3.12",
|
|
31
|
+
"Topic :: Scientific/Engineering :: Mathematics",
|
|
32
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence"
|
|
33
|
+
]
|
|
34
|
+
dependencies = [
|
|
35
|
+
"torch>=2.2"
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
[project.optional-dependencies]
|
|
39
|
+
dev = [
|
|
40
|
+
"build>=1.2",
|
|
41
|
+
"pytest>=8",
|
|
42
|
+
"ruff>=0.5",
|
|
43
|
+
"mypy>=1.10",
|
|
44
|
+
"twine>=5"
|
|
45
|
+
]
|
|
46
|
+
docs = [
|
|
47
|
+
"zensical>=0.0.11",
|
|
48
|
+
"mkdocstrings-python>=1.10"
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
[tool.setuptools.packages.find]
|
|
52
|
+
where = ["."]
|
|
53
|
+
include = ["optora*"]
|
|
54
|
+
|
|
55
|
+
[tool.pytest.ini_options]
|
|
56
|
+
testpaths = ["tests"]
|
|
57
|
+
addopts = "-q"
|
|
58
|
+
pythonpath = ["."]
|
|
59
|
+
|
|
60
|
+
[tool.ruff]
|
|
61
|
+
line-length = 88
|
|
62
|
+
target-version = "py310"
|
|
63
|
+
|
|
64
|
+
[tool.ruff.lint]
|
|
65
|
+
select = ["E", "F", "I", "UP", "B", "SIM"]
|
|
66
|
+
|
|
67
|
+
[tool.mypy]
|
|
68
|
+
python_version = "3.10"
|
|
69
|
+
packages = ["optora"]
|
|
70
|
+
ignore_missing_imports = true
|
|
71
|
+
strict = true
|
optora-0.0.3/setup.cfg
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Tests for release version automation."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from tools.release_version import (
|
|
6
|
+
Version,
|
|
7
|
+
choose_bump,
|
|
8
|
+
next_version,
|
|
9
|
+
update_release_files,
|
|
10
|
+
update_version_block,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def test_choose_bump_prefers_major() -> None:
|
|
15
|
+
assert choose_bump("add solver #minor #major") == "major"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def test_choose_bump_defaults_to_patch() -> None:
|
|
19
|
+
assert choose_bump("fix line search tolerance") == "patch"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def test_next_version_minor_resets_patch() -> None:
|
|
23
|
+
version, bump = next_version(Version.parse("v0.1.4"), "restore docs #minor")
|
|
24
|
+
|
|
25
|
+
assert version == Version(0, 2, 0)
|
|
26
|
+
assert bump == "minor"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def test_next_version_major_resets_minor_and_patch() -> None:
|
|
30
|
+
version, bump = next_version(Version.parse("v0.7.9"), "stabilize api #major")
|
|
31
|
+
|
|
32
|
+
assert version == Version(1, 0, 0)
|
|
33
|
+
assert bump == "major"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def test_update_version_block(tmp_path: Path) -> None:
|
|
37
|
+
path = tmp_path / "index.md"
|
|
38
|
+
path.write_text(
|
|
39
|
+
"# Optora\n\n"
|
|
40
|
+
"<!-- optora-version-start -->\n"
|
|
41
|
+
"Latest release: `v0.1.0`\n"
|
|
42
|
+
"<!-- optora-version-end -->\n",
|
|
43
|
+
encoding="utf-8",
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
changed = update_version_block(path, Version(0, 1, 1))
|
|
47
|
+
|
|
48
|
+
assert changed == path
|
|
49
|
+
assert "Latest release: `v0.1.1`" in path.read_text(encoding="utf-8")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def test_release_files_include_documentation_release_page(tmp_path: Path) -> None:
|
|
53
|
+
(tmp_path / "optora").mkdir()
|
|
54
|
+
(tmp_path / "docs").mkdir()
|
|
55
|
+
(tmp_path / "pyproject.toml").write_text(
|
|
56
|
+
'[project]\nname = "optora"\nversion = "0.1.0"\n',
|
|
57
|
+
encoding="utf-8",
|
|
58
|
+
)
|
|
59
|
+
(tmp_path / "optora" / "_version.py").write_text(
|
|
60
|
+
'"""Package version for Optora."""\n\n__version__ = "0.1.0"\n',
|
|
61
|
+
encoding="utf-8",
|
|
62
|
+
)
|
|
63
|
+
for docs_file in ("index.md", "release.md"):
|
|
64
|
+
(tmp_path / "docs" / docs_file).write_text(
|
|
65
|
+
"# Optora\n\n"
|
|
66
|
+
"<!-- optora-version-start -->\n"
|
|
67
|
+
"Latest release: `v0.1.0`\n"
|
|
68
|
+
"<!-- optora-version-end -->\n",
|
|
69
|
+
encoding="utf-8",
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
changed = update_release_files(tmp_path, Version(0, 1, 1))
|
|
73
|
+
|
|
74
|
+
assert sorted(path.relative_to(tmp_path).as_posix() for path in changed) == [
|
|
75
|
+
"docs/index.md",
|
|
76
|
+
"docs/release.md",
|
|
77
|
+
"optora/_version.py",
|
|
78
|
+
"pyproject.toml",
|
|
79
|
+
]
|
|
80
|
+
assert "Latest release: `v0.1.1`" in (tmp_path / "docs" / "release.md").read_text(
|
|
81
|
+
encoding="utf-8"
|
|
82
|
+
)
|