transformer_layer.py 10.4 KB
Newer Older
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
# Copyright (c) 2022-2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# See LICENSE for license information.

from transformer_engine.tensorflow import Format, DelayedScaling
import argparse
import tensorflow as tf
import time
import transformer_engine.tensorflow as te

from keras import layers
from keras import Model
from typing import Optional

parser = argparse.ArgumentParser(description="Benchmark TransformerLayer.")
parser.add_argument(
    '-t', '--type', type=int, default=0,
    help="""Pick TE implementation (0:all|1:TF-fp16|2:TE-fp16|3:TE-fp8)""")
args, _ = parser.parse_known_args()
tl_type = args.type

tf.keras.mixed_precision.set_global_policy('mixed_float16')

dropout_rate = 0.0


class DotProductAttention(tf.keras.Model):
    """Attention operation in Transformer layer
    """

    def __init__(
        self,
        num_attention_heads: int,
        kv_channels: int,
        attention_dropout: float,
    ):
        super().__init__()
        self.projection_size = kv_channels * num_attention_heads
        self.hidden_size_per_attention_head = float(kv_channels)
        self.norm_factor = tf.math.sqrt(self.hidden_size_per_attention_head)
        self.dropout = layers.Dropout(attention_dropout)
        if self.dropout.dtype_policy.name == 'mixed_float16':
            self.norm_factor = tf.cast(self.norm_factor, dtype=tf.float16)

    def masked_softmax(
        self,
        inp: tf.Tensor,
        mask: Optional[tf.Tensor]
    ) -> tf.Tensor:
        if mask is not None:
            inp = tf.where(mask, -10000.0, inp)
        return tf.nn.softmax(inp, axis=-1)

    def call(
        self,
        query: tf.Tensor,
        key: tf.Tensor,
        value: tf.Tensor,
        attention_mask: Optional[tf.Tensor] = None,
    ) -> tf.Tensor:
        b = query.shape[1]
        np = query.shape[2]
        sq = query.shape[0]
        sk = key.shape[0]
        hn = value.shape[3]

        # [sq, b, np, hn] -> [sq, b * np, hn]
        query = tf.reshape(query, shape=(sq, b * np, hn))
        # [sk, b, np, hn] -> [sk, b * np, hn]
        key = tf.reshape(key, shape=(sk, b * np, hn))

        bmm1 = tf.matmul(tf.transpose(query, perm=(1, 0, 2)),
                         tf.transpose(key, perm=(1, 2, 0))) / self.norm_factor

        # change view to [b, np, sq, sk]
        attention_scores = tf.reshape(bmm1, shape=(b, np, sq, sk))

        attention_probs = self.masked_softmax(attention_scores, attention_mask)

        attention_probs = self.dropout(attention_probs)

        # change view [sk, b * np, hn]
        value = tf.reshape(value, shape=(sk, b * np, hn))

        # change view [b * np, sq, sk]
        attention_probs = tf.reshape(attention_probs, shape=(b * np, sq, sk))

        # matmul: [b * np, sq, hn]
        context = tf.matmul(attention_probs,
                            tf.transpose(value, perm=(1, 0, 2)))

        # change view [b, np, sq, hn]
        context = tf.reshape(context, shape=(b, np, sq, hn))

        # [b, np, sq, hn] --> [sq, b, np, hn]
        context = tf.transpose(context, perm=(2, 0, 1, 3))

        # [sq, b, np, hn] --> [sq, b, hp]
        context = tf.reshape(context, shape=(sq, b, self.projection_size))

        return context


class BasicMLP(tf.keras.Model):
    """Feed-forward network in Transformer layer
    """

    def __init__(
        self,
        hidden_size: int,
        ffn_hidden_size: int,
    ):
        super().__init__()
        self.linear1 = layers.Dense(ffn_hidden_size, use_bias=True)
        self.linear2 = layers.Dense(hidden_size, use_bias=True)

    def call(
        self,
        x: tf.Tensor
    ) -> tf.Tensor:
        x = self.linear1(x)
        x = tf.nn.gelu(x, approximate=True)
        x = self.linear2(x)
        return x


class BasicTransformer(tf.keras.Model):
    def __init__(
        self,
        hidden_size: int,
        ffn_hidden_size: int,
        num_attention_heads: int,
        layernorm_eps: int = 1e-5,
        attention_dropout: float = 0.1,
        hidden_dropout: float = 0.1,
    ):
        super().__init__()
        self.num_attention_heads = num_attention_heads
        self.kv_channels = hidden_size // num_attention_heads
        self.ln1 = layers.LayerNormalization(epsilon=layernorm_eps)
        self.qkv_projection = layers.Dense(3 * hidden_size, use_bias=True)
        self.attention = DotProductAttention(
            num_attention_heads=num_attention_heads,
            kv_channels=self.kv_channels,
            attention_dropout=attention_dropout,
        )
        self.projection = layers.Dense(hidden_size, use_bias=True)
        self.dropout = layers.Dropout(hidden_dropout)
        self.ln2 = layers.LayerNormalization(epsilon=layernorm_eps)
        self.mlp = BasicMLP(
            hidden_size=hidden_size,
            ffn_hidden_size=ffn_hidden_size,
        )

    def call(
        self,
        x: tf.Tensor,
        attention_mask: tf.Tensor,
    ) -> tf.Tensor:
        res = x
        x = self.ln1(x)

        # Fused QKV projection
        qkv = self.qkv_projection(x)
        qkv_shape = qkv.shape
        qkv = tf.reshape(qkv,
                         shape=(qkv_shape[0], qkv_shape[1],
                                self.num_attention_heads, 3 * self.kv_channels))
        q, k, v = tf.split(qkv, 3, axis=3)

        x = self.attention(q, k, v, attention_mask)
        x = self.projection(x)
        x = self.dropout(x)
        x = res + x
        res = x
        x = self.ln2(x)
        x = self.mlp(x)

        return x + res


