@tangent.to/opt 0.2.0 → 0.2.2

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.
package/llms.txt ADDED
@@ -0,0 +1,183 @@
1
+ # @tangent.to/opt 0.2.2
2
+
3
+ > Numerical optimization for JavaScript (ESM): L-BFGS, Nelder-Mead, gradient descent and Adam with box bounds; scalar minimization and root-finding; least squares and curve fitting
4
+
5
+ Numerical optimization for JavaScript (ESM): minimization in one or many
6
+ variables, scalar root-finding and nonlinear least squares. Zero
7
+ dependencies; runs in browsers, Node.js and Deno.
8
+
9
+ - **Multivariate**: L-BFGS with strong Wolfe line search (the default for
10
+ smooth problems), Nelder-Mead (derivative-free), gradient descent (optional
11
+ backtracking line search) and Adam
12
+ - **Scalar**: Brent and golden-section minimization with auto-bracketing;
13
+ Brent and bisection root-finding
14
+ - **Least squares**: Levenberg-Marquardt, and `curveFit` with covariance and
15
+ standard errors; robust losses `huber`, `soft_l1`, `cauchy`
16
+ - **Box bounds** for `minimize`, `leastSquares` and `curveFit`
17
+ (`bounds: [[0, 10], [null, 5]]`), by MINUIT-style parameter transforms
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ npm install @tangent.to/opt # npm
23
+ deno add jsr:@tangent/opt # Deno / JSR
24
+ ```
25
+
26
+ Types ship with the package. In a notebook, `await help('minimize')` returns
27
+ an export's documentation; `llms-full.txt` in the package holds all of it.
28
+
29
+ ## Usage
30
+
31
+ ```javascript
32
+ import { minimize } from '@tangent.to/opt';
33
+
34
+ // Derivative-free (default method: Nelder-Mead)
35
+ const result = minimize({
36
+ f: ([a, b]) => (1 - a) ** 2 + 100 * (b - a * a) ** 2,
37
+ x0: [-1.2, 1],
38
+ });
39
+ // { x: ≈ [1, 1], fx: 5.4e-11, iterations: 89, fevals: 168, converged: true, method: 'neldermead', ... }
40
+
41
+ // L-BFGS: use this for smooth objectives
42
+ const fit = minimize({
43
+ f: (x) => x[0] ** 2 + x[1] ** 2,
44
+ grad: (x) => [2 * x[0], 2 * x[1]], // optional; finite differences otherwise
45
+ x0: [3, -2],
46
+ method: 'lbfgs',
47
+ });
48
+ // fit.x: [0, 0]
49
+ ```
50
+
51
+ Methods for `minimize`: `'neldermead'`, `'lbfgs'`, `'gd'`, `'adam'` (aliases
52
+ in `methods()`). Other keys of the spec (`maxIter`, `tol`, `learningRate`,
53
+ `history`, ...) are passed to the method.
54
+
55
+ Scalar optimization, root-finding and curve fitting:
56
+
57
+ ```javascript
58
+ import { curveFit, minimizeScalar, rootScalar } from '@tangent.to/opt';
59
+
60
+ minimizeScalar(Math.cos, { bracket: [2, 4] }).x; // 3.14159265441603
61
+ rootScalar(Math.cos, { bracket: [1, 2] }).x; // 1.5707963267948966
62
+
63
+ const { params, stdErr } = curveFit({
64
+ model: (t, [a, b, c]) => a * Math.exp(-b * t) + c,
65
+ x: [0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4],
66
+ y: [3.02, 1.80, 1.17, 0.85, 0.66, 0.59, 0.55, 0.52, 0.51],
67
+ p0: [1, 1, 0],
68
+ bounds: [[0, null], [0, null], [null, null]], // optional
69
+ });
70
+ // params ≈ [2.524, 1.322, 0.496], stdErr ≈ [0.0078, 0.0100, 0.0043]
71
+ ```
72
+
73
+ `curveFit` and `leastSquares` take `loss: 'huber' | 'soft_l1' | 'cauchy'`
74
+ with a residual scale `fScale`. With a robust loss, `cov` and `stdErr` are
75
+ `NaN`: the Gaussian covariance formula does not apply.
76
+
77
+ ### Objectives
78
+
79
+ An objective returns a number, `{ loss, gradient }` or `{ value, gradient }`.
80
+ The last is what `@tangent.to/grad`'s `valueAndGrad` and `compile` return,
81
+ so either can be passed to `lbfgs` or `adam` as it is. Without a returned
82
+ gradient or a `grad` option, gradient methods use central finite
83
+ differences.
84
+
85
+ ### One step at a time
86
+
87
+ For a training loop that samples its own mini-batches, each update rule is
88
+ also a step function. It moves `x` in place (an array or `Float64Array`),
89
+ keeps its moments in a state created on the first call, and reads its options
90
+ on every call, so a learning-rate schedule is a number changed between steps.
91
+
92
+ ```javascript
93
+ import { adamStep } from '@tangent.to/opt';
94
+
95
+ const params = [3, -2];
96
+ const opts = { learningRate: 0.1 };
97
+ let state = null;
98
+ for (let i = 0; i < 500; i++) {
99
+ const gradient = [2 * params[0], 2 * params[1]]; // from a mini-batch, in practice
100
+ state = adamStep(params, gradient, state, opts);
101
+ }
102
+ // params ≈ [0, 0]
103
+ ```
104
+
105
+ `gradientStep`, `momentumStep`, `rmspropStep` and `adamStep` share this
106
+ signature. Keep one state per parameter tensor.
107
+
108
+ ### Result shape
109
+
110
+ Minimizers return `{ x, fx, iterations, converged, ... }`. `fevals` is
111
+ reported by Nelder-Mead, L-BFGS, the scalar methods and `leastSquares`;
112
+ `history` by L-BFGS and the gradient methods always, by Nelder-Mead and
113
+ `leastSquares` with `history: true`. `curveFit` returns
114
+ `{ params, cov, stdErr, fx, iterations, converged }`.
115
+
116
+ ## API
117
+
118
+ | export | purpose |
119
+ | --- | --- |
120
+ | `minimize(spec)`, `methods()` | multivariate minimization by method name |
121
+ | `nelderMead`, `lbfgs`, `gradientDescent`, `adam`, `momentumDescent`, `rmsprop` | the methods, as `(f, x0, options)` |
122
+ | `gradientStep`, `momentumStep`, `rmspropStep`, `adamStep` | single update steps |
123
+ | `minimizeScalar(f, options)`, `rootScalar(f, options)` | scalar minimization and root-finding |
124
+ | `leastSquares(spec)`, `curveFit(spec)` | nonlinear least squares |
125
+ | `numericalGradient`, `numericalJacobian`, `numericalHessian` | central finite differences |
126
+ | `strongWolfeLineSearch`, `backtrackingLineSearch`, `makeBoundsTransform`, `solve` | building blocks |
127
+ | `GradientDescent`, `MomentumOptimizer`, `RMSProp`, `AdamOptimizer`, `createOptimizer` | class interface used by `tangent/ds`: `minimize(lossFn, x0)` returns `{ x, history }` |
128
+
129
+ ## Validation
130
+
131
+ `npm run test:scipy` (needs [uv](https://docs.astral.sh/uv/) and Node)
132
+ checks each method against `scipy.optimize`: Nelder-Mead, L-BFGS against
133
+ `L-BFGS-B` (also with bounds), `minimizeScalar` against `minimize_scalar`,
134
+ `rootScalar` against `brentq`, `curveFit` parameters and standard errors
135
+ against `curve_fit`, robust losses against `least_squares`, gradient methods
136
+ against a BFGS optimum, and `numericalGradient` against `approx_fprime`.
137
+
138
+ ## Scope
139
+
140
+ General constrained optimization, LP/QP and global optimization are out of
141
+ scope.
142
+
143
+ ## License
144
+
145
+ MIT. The Nelder-Mead implementation is ported from
146
+ [fmin](https://github.com/benfred/fmin) (BSD-3-Clause); see
147
+ [THIRD_PARTY_NOTICES.md](./THIRD_PARTY_NOTICES.md).
148
+
149
+ ## Exports
150
+
151
+ - `nelderMead`: Minimize a function using the Nelder-Mead downhill simplex method.
152
+ - `lbfgs`: Minimize a function with L-BFGS.
153
+ - `strongWolfeLineSearch`: Find a step along direction p from x that satisfies the strong Wolfe conditions.
154
+ - `solve`: Solve the linear system A x = b by Gaussian elimination with scaled partial pivoting.
155
+ - `makeBoundsTransform`: Build the transform between bounded parameters and unbounded internal ones, or null when every parameter is free.
156
+ - `help`: This package's documentation, for where the README is out of reach, such as a notebook, and for coding assistants.
157
+ - `version`: This package's version.
158
+ - `methods`: List the method names `minimize` accepts, aliases included.
159
+ - `minimize`: Minimize a scalar function of one or more variables.
160
+ - `adam`: Minimize a function with Adam (adaptive moment estimation).
161
+ - `backtrackingLineSearch`: Find a step size along the negative gradient by backtracking until the Armijo condition holds.
162
+ - `gradientDescent`: Minimize a function by plain gradient descent, with optional backtracking line search.
163
+ - `momentumDescent`: Minimize a function by gradient descent with momentum.
164
+ - `rmsprop`: Minimize a function with RMSProp.
165
+ - `adamStep`: Take one Adam step in place (Kingma and Ba, 2015): bias-corrected first and second moments.
166
+ - `gradientStep`: Take one plain gradient-descent step in place: `x -= lr · g`.
167
+ - `momentumStep`: Take one gradient-descent-with-momentum step in place: `v = μ v + lr · g; x -= v`.
168
+ - `rmspropStep`: Take one RMSProp step in place: a running mean of squared gradients scales each coordinate's step.
169
+ - `minimizeScalar`: Minimize a univariate function.
170
+ - `rootScalar`: Find a root of a univariate function inside a sign-changing bracket.
171
+ - `curveFit`: Fit a model to (x, y) data by least squares, scipy.optimize.curve_fit style.
172
+ - `leastSquares`: Minimize a sum of squared residuals, 0.5 * sum(r(p)^2), with Levenberg-Marquardt.
173
+ - `numericalGradient`: Approximate the gradient of a scalar function by central finite differences.
174
+ - `numericalHessian`: Approximate the Hessian of a scalar function by central finite differences.
175
+ - `numericalJacobian`: Approximate the Jacobian of a vector-valued function by central finite differences.
176
+ - `AdamOptimizer`: Adam as a `tangent/ds`-style optimizer object: `minimize(lossFn, x0)` returns `{x, history}`.
177
+ - `createOptimizer`: Create a `tangent/ds`-style optimizer by name.
178
+ - `GradientDescent`: Batch gradient descent, with optional backtracking line search, as a `tangent/ds`-style optimizer object: `minimize(lossFn, x0)` returns `{x, history}`.
179
+ - `MomentumOptimizer`: Gradient descent with momentum as a `tangent/ds`-style optimizer object: `minimize(lossFn, x0)` returns `{x, history}`.
180
+ - `RMSProp`: RMSProp as a `tangent/ds`-style optimizer object: `minimize(lossFn, x0)` returns `{x, history}`.
181
+
182
+ Each export in full, with its types and options: https://cdn.jsdelivr.net/npm/@tangent.to/opt@0.2.2/llms-full.txt, or `await help('name')`
183
+ from the package itself.
package/package.json CHANGED
@@ -1,13 +1,15 @@
1
1
  {
2
2
  "name": "@tangent.to/opt",
3
- "version": "0.2.0",
4
- "description": "Declarative numerical optimization for JavaScript (ESM): Nelder-Mead, gradient descent, momentum, RMSProp, Adam",
3
+ "version": "0.2.2",
4
+ "description": "Numerical optimization for JavaScript (ESM): L-BFGS, Nelder-Mead, gradient descent and Adam with box bounds; scalar minimization and root-finding; least squares and curve fitting",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "module": "./dist/index.js",
8
8
  "browser": "./dist/index.js",
9
+ "types": "./types/index.d.ts",
9
10
  "exports": {
10
11
  ".": {
12
+ "types": "./types/index.d.ts",
11
13
  "import": "./dist/index.js",
12
14
  "default": "./dist/index.js"
13
15
  }
@@ -17,10 +19,13 @@
17
19
  "dist",
18
20
  "README.md",
19
21
  "LICENSE",
20
- "THIRD_PARTY_NOTICES.md"
22
+ "THIRD_PARTY_NOTICES.md",
23
+ "types",
24
+ "llms.txt",
25
+ "llms-full.txt"
21
26
  ],
22
27
  "scripts": {
23
- "prepare": "npm run build:browser",
28
+ "prepare": "npm run build:browser && npm run build:docs",
24
29
  "test": "vitest",
25
30
  "test:run": "vitest run",
26
31
  "test:coverage": "vitest --coverage",
@@ -32,7 +37,8 @@
32
37
  "deno:lint": "deno lint src/",
33
38
  "deno:fmt": "deno fmt src/",
34
39
  "deno:check": "deno check src/index.js",
35
- "version": "node scripts/sync-version.mjs && git add deno.json"
40
+ "version": "node scripts/sync-version.mjs && git add deno.json src/version.js",
41
+ "build:docs": "node scripts/docs.mjs"
36
42
  },
37
43
  "keywords": [
38
44
  "optimization",
@@ -56,6 +62,7 @@
56
62
  },
57
63
  "devDependencies": {
58
64
  "esbuild": "^0.25.11",
65
+ "typescript": "^6.0.3",
59
66
  "vitest": "^1.6.0"
60
67
  }
61
68
  }
package/src/bounds.js CHANGED
@@ -23,12 +23,20 @@ const UPPER = 2;
23
23
  const BOTH = 3;
24
24
 
25
25
  /**
26
- * Build a bounds transform, or return null when every parameter is free.
26
+ * Build the transform between bounded parameters and unbounded internal ones, or null when every parameter is free.
27
27
  *
28
- * @param {Array<Array<number|null>>} bounds - Per-parameter [lo, hi];
29
- * null/undefined/±Infinity mean unbounded on that side
28
+ * Both bounds: `ext = lo + (hi - lo) * (sin(int) + 1) / 2`; lower only:
29
+ * `ext = lo - 1 + sqrt(int^2 + 1)`; upper only: `ext = hi + 1 - sqrt(int^2 + 1)`.
30
+ * This is MINUIT's transform; `minimize`, `leastSquares` and `curveFit` use
31
+ * it for their `bounds`.
32
+ *
33
+ * @param {Array<[number|null|undefined, number|null|undefined]|null|undefined>} bounds - Per-parameter
34
+ * [lo, hi]; null/undefined/±Infinity mean unbounded on that side
30
35
  * @param {number} n - Number of parameters
31
- * @returns {Object|null} {toInternal, toExternal, dExtDInt, clamp}
36
+ * @returns {{toInternal: (xExt: number[]) => number[], toExternal: (xInt: number[]) => number[], dExtDInt: (xInt: number[]) => number[], clamp: (xExt: number[]) => number[]}|null}
37
+ * `toInternal` first clamps a point on or past a bound to just inside it;
38
+ * `dExtDInt` is d ext_i / d int_i at an internal point
39
+ * @throws {Error} if `bounds.length !== n` or a lower bound is not below its upper
32
40
  */
33
41
  export function makeBoundsTransform(bounds, n) {
34
42
  if (!Array.isArray(bounds) || bounds.length !== n) {
@@ -140,8 +148,8 @@ export function makeBoundsTransform(bounds, n) {
140
148
 
141
149
  /**
142
150
  * Wrap an objective (and optional gradient) so optimizers can run in
143
- * internal space. Supports both the scalar form (x) => number and the
144
- * combined form (x) => {loss, gradient}.
151
+ * internal space. Supports scalar objectives and combined objectives
152
+ * returning either {loss, gradient} or {value, gradient}.
145
153
  *
146
154
  * @param {Function} f - External objective
147
155
  * @param {Function|undefined} grad - External gradient
@@ -151,9 +159,11 @@ export function makeBoundsTransform(bounds, n) {
151
159
  export function wrapObjective(f, grad, T) {
152
160
  const fInt = (xInt) => {
153
161
  const out = f(T.toExternal(xInt));
154
- if (out !== null && typeof out === 'object' && 'loss' in out) {
162
+ if (out !== null && typeof out === 'object' &&
163
+ ('loss' in out || 'value' in out) && out.gradient != null) {
155
164
  const d = T.dExtDInt(xInt);
156
- return { loss: out.loss, gradient: out.gradient.map((gi, i) => gi * d[i]) };
165
+ const loss = 'loss' in out ? out.loss : out.value;
166
+ return { loss, gradient: out.gradient.map((gi, i) => gi * d[i]) };
157
167
  }
158
168
  return out;
159
169
  };
package/src/compat.js CHANGED
@@ -13,11 +13,18 @@
13
13
  import { adam, gradientDescent, momentumDescent, rmsprop } from './gradient.js';
14
14
 
15
15
  class Optimizer {
16
+ /**
17
+ * @param {Object} [options]
18
+ * @param {number} [options.learningRate=0.01] - Step size
19
+ * @param {number} [options.maxIter=1000] - Maximum iterations
20
+ * @param {number} [options.tol=1e-6] - Convergence tolerance on the gradient norm
21
+ * @param {boolean} [options.verbose=false] - Log progress every 100 iterations
22
+ */
16
23
  constructor(options = {}) {
17
- this.learningRate = options.learningRate || 0.01;
18
- this.maxIter = options.maxIter || 1000;
19
- this.tol = options.tol || 1e-6;
20
- this.verbose = options.verbose || false;
24
+ this.learningRate = options.learningRate ?? 0.01;
25
+ this.maxIter = options.maxIter ?? 1000;
26
+ this.tol = options.tol ?? 1e-6;
27
+ this.verbose = options.verbose ?? false;
21
28
  }
22
29
 
23
30
  /**
@@ -34,24 +41,46 @@ class Optimizer {
34
41
  _options(options) {
35
42
  return {
36
43
  learningRate: this.learningRate,
37
- maxIter: options.maxIter || this.maxIter,
38
- tol: options.tol || this.tol,
44
+ maxIter: options.maxIter ?? this.maxIter,
45
+ tol: options.tol ?? this.tol,
39
46
  verbose: this.verbose,
40
47
  };
41
48
  }
42
49
  }
43
50
 
44
51
  /**
45
- * Gradient Descent (batch; optional backtracking line search)
52
+ * Batch gradient descent, with optional backtracking line search, as a `tangent/ds`-style optimizer object: `minimize(lossFn, x0)` returns `{x, history}`.
53
+ *
54
+ * New code can call `gradientDescent` or `minimize` directly.
46
55
  */
47
56
  export class GradientDescent extends Optimizer {
57
+ /**
58
+ * @param {Object} [options]
59
+ * @param {number} [options.learningRate=0.01] - Step size
60
+ * @param {number} [options.maxIter=1000] - Maximum iterations
61
+ * @param {number} [options.tol=1e-6] - Convergence tolerance on the gradient norm
62
+ * @param {boolean} [options.verbose=false] - Log progress every 100 iterations
63
+ * @param {boolean} [options.lineSearch=false] - Backtracking line search in place of the fixed step
64
+ * @param {boolean} [options.stochastic=false] - Stored, unused
65
+ * @param {number} [options.batchSize=32] - Stored, unused
66
+ */
48
67
  constructor(options = {}) {
49
68
  super(options);
50
- this.stochastic = options.stochastic || false;
51
- this.batchSize = options.batchSize || 32;
52
- this.lineSearch = options.lineSearch || false;
69
+ this.stochastic = options.stochastic ?? false;
70
+ this.batchSize = options.batchSize ?? 32;
71
+ this.lineSearch = options.lineSearch ?? false;
53
72
  }
54
73
 
74
+ /**
75
+ * Minimize `lossFn` from `x0`.
76
+ * @param {(x: number[]) => number | {loss: number, gradient: number[]|Float64Array} | {value: number, gradient: number[]|Float64Array}} lossFn
77
+ * - Objective; usually `{loss, gradient}`, finite differences for a number
78
+ * @param {number[]} x0 - Initial parameters
79
+ * @param {Object} [options] - Overrides for this call
80
+ * @param {number} [options.maxIter] - Maximum iterations
81
+ * @param {number} [options.tol] - Gradient-norm tolerance
82
+ * @returns {{x: number[], history: {loss: number[], gradNorm: number[], learningRate: number[]}}}
83
+ */
55
84
  minimize(lossFn, x0, options = {}) {
56
85
  const { x, history } = gradientDescent(lossFn, x0, {
57
86
  ...this._options(options),
@@ -62,14 +91,34 @@ export class GradientDescent extends Optimizer {
62
91
  }
63
92
 
64
93
  /**
65
- * Momentum Optimizer
94
+ * Gradient descent with momentum as a `tangent/ds`-style optimizer object: `minimize(lossFn, x0)` returns `{x, history}`.
95
+ *
96
+ * New code can call `momentumDescent` or `minimize` directly.
66
97
  */
67
98
  export class MomentumOptimizer extends Optimizer {
99
+ /**
100
+ * @param {Object} [options]
101
+ * @param {number} [options.learningRate=0.01] - Step size
102
+ * @param {number} [options.maxIter=1000] - Maximum iterations
103
+ * @param {number} [options.tol=1e-6] - Convergence tolerance on the gradient norm
104
+ * @param {boolean} [options.verbose=false] - Log progress every 100 iterations
105
+ * @param {number} [options.momentum=0.9] - Momentum coefficient
106
+ */
68
107
  constructor(options = {}) {
69
108
  super(options);
70
- this.momentum = options.momentum || 0.9;
109
+ this.momentum = options.momentum ?? 0.9;
71
110
  }
72
111
 
112
+ /**
113
+ * Minimize `lossFn` from `x0`.
114
+ * @param {(x: number[]) => number | {loss: number, gradient: number[]|Float64Array} | {value: number, gradient: number[]|Float64Array}} lossFn
115
+ * - Objective; usually `{loss, gradient}`, finite differences for a number
116
+ * @param {number[]} x0 - Initial parameters
117
+ * @param {Object} [options] - Overrides for this call
118
+ * @param {number} [options.maxIter] - Maximum iterations
119
+ * @param {number} [options.tol] - Gradient-norm tolerance
120
+ * @returns {{x: number[], history: {loss: number[], gradNorm: number[]}}}
121
+ */
73
122
  minimize(lossFn, x0, options = {}) {
74
123
  const { x, history } = momentumDescent(lossFn, x0, {
75
124
  ...this._options(options),
@@ -80,15 +129,36 @@ export class MomentumOptimizer extends Optimizer {
80
129
  }
81
130
 
82
131
  /**
83
- * RMSProp Optimizer
132
+ * RMSProp as a `tangent/ds`-style optimizer object: `minimize(lossFn, x0)` returns `{x, history}`.
133
+ *
134
+ * New code can call `rmsprop` or `minimize` directly.
84
135
  */
85
136
  export class RMSProp extends Optimizer {
137
+ /**
138
+ * @param {Object} [options]
139
+ * @param {number} [options.learningRate=0.01] - Step size
140
+ * @param {number} [options.maxIter=1000] - Maximum iterations
141
+ * @param {number} [options.tol=1e-6] - Convergence tolerance on the gradient norm
142
+ * @param {boolean} [options.verbose=false] - Log progress every 100 iterations
143
+ * @param {number} [options.decay=0.9] - Decay of the running mean of squared gradients
144
+ * @param {number} [options.epsilon=1e-8] - Added to the denominator
145
+ */
86
146
  constructor(options = {}) {
87
147
  super(options);
88
- this.decay = options.decay || 0.9;
89
- this.epsilon = options.epsilon || 1e-8;
148
+ this.decay = options.decay ?? 0.9;
149
+ this.epsilon = options.epsilon ?? 1e-8;
90
150
  }
91
151
 
152
+ /**
153
+ * Minimize `lossFn` from `x0`.
154
+ * @param {(x: number[]) => number | {loss: number, gradient: number[]|Float64Array} | {value: number, gradient: number[]|Float64Array}} lossFn
155
+ * - Objective; usually `{loss, gradient}`, finite differences for a number
156
+ * @param {number[]} x0 - Initial parameters
157
+ * @param {Object} [options] - Overrides for this call
158
+ * @param {number} [options.maxIter] - Maximum iterations
159
+ * @param {number} [options.tol] - Gradient-norm tolerance
160
+ * @returns {{x: number[], history: {loss: number[], gradNorm: number[]}}}
161
+ */
92
162
  minimize(lossFn, x0, options = {}) {
93
163
  const { x, history } = rmsprop(lossFn, x0, {
94
164
  ...this._options(options),
@@ -100,16 +170,38 @@ export class RMSProp extends Optimizer {
100
170
  }
101
171
 
102
172
  /**
103
- * Adam Optimizer (Adaptive Moment Estimation)
173
+ * Adam as a `tangent/ds`-style optimizer object: `minimize(lossFn, x0)` returns `{x, history}`.
174
+ *
175
+ * New code can call `adam` or `minimize` directly.
104
176
  */
105
177
  export class AdamOptimizer extends Optimizer {
178
+ /**
179
+ * @param {Object} [options]
180
+ * @param {number} [options.learningRate=0.01] - Step size
181
+ * @param {number} [options.maxIter=1000] - Maximum iterations
182
+ * @param {number} [options.tol=1e-6] - Convergence tolerance on the gradient norm
183
+ * @param {boolean} [options.verbose=false] - Log progress every 100 iterations
184
+ * @param {number} [options.beta1=0.9] - First-moment decay
185
+ * @param {number} [options.beta2=0.999] - Second-moment decay
186
+ * @param {number} [options.epsilon=1e-8] - Added to the denominator
187
+ */
106
188
  constructor(options = {}) {
107
189
  super(options);
108
- this.beta1 = options.beta1 || 0.9;
109
- this.beta2 = options.beta2 || 0.999;
110
- this.epsilon = options.epsilon || 1e-8;
190
+ this.beta1 = options.beta1 ?? 0.9;
191
+ this.beta2 = options.beta2 ?? 0.999;
192
+ this.epsilon = options.epsilon ?? 1e-8;
111
193
  }
112
194
 
195
+ /**
196
+ * Minimize `lossFn` from `x0`.
197
+ * @param {(x: number[]) => number | {loss: number, gradient: number[]|Float64Array} | {value: number, gradient: number[]|Float64Array}} lossFn
198
+ * - Objective; usually `{loss, gradient}`, finite differences for a number
199
+ * @param {number[]} x0 - Initial parameters
200
+ * @param {Object} [options] - Overrides for this call
201
+ * @param {number} [options.maxIter] - Maximum iterations
202
+ * @param {number} [options.tol] - Gradient-norm tolerance
203
+ * @returns {{x: number[], history: {loss: number[], gradNorm: number[]}}}
204
+ */
113
205
  minimize(lossFn, x0, options = {}) {
114
206
  const { x, history } = adam(lossFn, x0, {
115
207
  ...this._options(options),
@@ -122,10 +214,16 @@ export class AdamOptimizer extends Optimizer {
122
214
  }
123
215
 
124
216
  /**
125
- * Convenience function to create optimizer by name
126
- * @param {string} name - Optimizer name
127
- * @param {Object} options - Optimizer options
128
- * @returns {Optimizer} Optimizer instance
217
+ * Create a `tangent/ds`-style optimizer by name.
218
+ *
219
+ * @param {'gd'|'gradient_descent'|'sgd'|'momentum'|'rmsprop'|'adam'} name - Case-insensitive;
220
+ * `'gd'`, `'gradient_descent'` and `'sgd'` all give a `GradientDescent`
221
+ * @param {Object} [options] - The class's constructor options
222
+ * @returns {GradientDescent|MomentumOptimizer|RMSProp|AdamOptimizer}
223
+ * @throws {Error} for an unknown name
224
+ * @example
225
+ * const opt = createOptimizer('adam', { learningRate: 0.1 });
226
+ * opt.minimize((x) => ({ loss: x[0] ** 2, gradient: [2 * x[0]] }), [3]).x; // ≈ [0]
129
227
  */
130
228
  export function createOptimizer(name, options = {}) {
131
229
  const optimizers = {