r/Clojure • u/asterix276 • Jun 21 '26
I've been using PyTorch from Clojure for 3 years — finally cleaned it up into a library
Been doing ML work in Clojure for a few years using the excellent libpython-clj to bridge into PyTorch. Kept rewriting the same boilerplate across projects so I finally consolidated it into a clj-pytorch library.
The main thing that makes it more than just a thin wrapper is a defmodule macro for defining real nn.Module subclasses:
(nn/defmodule MLP [in-features hidden out-features]
:layers {:fc1 (nn/linear in-features hidden)
:act (nn/relu)
:fc2 (nn/linear hidden out-features)}
:forward (fn [self x]
(-> x
((nn/get-layer self :fc1))
((nn/get-layer self :act))
((nn/get-layer self :fc2)))))
(def model (MLP 128 256 10))
(model x) ;; modules implement IFnAlso includes training loops, dataloaders, optimizer helpers, and some inference utilities. If you're doing ML in with Pytorch and Clojure, maybe it saves you some time. There was a very good post some time ago on clojure civitas explaining pytorch and how to use it within clojure if you need a refresher.
It's not published to Clojars yet — if you want to try it, just add the GitHub sha to your deps.edn:▎
clj-pytorch/clj-pytorch {:git/url "https://github.com/rthadani/clj-pytorch"
:git/sha "642504807aa96bb3e72963b9170836b32324f95a"}github-link: https://github.com/rthadani/clj-pytorch