-
-
Notifications
You must be signed in to change notification settings - Fork 77
/
layer.rs
1699 lines (1555 loc) · 65.5 KB
/
layer.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
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
170
171
172
173
174
175
176
177
178
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
206
207
208
209
210
211
212
213
214
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Provides the generics and interfaces for the specific Layers.
//!
//! See [Layers][layers]
//! [layers]: ../layers/index.html
use std::cmp;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::fs::File;
use std::io::{self, BufReader};
use std::path::Path;
use std::rc::Rc;
use std::sync::{Arc, RwLock};
use crate::capnp_util::*;
use crate::co::prelude::*;
use crate::juice_capnp::layer as capnp_layer;
use crate::juice_capnp::layer_config as capnp_layer_config;
use crate::juice_capnp::layer_config::layer_type as capnp_layer_type;
use crate::layers::*;
use crate::util::{ArcLock, LayerOps};
use crate::weight::WeightConfig;
#[derive(Debug)]
/// The generic Layer
pub struct Layer<B: IBackend> {
/// Identifies the Network
///
/// The name is mainly used for logging purposes.
pub name: String,
/// The configuration of the Layer
pub config: Box<LayerConfig>,
/// The [implementation][1] of the Layer.
/// [1]: ../layers/index.html
///
/// This is the part that does most of the work ([forward][2]/[backward][3]).
/// [2]: ./trait.ILayer.html#method.forward
/// [3]: ./trait.ILayer.html#method.backward
pub worker: Box<dyn ILayer<B>>,
backend: Rc<B>,
/// Determines if layer will skip computations for [backward][1] step.
/// [1]: ./trait.ILayer.html#method.backward
needs_backward: bool,
/// The vector that stores shared references to the weights in the form of blobs.
pub weights_data: Vec<ArcLock<SharedTensor<f32>>>,
/// The vector that stores shared references to the weights in the form of blobs.
pub weights_gradient: Vec<ArcLock<SharedTensor<f32>>>,
// contains all the learnable weights (does not include bias(?) and shared weights)
learnable_weights: Vec<ArcLock<SharedTensor<f32>>>,
// learning rate for each weight
weights_lr: Vec<Option<f32>>,
// weight decay for each weight
weights_weight_decay: Vec<Option<f32>>,
// display name for each weight
weights_display_names: Vec<String>,
/// Vector indicating whether to compute the diff of each weight blob.
///
/// You can safely ignore false values and always compute gradients
/// for all weights, but possibly with wasteful computation.
///
/// Can be used by some [Layer implementations][1] to optimize performance.
/// [1]: ../layers/index.html
weight_propagate_down: Vec<bool>,
/// References to all the input blobs of the layer.
pub input_blobs_data: Vec<ArcLock<SharedTensor<f32>>>,
/// References to all the input blobs of the layer.
pub input_blobs_gradient: Vec<ArcLock<SharedTensor<f32>>>,
/// Names for all the input blobs of the layer.
pub input_blob_names: Vec<String>,
input_need_backwards: Vec<bool>,
/// References to all the output blobs of the layer.
pub output_blobs_data: Vec<ArcLock<SharedTensor<f32>>>,
/// References to all the output blobs of the layer.
pub output_blobs_gradient: Vec<ArcLock<SharedTensor<f32>>>,
output_blob_names: Vec<String>,
/// The vector that indicates whether each output blob contributes to
/// the [loss][1] of the network and with which weight.
/// [1]: http://caffe.berkeleyvision.org/tutorial/loss.html
loss: Vec<f32>,
/// All the blobs of the layer that can be addressed by name.
///
/// Does not contain anonymous blobs.
pub blob_names: HashMap<String, (ArcLock<SharedTensor<f32>>, ArcLock<SharedTensor<f32>>)>,
}
impl<B: IBackend> Layer<B> {
/// Connect the layer to another layers and set up tensors for intermediate results and weights.
///
/// Connects to the outputs provided by other layers via the `registry`.
/// Adds output blobs to the layer and then adds them to the `registry`, so the next
/// layers can connect them as their inputs.
/// In the end it initializes the underlying [layer implementation][2].
///
/// [2]: ./trait.ILayer.html
///
/// Called during initialization of containter layers.
pub fn connect(
&mut self,
registry: &mut HashMap<String, (ArcLock<SharedTensor<f32>>, ArcLock<SharedTensor<f32>>)>,
weight_registry: &mut HashMap<
String,
(
ArcLock<SharedTensor<f32>>,
ArcLock<SharedTensor<f32>>,
Option<f32>,
Option<f32>,
),
>,
) {
// connect to all required inputs
for input_name in &self.config.inputs.clone() {
self.connect_input(input_name, registry)
}
// setup outputs
for (output_id, _) in self.config.outputs.clone().iter().rev().enumerate() {
self.append_output(output_id, registry);
}
let config = self.config.clone();
for (output_id, _) in self.config.outputs.clone().iter().rev().enumerate() {
self.append_weight(&config, weight_registry, 0, output_id);
}
// If the layer specifies that AutoTopBlobs() -> true and the LayerParameter
// specified fewer than the required number (as specified by
// exact_num_top_blobs() or min_output_blobs()), allocate them here.
let auto_output_blobs = self.worker.auto_output_blobs();
debug!("Layer {} - auto_output_blobs: {}", &self.name, &auto_output_blobs);
let min_output_blobs = self.worker.min_output_blobs();
let exact_num_output_blobs = self.worker.exact_num_output_blobs().unwrap_or(0);
if auto_output_blobs {
let needed_num_outputs = cmp::max(min_output_blobs, exact_num_output_blobs);
for _ in 0..(needed_num_outputs - self.output_blobs_data.len()) {
// Add "anonymous" output blobs -- do not add to registry
// as we don't want these blobs to be usable as input
// to other layers.
info!("Adding anonymous output blob for layer {}", &self.name);
self.create_anonymous_output();
}
}
self.worker.init(self.backend.clone());
self.reshape();
self.worker.resize_shared_workspace(self.backend.clone(), None);
for t in &self.output_blobs_data {
debug!("Layer {} - output shape: {:?}", self.name, t.read().unwrap().desc());
}
}
/// Append blob as [input blob][1] to the Layer.
/// [1]: ../layer/index.html
///
/// During network initalization the blobs will be appended to the Layers as per their
/// [LayerConfig][3]. It is also determined if a output blob skips backpropagation
/// from [LayerConfig.propagate_down][3] (see also [init_backprop][5]).
///
/// [3]: ../layer/struct.LayerConfig.html
/// [5]: #method.init_backprop
fn connect_input(
&mut self,
blob_name: &str,
available_blobs: &mut HashMap<String, (ArcLock<SharedTensor<f32>>, ArcLock<SharedTensor<f32>>)>,
) {
let input_id = self
.config
.inputs
.iter()
.position(|input_name| input_name == blob_name)
.unwrap();
if !available_blobs.contains_key(&*blob_name) {
error!(
"Unknown input blob {} (layer '{}', input_id: {})",
blob_name, self.name, input_id
);
}
info!("Input {:<15} -> Layer {:>15}", blob_name, self.name);
self.input_blob_names.push(blob_name.to_owned());
self.input_blobs_data.push(
available_blobs
.get(&*blob_name)
.expect(&format!("Unknown blob name {}", blob_name))
.0
.clone(),
);
self.input_blobs_gradient.push(
available_blobs
.get(&*blob_name)
.expect(&format!("Unknown blob name {}", blob_name))
.1
.clone(),
);
// available_blobs.remove(&*blob_name);
let mut propagate_down = true;
// Check if the backpropagation on input_id should be skipped
if !self.config.propagate_down.is_empty() {
propagate_down = self.config.propagate_down[input_id];
}
let need_backward = propagate_down;
self.input_need_backwards.push(need_backward);
}
/// Append blob as [output blob][1] to the Layer.
/// [1]: ../layer/index.html
///
/// During network initalization the blobs will be appended to the Layers as per their
/// [LayerConfig][2]. It is also determined if computations can be done in-place, in which
/// no additional Blob will be allocated.</br>
/// Finally, the new blob will be added to the registry, so that the other layers can
/// connect it as their input.
/// [2]: ../layer/struct.LayerConfig.html
fn append_output(
&mut self,
output_id: usize,
registry: &mut HashMap<String, (ArcLock<SharedTensor<f32>>, ArcLock<SharedTensor<f32>>)>,
) {
let layer_config = &self.config;
let blob_name = layer_config.output(output_id).unwrap().clone();
let blob_data: ArcLock<SharedTensor<f32>>;
let blob_gradient: ArcLock<SharedTensor<f32>>;
if layer_config.input(output_id).is_some() && *layer_config.input(output_id).unwrap() == blob_name {
info!("Layer {:<15} -> Output {:>15} (in-place)", layer_config.name, blob_name);
blob_data = registry[&blob_name].0.clone();
blob_gradient = registry[&blob_name].1.clone();
} else if registry.contains_key(&blob_name) {
// If we are not doing in-place computation but have duplicated blobs, raise an
// error.
error!("Top blob {} produced by multiple sources.", blob_name);
return;
} else {
{
info!("Layer {:<15} -> Output {:>15}", self.name, blob_name);
info!("Output {} = {}", output_id, blob_name);
}
let backend: Rc<dyn IBackend<F = B::F>> = self.backend.clone();
blob_data = Arc::new(RwLock::new(SharedTensor::new(&[1, 1, 1]))); // [1,1,1] for CUDA
blob_gradient = Arc::new(RwLock::new(SharedTensor::new(&[1, 1, 1])));
// [1,1,1] for CUDA
}
self.output_blob_names.push(blob_name.clone());
self.output_blobs_data.push(blob_data.clone());
self.output_blobs_gradient.push(blob_gradient.clone());
self.blob_names
.insert(blob_name.clone(), (blob_data.clone(), blob_gradient.clone()));
registry.insert(blob_name.clone(), (blob_data.clone(), blob_gradient.clone()));
}
/// Append anonymous blob as [output blob][1] to the Layer.
/// [1]: ../layer/index.html
///
/// [Layer implementations][2] may request creation of anonymous output blobs
/// via [auto_output_blobs][3]. Since the blobs are not named, other layers can
/// not use them as their input blobs.
/// [2]: ./trait.ILayer.html
/// [3]: ./trait.ILayer.html#method.auto_output_blobs
fn create_anonymous_output(&mut self) {
let blob_name = "(automatic)".to_owned();
info!("{} -> {}", self.name, blob_name);
let backend: Rc<dyn IBackend<F = B::F>> = self.backend.clone();
let output_data = Arc::new(RwLock::new(SharedTensor::new(&[1, 1, 1]))); // [1,1,1] for CUDA
let output_gradient = Arc::new(RwLock::new(SharedTensor::new(&[1, 1, 1]))); // [1,1,1] for CUDA
self.output_blobs_data.push(output_data);
self.output_blobs_gradient.push(output_gradient);
}
fn append_weight(
&mut self,
layer_config: &LayerConfig,
registry: &mut HashMap<
String,
(
ArcLock<SharedTensor<f32>>,
ArcLock<SharedTensor<f32>>,
Option<f32>,
Option<f32>,
),
>,
layer_id: usize,
weight_id: usize,
) {
if self.worker.auto_weight_blobs() {
info!("Layer {} - appending weight", &layer_config.name);
let weights_len = self.weights_data.len();
let weight_name = if weights_len > weight_id {
layer_config.param(weight_id).unwrap().name.clone()
} else {
"".to_owned()
};
// use weight_name (or weight_id as a fallback) as display_name
let display_name = if !weight_name.is_empty() {
weight_name.clone()
} else {
format!("{}-{}", self.name, weight_id)
};
self.weights_display_names.push(display_name.clone());
// create name for registry
let registry_name = format!("SHARED_WEIGHT_{}", display_name);
// add to tracking vectors
let net_weight_id = weights_len;
let output_data = self.output_blobs_data[weight_id].read().unwrap();
debug!(
"Layer {} - creating weight and gradient of size {:?}",
&layer_config.name,
output_data.desc()
);
let weight_data = Arc::new(RwLock::new(SharedTensor::new(output_data.desc())));
let weight_bias = Arc::new(RwLock::new(SharedTensor::new(output_data.desc())));
let weight_gradient = Arc::new(RwLock::new(SharedTensor::new(output_data.desc())));
let weight_bias_gradient = Arc::new(RwLock::new(SharedTensor::new(output_data.desc())));
self.weights_data.push(weight_data.clone());
// Add Bias
self.weights_data.push(weight_bias.clone());
self.weights_gradient.push(weight_gradient.clone());
// Add Bias
self.weights_gradient.push(weight_bias_gradient.clone());
let mut weight_config = &WeightConfig::default();
if layer_config.params_len() > weight_id {
weight_config = layer_config.param(weight_id).unwrap();
}
// This layer "owns" this weight blob -- it is either anonymous
// (i.e., not given a weight_name) or explicitly given a name that we
// haven't already seen.
if weight_name.is_empty() || !registry.contains_key(®istry_name) {
// self.weight_owners.push(None);
if !weight_name.is_empty() {
registry.insert(
weight_name.clone(),
(
weight_data.clone(),
weight_gradient.clone(),
weight_config.lr_mult,
weight_config.decay_mult,
),
);
}
let learnable_weight_id = self.learnable_weights.len();
self.learnable_weights.push(weight_data.clone());
// self.learnable_weight_ids.push(learnable_weight_id);
self.weights_lr.push(weight_config.lr_mult);
self.weights_weight_decay.push(weight_config.decay_mult);
} else {
// Named weight blob with name we've seen before: share weights
let (shared_weight_data, shared_weight_gradient, shared_lr, shared_decay_mult) =
registry.get(®istry_name).unwrap().clone();
info!("Sharing weight blob '{}'", weight_name.clone());
// can only share parameters if both have same lr_mult
if let Some(lr_mult) = weight_config.lr_mult {
if let Some(owner_lr_mult) = shared_lr {
if !lr_mult.eq(&owner_lr_mult) {
error!("Shared param '{}' has mismatched lr_mult.", weight_name.clone());
}
} else {
// this is the first shared instance that has a lr_mult value so we take that
registry.remove(®istry_name).unwrap();
registry.insert(
registry_name.clone(),
(
shared_weight_data.clone(),
shared_weight_gradient.clone(),
weight_config.lr_mult,
shared_decay_mult,
),
);
}
}
// can only share weights if both have same decay_mult
if let Some(decay_mult) = weight_config.decay_mult {
if let Some(owner_decay_mult) = shared_decay_mult {
if !decay_mult.eq(&owner_decay_mult) {
error!("Shared param '{}' has mismatched decay_mult.", weight_name.clone());
}
} else {
// this is the first shared instance that has a decay_mult value so we take that
registry.remove(®istry_name).unwrap();
registry.insert(
registry_name,
(
shared_weight_data.clone(),
shared_weight_gradient.clone(),
shared_lr,
weight_config.decay_mult,
),
);
}
}
}
}
}
fn reshape(&mut self) {
match self.is_using_in_place() {
false => {
self.worker.reshape(
self.backend.clone(),
&mut self.input_blobs_data,
&mut self.input_blobs_gradient,
&mut self.weights_data,
&mut self.weights_gradient,
&mut self.output_blobs_data,
&mut self.output_blobs_gradient,
);
}
true => {
self.worker.reshape(
self.backend.clone(),
&mut vec![],
&mut vec![],
&mut self.weights_data,
&mut self.weights_gradient,
&mut self.output_blobs_data,
&mut self.output_blobs_gradient,
);
}
}
}
/// Initializes layer for [backpropagation][1]
/// [1]: https://en.wikipedia.org/wiki/Backpropagation
///
/// Go through all the blobs of a layer to determine which blobs contribute to the
/// loss of the next layer. We can skip backward computation for blobs that don't contribute
/// to the loss.
/// If all of the blobs skip backpropagation we set a flag to skip backpropagation
/// of the whole layer.
pub fn init_backprop(&mut self, blobs_under_loss: &mut HashSet<String>, blobs_skip_backp: &mut HashSet<String>) {
let mut layer_contributes_loss = false;
let mut layer_skip_propagate_down = true;
for (output_id, _) in self.output_blobs_data.iter().enumerate() {
let blob_name = self.output_blob_names.get(output_id);
// layer is a loss layer or under a loss layer
if self.loss(output_id).is_some() || blob_name.is_some() && blobs_under_loss.contains(blob_name.unwrap()) {
layer_contributes_loss = true;
}
// layer is not marked to skip backpropagation
if blob_name.is_none() || blob_name.is_some() && !blobs_skip_backp.contains(blob_name.unwrap()) {
layer_skip_propagate_down = false;
}
// layer contributes loss to some
if layer_contributes_loss && !layer_skip_propagate_down {
break;
}
}
// If this layer can skip backward computation, also all his input blobs
// don't need backpropagation
if self.needs_backward && layer_skip_propagate_down {
self.needs_backward = false;
for (input_id, _) in self.input_blobs_data.iter().enumerate() {
self.input_need_backwards[input_id] = false;
}
}
// layer doesn't contribute loss so it does not need to be backpropagated
if !layer_contributes_loss {
self.needs_backward = false;
}
{
info!("{} needs backward computation: {}", self.name, self.needs_backward);
}
for (input_id, input_name) in self.input_blob_names.iter().enumerate() {
if layer_contributes_loss {
blobs_under_loss.insert(input_name.clone());
} else {
self.input_need_backwards[input_id] = false;
}
if !self.input_need_backwards[input_id] {
blobs_skip_backp.insert(input_name.clone());
}
}
}
/// Set [backpropagation][1] flags to force this layer to backpropagate.
/// [1]: https://en.wikipedia.org/wiki/Backpropagation
///
/// Is executed during Network initalization if [NetworkConfig][2].force_backward is true.
/// Forcing backpropagation is useful for debugging.
pub fn init_force_backward(&mut self) {
self.needs_backward = true;
for (input_id, _) in self.input_need_backwards.clone().iter().enumerate() {
self.input_need_backwards[input_id] = *self
.input_need_backwards
.get(input_id)
.unwrap_or(&self.worker.allow_force_backward(input_id));
}
for (weight_id, _) in self.weights_data.clone().iter().enumerate() {
self.set_weight_propagate_down(weight_id, true);
}
}
/// Expose the internal inputs of a container layer.
fn expose_inputs(&mut self) {
if let Some(inputs) = self.worker.inputs_data() {
self.input_blobs_data = inputs;
}
if let Some(gradients) = self.worker.inputs_gradients() {
self.input_blobs_gradient = gradients;
}
}
/// Expose the internal outputs of a container layer.
fn expose_outputs(&mut self) {
if let Some(outputs) = self.worker.outputs_data() {
self.output_blobs_data = outputs;
}
if let Some(gradients) = self.worker.outputs_gradients() {
self.output_blobs_gradient = gradients;
}
}
/// Uses the underlying layer implementation to compute a forward step.
///
/// See [ILayer.forward](./trait.ILayer.html#method.forward)
pub fn forward(&mut self, inputs: &[ArcLock<SharedTensor<f32>>]) -> Vec<ArcLock<SharedTensor<f32>>> {
debug!("LAYER: {:?}", &self.name);
for (input_i, input) in inputs.iter().enumerate() {
let reshaped_shape = self.input_blobs_data[input_i].read().unwrap().desc().clone();
self.input_blobs_data[input_i] = input.clone();
// reshape input tensor to the reshaped shape
let old_shape = self.input_blobs_data[input_i].read().unwrap().desc().clone();
if old_shape.size() != reshaped_shape.size() {
panic!(
"Input Shape Mismatch\nExpected {:?}\nActual {:?}",
reshaped_shape, old_shape
);
}
self.input_blobs_data[input_i]
.write()
.unwrap()
.reshape(&reshaped_shape)
.unwrap();
}
let forward_time = timeit_loops!(1, {
if self.is_using_in_place() {
self.worker
.forward(&self.backend, &[], &self.weights_data, &mut self.output_blobs_data);
} else {
self.worker.forward(
&self.backend,
&self.input_blobs_data,
&self.weights_data,
&mut self.output_blobs_data,
);
}
});
debug!("{:<15} - Forward time: {:.5} ms", &self.name, forward_time / 0.001);
self.output_blobs_data.clone()
}
/// Uses the underlying layer implementation to compute a backward step.
///
/// See [ILayer.backward](./trait.ILayer.html#method.backward)
pub fn backward(&mut self, output_gradients: &[ArcLock<SharedTensor<f32>>]) -> Vec<ArcLock<SharedTensor<f32>>> {
if self.needs_backward {
let input_gradients = self.backward_input(output_gradients);
self.backward_parameters();
input_gradients
} else {
vec![]
}
}
/// Calculate the gradient w.r.t. input.
///
/// This method is mostly used when doing backpropagation.
pub fn backward_input(
&mut self,
output_gradients: &[ArcLock<SharedTensor<f32>>],
) -> Vec<ArcLock<SharedTensor<f32>>> {
for (output_i, output) in output_gradients.iter().enumerate() {
self.output_blobs_gradient[output_i] = output.clone();
}
if self.is_using_in_place() {
self.worker.backward_input(
&self.backend,
&self.weights_data,
&[],
&[],
&self.input_blobs_data,
&mut self.input_blobs_gradient,
)
} else {
self.worker.backward_input(
&self.backend,
&self.weights_data,
&self.output_blobs_data,
&self.output_blobs_gradient,
&self.input_blobs_data,
&mut self.input_blobs_gradient,
)
}
self.input_blobs_gradient.clone()
}
/// Calculate the gradient w.r.t. parameters.
///
/// "Parameters" here refers to weights and also possibly bias, depending on the layer.
///
/// This method is mostly used when doing backpropagation.
pub fn backward_parameters(&mut self) {
self.worker.backward_parameters(
&self.backend,
&self.output_blobs_data,
&self.output_blobs_gradient,
&self.input_blobs_data,
&mut self.weights_gradient,
)
}
/// Synchronize the layers backend.
pub fn synchronize(&self) {
self.backend.synchronize().unwrap();
}
/// Updates the [weights][1] with the weight update computed by the [Solver][2].
/// [1]: https://en.wikipedia.org/wiki/Synaptic_weight
/// [2]: ../solver/struct.Solver.html
///
/// Updating the weights is the last step of computing a [Solver][2] minibatch.
/// The update value is computed in previous steps according to the [learning rate policy][3]
///
/// [3]: ../solver/enum.LRPolicy.html
pub fn update_weights<SolverB: IBackend + crate::util::SolverOps<f32>>(&mut self, backend: &SolverB) {
// PERF: allocate this scalar once
let shared_a = crate::util::native_scalar(-1f32);
for (weight_gradient, weight_data) in self
.learnable_weights_gradients()
.iter()
.zip(&mut self.learnable_weights_data())
{
backend
.axpy(
&shared_a,
&weight_gradient.read().unwrap(),
&mut weight_data.write().unwrap(),
)
.unwrap();
}
}
/// Clears the [weights][1] gradients and zero-inits them.
/// [1]: https://en.wikipedia.org/wiki/Synaptic_weight
///
/// The gradients for the weights accumulate over the backpropagation steps of
/// a [Solver][2] minibatch and are cleared between each minibatch
/// to start over with a clean slate.
///
/// [2]: ../solver/struct.Solver.html
pub fn clear_weights_gradients(&mut self) {
for weight_gradient in &mut self.learnable_weights_gradients().iter() {
let filler = crate::weight::FillerType::Constant { value: 0f32 };
filler.fill(&mut weight_gradient.write().unwrap());
}
}
/// Serialize the Layer and it's weights to a Cap'n Proto file at the specified path.
///
/// You can find the capnp schema [here](../../../../capnp/juice.capnp).
///
/// ```
/// # #[cfg(feature = "native")]
/// # mod native {
/// # use std::rc::Rc;
/// # use juice::layer::*;
/// # use juice::layers::*;
/// # use juice::util;
/// # pub fn test() {
/// #
/// let mut net_cfg = SequentialConfig::default();
/// // ... set up network ...
/// let cfg = LayerConfig::new("network", net_cfg);
///
/// let native_backend = Rc::new(util::native_backend());
/// let mut layer = Layer::from_config(native_backend, &cfg);
/// // ... do stuff with the layer ...
/// // ... and save it
/// layer.save("mynetwork").unwrap();
/// #
/// # }}
/// #
/// # #[cfg(not(feature = "native"))]
/// # mod native {
/// # pub fn test() {}
/// # }
/// #
/// # fn main() {
/// # if cfg!(feature = "native") {
/// # crate::native::test();
/// # }
/// # }
/// ```
pub fn save<P: AsRef<Path>>(&mut self, path: P) -> io::Result<()> {
let path = path.as_ref();
let ref mut out = File::create(path)?;
let mut message = ::capnp::message::Builder::new_default();
{
let mut layer = message.init_root::<capnp_layer::Builder>();
self.write_capnp(&mut layer);
}
::capnp::serialize_packed::write_message(out, &message).unwrap();
Ok(())
}
/// Read a Cap'n Proto file at the specified path and deserialize the Layer inside it.
///
/// You can find the capnp schema [here](../../../../capnp/juice.capnp).
///
/// ```
/// # extern crate juice;
/// # extern crate coaster;
/// # #[cfg(feature = "native")]
/// # mod native {
/// # use std::rc::Rc;
/// # use juice::layer::*;
/// # use juice::layers::*;
/// # use juice::util;
/// use coaster::prelude::*;
/// # pub fn test() {
///
/// let native_backend = Rc::new(util::native_backend());
/// # let mut net_cfg = SequentialConfig::default();
/// # let cfg = LayerConfig::new("network", net_cfg);
/// # let mut layer = Layer::from_config(native_backend.clone(), &cfg);
/// # layer.save("mynetwork").unwrap();
/// // Load layer from file "mynetwork"
/// let layer = Layer::<Backend<Native>>::load(native_backend, "mynetwork").unwrap();
/// #
/// # }}
/// #
/// # #[cfg(not(feature = "native"))]
/// # mod native {
/// # pub fn test() {}
/// # }
/// #
/// # fn main() {
/// # if cfg!(feature = "native") {
/// # crate::native::test();
/// # }
/// # }
/// ```
pub fn load<LB: IBackend + LayerOps<f32> + 'static, P: AsRef<Path>>(
backend: Rc<LB>,
path: P,
) -> io::Result<Layer<LB>> {
let path = path.as_ref();
let ref mut file = File::open(path)?;
let mut reader = BufReader::new(file);
let message_reader =
::capnp::serialize_packed::read_message(&mut reader, ::capnp::message::ReaderOptions::new()).unwrap();
let read_layer = message_reader.get_root::<capnp_layer::Reader>().unwrap();
let name = read_layer.get_name().unwrap().to_owned();
let layer_config = LayerConfig::read_capnp(read_layer.get_config().unwrap());
let mut layer = Layer::from_config(backend, &layer_config);
layer.name = name;
let read_weights = read_layer.get_weights_data().unwrap();
let names = layer.learnable_weights_names();
let weights_data = layer.learnable_weights_data();
let native_backend = Backend::<Native>::default().unwrap();
for (i, (name, weight)) in names.iter().zip(weights_data).enumerate() {
for j in 0..read_weights.len() {
let capnp_weight = read_weights.get(i as u32);
if capnp_weight.get_name().unwrap() != name {
continue;
}
let mut weight_lock = weight.write().unwrap();
let capnp_tensor = capnp_weight.get_tensor().unwrap();
let mut shape = Vec::new();
let capnp_shape = capnp_tensor.get_shape().unwrap();
for k in 0..capnp_shape.len() {
shape.push(capnp_shape.get(k) as usize)
}
weight_lock.reshape(&shape).unwrap();
let native_slice = weight_lock
.write_only(native_backend.device())
.unwrap()
.as_mut_slice::<f32>();
let data = capnp_tensor.get_data().unwrap();
for k in 0..data.len() {
native_slice[k as usize] = data.get(k);
}
}
}
Ok(layer)
}
/// Sets whether the layer should compute gradients w.r.t. a
/// weight at a particular index given by `weight_id`.
///
/// See [`weight_propagate_down`][1]
/// ./struct.Layer.html
pub fn set_weight_propagate_down(&mut self, weight_id: usize, value: bool) {
if self.weight_propagate_down.len() <= weight_id {
self.weight_propagate_down.resize(weight_id + 1, true);
}
self.weight_propagate_down[weight_id] = value;
}
/// Returns `true` when the layer is using in-place computation.
///
/// For a layer to use in-place computation it needs to support it via `compute_in_place`
/// and the names of the first input and output tensor have to match.
pub fn is_using_in_place(&self) -> bool {
self.worker.compute_in_place()
&& self.input_blob_names.get(0).is_some()
&& self.output_blob_names.get(0).is_some()
&& self.input_blob_names[0] == self.output_blob_names[0]
}
/// Returns the names of all the input blobs.
pub fn input_blob_names(&self) -> &[String] {
&self.input_blob_names
}
/// Returns the [loss weight][1] associated with the weight blob
/// with id `weight_id`.
/// [1]: http://caffe.berkeleyvision.org/tutorial/loss.html
pub fn loss(&self, weight_id: usize) -> Option<&f32> {
self.loss.get(weight_id)
}
/// Returns all the learnable weights in the layer.
///
/// If the layer is a container layer it will return all the weights of the
/// layers inside it.
pub fn learnable_weights_data(&self) -> Vec<ArcLock<SharedTensor<f32>>> {
if let Some(weights) = self.worker.learnable_weights() {
weights
} else {
self.weights_data.clone()
}
}
/// Returns the gradients for all the learnable weights in the layer.
///
/// If the layer is a container layer it will return all the gradients of the
/// layers inside it.
pub fn learnable_weights_gradients(&self) -> Vec<ArcLock<SharedTensor<f32>>> {
if let Some(gradients) = self.worker.learnable_weights_gradients() {
gradients
} else {
self.weights_gradient.clone()
}
}
/// Returns the names of all the learnable weights in the layer.
///
/// If the layer is a container layer it will return all the names of the
/// layers inside it.
pub fn learnable_weights_names(&self) -> Vec<String> {
if let Some(names) = self.worker.learnable_weights_names() {
names
} else {
self.weights_display_names.clone()
}
}
/// Returns the learning rate for all the learnable weights in the layer.
///
/// If the layer is a container layer it will return all learning rates of the
/// layers inside it.
pub fn learnable_weights_lr(&self) -> Vec<Option<f32>> {
if let Some(lr) = self.worker.learnable_weights_lr() {
lr
}
// else { self.weights_lr.clone() }
else {
self.learnable_weights_data()
.iter()
.map(|_| Some(1f32))
.collect::<Vec<_>>()
}
}
}
#[allow(unsafe_code)]
unsafe impl<B: IBackend> Send for Layer<B> {}
impl<'a, B: IBackend> CapnpWrite<'a> for Layer<B> {
type Builder = capnp_layer::Builder<'a>;
/// Write the Layer into a capnp message.
fn write_capnp(&self, builder: &mut Self::Builder) {
builder.set_name(&self.name);
{
let mut layer_config = builder.reborrow().init_config();
self.config.write_capnp(&mut layer_config);
}
{
let native_backend = Backend::<Native>::default().unwrap();
let mut weights = builder
.reborrow()
.init_weights_data(self.learnable_weights_names().len() as u32);
let names = self.learnable_weights_names();
let weights_data = self.learnable_weights_data();
for (i, (name, weight)) in names.iter().zip(weights_data).enumerate() {
let mut capnp_weight = weights.reborrow().get(i as u32);
capnp_weight.set_name(name);
let weight_lock = weight.write().unwrap();
let mut tensor = capnp_weight.init_tensor();
{
let mut tensor_shape = tensor.reborrow().init_shape(weight_lock.desc().len() as u32);
for (i, dim) in weight_lock.desc().iter().enumerate() {
tensor_shape.set(i as u32, *dim as u64);
}
}
{
let native_slice = weight_lock.read(native_backend.device()).unwrap().as_slice::<f32>();
let mut tensor_data = tensor.reborrow().init_data(native_slice.len() as u32);
for (i, datum) in native_slice.iter().enumerate() {
tensor_data.set(i as u32, *datum);
}
}
}
}
}
}
impl<B: IBackend + LayerOps<f32> + crate::coblas::plugin::Copy<f32> + 'static> Layer<B> {
/// Creates a new Layer from a [LayerConfig][1].
/// [1]: ./struct.LayerConfig.html
pub fn from_config(backend: Rc<B>, config: &LayerConfig) -> Layer<B> {
let cl = config.clone();
let cfg = Box::<LayerConfig>::new(cl);
let mut layer = Layer {
name: cfg.name.clone(),
needs_backward: true,
weights_data: Vec::new(),
weights_gradient: Vec::new(),
learnable_weights: Vec::new(),
weight_propagate_down: Vec::new(),
weights_lr: Vec::new(),
weights_weight_decay: Vec::new(),
weights_display_names: Vec::new(),
input_blobs_data: Vec::new(),
input_blobs_gradient: Vec::new(),
input_blob_names: Vec::new(),
input_need_backwards: Vec::new(),
output_blobs_data: Vec::new(),
output_blobs_gradient: Vec::new(),
output_blob_names: Vec::new(),
loss: vec![1f32, 1f32, 1f32],
blob_names: HashMap::new(),
backend: backend.clone(),
worker: Layer::<B>::worker_from_config(backend, &cfg),
config: cfg,
};
layer.expose_inputs();
layer.expose_outputs();
layer
}
/// Helper for [from_config] to match a [LayerType][2] to its [implementation][3].
/// [1]: #method.from_config
/// [2]: ./enum.LayerType.html
/// [3]: ../layers/index.html
fn worker_from_config(backend: Rc<B>, config: &LayerConfig) -> Box<dyn ILayer<B>> {
match config.layer_type.clone() {