"Machine Learning" (curve fitting) Bezier curves with Enzyme AD and WASM
Calling this machine learning is really stretching it, but hey! atleast the title isn't "using AI to ...". The idea here is a canvas on which one can draw curves, and a program finds the closest possible cubic bezier and render it on an SVG. There exists a "loss value" which is the distance of the curve points from a bezier curve. The bezier with the smallest loss value will have the points of the drawn curve closest to it . It turns out one can have a closed form solution to the minima as shown here , but i wanted to try my hand at using gradient descent with Enzyme AD in WASM, and here we are. (besides, I see a matrix inversion in that blog post, which almost certainly would have to use an algorithm that is iterative).
The gradient descent curve fitting is written in C and compiled to WASM to run in the browser. For automatic differentation the excellent Enzyme AD is used. Enzyme can perform AD on LLVM IR the intermediate representation that clang compiler produces before compiling it all down to WASM.
It isn't perfect ofcourse, for one drawing a really complex curvy shape may not find a good fit to a bezier after all. Thats expected i guess since curves with more than two "squigles" cannot certainly be made by a cubic bezier. Sometimes even simple curves dont fit very well. But for the most part it looks good , and its kinda satisfying to see a smooth curve overlay over the jagged lines that one draws
Maybe sometime i'll sit down and explain it all in a post but till then source can be found here.