core.h 98.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
// Copyright (C) 2015  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.
#ifndef DLIB_DNn_CORE_H_
#define DLIB_DNn_CORE_H_

#include "core_abstract.h"
#include "tensor.h"
#include <iterator>
#include <memory>
10
#include <sstream>
11
#include <type_traits>
Davis King's avatar
Davis King committed
12
13
#include "../statistics.h"
#include "../rand.h"
14
#include "../algs.h"
15
#include <utility>
16
#include <tuple>
Davis King's avatar
Davis King committed
17
#include <cmath>
18
#include <vector>
19
20
#include "tensor_tools.h"

21
22
23
24
25


namespace dlib
{

Davis King's avatar
Davis King committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// ----------------------------------------------------------------------------------------

    inline double log1pexp(double x)
    {
        using std::exp;
        using namespace std; // Do this instead of using std::log1p because some compilers
                             // error out otherwise (E.g. gcc 4.9 in cygwin)
        if (x <= -37)
            return exp(x);
        else if (-37 < x && x <= 18)
            return log1p(exp(x));
        else if (18 < x && x <= 33.3)
            return x + exp(-x);
        else
            return x;
    }
    
43
44
// ----------------------------------------------------------------------------------------

Davis King's avatar
Davis King committed
45
    // Tell us if T is one of the special layer types (i.e. add_layer, repeat, add_tag_layer, or
Davis King's avatar
Davis King committed
46
47
48
    // add_skip_layer).
    template <typename T> struct is_nonloss_layer_type : std::false_type {};
    // Tell us if T is an instance of add_loss_layer.
49
50
    template <typename T> struct is_loss_layer_type : std::false_type {};

51
52
53
54
55
56
57
58
59
60
61
62
63
64
    namespace impl
    {
        template <size_t... n>
        struct ct_integers_list {
            template <size_t m>
            struct push_back
            {
                typedef ct_integers_list<n..., m> type;
            };
        };

        template <size_t max>
        struct ct_make_integer_range
        {
65
            // recursively call push_back on ct_integers_list to build a range from 1 to max
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
            // inclusive.
            typedef typename ct_make_integer_range<max-1>::type::template push_back<max>::type type;
        };

        template <>
        struct ct_make_integer_range<0>
        {
            typedef ct_integers_list<> type;
        };

        template <size_t... indices, typename Tuple>
        auto tuple_subset(
            const Tuple& item, 
            ct_integers_list<indices...>
        ) -> decltype(std::make_tuple(std::get<indices>(item)...))
        {
            return std::make_tuple(std::get<indices>(item)...);
        }

85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
        template <typename Head, typename... Tail>
        std::tuple<Tail...> basic_tuple_tail(
            const std::tuple<Head, Tail...>& item
        )
        {
            return tuple_subset(item, typename ct_make_integer_range<sizeof...(Tail)>::type());
        }

        template <typename T>
        std::tuple<T> tuple_flatten(const T& t) 
        {
            return std::make_tuple(t);
        }

        template <typename... T>
        auto tuple_flatten(
            const std::tuple<T...>& item
        ) -> decltype(tuple_flatten(item, typename ct_make_integer_range<sizeof...(T)>::type()))
        {
            return tuple_flatten(item, typename ct_make_integer_range<sizeof...(T)>::type());
        }

        template <size_t... indices, typename... T>
        auto tuple_flatten(
            const std::tuple<T...>& item, 
            ct_integers_list<indices...>
        ) -> decltype(std::tuple_cat(tuple_flatten(std::get<indices-1>(item))...))
        {
            return std::tuple_cat(tuple_flatten(std::get<indices-1>(item))...);
        }

        template <typename T>
        struct tuple_head_helper
        {
            typedef T type;
            static const type& get(const T& item) 
            {
                return item;
            }
        };

        template <typename T, typename... U>
        struct tuple_head_helper<std::tuple<T, U...>>
        {
            typedef typename tuple_head_helper<T>::type type;
            static const type& get(const std::tuple<T,U...>& item) 
            {
                return tuple_head_helper<T>::get(std::get<0>(item));
            }
        };

136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
        template <typename T> struct alwaysbool { typedef bool type; };

        resizable_tensor& rt();

        // The significance of a layer's backward method requiring forward's outputs is
        // that such as layer can't have an in-place layer stacked on top of it because
        // in-place layers overwrite the output of the layer they sit on top of.
        template <typename layer_type, typename SUBNET>
        constexpr auto backward_requires_forward_output(
            layer_type& layer,
            SUBNET& sub
        ) -> typename alwaysbool<decltype(layer.backward(rt(),rt(),sub,rt()))>::type
        {
            return true;
        }

        template <typename layer_type, typename SUBNET>
        constexpr auto backward_requires_forward_output(
            layer_type& layer,
            SUBNET& sub
        ) -> typename alwaysbool<decltype(layer.backward(rt(),sub,rt()))>::type
        {
            return false;
        }

        template <typename layer_type, typename SUBNET>
        constexpr auto backward_requires_forward_output(
            layer_type& layer,
            SUBNET& sub
        ) -> typename alwaysbool<decltype(layer.backward_inplace(rt(),rt(),sub.get_gradient_input(),rt()))>::type
        {
            return true;
        }

170
171
172
173
174
175
176
177
178
        template <typename layer_type, typename SUBNET>
        constexpr auto backward_requires_forward_output(
            layer_type& layer,
            SUBNET& sub
        ) -> typename alwaysbool<decltype(layer.backward_inplace(rt(),sub.get_gradient_input(),rt()))>::type
        {
            return false;
        }

179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
        template <typename layer_type, typename SUBNET>
        constexpr auto has_inplace_backward(
            layer_type& layer,
            SUBNET& sub
        ) -> typename alwaysbool<decltype(layer.backward(rt(),rt(),sub,rt()))>::type
        {
            return false;
        }

        template <typename layer_type, typename SUBNET>
        constexpr auto has_inplace_backward(
            layer_type& layer,
            SUBNET& sub
        ) -> typename alwaysbool<decltype(layer.backward(rt(),sub,rt()))>::type
        {
            return false;
        }

        template <typename layer_type, typename SUBNET>
        constexpr auto has_inplace_backward(
            layer_type& layer,
            SUBNET& sub
        ) -> typename alwaysbool<decltype(layer.backward_inplace(rt(),rt(),sub.get_gradient_input(),rt()))>::type
        {
            return true;
        }

206
207
208
209
210
211
212
213
214
        template <typename layer_type, typename SUBNET>
        constexpr auto has_inplace_backward(
            layer_type& layer,
            SUBNET& sub
        ) -> typename alwaysbool<decltype(layer.backward_inplace(rt(),sub.get_gradient_input(),rt()))>::type
        {
            return true;
        }

215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
        template <typename layer_type, typename SUBNET>
        constexpr auto is_inplace_layer(
            layer_type& layer,
            const SUBNET& sub 
        ) -> typename alwaysbool<decltype(layer.forward(sub,rt()))>::type
        {
            return false;
        }

        template <typename layer_type, typename SUBNET>
        constexpr auto is_inplace_layer(
            layer_type& layer,
            const SUBNET& sub
        ) -> typename alwaysbool<decltype(layer.forward_inplace(sub.get_output(),rt()))>::type
        {
            return true;
        }

        template <typename layer_type, typename SUBNET>
        auto call_layer_backward(
            layer_type& layer,
            const tensor& computed_output, 
            const tensor& gradient_input, 
            SUBNET& sub, 
            tensor& params_grad
        ) -> decltype(layer.backward(computed_output,gradient_input,sub,params_grad))
        {
            layer.backward(computed_output,gradient_input,sub,params_grad);
        }

        template <typename layer_type, typename SUBNET>
        auto call_layer_backward(
            layer_type& layer,
            const tensor& , 
            const tensor& gradient_input, 
            SUBNET& sub, 
            tensor& params_grad
        ) -> decltype(layer.backward(gradient_input,sub,params_grad))
        {
            layer.backward(gradient_input,sub,params_grad);
        }

        template <typename layer_type, typename SUBNET>
        auto call_layer_backward(
            layer_type& layer,
            const tensor& computed_output, 
            const tensor& gradient_input, 
            SUBNET& sub, 
            tensor& params_grad
        ) -> decltype(layer.backward_inplace(computed_output,gradient_input,sub.get_gradient_input(),params_grad))
        {
            layer.backward_inplace(computed_output,gradient_input,sub.get_gradient_input(),params_grad);
        }

269
270
271
272
273
274
275
276
277
278
279
280
        template <typename layer_type, typename SUBNET>
        auto call_layer_backward(
            layer_type& layer,
            const tensor& , 
            const tensor& gradient_input, 
            SUBNET& sub, 
            tensor& params_grad
        ) -> decltype(layer.backward_inplace(gradient_input,sub.get_gradient_input(),params_grad))
        {
            layer.backward_inplace(gradient_input,sub.get_gradient_input(),params_grad);
        }

281
282
283
284
285

        template <typename layer_type, typename SUBNET>
        auto call_layer_forward(
            layer_type& layer,
            const SUBNET& sub, 
286
            tensor& /*data_output*/
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
        ) -> decltype(layer.forward(sub,rt()))
        {
            // This overload of call_layer_forward() is here because this template
            // naturally gets instantiated but only on code paths that never get executed.
            // So rather than writing a bunch of hard to read template magic around call
            // sites we just have this overload that doesn't do anything (and an assert to
            // make sure that's the case).
            DLIB_CASSERT(false, "This should never happen");
        }

        template <typename layer_type, typename SUBNET>
        auto call_layer_forward(
            layer_type& layer,
            const SUBNET& sub, 
            resizable_tensor& data_output
        ) -> decltype(layer.forward(sub,data_output))
        {
            layer.forward(sub,data_output);
        }

        template <typename layer_type, typename SUBNET>
        auto call_layer_forward(
            layer_type& layer,
            const SUBNET& sub, 
            tensor& data_output
        ) -> decltype(layer.forward_inplace(sub.get_output(),data_output))
        {
            layer.forward_inplace(sub.get_output(),data_output);
        }

        template <typename layer_type, typename SUBNET>
        auto call_layer_forward(
            layer_type& layer,
            const SUBNET& sub, 
            resizable_tensor& data_output
        ) -> decltype(layer.forward_inplace(sub.get_output(),data_output))
        {
            if (!have_same_dimensions(data_output, sub.get_output()))
                data_output.copy_size(sub.get_output());
            layer.forward_inplace(sub.get_output(),data_output);
        }


    } // end namespace impl
331

332
333
334
335
336
337
338
339
340
341
342
343
    template <typename... T>
    typename impl::tuple_head_helper<std::tuple<T...>>::type tuple_head (
        const std::tuple<T...>& item
    ) 
    {
        return impl::tuple_head_helper<std::tuple<T...>>::get(item);
    }

    template <typename... T>
    auto tuple_tail(
        const std::tuple<T...>& item
    ) -> decltype(impl::basic_tuple_tail(impl::tuple_flatten(item)))
344
    {
345
        return impl::basic_tuple_tail(impl::tuple_flatten(item));
346
347
    }

348
349
350
351
352
353
    inline std::tuple<> tuple_tail(
        const std::tuple<>& item
    ) 
    {
        return item;
    }
354
355
356
357
358
359
360
361
// ----------------------------------------------------------------------------------------

    inline void randomize_parameters (
        tensor& params,
        unsigned long num_inputs_and_outputs,
        dlib::rand& rnd
    )
    {
Davis King's avatar
Davis King committed
362
        for (auto& val : params)
363
364
365
366
        {
            // Draw a random number to initialize the layer according to formula (16)
            // from Understanding the difficulty of training deep feedforward neural
            // networks by Xavier Glorot and Yoshua Bengio.
Davis King's avatar
Davis King committed
367
            val = 2*rnd.get_random_float()-1;
368
369
370
371
372
373
            val *= std::sqrt(6.0/(num_inputs_and_outputs));
        }
    }

// ----------------------------------------------------------------------------------------

374
    template <typename T>
375
376
    class sstack
    {
Davis King's avatar
Davis King committed
377
378
    public:
        typedef T value_type;
379

380
        sstack() = delete;
381

382
383
384
385
        sstack (
            T* data_,
            size_t s
        ) : data(data_), mysize(s) {}
386

387
388
389
390
391
392
393
394
395
        const T& top() const 
        { 
            DLIB_CASSERT(size() != 0, "You can't call top() on an empty stack");
            return *data;
        }
        T& top()  
        { 
            DLIB_CASSERT(size() != 0, "You can't call top() on an empty stack");
            return *data;
396
397
        }

398
399
400
401
402
403
        size_t size() const { return mysize; }

