@tangent.to/opt 0.1.0

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.
@@ -0,0 +1,236 @@
1
+ /**
2
+ * Gradient-based minimizers: gradient descent, momentum, RMSProp, Adam.
3
+ *
4
+ * Moved from tangent/ds (ds.core.optimize). Update rules are unchanged;
5
+ * the API is functional and all methods share the evaluator contract from
6
+ * evaluate.js, so objectives may be (x) => number with an optional separate
7
+ * gradient, or the combined (x) => {loss, gradient} form used in tangent/ds.
8
+ */
9
+
10
+ import { makeEvaluator } from './evaluate.js';
11
+
12
+ function gradNorm(gradient) {
13
+ let sum = 0;
14
+ for (let i = 0; i < gradient.length; i++) {
15
+ sum += gradient[i] * gradient[i];
16
+ }
17
+ return Math.sqrt(sum);
18
+ }
19
+
20
+ /**
21
+ * Backtracking line search satisfying the Armijo condition.
22
+ *
23
+ * @param {Function} evaluate - (x) => {loss, gradient}
24
+ * @param {Array<number>} x - Current point
25
+ * @param {Array<number>} gradient - Gradient at x
26
+ * @param {number} currentLoss - Loss at x
27
+ * @returns {number} Step size
28
+ */
29
+ export function backtrackingLineSearch(evaluate, x, gradient, currentLoss) {
30
+ const alpha = 0.3; // Armijo condition constant
31
+ const beta = 0.8; // Reduction factor
32
+ let t = 1.0;
33
+
34
+ let gradNormSq = 0;
35
+ for (let i = 0; i < gradient.length; i++) {
36
+ gradNormSq += gradient[i] * gradient[i];
37
+ }
38
+
39
+ for (let i = 0; i < 20; i++) {
40
+ const xNew = x.map((xi, j) => xi - t * gradient[j]);
41
+ const { loss: newLoss } = evaluate(xNew);
42
+ if (newLoss <= currentLoss - alpha * t * gradNormSq) {
43
+ return t;
44
+ }
45
+ t *= beta;
46
+ }
47
+
48
+ return t;
49
+ }
50
+
51
+ /**
52
+ * Shared descent loop.
53
+ *
54
+ * @param {Object} spec
55
+ * @param {Function} spec.init - (n) => state
56
+ * @param {Function} spec.step - ({x, gradient, state, iter, lr}) mutates x in place
57
+ * @param {boolean} [spec.trackLearningRate] - Record per-iteration step sizes
58
+ * @param {Function} f - Objective
59
+ * @param {Array<number>} x0 - Initial parameters
60
+ * @param {Object} options
61
+ * @returns {Object} {x, fx, iterations, converged, history}
62
+ */
63
+ function descend(spec, f, x0, options = {}) {
64
+ const learningRate = options.learningRate || 0.01;
65
+ const maxIter = options.maxIter || 1000;
66
+ const tol = options.tol || 1e-6;
67
+ const verbose = options.verbose || false;
68
+ const lineSearch = options.lineSearch || false;
69
+
70
+ const evaluateRaw = makeEvaluator(f, options.grad, options);
71
+ let nfev = 0;
72
+ const evaluate = (xx) => {
73
+ nfev++;
74
+ return evaluateRaw(xx);
75
+ };
76
+
77
+ const x = [...x0];
78
+ const state = spec.init(x.length);
79
+
80
+ const history = { loss: [], gradNorm: [] };
81
+ if (spec.trackLearningRate) {
82
+ history.learningRate = [];
83
+ }
84
+
85
+ let converged = false;
86
+ let iteration = 0;
87
+ let lastLoss = NaN;
88
+
89
+ for (; iteration < maxIter; iteration++) {
90
+ const { loss, gradient } = evaluate(x);
91
+ lastLoss = loss;
92
+
93
+ history.loss.push(loss);
94
+ const norm = gradNorm(gradient);
95
+ history.gradNorm.push(norm);
96
+
97
+ if (norm < tol) {
98
+ converged = true;
99
+ if (verbose) {
100
+ console.log(`Converged at iteration ${iteration}, loss: ${loss.toFixed(6)}`);
101
+ }
102
+ break;
103
+ }
104
+
105
+ let lr = learningRate;
106
+ if (lineSearch && spec.trackLearningRate) {
107
+ lr = backtrackingLineSearch(evaluate, x, gradient, loss);
108
+ }
109
+ if (spec.trackLearningRate) {
110
+ history.learningRate.push(lr);
111
+ }
112
+
113
+ spec.step({ x, gradient, state, iter: iteration, lr });
114
+
115
+ if (verbose && iteration % 100 === 0) {
116
+ console.log(`Iter ${iteration}: loss=${loss.toFixed(6)}, grad_norm=${norm.toFixed(6)}`);
117
+ }
118
+ }
119
+
120
+ const fx = converged ? lastLoss : evaluate(x).loss;
121
+
122
+ return { x, fx, iterations: iteration, nfev, converged, success: converged, history };
123
+ }
124
+
125
+ /**
126
+ * Plain gradient descent, with optional backtracking line search.
127
+ *
128
+ * @param {Function} f - Objective: (x) => number or (x) => {loss, gradient}
129
+ * @param {Array<number>} x0 - Initial parameters
130
+ * @param {Object} [options] - {grad, learningRate, maxIter, tol, lineSearch, verbose}
131
+ * @returns {Object} {x, fx, iterations, converged, history}
132
+ */
133
+ export function gradientDescent(f, x0, options = {}) {
134
+ return descend(
135
+ {
136
+ init: () => null,
137
+ step: ({ x, gradient, lr }) => {
138
+ for (let i = 0; i < x.length; i++) {
139
+ x[i] -= lr * gradient[i];
140
+ }
141
+ },
142
+ trackLearningRate: true,
143
+ },
144
+ f,
145
+ x0,
146
+ options,
147
+ );
148
+ }
149
+
150
+ /**
151
+ * Gradient descent with momentum.
152
+ *
153
+ * @param {Function} f - Objective
154
+ * @param {Array<number>} x0 - Initial parameters
155
+ * @param {Object} [options] - {grad, learningRate, maxIter, tol, momentum, verbose}
156
+ * @returns {Object} {x, fx, iterations, converged, history}
157
+ */
158
+ export function momentumDescent(f, x0, options = {}) {
159
+ const momentum = options.momentum || 0.9;
160
+ return descend(
161
+ {
162
+ init: (n) => ({ velocity: new Array(n).fill(0) }),
163
+ step: ({ x, gradient, state, lr }) => {
164
+ for (let i = 0; i < x.length; i++) {
165
+ state.velocity[i] = momentum * state.velocity[i] + lr * gradient[i];
166
+ x[i] -= state.velocity[i];
167
+ }
168
+ },
169
+ },
170
+ f,
171
+ x0,
172
+ options,
173
+ );
174
+ }
175
+
176
+ /**
177
+ * RMSProp.
178
+ *
179
+ * @param {Function} f - Objective
180
+ * @param {Array<number>} x0 - Initial parameters
181
+ * @param {Object} [options] - {grad, learningRate, maxIter, tol, decay, epsilon, verbose}
182
+ * @returns {Object} {x, fx, iterations, converged, history}
183
+ */
184
+ export function rmsprop(f, x0, options = {}) {
185
+ const decay = options.decay || 0.9;
186
+ const epsilon = options.epsilon || 1e-8;
187
+ return descend(
188
+ {
189
+ init: (n) => ({ cache: new Array(n).fill(0) }),
190
+ step: ({ x, gradient, state, lr }) => {
191
+ for (let i = 0; i < x.length; i++) {
192
+ state.cache[i] = decay * state.cache[i] + (1 - decay) * gradient[i] * gradient[i];
193
+ x[i] -= lr * gradient[i] / (Math.sqrt(state.cache[i]) + epsilon);
194
+ }
195
+ },
196
+ },
197
+ f,
198
+ x0,
199
+ options,
200
+ );
201
+ }
202
+
203
+ /**
204
+ * Adam (adaptive moment estimation).
205
+ *
206
+ * @param {Function} f - Objective
207
+ * @param {Array<number>} x0 - Initial parameters
208
+ * @param {Object} [options] - {grad, learningRate, maxIter, tol, beta1, beta2, epsilon, verbose}
209
+ * @returns {Object} {x, fx, iterations, converged, history}
210
+ */
211
+ export function adam(f, x0, options = {}) {
212
+ const beta1 = options.beta1 || 0.9;
213
+ const beta2 = options.beta2 || 0.999;
214
+ const epsilon = options.epsilon || 1e-8;
215
+ return descend(
216
+ {
217
+ init: (n) => ({ m: new Array(n).fill(0), v: new Array(n).fill(0) }),
218
+ step: ({ x, gradient, state, iter, lr }) => {
219
+ const { m, v } = state;
220
+ for (let i = 0; i < x.length; i++) {
221
+ m[i] = beta1 * m[i] + (1 - beta1) * gradient[i];
222
+ v[i] = beta2 * v[i] + (1 - beta2) * gradient[i] * gradient[i];
223
+ }
224
+ const t = iter + 1;
225
+ for (let i = 0; i < x.length; i++) {
226
+ const mHat = m[i] / (1 - Math.pow(beta1, t));
227
+ const vHat = v[i] / (1 - Math.pow(beta2, t));
228
+ x[i] -= lr * mHat / (Math.sqrt(vHat) + epsilon);
229
+ }
230
+ },
231
+ },
232
+ f,
233
+ x0,
234
+ options,
235
+ );
236
+ }
package/src/index.js ADDED
@@ -0,0 +1,67 @@
1
+ /**
2
+ * @tangent.to/opt - Declarative numerical optimization for JavaScript (ESM)
3
+ *
4
+ * Function minimization, scalar optimization/root-finding and nonlinear
5
+ * least squares for the browser, Node, and Deno. Companion package to
6
+ * @tangent.to/ds.
7
+ */
8
+
9
+ export { methods, minimize } from './minimize.js';
10
+ export { nelderMead } from './neldermead.js';
11
+ export { lbfgs } from './lbfgs.js';
12
+ export { adam, backtrackingLineSearch, gradientDescent, momentumDescent, rmsprop } from './gradient.js';
13
+ export { strongWolfeLineSearch } from './linesearch.js';
14
+ export { minimizeScalar, rootScalar } from './scalar.js';
15
+ export { curveFit, leastSquares } from './leastsq.js';
16
+ export { solve } from './linsolve.js';
17
+ export { makeBoundsTransform } from './bounds.js';
18
+ export { numericalGradient, numericalHessian, numericalJacobian } from './numdiff.js';
19
+
20
+ // tangent/ds compatibility layer (ds.core.optimize drop-in)
21
+ export {
22
+ AdamOptimizer,
23
+ createOptimizer,
24
+ GradientDescent,
25
+ MomentumOptimizer,
26
+ RMSProp,
27
+ } from './compat.js';
28
+
29
+ import { methods, minimize } from './minimize.js';
30
+ import { nelderMead } from './neldermead.js';
31
+ import { lbfgs } from './lbfgs.js';
32
+ import { adam, gradientDescent, momentumDescent, rmsprop } from './gradient.js';
33
+ import { minimizeScalar, rootScalar } from './scalar.js';
34
+ import { curveFit, leastSquares } from './leastsq.js';
35
+ import { solve } from './linsolve.js';
36
+ import { numericalGradient, numericalHessian, numericalJacobian } from './numdiff.js';
37
+ import {
38
+ AdamOptimizer,
39
+ createOptimizer,
40
+ GradientDescent,
41
+ MomentumOptimizer,
42
+ RMSProp,
43
+ } from './compat.js';
44
+
45
+ export default {
46
+ minimize,
47
+ methods,
48
+ nelderMead,
49
+ lbfgs,
50
+ gradientDescent,
51
+ momentumDescent,
52
+ rmsprop,
53
+ adam,
54
+ minimizeScalar,
55
+ rootScalar,
56
+ leastSquares,
57
+ curveFit,
58
+ solve,
59
+ numericalGradient,
60
+ numericalHessian,
61
+ numericalJacobian,
62
+ GradientDescent,
63
+ MomentumOptimizer,
64
+ RMSProp,
65
+ AdamOptimizer,
66
+ createOptimizer,
67
+ };
package/src/lbfgs.js ADDED
@@ -0,0 +1,176 @@
1
+ /**
2
+ * L-BFGS: limited-memory quasi-Newton minimization
3
+ * (Nocedal & Wright, "Numerical Optimization", algorithm 7.4/7.5).
4
+ *
5
+ * Two-loop recursion over a ring buffer of the last `memory` curvature
6
+ * pairs (s, y), with strong Wolfe line search. Ring storage and work
7
+ * vectors use Float64Array and are allocated once per call.
8
+ */
9
+
10
+ import { makeEvaluator } from './evaluate.js';
11
+ import { strongWolfeLineSearch } from './linesearch.js';
12
+
13
+ function dot(a, b) {
14
+ let s = 0;
15
+ for (let i = 0; i < a.length; i++) s += a[i] * b[i];
16
+ return s;
17
+ }
18
+
19
+ function norm2(a) {
20
+ return Math.sqrt(dot(a, a));
21
+ }
22
+
23
+ /**
24
+ * Minimize a function with L-BFGS.
25
+ *
26
+ * @param {Function} f - Objective: (x) => number or (x) => {loss, gradient}
27
+ * @param {Array<number>} x0 - Initial parameters
28
+ * @param {Object} [options]
29
+ * @param {Function} [options.grad] - Gradient: (x) => Array<number> (finite differences otherwise)
30
+ * @param {number} [options.memory=10] - Number of curvature pairs kept
31
+ * @param {number} [options.maxIter=1000] - Maximum iterations
32
+ * @param {number} [options.tol=1e-6] - Convergence tolerance on the gradient norm
33
+ * @param {number} [options.fTol=1e-12] - Relative function-decrease tolerance
34
+ * @param {number} [options.c1=1e-4] - Line search sufficient-decrease constant
35
+ * @param {number} [options.c2=0.9] - Line search curvature constant
36
+ * @param {boolean} [options.verbose=false]
37
+ * @returns {Object} {x, fx, iterations, fevals, converged, history}
38
+ */
39
+ export function lbfgs(f, x0, options = {}) {
40
+ const n = x0.length;
41
+ const m = options.memory || 10;
42
+ const maxIter = options.maxIter || 1000;
43
+ const tol = options.tol || 1e-6;
44
+ const fTol = options.fTol !== undefined ? options.fTol : 1e-12;
45
+ const verbose = options.verbose || false;
46
+
47
+ const evaluate = makeEvaluator(f, options.grad, options);
48
+ let fevals = 0;
49
+ const ev = (x) => {
50
+ fevals++;
51
+ return evaluate(x);
52
+ };
53
+
54
+ // Ring buffers of curvature pairs and the two-loop workspace
55
+ const S = Array.from({ length: m }, () => new Float64Array(n));
56
+ const Y = Array.from({ length: m }, () => new Float64Array(n));
57
+ const rhoBuf = new Float64Array(m);
58
+ const alphaBuf = new Float64Array(m);
59
+ let stored = 0; // number of valid pairs
60
+ let head = 0; // next slot to write
61
+
62
+ const d = new Float64Array(n);
63
+ const history = { loss: [], gradNorm: [] };
64
+
65
+ let x = [...x0];
66
+ let { loss: fx, gradient: g } = ev(x);
67
+ let converged = false;
68
+ let iteration = 0;
69
+
70
+ /** d = -H*g via the two-loop recursion (γ-scaled identity as H0). */
71
+ function computeDirection() {
72
+ for (let i = 0; i < n; i++) d[i] = -g[i];
73
+ if (stored === 0) return;
74
+
75
+ for (let k = 0; k < stored; k++) {
76
+ const idx = (head - 1 - k + m * 2) % m; // newest to oldest
77
+ const a = rhoBuf[idx] * dot(S[idx], d);
78
+ alphaBuf[idx] = a;
79
+ const y = Y[idx];
80
+ for (let i = 0; i < n; i++) d[i] -= a * y[i];
81
+ }
82
+
83
+ // H0 = γI with γ = s'y / y'y from the most recent pair
84
+ const newest = (head - 1 + m) % m;
85
+ const gamma = 1 / (rhoBuf[newest] * dot(Y[newest], Y[newest]));
86
+ for (let i = 0; i < n; i++) d[i] *= gamma;
87
+
88
+ for (let k = stored - 1; k >= 0; k--) {
89
+ const idx = (head - 1 - k + m * 2) % m;
90
+ const beta = rhoBuf[idx] * dot(Y[idx], d);
91
+ const a = alphaBuf[idx];
92
+ const s = S[idx];
93
+ for (let i = 0; i < n; i++) d[i] += (a - beta) * s[i];
94
+ }
95
+ }
96
+
97
+ for (; iteration < maxIter; iteration++) {
98
+ history.loss.push(fx);
99
+ const gNorm = norm2(g);
100
+ history.gradNorm.push(gNorm);
101
+
102
+ if (gNorm < tol) {
103
+ converged = true;
104
+ break;
105
+ }
106
+
107
+ computeDirection();
108
+
109
+ // Guard: fall back to steepest descent if d is not a descent direction
110
+ if (dot(g, d) >= 0) {
111
+ stored = 0;
112
+ head = 0;
113
+ for (let i = 0; i < n; i++) d[i] = -g[i];
114
+ }
115
+
116
+ // Unit initial step once curvature is captured; scaled on iteration 0
117
+ const t0 = stored === 0 ? Math.min(1, 1 / Math.max(gNorm, 1e-12)) : 1;
118
+ let ls = strongWolfeLineSearch(ev, x, d, fx, g, {
119
+ t0,
120
+ c1: options.c1,
121
+ c2: options.c2,
122
+ });
123
+
124
+ if (!ls.success && stored > 0) {
125
+ // Curvature memory may be stale: restart from steepest descent
126
+ stored = 0;
127
+ head = 0;
128
+ for (let i = 0; i < n; i++) d[i] = -g[i];
129
+ ls = strongWolfeLineSearch(ev, x, d, fx, g, {
130
+ t0: Math.min(1, 1 / Math.max(gNorm, 1e-12)),
131
+ c1: options.c1,
132
+ c2: options.c2,
133
+ });
134
+ }
135
+ if (!ls.success) break; // converged stays false
136
+
137
+ // Store the curvature pair when it keeps H positive definite
138
+ const s = S[head];
139
+ const y = Y[head];
140
+ let ys = 0;
141
+ for (let i = 0; i < n; i++) {
142
+ s[i] = ls.xNew[i] - x[i];
143
+ y[i] = ls.gradient[i] - g[i];
144
+ ys += s[i] * y[i];
145
+ }
146
+ if (ys > 1e-10 * norm2(s) * norm2(y)) {
147
+ rhoBuf[head] = 1 / ys;
148
+ head = (head + 1) % m;
149
+ if (stored < m) stored++;
150
+ }
151
+
152
+ const fxPrev = fx;
153
+ x = ls.xNew;
154
+ fx = ls.fx;
155
+ g = ls.gradient;
156
+
157
+ if (verbose && iteration % 10 === 0) {
158
+ console.log(`Iter ${iteration}: loss=${fx.toFixed(8)}, grad_norm=${gNorm.toExponential(2)}`);
159
+ }
160
+
161
+ // Relative function-decrease stop (scipy factr-style)
162
+ if (fxPrev - fx <= fTol * Math.max(Math.abs(fxPrev), Math.abs(fx), 1)) {
163
+ converged = true;
164
+ iteration++;
165
+ history.loss.push(fx);
166
+ history.gradNorm.push(norm2(g));
167
+ break;
168
+ }
169
+ }
170
+
171
+ return {
172
+ x, fx, iterations: iteration,
173
+ nfev: fevals, fevals, // fevals is a deprecated alias for nfev
174
+ converged, success: converged, history,
175
+ };
176
+ }