This repository has been archived by the owner on Jul 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 136
/
Copy pathLayer.swift
378 lines (344 loc) · 12.5 KB
/
Layer.swift
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
// Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import _Differentiation
import Foundation
#if TENSORFLOW_USE_STANDARD_TOOLCHAIN
import Numerics
#endif
public protocol Module: EuclideanDifferentiable, KeyPathIterable
where
TangentVector: VectorProtocol & ElementaryFunctions & PointwiseMultiplicative & KeyPathIterable
{
/// The input type of the layer.
associatedtype Input
/// The output type of the layer.
associatedtype Output: Differentiable
/// Returns the output obtained from applying the layer to the given input.
///
/// - Parameter input: The input to the layer.
/// - Returns: The output.
@differentiable(wrt: self)
func callAsFunction(_ input: Input) -> Output
/// Returns the output obtained from applying the layer to the given input.
///
/// - Parameter input: The input to the layer.
/// - Returns: The output.
@differentiable(wrt: self)
func forward(_ input: Input) -> Output
}
extension Module {
/// Returns the output obtained from applying the layer to the given input.
///
/// - Parameter input: The input to the layer.
/// - Returns: The output.
@differentiable(wrt: self)
public func forward(_ input: Input) -> Output {
return callAsFunction(input)
}
}
extension Module where Input: TensorProtocol, Output: DifferentiableTensorProtocol {
/// Returns the annotated output obtained from applying the layer to the
/// given input.
///
/// - Parameter input: The input to the layer.
/// - Returns: The annotated output.
@differentiable(wrt: self)
public func callAsFunction(_ input: Input) -> Output {
let activation = forward(input)
return annotated(activation)
}
/// Annotates `output`.
///
/// Note: Returns `output` if using a backend that does not support annotations.
///
/// - Parameter output: The output to the layer.
/// - Returns: The annotated output.
@differentiable
public func annotated(_ output: Output) -> Output {
let annotated = output.annotate("type=\(Self.self)")
return annotated
}
/// Returns the annotations obtained from applying the layer to the given input.
///
/// - Parameter input: The input to the layer.
/// - Returns: All collected annotations from the XLA graph.
public func summary(input: Input) -> String {
let output = self.callAsFunction(input)
return formatAnnotations(from: output)
}
/// Returns a formatted version of `tensor.annotations`.
///
/// - Parameter tensor: The output to the layer.
/// - Returns: A formatted summary of `tensor.annotations`.
private func formatAnnotations(from tensor: Output) -> String {
let rawAnnotations = tensor.annotations
if rawAnnotations == Device.defaultTFEager.annotationsAvailable {
return rawAnnotations
}
let lines = rawAnnotations.components(separatedBy: "\n")
if lines.count < 3 {
return ""
}
// Isolate layers.
let pattern = "\\s*shape=(.+)\\s+type=([^\\s]+)(\\s+.+=.+)?$"
let regex = try! NSRegularExpression(pattern: pattern)
let contents = lines.filter { $0.contains("shape=") }
.map { line -> String in
let nsrange = NSRange(line.startIndex..., in: line)
if let match = regex.firstMatch(in: line, range: nsrange) {
var content = ""
if let typeRange = Range(match.range(at: 2), in: line) {
let type = line[typeRange]
content += type
}
content += "\t\t\t"
if let shapeRange = Range(match.range(at: 1), in: line) {
let shape = line[shapeRange]
content += shape
}
content += "\t\t"
if let attributesRange = Range(match.range(at: 3), in: line) {
let attribute = line[attributesRange]
content += attribute
}
return content
} else {
return line
}
}
let formattedAnnotations = """
Layer Output Shape Attributes
=============================== ==================== ======================
\(contents.joined(separator: "\n"))
"""
return formattedAnnotations
}
}
/// A neural network layer.
///
/// Types that conform to `Layer` represent functions that map inputs to outputs. They may have an
/// internal state represented by parameters, such as weight tensors.
///
/// `Layer` instances define a differentiable `callAsFunction(_:)` method for mapping inputs to
/// outputs.
public protocol Layer: Module where Input: Differentiable {
/// Returns the output obtained from applying the layer to the given input.
///
/// - Parameter input: The input to the layer.
/// - Returns: The output.
@differentiable
func callAsFunction(_ input: Input) -> Output
@differentiable
func forward(_ input: Input) -> Output
}
extension Layer {
// Workaround for SR-13455: autodiff undefined symbol linker error.
@differentiable(wrt: self)
@differentiable
public func forward(_ input: Input) -> Output {
return callAsFunction(input)
}
}
extension Layer where Input: DifferentiableTensorProtocol, Output: DifferentiableTensorProtocol {
// Workaround for SR-13455: autodiff undefined symbol linker error.
@differentiable(wrt: self)
@differentiable
public func callAsFunction(_ input: Input) -> Output {
let activation = forward(input)
return annotated(activation)
}
}
/// An empty struct representing empty `TangentVector`s for parameterless layers.
public struct EmptyTangentVector: EuclideanDifferentiable, VectorProtocol, ElementaryFunctions,
PointwiseMultiplicative, KeyPathIterable
{
public typealias VectorSpaceScalar = Float
public typealias TangentVector = Self
public init() {}
public func adding(_ x: Float) -> EmptyTangentVector { self }
public mutating func add(_ x: Float) {}
public func subtracting(_ x: Float) -> EmptyTangentVector { self }
public mutating func subtract(_ x: Float) {}
public func scaled(by scalar: Float) -> EmptyTangentVector { self }
public mutating func scale(by scalar: Float) {}
}
/// A parameterless neural network layer.
///
/// The `TangentVector` of parameterless layers is always `EmptyTangentVector`.
public protocol ParameterlessLayer: Layer where TangentVector == EmptyTangentVector {
@differentiable
func callAsFunction(_ input: Input) -> Output
}
extension ParameterlessLayer {
public mutating func move(along direction: EmptyTangentVector) {}
public var differentiableVectorView: EmptyTangentVector { EmptyTangentVector() }
}
extension Layer {
/// Returns the inference output obtained from applying the layer to the given input.
///
/// - Parameter input: The input to the layer.
/// - Returns: The inference output.
public func inferring(from input: Input) -> Output {
withLearningPhase(LearningPhase.inference) { self(input) }
}
// TODO(TF-433, SR-11882): Remove this custom derivative when
// differentiation supports `rethrows` functions and currying.
@usableFromInline
@derivative(of: inferring(from:))
internal func _vjpInferring(from input: Input)
-> (
value: Output,
pullback: (Output.TangentVector)
-> (TangentVector, Input.TangentVector)
)
{
withLearningPhase(LearningPhase.inference) {
let (output, pullback) = appliedForBackpropagation(to: input)
return (output, { v in pullback(v) })
}
}
public typealias Backpropagator = (_ direction: Output.TangentVector)
-> (layerGradient: TangentVector, inputGradient: Input.TangentVector)
/// Returns the inference output and the backpropagation function obtained from applying the
/// layer to the given input.
///
/// - Parameter input: The input to the layer.
/// - Returns: A tuple containing the output and the backpropagation function. The
/// backpropagation function (a.k.a. backpropagator) takes a direction vector and returns the
/// gradients at the layer and at the input, respectively.
public func appliedForBackpropagation(to input: Input)
-> (output: Output, backpropagator: Backpropagator)
{
#if TENSORFLOW_USE_STANDARD_TOOLCHAIN
let (out, pullback) = _Differentiation.valueWithPullback(at: self, input) { layer, input in
return layer(input)
}
#else
let (out, pullback) = Swift.valueWithPullback(at: self, input) { layer, input in
return layer(input)
}
#endif
return (out, pullback)
}
}
extension Differentiable {
/// Returns the output computed by applying a sequence of layers to the previous layer's output,
/// except that the first layer's input is `self`.
///
/// - Parameters:
/// - l1: The first layer.
/// - l2: The second layer.
/// - Returns: The final layer's output after sequential application.
@differentiable
public func sequenced<L1: Layer, L2: Layer>(through l1: L1, _ l2: L2) -> L2.Output
where L1.Input == Self, L1.Output == L2.Input {
let o1 = l1(self)
return l2(o1)
}
/// Returns the output computed by applying a sequence of layers to the previous layer's output,
/// except that the first layer's input is `self`.
///
/// - Parameters:
/// - l1: The first layer.
/// - l2: The second layer.
/// - l3: The third layer.
/// - Returns: The final layer's output after sequential application.
@differentiable
public func sequenced<L1: Layer, L2: Layer, L3: Layer>(through l1: L1, _ l2: L2, _ l3: L3)
-> L3.Output
where L1.Input == Self, L1.Output == L2.Input, L2.Output == L3.Input {
let o1 = l1(self)
let o2 = l2(o1)
return l3(o2)
}
/// Returns the output computed by applying a sequence of layers to the previous layer's output,
/// except that the first layer's input is `self`.
///
/// - Parameters:
/// - l1: The first layer.
/// - l2: The second layer.
/// - l3: The third layer.
/// - l4: The fourth layer.
/// - Returns: The final layer's output after sequential application.
@differentiable
public func sequenced<L1: Layer, L2: Layer, L3: Layer, L4: Layer>(
through l1: L1, _ l2: L2, _ l3: L3, _ l4: L4
) -> L4.Output
where
L1.Input == Self, L1.Output == L2.Input, L2.Output == L3.Input,
L3.Output == L4.Input
{
let o1 = l1(self)
let o2 = l2(o1)
let o3 = l3(o2)
return l4(o3)
}
/// Returns the output computed by applying a sequence of layers to the previous layer's output,
/// except that the first layer's input is `self`.
///
/// - Parameters:
/// - l1: The first layer.
/// - l2: The second layer.
/// - l3: The third layer.
/// - l4: The third layer.
/// - l5: The fifth layer.
/// - Returns: The final layer's output after sequential application.
@differentiable
public func sequenced<L1: Layer, L2: Layer, L3: Layer, L4: Layer, L5: Layer>(
through l1: L1, _ l2: L2, _ l3: L3, _ l4: L4, _ l5: L5
) -> L5.Output
where
L1.Input == Self, L1.Output == L2.Input, L2.Output == L3.Input, L3.Output == L4.Input,
L4.Output == L5.Input
{
let o1 = l1(self)
let o2 = l2(o1)
let o3 = l3(o2)
let o4 = l4(o3)
return l5(o4)
}
/// Returns the output computed by applying a sequence of layers to the previous layer's output,
/// except that the first layer's input is `self`.
///
/// - Parameters:
/// - l1: The first layer.
/// - l2: The second layer.
/// - l3: The third layer.
/// - l4: The third layer.
/// - l5: The fifth layer.
/// - l6: The sixth layer.
/// - Returns: The final layer's output after sequential application.
@differentiable
public func sequenced<L1: Layer, L2: Layer, L3: Layer, L4: Layer, L5: Layer, L6: Layer>(
through l1: L1, _ l2: L2, _ l3: L3, _ l4: L4, _ l5: L5, _ l6: L6
) -> L6.Output
where
L1.Input == Self, L1.Output == L2.Input, L2.Output == L3.Input, L3.Output == L4.Input,
L4.Output == L5.Input, L5.Output == L6.Input
{
let o1 = l1(self)
let o2 = l2(o1)
let o3 = l3(o2)
let o4 = l4(o3)
let o5 = l5(o4)
return l6(o5)
}
}
/// A mutable, shareable, owning reference to a tensor.
public final class Parameter<Scalar: TensorFlowScalar> {
public var value: Tensor<Scalar>
public init(_ value: Tensor<Scalar>) {
self.value = value
}
}