        sstack pop(size_t num=1) 
        { 
            DLIB_CASSERT(num < size(), "You can't pop more things from the stack than it has in it.");
            return sstack(data+num, mysize-num);
404
405
        }

Davis King's avatar
Davis King committed
406
    private:
407
408
409

        T* data;
        size_t mysize;
410
411
412
    };

    template <typename T>
413
    sstack<T> make_sstack(std::vector<T>& item)
414
    {
415
416
        return sstack<T>(item.data(), item.size());
    }
417
418
419
420
421
422
423

// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

    namespace dimpl
    {
424
        template <typename T, bool is_first = true, typename enabled=void>
Davis King's avatar
Davis King committed
425
        class subnet_wrapper
426
427
428
        {
            /*!
                WHAT THIS OBJECT REPRESENTS
Davis King's avatar
Davis King committed
429
                    This is a tool that makes an add_layer or add_loss_layer object
Davis King's avatar
Davis King committed
430
                    expose only the part of its interface defined by the SUBNET
431
                    type in layers_abstract.h.  This way, when we pass subnetwork
432
                    objects to the layer callbacks those callbacks won't be able to 
433
                    interact with the subnetworks in a way other than specified 
Davis King's avatar
Davis King committed
434
                    by the SUBNET interface spec.
435
436
437
438
439
440
441

                    We also allow the top layer of a subnet_wrapper stack to call the
                    private_get_output() and private_get_gradient_input() functions.  This
                    way, layers that have had their output/gradient overwritten by in-place
                    layers can only be accessed from the in-place layers that sit directly
                    on top of them since those in-place layers are the only layers that
                    know how to interact with them properly.
442
443
444
            !*/

        public:
Davis King's avatar
Davis King committed
445
446
            subnet_wrapper(const subnet_wrapper&) = delete;
            subnet_wrapper& operator=(const subnet_wrapper&) = delete;
447

Davis King's avatar
Davis King committed
448
            subnet_wrapper(T& l_) {}
449
450
451
452
453
            // Nothing here because in this case T is one of the input layer types 
            // that doesn't have anything in it.
        };

        template <typename T>
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
        class subnet_wrapper<T,true, typename std::enable_if<is_nonloss_layer_type<T>::value>::type>
        {

        public:
            subnet_wrapper(const subnet_wrapper&) = delete;
            subnet_wrapper& operator=(const subnet_wrapper&) = delete;

            typedef T wrapped_type;
            const static size_t num_layers = T::num_layers;

            subnet_wrapper(T& l_) : l(l_),subnetwork(l.subnet()) {}

            const tensor& get_output() const { return l.private_get_output(); }
            tensor& get_gradient_input() { return l.private_get_gradient_input(); }

Davis King's avatar
Davis King committed
469
470
            const subnet_wrapper<typename T::subnet_type,false>& subnet() const { return subnetwork; }
            subnet_wrapper<typename T::subnet_type,false>& subnet() { return subnetwork; }
471
472
473
474
475
476
477
478

        private:
            T& l;
            subnet_wrapper<typename T::subnet_type,false> subnetwork;
        };

        template <typename T>
        class subnet_wrapper<T,false, typename std::enable_if<is_nonloss_layer_type<T>::value>::type>
479
480
481
        {

        public:
Davis King's avatar
Davis King committed
482
483
            subnet_wrapper(const subnet_wrapper&) = delete;
            subnet_wrapper& operator=(const subnet_wrapper&) = delete;
484

485
486
487
            typedef T wrapped_type;
            const static size_t num_layers = T::num_layers;

Davis King's avatar
Davis King committed
488
            subnet_wrapper(T& l_) : l(l_),subnetwork(l.subnet()) {}
489
490
491
492

            const tensor& get_output() const { return l.get_output(); }
            tensor& get_gradient_input() { return l.get_gradient_input(); }

Davis King's avatar
Davis King committed
493
494
            const subnet_wrapper<typename T::subnet_type,false>& subnet() const { return subnetwork; }
            subnet_wrapper<typename T::subnet_type,false>& subnet() { return subnetwork; }
495
496
497

        private:
            T& l;
Davis King's avatar
Davis King committed
498
            subnet_wrapper<typename T::subnet_type,false> subnetwork;
499
500
501
        };
    }

Davis King's avatar
Davis King committed
502
503
// ----------------------------------------------------------------------------------------

Davis King's avatar
Davis King committed
504
    template <typename LAYER_DETAILS, typename SUBNET, typename enabled = void>
505
506
507
    class add_layer;

    template <typename T, typename U>
Davis King's avatar
Davis King committed
508
    struct is_nonloss_layer_type<add_layer<T,U>> : std::true_type {};
509

Davis King's avatar
Davis King committed
510
511
512
    template <typename LAYER_DETAILS, typename SUBNET>
    class add_layer<LAYER_DETAILS,SUBNET, 
            typename std::enable_if<is_nonloss_layer_type<SUBNET>::value>::type>
513
514
515
    {
    public:
        typedef LAYER_DETAILS layer_details_type;
Davis King's avatar
Davis King committed
516
517
518
519
        typedef SUBNET subnet_type;
        typedef typename subnet_type::input_type input_type;
        const static size_t num_layers = subnet_type::num_layers + 1;
        const static unsigned int sample_expansion_factor = subnet_type::sample_expansion_factor;
520
521
522

        add_layer(
        ):
523
            subnetwork(new subnet_type()),
524
            this_layer_setup_called(false),
525
526
            gradient_input_is_stale(true),
            get_output_and_gradient_input_disabled(false)
527
        {
528
            if (this_layer_operates_inplace())
529
                subnetwork->disable_output_and_gradient_getters();
530
531
        }

532
533
534
535
536
537
538
539
540
541
542
543
544
        add_layer(const add_layer& item)
        {
            details = item.details;
            subnetwork.reset(new subnet_type(*item.subnetwork));
            this_layer_setup_called = item.this_layer_setup_called;
            gradient_input_is_stale = item.gradient_input_is_stale;
            get_output_and_gradient_input_disabled = item.get_output_and_gradient_input_disabled;
            x_grad = item.x_grad;
            cached_output = item.cached_output; 
            params_grad = item.params_grad; 
            temp_tensor = item.temp_tensor;
        }
        add_layer& operator=(const add_layer& item) { add_layer(item).swap(*this); return *this;}
545
546
        add_layer(add_layer&& item) : add_layer() { swap(item); }
        add_layer& operator=(add_layer&& item) { swap(item); return *this; }
547
548
549

        template <typename T, typename U, typename E>
        friend class add_layer;
550
551
        template <typename T, bool is_first, typename E>
        friend class dimpl::subnet_wrapper;
552
553
554
555
        template <unsigned long T, typename U, typename E>
        friend class add_tag_layer;
        template <template<typename> class T, typename U>
        friend class add_skip_layer;
556
557
        template <size_t N, template<typename> class L, typename S>
        friend class repeat;
558
559
560
561
562
563
564
565

        // Allow copying networks from one to another as long as their corresponding 
        // layers can be constructed from each other.
        template <typename T, typename U, typename E>
        add_layer(
            const add_layer<T,U,E>& item
        ) :
            details(item.layer_details()), 
566
            subnetwork(new subnet_type(item.subnet())),
567
568
            this_layer_setup_called(item.this_layer_setup_called),
            gradient_input_is_stale(item.gradient_input_is_stale),
569
            get_output_and_gradient_input_disabled(item.get_output_and_gradient_input_disabled),
570
571
572
            x_grad(item.x_grad),
            cached_output(item.cached_output)
        {
573
            if (this_layer_operates_inplace())
574
                subnetwork->disable_output_and_gradient_getters();
575
576
577
578
579
580
581
582
        }

        template <typename ...T>
        add_layer(
            const LAYER_DETAILS& layer_det, 
            T&& ...args
        ) : 
            details(layer_det), 
583
            subnetwork(new subnet_type(std::forward<T>(args)...)),
584
            this_layer_setup_called(false),
585
586
            gradient_input_is_stale(true),
            get_output_and_gradient_input_disabled(false)
587
        {
588
            if (this_layer_operates_inplace())
589
                subnetwork->disable_output_and_gradient_getters();
590
591
        }

592
        template <typename T, typename ...U>
593
        struct disable_forwarding_constr 
594
595
596
597
        {
            const static bool value = std::is_constructible<LAYER_DETAILS,T>::value;
        };
        template <typename ...T, typename ...U>
598
        struct disable_forwarding_constr<std::tuple<T...>,U...>
599
600
601
602
603
604
605
606
607
608
        {
            const static bool value = disable_forwarding_constr<typename std::remove_reference<T>::type...>::value;
        };
        template <typename T, typename ...U>
        struct disable_forwarding_constr<std::tuple<T>,U...>
        {
            const static bool value = disable_forwarding_constr<typename std::remove_reference<T>::type>::value;
        };
        template <typename ...U>
        struct disable_forwarding_constr<std::tuple<>,U...>
609
610
611
612
613
        {
            const static bool value = true;
        };
        template <typename ...T>
        struct disable_forwarding_constr<add_layer<T...>>
614
615
616
        {
            const static bool value = true;
        };
617
618
619

        template <
            typename ...T,
620
            typename = typename std::enable_if<!disable_forwarding_constr<typename std::remove_reference<T>::type...>::value>::type
621
622
623
624
625
626
627
628
629
630
631
632
633
            >
        add_layer(
            T&& ...args
        ) : 
            subnetwork(new subnet_type(std::forward<T>(args)...)),
            this_layer_setup_called(false),
            gradient_input_is_stale(true),
            get_output_and_gradient_input_disabled(false)
        {
            if (this_layer_operates_inplace())
                subnetwork->disable_output_and_gradient_getters();
        }

634
635
636
637
638
639
        template <typename ...T>
        add_layer(
            LAYER_DETAILS&& layer_det, 
            T&& ...args
        ) : 
            details(std::move(layer_det)), 
640
            subnetwork(new subnet_type(std::forward<T>(args)...)),
641
            this_layer_setup_called(false),
642
643
            gradient_input_is_stale(true),
            get_output_and_gradient_input_disabled(false)
644
        {
645
            if (this_layer_operates_inplace())
646
                subnetwork->disable_output_and_gradient_getters();
647
648
        }

649
        template <typename ...T, typename LD, typename ...U>
650
        add_layer(
651
            const std::tuple<LD,U...>& layer_det, 
652
653
            T&& ...args
        ) : 
654
            details(tuple_head(layer_det)), 
655
            subnetwork(new subnet_type(tuple_tail(layer_det),std::forward<T>(args)...)),
656
            this_layer_setup_called(false),
657
658
            gradient_input_is_stale(true),
            get_output_and_gradient_input_disabled(false)
659
        {
660
            if (this_layer_operates_inplace())
661
                subnetwork->disable_output_and_gradient_getters();
662
663
        }

664
        template <typename ...T, typename LD, typename ...U>
665
666
        add_layer(
            std::tuple<>,
667
            const std::tuple<LD,U...>& layer_det, 
668
669
670
            T&& ...args
        ) : add_layer(layer_det,args...) { }

671
672
673
674
        add_layer (
            std::tuple<>
        ) : add_layer() {}

675
676
677
678
679
680
681
        template <typename ...T>
        add_layer(
            std::tuple<>, 
            LAYER_DETAILS&& layer_det, 
            T&& ...args
        ) : add_layer(layer_det, args...) { }

682
683
        template <typename input_iterator>
        void to_tensor (
684
685
            input_iterator ibegin,
            input_iterator iend,
686
687
688
            resizable_tensor& data
        ) const
        {
689
            subnetwork->to_tensor(ibegin,iend,data);
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
        }

        template <typename input_iterator>
        const tensor& operator() (
            input_iterator ibegin,
            input_iterator iend
        )
        {
            to_tensor(ibegin,iend,temp_tensor);
            return forward(temp_tensor);
        }


        const tensor& operator() (const input_type& x)
        {
            return (*this)(&x, &x+1);
        }

        const tensor& forward(const tensor& x)
        {
710
711
            subnetwork->forward(x);
            const dimpl::subnet_wrapper<subnet_type> wsub(*subnetwork);
712
713
714
715
716
            if (!this_layer_setup_called)
            {
                details.setup(wsub);
                this_layer_setup_called = true;
            }
717
718
719
720
721
            if (this_layer_operates_inplace())
                impl::call_layer_forward(details, wsub, private_get_output());
            else
                impl::call_layer_forward(details, wsub, cached_output);

722
            gradient_input_is_stale = true;
723
            return private_get_output();
724
725
        }

726
727
    private:
        tensor& private_get_output() const
728
        { 
729
            if (const_cast<add_layer&>(*this).this_layer_operates_inplace())
730
                return subnetwork->private_get_output();
731
732
733
734
735
736
            else
                return const_cast<resizable_tensor&>(cached_output); 
        }
        tensor& private_get_gradient_input() 
        { 
            if (this_layer_operates_inplace())
737
            {
738
                return subnetwork->private_get_gradient_input();
739
            }
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
            else
            {
                if (gradient_input_is_stale)
                {
                    gradient_input_is_stale = false;
                    x_grad.copy_size(private_get_output());
                    x_grad = 0;
                }
                return x_grad; 
            }
        }
        void disable_output_and_gradient_getters (
        ) { get_output_and_gradient_input_disabled = true; }
    public:
        const tensor& get_output() const 
        { 
            if (get_output_and_gradient_input_disabled)
                throw dlib::error("Accessing this layer's get_output() is disabled because an in-place layer has been stacked on top of it.");
            return private_get_output(); 
        }
        tensor& get_gradient_input() 
        { 
            if (get_output_and_gradient_input_disabled)
                throw dlib::error("Accessing this layer's get_gradient_input() is disabled because an in-place layer has been stacked on top of it.");
            return private_get_gradient_input();
765
766
        }

767
        const tensor& get_final_data_gradient(
768
        ) const { return subnetwork->get_final_data_gradient(); }
769

770
        template <typename solver_type>
771
        void update(const tensor& x, sstack<solver_type> solvers, double step_size)
772
        {
773
            update(x,private_get_gradient_input(),solvers,step_size);
774
775
776
        }

        template <typename solver_type>
777
        void update(const tensor& x, const tensor& gradient_input, sstack<solver_type> solvers, double step_size)
778
        {
779
            DLIB_CASSERT(solvers.size()>=num_layers,"");
780
            dimpl::subnet_wrapper<subnet_type> wsub(*subnetwork);
781
            params_grad.copy_size(details.get_layer_params());
782
            impl::call_layer_backward(details, private_get_output(),
783
                gradient_input, wsub, static_cast<tensor&>(params_grad));
784

785
786
            // Don't try to adjust the parameters if this layer doesn't have any.
            if (params_grad.size() != 0)
787
788
789
790
791
            {
                const tensor& step = solvers.top()(details.get_layer_params(), static_cast<const tensor&>(params_grad));
                tt::add(1,details.get_layer_params(), step_size, step);
            }
            subnetwork->update(x, solvers.pop(), step_size);
792
            gradient_input_is_stale = true;
793
794
        }

795
796
        const subnet_type& subnet() const { return *subnetwork; }
        subnet_type& subnet() { return *subnetwork; }
797
798
799
800
801
802
803
804
805
806
807

        const layer_details_type& layer_details() const { return details; } 
        layer_details_type& layer_details() { return details; } 

        void clean()
        {
            x_grad.clear();
            cached_output.clear();
            params_grad.clear();
            temp_tensor.clear();
            gradient_input_is_stale = true;
808
            subnetwork->clean();
809
810
        }

811
812
813
814
        friend void serialize(const add_layer& item, std::ostream& out)
        {
            int version = 1;
            serialize(version, out);
815
            serialize(*item.subnetwork, out);
816
817
818
            serialize(item.details, out);
            serialize(item.this_layer_setup_called, out);
            serialize(item.gradient_input_is_stale, out);
819
            serialize(item.get_output_and_gradient_input_disabled, out);
820
821
822
823
824
825
826
827
828
829
            serialize(item.x_grad, out);
            serialize(item.cached_output, out);
        }

        friend void deserialize(add_layer& item, std::istream& in)
        {
            int version = 0;
            deserialize(version, in);
            if (version != 1)
                throw serialization_error("Unexpected version found while deserializing dlib::add_layer.");
830
            deserialize(*item.subnetwork, in);
831
832
833
            deserialize(item.details, in);
            deserialize(item.this_layer_setup_called, in);
            deserialize(item.gradient_input_is_stale, in);
834
            deserialize(item.get_output_and_gradient_input_disabled, in);
835
836
837
838
            deserialize(item.x_grad, in);
            deserialize(item.cached_output, in);
        }

839
840
    private:

841
842
843
844
        bool this_layer_operates_inplace(
        ) 
        {
            // This layer can run in-place if it's an in-place capable layer and also if
845
            // the layer it's on top of doesn't need its own output tensor (since in-place
846
            // layers overwrite that tensor)
847
            return impl::is_inplace_layer(details, *subnetwork) && !subnetwork->this_layer_requires_forward_output();
848
849
850
851
        }
        bool this_layer_requires_forward_output(
        ) 
        {
852
            return impl::backward_requires_forward_output(details, *subnetwork);
853
854
        }

855
856
857
858
859
860
        void swap(add_layer& item)
        {
            std::swap(subnetwork,item.subnetwork);
            std::swap(details, item.details);
            std::swap(this_layer_setup_called, item.this_layer_setup_called);
            std::swap(gradient_input_is_stale, item.gradient_input_is_stale);
861
            std::swap(get_output_and_gradient_input_disabled, item.get_output_and_gradient_input_disabled);
862
863
864
865
            std::swap(x_grad, item.x_grad);
            std::swap(cached_output, item.cached_output);
        }

866
867

        LAYER_DETAILS details;
868
        std::unique_ptr<subnet_type> subnetwork;
869
870
        bool this_layer_setup_called;
        bool gradient_input_is_stale;
871
872
873
874
        bool get_output_and_gradient_input_disabled;
        // Note that if this_layer_operates_inplace()==true then x_grad and cached_output
        // are not used at all.  Instead, this layer uses these variables from the lower
        // layer.
875
876
877
878
879
880
881
882
883
884
885
886
887
        resizable_tensor x_grad;
        resizable_tensor cached_output; 

        // The following 2 objects don't logically contribute to the state of this class.
        // They are only here to prevent them from being reallocated over and over in
        // member functions.
        resizable_tensor params_grad; 
        resizable_tensor temp_tensor;

    };

// ----------------------------------------------------------------------------------------

888
// This version of add_layer handles the special case where the subnetwork being given is
Davis King's avatar
Davis King committed
889
// just an input layer object.
890
891
892
893
894
    template <typename LAYER_DETAILS, typename INPUT_LAYER, typename enabled>
    class add_layer
    {
    public:
        typedef LAYER_DETAILS layer_details_type;
Davis King's avatar
Davis King committed
895
        typedef INPUT_LAYER subnet_type;
896
897
898
899
900
901
902
903
904
        typedef typename INPUT_LAYER::input_type input_type;
        const static unsigned int sample_expansion_factor = INPUT_LAYER::sample_expansion_factor;
        const static size_t num_layers = 1;
        static_assert(sample_expansion_factor >= 1,
            "The input layer can't produce fewer output tensors than there are inputs.");

