-
Notifications
You must be signed in to change notification settings - Fork 149
/
Copy pathTransformerLM.swift
350 lines (312 loc) · 13.4 KB
/
TransformerLM.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
// 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 TensorFlow
struct TimeDistributed: Layer {
var dense: Dense<Float>
init(_ wrapped: Dense<Float>) {
self.dense = wrapped
}
@differentiable(wrt: (self,input))
func callAsFunction(_ input: Tensor<Float>) -> Tensor<Float> {
let (batchSize, timeSteps, features) = (input.shape[0], input.shape[1], input.shape[2])
let reshaped = input.reshaped(to: [batchSize * timeSteps, features])
let output = dense(reshaped)
let outputFeatures = output.shape[1]
return output.reshaped(to: [batchSize, timeSteps, outputFeatures])
}
}
@differentiable
func timeDistributed(_ input: Tensor<Float>, _ weight: Tensor<Float>) -> Tensor<Float> {
let (batchSize, timeSteps, features) = (input.shape[0], input.shape[1], input.shape[2])
let reshaped = input.reshaped(to: [batchSize * timeSteps, features])
let output = matmul(reshaped, weight)
let outputFeatures = output.shape[1]
return output.reshaped(to: [batchSize, timeSteps, outputFeatures])
}
struct FeedForward: Layer {
var dense1: TimeDistributed
var dense2: TimeDistributed
init(size: Int, hidden: Int) {
dense1 = TimeDistributed(
Dense<Float>(inputSize: size, outputSize: hidden, activation: gelu))
dense2 = TimeDistributed(Dense<Float>(inputSize: hidden, outputSize: size))
}
@differentiable(wrt: (self,input))
func callAsFunction(_ input: Tensor<Float>) -> Tensor<Float> {
return input.sequenced(through: dense1, dense2)
}
}
struct AttentionInputGPT2: Differentiable {
var query: Tensor<Float>
var key: Tensor<Float>
var value: Tensor<Float>
}
@differentiable(wrt: (query,key,value))
func makeAttentionInput(query: Tensor<Float>, key: Tensor<Float>, value: Tensor<Float>)
-> AttentionInputGPT2
{
return AttentionInputGPT2(query: query, key: key, value: value)
}
@derivative(of: makeAttentionInput, wrt: (query,key,value))
func _vjpMakeAttentionInput(query: Tensor<Float>, key: Tensor<Float>, value: Tensor<Float>)
-> (
value: AttentionInputGPT2,
pullback: (AttentionInputGPT2.TangentVector)
-> (Tensor<Float>, Tensor<Float>, Tensor<Float>)
)
{
let result = AttentionInputGPT2(query: query, key: key, value: value)
return (result, { seed in (seed.query, seed.key, seed.value) })
}
public struct AttentionContext: Differentiable {
var key: Tensor<Float>
var value: Tensor<Float>
public init(key: Tensor<Float>, value: Tensor<Float>) {
self.key = key
self.value = value
}
}
@differentiable(wrt: (key,value))
func makeAttentionContext(key: Tensor<Float>, value: Tensor<Float>) -> AttentionContext {
return AttentionContext(key: key, value: value)
}
@derivative(of: makeAttentionContext, wrt: (key,value))
func _vjpMakeAttentionContext(key: Tensor<Float>, value: Tensor<Float>)
-> (
value: AttentionContext,
pullback: (AttentionContext.TangentVector)
-> (Tensor<Float>, Tensor<Float>)
)
{
let result = AttentionContext(key: key, value: value)
return (result, { seed in (seed.key, seed.value) })
}
@differentiable(wrt: dotProducts)
func causallyMasked(_ dotProducts: Tensor<Float>, enable: Bool = false) -> Tensor<Float> {
if !enable {
return dotProducts
}
let (queryTimeSteps, keyTimeSteps) = (dotProducts.shape[1], dotProducts.shape[2])
let device = dotProducts.device
let ones = Tensor<Float>(repeating: 1, shape: [1, queryTimeSteps, keyTimeSteps], on: device)
let mask = ones.bandPart(
subdiagonalCount: -1, superdiagonalCount: queryTimeSteps - keyTimeSteps)
return dotProducts * mask - 1e10 * (1 - mask)
}
// causal mask is intentionally invisible to differentiation
@derivative(of: causallyMasked, wrt: dotProducts)
func _vjpCausallyMasked(_ dotProducts: Tensor<Float>, enable: Bool)
-> (value: Tensor<Float>, pullback: (Tensor<Float>) -> Tensor<Float>)
{
return (causallyMasked(dotProducts, enable: enable), identity)
}
struct Attention: ParameterlessLayer {
typealias TangentVector = EmptyTangentVector
@noDerivative var dropout: Dropout<Float>
@noDerivative var scale: Tensor<Float>
@noDerivative var causal: Bool
init(size: Int, causal: Bool = false, dropProbability: Double) {
scale = Tensor(sqrtf(Float(size)))
dropout = Dropout<Float>(probability: dropProbability)
self.causal = causal
}
@differentiable(wrt: (self,input))
func callAsFunction(_ input: AttentionInputGPT2) -> Tensor<Float> {
var dotProducts = batchedMatmul(input.query, input.key, adjointRight: true)
dotProducts = causallyMasked(dotProducts, enable: causal) / scale
return batchedMatmul(dropout(softmax(dotProducts)), input.value)
}
func callAsFunction(_ input: AttentionInputGPT2, state: inout AttentionContext) -> Tensor<Float>
{
state = AttentionContext(
key: state.key.concatenated(with: input.key, alongAxis: 1),
value: state.value.concatenated(with: input.value, alongAxis: 1))
var dotProducts = batchedMatmul(input.query, state.key, adjointRight: true)
dotProducts = causallyMasked(dotProducts, enable: causal) / scale
return batchedMatmul(dropout(softmax(dotProducts)), state.value)
}
}
@differentiable(wrt: input)
func splitHeads(_ input: Tensor<Float>, headCount: Int) -> Tensor<Float> {
let (batchSize, timeSteps, features) = (input.shape[0], input.shape[1], input.shape[2])
let featuresPerHead = features / headCount
let splitLastDim = input.reshaped(to: [batchSize, timeSteps, headCount, featuresPerHead])
let movedToFront = splitLastDim.transposed(permutation: 0, 2, 1, 3)
return movedToFront.reshaped(to: [batchSize * headCount, timeSteps, featuresPerHead])
}
@differentiable(wrt: input)
func joinHeads(_ input: Tensor<Float>, headCount: Int) -> Tensor<Float> {
let (generalizedBatch, timeSteps, featuresPerHead) = (
input.shape[0], input.shape[1], input.shape[2]
)
let batchSize = generalizedBatch / headCount
let features = featuresPerHead * headCount
let splitFirstDim = input.reshaped(to: [batchSize, headCount, timeSteps, featuresPerHead])
let movedToBack = splitFirstDim.transposed(permutation: 0, 2, 1, 3)
return movedToBack.reshaped(to: [batchSize, timeSteps, features])
}
@differentiable(wrt: input)
func splitQKV(_ input: Tensor<Float>) -> AttentionInputGPT2 {
let (generalizedBatch, timeSteps, featuresPerHead) = (
input.shape[0], input.shape[1], input.shape[2] / 3
)
let query = input.slice(
lowerBounds: [0, 0, 0],
upperBounds: [generalizedBatch, timeSteps, featuresPerHead])
let key = input.slice(
lowerBounds: [0, 0, featuresPerHead],
upperBounds: [generalizedBatch, timeSteps, 2 * featuresPerHead])
let value = input.slice(
lowerBounds: [0, 0, 2 * featuresPerHead],
upperBounds: [generalizedBatch, timeSteps, 3 * featuresPerHead])
return makeAttentionInput(query: query, key: key, value: value)
}
@derivative(of: splitQKV, wrt: input)
func _vjpSplitQKV(_ input: Tensor<Float>)
-> (value: AttentionInputGPT2, pullback: (AttentionInputGPT2.TangentVector) -> Tensor<Float>)
{
let value = splitQKV(input)
return (
value,
{ seed in
return Tensor(concatenating: [seed.query, seed.key, seed.value], alongAxis: 2)
}
)
}
struct MultiHeadAttentionGPT2: Layer {
var attention: Attention
var wqkv: TimeDistributed
var wo: TimeDistributed
@noDerivative var headCount: Int
init(attention: Attention, size: Int, headCount: Int) {
self.attention = attention
wqkv = TimeDistributed(
Dense<Float>(
inputSize: size, outputSize: size * 3, activation: identity))
wo = TimeDistributed(Dense<Float>(inputSize: size, outputSize: size, activation: identity))
self.headCount = headCount
}
@differentiable(wrt: (self,input))
func callAsFunction(_ input: Tensor<Float>) -> Tensor<Float> {
let qkvProjected = wqkv(input)
let qkvSplit = splitQKV(qkvProjected)
let attentionInput = makeAttentionInput(
query: splitHeads(qkvSplit.query, headCount: headCount),
key: splitHeads(qkvSplit.key, headCount: headCount),
value: splitHeads(qkvSplit.value, headCount: headCount)
)
let outputs = attention(attentionInput)
return wo(joinHeads(outputs, headCount: headCount))
}
func callAsFunction(_ input: Tensor<Float>, state: inout AttentionContext) -> Tensor<Float> {
let qkvProjected = wqkv(input)
let qkvSplit = splitQKV(qkvProjected)
let attentionInput = makeAttentionInput(
query: splitHeads(qkvSplit.query, headCount: headCount),
key: splitHeads(qkvSplit.key, headCount: headCount),
value: splitHeads(qkvSplit.value, headCount: headCount)
)
let outputs = attention(attentionInput, state: &state)
return wo(joinHeads(outputs, headCount: headCount))
}
}
public struct EncoderLayer: Layer {
var selfAttention: MultiHeadAttentionGPT2
var selfAttentionDropout: Dropout<Float>
var selfAttentionNorm: LayerNorm<Float>
var feedForward: FeedForward
var feedForwardDropout: Dropout<Float>
var feedForwardNorm: LayerNorm<Float>
init(size: Int, headCount: Int, dropProbability: Double) {
selfAttention = MultiHeadAttentionGPT2(
attention: Attention(size: size, dropProbability: dropProbability),
size: size,
headCount: headCount)
selfAttentionDropout = Dropout(probability: dropProbability)
selfAttentionNorm = LayerNorm(featureCount: size, axis: 2, epsilon: 1e-5)
feedForward = FeedForward(size: size, hidden: 4 * size)
feedForwardDropout = Dropout(probability: dropProbability)
feedForwardNorm = LayerNorm(featureCount: size, axis: 2, epsilon: 1e-5)
}
@differentiable(wrt: (self,input))
public func callAsFunction(_ input: Tensor<Float>) -> Tensor<Float> {
let attended =
input
+ input.sequenced(
through: selfAttentionNorm, selfAttention, selfAttentionDropout)
return attended
+ attended.sequenced(
through: feedForwardNorm, feedForward, feedForwardDropout)
}
func callAsFunction(_ input: Tensor<Float>, state: inout AttentionContext) -> Tensor<Float> {
var tmp = input
tmp = selfAttentionNorm(tmp)
tmp = selfAttention(tmp, state: &state)
tmp = selfAttentionDropout(tmp)
let attended = tmp + input
return attended
+ attended.sequenced(
through: feedForwardNorm, feedForward, feedForwardDropout)
}
}
public struct TransformerLM: Module {
var embedding: Embedding<Float>
var positionalEmbeddings: Tensor<Float>
var embeddingDropout: Dropout<Float>
var layers: [EncoderLayer]
var norm: LayerNorm<Float>
public init(
embedding: Embedding<Float>, positionalEmbeddings: Tensor<Float>,
dropProbability: Double,
layers: [EncoderLayer], norm: LayerNorm<Float>
) {
self.embedding = embedding
self.positionalEmbeddings = positionalEmbeddings
self.embeddingDropout = Dropout(probability: dropProbability)
self.layers = layers
self.norm = norm
}
// Used for generation, where state transference is important.
public func callAsFunction(_ tokens: Tensor<Int32>, states: inout [AttentionContext]) -> Tensor<
Float
> {
let positions = (0..<tokens.shape[1]).map { Int32($0 + states[0].key.shape[1]) }
let positionsTensor = Tensor<Int32>(shape: [1, tokens.shape[1]], scalars: positions)
var h = embedding(tokens)
h = h + positionalEmbeddings.gathering(atIndices: positionsTensor)
h = embeddingDropout(h)
for i in 0..<layers.count {
// Remove the .call when TF-516 is fixed.
h = layers[i].callAsFunction(h, state: &states[i])
}
h = norm(h)
// A somewhat hacky way to share weights.
let logits = timeDistributed(h, embedding.embeddings.transposed())
return logits
}
// Used for training, where examples are independent.
@differentiable
public func callAsFunction(_ tokens: Tensor<Int32>) -> Tensor<Float> {
let positions = { (0..<tokens.shape[1]).map { Int32($0) } }()
let positionsTensor = Tensor<Int32>(shape: [1, tokens.shape[1]], scalars: positions, on: tokens.device)
var h = embedding(tokens)
h = h + positionalEmbeddings.gathering(atIndices: positionsTensor)
h = embeddingDropout(h)
h = layers.differentiableReduce(h) { $1($0) }
h = norm(h)
// A somewhat hacky way to share weights.
let logits = timeDistributed(h, embedding.embeddings.transposed())
return logits
}
}