## Neural Networks with Weighty Lenses (DiOptics?)

I wrote a while back how you can make a pretty nice DSL for reverse mode differentiation based on the same type as Lens. I’d heard some interesting rumblings on the internet around these ideas and so was revisiting them.

type Lens s t a b = s -> (a, b -> t)
type AD x dx y dy = x -> (y, dy -> dx)

Composition is defined identically for reverse mode just as it is for lens.

After chewing on it a while, I realized this really isn’t that exotic. How it works is that you store the reverse mode computation graph, and all necessary saved data from the forward pass in the closure of the (dy -> dx). I also have a suspicion that if you defunctionalized this construction, you’d get the Wengert tape formulation of reverse mode ad.

Second, Lens is just a nice structure for bidirectional computation, with one forward pass and one backward pass which may or may not be getting/setting. There are other examples for using it like this.

It is also pretty similar to the standard “dual number” form type FAD x dx y dy = (x,dx)->(y,dy) for forward mode AD. We can bring the two closer by a CPS/Yoneda transformation and then some rearrangement.

     x -> (y, dy -> dx)
==>  x -> (y, forall s. (dx -> s) -> (dy -> s))
==>  forall s. (x, dx -> s) -> (y, dx -> s) 

and meet it in the middle with

(x,dx) -> (y,dy)
==> forall s. (x, s -> dx) -> (y, s -> dy)

I ended the previous post somewhat unsatisfied by how ungainly writing that neural network example was, and I called for Conal Elliot’s compiling to categories plugin as a possible solution. The trouble is piping the weights all over the place. This piping is very frustrating in point-free form, especially when you know it’d be so trivial pointful. While the inputs and outputs of layers of the network compose nicely (you no longer need to know about the internal computations), the weights do not. As we get more and more layers, we get more and more weights. The weights are in some sense not as compositional as the inputs and outputs of the layers, or compose in a different way that you need to maintain access to.

I thought of a very slight conceptual twist that may help.

The idea is we keep the weights out to the side in their own little type parameter slots. Then we define composition such that it composes input/outputs while tupling the weights. Basically we throw the repetitive complexity appearing in piping the weights around into the definition of composition itself.

These operations are easily seen as 2 dimensional diagrams.

Here’s the core reverse lens ad combinators

import Control.Arrow ((***))

type Lens'' a b = a -> (b, b -> a)

comp :: (b -> (c, (c -> b))) -> (a -> (b, (b -> a))) -> (a -> (c, (c -> a)))
comp f g x = let (b, dg) = g x in
let (c, df) = f b in
(c, dg . df)

id' :: Lens'' a a
id' x = (x, id)

relu' :: (Ord a, Num a) => Lens'' a a
relu' = \x -> (frelu x, brelu x) where
frelu x | x > 0 = x
| otherwise = 0
brelu x dy | x > 0 = dy
| otherwise = 0

add' :: Num a => Lens'' (a,a) a
add' = \(x,y) -> (x + y, \ds -> (ds, ds))

dup' :: Num a => Lens'' a (a,a)
dup' = \x -> ((x,x), \(dx,dy) -> dx + dy)

sub' :: Num a => Lens'' (a,a) a
sub' = \(x,y) -> (x - y, \ds -> (ds, -ds))

mul' :: Num a => Lens'' (a,a) a
mul' = \(x,y) -> (x * y, \dz -> (dz * y, x * dz))

recip' :: Fractional a => Lens'' a a
recip' = \x-> (recip x, \ds -> - ds / (x * x))

div' :: Fractional a => Lens'' (a,a) a
div' = (\(x,y) -> (x / y, \d -> (d/y,-x*d/(y * y))))

sin' :: Floating a => Lens'' a a
sin' = \x -> (sin x, \dx -> dx * (cos x))

cos' :: Floating a => Lens'' a a
cos' = \x -> (cos x, \dx -> -dx * (sin x))

pow' :: Num a => Integer -> Lens'' a a
pow' n = \x -> (x ^ n, \dx -> (fromInteger n) * dx * x ^ (n-1))

--cmul :: Num a => a -> Lens' a a
--cmul c = lens (* c) (\x -> \dx -> c * dx)

exp' :: Floating a => Lens'' a a
exp' = \x -> let ex = exp x in
(ex, \dx -> dx * ex)

fst' :: Num b => Lens'' (a,b) a
fst' = (\(a,b) -> (a, \ds -> (ds, 0)))

snd' :: Num a => Lens'' (a,b) b
snd' = (\(a,b) -> (b, \ds -> (0, ds)))

-- some monoidal combinators
swap' :: Lens'' (a,b) (b,a)
swap' = (\(a,b) -> ((b,a), \(db,da) -> (da, db)))

assoc' :: Lens'' ((a,b),c) (a,(b,c))
assoc' = \((a,b),c) -> ((a,(b,c)), \(da,(db,dc)) -> ((da,db),dc))

assoc'' :: Lens'' (a,(b,c)) ((a,b),c)
assoc'' = \(a,(b,c)) -> (((a,b),c), \((da,db),dc)->  (da,(db,dc)))

par' :: Lens'' a b -> Lens'' c d -> Lens'' (a,c) (b,d)
par' l1 l2 = l3 where
l3 (a,c) = let (b , j1) = l1 a in
let (d, j2) = l2 c in
((b,d) , j1 *** j2)
first' :: Lens'' a b -> Lens'' (a, c) (b, c)
first' l = par' l id'

second' :: Lens'' a b -> Lens'' (c, a) (c, b)
second' l = par' id' l

labsorb :: Lens'' ((),a) a
labsorb (_,a) = (a, \a' -> ((),a'))

labsorb' :: Lens'' a ((),a)
labsorb' a = (((),a), \(_,a') -> a')

rabsorb :: Lens'' (a,()) a
rabsorb = comp labsorb swap'

And here are the two dimensional combinators. I tried to write them point-free in terms of the combinators above to demonstrate that there is no monkey business going on. We