        add_layer(
        ): 
            this_layer_setup_called(false),
905
906
            gradient_input_is_stale(true),
            get_output_and_gradient_input_disabled(false)
907
908
909
        {}

        add_layer(const add_layer&) = default;
910
        add_layer(add_layer&& item) : add_layer() { swap(item); }
911
        add_layer& operator=(const add_layer&) = default;
912
        add_layer& operator=(add_layer&& item) { swap(item); return *this; }
913
914
915

        template <typename T, typename U, typename E>
        friend class add_layer;
916
917
        template <typename T, bool is_first, typename E>
        friend class dimpl::subnet_wrapper;
918
919
920
921
        template <unsigned long T, typename U, typename E>
        friend class add_tag_layer;
        template <template<typename> class T, typename U>
        friend class add_skip_layer;
922
923
        template <size_t N, template<typename> class L, typename S>
        friend class repeat;
924
925
926
927
928
929
930

        // Allow copying networks from one to another as long as their corresponding 
        // layers can be constructed from each other.
        template <typename T, typename U, typename E>
        add_layer(
            const add_layer<T,U,E>& item
        ):
Davis King's avatar
Davis King committed
931
            input_layer(item.subnet()),
932
933
934
            details(item.layer_details()),
            this_layer_setup_called(item.this_layer_setup_called),
            gradient_input_is_stale(item.gradient_input_is_stale),
935
            get_output_and_gradient_input_disabled(false),
936
            x_grad(item.x_grad),
937
938
            cached_output(item.cached_output),
            grad_final(item.grad_final)
939
940
941
942
943
944
945
946
        {
        }

        add_layer(
            const LAYER_DETAILS& layer_det
        ) : 
            details(layer_det), 
            this_layer_setup_called(false),
947
948
            gradient_input_is_stale(true),
            get_output_and_gradient_input_disabled(false)
949
950
951
952
953
954
955
        {}

        add_layer(
            LAYER_DETAILS&& layer_det
        ) : 
            details(std::move(layer_det)), 
            this_layer_setup_called(false),
956
957
            gradient_input_is_stale(true),
            get_output_and_gradient_input_disabled(false)
958
959
960
961
962
963
        {}

        add_layer(
            LAYER_DETAILS layer_det, 
            INPUT_LAYER il
        ) : 
964
965
            details(std::move(layer_det)),
            input_layer(std::move(il)),
966
            this_layer_setup_called(false),
967
968
            gradient_input_is_stale(true),
            get_output_and_gradient_input_disabled(false)
969
970
        {}

971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
        add_layer(
            std::tuple<>,
            const LAYER_DETAILS& layer_det
        ) : add_layer(layer_det) {}

        add_layer(
            std::tuple<>,
            LAYER_DETAILS&& layer_det
        ) : add_layer(layer_det) {}

        add_layer(
            std::tuple<>,
            LAYER_DETAILS layer_det, 
            INPUT_LAYER il
        ) : add_layer(layer_det,il) {}

        add_layer(
            const std::tuple<LAYER_DETAILS>& layer_det
989
        ) : add_layer(tuple_head(layer_det)) {}
990
991
992
993

        add_layer(
            const std::tuple<LAYER_DETAILS>& layer_det,
            INPUT_LAYER il
994
        ) : add_layer(tuple_head(layer_det),il) {}
995

996
997
        template <typename input_iterator>
        void to_tensor (
998
999
            input_iterator ibegin,
            input_iterator iend,
1000
1001
1002
            resizable_tensor& data
        ) const
        {
1003
            input_layer.to_tensor(ibegin, iend, data);
1004
            // make sure the input layer's to_tensor() function is implemented properly.
1005
            DLIB_CASSERT(std::distance(ibegin,iend)*sample_expansion_factor == data.num_samples(),"");
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
            data.async_copy_to_device();
        }


        template <typename input_iterator>
        const tensor& operator() (
            input_iterator ibegin,
            input_iterator iend
        )
        {
            to_tensor(ibegin,iend,temp_tensor);
            return forward(temp_tensor);
        }


        const tensor& operator() (const input_type& x)
        {
            return (*this)(&x, &x+1);
        }

        const tensor& forward (const tensor& x)
        {
            DLIB_CASSERT(x.num_samples()%sample_expansion_factor == 0,"");
1029
            subnet_wrapper wsub(x, grad_final);
1030
1031
1032
1033
1034
            if (!this_layer_setup_called)
            {
                details.setup(wsub);
                this_layer_setup_called = true;
            }
1035
            impl::call_layer_forward(details, wsub, cached_output);
1036
            gradient_input_is_stale = true;
1037
            return private_get_output();
1038
1039
        }

1040
1041
1042
    private:
        tensor& private_get_output() const { return const_cast<resizable_tensor&>(cached_output); }
        tensor& private_get_gradient_input() 
1043
1044
1045
1046
        { 
            if (gradient_input_is_stale)
            {
                gradient_input_is_stale = false;
1047
                x_grad.copy_size(private_get_output());
1048
1049
1050
1051
                x_grad = 0;
            }
            return x_grad; 
        }
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
        void disable_output_and_gradient_getters (
        ) { get_output_and_gradient_input_disabled = true; }
    public:
        const tensor& get_output() const 
        { 
            if (get_output_and_gradient_input_disabled)
                throw dlib::error("Accessing this layer's get_output() is disabled because an in-place layer has been stacked on top of it.");
            return private_get_output(); 
        }
        tensor& get_gradient_input() 
        { 
            if (get_output_and_gradient_input_disabled)
                throw dlib::error("Accessing this layer's get_gradient_input() is disabled because an in-place layer has been stacked on top of it.");
            return private_get_gradient_input();
        }
1067

1068
        const tensor& get_final_data_gradient(
1069
        ) const { return grad_final; }
1070

1071
        template <typename solver_type>
1072
        void update(const tensor& x, sstack<solver_type> solvers, double step_size)
1073
        {
1074
            return update(x,private_get_gradient_input(),solvers, step_size);
1075
1076
1077
        }

