@@ -17,12 +17,12 @@ module Grenade.Recurrent.Core.Network (
18 , RecurrentNetwork (..)
18 , RecurrentNetwork (..)
19 , RecurrentInputs (..)
19 , RecurrentInputs (..)
20− , RecurrentTapes (..)
20+ , RecurrentTape (..)
21− , RecurrentGradients (..)
21+ , RecurrentGradient (..)
23 , randomRecurrent
23 , randomRecurrent
24− , runRecurrentNetwork
24+ , runRecurrent
25− , runRecurrentGradient
25+ , runRecurrent'
26 , applyRecurrentUpdate
26 , applyRecurrentUpdate
@@ -31,14 +31,10 @@ import Control.Monad.Random ( MonadRandom )
31import Data.Singletons ( SingI )
31import Data.Singletons ( SingI )
32import Data.Singletons.Prelude ( Head, Last )
32import Data.Singletons.Prelude ( Head, Last )
33import Data.Serialize
33import Data.Serialize
34−import qualified Data.Vector.Storable as V
36import Grenade.Core
35import Grenade.Core
37import Grenade.Recurrent.Core.Layer
36import Grenade.Recurrent.Core.Layer
39−import qualified Numeric.LinearAlgebra as LA
40−import qualified Numeric.LinearAlgebra.Static as LAS
42-- | Witness type to say indicate we're building up with a normal feed
38-- | Witness type to say indicate we're building up with a normal feed
43-- forward layer.
39-- forward layer.
44data FeedForward :: * -> *
40data FeedForward :: * -> *
@@ -75,96 +71,82 @@ infixr 5 :~@>
75-- | Gradient of a network.
71-- | Gradient of a network.
77-- Parameterised on the layers of the network.
73-- Parameterised on the layers of the network.
78−data RecurrentGradients :: [*] -> * where
74+data RecurrentGradient :: [*] -> * where
79− RGNil :: RecurrentGradients '[]
75+ RGNil :: RecurrentGradient '[]
81 (://>) :: UpdateLayer x
77 (://>) :: UpdateLayer x
82− => [Gradient x]
78+ => Gradient x
83− -> RecurrentGradients xs
79+ -> RecurrentGradient xs
84− -> RecurrentGradients (phantom x ': xs)
80+ -> RecurrentGradient (phantom x ': xs)
86-- | Recurrent inputs (sideways shapes on an imaginary unrolled graph)
82-- | Recurrent inputs (sideways shapes on an imaginary unrolled graph)
87-- Parameterised on the layers of a Network.
83-- Parameterised on the layers of a Network.
88data RecurrentInputs :: [*] -> * where
84data RecurrentInputs :: [*] -> * where
89 RINil :: RecurrentInputs '[]
85 RINil :: RecurrentInputs '[]
91− (:~~+>) :: UpdateLayer x
87+ (:~~+>) :: (UpdateLayer x, Fractional (RecurrentInputs xs))
92 => () -> !(RecurrentInputs xs) -> RecurrentInputs (FeedForward x ': xs)
88 => () -> !(RecurrentInputs xs) -> RecurrentInputs (FeedForward x ': xs)
94− (:~@+>) :: (SingI (RecurrentShape x), RecurrentUpdateLayer x)
90+ (:~@+>) :: (Fractional (RecurrentShape x), Fractional (RecurrentInputs xs), RecurrentUpdateLayer x)
95− => !(S (RecurrentShape x)) -> !(RecurrentInputs xs) -> RecurrentInputs (Recurrent x ': xs)
91+ => !(RecurrentShape x) -> !(RecurrentInputs xs) -> RecurrentInputs (Recurrent x ': xs)
97-- | All the information required to backpropogate
93-- | All the information required to backpropogate
98-- through time safely.
94-- through time safely.
100-- We index on the time step length as well, to ensure
96-- We index on the time step length as well, to ensure
101-- that that all Tape lengths are the same.
97-- that that all Tape lengths are the same.
102−data RecurrentTapes :: [*] -> [Shape] -> * where
98+data RecurrentTape :: [*] -> [Shape] -> * where
103 TRNil :: SingI i
99 TRNil :: SingI i
104− => RecurrentTapes '[] '[i]
100+ => RecurrentTape '[] '[i]
106− (:\~>) :: [Tape x i h]
107− -> !(RecurrentTapes xs (h ': hs))
108− -> RecurrentTapes (FeedForward x ': xs) (i ': h ': hs)
102+ (:\~>) :: Tape x i h
103+ -> !(RecurrentTape xs (h ': hs))
104+ -> RecurrentTape (FeedForward x ': xs) (i ': h ': hs)
111− (:\@>) :: [RecTape x i h]
106+ (:\@>) :: RecTape x i h
112− -> !(RecurrentTapes xs (h ': hs))
107+ -> !(RecurrentTape xs (h ': hs))
113− -> RecurrentTapes (Recurrent x ': xs) (i ': h ': hs)
108+ -> RecurrentTape (Recurrent x ': xs) (i ': h ': hs)
116−runRecurrentNetwork :: forall shapes layers.
111+runRecurrent :: forall shapes layers.
117− RecurrentNetwork layers shapes
112+ RecurrentNetwork layers shapes
118− -> RecurrentInputs layers
113+ -> RecurrentInputs layers
119− -> [S (Head shapes)]
114+ -> S (Head shapes)
120− -> (RecurrentTapes layers shapes, RecurrentInputs layers, [S (Last shapes)])
115+ -> (RecurrentTape layers shapes, RecurrentInputs layers, S (Last shapes))
121−runRecurrentNetwork =
116+runRecurrent =
124 go :: forall js sublayers. (Last js ~ Last shapes)
119 go :: forall js sublayers. (Last js ~ Last shapes)
125 => RecurrentNetwork sublayers js
120 => RecurrentNetwork sublayers js
126 -> RecurrentInputs sublayers
121 -> RecurrentInputs sublayers
127− -> [S (Head js)]
122+ -> S (Head js)
128− -> (RecurrentTapes sublayers js, RecurrentInputs sublayers, [S (Last js)])
123+ -> (RecurrentTape 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
124+ go (!layer :~~> n) (() :~~+> nIn) !x
131− = let tys = runForwards layer <$> xs
125+ = let (!tape, !forwards) = runForwards layer x
132− feedForwardTapes = fst <$> tys
126+
133− forwards = snd <$> tys
134 -- recursively run the rest of the network, and get the gradients from above.
127 -- recursively run the rest of the network, and get the gradients from above.
135− (newFN, ig, answer) = go n nIn forwards
128+ (!newFN, !ig, !answer) = go n nIn forwards
136− in (feedForwardTapes :\~> newFN, () :~~+> ig, answer)
129+ in (tape :\~> newFN, () :~~+> ig, answer)
138 -- This is a recurrent layer, so we need to do a scan, first input to last, providing
131 -- This is a recurrent layer, so we need to do a scan, first input to last, providing
139 -- the recurrent shape output to the next layer.
132 -- the recurrent shape output to the next layer.
140− go (layer :~@> n) (recIn :~@+> nIn) !xs
133+ go (layer :~@> n) (recIn :~@+> nIn) !x
141− = let (recOut, tys) = goR layer recIn xs
134+ = let (tape, shape, forwards) = runRecurrentForwards layer recIn x
142− recurrentTapes = fst <$> tys
143− forwards = snd <$> tys
145 (newFN, ig, answer) = go n nIn forwards
135 (newFN, ig, answer) = go n nIn forwards
146− in (recurrentTapes :\@> newFN, recOut :~@+> ig, answer)
136+ in (tape :\@> newFN, shape :~@+> ig, answer)
148 -- Handle the output layer, bouncing the derivatives back down.
138 -- Handle the output layer, bouncing the derivatives back down.
149 -- We may not have a target for each example, so when we don't use 0 gradient.
139 -- We may not have a target for each example, so when we don't use 0 gradient.
150 go RNil RINil !x
140 go RNil RINil !x
151 = (TRNil, RINil, x)
141 = (TRNil, RINil, x)
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, [])
161−runRecurrentGradient :: forall layers shapes.
143+runRecurrent' :: forall layers shapes.
162− RecurrentNetwork layers shapes
144+ RecurrentNetwork layers shapes
163− -> RecurrentTapes layers shapes
145+ -> RecurrentTape layers shapes
164− -> RecurrentInputs layers
146+ -> RecurrentInputs layers
165− -> [S (Last shapes)]
147+ -> S (Last shapes)
166− -> (RecurrentGradients layers, RecurrentInputs layers, [S (Head shapes)])
148+ -> (RecurrentGradient layers, RecurrentInputs layers, S (Head shapes))
167−runRecurrentGradient net tapes r o =
149+runRecurrent' net tapes r o =
168 go net tapes r
150 go net tapes r
170 -- We have to be careful regarding the direction of the lists
152 -- We have to be careful regarding the direction of the lists
@@ -172,51 +154,41 @@ runRecurrentGradient net tapes r o =
172 -- through time.
154 -- through time.
173 go :: forall js ss. (Last js ~ Last shapes)
155 go :: forall js ss. (Last js ~ Last shapes)
174 => RecurrentNetwork ss js
156 => RecurrentNetwork ss js
175− -> RecurrentTapes ss js
157+ -> RecurrentTape ss js
176 -> RecurrentInputs ss
158 -> RecurrentInputs ss
177− -> (RecurrentGradients ss, RecurrentInputs ss, [S (Head js)])
159+ -> (RecurrentGradient ss, RecurrentInputs ss, S (Head js))
178 -- This is a simple non-recurrent layer
160 -- This is a simple non-recurrent layer
179− -- Run the rest of the network, then fmap the tapes and gradients
161+ -- Run the rest of the network, update with the tapes and gradients
180− go (layer :~~> n) (feedForwardTapes :\~> nTapes) (() :~~+> nRecs) =
162+ go (!layer :~~> n) (!tape :\~> nTapes) (() :~~+> nRecs) =
181− let (gradients, rins, feed) = go n nTapes nRecs
163+ let (!gradients, !rins, !feed) = go n nTapes nRecs
182− backs = uncurry (runBackwards layer) <$> zip (reverse feedForwardTapes) feed
164+ (!grad, !back) = runBackwards layer tape feed
183− in ((fst <$> backs) ://> gradients, () :~~+> rins, snd <$> backs)
165+ in (grad ://> gradients, () :~~+> rins, back)
185 -- This is a recurrent layer
167 -- This is a recurrent layer
186 -- Run the rest of the network, scan over the tapes in reverse
168 -- Run the rest of the network, scan over the tapes in reverse
187− go (layer :~@> n) (recurrentTapes :\@> nTapes) (recGrad :~@+> nRecs) =
169+ go (!layer :~@> n) (!tape :\@> nTapes) (!recGrad :~@+> nRecs) =
188− let (gradients, rins, feed) = go n nTapes nRecs
170+ let (!gradients, !rins, !feed) = go n nTapes nRecs
189− backExamples = zip (reverse recurrentTapes) feed
171+ (!grad, !sidegrad, !back) = runRecurrentBackwards layer tape recGrad feed
190− (rg, backs) = goX layer recGrad backExamples
191− in ((fst <$> backs) ://> gradients, rg :~@+> rins, snd <$> backs)
172+ in (grad ://> gradients, sidegrad :~@+> rins, back)
193 -- End of the road, so we reflect the given gradients backwards.
174 -- End of the road, so we reflect the given gradients backwards.
194 -- Crucially, we reverse the list, so it's backwards in time as
175 -- Crucially, we reverse the list, so it's backwards in time as
196− go RNil TRNil RINil
177+ go !RNil !TRNil !RINil
197− = (RGNil, RINil, reverse o)
178+ = (RGNil, RINil, o)
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, [])
208-- | Apply a batch of gradients to the network
180-- | Apply a batch of gradients to the network
209-- Uses runUpdates which can be specialised for
181-- Uses runUpdates which can be specialised for
210-- a layer.
182-- a layer.
211applyRecurrentUpdate :: LearningParameters
183applyRecurrentUpdate :: LearningParameters
212 -> RecurrentNetwork layers shapes
184 -> RecurrentNetwork layers shapes
213− -> RecurrentGradients layers
185+ -> RecurrentGradient layers
214 -> RecurrentNetwork layers shapes
186 -> RecurrentNetwork layers shapes
215applyRecurrentUpdate rate (layer :~~> rest) (gradient ://> grest)
187applyRecurrentUpdate rate (layer :~~> rest) (gradient ://> grest)
216− = runUpdates rate layer gradient :~~> applyRecurrentUpdate rate rest grest
188+ = runUpdate rate layer gradient :~~> applyRecurrentUpdate rate rest grest
218applyRecurrentUpdate rate (layer :~@> rest) (gradient ://> grest)
190applyRecurrentUpdate rate (layer :~@> rest) (gradient ://> grest)
219− = runUpdates rate layer gradient :~@> applyRecurrentUpdate rate rest grest
191+ = runUpdate rate layer gradient :~@> applyRecurrentUpdate rate rest grest
221applyRecurrentUpdate _ RNil RGNil
193applyRecurrentUpdate _ RNil RGNil
@@ -234,24 +206,23 @@ instance (Show x, Show (RecurrentNetwork xs rs)) => Show (RecurrentNetwork (Recu
234-- recurrent network and a set of random inputs for it is with the randomRecurrent.
206-- recurrent network and a set of random inputs for it is with the randomRecurrent.
235class CreatableRecurrent (xs :: [*]) (ss :: [Shape]) where
207class CreatableRecurrent (xs :: [*]) (ss :: [Shape]) where
236 -- | Create a network of the types requested
208 -- | Create a network of the types requested
237− randomRecurrent :: MonadRandom m => m (RecurrentNetwork xs ss, RecurrentInputs xs)
209+ randomRecurrent :: MonadRandom m => m (RecurrentNetwork xs ss)
239instance SingI i => CreatableRecurrent '[] '[i] where
211instance SingI i => CreatableRecurrent '[] '[i] where
240 randomRecurrent =
212 randomRecurrent =
241− return (RNil, RINil)
213+ return RNil
243instance (SingI i, Layer x i o, CreatableRecurrent xs (o ': rs)) => CreatableRecurrent (FeedForward x ': xs) (i ': o ': rs) where
215instance (SingI i, Layer x i o, CreatableRecurrent xs (o ': rs)) => CreatableRecurrent (FeedForward x ': xs) (i ': o ': rs) where
244 randomRecurrent = do
216 randomRecurrent = do
245 thisLayer <- createRandom
217 thisLayer <- createRandom
246− (rest, resti) <- randomRecurrent
218+ rest <- randomRecurrent
247− return (thisLayer :~~> rest, () :~~+> resti)
219+ return (thisLayer :~~> rest)
249instance (SingI i, RecurrentLayer x i o, CreatableRecurrent xs (o ': rs)) => CreatableRecurrent (Recurrent x ': xs) (i ': o ': rs) where
221instance (SingI i, RecurrentLayer x i o, CreatableRecurrent xs (o ': rs)) => CreatableRecurrent (Recurrent x ': xs) (i ': o ': rs) where
250 randomRecurrent = do
222 randomRecurrent = do
251 thisLayer <- createRandom
223 thisLayer <- createRandom
252− thisShape <- randomOfShape
253− (rest, resti) <- randomRecurrent
224+ rest <- randomRecurrent
254− return (thisLayer :~@> rest, thisShape :~@+> resti)
225+ return (thisLayer :~@> rest)
256-- | Add very simple serialisation to the recurrent network
227-- | Add very simple serialisation to the recurrent network
257instance SingI i => Serialize (RecurrentNetwork '[] '[i]) where
228instance SingI i => Serialize (RecurrentNetwork '[] '[i]) where
@@ -270,23 +241,13 @@ instance (Serialize (RecurrentInputs '[])) where
270 put _ = return ()
241 put _ = return ()
271 get = return RINil
242 get = return RINil
273−instance (UpdateLayer x, Serialize (RecurrentInputs ys)) => (Serialize (RecurrentInputs (FeedForward x ': ys))) where
244+instance (UpdateLayer x, Serialize (RecurrentInputs ys), Fractional (RecurrentInputs ys)) => (Serialize (RecurrentInputs (FeedForward x ': ys))) where
274 put ( () :~~+> rest) = put rest
245 put ( () :~~+> rest) = put rest
275 get = ( () :~~+> ) <$> get
246 get = ( () :~~+> ) <$> get
277−instance (SingI (RecurrentShape x), RecurrentUpdateLayer x, Serialize (RecurrentInputs ys)) => (Serialize (RecurrentInputs (Recurrent x ': ys))) where
248+instance (Serialize (RecurrentShape x), Fractional (RecurrentShape x), RecurrentUpdateLayer x, Serialize (RecurrentInputs ys), Fractional (RecurrentInputs ys)) => (Serialize (RecurrentInputs (Recurrent x ': ys))) where
278− put ( i :~@+> rest ) = do
249+ put ( i :~@+> rest ) = put i >> put rest
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
286− get = do
250+ get = (:~@+>) <$> get <*> get
287− Just i <- fromStorable . V.fromList <$> getListOf get
289− return ( i :~@+> rest)
292-- Num instance for `RecurrentInputs layers`
253-- Num instance for `RecurrentInputs layers`
@@ -307,7 +268,7 @@ instance (Num (RecurrentInputs '[])) where
307 signum _ = RINil
268 signum _ = RINil
308 fromInteger _ = RINil
269 fromInteger _ = RINil
310−instance (UpdateLayer x, Num (RecurrentInputs ys)) => (Num (RecurrentInputs (FeedForward x ': ys))) where
271+instance (UpdateLayer x, Fractional (RecurrentInputs ys)) => (Num (RecurrentInputs (FeedForward x ': ys))) where
311 (+) (() :~~+> x) (() :~~+> y) = () :~~+> (x + y)
272 (+) (() :~~+> x) (() :~~+> y) = () :~~+> (x + y)
312 (-) (() :~~+> x) (() :~~+> y) = () :~~+> (x - y)
273 (-) (() :~~+> x) (() :~~+> y) = () :~~+> (x - y)
313 (*) (() :~~+> x) (() :~~+> y) = () :~~+> (x * y)
274 (*) (() :~~+> x) (() :~~+> y) = () :~~+> (x * y)
@@ -315,10 +276,51 @@ instance (UpdateLayer x, Num (RecurrentInputs ys)) => (Num (RecurrentInputs (Fee
315 signum (() :~~+> x) = () :~~+> signum x
276 signum (() :~~+> x) = () :~~+> signum x
316 fromInteger x = () :~~+> fromInteger x
277 fromInteger x = () :~~+> fromInteger x
318−instance (SingI (RecurrentShape x), RecurrentUpdateLayer x, Num (RecurrentInputs ys)) => (Num (RecurrentInputs (Recurrent x ': ys))) where
279+instance (Fractional (RecurrentShape x), RecurrentUpdateLayer x, Fractional (RecurrentInputs ys)) => (Num (RecurrentInputs (Recurrent x ': ys))) where
319 (+) (x :~@+> x') (y :~@+> y') = (x + y) :~@+> (x' + y')
280 (+) (x :~@+> x') (y :~@+> y') = (x + y) :~@+> (x' + y')
320 (-) (x :~@+> x') (y :~@+> y') = (x - y) :~@+> (x' - y')
281 (-) (x :~@+> x') (y :~@+> y') = (x - y) :~@+> (x' - y')
321 (*) (x :~@+> x') (y :~@+> y') = (x * y) :~@+> (x' * y')
282 (*) (x :~@+> x') (y :~@+> y') = (x * y) :~@+> (x' * y')
322 abs (x :~@+> x') = abs x :~@+> abs x'
283 abs (x :~@+> x') = abs x :~@+> abs x'
323 signum (x :~@+> x') = signum x :~@+> signum x'
284 signum (x :~@+> x') = signum x :~@+> signum x'
324 fromInteger x = fromInteger x :~@+> fromInteger x
285 fromInteger x = fromInteger x :~@+> fromInteger x
287+instance (Fractional (RecurrentInputs '[])) where
290+ fromRational _ = RINil
292+instance (UpdateLayer x, Fractional (RecurrentInputs ys)) => (Fractional (RecurrentInputs (FeedForward x ': ys))) where
293+ (/) (() :~~+> x) (() :~~+> y) = () :~~+> (x / y)
294+ recip (() :~~+> x) = () :~~+> recip x
295+ fromRational x = () :~~+> fromRational x
297+instance (Fractional (RecurrentShape x), RecurrentUpdateLayer x, Fractional (RecurrentInputs ys)) => (Fractional (RecurrentInputs (Recurrent x ': ys))) where
298+ (/) (x :~@+> x') (y :~@+> y') = (x / y) :~@+> (x' / y')
299+ recip (x :~@+> x') = recip x :~@+> recip x'
300+ fromRational x = fromRational x :~@+> fromRational x
303+-- | Ultimate composition.
305+-- This allows a complete network to be treated as a layer in a larger network.
306+instance CreatableRecurrent sublayers subshapes => UpdateLayer (RecurrentNetwork sublayers subshapes) where
307+ type Gradient (RecurrentNetwork sublayers subshapes) = RecurrentGradient sublayers
308+ runUpdate = applyRecurrentUpdate
309+ createRandom = randomRecurrent
311+-- | Ultimate composition.
313+-- This allows a complete network to be treated as a layer in a larger network.
314+instance CreatableRecurrent sublayers subshapes => RecurrentUpdateLayer (RecurrentNetwork sublayers subshapes) where
315+ type RecurrentShape (RecurrentNetwork sublayers subshapes) = RecurrentInputs sublayers
317+-- | Ultimate composition.
319+-- This allows a complete network to be treated as a layer in a larger network.
320+instance ( CreatableRecurrent sublayers subshapes
321+ , i ~ (Head subshapes), o ~ (Last subshapes)
322+ , Num (RecurrentShape (RecurrentNetwork sublayers subshapes))
323+ ) => RecurrentLayer (RecurrentNetwork sublayers subshapes) i o where
324+ type RecTape (RecurrentNetwork sublayers subshapes) i o = RecurrentTape sublayers subshapes
325+ runRecurrentForwards = runRecurrent
326+ runRecurrentBackwards = runRecurrent'