type WAD' w w' a b = Lens'' (w,a) (w',b)
type WAD'' w a b = WAD' w () a b -- terminate the weights for a closed network
{- For any monoidal category we can construct this composition? -}
-- horizontal composition
hcompose :: forall w w' w'' w''' a b c. WAD' w' w'' b c -> WAD' w w''' a b -> WAD' (w',w) (w'',w''') a c
hcompose f g = comp f' g' where
f' :: Lens'' ((w',r),b) ((w'',r),c)
f' = (first' swap') comp assoc'' comp (par' id' f) comp assoc' comp  (first' swap')
g' :: Lens'' ((r,w),a) ((r,w'''),b)
g' = assoc'' comp (par' id' g) comp assoc'

rotate :: WAD' w w' a b -> WAD' a b w w'
rotate f = swap' comp f comp swap'

-- vertical composition of weights
vcompose :: WAD' w'  w'' c d -> WAD' w w' a b -> WAD' w w'' (c, a) (d, b)
vcompose f g = rotate (hcompose (rotate f)  (rotate g) )

-- a double par.
diagpar :: forall w w' a b w'' w''' c d. WAD' w  w' a b -> WAD' w'' w''' c d
-> WAD' (w,w'') (w',w''') (a, c) (b, d)
diagpar f g = t' comp (par' f g) comp t where
t :: Lens'' ((w,w''),(a,c)) ((w,a), (w'',c)) -- yikes. just rearrangements.
t =  assoc'' comp (second' ((second' swap') comp assoc' comp swap')) comp assoc'
t' :: Lens'' ((w',b), (w''',d)) ((w',w'''),(b,d)) -- the tranpose of t
t' =  assoc'' comp (second'  ( swap'  comp assoc'' comp (second' swap')))  comp assoc'

id''' :: WAD' () () a a
id''' = id'

-- rotate:: WAD' w a a w
-- rotate = swap'

liftIO :: Lens'' a b -> WAD' w w a b
liftIO = second'

liftW :: Lens'' w w' -> WAD' w w' a a
liftW = first'

wassoc' = liftW assoc'
wassoc'' = liftW assoc''

labsorb'' :: WAD' ((),w) w a a
labsorb'' = first' labsorb

labsorb''' :: WAD' w ((),w) a a
labsorb''' = first' labsorb'

wswap' :: WAD' (w,w') (w',w) a a
wswap' = first' swap'
-- and so on we can lift all combinators

I wonder if this is actually nice?

I asked around and it seems like this idea may be what davidad is talking about when he refers to dioptics

http://events.cs.bham.ac.uk/syco/strings3-syco5/slides/dalrymple.pdf

Perhaps this will initiate a convo.

Edit: He confirms that what I’m doing appears to be a dioptic. Also he gave a better link http://events.cs.bham.ac.uk/syco/strings3-syco5/papers/dalrymple.pdf

He is up to some interesting diagrams

### Bits and Bobbles

• Does this actually work or help make things any better?
• Recurrent neural nets flip my intended role of weights and inputs.
• Do conv-nets naturally require higher dimensional diagrams?
• This weighty style seems like a good fit for my gauss seidel and iterative LQR solvers. A big problem I hit there was getting all the information to the outside, which is a similar issue to getting the weights around in a neural net.

## Applicative Bidirectional Programming and Automatic Differentiation

I got referred to an interesting paper by a comment of /u/syrak.

http://www2.sf.ecei.tohoku.ac.jp/~kztk/papers/kztk_jfp_am_2018.pdf

Applicative bidirectional programming (PDF), by Kazutaka Matsuda and Meng Wang

In it, they use a couple interesting tricks to make Lens programming more palatable. Lens often need to be be programmed in a point free style, which is rough, but by using some combinators, they are able to program lenses in a pointful style (with some pain points still left over). It is a really interesting, well-written paper. Lots ‘o’ Yoneda and laws. I’m not doing it justice. Check it out!

A while back I noted that reverse mode auto-differentiation has a type very similar to a lens and in fact you can build a working reverse mode automatic differentiation DSL out of lenses and lens-combinators. Many things about lenses, but not all, transfer over to automatic differentiation. The techniques of Matsuda and Wang do appear to transfer fairly well.

This is interesting to me for another reason. Their lift2 and unlift2 functions remind me very much of my recent approach to compiling to categories. The lift2 function is fanning a lens pair. This is basically what my FanOutput typeclass automated. unlift2 is building the input for a function function by supplying a tuple of projection lenses. This is what my BuildInput typeclass did. I think their style may extend many monoidal cartesian categories, not just lenses.

lift2 :: Lens (a,b) c -> (forall s. Num s => (Lens s a, Lens s b) -> Lens s c)
lift2 l (x,y) = lift l (fan x y)

unlift2 :: (Num a, Num b) => (forall s. Num s => (Lens s a, Lens s b) -> Lens s c) -> Lens (a,b) c
unlift2 f = f (fst', snd')

One can use the function b -> a in many of the situations one can use a in. You can do elegant things by making a Num typeclass of b -> a for example. This little fact seems to extend to other categories as well. By making a Num typeclass for Lens s a when a is a Num, we can use reasonable looking notation for arithmetic.

t1 :: Num a => Lens (a,a) a
t1 = unlift2 $\(x,y) -> x + y*y + y * 7 They spend some time discussing the necessity of a Poset typeclass. For actual lawful lenses, the dup implementation needs a way to recombine multiple adjustments to the same object. In the AD-lens case, dup takes care of this by adding together the differentials. This means that everywhere they needed an Eq typeclass, we can use a Num typeclass. There may be usefulness to building a wrapped type data NZ a = Zero | NonZero a like their Tag type to accelerate the many 0 values that may be propagating through the system. Unfortunately, as is, the performance of this is abysmal. Maybe there is a way to fix it? Unlifting and lifting destroys a lot of sharing and often necessitates adding many redundant zeros. Why are you doing reverse mode differentiation unless you care about performance? Forward mode is simpler to implement. In the intended use case of Matsuda and Wang, they are working with actual lawful lenses, which have far less computational content than AD-lenses. Good lawful lenses should just be shuffling stuff around a little. Maybe one can hope GHC is insanely intelligent and can optimize these zeros away. One point in favor of that is that our differentiation is completely pure (no mutation). Nevertheless, I suspect it will not without help. Being careful and unlifting and lifting manually may also help. In principle, I think the Lensy approach could be pretty fast (since all it is is just packing together exactly what you need to differentiate into a data type), but how to make it fast while still being easily programmable? It is also nice that it is pretty simple to implement. It is the simplest method that I know of if you needed to port operable reverse mode differentiation to a new library (Massiv?) or another functional language (Futhark?). And a smart compiler really does have a shot at finding optimizations/fusions. While I was at it, unrelated to the paper above, I think I made a working generic auto differentiable fold lens combinator. Pretty cool. mapAccumL is a hot tip. For practical Haskell purposes, all of this is a little silly with the good Haskell AD packages around, the most prominent being It is somewhat interesting to note the similarity of type forall s. Lens s appearing in the Matsuda and Wang approach to those those of the forall s. BVar s monad appearing in the backprop package. In this case I believe that the s type variable plays the same role it does in the ST monad, protecting a mutating Wengert tape state held in the monad, but I haven’t dug much into it. I don’t know enough about backprop to know what to make of this similarity. http://hackage.haskell.org/package/backprop The github repo with my playing around and stream of consciousness commentary is here {-# LANGUAGE NoImplicitPrelude, TypeSynonymInstances, RankNTypes #-} module Numeric.ADLens.AppBi where -- import Numeric.ADLens.Lens import Control.Category import Prelude hiding (id, (.)) import Control.Arrow ((***)) import Data.Functor.Const import Data.Traversable newtype Lens x y = Lens (x -> (y, y -> x)) type L s a = Num s => Lens s a instance Category Lens where id = Lens (\x -> (x, id)) (Lens f) . (Lens g) = Lens$ \x -> let (y, g') = g x in
let (z, f') = f y in
(z, g' . f')

grad'' (Lens f) x = let (y,j) = (f x) in j 1

lift :: Lens a b -> (forall s. Lens s a -> Lens s b)
lift l l' = l . l'

unlift :: Num a => (forall s. Num s => Lens s a -> Lens s b) -> Lens a b
unlift f = f id

dup :: Num a => Lens a (a,a)
dup = Lens $\x -> ((x,x), \(dx,dy) -> dx + dy) par :: Lens a b -> Lens c d -> Lens (a,c) (b,d) par (Lens f) (Lens g) = Lens l'' where l'' (a,c) = ((b,d), f' *** g') where (b,f') = f a (d,g') = g c fan :: Num s => Lens s a -> Lens s b -> Lens s (a,b) fan x y = (par x y) . dup -- impredicative polymorphism errror when we use L in type sig. I'm just going to avoid that. lift2 :: Lens (a,b) c -> (forall s. Num s => (Lens s a, Lens s b) -> Lens s c) lift2 l (x,y) = lift l (fan x y) unlift2 :: (Num a, Num b) => (forall s. Num s => (Lens s a, Lens s b) -> Lens s c) -> Lens (a,b) c unlift2 f = f (fst', snd') instance (Num a, Num b) => Num (a,b) where (x,y) + (a,b) = (x + a, y + b) (x,y) * (a,b) = (x * a, y * b) abs (x,y) = abs (x,y) fromInteger x = (fromInteger x, fromInteger x) -- and so on fst' :: Num b => Lens (a,b) a fst' = Lens (\(a,b) -> (a, \ds -> (ds, 0))) snd' :: Num a => Lens (a,b) b snd' = Lens (\(a,b) -> (b, \ds -> (0, ds))) unit :: Num s => Lens s () -- ? This isn't right. unit = Lens (\s -> ((), const 0)) add :: Num a => Lens (a,a) a add = Lens$ \(x,y) -> (x + y, \ds -> (ds, ds))

sub :: Num a => Lens (a,a) a
sub = Lens $\(x,y) -> (x - y, \ds -> (ds, -ds)) mul :: Num a => Lens (a,a) a mul = Lens$ \(x,y) -> (x * y, \dz -> (dz * y, x * dz))

recip' :: Fractional a => Lens a a
recip' = Lens $\x-> (recip x, \ds -> - ds / (x * x)) div :: Fractional a => Lens (a,a) a div = Lens$ (\(x,y) -> (x / y, \d -> (d/y,-x*d/(y * y))))

-- They called this "new" Section 3.2
constLens :: Num s => a -> Lens s a
constLens x = Lens (const (x, const 0))

-- or rather we might define add = unlift2 (+)
instance (Num s, Num a) => Num (Lens s a) where
x + y = (lift2 add) (x,y)
x - y = (lift2 sub) (x,y)
x * y = (lift2 mul) (x,y)
abs = error "TODO"
fromInteger x = constLens (fromInteger x)

t1 :: Num a => Lens (a,a) a
t1 = unlift2 $\(x,y) -> x + y*y + y * 7 -- See section on lifting list functions form biapplicative paper -- These are could be Iso. lcons :: Lens (a,[a]) [a] lcons = Lens$ \(a,as) -> (a : as, \xs -> (head xs, tail xs))
lnil :: Lens () [b]
lnil = Lens $const ([], const ()) lsequence :: Num s => [Lens s a] -> Lens s [a] lsequence [] = lift lnil unit lsequence (x : xs) = lift2 lcons (x, lsequence xs) llift :: Num s => Lens [a] b -> [Lens s a] -> Lens s b llift l xs = lift l (lsequence xs) instance (Num a) => Num [a] where (+) = zipWith (+) (*) = zipWith (*) (-) = zipWith (-) abs = map abs fromInteger x = repeat (fromInteger x) -- We need to hand f a list of the accessor lenses -- [Lens [a] a] -- This feels quite wrong. Indexing into a list is naughty. -- But that is what they do. Shrug. lunlift :: Num a => (forall s. Num s => [Lens s a] -> Lens s b) -> Lens [a] b lunlift f = Lens$ \xs ->
let n = length xs in
let inds = [0 .. n-1] in
let ls = map (lproj n) inds in
let (Lens f') = f ls in
f' xs

t2 :: Num a => Lens [a] a
t2 = lunlift sum
t3 :: Num a => Lens [a] a
t3 = lunlift product

lproj :: Num a => Int -> Int -> Lens [a] a
lproj n' ind = Lens $\xs -> ((xs !! ind), \x' -> replace ind x' zeros) where replace 0 x (y:ys) = x : ys replace n x (y:ys) = y : (replace (n-1) x ys) zeros = replicate n' 0 lensmap :: Applicative f => Lens a b -> Lens (f a) (f b) lensmap (Lens f) = Lens$ \fa ->
let fbb = fmap f fa in
let fb = fmap fst fbb in
let fb2s = fmap snd fbb in
(fb, \fb' -> fb2s <*> fb')

-- Types work, but does this actually make sense?
lsequenceA :: (Applicative f, Applicative t, Traversable f, Traversable t) => Lens (t (f a)) (f (t a))
lsequenceA = Lens $\tfa -> (sequenceA tfa, sequenceA) ltraverse :: (Applicative f, Applicative t, Traversable f, Traversable t) => Lens a (f b) -> Lens (t a) (f (t b)) ltraverse f = lsequenceA . (lensmap f) lensfoldl :: Traversable t => Lens (a, b) a -> Lens (a, t b) a lensfoldl (Lens f) = Lens$ \(s, t) -> let (y, tape) = mapAccumL (curry f) s t  in
(y,  \db ->  mapAccumR (\db' f -> (f db')) db tape)
lensfoldr :: Traversable t => Lens (a, b) a -> Lens (a, t b) a
lensfoldr (Lens f) = Lens $\(s, t) -> let (y, tape) = mapAccumR (curry f) s t in (y, \db -> mapAccumL (\db' f -> (f db')) db tape) t5 = grad'' (lensfoldl mul) (1, [1,1,2,3]) liftC :: Num a => (Lens a b -> Lens c d) -> (forall s. Num s => Lens s a -> Lens s b) -> (forall t. Num t => Lens t c -> Lens t d) liftC c f = lift (c (unlift f)) ungrad :: Lens (a,b) c -> (a -> Lens b c) ungrad (Lens f) a = Lens (\b -> let (c,j) = f (a,b) in (c, snd . j)) ## Reverse Mode Differentiation is Kind of Like a Lens II For those looking for more on automatic differentiation in Haskell: Ed Kmett’s ad package http://hackage.haskell.org/package/ad Conal Elliott is making the rounds with a new take on AD (GOOD STUFF). http://conal.net/papers/essence-of-ad/ Justin Le has been making excellent posts and has another library he’s working on. https://blog.jle.im/entry/introducing-the-backprop-library.html And here we go: Reverse mode automatic differentiation is kind of like a lens. Here is the type for a non-fancy lens type Lens s t a b = s -> (a, b -> t) When you compose two lenses, you compose the getters (s -> a) and you compose the partially applied setter (b -> t) in the reverse direction. We can define a type for a reverse mode differentiable function type AD x dx y dy = x -> (y, dy -> dx) When you compose two differentiable functions you compose the functions and you flip compose the Jacobian transpose (dy -> dx). It is this flip composition which gives reverse mode it’s name. The dependence of the Jacobian on the base point x corresponds to the dependence of the setter on the original object The implementation of composition for Lens and AD are identical. Both of these things are described by the same box diagram (cribbed from the profunctor optics paper www.cs.ox.ac.uk/people/jeremy.gibbons/publications/poptics.pdf ). This is a very simple way of implementing a reserve mode automatic differentiation using only non exotic features of a functional programming language. Since it is so bare bones and functional, is this a good way to achieve the vision gorgeous post by Christoper Olah? http://colah.github.io/posts/2015-09-NN-Types-FP/ I do not know. Now, to be clear, these ARE NOT lenses. Please, I don’t want to cloud the water, do not call these lenses. They’re pseudolenses or something. A very important part of what makes a lens a lens is that it obeys the lens laws, in which the getter and setter behave as one would expect. Our “setter” is a functional representation of the Jacobian transpose and our getter is the function itself. These do not obey lens laws in general. ###### Chain Rule AND Jacobian What is reverse mode differentiation? One’s thinking is muddled by defaulting to the Calc I perspective of one dimensional functions. Thinking is also muddled by the general conception that the gradient is a vector. This is slightly sloppy talk and can lead to confusion. It definitely has confused me. The right setting for intuition is $R^n \rightarrow R^m$ functions If one looks at a multidimensional to multidimensional function like this, you can form a matrix of partial derivatives known as the Jacobian. In the scalar to scalar case this is a $1\times 1$ matrix, which we can think of as just a number. In the multi to scalar case this is a $1\times n$ matrix which we somewhat fuzzily can think of as a vector. The chain rule is a beautiful thing. It is what makes differentiation so elegant and tractable. For many-to-many functions, if you compose them you matrix multiply their Jacobians. Just to throw in some category theory spice (who can resist), the chain rule is a functor between the category of differentiable functions and the category of vector spaces where composition is given by Jacobian multiplication. This is probably wholly unhelpful. The cost of multiplication for an $a \times b$ matrix A and an $b \times c$ matrix B is $O(abc)$. If we have 3 matrices ABC, we can associate to the left or right. (AB)C vs A(BC) choosing which product to form first. These two associations have different cost, abc * acd for left association or abd * bcd for right association. We want to use the smallest dimension over and over. For functions that are ultimately many to scalar functions, that means we want to multiply starting at the right. For a clearer explanation of the importance of the association, maybe this will help https://en.wikipedia.org/wiki/Matrix_chain_multiplication ###### Functional representations of matrices A Matrix data type typically gives you full inspection of the elements. If you partially apply the matrix vector product function (!* :: Matrix -> Vector -> Vector) to a matrix m, you get a vector to vector function (!* m) :: Vector -> Vector. In the sense that a matrix is data representing a linear map, this type looks gorgeous. It is so evocative of purpose. If all you want to do is multiply matrices or perform matrix vector products this is not a bad way to go. A function in Haskell is a thing that exposes only a single interface, the ability to be applied. Very often, the loss of Gaussian elimination or eigenvalue decompositions is quite painfully felt. For simple automatic differentiation, it isn’t so bad though. You can inefficiently reconstitute a matrix from it’s functional form by applying it to a basis of vectors. One weakness of the functional form is that the type does not constrain the function to actually act linearly on the vectors. One big advantage of the functional form is that you can intermix different matrix types (sparse, low-rank, dense) with no friction, just so long as they all have some way of being applied to the same kind of vector. You can also use functions like (id :: a -> a) as the identity matrix, which are not built from any underlying matrix type at all. To match the lens, we need to represent the Jacobian transpose as the function (dy -> dx) mapping differentials in the output space to differentials in the input space. ###### The Lens Trick A lens is the combination of a getter (a function that grabs a piece out of a larger object) and a setter (a function that takes the object and a new piece and returns the object with that piece replaced). The common form of lens used in Haskell doesn’t look like the above. It looks like this. type Lens s t a b = forall f. Functor f => (a -> f b) -> (s -> f t) This form has exactly the same content as the previous form (A non obvious fact. See the Profunctor Optics paper above. Magic neato polymorphism stuff), with the added functionality of being able to compose using the regular Haskell (.) operator. I think a good case can be made to NOT use the lens trick (do as I say, not as I do). It obfuscates sharing and obfuscates your code to the compiler (I assume the compiler optimizations have less understanding of polymorphic functor types than it does of tuples and functions), meaning the compiler has less opportunity to help you out. But it is also pretty cool. So… I dunno. Edit: /u/mstksg points out that compilers actually LOVE the van Laarhoven representation (the lens trick) because when f is finally specialized it is a newtype wrappers which have no runtime cost. Then the compiler can just chew the thing apart. https://www.reddit.com/r/haskell/comments/9oc9dq/reverse_mode_differentiation_is_kind_of_like_a/ One thing that is extra scary about the fancy form is that it makes it less clear how much data is likely to be shared between the forward and backward pass. Another alternative to the lens that shows this is the following. type AD x dx y dy = (x -> y, x -> dy -> dx) This form is again the same in end result. However it cannot share computation and therefore isn’t the same performance wise. One nontrivial function that took me some head scratching is how to convert from the fancy lens directly to the regular lens without destroying sharing. I think this does it unfancy :: Lens' a b -> (a -> (b, b -> a)) unfancy l = getCompose . l (\b -> Compose (b, id)) ###### Some code I have some small exploration of the concept in this git https://github.com/philzook58/ad-lens Again, really check out Conal Elliott’s AD paper and enjoy the many, many apostrophes to follow. Some basic definitions and transformations between fancy and non fancy lenses. Extracting the gradient is similar to the set function. Gradient assumes a many to one function and it applies it to 1. import Data.Functor.Identity import Data.Functor.Const import Data.Functor.Compose type Lens' a b = forall f. Functor f => (b -> f b) -> a -> f a lens'' :: (a -> (b, b -> a)) -> Lens' a b lens'' h g x = fmap j fb where (b, j) = h x fb = g b over :: Lens' a b -> ((b -> b) -> a -> a) over l f = runIdentity . l (Identity . f) set :: Lens' a b -> a -> b -> a set l = flip (\x -> (over l (const x))) view :: Lens' a b -> a -> b view l = getConst . l Const unlens'' :: Lens' a b -> (a -> (b, b -> a)) unlens'' l = getCompose . l (\b -> Compose (b, id)) constlens :: Lens' (a,b) c -> b -> Lens' a c constlens l b = lens''$ \a -> let (c, df) = f (a,b) in
(c, fst . df) where
f = unlens'' l

grad :: Num b => Lens' a b -> a -> a
grad l = (flip (set l)) 1

Basic 1D functions and arrow/categorical combinators

-- add and dup are dual!

add' :: Num a => Lens' (a,a) a
add' = lens'' $\(x,y) -> (x + y, \ds -> (ds, ds)) dup' :: Num a => Lens' a (a,a) dup' = lens''$ \x -> ((x,x), \(dx,dy) -> dx + dy)

sub' :: Num a => Lens' (a,a) a
sub' = lens'' $\(x,y) -> (x - y, \ds -> (ds, -ds)) mul' :: Num a => Lens' (a,a) a mul' = lens''$ \(x,y) -> (x * y, \dz -> (dz * y, x * dz))

recip' :: Fractional a => Lens' a a
recip' = lens'' $\x-> (recip x, \ds -> - ds / (x * x)) div' :: Fractional a => Lens' (a,a) a div' = lens''$ (\(x,y) -> (x / y, \d -> (d/y,-x*d/(y * y))))

sin' :: Floating a => Lens' a a
sin' = lens'' $\x -> (sin x, \dx -> dx * (cos x)) cos' :: Floating a => Lens' a a cos' = lens''$ \x -> (cos x, \dx -> -dx * (sin x))

pow' :: Num a => Integer -> Lens' a a
pow' n = lens'' $\x -> (x ^ n, \dx -> (fromInteger n) * dx * x ^ (n-1)) --cmul :: Num a => a -> Lens' a a --cmul c = lens (* c) (\x -> \dx -> c * dx) exp' :: Floating a => Lens' a a exp' = lens''$ \x -> let ex = exp x in
(ex, \dx -> dx * ex)

fst' :: Num b => Lens' (a,b) a
fst' = lens'' (\(a,b) -> (a, \ds -> (ds, 0)))

snd' :: Num a => Lens' (a,b) b
snd' = lens'' (\(a,b) -> (b, \ds -> (0, ds)))

swap' :: Lens' (a,b) (b,a)
swap' = lens'' (\(a,b) -> ((b,a), \(db,da) -> (da, db)))

assoc' :: Lens' ((a,b),c) (a,(b,c))
assoc' = lens'' $\((a,b),c) -> ((a,(b,c)), \(da,(db,dc)) -> ((da,db),dc)) par' :: Lens' a b -> Lens' c d -> Lens' (a,c) (b,d) par' l1 l2 = lens'' f3 where f1 = unlens'' l1 f2 = unlens'' l2 f3 (a,c) = ((b,d), df1 *** df2) where (b,df1) = f1 a (d,df2) = f2 c fan' :: Num a => Lens' a b -> Lens' a c -> Lens' a (b,c) fan' l1 l2 = lens'' f3 where f1 = unlens'' l1 f2 = unlens'' l2 f3 a = ((b,c), \(db,dc) -> df1 db + df2 dc) where (b,df1) = f1 a (c,df2) = f2 a first' :: Lens' a b -> Lens' (a, c) (b, c) first' l = par' l id second' :: Lens' a b -> Lens' (c, a) (c, b) second' l = par' id l relu' :: (Ord a, Num a) => Lens' a a relu' = lens''$ \x -> (frelu x, brelu x) where
frelu x | x > 0 = x
| otherwise = 0
brelu x dy | x > 0 = dy
| otherwise = 0

Some List based stuff.

import Data.List (sort)
import Control.Applicative (ZipList (..))

-- replicate and sum are dual!

sum' :: Num a => Lens' [a] a
sum' = lens'' $\xs -> (sum xs, \dy -> replicate (length xs) dy) replicate' :: Num a => Int -> Lens' a [a] replicate' n = lens''$ \x -> (replicate n x, sum)

repeat' :: Num a => Lens' a [a]
repeat' = lens'' $\x -> (repeat x, sum) map' :: Lens' a b -> Lens' [a] [b] map' l = lens''$ \xs -> let (bs, fs) = unzip . map (unlens'' l) $xs in (bs, getZipList . ((ZipList fs) <*>) . ZipList) zip' :: Lens' ([a], [b]) [(a,b)] zip' = lens''$ \(as,bs) -> (zip as bs, unzip)

unzip' :: Lens' [(a,b)] ([a], [b])
unzip' = lens'' $\xs -> (unzip xs, uncurry zip) maximum' :: (Num a, Ord a) => Lens' [a] a maximum' = lens''$ \(x:xs) -> let (best, bestind, lenxs) = argmaxixum x 0 1 xs in
(best, \dy -> onehot bestind lenxs dy) where
argmaxixum best bestind len [] = (best, bestind, len)
argmaxixum best bestind curind (x:xs) = if x > best then argmaxixum x curind (curind + 1) xs else argmaxixum best bestind (curind + 1) xs
onehot n m x | m == 0 = []
| n == m = x : (onehot n (m-1) x)
| otherwise = 0 : (onehot n (m-1) x)

sort' :: Ord a => Lens' [a] [a]
sort' = lens'' $\xs -> let (sxs, indices) = unzip . sort$ zip xs [0 ..] in
(sxs, desort indices) where
desort indices = snd . unzip . sort . zip indices

And some functionality from HMatrix

import Numeric.LinearAlgebra
import Numeric.LinearAlgebra.Devel (zipVectorWith)
-- import Data.Vector as V

dot' :: (Container Vector t, Numeric t) => Lens' (Vector t, Vector t) t
dot' = lens'' $\(v1,v2) -> (v1 <.> v2, \ds -> (scale ds v2, scale ds v1)) mdot' :: (Product t, Numeric t) => Lens' (Matrix t, Vector t) (Vector t) mdot' = lens''$ \(a,v) -> (a #> v, \dv -> (outer dv v, dv <# a))

add' :: Additive c => Lens' (c, c) c
add' = lens'' $\(v1,v2) -> (add v1 v2, \dv -> (dv, dv)) -- I need konst I think? sumElements' :: (Container Vector t, Numeric t) => Lens' (Vector t) t sumElements' = lens''$ \v -> (sumElements v, \ds -> scalar ds)

reshape' :: Container Vector t => Int -> Lens' (Vector t) (Matrix t)
reshape' n = lens'' $\v -> (reshape n v, \dm -> flatten dm) -- conjugate transpose not trace tr'' :: (Transposable m mt, Transposable mt m) => Lens' m mt tr'' = lens''$ \x -> (tr x, \dt -> tr dt)

flatten' :: (Num t, Container Vector t) => Lens' (Matrix t) (Vector t)
flatten' = lens'' $\m -> let s = fst$ size m in
(flatten m,  \dm -> reshape s dm)

norm_2' :: (Container c R, Normed (c R), Linear R c) => Lens' (c R) R
norm_2' = lens'' $\v -> let nv = norm_2 v in (nv, \dnv -> scale (2 * dnv / nv) v ) cmap' :: (Element b, Container Vector e) => (Lens' e b) -> Lens' (Vector e) (Vector b) cmap' l = lens''$ \c -> (cmap f c, \dc -> zipVectorWith f' c dc) where
f = view l
f' = set l

{-
maxElement' :: Container c e => Lens' (c e) e
maxElement' = lens'' $\v -> let i = maxIndex v in (v ! i, dv -> scalar 0) -} det' :: Field t => Lens' (Matrix t) t det' = lens''$ \m -> let (minv, (lndet, phase)) = invlndet m in
let detm = phase * exp detm in
(detm, \ds -> (scale (ds * detm) minv))

diag' :: (Num a, Element a) => Lens' (Vector a) (Matrix a)
diag' = lens'' $\v -> (diag v, takeDiag) takeDiag' :: (Num a, Element a) => Lens' (Matrix a) (Vector a) takeDiag' = lens''$ \m -> (takeDiag m, diag)

In practice, I don’t think this is a very ergonomic approach without something like Conal Elliott’s Compiling to Categories plugin. You have to program in a point-free arrow style (inspired very directly by Conal’s above AD paper) which is pretty nasty IMO. The neural network code here is inscrutable. It is only a three layer neural network.

import Numeric.ADLens.Lens

import Numeric.LinearAlgebra

type L1 = Matrix Double
type L2 = Matrix Double
type L3 = Matrix Double

type Input = Vector Double
type Output = Vector Double
type Weights = (L1,(L2,(L3,())))

class TupleSum a where
tupsum :: a -> a -> a
instance TupleSum () where
tupsum _ _ = ()
instance (Num a, TupleSum b) => TupleSum (a,b) where
tupsum (a,x) (b,y) = (a + b, tupsum x y)

-- A dense relu neural network example
swaplayer :: Lens' ((Matrix t, b), Vector t) (b, (Matrix t, Vector t))
swaplayer = first' swap' . assoc'

mmultlayer :: Numeric t => Lens' (b, (Matrix t, Vector t)) (b, Vector t)
mmultlayer = second' mdot'

relulayer :: Lens' (b, Vector Double) (b, Vector Double)
relulayer = second' $cmap' relu' uselayer :: Lens' ((Matrix Double, b), Vector Double) (b, Vector Double) uselayer = swaplayer . mmultlayer . relulayer runNetwork :: Lens' (Weights, Input) ((), Output) runNetwork = uselayer . uselayer . uselayer main :: IO () main = do putStrLn "Starting Tests" print$ grad (pow' 2) 1
print $grad (pow' 4) 1 print$ grad (map' (pow' 2) . sum') $[1 .. 5] print$ grad (map' (pow' 4) . sum') $[1 .. 5] print$ map (\x -> 4 * x ^ 3 )  [1 .. 5]
l1 <- randn 3 4
l2 <- randn 2 3
l3 <- randn 1 2
let weights = (l1,(l2,(l3,())))
print $view runNetwork (weights, vector [1,2,3,4]) putStrLn "The neural network gradients" print$ set runNetwork (weights, vector [1,2,3,4]) ((), vector [1])

## Extracting a Banded Hessian in PyTorch

So pytorch does have some capability towards higher derivatives, with the caveat that you have to dot the gradients to turn them back into scalars before continuing. What this means is that you can sample a single application of the  Hessian (the matrix of second derivatives) at a time.

One could sample out every column of the hessian for example. Performance-wise I don’t know how bad this might be.

For a banded hessian, which will occur in a trajectory optimization problem (the bandedness being a reflection of the finite difference scheme), you don’t need that many samples. This feels more palatable. You only need to sample the hessian roughly the bandwidth number of times, which may be quite small. Plus, then you can invert that banded hessian very quickly using special purpose banded matrix solvers, which are also quite fast. I’m hoping that once I plug this into the trajectory optimization, I can use a Newton method (or SQP?) which will perform better than straight gradient descent.

If you pulled just a single column using [1,0,0,0,0,0..] for example, that would be wasteful, since there are so many known zeros in the banded matrix. Instead something like [1,0,0,1,0,0,1,0,0..] will not have any zeros in the result. This gets us every 3rd row of the matrix. Then we can sample with shifted versions like [0,1,0,0,1,0,0,1,0,0..]. until we have all the rows somewhere. Then there is some index shuffling to put the thing into a sane ordering, especially so that we can use https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.solveh_banded.html which requires the banded matrix to be given in a particular form.

An alternative approach might be to use an fft with some phase twiddling. Also it feels like since the Hessian is hermitian we ought to be able to use about half the samples, since half are redundant, but I haven’t figured out a clean way to do this yet. I think that perhaps sampling with random vectors and then solving for the coefficients would work, but again how to organize the code for such a thing?

Here’s a snippet simulatng extracting the band matrix from matrix products.

import numpy as np

N = 6
B = 5
h = np.diag(np.random.randn(N))
h = h + h.T # symmetrize our matrix
print(h)
band = y = np.zeros((B, N))
for i in range(B):
y = np.zeros(N)
y[i::B]=1
band[i,:] = h @ y
print(band)
for i in range(B):
band[:,i::B] = np.roll(band[:,i::B], -i, axis=0) #B//2

print(band)
print(band[:B//2+1,:])

and here is the full pytorch implementation including a linear banded solve.

import torch
import matplotlib.pyplot as plt
import numpy as np
import torch.optim
from scipy import linalg
import matplotlib.pyplot as plt

N = 12

x = torch.zeros(N, requires_grad=True)

L = torch.sum((x[1:] - x[ :-1])**2)/2 + x[0]**2/2 + x[-1]**2/2 #torch.sum((x**2))

#L.backward()
B = 3

print(delL)

hess = torch.zeros(3,N, requires_grad=False)
for i in range(3):
y = torch.zeros(N, requires_grad=False)
y[i::3]=1
delLy = delL @ y

delLy.backward(retain_graph=True)
print(hess)
nphess = hess.detach().numpy()
print(nphess)
for i in range(B):
nphess[:,i::B] = np.roll(nphess[:,i::B], -i, axis=0)

print(nphess)
print(nphess[:B//2+1,:])
hessband = nphess[:B//2+1,:]
b = np.zeros(N)
b[4]=1
x = linalg.solveh_banded(hessband, b, lower=True)
print(x)

plt.plot(x)
plt.show()


Output:

tensor([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])
None
tensor([ 2., -1., -1.,  2., -1., -1.,  2., -1., -1.,  2., -1.,  0.])
tensor([-1.,  2., -1., -1.,  2., -1., -1.,  2., -1., -1.,  2., -1.])
tensor([ 0., -1.,  2., -1., -1.,  2., -1., -1.,  2., -1., -1.,  2.])
tensor([[ 2., -1., -1.,  2., -1., -1.,  2., -1., -1.,  2., -1.,  0.],
[-1.,  2., -1., -1.,  2., -1., -1.,  2., -1., -1.,  2., -1.],
[ 0., -1.,  2., -1., -1.,  2., -1., -1.,  2., -1., -1.,  2.]])
[[ 2. -1. -1.  2. -1. -1.  2. -1. -1.  2. -1.  0.]
[-1.  2. -1. -1.  2. -1. -1.  2. -1. -1.  2. -1.]
[ 0. -1.  2. -1. -1.  2. -1. -1.  2. -1. -1.  2.]]
[[ 2.  2.  2.  2.  2.  2.  2.  2.  2.  2.  2.  2.]
[-1. -1. -1. -1. -1. -1. -1. -1. -1. -1. -1.  0.]
[ 0. -1. -1. -1. -1. -1. -1. -1. -1. -1. -1. -1.]]
[[ 2.  2.  2.  2.  2.  2.  2.  2.  2.  2.  2.  2.]
[-1. -1. -1. -1. -1. -1. -1. -1. -1. -1. -1.  0.]]
[0.61538462 1.23076923 1.84615385 2.46153846 3.07692308 2.69230769
2.30769231 1.92307692 1.53846154 1.15384615 0.76923077 0.38461538]

## Reverse Mode Auto Differentiation is Kind of Like a Lens

Edit: More cogent version here http://www.philipzucker.com/reverse-mode-differentiation-is-kind-of-like-a-lens-ii/

Warning: I’m using sketchy uncompiled Haskell pseudocode.

Auto-differentiation is writing a function that also computes the derivative alongside calculating its value. Function composition is done alongside applying the chain rule to the derivative part.

One way to do this is to use a “dual number”. Functions now take a tuple of values and derivatives.

The Jacobean of a function from $R^n \rightarrow R^m$ is a m by n matrix. The chain rule basically says that you need to compose the matrices via multiplication when you compose the value functions.  This is the composition of the linear maps.

Conceptually, you initialize the process with a NxN identity matrix corresponding to the fact that $\partial x_i/\partial x_j=\delta_{ij}$

type DFun = (Vector Double, Matrix Double) -> (Vector Double, Matrix Double)

sin' :: DFun
sin' (x, j) = (sin x, dot (diag \$ cos x) j )

Vectorized versions of scalar functions (maps) will often use diag

A couple points:

1.  Since the Jacobean j is always going to be multiplied in composition, it makes sense to factor this out into a Monad structure (Applicative maybe? Not sure we need full Monad power).
2. There is an alternative to using explicit Matrix data types for linear maps. We could instead represent the jacobeans using (Vector Double) -> Vector Double. The downside of this is that you can’t inspect elements. You need explicit matrices as far as I know to do Gaussian elimination and QR decomposition. You can sample the function to reconstitute the matrix if need be, but this is somewhat roundabout. On the other hand, if your only objective is to multiply matrices, one can use very efficient versions. Instead of an explicit dense NxN identity matrix, you can use the function id :: a -> a, which only does some minimal pointer manipulation or is optimized away. I think that since we are largely multiplying Jacobeans, this is fine.
newtype DMonad a = (a , a -> a)

return a = (a, id)
(x, j) >>= f =  let (y, j') = f x in (y, j' . j)

What we’ve shown so far is Forward Mode.

When you multiply matrices you are free to associate them in any direction you like. (D(C(BA))) is the association we’re using right now. But you are free to left associate them. ((DC)B)A). You can write this is right associated form using the transpose $((DC)B)A)^T = (A^T(B^T(C^TD^T)))$

This form is reverse mode auto differentiation. Its advantage is the number of computations you have to do and the intermediate values you have to hold. If one is going from many variables to a small result, this is preferable.

It is actually exactly the same in implementation except you reverse the order of composition of the derivatives. We forward compose value functions and reverse compose derivative functions (matrices).

newtype RDMonad a = (a , a -> a)

return a = (a, id)
(x, j) >>= f =  let (y, j') = f x in (y, j . j')

We have CPSed our derivative matrices.

Really a better typed version would not unify all the objects into a. While we’ve chosen to use Vector Double as our type, if we could tell the difference between R^n and R^m at the type level the following would make more sense.

newtype FD a b = (a , b -> a)
newtype RD a b = (a , a -> b)

However, this will no longer be a monad. Instead you’ll have to specify a Category instance. The way I got down to this stuff is via reading Conal Elliott’s new Automatic Differentiation paper which heavily uses the category interface.  I was trying to remove the need to use constrained categories (it is possible, but I was bogged down in type errors) and make it mesh nice with hmatrix. Let me also mention that using the Arrow style operators *** and dup and &&& and fst, and clever currying that he mentions also seems quite nice here. The Tuple structure is nice for expressing direct sum spaces in matrices. (Vector a, Vector b) is the direct sum of those vector spaces.

Anyway, the arrows for RD are

type DFun' = a -> RD a b = a -> (b, b -> a)

This is a form I’ve seen before though. It is a lens. Lens’ have a getter (a -> b) that extracts b from a and a setter (a -> b -> a) that given an a and a new b returns the replaced a.

Is an automatic derivative function in some sense extracting an implicit calculable value from the original vector and returning in a sense how to change the original function? It is unclear whether one should take the lens analogy far or not.

The type of Lens’  (forall f. Functor f => (b -> f b) -> a -> f a) means that it is isomorphic to a type like DFun’. The type itself does imply the lens laws of setters and getters, so these functions are definitely not proper lawful lenses. It is just curious that conceptually they are not that far off.

The lens trick of replacing this function with a quantified rank 1 type (forall f. ) or quantified rank-2 (forall p.) profunctor trick seems applicable here. We can then compose reverse mode functions using the ordinary (.) operator and abuse convenience functions from the lens library.

Neat if true.