        template <typename solver_type>
1078
        void update(const tensor& x, const tensor& gradient_input, sstack<solver_type> solvers, double step_size)
1079
        {
1080
1081
1082
1083
1084
1085
1086
            DLIB_CASSERT(solvers.size()>=num_layers,"");
            // make sure grad_final is initialized to 0
            if (!have_same_dimensions(x, grad_final))
                grad_final.copy_size(x);
            grad_final = 0;  

            subnet_wrapper wsub(x, grad_final);
1087
            params_grad.copy_size(details.get_layer_params());
1088
            impl::call_layer_backward(details, private_get_output(),
1089
                gradient_input, wsub, static_cast<tensor&>(params_grad));
1090

1091
1092
            // Don't try to adjust the parameters if this layer doesn't have any.
            if (params_grad.size() != 0)
1093
1094
1095
1096
            {
                const tensor& step = solvers.top()(details.get_layer_params(), static_cast<const tensor&>(params_grad));
                tt::add(1,details.get_layer_params(), step_size, step);
            }
1097
            gradient_input_is_stale = true;
1098
1099
        }

Davis King's avatar
Davis King committed
1100
1101
        const subnet_type& subnet() const { return input_layer; } 
        subnet_type& subnet() { return input_layer; } 
1102
1103
1104
1105
1106
1107
1108

        const layer_details_type& layer_details() const { return details; } 
        layer_details_type& layer_details() { return details; } 

        void clean()
        {
            x_grad.clear();
1109
            grad_final.clear();
1110
1111
1112
1113
1114
1115
            cached_output.clear();
            params_grad.clear();
            temp_tensor.clear();
            gradient_input_is_stale = true;
        }

1116
1117
        friend void serialize(const add_layer& item, std::ostream& out)
        {
1118
            int version = 2;
1119
1120
1121
1122
1123
            serialize(version, out);
            serialize(item.input_layer, out);
            serialize(item.details, out);
            serialize(item.this_layer_setup_called, out);
            serialize(item.gradient_input_is_stale, out);
1124
            serialize(item.get_output_and_gradient_input_disabled, out);
1125
1126
            serialize(item.x_grad, out);
            serialize(item.cached_output, out);
1127
            serialize(item.grad_final, out);
1128
1129
1130
1131
1132
1133
        }

        friend void deserialize(add_layer& item, std::istream& in)
        {
            int version = 0;
            deserialize(version, in);
1134
            if (version != 2)
1135
1136
1137
1138
1139
                throw serialization_error("Unexpected version found while deserializing dlib::add_layer.");
            deserialize(item.input_layer, in);
            deserialize(item.details, in);
            deserialize(item.this_layer_setup_called, in);
            deserialize(item.gradient_input_is_stale, in);
1140
            deserialize(item.get_output_and_gradient_input_disabled, in);
1141
1142
            deserialize(item.x_grad, in);
            deserialize(item.cached_output, in);
1143
            deserialize(item.grad_final, in);
1144
1145
        }

1146
1147
    private:

1148
1149
1150
        bool this_layer_requires_forward_output(
        ) 
        {
1151
            subnet_wrapper wsub(grad_final, grad_final);
1152
1153
1154
            return impl::backward_requires_forward_output(details, wsub);
        }

Davis King's avatar
Davis King committed
1155
        class subnet_wrapper
1156
1157
        {
        public:
1158
1159
            subnet_wrapper(const tensor& x_, resizable_tensor& grad_final_) :
                x(x_), grad_final(grad_final_) {}
1160

Davis King's avatar
Davis King committed
1161
1162
            subnet_wrapper(const subnet_wrapper&) = delete;
            subnet_wrapper& operator=(const subnet_wrapper&) = delete;
1163

1164
1165
1166
            const tensor& get_output() const { return x; }
            tensor& get_gradient_input() 
            { 
1167
                if (!have_same_dimensions(x, grad_final))
1168
                {
1169
1170
                    grad_final.copy_size(x);
                    grad_final = 0;  
1171
                }
1172
                return grad_final; 
1173
1174
1175
1176
            }

        private:
            const tensor& x;
1177
            resizable_tensor& grad_final;
1178
1179
        };

1180
1181
1182
1183
1184
1185
        void swap(add_layer& item)
        {
            std::swap(input_layer, item.input_layer);
            std::swap(details, item.details);
            std::swap(this_layer_setup_called, item.this_layer_setup_called);
            std::swap(gradient_input_is_stale, item.gradient_input_is_stale);
1186
            std::swap(get_output_and_gradient_input_disabled, item.get_output_and_gradient_input_disabled);
1187
1188
            std::swap(x_grad, item.x_grad); 
            std::swap(cached_output, item.cached_output); 
1189
            std::swap(grad_final, item.grad_final); 
1190
1191
        }

Davis King's avatar
Davis King committed
1192
        subnet_type input_layer;
1193
1194
1195
        LAYER_DETAILS details;
        bool this_layer_setup_called;
        bool gradient_input_is_stale;
1196
        bool get_output_and_gradient_input_disabled;
1197
1198
        resizable_tensor x_grad; 
        resizable_tensor cached_output; 
1199
        resizable_tensor grad_final;
1200

1201
        // The following 2 objects don't logically contribute to the state of this class.
1202
1203
1204
1205
1206
1207
1208
1209
        // They are only here to prevent them from being reallocated over and over in
        // member functions.
        resizable_tensor params_grad; 
        resizable_tensor temp_tensor; 
    };

// ----------------------------------------------------------------------------------------

Davis King's avatar
Davis King committed
1210
    template <unsigned long ID, typename SUBNET, typename enabled=void>
1211
1212
    class add_tag_layer;

Davis King's avatar
Davis King committed
1213
1214
1215
    template <unsigned long ID, typename SUBNET>
    class add_tag_layer<ID,SUBNET,
            typename std::enable_if<is_nonloss_layer_type<SUBNET>::value>::type>
1216
1217
    {
    public:
Davis King's avatar
Davis King committed
1218
1219
        typedef SUBNET subnet_type;
        typedef typename subnet_type::input_type input_type;
1220
        const static size_t num_layers = subnet_type::num_layers;
Davis King's avatar
Davis King committed
1221
        const static unsigned int sample_expansion_factor = subnet_type::sample_expansion_factor;
1222
1223
1224
        static_assert(sample_expansion_factor >= 1,
            "The input layer can't produce fewer output tensors than there are inputs.");

Davis King's avatar
Davis King committed
1225
1226
1227
1228
1229
        add_tag_layer() = default;
        add_tag_layer(const add_tag_layer&) = default;
        add_tag_layer(add_tag_layer&&) = default;
        add_tag_layer& operator=(add_tag_layer&&) = default;
        add_tag_layer& operator=(const add_tag_layer&) = default;
1230
1231

        template <typename T>
Davis King's avatar
Davis King committed
1232
1233
        add_tag_layer(
            const add_tag_layer<ID,T>& item
Davis King's avatar
Davis King committed
1234
        ) : subnetwork(item.subnet())
1235
1236
1237
        {}

        template <typename ...T>
Davis King's avatar
Davis King committed
1238
        add_tag_layer(
1239
1240
            T ...args
        ) : 
Davis King's avatar
Davis King committed
1241
            subnetwork(std::move(args)...) 
1242
1243
1244
1245
1246
        {
        }

        template <typename input_iterator>
        void to_tensor (
1247
1248
            input_iterator ibegin,
            input_iterator iend,
1249
1250
1251
            resizable_tensor& data
        ) const
        {
Davis King's avatar
Davis King committed
1252
            subnetwork.to_tensor(ibegin,iend,data);
1253
1254
1255
1256
1257
1258
1259
1260
        }

        template <typename input_iterator>
        const tensor& operator() (
            input_iterator ibegin,
            input_iterator iend
        )
        {
Davis King's avatar
Davis King committed
1261
            return subnetwork(ibegin,iend);
1262
1263
1264
1265
        }

        const tensor& operator() (const input_type& x)
        {
Davis King's avatar
Davis King committed
1266
            return subnetwork(x);
1267
1268
1269
1270
        }

        const tensor& forward(const tensor& x)
        {
Davis King's avatar
Davis King committed
1271
            return subnetwork.forward(x);
1272
1273
        }

Davis King's avatar
Davis King committed
1274
        const tensor& get_output() const { return subnetwork.get_output(); }
1275
1276
1277

        tensor& get_gradient_input() 
        { 
Davis King's avatar
Davis King committed
1278
            return subnetwork.get_gradient_input();
1279
1280
        }

1281
1282
1283
        const tensor& get_final_data_gradient(
        ) const { return subnetwork.get_final_data_gradient(); }

1284
        template <typename solver_type>
1285
        void update(const tensor& x, sstack<solver_type> solvers, double step_size)
1286
        {
1287
            subnetwork.update(x,solvers, step_size);
1288
1289
        }

1290
        template <typename solver_type>
1291
        void update(const tensor& x, const tensor& gradient_input, sstack<solver_type> solvers, double step_size)
1292
        {
1293
            subnetwork.update(x,gradient_input,solvers, step_size);
1294
1295
        }

Davis King's avatar
Davis King committed
1296
1297
        const subnet_type& subnet() const { return subnetwork; }
        subnet_type& subnet() { return subnetwork; }
1298
1299
1300

        void clean()
        {
Davis King's avatar
Davis King committed
1301
            subnetwork.clean();
1302
1303
        }

1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
        friend void serialize(const add_tag_layer& item, std::ostream& out)
        {
            int version = 1;
            serialize(version, out);
            serialize(item.subnetwork, out);
        }

        friend void deserialize(add_tag_layer& item, std::istream& in)
        {
            int version = 0;
            deserialize(version, in);
            if (version != 1)
                throw serialization_error("Unexpected version found while deserializing dlib::add_tag_layer.");
            deserialize(item.subnetwork, in);
        }

1320
1321
    private:

1322
1323
1324
1325
1326
1327
1328
1329
        template <typename T, typename U, typename E>
        friend class add_layer;
        template <typename T, bool is_first, typename E>
        friend class dimpl::subnet_wrapper;
        template <unsigned long T, typename U, typename E>
        friend class add_tag_layer;
        template <template<typename> class T, typename U>
        friend class add_skip_layer;
1330
1331
        template <size_t N, template<typename> class L, typename S>
        friend class repeat;
1332

Davis King's avatar
Davis King committed
1333
        // You wouldn't put a tag on a layer if you didn't want to access its forward
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
        // outputs.  So this is always true.
        bool this_layer_requires_forward_output(
        ) { return true; } 

        void disable_output_and_gradient_getters (
        ) 
        { 
            // This should never happen because only inplace layers call
            // disable_output_and_gradient_getters(), however, putting a tag layer right
            // before an inplace layer basically means you don't want the following layer
            // to operate in place.  So the inplace layer should turn itself into an
            // out-of-place layer and not call disable_output_and_gradient_getters(). 
            DLIB_CASSERT(false,"This should never happen");
        }

        tensor& private_get_output() const
        { return subnetwork.private_get_output(); }
        tensor& private_get_gradient_input() 
        { return subnetwork.private_get_gradient_input(); }

Davis King's avatar
Davis King committed
1354
        subnet_type subnetwork;
1355
1356
    };

1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
// ----------------------------------------------------------------------------------------

    namespace impl
    {
        class repeat_input_layer 
        {
            /*!
                None of the declarations in this object are really used. The only reason it
                exists is to allow the repeat object to use a special input layer in its
                internal networks which will cause add_tag_layer objects that happen to be
                right at the input to not create copies of their input tensors.  So
                introducing the repeat_input_layer object allows us to optimize the
                implementation of add_tag_layer for a special case that arises when it's
                used in the context of the repeat layer.
            !*/
        public:
            typedef int input_type;
            const static unsigned int sample_expansion_factor = 1;

            template <typename input_iterator>
            void to_tensor (
                input_iterator ,
                input_iterator ,
                resizable_tensor& 
            ) const
            {
                DLIB_CASSERT(false,"This function should never be called");
            }

            friend void serialize(const repeat_input_layer&, std::ostream&){}
            friend void deserialize(repeat_input_layer&, std::istream&){}
        };
    }

1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
    template <typename ...T>
    struct decorator_repeat_group
    {
        decorator_repeat_group(
            T&& ...args
        ) : data(std::forward<T>(args)...) {}

        std::tuple<T...> data;
    };
    template <typename ...T>
    decorator_repeat_group<T...> repeat_group (
        T&& ...args
    )
    {
        return decorator_repeat_group<T...>(std::forward<T>(args)...);
    }

1408
1409
    template <
        size_t num,
1410
        template<typename> class REPEATED_LAYER, 
1411
1412
1413
1414
1415
1416
1417
1418
        typename SUBNET
        >
    class repeat
    {
        static_assert(num > 0, "You can't have a layer repeated 0 times.");
    public:
        typedef SUBNET subnet_type;
        typedef typename SUBNET::input_type input_type;
1419
        const static size_t num_layers = (REPEATED_LAYER<SUBNET>::num_layers-SUBNET::num_layers)*num + SUBNET::num_layers;
1420
1421
        const static unsigned int sample_expansion_factor = SUBNET::sample_expansion_factor;

1422
        typedef REPEATED_LAYER<impl::repeat_input_layer> repeated_layer_type;
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473

