on master help sign in
Change the singleton type for shape.

This allows us to more easily get a handle to the parameters of the shape, while still being pretty easy to cast to a KnownNat. We can now more easily add to the gradients test, and properly check the sizes of the head without silly hacks.

commit8767e836a1cf06c7dcb68473018842f5b417aa1f authorHuw Campbell <huw.campbell@ambiata.com> dateWed 12 Apr 2017, 11:59 (10 years ago) parentf9b5379
11 files changed+261−158
grenade.cabal+3 src/Grenade/Core/Shape.hs+33−15 test/Test/Grenade/Layers/Convolution.hs+1−2 test/Test/Grenade/Layers/Nonlinear.hs−13 test/Test/Grenade/Layers/Pooling.hs+2−2 test/Test/Grenade/Recurrent/Layers/LSTM.hs+2−2 test/Test/Hedgehog/Compat.hs+11−10 test/Test/Hedgehog/Hmatrix.hs+13−10 test/Test/Hedgehog/Network.hs+188−96 test/Test/Hedgehog/TypeLits.hs+5−6 test/test.hs+3−2
grenade.cabal+3
@@ -122,6 +122,9 @@ test-suite test
122122 hs-source-dirs:
123123 test
124124
125+ if impl(ghc < 8.0)
126+ ghc-options: -fno-warn-incomplete-patterns
127+
125128 build-depends:
126129 base >= 4.8 && < 5
127130 , grenade
src/Grenade/Core/Shape.hs+33−15
@@ -81,16 +81,16 @@ deriving instance Show (S n)
8181-- clear and makes adding the KnownNat constraints simple.
8282-- We can also keep our code TH free, which is great.
8383data instance Sing (n :: Shape) where
84− D1Sing :: KnownNat a => Sing ('D1 a)
85− D2Sing :: (KnownNat a, KnownNat b) => Sing ('D2 a b)
86− D3Sing :: (KnownNat a, KnownNat b, KnownNat c, KnownNat (a * c)) => Sing ('D3 a b c)
84+ D1Sing :: Sing a -> Sing ('D1 a)
85+ D2Sing :: Sing a -> Sing b -> Sing ('D2 a b)
86+ D3Sing :: KnownNat (a * c) => Sing a -> Sing b -> Sing c -> Sing ('D3 a b c)
8787
8888instance KnownNat a => SingI ('D1 a) where
89− sing = D1Sing
89+ sing = D1Sing sing
9090instance (KnownNat a, KnownNat b) => SingI ('D2 a b) where
91− sing = D2Sing
91+ sing = D2Sing sing sing
9292instance (KnownNat a, KnownNat b, KnownNat c, KnownNat (a * c)) => SingI ('D3 a b c) where
93− sing = D3Sing
93+ sing = D3Sing sing sing sing
9494
9595instance SingI x => Num (S x) where
9696 (+) = n2 (+)
@@ -139,18 +139,30 @@ randomOfShape :: forall x m. ( MonadRandom m, SingI x ) => m (S x)
139139randomOfShape = do
140140 seed :: Int <- getRandom
141141 return $ case (sing :: Sing x) of
142− D1Sing -> S1D (randomVector seed Uniform * 2 - 1)
143− D2Sing -> S2D (uniformSample seed (-1) 1)
144− D3Sing -> S3D (uniformSample seed (-1) 1)
142+ D1Sing l ->
143+ withKnownNat l $
144+ S1D (randomVector seed Uniform * 2 - 1)
145+ D2Sing r c ->
146+ withKnownNat r $ withKnownNat c $
147+ S2D (uniformSample seed (-1) 1)
148+ D3Sing r c d ->
149+ withKnownNat r $ withKnownNat c $ withKnownNat d $
150+ S3D (uniformSample seed (-1) 1)
145151
146152-- | Generate a shape from a Storable Vector.
147153--
148154-- Returns Nothing if the vector is of the wrong size.
149155fromStorable :: forall x. SingI x => Vector Double -> Maybe (S x)
150156fromStorable xs = case sing :: Sing x of
151− D1Sing -> S1D <$> H.create xs
152− D2Sing -> S2D <$> mkL xs
153− D3Sing -> S3D <$> mkL xs
157+ D1Sing l ->
158+ withKnownNat l $
159+ S1D <$> H.create xs
160+ D2Sing r c ->
161+ withKnownNat r $ withKnownNat c $
162+ S2D <$> mkL xs
163+ D3Sing r c d ->
164+ withKnownNat r $ withKnownNat c $ withKnownNat d $
165+ S3D <$> mkL xs
154166 where
155167 mkL :: forall rows columns. (KnownNat rows, KnownNat columns)
156168 => Vector Double -> Maybe (L rows columns)
@@ -176,6 +188,12 @@ n2 f (S3D x) (S3D y) = S3D (f x y)
176188-- Helper function for creating the number instances
177189nk :: forall x. SingI x => Double -> S x
178190nk x = case (sing :: Sing x) of
179− D1Sing -> S1D (konst x)
180− D2Sing -> S2D (konst x)
181− D3Sing -> S3D (konst x)
191+ D1Sing l ->
192+ withKnownNat l $
193+ S1D (konst x)
194+ D2Sing r c ->
195+ withKnownNat r $ withKnownNat c $
196+ S2D (konst x)
197+ D3Sing r c d ->
198+ withKnownNat r $ withKnownNat c $ withKnownNat d $
199+ S3D (konst x)
test/Test/Grenade/Layers/Convolution.hs+1−2
@@ -19,7 +19,6 @@ import Grenade.Core
1919import Grenade.Layers.Convolution
2020
2121import Hedgehog
22−import Hedgehog.Gen ( Gen )
2322import qualified Hedgehog.Gen as Gen
2423
2524import Test.Hedgehog.Hmatrix
@@ -41,7 +40,7 @@ genConvolution :: ( KnownNat channels
4140 , KnownNat kernelFlattened
4241 , kernelFlattened ~ (kernelRows * kernelColumns * channels)
4342 , Monad m
44− ) => Gen m (Convolution channels filters kernelRows kernelColumns strideRows strideColumns)
43+ ) => Gen.Gen m (Convolution channels filters kernelRows kernelColumns strideRows strideColumns)
4544genConvolution = Convolution <$> uniformSample <*> uniformSample
4645
4746genOpaqueOpaqueConvolution :: Monad m => Gen m OpaqueConvolution
test/Test/Grenade/Layers/Nonlinear.hs−13
@@ -16,7 +16,6 @@ import Data.Proxy
1616#endif
1717
1818import Grenade
19−import GHC.TypeLits
2019
2120import Hedgehog
2221
@@ -56,18 +55,6 @@ prop_tanh_grad = property $
5655 (S2D x) -> norm_Inf x < 0.001
5756 (S3D x) -> norm_Inf x < 0.001) :: Bool)
5857
59−prop_softmax_grad :: Property
60−prop_softmax_grad = property $
61− blindForAll genNat >>= \case
62− (SomeNat (_ :: Proxy s)) ->
63− blindForAll genOfShape >>= \(ds :: S ('D1 s)) ->
64− let (tape, f :: S ('D1 s)) = runForwards Relu ds
65− ((), ret :: S ('D1 s)) = runBackwards Relu tape (1 :: S ('D1 s))
66− (_, numer :: S ('D1 s)) = runForwards Relu (ds + 0.0001)
67− numericalGradient = (numer - f) * 10000
68− in assert ((case numericalGradient - ret of
69− (S1D x) -> norm_Inf x < 0.0001) :: Bool)
70−
7158tests :: IO Bool
7259tests = $$(checkConcurrent)
7360
test/Test/Grenade/Layers/Pooling.hs+2−2
@@ -13,7 +13,7 @@ import GHC.TypeLits
1313import Grenade.Layers.Pooling
1414
1515import Hedgehog
16−import Hedgehog.Gen ( Gen )
16+import qualified Hedgehog.Gen as Gen
1717
1818import Test.Hedgehog.Compat
1919
@@ -23,7 +23,7 @@ data OpaquePooling :: * where
2323instance Show OpaquePooling where
2424 show (OpaquePooling n) = show n
2525
26−genOpaquePooling :: Monad m => Gen m OpaquePooling
26+genOpaquePooling :: Monad m => Gen.Gen m OpaquePooling
2727genOpaquePooling = do
2828 Just kernelHeight <- someNatVal <$> choose 2 15
2929 Just kernelWidth <- someNatVal <$> choose 2 15
test/Test/Grenade/Recurrent/Layers/LSTM.hs+2−2
@@ -11,7 +11,7 @@
1111module Test.Grenade.Recurrent.Layers.LSTM where
1212
1313import Hedgehog
14−import Hedgehog.Gen ( Gen )
14+import qualified Hedgehog.Gen as Gen
1515import Hedgehog.Internal.Source
1616import Hedgehog.Internal.Show
1717import Hedgehog.Internal.Property ( failWith, Diff (..) )
@@ -29,7 +29,7 @@ import qualified Numeric.LinearAlgebra.Static as S
2929import qualified Test.Grenade.Recurrent.Layers.LSTM.Reference as Reference
3030import Test.Hedgehog.Hmatrix
3131
32−genLSTM :: forall i o m. (KnownNat i, KnownNat o, Monad m) => Gen m (LSTM i o)
32+genLSTM :: forall i o m. (KnownNat i, KnownNat o, Monad m) => Gen.Gen m (LSTM i o)
3333genLSTM = do
3434 let w = uniformSample
3535 u = uniformSample
test/Test/Hedgehog/Compat.hs+11−10
@@ -1,11 +1,16 @@
11{-# LANGUAGE RankNTypes #-}
2−module Test.Hedgehog.Compat where
2+module Test.Hedgehog.Compat (
3+ (...)
4+ , choose
5+ , blindForAll
6+ , semiBlindForAll
7+ , forAllRender
8+ )where
39
410import Control.Monad.Trans.Class (MonadTrans(..))
511
612import Data.Typeable ( typeOf )
713
8−import Hedgehog.Gen ( Gen )
914import qualified Hedgehog.Gen as Gen
1015import qualified Hedgehog.Range as Range
1116import Hedgehog.Internal.Property
@@ -16,23 +21,19 @@ import Hedgehog.Internal.Show
1621(...) = (.) . (.)
1722{-# INLINE (...) #-}
1823
19−choose :: ( Monad m, Integral a ) => a -> a -> Gen m a
24+choose :: ( Monad m, Integral a ) => a -> a -> Gen.Gen m a
2025choose = Gen.integral ... Range.constant
2126
22−-- | Generates a random input for the test by running the provided generator.
23−blindForAll :: Monad m => Gen m a -> Test m a
27+blindForAll :: Monad m => Gen.Gen m a -> Test m a
2428blindForAll = Test . lift . lift
2529
26−-- | Generates a random input for the test by running the provided generator.
27−semiBlindForAll :: (Monad m, Show a, HasCallStack) => Gen m a -> Test m a
30+semiBlindForAll :: (Monad m, Show a, HasCallStack) => Gen.Gen m a -> Test m a
2831semiBlindForAll gen = do
2932 x <- Test . lift $ lift gen
3033 writeLog $ Input (getCaller callStack) (typeOf ()) (showPretty x)
3134 return x
3235
33−
34−-- | Generates a random input for the test by running the provided generator.
35−forAllRender :: (Monad m, HasCallStack) => ( a -> String ) -> Gen m a -> Test m a
36+forAllRender :: (Monad m, HasCallStack) => ( a -> String ) -> Gen.Gen m a -> Test m a
3637forAllRender render gen = do
3738 x <- Test . lift $ lift gen
3839 writeLog $ Input (getCaller callStack) (typeOf ()) (render x)
test/Test/Hedgehog/Hmatrix.hs+13−10
@@ -7,29 +7,32 @@ module Test.Hedgehog.Hmatrix where
77
88import Grenade
99import Data.Singletons
10+import Data.Singletons.TypeLits
1011
11−import Hedgehog.Gen ( Gen )
1212import qualified Hedgehog.Gen as Gen
1313import qualified Hedgehog.Range as Range
1414
15−import GHC.TypeLits
16−
1715import qualified Numeric.LinearAlgebra.Static as HStatic
1816
19−randomVector :: forall m n. ( Monad m, KnownNat n ) => Gen m (HStatic.R n)
17+randomVector :: forall m n. ( Monad m, KnownNat n ) => Gen.Gen m (HStatic.R n)
2018randomVector = (\s -> HStatic.randomVector s HStatic.Uniform * 2 - 1) <$> Gen.int Range.linearBounded
2119
22−uniformSample :: forall mm m n. ( Monad mm, KnownNat m, KnownNat n ) => Gen mm (HStatic.L m n)
20+uniformSample :: forall mm m n. ( Monad mm, KnownNat m, KnownNat n ) => Gen.Gen mm (HStatic.L m n)
2321uniformSample = (\s -> HStatic.uniformSample s (-1) 1 ) <$> Gen.int Range.linearBounded
2422
2523-- | Generate random data of the desired shape
26−genOfShape :: forall m x. ( Monad m, SingI x ) => Gen m (S x)
24+genOfShape :: forall m x. ( Monad m, SingI x ) => Gen.Gen m (S x)
2725genOfShape =
2826 case (sing :: Sing x) of
29− D1Sing -> S1D <$> randomVector
30− D2Sing -> S2D <$> uniformSample
31− D3Sing -> S3D <$> uniformSample
32−
27+ D1Sing l ->
28+ withKnownNat l $
29+ S1D <$> randomVector
30+ D2Sing r c ->
31+ withKnownNat r $ withKnownNat c $
32+ S2D <$> uniformSample
33+ D3Sing r c d ->
34+ withKnownNat r $ withKnownNat c $ withKnownNat d $
35+ S3D <$> uniformSample
3336
3437nice :: S shape -> String
3538nice (S1D x) = show . HStatic.extract $ x
test/Test/Hedgehog/Network.hs+188−96
@@ -1,4 +1,5 @@
11{-# LANGUAGE CPP #-}
2+{-# LANGUAGE BangPatterns #-}
23{-# LANGUAGE RankNTypes #-}
34{-# LANGUAGE DataKinds #-}
45{-# LANGUAGE ScopedTypeVariables #-}
@@ -9,6 +10,7 @@
910{-# LANGUAGE FlexibleContexts #-}
1011module Test.Hedgehog.Network where
1112
13+import Control.Monad ( guard )
1214import Control.Monad.ST ( runST )
1315
1416import Data.Constraint
@@ -19,10 +21,11 @@ import qualified Data.Vector.Storable as VS
1921import qualified Data.Vector.Storable.Mutable as VS ( write )
2022import Data.Singletons
2123import Data.Singletons.Prelude.List
24+import Data.Singletons.TypeLits
25+
2226-- import Data.Type.Equality
2327
2428import Hedgehog
25−import Hedgehog.Gen ( Gen )
2629import qualified Hedgehog.Gen as Gen
2730import Hedgehog.Internal.Source
2831import Hedgehog.Internal.Property ( failWith )
@@ -37,7 +40,7 @@ import Test.Hedgehog.Hmatrix
3740import Test.Grenade.Layers.Convolution
3841
3942import Numeric.LinearAlgebra ( flatten )
40−import Numeric.LinearAlgebra.Static ( size , extract, norm_Inf )
43+import Numeric.LinearAlgebra.Static ( extract, norm_Inf )
4144import Unsafe.Coerce
4245
4346data SomeNetwork :: * where
@@ -48,8 +51,9 @@ instance Show SomeNetwork where
4851
4952-- | Generate a random network of a random type
5053--
51−-- This is slightly insane
52−genNetwork :: Monad m => Gen m SomeNetwork
54+-- This is slightly insane for a few reasons. Everything must be wrapped up
55+-- in a SomeNetwork.
56+genNetwork :: Monad m => Gen.Gen m SomeNetwork
5357genNetwork =
5458 Gen.recursive Gen.choice [
5559 do SomeSing ( r :: Sing final ) <- genShape
@@ -59,126 +63,214 @@ genNetwork =
5963 do SomeNetwork ( rest :: Network layers shapes ) <- genNetwork
6064 case ( sing :: Sing shapes ) of
6165 SNil -> Gen.discard
62− SCons ( r :: Sing h ) ( _ :: Sing hs ) ->
63− withSingI r $ Gen.choice [
64− pure (SomeNetwork (Logit :~> rest :: Network ( Logit ': layers ) ( h ': h ': hs )))
65− , pure (SomeNetwork (Tanh :~> rest :: Network ( Tanh ': layers ) ( h ': h ': hs )))
66− , case r of
67− D1Sing ->
66+ SCons ( h :: Sing h ) ( _ :: Sing hs ) ->
67+ withSingI h $
68+ case h of
69+ D1Sing l -> withKnownNat l $
6870 Gen.choice [
69− pure (SomeNetwork (Relu :~> rest :: Network ( Relu ': layers ) ( h ': h ': hs )))
71+ pure (SomeNetwork (Tanh :~> rest :: Network ( Tanh ': layers ) ( h ': h ': hs )))
72+ , pure (SomeNetwork (Logit :~> rest :: Network ( Logit ': layers ) ( h ': h ': hs )))
73+ , pure (SomeNetwork (Relu :~> rest :: Network ( Relu ': layers ) ( h ': h ': hs )))
7074 , pure (SomeNetwork (Elu :~> rest :: Network ( Elu ': layers ) ( h ': h ': hs )))
7175 , pure (SomeNetwork (Softmax :~> rest :: Network ( Softmax ': layers ) ( h ': h ': hs )))
7276 ]
73− D2Sing ->
77+ D2Sing r c -> withKnownNat r $ withKnownNat c $
7478 Gen.choice [
75− pure (SomeNetwork (Relu :~> rest :: Network ( Relu ': layers ) ( h ': h ': hs )))
79+ pure (SomeNetwork (Tanh :~> rest :: Network ( Tanh ': layers ) ( h ': h ': hs )))
80+ , pure (SomeNetwork (Logit :~> rest :: Network ( Logit ': layers ) ( h ': h ': hs )))
81+ , pure (SomeNetwork (Relu :~> rest :: Network ( Relu ': layers ) ( h ': h ': hs )))
7682 , pure (SomeNetwork (Elu :~> rest :: Network ( Elu ': layers ) ( h ': h ': hs )))
7783 , do -- Build a convolution layer with one filter output
7884 -- Figure out some kernel sizes which work for this layer
7985 -- There must be a better way than this...
80− let dumb :: S h = 0
81− case dumb of
82− S2D x -> do
83− let (rs, cs) = size x
84− let output_r = fromIntegral rs
85− let output_c = fromIntegral cs
86−
87− let ok extent kernel = [stride | stride <- [ 1 .. extent ], (extent - kernel) `mod` stride == 0]
88−
89− -- Get some kernels which will fit
90− kernel_r <- choose 1 output_r
91− kernel_c <- choose 1 output_c
92−
93− -- Build up some strides which also fit
94− stride_r <- Gen.element $ ok output_r kernel_r
95− stride_c <- Gen.element $ ok output_c kernel_c
96−
97− -- Determine the input size
98− let input_r = (output_r - 1) * stride_r + kernel_r
99− let input_c = (output_c - 1) * stride_c + kernel_c
100−
101− -- Remake types for input
102− case ( someNatVal input_r, someNatVal input_c, someNatVal output_r, someNatVal output_c, someNatVal kernel_r, someNatVal kernel_c, someNatVal stride_r, someNatVal stride_c ) of
103− ( Just (SomeNat (_ :: Proxy inRows)), Just (SomeNat (_ :: Proxy inCols)),
104− Just (SomeNat (_ :: Proxy outRows)), Just (SomeNat (_ :: Proxy outCols)),
105− Just (SomeNat (pkr :: Proxy kernelRows)), Just (SomeNat (pkc :: Proxy kernelCols)),
106− Just (SomeNat (_ :: Proxy strideRows)), Just (SomeNat (_ :: Proxy strideCols))) ->
107− let p1 = natDict pkr
108− p2 = natDict pkc
109− in case ( p1 %* p2
110− -- Fake it till you make it.
111− , (unsafeCoerce (Dict :: Dict ()) :: Dict ( ( 'D2 outRows outCols ) ~ h ))
112− , (unsafeCoerce (Dict :: Dict ()) :: Dict (((outRows - 1) * strideRows) ~ (inRows - kernelRows)))
113− , (unsafeCoerce (Dict :: Dict ()) :: Dict (((outCols - 1) * strideCols) ~ (inCols - kernelCols)))) of
114− (Dict, Dict, Dict, Dict) -> do
115− conv <- genConvolution
116− pure (SomeNetwork (conv :~> rest :: Network ( Convolution 1 1 kernelRows kernelCols strideRows strideCols ': layers ) ( ('D2 inRows inCols) ': h ': hs )))
117− _ -> Gen.discard
86+ let output_r = natVal r
87+ let output_c = natVal c
88+
89+ let ok extent kernel = [stride | stride <- [ 1 .. extent ], (extent - kernel) `mod` stride == 0]
90+
91+ -- Get some kernels which will fit
92+ kernel_r <- choose 1 output_r
93+ kernel_c <- choose 1 output_c
94+
95+ -- Build up some strides which also fit
96+ stride_r <- Gen.element $ ok output_r kernel_r
97+ stride_c <- Gen.element $ ok output_c kernel_c
98+
99+ -- Determine the input size
100+ let input_r = (output_r - 1) * stride_r + kernel_r
101+ let input_c = (output_c - 1) * stride_c + kernel_c
102+
103+ guard (input_r < 100)
104+ guard (input_c < 100)
105+
106+ -- Remake types for input
107+ case ( someNatVal input_r, someNatVal input_c, someNatVal output_r, someNatVal output_c, someNatVal kernel_r, someNatVal kernel_c, someNatVal stride_r, someNatVal stride_c ) of
108+ ( Just (SomeNat (_ :: Proxy inRows)), Just (SomeNat (_ :: Proxy inCols)),
109+ Just (SomeNat (_ :: Proxy outRows)), Just (SomeNat (_ :: Proxy outCols)),
110+ Just (SomeNat (pkr :: Proxy kernelRows)), Just (SomeNat (pkc :: Proxy kernelCols)),
111+ Just (SomeNat (_ :: Proxy strideRows)), Just (SomeNat (_ :: Proxy strideCols))) ->
112+ let p1 = natDict pkr
113+ p2 = natDict pkc
114+ in case ( p1 %* p2
115+ -- Fake it till you make it.
116+ , (unsafeCoerce (Dict :: Dict ()) :: Dict ( ( 'D2 outRows outCols ) ~ h ))
117+ , (unsafeCoerce (Dict :: Dict ()) :: Dict (((outRows - 1) * strideRows) ~ (inRows - kernelRows)))
118+ , (unsafeCoerce (Dict :: Dict ()) :: Dict (((outCols - 1) * strideCols) ~ (inCols - kernelCols)))) of
119+ (Dict, Dict, Dict, Dict) -> do
120+ conv <- genConvolution
121+ pure (SomeNetwork (conv :~> rest :: Network ( Convolution 1 1 kernelRows kernelCols strideRows strideCols ': layers ) ( ('D2 inRows inCols) ': h ': hs )))
122+ _ -> Gen.discard -- Can't occur
123+ , do -- Build a convolution layer with one filter output
124+ -- Figure out some kernel sizes which work for this layer
125+ -- There must be a better way than this...
126+ let output_r = natVal r
127+ let output_c = natVal c
128+
129+ let ok extent kernel = [stride | stride <- [ 1 .. extent ], (extent - kernel) `mod` stride == 0]
130+
131+ -- Get some kernels which will fit
132+ kernel_r <- choose 1 output_r
133+ kernel_c <- choose 1 output_c
134+ channels <- choose 1 10
135+
136+ -- Build up some strides which also fit
137+ stride_r <- Gen.element $ ok output_r kernel_r
138+ stride_c <- Gen.element $ ok output_c kernel_c
139+
140+ -- Determine the input size
141+ let input_r = (output_r - 1) * stride_r + kernel_r
142+ let input_c = (output_c - 1) * stride_c + kernel_c
143+
144+ guard (input_r < 100)
145+ guard (input_c < 100)
146+
147+ -- Remake types for input
148+ case ( someNatVal channels, someNatVal input_r, someNatVal input_c, someNatVal output_r, someNatVal output_c, someNatVal kernel_r, someNatVal kernel_c, someNatVal stride_r, someNatVal stride_c ) of
149+ ( Just (SomeNat (chan :: Proxy channels)),
150+ Just (SomeNat (pinr :: Proxy inRows)), Just (SomeNat (_ :: Proxy inCols)),
151+ Just (SomeNat (_ :: Proxy outRows)), Just (SomeNat (_ :: Proxy outCols)),
152+ Just (SomeNat (pkr :: Proxy kernelRows)), Just (SomeNat (pkc :: Proxy kernelCols)),
153+ Just (SomeNat (_ :: Proxy strideRows)), Just (SomeNat (_ :: Proxy strideCols))) ->
154+ let p1 = natDict pkr
155+ p2 = natDict pkc
156+ p3 = natDict chan
157+ in case ( p1 %* p2 %* p3
158+ , natDict pinr %* natDict chan
159+ -- Fake it till you make it.
160+ , (unsafeCoerce (Dict :: Dict ()) :: Dict ( ( 'D2 outRows outCols ) ~ h ))
161+ , (unsafeCoerce (Dict :: Dict ()) :: Dict (((outRows - 1) * strideRows) ~ (inRows - kernelRows)))
162+ , (unsafeCoerce (Dict :: Dict ()) :: Dict (((outCols - 1) * strideCols) ~ (inCols - kernelCols)))) of
163+ (Dict, Dict, Dict, Dict, Dict) -> do
164+ conv <- genConvolution
165+ pure (SomeNetwork (conv :~> rest :: Network ( Convolution channels 1 kernelRows kernelCols strideRows strideCols ': layers ) ( ('D3 inRows inCols channels) ': h ': hs )))
166+ _ -> Gen.discard -- Can't occur
167+ , do -- Build a Pooling layer
168+ let output_r = natVal r
169+ let output_c = natVal c
170+
171+ let ok extent kernel = [stride | stride <- [ 1 .. extent ], (extent - kernel) `mod` stride == 0]
172+
173+ -- Get some kernels which will fit
174+ kernel_r <- choose 1 output_r
175+ kernel_c <- choose 1 output_c
176+
177+ -- Build up some strides which also fit
178+ stride_r <- Gen.element $ ok output_r kernel_r
179+ stride_c <- Gen.element $ ok output_c kernel_c
180+
181+ -- Determine the input size
182+ let input_r = (output_r - 1) * stride_r + kernel_r
183+ let input_c = (output_c - 1) * stride_c + kernel_c
184+
185+ guard (input_r < 100)
186+ guard (input_c < 100)
187+
188+ -- Remake types for input
189+ case ( someNatVal input_r, someNatVal input_c, someNatVal output_r, someNatVal output_c, someNatVal kernel_r, someNatVal kernel_c, someNatVal stride_r, someNatVal stride_c ) of
190+ ( Just (SomeNat (_ :: Proxy inRows)), Just (SomeNat (_ :: Proxy inCols)),
191+ Just (SomeNat (_ :: Proxy outRows)), Just (SomeNat (_ :: Proxy outCols)),
192+ Just (SomeNat (pkr :: Proxy kernelRows)), Just (SomeNat (pkc :: Proxy kernelCols)),
193+ Just (SomeNat (_ :: Proxy strideRows)), Just (SomeNat (_ :: Proxy strideCols))) ->
194+ let p1 = natDict pkr
195+ p2 = natDict pkc
196+ in case ( p1 %* p2
197+ -- Fake it till you make it.
198+ , (unsafeCoerce (Dict :: Dict ()) :: Dict ( ( 'D2 outRows outCols ) ~ h ))
199+ , (unsafeCoerce (Dict :: Dict ()) :: Dict (((outRows - 1) * strideRows) ~ (inRows - kernelRows)))
200+ , (unsafeCoerce (Dict :: Dict ()) :: Dict (((outCols - 1) * strideCols) ~ (inCols - kernelCols)))) of
201+ (Dict, Dict, Dict, Dict) ->
202+ pure (SomeNetwork (Pooling :~> rest :: Network ( Pooling kernelRows kernelCols strideRows strideCols ': layers ) ( ('D2 inRows inCols) ': h ': hs )))
203+ _ -> Gen.discard -- Can't occur
118204 ]
119− D3Sing ->
205+ D3Sing r c d -> withKnownNat d $ withKnownNat r $ withKnownNat c $
120206 Gen.choice [
121− pure (SomeNetwork (Relu :~> rest :: Network ( Relu ': layers ) ( h ': h ': hs )))
207+ pure (SomeNetwork (Tanh :~> rest :: Network ( Tanh ': layers ) ( h ': h ': hs )))
208+ , pure (SomeNetwork (Logit :~> rest :: Network ( Logit ': layers ) ( h ': h ': hs )))
209+ , pure (SomeNetwork (Relu :~> rest :: Network ( Relu ': layers ) ( h ': h ': hs )))
122210 , pure (SomeNetwork (Elu :~> rest :: Network ( Elu ': layers ) ( h ': h ': hs )))
123211 ]
124− ]
125212 ]
126213
127−-- Test a partial derivative numerically for a random network and input
214+-- | Test a partial derivative numerically for a random network and input
215+--
216+-- This is the most important test.
128217prop_auto_diff :: Property
129−prop_auto_diff = property $ do
218+prop_auto_diff = withTests 10000 . property $ do
130219 SomeNetwork (network :: Network layers shapes) <- forAll genNetwork
131220 (input :: S (Head shapes)) <- forAllRender nice genOfShape
132221 (target :: S (Last shapes)) <- forAllRender nice oneUp
133222 (tested :: S (Head shapes)) <- forAllRender nice oneUp
134223
135− let (tapes, output) = runNetwork network input
136− let (_, bgrad) = runGradient network tapes target
137− let inputDiff = input + tested * 0.00001
138− let expected = maxVal ( bgrad * tested )
139− let (_, outputDiff) = runNetwork network inputDiff
140− let result = maxVal ( outputDiff * target - output * target ) / 0.00001
224+ let (!tapes, !output) = runNetwork network input
225+ let (_, !backgrad) = runGradient network tapes target
226+ let inputDiff = input + tested * 0.00001
227+ let expected = maxVal ( backgrad * tested )
228+ let (_, !outputDiff) = runNetwork network inputDiff
229+ let result = maxVal ( outputDiff * target - output * target ) / 0.00001
141230
142231 result ~~~ expected
143232
144233 where
145234
146235-- Make a shape where all are 0 except for 1 value, which is 1.
147−oneUp :: forall shape m. ( Monad m, SingI shape ) => Gen m (S shape)
236+oneUp :: forall shape m. ( Monad m, SingI shape ) => Gen.Gen m (S shape)
148237oneUp =
149238 case ( sing :: Sing shape ) of
150− D1Sing -> let x = 0 :: S ( shape )
151− in case x of
152− ( S1D x' ) -> do
153− let ex = extract x'
154− let len = VS.length ex
155− ix <- choose 0 (len - 1)
156− let nx = runST $ do ex' <- VS.thaw ex
157− VS.write ex' ix 1.0
158− VS.freeze ex'
159− maybe Gen.discard pure . fromStorable $ nx
160−
161− D2Sing -> let x = 0 :: S ( shape )
162− in case x of
163− ( S2D x' ) -> do
164− let ex = flatten ( extract x' )
165− let len = VS.length ex
166− ix <- choose 0 (len - 1)
167− let nx = runST $ do ex' <- VS.thaw ex
168− VS.write ex' ix 1
169− VS.freeze ex'
170− maybe Gen.discard pure . fromStorable $ nx
171−
172− D3Sing -> let x = 0 :: S ( shape )
173− in case x of
174− ( S3D x' ) -> do
175− let ex = flatten ( extract x' )
176− let len = VS.length ex
177− ix <- choose 0 (len - 1)
178− let nx = runST $ do ex' <- VS.thaw ex
179− VS.write ex' ix 1
180− VS.freeze ex'
181− maybe Gen.discard pure . fromStorable $ nx
239+ D1Sing l -> withKnownNat l $
240+ let x = 0 :: S ( shape )
241+ in case x of
242+ ( S1D x' ) -> do
243+ let ex = extract x'
244+ let len = VS.length ex
245+ ix <- choose 0 (len - 1)
246+ let nx = runST $ do ex' <- VS.thaw ex
247+ VS.write ex' ix 1.0
248+ VS.freeze ex'
249+ maybe Gen.discard pure . fromStorable $ nx
250+
251+ D2Sing r c -> withKnownNat r $ withKnownNat c $
252+ let x = 0 :: S ( shape )
253+ in case x of
254+ ( S2D x' ) -> do
255+ let ex = flatten ( extract x' )
256+ let len = VS.length ex
257+ ix <- choose 0 (len - 1)
258+ let nx = runST $ do ex' <- VS.thaw ex
259+ VS.write ex' ix 1
260+ VS.freeze ex'
261+ maybe Gen.discard pure . fromStorable $ nx
262+
263+ D3Sing r c d -> withKnownNat r $ withKnownNat c $ withKnownNat d $
264+ let x = 0 :: S ( shape )
265+ in case x of
266+ ( S3D x' ) -> do
267+ let ex = flatten ( extract x' )
268+ let len = VS.length ex
269+ ix <- choose 0 (len - 1)
270+ let nx = runST $ do ex' <- VS.thaw ex
271+ VS.write ex' ix 1
272+ VS.freeze ex'
273+ maybe Gen.discard pure . fromStorable $ nx
182274
183275maxVal :: S shape -> Double
184276maxVal ( S1D x ) = norm_Inf x
@@ -187,7 +279,7 @@ maxVal ( S3D x ) = norm_Inf x
187279
188280(~~~) :: (Monad m, HasCallStack) => Double -> Double -> Test m ()
189281(~~~) x y =
190− if (x - y) < 1e-5 then
282+ if abs (x - y) < 1e-5 then
191283 success
192284 else
193285 withFrozenCallStack $
test/Test/Hedgehog/TypeLits.hs+5−6
@@ -13,7 +13,6 @@ import Data.Proxy
1313#endif
1414import Data.Singletons
1515
16−import Hedgehog.Gen ( Gen )
1716import qualified Hedgehog.Gen as Gen
1817
1918import Grenade
@@ -22,7 +21,7 @@ import GHC.TypeLits
2221import GHC.TypeLits.Witnesses
2322import Test.Hedgehog.Compat
2423
25−genNat :: Monad m => Gen m SomeNat
24+genNat :: Monad m => Gen.Gen m SomeNat
2625genNat = do
2726 Just n <- someNatVal <$> choose 1 10
2827 return n
@@ -33,7 +32,7 @@ type Shape' = ('KProxy :: KProxy Shape)
3332type Shape' = Shape
3433#endif
3534
36−genShape :: Monad m => Gen m (SomeSing Shape')
35+genShape :: Monad m => Gen.Gen m (SomeSing Shape')
3736genShape
3837 = Gen.choice [
3938 genD1
@@ -41,20 +40,20 @@ genShape
4140 , genD3
4241 ]
4342
44−genD1 :: Monad m => Gen m (SomeSing Shape')
43+genD1 :: Monad m => Gen.Gen m (SomeSing Shape')
4544genD1 = do
4645 n <- genNat
4746 return $ case n of
4847 SomeNat (_ :: Proxy x) -> SomeSing (sing :: Sing ('D1 x))
4948
50−genD2 :: Monad m => Gen m (SomeSing Shape')
49+genD2 :: Monad m => Gen.Gen m (SomeSing Shape')
5150genD2 = do
5251 n <- genNat
5352 m <- genNat
5453 return $ case (n, m) of
5554 (SomeNat (_ :: Proxy x), SomeNat (_ :: Proxy y)) -> SomeSing (sing :: Sing ('D2 x y))
5655
57−genD3 :: Monad m => Gen m (SomeSing Shape')
56+genD3 :: Monad m => Gen.Gen m (SomeSing Shape')
5857genD3 = do
5958 n <- genNat
6059 m <- genNat
test/test.hs+3−2
@@ -18,7 +18,9 @@ import System.IO
1818main :: IO ()
1919main =
2020 disorderMain [
21− Test.Grenade.Layers.Pooling.tests
21+ Test.Hedgehog.Network.tests
22+
23+ , Test.Grenade.Layers.Pooling.tests
2224 , Test.Grenade.Layers.Convolution.tests
2325 , Test.Grenade.Layers.FullyConnected.tests
2426 , Test.Grenade.Layers.Nonlinear.tests
@@ -29,7 +31,6 @@ main =
2931
3032 , Test.Grenade.Recurrent.Layers.LSTM.tests
3133
32− , Test.Hedgehog.Network.tests
3334 ]
3435
3536disorderMain :: [IO Bool] -> IO ()