@@ -1,4 +1,5 @@
1{-# LANGUAGE CPP #-}
1{-# LANGUAGE CPP #-}
2+{-# LANGUAGE BangPatterns #-}
2{-# LANGUAGE RankNTypes #-}
3{-# LANGUAGE RankNTypes #-}
3{-# LANGUAGE DataKinds #-}
4{-# LANGUAGE DataKinds #-}
4{-# LANGUAGE ScopedTypeVariables #-}
5{-# LANGUAGE ScopedTypeVariables #-}
@@ -9,6 +10,7 @@
9{-# LANGUAGE FlexibleContexts #-}
10{-# LANGUAGE FlexibleContexts #-}
10module Test.Hedgehog.Network where
11module Test.Hedgehog.Network where
13+import Control.Monad ( guard )
12import Control.Monad.ST ( runST )
14import Control.Monad.ST ( runST )
14import Data.Constraint
16import Data.Constraint
@@ -19,10 +21,11 @@ import qualified Data.Vector.Storable as VS
19import qualified Data.Vector.Storable.Mutable as VS ( write )
21import qualified Data.Vector.Storable.Mutable as VS ( write )
20import Data.Singletons
22import Data.Singletons
21import Data.Singletons.Prelude.List
23import Data.Singletons.Prelude.List
24+import Data.Singletons.TypeLits
22-- import Data.Type.Equality
26-- import Data.Type.Equality
24import Hedgehog
28import Hedgehog
25−import Hedgehog.Gen ( Gen )
26import qualified Hedgehog.Gen as Gen
29import qualified Hedgehog.Gen as Gen
27import Hedgehog.Internal.Source
30import Hedgehog.Internal.Source
28import Hedgehog.Internal.Property ( failWith )
31import Hedgehog.Internal.Property ( failWith )
@@ -37,7 +40,7 @@ import Test.Hedgehog.Hmatrix
37import Test.Grenade.Layers.Convolution
40import Test.Grenade.Layers.Convolution
39import Numeric.LinearAlgebra ( flatten )
42import Numeric.LinearAlgebra ( flatten )
40−import Numeric.LinearAlgebra.Static ( size , extract, norm_Inf )
43+import Numeric.LinearAlgebra.Static ( extract, norm_Inf )
41import Unsafe.Coerce
44import Unsafe.Coerce
43data SomeNetwork :: * where
46data SomeNetwork :: * where
@@ -48,8 +51,9 @@ instance Show SomeNetwork where
49-- | Generate a random network of a random type
52-- | Generate a random network of a random type
51−-- This is slightly insane
54+-- This is slightly insane for a few reasons. Everything must be wrapped up
52−genNetwork :: Monad m => Gen m SomeNetwork
56+genNetwork :: Monad m => Gen.Gen m SomeNetwork
53genNetwork =
57genNetwork =
54 Gen.recursive Gen.choice [
58 Gen.recursive Gen.choice [
55 do SomeSing ( r :: Sing final ) <- genShape
59 do SomeSing ( r :: Sing final ) <- genShape
@@ -59,126 +63,214 @@ genNetwork =
59 do SomeNetwork ( rest :: Network layers shapes ) <- genNetwork
63 do SomeNetwork ( rest :: Network layers shapes ) <- genNetwork
60 case ( sing :: Sing shapes ) of
64 case ( sing :: Sing shapes ) of
61 SNil -> Gen.discard
65 SNil -> Gen.discard
62− SCons ( r :: Sing h ) ( _ :: Sing hs ) ->
66+ SCons ( h :: Sing h ) ( _ :: Sing hs ) ->
63− withSingI r $ Gen.choice [
67+ withSingI h $
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
68+ case h of
67− D1Sing ->
69+ D1Sing l -> withKnownNat l $
68 Gen.choice [
70 Gen.choice [
71+ pure (SomeNetwork (Tanh :~> rest :: Network ( Tanh ': layers ) ( h ': h ': hs )))
72+ , pure (SomeNetwork (Logit :~> rest :: Network ( Logit ': layers ) ( h ': h ': hs )))
69− pure (SomeNetwork (Relu :~> rest :: Network ( Relu ': layers ) ( h ': h ': hs )))
73+ , pure (SomeNetwork (Relu :~> rest :: Network ( Relu ': layers ) ( h ': h ': hs )))
70 , pure (SomeNetwork (Elu :~> rest :: Network ( Elu ': layers ) ( h ': h ': hs )))
74 , pure (SomeNetwork (Elu :~> rest :: Network ( Elu ': layers ) ( h ': h ': hs )))
71 , pure (SomeNetwork (Softmax :~> rest :: Network ( Softmax ': layers ) ( h ': h ': hs )))
75 , pure (SomeNetwork (Softmax :~> rest :: Network ( Softmax ': layers ) ( h ': h ': hs )))
73− D2Sing ->
77+ D2Sing r c -> withKnownNat r $ withKnownNat c $
74 Gen.choice [
78 Gen.choice [
79+ pure (SomeNetwork (Tanh :~> rest :: Network ( Tanh ': layers ) ( h ': h ': hs )))
80+ , pure (SomeNetwork (Logit :~> rest :: Network ( Logit ': layers ) ( h ': h ': hs )))
75− pure (SomeNetwork (Relu :~> rest :: Network ( Relu ': layers ) ( h ': h ': hs )))
81+ , pure (SomeNetwork (Relu :~> rest :: Network ( Relu ': layers ) ( h ': h ': hs )))
76 , pure (SomeNetwork (Elu :~> rest :: Network ( Elu ': layers ) ( h ': h ': hs )))
82 , pure (SomeNetwork (Elu :~> rest :: Network ( Elu ': layers ) ( h ': h ': hs )))
77 , do -- Build a convolution layer with one filter output
83 , do -- Build a convolution layer with one filter output
78 -- Figure out some kernel sizes which work for this layer
84 -- Figure out some kernel sizes which work for this layer
79 -- There must be a better way than this...
85 -- There must be a better way than this...
80− let dumb :: S h = 0
86+ let output_r = natVal r
81− case dumb of
87+ let output_c = natVal c
83− let (rs, cs) = size x
89+ let ok extent kernel = [stride | stride <- [ 1 .. extent ], (extent - kernel) `mod` stride == 0]
91+ -- Get some kernels which will fit
92+ kernel_r <- choose 1 output_r
93+ kernel_c <- choose 1 output_c
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
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
103+ guard (input_r < 100)
104+ guard (input_c < 100)
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
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
129+ let ok extent kernel = [stride | stride <- [ 1 .. extent ], (extent - kernel) `mod` stride == 0]
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
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
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
144+ guard (input_r < 100)
145+ guard (input_c < 100)
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
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
84− let output_r = fromIntegral rs
168+ let output_r = natVal r
85− let output_c = fromIntegral cs
169+ let output_c = natVal c
87− let ok extent kernel = [stride | stride <- [ 1 .. extent ], (extent - kernel) `mod` stride == 0]
171+ let ok extent kernel = [stride | stride <- [ 1 .. extent ], (extent - kernel) `mod` stride == 0]
89− -- Get some kernels which will fit
173+ -- Get some kernels which will fit
90− kernel_r <- choose 1 output_r
174+ kernel_r <- choose 1 output_r
91− kernel_c <- choose 1 output_c
175+ kernel_c <- choose 1 output_c
93− -- Build up some strides which also fit
177+ -- Build up some strides which also fit
94− stride_r <- Gen.element $ ok output_r kernel_r
178+ stride_r <- Gen.element $ ok output_r kernel_r
95− stride_c <- Gen.element $ ok output_c kernel_c
179+ stride_c <- Gen.element $ ok output_c kernel_c
97− -- Determine the input size
181+ -- Determine the input size
98− let input_r = (output_r - 1) * stride_r + kernel_r
182+ let input_r = (output_r - 1) * stride_r + kernel_r
99− let input_c = (output_c - 1) * stride_c + kernel_c
183+ let input_c = (output_c - 1) * stride_c + kernel_c
185+ guard (input_r < 100)
186+ guard (input_c < 100)
101− -- Remake types for input
188+ -- 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
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
103− ( Just (SomeNat (_ :: Proxy inRows)), Just (SomeNat (_ :: Proxy inCols)),
190+ ( Just (SomeNat (_ :: Proxy inRows)), Just (SomeNat (_ :: Proxy inCols)),
104− Just (SomeNat (_ :: Proxy outRows)), Just (SomeNat (_ :: Proxy outCols)),
191+ Just (SomeNat (_ :: Proxy outRows)), Just (SomeNat (_ :: Proxy outCols)),
105− Just (SomeNat (pkr :: Proxy kernelRows)), Just (SomeNat (pkc :: Proxy kernelCols)),
192+ Just (SomeNat (pkr :: Proxy kernelRows)), Just (SomeNat (pkc :: Proxy kernelCols)),
106− Just (SomeNat (_ :: Proxy strideRows)), Just (SomeNat (_ :: Proxy strideCols))) ->
193+ Just (SomeNat (_ :: Proxy strideRows)), Just (SomeNat (_ :: Proxy strideCols))) ->
107− let p1 = natDict pkr
194+ let p1 = natDict pkr
108− p2 = natDict pkc
195+ p2 = natDict pkc
109− in case ( p1 %* p2
196+ in case ( p1 %* p2
110− -- Fake it till you make it.
197+ -- Fake it till you make it.
111− , (unsafeCoerce (Dict :: Dict ()) :: Dict ( ( 'D2 outRows outCols ) ~ h ))
198+ , (unsafeCoerce (Dict :: Dict ()) :: Dict ( ( 'D2 outRows outCols ) ~ h ))
112− , (unsafeCoerce (Dict :: Dict ()) :: Dict (((outRows - 1) * strideRows) ~ (inRows - kernelRows)))
199+ , (unsafeCoerce (Dict :: Dict ()) :: Dict (((outRows - 1) * strideRows) ~ (inRows - kernelRows)))
113− , (unsafeCoerce (Dict :: Dict ()) :: Dict (((outCols - 1) * strideCols) ~ (inCols - kernelCols)))) of
200+ , (unsafeCoerce (Dict :: Dict ()) :: Dict (((outCols - 1) * strideCols) ~ (inCols - kernelCols)))) of
114− (Dict, Dict, Dict, Dict) -> do
201+ (Dict, Dict, Dict, Dict) ->
115− conv <- genConvolution
116− pure (SomeNetwork (conv :~> rest :: Network ( Convolution 1 1 kernelRows kernelCols strideRows strideCols ': layers ) ( ('D2 inRows inCols) ': h ': hs )))
202+ pure (SomeNetwork (Pooling :~> rest :: Network ( Pooling kernelRows kernelCols strideRows strideCols ': layers ) ( ('D2 inRows inCols) ': h ': hs )))
117− _ -> Gen.discard
203+ _ -> Gen.discard -- Can't occur
119− D3Sing ->
205+ D3Sing r c d -> withKnownNat d $ withKnownNat r $ withKnownNat c $
120 Gen.choice [
206 Gen.choice [
207+ pure (SomeNetwork (Tanh :~> rest :: Network ( Tanh ': layers ) ( h ': h ': hs )))
208+ , pure (SomeNetwork (Logit :~> rest :: Network ( Logit ': layers ) ( h ': h ': hs )))
121− pure (SomeNetwork (Relu :~> rest :: Network ( Relu ': layers ) ( h ': h ': hs )))
209+ , pure (SomeNetwork (Relu :~> rest :: Network ( Relu ': layers ) ( h ': h ': hs )))
122 , pure (SomeNetwork (Elu :~> rest :: Network ( Elu ': layers ) ( h ': h ': hs )))
210 , pure (SomeNetwork (Elu :~> rest :: Network ( Elu ': layers ) ( h ': h ': hs )))
127−-- Test a partial derivative numerically for a random network and input
214+-- | Test a partial derivative numerically for a random network and input
216+-- This is the most important test.
128prop_auto_diff :: Property
217prop_auto_diff :: Property
129−prop_auto_diff = property $ do
218+prop_auto_diff = withTests 10000 . property $ do
130 SomeNetwork (network :: Network layers shapes) <- forAll genNetwork
219 SomeNetwork (network :: Network layers shapes) <- forAll genNetwork
131 (input :: S (Head shapes)) <- forAllRender nice genOfShape
220 (input :: S (Head shapes)) <- forAllRender nice genOfShape
132 (target :: S (Last shapes)) <- forAllRender nice oneUp
221 (target :: S (Last shapes)) <- forAllRender nice oneUp
133 (tested :: S (Head shapes)) <- forAllRender nice oneUp
222 (tested :: S (Head shapes)) <- forAllRender nice oneUp
135− let (tapes, output) = runNetwork network input
224+ let (!tapes, !output) = runNetwork network input
136− let (_, bgrad) = runGradient network tapes target
225+ let (_, !backgrad) = runGradient network tapes target
137− let inputDiff = input + tested * 0.00001
226+ let inputDiff = input + tested * 0.00001
138− let expected = maxVal ( bgrad * tested )
227+ let expected = maxVal ( backgrad * tested )
139− let (_, outputDiff) = runNetwork network inputDiff
228+ let (_, !outputDiff) = runNetwork network inputDiff
140− let result = maxVal ( outputDiff * target - output * target ) / 0.00001
229+ let result = maxVal ( outputDiff * target - output * target ) / 0.00001
142 result ~~~ expected
231 result ~~~ expected
146-- Make a shape where all are 0 except for 1 value, which is 1.
235-- 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)
149 case ( sing :: Sing shape ) of
238 case ( sing :: Sing shape ) of
239+ D1Sing l -> withKnownNat l $
150− D1Sing -> let x = 0 :: S ( shape )
240+ let x = 0 :: S ( shape )
151− in case x of
241+ in case x of
152− ( S1D x' ) -> do
242+ ( S1D x' ) -> do
153− let ex = extract x'
243+ let ex = extract x'
154− let len = VS.length ex
244+ let len = VS.length ex
155− ix <- choose 0 (len - 1)
245+ ix <- choose 0 (len - 1)
156− let nx = runST $ do ex' <- VS.thaw ex
246+ let nx = runST $ do ex' <- VS.thaw ex
157− VS.write ex' ix 1.0
247+ VS.write ex' ix 1.0
158− VS.freeze ex'
248+ VS.freeze ex'
159− maybe Gen.discard pure . fromStorable $ nx
249+ maybe Gen.discard pure . fromStorable $ nx
251+ D2Sing r c -> withKnownNat r $ withKnownNat c $
161− D2Sing -> let x = 0 :: S ( shape )
252+ let x = 0 :: S ( shape )
162− in case x of
253+ in case x of
163− ( S2D x' ) -> do
254+ ( S2D x' ) -> do
164− let ex = flatten ( extract x' )
255+ let ex = flatten ( extract x' )
165− let len = VS.length ex
256+ let len = VS.length ex
166− ix <- choose 0 (len - 1)
257+ ix <- choose 0 (len - 1)
167− let nx = runST $ do ex' <- VS.thaw ex
258+ let nx = runST $ do ex' <- VS.thaw ex
168− VS.write ex' ix 1
259+ VS.write ex' ix 1
169− VS.freeze ex'
260+ VS.freeze ex'
170− maybe Gen.discard pure . fromStorable $ nx
261+ maybe Gen.discard pure . fromStorable $ nx
263+ D3Sing r c d -> withKnownNat r $ withKnownNat c $ withKnownNat d $
172− D3Sing -> let x = 0 :: S ( shape )
264+ let x = 0 :: S ( shape )
173− in case x of
265+ in case x of
174− ( S3D x' ) -> do
266+ ( S3D x' ) -> do
175− let ex = flatten ( extract x' )
267+ let ex = flatten ( extract x' )
176− let len = VS.length ex
268+ let len = VS.length ex
177− ix <- choose 0 (len - 1)
269+ ix <- choose 0 (len - 1)
178− let nx = runST $ do ex' <- VS.thaw ex
270+ let nx = runST $ do ex' <- VS.thaw ex
179− VS.write ex' ix 1
271+ VS.write ex' ix 1
180− VS.freeze ex'
272+ VS.freeze ex'
181− maybe Gen.discard pure . fromStorable $ nx
273+ maybe Gen.discard pure . fromStorable $ nx
183maxVal :: S shape -> Double
275maxVal :: S shape -> Double
184maxVal ( S1D x ) = norm_Inf x
276maxVal ( S1D x ) = norm_Inf x
@@ -187,7 +279,7 @@ maxVal ( S3D x ) = norm_Inf x
188(~~~) :: (Monad m, HasCallStack) => Double -> Double -> Test m ()
280(~~~) :: (Monad m, HasCallStack) => Double -> Double -> Test m ()
189(~~~) x y =
281(~~~) x y =
190− if (x - y) < 1e-5 then
282+ if abs (x - y) < 1e-5 then
193 withFrozenCallStack $
285 withFrozenCallStack $