class FusedTETransformer(tf.keras.Model):
    def __init__(
        self,
        hidden_size: int,
        ffn_hidden_size: int,
        num_attention_heads: int,
        layernorm_eps: int = 1e-5,
        attention_dropout: float = 0.1,
        hidden_dropout: float = 0.1,
    ):
        super().__init__()
        self.num_attention_heads = num_attention_heads
        self.kv_channels = hidden_size // num_attention_heads
        self.ln_qkv = te.LayerNormDense(3 * hidden_size, epsilon=layernorm_eps,
                                        use_bias=True)
        self.attention = DotProductAttention(
            num_attention_heads=num_attention_heads,
            kv_channels=self.kv_channels,
            attention_dropout=attention_dropout,
        )
        self.projection = te.Dense(hidden_size, use_bias=True)
        self.dropout = layers.Dropout(hidden_dropout)
        self.ln_mlp = te.LayerNormMLP(ffn_hidden_size, hidden_size,
                                      epsilon=layernorm_eps, use_bias=True,
                                      return_layernorm_output=False)

    def call(
        self,
        x: tf.Tensor,
        attention_mask: tf.Tensor,
    ) -> tf.Tensor:
        res = x
        qkv = self.ln_qkv(x)

        # Split qkv into query, key and value
        qkv_shape = qkv.shape
        qkv = tf.reshape(qkv,
                         shape=(qkv_shape[0], qkv_shape[1],
                                self.num_attention_heads, 3 * self.kv_channels))
        q, k, v = tf.split(qkv, 3, axis=3)

        x = self.attention(q, k, v, attention_mask)
        x = self.projection(x)
        x = self.dropout(x)
        x = res + x
        res = x
        x = self.ln_mlp(x)

        return x + res


# Layer configuration
hidden_size = 4096
sequence_length = 2048
batch_size = 4
ffn_hidden_size = 16384
num_attention_heads = 32
dtype = tf.float32


def speedometer(
    model: tf.keras.Model,
    input: tf.Tensor,
    forward_kwargs: dict = {},
    fp8_autocast_kwargs: Optional[dict] = None,
    timing_iters: int = 50,
    warmup_iters: int = 50,
) -> None:
    """Measure average run time for a TF model

    Performs forward and backward passes.
    """
    if fp8_autocast_kwargs is None:
        fp8_autocast_kwargs = {"enabled": False}

    p = tf.constant(0.)  # Create small tensor to force GPU resync

    # Warmup runs
    for _ in range(warmup_iters):
        with tf.GradientTape(persistent=True) as tape:
            tape.watch(input)
            with te.fp8_autocast(**fp8_autocast_kwargs):
                output = model(input, **forward_kwargs)
            loss = tf.reduce_sum(output)
        dx, dvars = tape.gradient(loss, [input, model.variables])

    (p + 1.).numpy()  # Sync the GPU

    # Timing runs
    start = time.time()
    for _ in range(timing_iters):
        with tf.GradientTape(persistent=True) as tape:
            tape.watch(input)
            with te.fp8_autocast(**fp8_autocast_kwargs):
                output = model(input, **forward_kwargs)
            loss = tf.reduce_sum(output)
        dx, dvars = tape.gradient(loss, [input, model.variables])

    (p + 1.).numpy()  # Sync the GPU
    end = time.time()

    elapsed_time = (end - start) / timing_iters * 1000

    print(f"Mean time: {elapsed_time} ms")


tf.random.set_seed(12)
tf.keras.utils.set_random_seed(1)
# Synthetic data
x = tf.random.normal(shape=(sequence_length, batch_size, hidden_size),
                     dtype=dtype)

basic_transformer = BasicTransformer(
    hidden_size,
    ffn_hidden_size,
    num_attention_heads,
    attention_dropout=dropout_rate,
    hidden_dropout=dropout_rate,
)

y = basic_transformer(x, attention_mask=None)

if tl_type in (0, 1):
    print("Running in the native TF:")
    speedometer(
        basic_transformer,
        x,
        forward_kwargs={"attention_mask": None, "training": True},
    )

te_transformer = FusedTETransformer(
    hidden_size,
    ffn_hidden_size,
    num_attention_heads,
    attention_dropout=dropout_rate,
    hidden_dropout=dropout_rate,
)


fp8_recipe = DelayedScaling(margin=0, interval=1, fp8_format=Format.HYBRID,
                            amax_compute_algo='max', amax_history_len=16)

# Run once to build the variables.
te_transformer(x, attention_mask=None)
# Sync the variables with the reference.
for v0, v1 in zip(basic_transformer.variables, te_transformer.variables):
    v1.assign(v0)
    tf.debugging.assert_near(v1, v0)

y_te = te_transformer(x, attention_mask=None)

if tl_type in (0, 2):
    print("Running in the TE:")
    speedometer(
        te_transformer,
        x,
        forward_kwargs={"attention_mask": None, "training": True},
        fp8_autocast_kwargs={"enabled": False, "fp8_recipe": None},
    )

with te.fp8_autocast(enabled=True, fp8_recipe=fp8_recipe):
    y_te = te_transformer(x, attention_mask=None)

if tl_type in (0, 3):
    print("Running in the TE with fp8:")
    speedometer(
        te_transformer,
        x,
        forward_kwargs={"attention_mask": None, "training": True},
        fp8_autocast_kwargs={"enabled": True, "fp8_recipe": fp8_recipe},
    )