@@ -1,4 +1,3 @@
1−{-# LANGUAGE CPP #-}
21{-# LANGUAGE DataKinds #-}
32{-# LANGUAGE GADTs #-}
43{-# LANGUAGE TypeOperators #-}
@@ -18,34 +17,37 @@ module Grenade.Recurrent.Core.Network (
1817
1918 , RecurrentNetwork (..)
2019 , RecurrentInputs (..)
21− , RecurrentTape (..)
22− , RecurrentGradient (..)
20+ , RecurrentTapes (..)
21+ , RecurrentGradients (..)
2322
2423 , randomRecurrent
25− , runRecurrent
26− , runRecurrent'
24+ , runRecurrentNetwork
25+ , runRecurrentGradient
2726 , applyRecurrentUpdate
2827 ) where
2928
3029
3130import Control.Monad.Random ( MonadRandom )
31+import Data.Singletons ( SingI )
32+import Data.Singletons.Prelude ( Head, Last )
3233import Data.Serialize
33−
34−import Data.Kind (Type)
34+import qualified Data.Vector.Storable as V
3535
3636import Grenade.Core
3737import Grenade.Recurrent.Core.Layer
38−import Prelude.Singletons
38+
39+import qualified Numeric.LinearAlgebra as LA
40+import qualified Numeric.LinearAlgebra.Static as LAS
3941
4042-- | Witness type to say indicate we're building up with a normal feed
4143-- forward layer.
42−data FeedForward :: Type -> Type
44+data FeedForward :: * -> *
4345-- | Witness type to say indicate we're building up with a recurrent layer.
44−data Recurrent :: Type -> Type
46+data Recurrent :: * -> *
4547
4648-- | Type of a recurrent neural network.
4749--
48−-- The [Type] type specifies the types of the layers.
50+-- The [*] type specifies the types of the layers.
4951--
5052-- The [Shape] type specifies the shapes of data passed between the layers.
5153--
@@ -54,7 +56,7 @@ data Recurrent :: Type -> Type
5456--
5557-- Often, to make the definitions more concise, one will use a type alias
5658-- for these empty data types.
57−data RecurrentNetwork :: [Type] -> [Shape] -> Type where
59+data RecurrentNetwork :: [*] -> [Shape] -> * where
5860 RNil :: SingI i
5961 => RecurrentNetwork '[] '[i]
6062
@@ -73,82 +75,96 @@ infixr 5 :~@>
7375-- | Gradient of a network.
7476--
7577-- Parameterised on the layers of the network.
76−data RecurrentGradient :: [Type] -> Type where
77− RGNil :: RecurrentGradient '[]
78+data RecurrentGradients :: [*] -> * where
79+ RGNil :: RecurrentGradients '[]
7880
7981 (://>) :: UpdateLayer x
80− => Gradient x
81− -> RecurrentGradient xs
82− -> RecurrentGradient (phantom x ': xs)
82+ => [Gradient x]
83+ -> RecurrentGradients xs
84+ -> RecurrentGradients (phantom x ': xs)
8385
8486-- | Recurrent inputs (sideways shapes on an imaginary unrolled graph)
8587-- Parameterised on the layers of a Network.
86−data RecurrentInputs :: [Type] -> Type where
88+data RecurrentInputs :: [*] -> * where
8789 RINil :: RecurrentInputs '[]
8890
89− (:~~+>) :: (UpdateLayer x, Fractional (RecurrentInputs xs))
91+ (:~~+>) :: UpdateLayer x
9092 => () -> !(RecurrentInputs xs) -> RecurrentInputs (FeedForward x ': xs)
9193
92− (:~@+>) :: (Fractional (RecurrentShape x), Fractional (RecurrentInputs xs), RecurrentUpdateLayer x)
93− => !(RecurrentShape x) -> !(RecurrentInputs xs) -> RecurrentInputs (Recurrent x ': xs)
94+ (:~@+>) :: (SingI (RecurrentShape x), RecurrentUpdateLayer x)
95+ => !(S (RecurrentShape x)) -> !(RecurrentInputs xs) -> RecurrentInputs (Recurrent x ': xs)
9496
9597-- | All the information required to backpropogate
9698-- through time safely.
9799--
98100-- We index on the time step length as well, to ensure
99101-- that that all Tape lengths are the same.
100−data RecurrentTape :: [Type] -> [Shape] -> Type where
102+data RecurrentTapes :: [*] -> [Shape] -> * where
101103 TRNil :: SingI i
102− => RecurrentTape '[] '[i]
104+ => RecurrentTapes '[] '[i]
105+
106+ (:\~>) :: [Tape x i h]
107+ -> !(RecurrentTapes xs (h ': hs))
108+ -> RecurrentTapes (FeedForward x ': xs) (i ': h ': hs)
103109
104− (:\~>) :: Tape x i h
105− -> !(RecurrentTape xs (h ': hs))
106− -> RecurrentTape (FeedForward x ': xs) (i ': h ': hs)
107110
108− (:\@>) :: RecTape x i h
109− -> !(RecurrentTape xs (h ': hs))
110− -> RecurrentTape (Recurrent x ': xs) (i ': h ': hs)
111+ (:\@>) :: [RecTape x i h]
112+ -> !(RecurrentTapes xs (h ': hs))
113+ -> RecurrentTapes (Recurrent x ': xs) (i ': h ': hs)
111114
112115
113−runRecurrent :: forall shapes layers.
114− RecurrentNetwork layers shapes
115− -> RecurrentInputs layers
116− -> S (Head shapes)
117− -> (RecurrentTape layers shapes, RecurrentInputs layers, S (Last shapes))
118−runRecurrent =
116+runRecurrentNetwork :: forall shapes layers.
117+ RecurrentNetwork layers shapes
118+ -> RecurrentInputs layers
119+ -> [S (Head shapes)]
120+ -> (RecurrentTapes layers shapes, RecurrentInputs layers, [S (Last shapes)])
121+runRecurrentNetwork =
119122 go
120123 where
121124 go :: forall js sublayers. (Last js ~ Last shapes)
122125 => RecurrentNetwork sublayers js
123126 -> RecurrentInputs sublayers
124− -> S (Head js)
125− -> (RecurrentTape sublayers js, RecurrentInputs sublayers, S (Last js))
126− go (!layer :~~> n) (() :~~+> nIn) !x
127− = let (!tape, !forwards) = runForwards layer x
128−
127+ -> [S (Head js)]
128+ -> (RecurrentTapes sublayers js, RecurrentInputs sublayers, [S (Last js)])
129+ -- This is a simple non-recurrent layer, just map it forwards
130+ go (layer :~~> n) (() :~~+> nIn) !xs
131+ = let tys = runForwards layer <$> xs
132+ feedForwardTapes = fst <$> tys
133+ forwards = snd <$> tys
129134 -- recursively run the rest of the network, and get the gradients from above.
130− (!newFN, !ig, !answer) = go n nIn forwards
131− in (tape :\~> newFN, () :~~+> ig, answer)
135+ (newFN, ig, answer) = go n nIn forwards
136+ in (feedForwardTapes :\~> newFN, () :~~+> ig, answer)
132137
133138 -- This is a recurrent layer, so we need to do a scan, first input to last, providing
134139 -- the recurrent shape output to the next layer.
135− go (layer :~@> n) (recIn :~@+> nIn) !x
136− = let (tape, shape, forwards) = runRecurrentForwards layer recIn x
140+ go (layer :~@> n) (recIn :~@+> nIn) !xs
141+ = let (recOut, tys) = goR layer recIn xs
142+ recurrentTapes = fst <$> tys
143+ forwards = snd <$> tys
144+
137145 (newFN, ig, answer) = go n nIn forwards
138− in (tape :\@> newFN, shape :~@+> ig, answer)
146+ in (recurrentTapes :\@> newFN, recOut :~@+> ig, answer)
139147
140148 -- Handle the output layer, bouncing the derivatives back down.
141149 -- We may not have a target for each example, so when we don't use 0 gradient.
142150 go RNil RINil !x
143151 = (TRNil, RINil, x)
144152
145−runRecurrent' :: forall layers shapes.
146− RecurrentNetwork layers shapes
147− -> RecurrentTape layers shapes
148− -> RecurrentInputs layers
149− -> S (Last shapes)
150− -> (RecurrentGradient layers, RecurrentInputs layers, S (Head shapes))
151−runRecurrent' net tapes r o =
153+ -- Helper function for recurrent layers
154+ -- Scans over the recurrent direction of the graph.
155+ goR !layer !recShape (x:xs) =
156+ let (tape, lerec, lepush) = runRecurrentForwards layer recShape x
157+ (rems, push) = goR layer lerec xs
158+ in (rems, (tape, lepush) : push)
159+ goR _ rin [] = (rin, [])
160+
161+runRecurrentGradient :: forall layers shapes.
162+ RecurrentNetwork layers shapes
163+ -> RecurrentTapes layers shapes
164+ -> RecurrentInputs layers
165+ -> [S (Last shapes)]
166+ -> (RecurrentGradients layers, RecurrentInputs layers, [S (Head shapes)])
167+runRecurrentGradient net tapes r o =
152168 go net tapes r
153169 where
154170 -- We have to be careful regarding the direction of the lists
@@ -156,41 +172,51 @@ runRecurrent' net tapes r o =
156172 -- through time.
157173 go :: forall js ss. (Last js ~ Last shapes)
158174 => RecurrentNetwork ss js
159− -> RecurrentTape ss js
175+ -> RecurrentTapes ss js
160176 -> RecurrentInputs ss
161− -> (RecurrentGradient ss, RecurrentInputs ss, S (Head js))
177+ -> (RecurrentGradients ss, RecurrentInputs ss, [S (Head js)])
162178 -- This is a simple non-recurrent layer
163− -- Run the rest of the network, update with the tapes and gradients
164− go (!layer :~~> n) (!tape :\~> nTapes) (() :~~+> nRecs) =
165− let (!gradients, !rins, !feed) = go n nTapes nRecs
166− (!grad, !back) = runBackwards layer tape feed
167− in (grad ://> gradients, () :~~+> rins, back)
179+ -- Run the rest of the network, then fmap the tapes and gradients
180+ go (layer :~~> n) (feedForwardTapes :\~> nTapes) (() :~~+> nRecs) =
181+ let (gradients, rins, feed) = go n nTapes nRecs
182+ backs = uncurry (runBackwards layer) <$> zip (reverse feedForwardTapes) feed
183+ in ((fst <$> backs) ://> gradients, () :~~+> rins, snd <$> backs)
168184
169185 -- This is a recurrent layer
170186 -- Run the rest of the network, scan over the tapes in reverse
171− go (!layer :~@> n) (!tape :\@> nTapes) (!recGrad :~@+> nRecs) =
172− let (!gradients, !rins, !feed) = go n nTapes nRecs
173− (!grad, !sidegrad, !back) = runRecurrentBackwards layer tape recGrad feed
174− in (grad ://> gradients, sidegrad :~@+> rins, back)
187+ go (layer :~@> n) (recurrentTapes :\@> nTapes) (recGrad :~@+> nRecs) =
188+ let (gradients, rins, feed) = go n nTapes nRecs
189+ backExamples = zip (reverse recurrentTapes) feed
190+ (rg, backs) = goX layer recGrad backExamples
191+ in ((fst <$> backs) ://> gradients, rg :~@+> rins, snd <$> backs)
175192
176193 -- End of the road, so we reflect the given gradients backwards.
177194 -- Crucially, we reverse the list, so it's backwards in time as
178195 -- well.
179− go !RNil !TRNil !RINil
180− = (RGNil, RINil, o)
196+ go RNil TRNil RINil
197+ = (RGNil, RINil, reverse o)
198+
199+ -- Helper function for recurrent layers
200+ -- Scans over the recurrent direction of the graph.
201+ goX :: RecurrentLayer x i o => x -> S (RecurrentShape x) -> [(RecTape x i o, S o)] -> (S (RecurrentShape x), [(Gradient x, S i)])
202+ goX layer !lastback ((recTape, backgrad):xs) =
203+ let (layergrad, recgrad, ingrad) = runRecurrentBackwards layer recTape lastback backgrad
204+ (pushedback, ll) = goX layer recgrad xs
205+ in (pushedback, (layergrad, ingrad) : ll)
206+ goX _ !lastback [] = (lastback, [])
181207
182208-- | Apply a batch of gradients to the network
183209-- Uses runUpdates which can be specialised for
184210-- a layer.
185211applyRecurrentUpdate :: LearningParameters
186212 -> RecurrentNetwork layers shapes
187− -> RecurrentGradient layers
213+ -> RecurrentGradients layers
188214 -> RecurrentNetwork layers shapes
189215applyRecurrentUpdate rate (layer :~~> rest) (gradient ://> grest)
190− = runUpdate rate layer gradient :~~> applyRecurrentUpdate rate rest grest
216+ = runUpdates rate layer gradient :~~> applyRecurrentUpdate rate rest grest
191217
192218applyRecurrentUpdate rate (layer :~@> rest) (gradient ://> grest)
193− = runUpdate rate layer gradient :~@> applyRecurrentUpdate rate rest grest
219+ = runUpdates rate layer gradient :~@> applyRecurrentUpdate rate rest grest
194220
195221applyRecurrentUpdate _ RNil RGNil
196222 = RNil
@@ -206,25 +232,26 @@ instance (Show x, Show (RecurrentNetwork xs rs)) => Show (RecurrentNetwork (Recu
206232
207233-- | A network can easily be created by hand with (:~~>) and (:~@>), but an easy way to initialise a random
208234-- recurrent network and a set of random inputs for it is with the randomRecurrent.
209−class CreatableRecurrent (xs :: [Type]) (ss :: [Shape]) where
235+class CreatableRecurrent (xs :: [*]) (ss :: [Shape]) where
210236 -- | Create a network of the types requested
211− randomRecurrent :: MonadRandom m => m (RecurrentNetwork xs ss)
237+ randomRecurrent :: MonadRandom m => m (RecurrentNetwork xs ss, RecurrentInputs xs)
212238
213239instance SingI i => CreatableRecurrent '[] '[i] where
214240 randomRecurrent =
215− return RNil
241+ return (RNil, RINil)
216242
217243instance (SingI i, Layer x i o, CreatableRecurrent xs (o ': rs)) => CreatableRecurrent (FeedForward x ': xs) (i ': o ': rs) where
218244 randomRecurrent = do
219245 thisLayer <- createRandom
220− rest <- randomRecurrent
221− return (thisLayer :~~> rest)
246+ (rest, resti) <- randomRecurrent
247+ return (thisLayer :~~> rest, () :~~+> resti)
222248
223249instance (SingI i, RecurrentLayer x i o, CreatableRecurrent xs (o ': rs)) => CreatableRecurrent (Recurrent x ': xs) (i ': o ': rs) where
224250 randomRecurrent = do
225251 thisLayer <- createRandom
226− rest <- randomRecurrent
227− return (thisLayer :~@> rest)
252+ thisShape <- randomOfShape
253+ (rest, resti) <- randomRecurrent
254+ return (thisLayer :~@> rest, thisShape :~@+> resti)
228255
229256-- | Add very simple serialisation to the recurrent network
230257instance SingI i => Serialize (RecurrentNetwork '[] '[i]) where
@@ -243,13 +270,23 @@ instance (Serialize (RecurrentInputs '[])) where
243270 put _ = return ()
244271 get = return RINil
245272
246−instance (UpdateLayer x, Serialize (RecurrentInputs ys), Fractional (RecurrentInputs ys)) => (Serialize (RecurrentInputs (FeedForward x ': ys))) where
273+instance (UpdateLayer x, Serialize (RecurrentInputs ys)) => (Serialize (RecurrentInputs (FeedForward x ': ys))) where
247274 put ( () :~~+> rest) = put rest
248275 get = ( () :~~+> ) <$> get
249276
250−instance (Serialize (RecurrentShape x), Fractional (RecurrentShape x), RecurrentUpdateLayer x, Serialize (RecurrentInputs ys), Fractional (RecurrentInputs ys)) => (Serialize (RecurrentInputs (Recurrent x ': ys))) where
251− put ( i :~@+> rest ) = put i >> put rest
252− get = (:~@+>) <$> get <*> get
277+instance (SingI (RecurrentShape x), RecurrentUpdateLayer x, Serialize (RecurrentInputs ys)) => (Serialize (RecurrentInputs (Recurrent x ': ys))) where
278+ put ( i :~@+> rest ) = do
279+ _ <- (case i of
280+ (S1D x) -> putListOf put . LA.toList . LAS.extract $ x
281+ (S2D x) -> putListOf put . LA.toList . LA.flatten . LAS.extract $ x
282+ (S3D x) -> putListOf put . LA.toList . LA.flatten . LAS.extract $ x
283+ ) :: PutM ()
284+ put rest
285+
286+ get = do
287+ Just i <- fromStorable . V.fromList <$> getListOf get
288+ rest <- get
289+ return ( i :~@+> rest)
253290
254291
255292-- Num instance for `RecurrentInputs layers`
@@ -270,7 +307,7 @@ instance (Num (RecurrentInputs '[])) where
270307 signum _ = RINil
271308 fromInteger _ = RINil
272309
273−instance (UpdateLayer x, Fractional (RecurrentInputs ys)) => (Num (RecurrentInputs (FeedForward x ': ys))) where
310+instance (UpdateLayer x, Num (RecurrentInputs ys)) => (Num (RecurrentInputs (FeedForward x ': ys))) where
274311 (+) (() :~~+> x) (() :~~+> y) = () :~~+> (x + y)
275312 (-) (() :~~+> x) (() :~~+> y) = () :~~+> (x - y)
276313 (*) (() :~~+> x) (() :~~+> y) = () :~~+> (x * y)
@@ -278,51 +315,10 @@ instance (UpdateLayer x, Fractional (RecurrentInputs ys)) => (Num (RecurrentInpu
278315 signum (() :~~+> x) = () :~~+> signum x
279316 fromInteger x = () :~~+> fromInteger x
280317
281−instance (Fractional (RecurrentShape x), RecurrentUpdateLayer x, Fractional (RecurrentInputs ys)) => (Num (RecurrentInputs (Recurrent x ': ys))) where
318+instance (SingI (RecurrentShape x), RecurrentUpdateLayer x, Num (RecurrentInputs ys)) => (Num (RecurrentInputs (Recurrent x ': ys))) where
282319 (+) (x :~@+> x') (y :~@+> y') = (x + y) :~@+> (x' + y')
283320 (-) (x :~@+> x') (y :~@+> y') = (x - y) :~@+> (x' - y')
284321 (*) (x :~@+> x') (y :~@+> y') = (x * y) :~@+> (x' * y')
285322 abs (x :~@+> x') = abs x :~@+> abs x'
286323 signum (x :~@+> x') = signum x :~@+> signum x'
287324 fromInteger x = fromInteger x :~@+> fromInteger x
288−
289−instance (Fractional (RecurrentInputs '[])) where
290− (/) _ _ = RINil
291− recip _ = RINil
292− fromRational _ = RINil
293−
294−instance (UpdateLayer x, Fractional (RecurrentInputs ys)) => (Fractional (RecurrentInputs (FeedForward x ': ys))) where
295− (/) (() :~~+> x) (() :~~+> y) = () :~~+> (x / y)
296− recip (() :~~+> x) = () :~~+> recip x
297− fromRational x = () :~~+> fromRational x
298−
299−instance (Fractional (RecurrentShape x), RecurrentUpdateLayer x, Fractional (RecurrentInputs ys)) => (Fractional (RecurrentInputs (Recurrent x ': ys))) where
300− (/) (x :~@+> x') (y :~@+> y') = (x / y) :~@+> (x' / y')
301− recip (x :~@+> x') = recip x :~@+> recip x'
302− fromRational x = fromRational x :~@+> fromRational x
303−
304−
305−-- | Ultimate composition.
306−--
307−-- This allows a complete network to be treated as a layer in a larger network.
308−instance CreatableRecurrent sublayers subshapes => UpdateLayer (RecurrentNetwork sublayers subshapes) where
309− type Gradient (RecurrentNetwork sublayers subshapes) = RecurrentGradient sublayers
310− runUpdate = applyRecurrentUpdate
311− createRandom = randomRecurrent
312−
313−-- | Ultimate composition.
314−--
315−-- This allows a complete network to be treated as a layer in a larger network.
316−instance CreatableRecurrent sublayers subshapes => RecurrentUpdateLayer (RecurrentNetwork sublayers subshapes) where
317− type RecurrentShape (RecurrentNetwork sublayers subshapes) = RecurrentInputs sublayers
318−
319−-- | Ultimate composition.
320−--
321−-- This allows a complete network to be treated as a layer in a larger network.
322−instance ( CreatableRecurrent sublayers subshapes
323− , i ~ (Head subshapes), o ~ (Last subshapes)
324− , Num (RecurrentShape (RecurrentNetwork sublayers subshapes))
325− ) => RecurrentLayer (RecurrentNetwork sublayers subshapes) i o where
326− type RecTape (RecurrentNetwork sublayers subshapes) i o = RecurrentTape sublayers subshapes
327− runRecurrentForwards = runRecurrent
328− runRecurrentBackwards = runRecurrent'