        repeat(
        ) : 
            details(num)
        {
        }

        size_t num_repetitions (
        ) const { return num; }

        const repeated_layer_type& get_repeated_layer (
            size_t i 
        ) const
        { 
            DLIB_CASSERT(i < num_repetitions(), "");
            return details[i]; 
        }

        repeated_layer_type& get_repeated_layer (
            size_t i 
        ) 
        { 
            DLIB_CASSERT(i < num_repetitions(), "");
            return details[i]; 
        }

        repeat(const repeat&) = default;
        repeat(repeat&&) = default;
        repeat& operator=(repeat&&) = default;
        repeat& operator=(const repeat&) = default;

        template <template<typename> class T, typename U>
        repeat(
            const repeat<num,T,U>& item
        ) : 
            subnetwork(item.subnetwork)
        {
            for (auto&& d : item.details)
                details.emplace_back(d);
        }

        template <typename T, typename ...U>
        repeat(
            T arg1,
            U ...args2
        ): 
            details(num, std::move(arg1)),
            subnetwork(std::move(args2)...)
        {
        }

1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
        template <typename ...T, typename ...U>
        repeat(
            decorator_repeat_group<T...>&& arg1,
            U ...args2
        ): 
            details(num, arg1.data),
            subnetwork(std::move(args2)...)
        {
        }

1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
        template <typename T, typename ...U>
        repeat(
            std::tuple<>,
            T arg1,
            U ...args2
        ): 
            details(num, std::move(arg1)),
            subnetwork(std::move(args2)...)
        {
        }

        template <typename input_iterator>
        void to_tensor (
            input_iterator ibegin,
            input_iterator iend,
            resizable_tensor& data
        ) const
        {
            subnetwork.to_tensor(ibegin,iend,data);
        }

        template <typename input_iterator>
        const tensor& operator() (
            input_iterator ibegin,
            input_iterator iend
        )
        {
            to_tensor(ibegin,iend,temp_tensor);
            return forward(temp_tensor);
        }

        const tensor& operator() (const input_type& x)
        {
            return (*this)(&x, &x+1);
        }

        const tensor& forward(const tensor& x)
        {
            subnetwork.forward(x);
            details[details.size()-1].forward(subnetwork.get_output());
            for (long i = details.size()-2; i >= 0; --i)
                details[i].forward(details[i+1].get_output());
            return private_get_output();
        }

    private:
        tensor& private_get_output() const
        { 
            return details[0].private_get_output();
        }
        tensor& private_get_gradient_input() 
        { 
            return details[0].private_get_gradient_input();
        }
    public:
        const tensor& get_output() const 
        { 
            return details[0].get_output(); 
        }
        tensor& get_gradient_input() 
        { 
            return details[0].get_gradient_input();
        }

        template <typename solver_type>
1549
        void update(const tensor& x, sstack<solver_type> solvers, double step_size)
1550
        {
1551
            update(x,private_get_gradient_input(),solvers,step_size);
1552
1553
1554
        }

        template <typename solver_type>
1555
        void update(const tensor& x, const tensor& gradient_input, sstack<solver_type> solvers, double step_size)
1556
        {
1557
            const auto cnt = (REPEATED_LAYER<SUBNET>::num_layers-SUBNET::num_layers);
1558
1559
            if (details.size() > 1)
            {
1560
                details[0].update(details[1].get_output(), gradient_input, solvers,step_size);
1561
1562
1563
                for (size_t i = 1; i < details.size(); ++i)
                {
                    if (i+1 < details.size())
1564
                        details[i].update(details[i+1].get_output(), details[i-1].get_final_data_gradient(), solvers.pop(cnt*i),step_size);
1565
                    else
1566
                        details[i].update(subnetwork.get_output(), details[i-1].get_final_data_gradient(), solvers.pop(cnt*i),step_size);
1567
1568
1569
1570
                }
            }
            else
            {
1571
                details[0].update(subnetwork.get_output(), gradient_input, solvers,step_size);
1572
            }
1573
            subnetwork.update(x, details.back().get_final_data_gradient(), solvers.pop(cnt*details.size()),step_size);
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
        }

        const subnet_type& subnet() const { return subnetwork; }
        subnet_type& subnet() { return subnetwork; }

        void clean()
        {
            temp_tensor.clear();
            subnetwork.clean();
            for (auto&& d : details)
                d.clean();
        }

        friend void serialize(const repeat& item, std::ostream& out)
        {
            int version = 1;
            serialize(version, out);
            serialize(item.details, out);
            serialize(item.subnetwork, out);
        }

        friend void deserialize(repeat& item, std::istream& in)
        {
            int version = 0;
            deserialize(version, in);
            if (version != 1)
                throw serialization_error("Unexpected version found while deserializing dlib::repeat.");
            deserialize(item.details, in);
            deserialize(item.subnetwork, in);
        }

    private:

        template <typename T, typename U, typename E>
        friend class add_layer;
        template <typename T, bool is_first, typename E>
        friend class dimpl::subnet_wrapper;
        template <unsigned long T, typename U, typename E>
        friend class add_tag_layer;
        template <template<typename> class T, typename U>
        friend class add_skip_layer;
        template <size_t N, template<typename> class L, typename S>
        friend class repeat;

        bool this_layer_requires_forward_output(
        ) 
        { 
            return details[0].this_layer_requires_forward_output(); 
        } 

        void disable_output_and_gradient_getters (
        ) 
        { 
            details[0].disable_output_and_gradient_getters();
        }


        std::vector<repeated_layer_type> details; 
        subnet_type subnetwork;

        // temp_tensor doesn't logically contribute to the state of this class.
        // It is here only to void needing to reallocate it over and over.
        resizable_tensor temp_tensor;
    };

    template <
        size_t num,
1641
        template<typename> class REPEATED_LAYER, 
1642
1643
        typename SUBNET
        >
1644
    struct is_nonloss_layer_type<repeat<num,REPEATED_LAYER,SUBNET>> : std::true_type {};
1645

1646
1647
// ----------------------------------------------------------------------------------------

1648
// This version of add_tag_layer handles the special case where the subnetwork being given
1649
1650
1651
1652
1653
// is just an input layer object.
    template <unsigned long ID, typename INPUT_LAYER, typename enabled>
    class add_tag_layer
    {
    public:
Davis King's avatar
Davis King committed
1654
1655
        typedef INPUT_LAYER subnet_type;
        typedef typename subnet_type::input_type input_type;
1656
        const static size_t num_layers = 1;
Davis King's avatar
Davis King committed
1657
        const static unsigned int sample_expansion_factor = subnet_type::sample_expansion_factor;
1658
1659
1660
        static_assert(sample_expansion_factor >= 1,
            "The input layer can't produce fewer output tensors than there are inputs.");

1661
        add_tag_layer():cached_output_ptr(nullptr),gradient_input_is_stale(true) {}
1662

1663
1664
        add_tag_layer(const add_tag_layer&) = default;
        add_tag_layer& operator=(const add_tag_layer&) = default;
1665
1666
        add_tag_layer(add_tag_layer&& item) : add_tag_layer() { swap(item); }
        add_tag_layer& operator=(add_tag_layer&& item) { swap(item); return *this; }
1667
1668
1669
1670

        template <typename T, typename E>
        add_tag_layer(
            const add_tag_layer<ID,T,E>& item
1671
1672
1673
1674
1675
        ) : input_layer(item.subnet()), 
            cached_output(item.cached_output),
            cached_output_ptr(nullptr),
            grad_final(item.grad_final),
            gradient_input_is_stale(item.gradient_input_is_stale)
1676
1677
1678
1679
1680
1681
        {}

        template <typename ...T>
        add_tag_layer(
            T ...args
        ) : 
1682
1683
1684
            input_layer(std::move(args)...),
            cached_output_ptr(nullptr),
            gradient_input_is_stale(true)
1685
1686
1687
        {
        }

1688
1689
1690
1691
1692
1693
1694
        add_tag_layer (
            std::tuple<>
        ) : 
            cached_output_ptr(nullptr),
            gradient_input_is_stale(true)
        {}

1695
1696
        template <typename input_iterator>
        void to_tensor (
1697
1698
            input_iterator ibegin,
            input_iterator iend,
1699
1700
1701
            resizable_tensor& data
        ) const
        {
1702
            input_layer.to_tensor(ibegin,iend,data);
1703
1704
1705
1706
        }

        template <typename input_iterator>
        const tensor& operator() (
1707
            input_iterator ibegin, 
1708
1709
1710
1711
            input_iterator iend
        )
        {
            input_layer.to_tensor(ibegin,iend,cached_output);
1712
            cached_output_ptr = nullptr;
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
            return get_output();
        }

        const tensor& operator() (const input_type& x)
        {
            return (*this)(&x, &x+1);
        }

        const tensor& forward(const tensor& x)
        {
1723
1724
1725
1726
1727
1728
1729
1730
1731
            // If this tag is the first layer in one of the sub networks inside a repeat
            // layer then we don't want it to be creating copies of x.  This is because, we
            // can just hold a pointer to x since the way repeat is constructed guarantees
            // that x will have a lifetime larger than this pointer. 
            if (is_same_type<INPUT_LAYER, impl::repeat_input_layer>::value)
                cached_output_ptr = const_cast<tensor*>(&x);
            else
                cached_output = x;
            gradient_input_is_stale = true;
1732
1733
1734
1735
1736
            return get_output();
        }

        const tensor& get_output() const 
        { 
1737
1738
1739
1740
            if (cached_output_ptr)
                return *cached_output_ptr;
            else
                return cached_output; 
1741
1742
        }

1743
        const tensor& get_final_data_gradient(
1744
        ) const { return grad_final; }
1745

1746
1747
        tensor& get_gradient_input() 
        { 
1748
1749
            if (!have_same_dimensions(get_output(), grad_final) ||
                gradient_input_is_stale)
1750
            {
1751
1752
1753
                grad_final.copy_size(get_output());
                grad_final = 0;
                gradient_input_is_stale = false;
1754
            }
1755
            return grad_final; 
1756
1757
1758
        }

        template <typename solver_type>
1759
1760
1761
1762
1763
        void update(
            const tensor& /*x*/, 
            sstack<solver_type> /*solvers*/,
            double /*step_size*/
        )
1764
1765
1766
1767
        {
            // nothing to update
        }

1768
        template <typename solver_type>
1769
1770
1771
1772
1773
1774
        void update(
            const tensor& /*x*/,
            const tensor& /*gradient_input*/,
            sstack<solver_type> /*solvers*/,
            double /*step_size*/
        )
1775
1776
1777
1778
        {
            // nothing to update
        }

Davis King's avatar
Davis King committed
1779
1780
        const subnet_type& subnet() const { return input_layer; }
        subnet_type& subnet() { return input_layer; }
1781
1782
1783

        void clean()
        {
1784
            grad_final.clear();
1785
            cached_output.clear();
1786
            cached_output_ptr = 0;
1787
1788
        }

1789
1790
1791
1792
1793
1794
        friend void serialize(const add_tag_layer& item, std::ostream& out)
        {
            int version = 1;
            serialize(version, out);
            serialize(item.input_layer, out);
            serialize(item.cached_output, out);
1795
1796
            serialize(item.grad_final, out);
            serialize(item.gradient_input_is_stale, out);
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
        }

        friend void deserialize(add_tag_layer& item, std::istream& in)
        {
            int version = 0;
            deserialize(version, in);
            if (version != 1)
                throw serialization_error("Unexpected version found while deserializing dlib::add_tag_layer.");
            deserialize(item.input_layer, in);
            deserialize(item.cached_output, in);
1807
1808
1809
            deserialize(item.grad_final, in);
            deserialize(item.gradient_input_is_stale, in);
            item.cached_output_ptr = nullptr;
1810
1811
        }

1812
1813
    private:

1814
1815
1816
1817
1818
1819
1820
1821
        template <typename T, typename U, typename E>
        friend class add_layer;
        template <typename T, bool is_first, typename E>
        friend class dimpl::subnet_wrapper;
        template <unsigned long T, typename U, typename E>
        friend class add_tag_layer;
        template <template<typename> class T, typename U>
        friend class add_skip_layer;
1822
1823
        template <size_t N, template<typename> class L, typename S>
        friend class repeat;
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841

        // You woudln't put a tag on a layer if you didn't want to access its forward
        // outputs.  So this is always true.
        bool this_layer_requires_forward_output(
        ) { return true; } 

