/
Weights.scala
97 lines (77 loc) · 2.89 KB
/
Weights.scala
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
package com.thoughtworks.deeplearning.plugins
import com.thoughtworks.deeplearning.DeepLearning
import com.thoughtworks.deeplearning.DeepLearning.Tape
import com.thoughtworks.feature.{Factory, ImplicitApply, PartialApply}
import com.thoughtworks.future._
import com.thoughtworks.raii.asynchronous._
import com.thoughtworks.tryt.covariant.TryT
import scala.util.{Failure, Success}
import scalaz.syntax.functor._
import com.thoughtworks.continuation._
/** A plugin that enables [[Weight]] in neural networks.
*
* @author 杨博 (Yang Bo)
*/
trait Weights {
trait WeightApi {
protected type PartiallyAppliedOptimizer
/** @usecase def forward: Do[Tape[Data, Delta] ] = ???
*/
final def forward[SubtypeOfOptimizer](
implicit implicitApplyRest: ImplicitApply.Aux[PartiallyAppliedOptimizer, SubtypeOfOptimizer],
asOptimizer: SubtypeOfOptimizer <:< OptimizerApi { type Delta <: WeightApi.this.Delta })
: Do[Tape[Data, Delta]] = {
Do.now(
Tape[Data, Delta](
data, { doDelta: Do[Delta] =>
val doUpdate: Do[Unit] = doDelta.intransitiveFlatMap(backward(_))
val Future(TryT(continuation)) = doUpdate.run
continuation.map {
case Success(()) => ()
case Failure(e) => handleException(e)
}
}
))
}
/** @usecase def backward(delta: Delta): Do[Unit] = ???
*/
protected def backward[SubtypeOfOptimizer](delta: Delta)(
implicit implicitApplyRest: ImplicitApply.Aux[PartiallyAppliedOptimizer, SubtypeOfOptimizer],
asOptimizer: SubtypeOfOptimizer <:< OptimizerApi { type Delta <: WeightApi.this.Delta }): Do[Unit]
type Data
type Delta
protected def handleException(throwable: Throwable): Unit = ()
var data: Data
}
/** @template */
type Weight <: WeightApi
trait OptimizerApi {
type Delta
protected val originalDelta: Delta
def delta: Delta = originalDelta
}
/** @template */
type Optimizer <: OptimizerApi
trait ImplicitsApi {
implicit def weightDeepLearning[SubtypeOfWeight, Data0, Delta0, OriginalDeltaRest, SubtypeOfOptimizer](
implicit asWeight: SubtypeOfWeight <:<
WeightApi {
type Data = Data0
type Delta = Delta0
type PartiallyAppliedOptimizer = OriginalDeltaRest
},
implicitApplyRest: ImplicitApply.Aux[OriginalDeltaRest, SubtypeOfOptimizer],
asOptimizer: SubtypeOfOptimizer <:< OptimizerApi { type Delta = Delta0 }
): DeepLearning.Aux[SubtypeOfWeight, Data0, Delta0] = {
new DeepLearning[SubtypeOfWeight] {
override type Data = Data0
override type Delta = Delta0
override def forward(subtypeOfWeight: SubtypeOfWeight): Do[Tape[Data0, Delta0]] = {
asWeight(subtypeOfWeight).forward[SubtypeOfOptimizer]
}
}
}
}
/** @template */
type Implicits <: ImplicitsApi
}