optimization-dev / dist /assets /pyodide.worker-CoStWDaX.js
nhamid289's picture
Deploy optimisation from main (6727a1a)
c964813 verified
Raw History Blame Contribute Delete
22.5 kB
(function(){"use strict";const S=Symbol("Comlink.proxy"),M=Symbol("Comlink.endpoint"),L=Symbol("Comlink.releaseProxy"),x=Symbol("Comlink.finalizer"),b=Symbol("Comlink.thrown"),j=e=>typeof e=="object"&&e!==null||typeof e=="function",D={canHandle:e=>j(e)&&e[S],serialize(e){const{port1:n,port2:t}=new MessageChannel;return E(e,n),[t,[t]]},deserialize(e){return e.start(),z(e)}},V={canHandle:e=>j(e)&&b in e,serialize({value:e}){let n;return e instanceof Error?n={isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:n={isError:!1,value:e},[n,[]]},deserialize(e){throw e.isError?Object.assign(new Error(e.value.message),e.value):e.value}},A=new Map([["proxy",D],["throw",V]]);function C(e,n){for(const t of e)if(n===t||t==="*"||t instanceof RegExp&&t.test(n))return!0;return!1}function E(e,n=globalThis,t=["*"]){n.addEventListener("message",function u(i){if(!i||!i.data)return;if(!C(t,i.origin)){console.warn(`Invalid origin '${i.origin}' for comlink proxy`);return}const{id:a,type:d,path:f}=Object.assign({path:[]},i.data),o=(i.data.argumentList||[]).map(c);let r;try{const s=f.slice(0,-1).reduce((p,g)=>p[g],e),l=f.reduce((p,g)=>p[g],e);switch(d){case"GET":r=l;break;case"SET":s[f.slice(-1)[0]]=c(i.data.value),r=!0;break;case"APPLY":r=l.apply(s,o);break;case"CONSTRUCT":{const p=new l(...o);r=F(p)}break;case"ENDPOINT":{const{port1:p,port2:g}=new MessageChannel;E(e,g),r=W(p,[p])}break;case"RELEASE":r=void 0;break;default:return}}catch(s){r={value:s,[b]:0}}Promise.resolve(r).catch(s=>({value:s,[b]:0})).then(s=>{const[l,p]=_(s);n.postMessage(Object.assign(Object.assign({},l),{id:a}),p),d==="RELEASE"&&(n.removeEventListener("message",u),R(n),x in e&&typeof e[x]=="function"&&e[x]())}).catch(s=>{const[l,p]=_({value:new TypeError("Unserializable return value"),[b]:0});n.postMessage(Object.assign(Object.assign({},l),{id:a}),p)})}),n.start&&n.start()}function H(e){return e.constructor.name==="MessagePort"}function R(e){H(e)&&e.close()}function z(e,n){const t=new Map;return e.addEventListener("message",function(i){const{data:a}=i;if(!a||!a.id)return;const d=t.get(a.id);if(d)try{d(a)}finally{t.delete(a.id)}}),w(e,t,[],n)}function v(e){if(e)throw new Error("Proxy has been released and is not useable")}function O(e){return m(e,new Map,{type:"RELEASE"}).then(()=>{R(e)})}const y=new WeakMap,h="FinalizationRegistry"in globalThis&&new FinalizationRegistry(e=>{const n=(y.get(e)||0)-1;y.set(e,n),n===0&&O(e)});function q(e,n){const t=(y.get(n)||0)+1;y.set(n,t),h&&h.register(e,n,e)}function G(e){h&&h.unregister(e)}function w(e,n,t=[],u=function(){}){let i=!1;const a=new Proxy(u,{get(d,f){if(v(i),f===L)return()=>{G(a),O(e),n.clear(),i=!0};if(f==="then"){if(t.length===0)return{then:()=>a};const o=m(e,n,{type:"GET",path:t.map(r=>r.toString())}).then(c);return o.then.bind(o)}return w(e,n,[...t,f])},set(d,f,o){v(i);const[r,s]=_(o);return m(e,n,{type:"SET",path:[...t,f].map(l=>l.toString()),value:r},s).then(c)},apply(d,f,o){v(i);const r=t[t.length-1];if(r===M)return m(e,n,{type:"ENDPOINT"}).then(c);if(r==="bind")return w(e,n,t.slice(0,-1));const[s,l]=I(o);return m(e,n,{type:"APPLY",path:t.map(p=>p.toString()),argumentList:s},l).then(c)},construct(d,f){v(i);const[o,r]=I(f);return m(e,n,{type:"CONSTRUCT",path:t.map(s=>s.toString()),argumentList:o},r).then(c)}});return q(a,e),a}function U(e){return Array.prototype.concat.apply([],e)}function I(e){const n=e.map(_);return[n.map(t=>t[0]),U(n.map(t=>t[1]))]}const P=new WeakMap;function W(e,n){return P.set(e,n),e}function F(e){return Object.assign(e,{[S]:!0})}function _(e){for(const[n,t]of A)if(t.canHandle(e)){const[u,i]=t.serialize(e);return[{type:"HANDLER",name:n,value:u},i]}return[{type:"RAW",value:e},P.get(e)||[]]}function c(e){switch(e.type){case"HANDLER":return A.get(e.name).deserialize(e.value);case"RAW":return e.value}}function m(e,n,t,u){return new Promise(i=>{const a=B();n.set(a,i),e.start&&e.start(),e.postMessage(Object.assign({id:a},t),u)})}function B(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}const T="https://cdn.jsdelivr.net/pyodide/v0.26.1/full/";function $(e){let n,t=null;function u(){return t??(t=(async()=>{const{loadPyodide:a}=await import(`${T}pyodide.mjs`);n=await a({indexURL:T}),await n.loadPackage(e.packages);for(const[o,r]of Object.entries(e.files))n.FS.writeFile(o,r);const{module:d,className:f}=e.manager??{module:"manager",className:"Manager"};return n.pyimport(d)[f]()})()),t}E({async init(){await u()},async call(a,d){let f;try{f=await u()}catch(l){return k(`Python failed to load: ${N(l)}`)}let o,r,s;try{return o=f[a],typeof o!="function"?k(`Manager has no method "${a}"`):(r=d===void 0?void 0:n.toPy(d),s=r===void 0?o():o(r),{ok:!0,data:(s?.toJs?s.toJs({dict_converter:Object.fromEntries}):s)??null})}catch(l){return l.type==="UserError"?{ok:!1,error:{kind:"user",message:J(N(l))}}:(console.error(l),k(N(l)))}finally{o?.destroy?.(),r?.destroy?.(),s?.destroy?.()}}})}function k(e){return{ok:!1,error:{kind:"internal",message:e}}}function N(e){return e instanceof Error?e.message:String(e)}function J(e){const n="UserError: ",t=e.lastIndexOf(n);return t===-1?e:e.slice(t+n.length).trim()}var X=`import json
from pathlib import Path
import numpy as np
from logic import OPTIMISERS, Objective, Run, parse_function
ALGORITHMS = {
spec["id"]: spec
for spec in json.loads((Path(__file__).parent / "algorithms.json").read_text())["algorithms"]
}
# Iterations a run can take before stepping stops
MAX_ITERATIONS = 1000
# Sample points for the plotted curve (one variable) or surface (two, per side)
CURVE_POINTS = 401
GRID_POINTS = 101
# Gradient arrows per side
ARROW_POINTS = 15
class UserError(Exception):
"""A mistake the student can fix; its message is shown in the UI."""
def _json_values(values: np.ndarray) -> list:
"""Values as JSON numbers, with null where f has no finite value."""
return [float(v) if np.isfinite(v) else None for v in values]
class Manager:
def __init__(self):
self._objective: Objective | None = None
self._runs: list[Run] = []
def handle_set_function(self, args: dict) -> None:
"""{variables: 1 | 2, expression}; clears the runs."""
self._objective = None
self._runs = []
n = int(args["variables"])
try:
expr = parse_function(str(args["expression"]), n)
except ValueError as e:
raise UserError(str(e))
try:
self._objective = Objective(expr, n)
except Exception:
raise UserError("This function can't be differentiated here. Try writing it another way.")
def handle_function_values(self, args: dict) -> dict | None:
"""f sampled over the plot's {x_range, y_range}; None with no function."""
f = self._objective
if f is None:
return None
with np.errstate(all="ignore"):
if f.n == 1:
x = np.linspace(*args["x_range"], CURVE_POINTS)
return {"x": x.tolist(), "f": _json_values(f.values_on(x))}
x = np.linspace(*args["x_range"], GRID_POINTS)
y = np.linspace(*args["y_range"], GRID_POINTS)
z = f.values_on(*np.meshgrid(x, y))
ax, ay = np.meshgrid(np.linspace(*args["x_range"], ARROW_POINTS), np.linspace(*args["y_range"], ARROW_POINTS))
u, v = f.gradient_on(ax, ay)
return {
"x": x.tolist(),
"y": y.tolist(),
# Rows follow y, columns follow x
"f": [_json_values(row) for row in z],
"arrows": {
"x": ax.ravel().tolist(),
"y": ay.ravel().tolist(),
"u": _json_values(u.ravel()),
"v": _json_values(v.ravel()),
},
}
def handle_set_runs(self, args: dict) -> None:
"""{runs: [{algorithm, start, params}]}: the optimisers to step together."""
self._runs = []
f = self._objective
if f is None:
raise ValueError("Function not set")
runs = []
for run in args["runs"]:
spec = ALGORITHMS[run["algorithm"]]
given = dict(run.get("params", {}))
params = {p["name"]: float(given.get(p["name"], p["default"])) for p in spec["params"]}
start = np.array(run["start"], dtype=float)
if start.shape != (f.n,):
raise ValueError(f"Start point needs {f.n} coordinates, got {start.tolist()}")
with np.errstate(all="ignore"):
if not np.isfinite(f.value(start)):
point = ", ".join(f"{c:g}" for c in start)
raise UserError(f"The function has no finite value at the initial point ({point}).")
runs.append(Run(f, OPTIMISERS[spec["id"]](f, **params), start))
self._runs = runs
def handle_state(self, args: dict) -> dict | None:
"""Every run after {iteration} iterations; None once all have stopped.
"stopped" says why a run ended, at its last point and after it (where
point is None). It is None while the run carries on.
"""
k = int(args["iteration"])
if not self._runs or k > MAX_ITERATIONS:
return None
points = [run.point(k) for run in self._runs]
if all(p is None for p in points):
return None
# Look one iteration ahead to know whether this is a run's last point
ended = [p is None or run.point(k + 1) is None for run, p in zip(self._runs, points)]
return {
"runs": [
{"point": p, "stopped": run.stopped if end else None}
for run, p, end in zip(self._runs, points, ended)
]
}
`,Y=`"""Objective functions and optimisers, in one or two variables.
Positions, gradients and Hessians are NumPy arrays of length 1 or 2, so each
optimiser is written once for both.
"""
import numpy as np
from sympy import Abs, Expr, acos, asin, atan, cos, exp, lambdify, log, pi, sin, sqrt, symbols, tan
from sympy.parsing.sympy_parser import (
convert_xor,
implicit_multiplication_application,
parse_expr,
standard_transformations,
)
# Real, so that e.g. d/dx |x| is sign(x)
VARIABLES = symbols("x y", real=True)
ALLOWED_NAMES = {
"sin": sin, "cos": cos, "tan": tan, "asin": asin, "acos": acos, "atan": atan,
"log": log, "ln": log, "sqrt": sqrt, "abs": Abs, "exp": exp,
"e": exp(1), "pi": pi, "π": pi,
}
def parse_function(expression: str, n_variables: int) -> Expr:
"""Parse e.g. "x^2 + 3y^2"; raises ValueError with a message for students."""
if not expression.strip():
raise ValueError("Enter a function.")
variables = VARIABLES[:n_variables]
names = {str(v): v for v in VARIABLES} | ALLOWED_NAMES
try:
expr = parse_expr(
expression,
local_dict=names,
transformations=standard_transformations + (implicit_multiplication_application, convert_xor),
)
except Exception:
raise ValueError("This isn't a function sympy can read. Check the brackets and operators.")
if not isinstance(expr, Expr):
raise ValueError("This isn't a function sympy can read. Check the brackets and operators.")
unknown = expr.free_symbols - set(variables)
if unknown:
allowed = " and ".join(str(v) for v in variables)
raise ValueError(f"Unknown name {', '.join(sorted(map(str, unknown)))}: use only {allowed}.")
return expr
class Objective:
"""f with its gradient and Hessian, evaluated at a point or on a grid."""
def __init__(self, expr: Expr, n_variables: int):
variables = VARIABLES[:n_variables]
self.n = n_variables
self._f = lambdify(variables, expr, modules="numpy")
self._gradient = [lambdify(variables, expr.diff(v), modules="numpy") for v in variables]
self._hessian = [[lambdify(variables, expr.diff(a, b), modules="numpy") for b in variables] for a in variables]
def value(self, p: np.ndarray) -> float:
return float(self._f(*p))
def gradient(self, p: np.ndarray) -> np.ndarray:
return np.array([float(g(*p)) for g in self._gradient])
def hessian(self, p: np.ndarray) -> np.ndarray:
return np.array([[float(h(*p)) for h in row] for row in self._hessian])
def values_on(self, *grid: np.ndarray) -> np.ndarray:
# Constant expressions give a scalar; spread it over the grid
return np.broadcast_to(np.asarray(self._f(*grid), dtype=float), grid[0].shape)
def gradient_on(self, *grid: np.ndarray) -> list[np.ndarray]:
return [np.broadcast_to(np.asarray(g(*grid), dtype=float), grid[0].shape) for g in self._gradient]
class SingularHessian(Exception):
pass
# Each optimiser keeps its own state between steps; step(p) returns the next position.
class GradientDescent:
"""Heavy-ball momentum: v ← μv − η∇f(x), x ← x + v."""
def __init__(self, objective: Objective, learning_rate: float, momentum: float):
self.f, self.lr, self.momentum = objective, learning_rate, momentum
self.v = 0.0
def step(self, p: np.ndarray) -> np.ndarray:
self.v = self.momentum * self.v - self.lr * self.f.gradient(p)
return p + self.v
class Nesterov:
"""Gradient taken at the look-ahead point x + μv."""
def __init__(self, objective: Objective, learning_rate: float, momentum: float):
self.f, self.lr, self.momentum = objective, learning_rate, momentum
self.v = 0.0
def step(self, p: np.ndarray) -> np.ndarray:
self.v = self.momentum * self.v - self.lr * self.f.gradient(p + self.momentum * self.v)
return p + self.v
class Newton:
"""x ← x − H⁻¹∇f(x)."""
def __init__(self, objective: Objective):
self.f = objective
def step(self, p: np.ndarray) -> np.ndarray:
h, g = self.f.hessian(p), self.f.gradient(p)
try:
delta = np.linalg.solve(h, g)
except np.linalg.LinAlgError:
raise SingularHessian()
# Pyodide's NumPy can't see floating-point errors, so solve returns inf or nan instead of raising
if np.all(np.isfinite(h)) and np.all(np.isfinite(g)) and not np.all(np.isfinite(delta)):
raise SingularHessian()
return p - delta
class Adagrad:
def __init__(self, objective: Objective, learning_rate: float, epsilon: float):
self.f, self.lr, self.eps = objective, learning_rate, epsilon
self.v = 0.0 # sum of squared gradients
def step(self, p: np.ndarray) -> np.ndarray:
g = self.f.gradient(p)
self.v = self.v + g**2
return p - self.lr / np.sqrt(self.v + self.eps) * g
class RMSProp:
def __init__(self, objective: Objective, learning_rate: float, beta: float, epsilon: float):
self.f, self.lr, self.beta, self.eps = objective, learning_rate, beta, epsilon
self.v = 0.0 # moving average of squared gradients
def step(self, p: np.ndarray) -> np.ndarray:
g = self.f.gradient(p)
self.v = self.beta * self.v + (1 - self.beta) * g**2
return p - self.lr / np.sqrt(self.v + self.eps) * g
class Adadelta:
def __init__(self, objective: Objective, beta: float, epsilon: float):
self.f, self.beta, self.eps = objective, beta, epsilon
self.v = 0.0 # moving average of squared gradients
self.s = 0.0 # moving average of squared updates
def step(self, p: np.ndarray) -> np.ndarray:
g = self.f.gradient(p)
self.v = self.beta * self.v + (1 - self.beta) * g**2
delta = -np.sqrt(self.s + self.eps) / np.sqrt(self.v + self.eps) * g
self.s = self.beta * self.s + (1 - self.beta) * delta**2
return p + delta
class Adam:
def __init__(self, objective: Objective, learning_rate: float, beta1: float, beta2: float, epsilon: float):
self.f, self.lr, self.beta1, self.beta2, self.eps = objective, learning_rate, beta1, beta2, epsilon
self.m = 0.0 # first moment
self.v = 0.0 # second moment
self.t = 0
def step(self, p: np.ndarray) -> np.ndarray:
g = self.f.gradient(p)
self.t += 1
self.m = self.beta1 * self.m + (1 - self.beta1) * g
self.v = self.beta2 * self.v + (1 - self.beta2) * g**2
m_hat = self.m / (1 - self.beta1**self.t)
v_hat = self.v / (1 - self.beta2**self.t)
return p - self.lr / (np.sqrt(v_hat) + self.eps) * m_hat
# Ids match backend/src/algorithms.json
OPTIMISERS = {
"gradient_descent": GradientDescent,
"nesterov": Nesterov,
"newton": Newton,
"adam": Adam,
"adagrad": Adagrad,
"rmsprop": RMSProp,
"adadelta": Adadelta,
}
# A run that gets further than this from the origin has diverged
DIVERGENCE_LIMIT = 1e6
DIVERGED = "The next point has no finite value or is beyond 1,000,000: the run diverged or left the function's domain."
SINGULAR = "The Hessian is singular here, so Newton's method can't take a step."
class Run:
"""One optimiser's trajectory, computed as far as it has been asked for."""
def __init__(self, objective: Objective, optimiser, start: np.ndarray):
self.f = objective
self.optimiser = optimiser
self.points = [self._describe(start)]
self.position = start
# Why the run ended, once it has
self.stopped: str | None = None
def point(self, k: int) -> dict | None:
"""The point after k iterations, or None if the run stopped before then."""
with np.errstate(all="ignore"):
while len(self.points) <= k and self.stopped is None:
self._advance()
return self.points[k] if k < len(self.points) else None
def _advance(self) -> None:
try:
p = self.optimiser.step(self.position)
except SingularHessian:
self.stopped = SINGULAR
return
if not np.all(np.abs(p) <= DIVERGENCE_LIMIT) or not np.isfinite(self.f.value(p)):
self.stopped = DIVERGED
return
self.position = p
self.points.append(self._describe(p))
def _describe(self, p: np.ndarray) -> dict:
return {
"position": p.tolist(),
"value": self.f.value(p),
"gradient": self.f.gradient(p).tolist(),
"hessian": self.f.hessian(p).tolist(),
}
`,K=`{
"algorithms": [
{
"id": "gradient_descent",
"label": "Gradient descent",
"params": [
{ "name": "learning_rate", "label": "Learning rate η", "symbol": "η", "kind": "number", "min": 0, "minExclusive": true, "default": 0.1, "description": "How far each step moves along the negative gradient." },
{ "name": "momentum", "label": "Momentum μ", "symbol": "μ", "kind": "number", "min": 0, "max": 1, "maxExclusive": true, "default": 0.0, "description": "How much of the previous step carries over into the next one." }
]
},
{
"id": "nesterov",
"label": "Nesterov momentum",
"params": [
{ "name": "learning_rate", "label": "Learning rate η", "symbol": "η", "kind": "number", "min": 0, "minExclusive": true, "default": 0.1, "description": "How far each step moves along the negative gradient." },
{ "name": "momentum", "label": "Momentum μ", "symbol": "μ", "kind": "number", "min": 0, "max": 1, "maxExclusive": true, "default": 0.1, "description": "How much of the previous step carries over; the gradient is taken at the look-ahead point." }
]
},
{
"id": "newton",
"label": "Newton's method",
"params": []
},
{
"id": "adam",
"label": "Adam",
"params": [
{ "name": "learning_rate", "label": "Learning rate η", "symbol": "η", "kind": "number", "min": 0, "minExclusive": true, "default": 0.1, "description": "The largest step size, roughly." },
{ "name": "beta1", "label": "Decay β₁", "symbol": "β₁", "kind": "number", "min": 0, "max": 1, "maxExclusive": true, "default": 0.9, "description": "Decay rate of the moving average of gradients (first moment)." },
{ "name": "beta2", "label": "Decay β₂", "symbol": "β₂", "kind": "number", "min": 0, "max": 1, "maxExclusive": true, "default": 0.999, "description": "Decay rate of the moving average of squared gradients (second moment)." },
{ "name": "epsilon", "label": "Epsilon ε", "symbol": "ε", "kind": "number", "min": 0, "minExclusive": true, "default": 1e-8, "description": "Added to the denominator to avoid dividing by zero." }
]
},
{
"id": "adagrad",
"label": "Adagrad",
"params": [
{ "name": "learning_rate", "label": "Learning rate η", "symbol": "η", "kind": "number", "min": 0, "minExclusive": true, "default": 0.1, "description": "Divided by the root of the summed squared gradients." },
{ "name": "epsilon", "label": "Epsilon ε", "symbol": "ε", "kind": "number", "min": 0, "minExclusive": true, "default": 1e-8, "description": "Added to the denominator to avoid dividing by zero." }
]
},
{
"id": "rmsprop",
"label": "RMSProp",
"params": [
{ "name": "learning_rate", "label": "Learning rate η", "symbol": "η", "kind": "number", "min": 0, "minExclusive": true, "default": 0.1, "description": "Divided by the root of the moving average of squared gradients." },
{ "name": "beta", "label": "Decay β", "symbol": "β", "kind": "number", "min": 0, "max": 1, "maxExclusive": true, "default": 0.9, "description": "Decay rate of the moving average of squared gradients." },
{ "name": "epsilon", "label": "Epsilon ε", "symbol": "ε", "kind": "number", "min": 0, "minExclusive": true, "default": 1e-8, "description": "Added to the denominator to avoid dividing by zero." }
]
},
{
"id": "adadelta",
"label": "Adadelta",
"params": [
{ "name": "beta", "label": "Decay β", "symbol": "β", "kind": "number", "min": 0, "max": 1, "maxExclusive": true, "default": 0.9, "description": "Decay rate of the moving averages of squared gradients and squared updates." },
{ "name": "epsilon", "label": "Epsilon ε", "symbol": "ε", "kind": "number", "min": 0, "minExclusive": true, "default": 0.001, "description": "Sets the first step size, and avoids dividing by zero." }
]
}
]
}
`;$({packages:["numpy","sympy"],files:{"manager.py":X,"logic.py":Y,"algorithms.json":K}})})();