        void disable_output_and_gradient_getters (
        ) 
        { 
            // This should never happen because only inplace layers call
            // disable_output_and_gradient_getters(), however, putting a tag layer right
            // before an inplace layer basically means you don't want the following layer
            // to operate in place.  So the inplace layer should turn itself into an
            // out-of-place layer and not call disable_output_and_gradient_getters(). 
            DLIB_CASSERT(false,"This should never happen");
        }

        tensor& private_get_output() const
1842
        { return const_cast<tensor&>(get_output()); }
1843
1844
1845
        tensor& private_get_gradient_input() 
        { return get_gradient_input(); }

1846
1847
1848
1849
        void swap(add_tag_layer& item)
        {
            std::swap(input_layer, item.input_layer);
            std::swap(cached_output, item.cached_output);
1850
1851
1852
            std::swap(cached_output_ptr, item.cached_output_ptr);
            std::swap(grad_final, item.grad_final);
            std::swap(gradient_input_is_stale, item.gradient_input_is_stale);
1853
1854
        }

Davis King's avatar
Davis King committed
1855
        subnet_type input_layer;
1856
        resizable_tensor cached_output;
1857
1858
1859
        tensor* cached_output_ptr;
        resizable_tensor grad_final;
        bool gradient_input_is_stale;
1860
1861
1862
1863
    };

    template <unsigned long ID, typename U, typename E>
    struct is_nonloss_layer_type<add_tag_layer<ID,U,E>> : std::true_type {};
1864
1865
1866
1867
1868
1869


// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

Davis King's avatar
Davis King committed
1870
    template <typename LOSS_DETAILS, typename SUBNET>
Davis King's avatar
Davis King committed
1871
    class add_loss_layer;
1872
1873
1874
1875
1876

    class no_label_type
    {
    private:
        // We don't want anyone making these no_label_type objects.  They are here only to
Davis King's avatar
Davis King committed
1877
        // allow add_loss_layer::label_type and dnn_trainer::label_type to exist which avoids
Davis King's avatar
Davis King committed
1878
        // needing to overload add_loss_layer and dnn_trainer for supervised an unsupervised
1879
1880
        // losses.  It also can be a type to use in template metaprogramming to indicate
        // "no label".  So here we make the constructor private with the exception that
Davis King's avatar
Davis King committed
1881
        // add_loss_layer objects can make it (again, just to simplify add_loss_layer's
1882
        // implementation).
1883
        no_label_type(){};
Davis King's avatar
Davis King committed
1884
        template <typename LOSS_DETAILS, typename SUBNET> friend class add_loss_layer;
1885
        template < typename net_type, typename solver_type > friend class dnn_trainer; 
1886
1887
1888
1889
    };

// ----------------------------------------------------------------------------------------

Davis King's avatar
Davis King committed
1890
    template <typename LOSS_DETAILS, typename SUBNET>
Davis King's avatar
Davis King committed
1891
    class add_loss_layer
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
    {
        template <typename T, typename enabled=void>
        struct get_loss_layer_label_type
        {
            typedef no_label_type type;
        };
        template <typename T>
        struct get_loss_layer_label_type<T,typename std::enable_if<sizeof(typename T::label_type)!=0>::type>
        {
            typedef typename T::label_type type;
        };

    public:
        typedef LOSS_DETAILS loss_details_type;
Davis King's avatar
Davis King committed
1906
1907
        typedef SUBNET subnet_type;
        typedef typename subnet_type::input_type input_type;
1908
        // Note that the loss layer doesn't count as an additional layer.
Davis King's avatar
Davis King committed
1909
1910
        const static size_t num_layers = subnet_type::num_layers;
        const static unsigned int sample_expansion_factor = subnet_type::sample_expansion_factor;
1911
1912
        typedef typename get_loss_layer_label_type<LOSS_DETAILS>::type label_type;

1913
1914
        static_assert(is_nonloss_layer_type<SUBNET>::value, 
            "SUBNET must be of type add_layer, add_skip_layer, or add_tag_layer."); 
1915
1916
1917
1918
        static_assert(sample_expansion_factor == LOSS_DETAILS::sample_expansion_factor,
            "The loss layer and input layer must agree on the sample_expansion_factor.");


1919
        add_loss_layer() {};
Davis King's avatar
Davis King committed
1920
1921
        add_loss_layer(const add_loss_layer&) = default;
        add_loss_layer& operator=(const add_loss_layer&) = default;
1922
1923
        add_loss_layer(add_loss_layer&& item) : add_loss_layer() { swap(item); }
        add_loss_layer& operator=(add_loss_layer&& item) { swap(item); return *this; }
1924
1925

        template <typename T, typename U>
Davis King's avatar
Davis King committed
1926
1927
        add_loss_layer(
            const add_loss_layer<T,U>& item
1928
1929
        ) : 
            loss(item.loss_details()),
Davis King's avatar
Davis King committed
1930
            subnetwork(item.subnet())
1931
1932
1933
        {}

        template <typename ...T>
Davis King's avatar
Davis King committed
1934
        add_loss_layer(
1935
1936
1937
1938
            const LOSS_DETAILS& layer_det, 
            T&& ...args
        ) : 
            loss(layer_det), 
Davis King's avatar
Davis King committed
1939
            subnetwork(std::forward<T>(args)...)
1940
1941
1942
1943
        {
        }

        template <typename ...T>
Davis King's avatar
Davis King committed
1944
        add_loss_layer(
1945
1946
1947
1948
            LOSS_DETAILS&& layer_det, 
            T&& ...args
        ) : 
            loss(std::move(layer_det)), 
Davis King's avatar
Davis King committed
1949
            subnetwork(std::forward<T>(args)...)
1950
1951
1952
1953
        {
        }

        template <typename ...T>
Davis King's avatar
Davis King committed
1954
        add_loss_layer(
1955
1956
            T ...args
        ) : 
Davis King's avatar
Davis King committed
1957
            subnetwork(std::move(args)...)
1958
        {
1959
1960
1961
1962
1963
1964
1965
1966
1967
        }

        template <typename input_iterator>
        void to_tensor (
            input_iterator ibegin,
            input_iterator iend,
            resizable_tensor& data
        ) const
        {
Davis King's avatar
Davis King committed
1968
            subnetwork.to_tensor(ibegin,iend,data);
1969
1970
1971
1972
1973
1974
1975
1976
        }

        template <typename output_iterator>
        void operator() (
            const tensor& x, 
            output_iterator obegin
        )
        {
Davis King's avatar
Davis King committed
1977
1978
            subnetwork.forward(x);
            const dimpl::subnet_wrapper<subnet_type> wsub(subnetwork);
1979
            loss.to_label(x, wsub, obegin);
1980
1981
1982
1983
1984
1985
1986
1987
1988
        }

        template <typename input_iterator, typename output_iterator>
        void operator() (
            input_iterator ibegin,
            input_iterator iend,
            output_iterator obegin
        )
        {
1989
1990
            to_tensor(ibegin,iend,temp_tensor);
            (*this)(temp_tensor, obegin);
1991
1992
1993
1994
1995
1996
1997
1998
        }

        const label_type& operator() (const input_type& x)
        {
            (*this)(&x, &x+1, &temp_label);
            return temp_label;
        }

1999
        template <typename iterable_type>
2000
        std::vector<label_type> operator() (
2001
            const iterable_type& data,
2002
2003
2004
            size_t batch_size = 128
        )
        {
2005
            std::vector<label_type> results(std::distance(data.begin(), data.end()));
2006
2007
2008
2009
2010
2011
2012
2013
2014
            auto o = results.begin();
            for (auto i = data.begin(); i < data.end(); i+=batch_size, o+=batch_size)
            {
                auto end = std::min(i+batch_size, data.end());
                (*this)(i, end, o);
            }
            return results;
        }

2015
2016
2017
2018
2019
2020
        template <typename label_iterator>
        double compute_loss (
            const tensor& x,
            label_iterator lbegin 
        )
        {
Davis King's avatar
Davis King committed
2021
2022
            subnetwork.forward(x);
            dimpl::subnet_wrapper<subnet_type> wsub(subnetwork);
2023
2024
            return loss.compute_loss(x, lbegin, wsub);
        }
2025
2026
2027
2028
2029
2030
2031
2032

        template <typename input_iterator, typename label_iterator>
        double compute_loss (
            input_iterator ibegin,
            input_iterator iend,
            label_iterator lbegin 
        )
        {
2033
2034
2035
2036
2037
2038
2039
2040
            to_tensor(ibegin,iend,temp_tensor);
            return compute_loss(temp_tensor, lbegin);
        }

        double compute_loss (
            const tensor& x
        )
        {
Davis King's avatar
Davis King committed
2041
2042
            subnetwork.forward(x);
            dimpl::subnet_wrapper<subnet_type> wsub(subnetwork);
2043
            return loss.compute_loss(x, wsub);
2044
2045
2046
2047
2048
2049
2050
2051
        }

        template <typename input_iterator>
        double compute_loss (
            input_iterator ibegin,
            input_iterator iend
        )
        {
2052
2053
2054
2055
2056
2057
2058
2059
            to_tensor(ibegin,iend,temp_tensor);
            return compute_loss(temp_tensor);
        }

        template <typename label_iterator, typename solver_type>
        double update (
            const tensor& x,
            label_iterator lbegin,
2060
2061
            sstack<solver_type> solvers,
            double step_size
2062
2063
        )
        {
Davis King's avatar
Davis King committed
2064
2065
            subnetwork.forward(x);
            dimpl::subnet_wrapper<subnet_type> wsub(subnetwork);
2066
            double l = loss.compute_loss(x, lbegin, wsub);
2067
            subnetwork.update(x, solvers, step_size);
2068
            return l;
2069
2070
2071
2072
2073
2074
2075
        }

        template <typename input_iterator, typename label_iterator, typename solver_type>
        double update (
            input_iterator ibegin,
            input_iterator iend,
            label_iterator lbegin,
2076
2077
            sstack<solver_type> solvers,
            double step_size
2078
2079
        )
        {
2080
            to_tensor(ibegin,iend,temp_tensor);
2081
            return update(temp_tensor, lbegin, solvers, step_size);
2082
2083
2084
2085
2086
        }

        template <typename solver_type>
        double update (
            const tensor& x,
2087
2088
            sstack<solver_type> solvers,
            double step_size
2089
2090
        )
        {
Davis King's avatar
Davis King committed
2091
2092
            subnetwork.forward(x);
            dimpl::subnet_wrapper<subnet_type> wsub(subnetwork);
2093
            double l = loss.compute_loss(x, wsub);
2094
            subnetwork.update(x, solvers, step_size);
2095
2096
2097
2098
2099
2100
2101
            return l;
        }

        template <typename input_iterator, typename solver_type>
        double update (
            input_iterator ibegin,
            input_iterator iend,
2102
2103
            sstack<solver_type> solvers,
            double step_size
2104
2105
        )
        {
2106
            to_tensor(ibegin,iend,temp_tensor);
2107
            return update(temp_tensor, solvers, step_size);
2108
2109
        }

Davis King's avatar
Davis King committed
2110
2111
        const subnet_type& subnet() const { return subnetwork; }
        subnet_type& subnet() { return subnetwork; }
2112
2113
2114
2115
2116
2117
2118
        const loss_details_type& loss_details() const { return loss; }
        loss_details_type& loss_details() { return loss; }

        void clean (
        )
        {
            temp_tensor.clear();
2119
            subnetwork.clean();
2120
2121
        }

2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
        friend void serialize(const add_loss_layer& item, std::ostream& out)
        {
            int version = 1;
            serialize(version, out);
            serialize(item.loss, out);
            serialize(item.subnetwork, out);
        }

        friend void deserialize(add_loss_layer& item, std::istream& in)
        {
            int version = 0;
            deserialize(version, in);
            if (version != 1)
                throw serialization_error("Unexpected version found while deserializing dlib::add_loss_layer.");
            deserialize(item.loss, in);
            deserialize(item.subnetwork, in);
        }

2140
2141
    private:

2142
2143
2144
2145
2146
2147
        void swap(add_loss_layer& item)
        {
            std::swap(loss, item.loss);
            std::swap(subnetwork, item.subnetwork);
        }

2148
        loss_details_type loss;
Davis King's avatar
Davis King committed
2149
        subnet_type subnetwork;
2150
2151
2152
2153
2154
2155
2156
2157
2158

        // These two objects don't logically contribute to the state of this object.  They
        // are here to prevent them from being reallocated over and over.
        label_type temp_label;
        resizable_tensor temp_tensor;
    };


    template <typename T, typename U>
Davis King's avatar
Davis King committed
2159
    struct is_loss_layer_type<add_loss_layer<T,U>> : std::true_type {};
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170

// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

    namespace impl
    {
        template <unsigned int i, typename T>
        struct layer_helper
        {
            static T& makeT();
Davis King's avatar
Davis King committed
2171
            using next_type = typename std::remove_reference<decltype(makeT().subnet())>::type;
2172
2173
2174
            using type = typename layer_helper<i-1,next_type>::type;
            static type& layer(T& n)
            {
Davis King's avatar
Davis King committed
2175
                return layer_helper<i-1,next_type>::layer(n.subnet());
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
            }
        };
        template <typename T>
        struct layer_helper<0,T>
        {
            using type = T;
            static type& layer(T& n)
            {
                return n;
            }
        };

        template <template<typename> class Match, typename T, unsigned int i, typename enabled = void>
        struct layer_helper_match
        {
            static T& makeT();
Davis King's avatar
Davis King committed
2192
            using next_type = typename std::remove_reference<decltype(makeT().subnet())>::type;
2193
2194
2195
            using type = typename layer_helper_match<Match,next_type,i>::type;
            static type& layer(T& n)
            {
Davis King's avatar
Davis King committed
2196
                return layer_helper_match<Match,next_type,i>::layer(n.subnet());
2197
2198
            }
        };
Davis King's avatar
Davis King committed
2199
        // This overload catches add_layer and add_loss_layer templates.
2200
2201
        template <template<typename> class Match, typename T, unsigned int i>
        struct layer_helper_match<Match,T,i,
Davis King's avatar
Davis King committed
2202
            typename std::enable_if<std::is_same<const T,const  Match<typename T::subnet_type>>::value>::type>
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
        {
            using type = typename layer_helper<i,T>::type;
            static type& layer(T& n)
            {
                return layer_helper<i,T>::layer(n);
            }
        };
        // This overload catches input templates.
        template <template<typename> class Match, typename T, unsigned int i>
        struct layer_helper_match<Match,T,i,
            typename std::enable_if<std::is_same<const T,const  Match<typename T::input_type>>::value>::type>
        {
            using type = typename layer_helper<i,T>::type;
            static type& layer(T& n)
            {
                return layer_helper<i,T>::layer(n);
            }
        };
Davis King's avatar
Davis King committed
2221
        // This overload catches subnet_wrapper templates.
2222
2223
2224
        template <template<typename> class Match, typename T, unsigned int i>
        struct layer_helper_match<Match,T,i,
            typename std::enable_if<std::is_same<const typename T::wrapped_type, 
Davis King's avatar
Davis King committed
2225
                                                 const Match<typename T::wrapped_type::subnet_type>>::value>::type>
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
        {
            using type = typename layer_helper<i,T>::type;
            static type& layer(T& n)
            {
                return layer_helper<i,T>::layer(n);
            }
        };
    }

    template <unsigned int i, typename T>
    typename impl::layer_helper<i,T>::type& layer (T& n) 
    {
        return impl::layer_helper<i,T>::layer(n);
    }

    template <template<typename> class Match, typename T>
    typename impl::layer_helper_match<Match,T,0>::type& layer (T& n) 
    {
        return impl::layer_helper_match<Match,T,0>::layer(n);
    }

    template <template<typename> class Match, unsigned int i, typename T>
    typename impl::layer_helper_match<Match,T,i>::type& layer (T& n) 
    {
        return impl::layer_helper_match<Match,T,i>::layer(n);
    }

// ----------------------------------------------------------------------------------------

Davis King's avatar
Davis King committed
2255
    template <template<typename> class TAG_TYPE, typename SUBNET>
Davis King's avatar
Davis King committed
2256
    class add_skip_layer
2257
2258
    {
    public:
Davis King's avatar
Davis King committed
2259
2260
        typedef SUBNET subnet_type;
        typedef typename subnet_type::input_type input_type;
2261
        const static size_t num_layers = subnet_type::num_layers;
Davis King's avatar
Davis King committed
2262
        const static unsigned int sample_expansion_factor = subnet_type::sample_expansion_factor;
2263
2264
2265
        static_assert(sample_expansion_factor >= 1,
            "The input layer can't produce fewer output tensors than there are inputs.");

Davis King's avatar
Davis King committed
2266
2267
2268
2269
2270
        add_skip_layer() = default;
        add_skip_layer(const add_skip_layer&) = default;
        add_skip_layer(add_skip_layer&&) = default;
        add_skip_layer& operator=(add_skip_layer&&) = default;
        add_skip_layer& operator=(const add_skip_layer&) = default;
2271
2272

        template <typename T>
Davis King's avatar
Davis King committed
2273
2274
        add_skip_layer(
            const add_skip_layer<TAG_TYPE,T>& item
Davis King's avatar
Davis King committed
2275
        ) : subnetwork(item.subnet())
2276
2277
2278
        {}

        template <typename ...T>
Davis King's avatar
Davis King committed
2279
        add_skip_layer(
2280
2281
            T ...args
        ) : 
Davis King's avatar
Davis King committed
2282
            subnetwork(std::move(args)...) 
2283
2284
2285
2286
2287
        {
        }

        template <typename input_iterator>
        void to_tensor (
2288
2289
            input_iterator ibegin,
            input_iterator iend,
2290
2291
2292
            resizable_tensor& data
        ) const
        {
Davis King's avatar
Davis King committed
2293
            subnetwork.to_tensor(ibegin,iend,data);
2294
2295
2296
2297
2298
2299
2300
2301
        }

        template <typename input_iterator>
        const tensor& operator() (
            input_iterator ibegin,
            input_iterator iend
        )
        {
Davis King's avatar
Davis King committed
2302
2303
            subnetwork(ibegin,iend);
            return layer<TAG_TYPE>(subnetwork).get_output();
2304
2305
2306
2307
        }

        const tensor& operator() (const input_type& x)
        {
Davis King's avatar
Davis King committed
2308
2309
            subnetwork(x);
            return layer<TAG_TYPE>(subnetwork).get_output();
2310
2311
2312
2313
        }

        const tensor& forward(const tensor& x)
        {
Davis King's avatar
Davis King committed
2314
2315
            subnetwork.forward(x);
            return layer<TAG_TYPE>(subnetwork).get_output();
2316
2317
2318
2319
        }

        const tensor& get_output() const 
        { 
Davis King's avatar
Davis King committed
2320
            return layer<TAG_TYPE>(subnetwork).get_output();
2321
2322
2323
2324
        }

        tensor& get_gradient_input() 
        { 
Davis King's avatar
Davis King committed
2325
            return layer<TAG_TYPE>(subnetwork).get_gradient_input();
2326
2327
        }

2328
2329
2330
2331
2332
2333
        const tensor& get_final_data_gradient(
        ) const 
        { 
            return subnetwork.get_final_data_gradient(); 
        }

2334
        template <typename solver_type>
2335
        void update(const tensor& x, sstack<solver_type> solvers)
2336
        {
2337
            subnetwork.update(x,solvers);
2338
2339
        }

2340
        template <typename solver_type>
2341
        void update(const tensor& x, const tensor& gradient_input, sstack<solver_type> solvers)
2342
        {
2343
            subnetwork.update(x,gradient_input,solvers);
2344
2345
        }

Davis King's avatar
Davis King committed
2346
        const subnet_type& subnet() const 
2347
        { 
Davis King's avatar
Davis King committed
2348
            return subnetwork; 
2349
2350
        }

Davis King's avatar
Davis King committed
2351
        subnet_type& subnet() 
2352
        { 
Davis King's avatar
Davis King committed
2353
            return subnetwork; 
2354
2355
2356
2357
        }

        void clean()
        {
Davis King's avatar
Davis King committed
2358
            subnetwork.clean();
2359
2360
        }

2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
        friend void serialize(const add_skip_layer& item, std::ostream& out)
        {
            int version = 1;
            serialize(version, out);
            serialize(item.subnetwork, out);
        }

        friend void deserialize(add_skip_layer& item, std::istream& in)
        {
            int version = 0;
            deserialize(version, in);
            if (version != 1)
                throw serialization_error("Unexpected version found while deserializing dlib::add_skip_layer.");
            deserialize(item.subnetwork, in);
        }

2377
2378
    private:

2379
2380
2381
2382
2383
2384
2385
2386
        template <typename T, typename U, typename E>
        friend class add_layer;
        template <typename T, bool is_first, typename E>
        friend class dimpl::subnet_wrapper;
        template <unsigned long T, typename U, typename E>
        friend class add_tag_layer;
        template <template<typename> class T, typename U>
        friend class add_skip_layer;
2387
2388
        template <size_t N, template<typename> class L, typename S>
        friend class repeat;
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400

        bool this_layer_requires_forward_output(
        ) { return layer<TAG_TYPE>(subnetwork).this_layer_requires_forward_output(); } 

        void disable_output_and_gradient_getters (
        ) { layer<TAG_TYPE>(subnetwork).disable_output_and_gradient_getters(); }

        tensor& private_get_output() const
        { return layer<TAG_TYPE>(subnetwork).private_get_output(); }
        tensor& private_get_gradient_input() 
        { return layer<TAG_TYPE>(subnetwork).private_get_gradient_input(); }

Davis King's avatar
Davis King committed
2401
        subnet_type subnetwork;
2402
2403
    };
    template <template<typename> class T, typename U>
Davis King's avatar
Davis King committed
2404
2405
    struct is_nonloss_layer_type<add_skip_layer<T,U>> : std::true_type {};

Davis King's avatar
Davis King committed
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
    template <typename SUBNET> using tag1  = add_tag_layer< 1, SUBNET>;
    template <typename SUBNET> using tag2  = add_tag_layer< 2, SUBNET>;
    template <typename SUBNET> using tag3  = add_tag_layer< 3, SUBNET>;
    template <typename SUBNET> using tag4  = add_tag_layer< 4, SUBNET>;
    template <typename SUBNET> using tag5  = add_tag_layer< 5, SUBNET>;
    template <typename SUBNET> using tag6  = add_tag_layer< 6, SUBNET>;
    template <typename SUBNET> using tag7  = add_tag_layer< 7, SUBNET>;
    template <typename SUBNET> using tag8  = add_tag_layer< 8, SUBNET>;
    template <typename SUBNET> using tag9  = add_tag_layer< 9, SUBNET>;
    template <typename SUBNET> using tag10 = add_tag_layer<10, SUBNET>;

    template <typename SUBNET> using skip1  = add_skip_layer< tag1, SUBNET>;
    template <typename SUBNET> using skip2  = add_skip_layer< tag2, SUBNET>;
    template <typename SUBNET> using skip3  = add_skip_layer< tag3, SUBNET>;
    template <typename SUBNET> using skip4  = add_skip_layer< tag4, SUBNET>;
    template <typename SUBNET> using skip5  = add_skip_layer< tag5, SUBNET>;
    template <typename SUBNET> using skip6  = add_skip_layer< tag6, SUBNET>;
    template <typename SUBNET> using skip7  = add_skip_layer< tag7, SUBNET>;
    template <typename SUBNET> using skip8  = add_skip_layer< tag8, SUBNET>;
    template <typename SUBNET> using skip9  = add_skip_layer< tag9, SUBNET>;
    template <typename SUBNET> using skip10 = add_skip_layer<tag10, SUBNET>;
2427
2428
2429
2430
2431

// ----------------------------------------------------------------------------------------

    namespace timpl
    {
2432
        inline void fill_with_gassuan_random_numbers (
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
            tensor& t,
            dlib::rand& rnd,
            double sigma = 1
        )
        {
            float* data = t.host();
            for (size_t i = 0; i < t.size(); ++i)
                data[i] = rnd.get_random_gaussian()*sigma;
        }

Davis King's avatar
Davis King committed
2443
        class test_layer_subnet 
2444
2445
        {
        public:
Davis King's avatar
Davis King committed
2446
            test_layer_subnet (
2447
2448
2449
2450
2451
2452
                dlib::rand& rnd_
            ) : rnd(rnd_) 
            {
                // Output and gradient_input have to have the same dimensions in each
                // layer.
                const long num_samples = rnd.get_random_32bit_number()%4+3;
2453
                const long k  = rnd.get_random_32bit_number()%4+2;
2454
2455
2456
                const long nr = rnd.get_random_32bit_number()%4+2;
                const long nc = rnd.get_random_32bit_number()%4+2;

2457
2458
                output.set_size(num_samples, k, nr, nc);
                gradient_input.set_size(num_samples, k, nr, nc);
2459
2460
2461
2462
2463
2464
2465
2466
2467

                // Use a non-zero initial gradient to make sure the layers add to it
                // rather than assign and blow away the initial value.
                fill_with_gassuan_random_numbers(gradient_input, rnd, 0.01);

                fill_with_gassuan_random_numbers(output, rnd);
            }


2468
            tensor& get_mutable_output() { return output; }
2469
            const tensor& get_output() const { return output; }
2470
            const tensor& private_get_output() const { return get_output(); }
Davis King's avatar
Davis King committed
2471
            const test_layer_subnet& subnet() const { init_sub(); return *subnetwork; }
2472
2473

            tensor& get_gradient_input() { return gradient_input; }
2474
            tensor& private_get_gradient_input() { return get_gradient_input(); }
Davis King's avatar
Davis King committed
2475
            test_layer_subnet& subnet() { init_sub(); return *subnetwork; }
2476
2477
2478
2479
2480



            unsigned long count_outputs() const
            {
Davis King's avatar
Davis King committed
2481
2482
                if (subnetwork)
                    return subnetwork->count_outputs() + output.size();
2483
2484
2485
2486
2487
2488
2489
2490
2491
                else
                    return output.size();
            }

            float& get_output_element(unsigned long i)
            {
                if (i < output.size())
                    return output.host()[i];
                else
Davis King's avatar
Davis King committed
2492
                    return subnet().get_output_element(i-output.size());
2493
2494
2495
2496
2497
2498
2499
            }

            float get_gradient_input_element(unsigned long i) const
            {
                if (i < gradient_input.size())
                    return gradient_input.host()[i];
                else
Davis King's avatar
Davis King committed
2500
                    return subnet().get_gradient_input_element(i-gradient_input.size());
2501
2502
2503
2504
2505
            }


        private:
            // We lazily initialize sub-layers as needed when someone tries to call
Davis King's avatar
Davis King committed
2506
            // subnet()
2507
2508
            void init_sub() const
            {
Davis King's avatar
Davis King committed
2509
2510
                if (!subnetwork)
                    subnetwork.reset(new test_layer_subnet(rnd));
2511
2512
2513
            }

            dlib::rand& rnd;
Davis King's avatar
Davis King committed
2514
            mutable std::unique_ptr<test_layer_subnet> subnetwork;
2515
2516
2517
2518
            resizable_tensor output;
            resizable_tensor gradient_input;
        };

2519
    }
2520

2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
    struct layer_test_results
    {
        layer_test_results() : was_good(true) {}
        explicit layer_test_results(const std::string& l) : log(l),was_good(false) {}

        std::string log;
        bool was_good;

        operator bool() const { return was_good; }
    };

    inline std::ostream& operator<< (std::ostream& out, const layer_test_results& item)
    {
        out << item.log;
        return out;
2536
2537
2538
2539
2540
    }

    template <
        typename layer_details_type
        >
Davis King's avatar
Davis King committed
2541
2542
2543
    layer_test_results impl_test_layer (
        layer_details_type l,
        const float base_eps 
2544
2545
2546
2547
    )
    {
        using namespace timpl;
        // Do some setup
2548
        running_stats<double> rs_data, rs_params;
2549
        dlib::rand rnd;
2550
2551
        std::ostringstream sout;
        for (int iter = 0; iter < 10; ++iter)
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
        {
            test_layer_subnet subnetwork(rnd);
            resizable_tensor output, out2, out3;
            // Run setup() and forward() as well to make sure any calls to subnet() have
            // happened before we start assuming we know how many data elements there are
            // (since we do a lazy layer creation thing based on calls to subnet() inside
            // test_layer_subnet).
            l.setup(subnetwork);
            impl::call_layer_forward(l, subnetwork, output);

            resizable_tensor input_grad;
            input_grad.copy_size(output);
            fill_with_gassuan_random_numbers(input_grad, rnd);


            // The f() we are computing gradients of is this thing.  It's value at the current
            // parameter and data values is:
            //sout << "f(data,params): " << dot(output, input_grad) << std::endl;

            // We are going to save a copy of the subnetwork.get_gradient_input() data before we do
            // backpropagation since the backward() function is supposed to *add* to the
            // gradients rather than overwrite them.  We will use this saved data to check if
            // that is the case.
            const unsigned long num_data_inputs = subnetwork.count_outputs();
            std::vector<float> initial_gradient_input(num_data_inputs);
            for (unsigned long i = 0; i < num_data_inputs; ++i)
                initial_gradient_input[i] = subnetwork.get_gradient_input_element(i);

2580

2581
2582
2583
            // Now tell the layer to compute all the gradients.  In the rest of this function
            // we will just be checking that these gradients were computed correctly by
            // comparing them to a central differences approximation.
2584
            resizable_tensor params_grad;
2585
2586
2587
            params_grad.copy_size(l.get_layer_params());
            // But first, set the params grad to something crazy so that it's very obvious if
            // it doesn't get fully assigned.
2588
            params_grad = std::numeric_limits<float>::infinity();
2589
            impl::call_layer_backward(l, output, input_grad, subnetwork, params_grad);
2590

2591
2592
2593
2594
2595
2596
            static_assert(impl::is_inplace_layer(l, subnetwork) == impl::has_inplace_backward(l, subnetwork),
                "Layer not defined correctly.  forward and backward methods must either both be in-place or both out-of-place. ");

            // Make sure the outputs of forward() and backward() are the same when they are run
            // in in-place mode.
            if (impl::is_inplace_layer(l, subnetwork))
2597
            {
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
                test_layer_subnet subnetwork2(rnd);
                layer_details_type ll(l);
                ll.setup(subnetwork2);
                resizable_tensor ip_out;
                impl::call_layer_forward(ll, subnetwork2, ip_out);
                impl::call_layer_forward(ll, subnetwork2, subnetwork2.get_mutable_output());
                const auto forward_error = max(abs(mat(ip_out) - mat(subnetwork2.get_output())));
                if (forward_error > 0.00001)
                {
                    using namespace std;
                    sout << "This layer is supposed to support in-place computations but the output of forward_inplace()\n";
                    sout << "changes when invoked in-place vs. out-of-place. The error was: " << forward_error << endl;
                    return layer_test_results(sout.str()); 
                }

                resizable_tensor params_grad;
                params_grad.copy_size(ll.get_layer_params());
                params_grad = std::numeric_limits<float>::infinity();

                resizable_tensor input_grad;
                input_grad.copy_size(ip_out);
                fill_with_gassuan_random_numbers(input_grad, rnd);
                resizable_tensor params_grad1, params_grad2, data_grad1, data_grad2;
                params_grad1 = params_grad;
                params_grad2 = params_grad;
                // Now call backward() and make sure it works as well.
                subnetwork2.get_gradient_input() = 9999;
                impl::call_layer_backward(ll, ip_out, input_grad, subnetwork2, params_grad1);
                data_grad1 = subnetwork2.get_gradient_input();

                subnetwork2.get_gradient_input() = mat(input_grad);
                impl::call_layer_backward(ll, ip_out, subnetwork2.get_gradient_input(), subnetwork2, params_grad2);
                data_grad2 = subnetwork2.get_gradient_input();
                if (params_grad.size() != 0)
                {
                    const auto backward_param_error = max(abs(mat(params_grad1) - mat(params_grad2)));
                    if (backward_param_error > 0.00001)
                    {
                        using namespace std;
                        sout << "This layer is supposed to support in-place computations but the output of backward_inplace()\n";
                        sout << "changes when invoked in-place vs. out-of-place. The error was: " << backward_param_error << endl;
                        return layer_test_results(sout.str()); 
                    }
                }
                const auto backward_data_error = max(abs(mat(data_grad1) - mat(data_grad2)));
                if (backward_data_error > 0.00001)
2644
2645
2646
                {
                    using namespace std;
                    sout << "This layer is supposed to support in-place computations but the output of backward_inplace()\n";
2647
                    sout << "changes when invoked in-place vs. out-of-place. The error was: " << backward_data_error << endl;
2648
2649
2650
                    return layer_test_results(sout.str()); 
                }
            }
2651

2652
2653
2654
            // ==================================================================
            // first validate the way the parameter gradients are computed
            for (unsigned long i = 0; i < params_grad.size(); ++i)
2655
            {
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
                layer_details_type l1(l);

                float eps = l1.get_layer_params().host()[i]*base_eps;
                if (eps == 0)
                    eps = base_eps;
                const float oldval = l1.get_layer_params().host()[i];
                l1.get_layer_params().host()[i] = oldval+eps;
                impl::call_layer_forward(l1, subnetwork, out2);
                l1.get_layer_params().host()[i] = oldval-eps;
                impl::call_layer_forward(l1, subnetwork, out3);
                l1.get_layer_params().host()[i] = oldval;

                // Compute a reference derivative via a central differences approximation and
                // compare it to the one output by the layer and make sure they match.
                double reference_derivative = (dot(out2,input_grad)-dot(out3, input_grad))/(2*eps);
                double output_derivative = params_grad.host()[i];
2672
2673
2674
2675
2676
                double relative_error;
                if (reference_derivative != 0)
                    relative_error = (reference_derivative - output_derivative)/(reference_derivative);
                else
                    relative_error = (reference_derivative - output_derivative);
2677
                double absolute_error = (reference_derivative - output_derivative);
2678
                rs_params.add(std::abs(relative_error));
Davis King's avatar
Davis King committed
2679
                if (std::abs(relative_error) > 0.05 && std::abs(absolute_error) > 0.006)
2680
2681
2682
2683
2684
                {
                    using namespace std;
                    sout << "Gradient error in parameter #" << i <<".  Relative error: "<< relative_error << endl;
                    sout << "expected derivative: " << reference_derivative << endl;
                    sout << "output derivative:   " << output_derivative << endl;
2685
                    sout << "iteration:           " << iter << endl;
2686
2687
2688
                    return layer_test_results(sout.str()); 
                }
            }
2689

2690
2691
2692
            // ==================================================================
            // now validate the data gradients
            for (unsigned long i = 0; i < num_data_inputs; ++i)
2693
            {
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
                const float oldval = subnetwork.get_output_element(i);
                float eps = oldval*base_eps;
                if (eps == 0)
                    eps = base_eps;
                subnetwork.get_output_element(i) = oldval+eps;
                impl::call_layer_forward(l, subnetwork, out2);
                subnetwork.get_output_element(i) = oldval-eps;
                impl::call_layer_forward(l, subnetwork, out3);
                subnetwork.get_output_element(i) = oldval;

                // Compute a reference derivative via a central differences approximation and
                // compare it to the one output by the layer and make sure they match.
                double reference_derivative = (dot(out2,input_grad)-dot(out3, input_grad))/(2*eps);
                double output_derivative = subnetwork.get_gradient_input_element(i);
                if (!impl::is_inplace_layer(l,subnetwork))
                    output_derivative -= initial_gradient_input[i];
2710
2711
2712
2713
2714
                double relative_error;
                if (reference_derivative != 0)
                    relative_error = (reference_derivative - output_derivative)/(reference_derivative);
                else
                    relative_error = (reference_derivative - output_derivative);
2715
                double absolute_error = (reference_derivative - output_derivative);
2716
                rs_data.add(std::abs(relative_error));
Davis King's avatar
Davis King committed
2717
                if (std::abs(relative_error) > 0.05 && std::abs(absolute_error) > 0.006)
2718
2719
2720
2721
2722
                {
                    using namespace std;
                    sout << "Gradient error in data variable #" << i <<".  Relative error: "<< relative_error << endl;
                    sout << "expected derivative: " << reference_derivative << endl;
                    sout << "output derivative:   " << output_derivative << endl;
2723
                    sout << "iteration:           " << iter << endl;
2724
2725
                    return layer_test_results(sout.str()); 
                }
2726
            }
2727
2728

        } // end for (int iter = 0; iter < 5; ++iter)
2729

2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
        if (rs_params.mean() > 0.003)
        {
            using namespace std;
            sout << "Average parameter gradient error is somewhat large at: "<< rs_params.mean() << endl;
            return layer_test_results(sout.str()); 
        }
        if (rs_data.mean() > 0.003)
        {
            using namespace std;
            sout << "Average data gradient error is somewhat large at: "<< rs_data.mean() << endl;
            return layer_test_results(sout.str()); 
        }

2743
        return layer_test_results();
2744
2745
    }

Davis King's avatar
Davis King committed
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
    template <
        typename layer_details_type
        >
    layer_test_results test_layer (
        layer_details_type l
    )
    {
        // Try a few different derivative step sizes to see if any work. 
        for (float base_eps = 0.0001; base_eps < 0.1; base_eps *= 2)
        {
            auto result = impl_test_layer(l, base_eps);
            if (result)
                return result;
        }
        // However, if none of the step sizes worked then try this one and probably result
        // in returning an error.
        return impl_test_layer(l, 0.01);
    }

2765
2766
2767
2768
// ----------------------------------------------------------------------------------------

}

2769
#endif // DLIB_DNn_CORE_H_
2770
2771