mlp.py 1.79 KB
Newer Older
Mitchell Wortsman's avatar
Mitchell Wortsman committed
1
2
3
4
5

import time
import torch
import torch.nn as nn
import bitsandbytes.nn as bnn
Tim Dettmers's avatar
Tim Dettmers committed
6
from bitsandbytes.nn.triton_based_modules import SwitchBackLinear, SwitchBackGlobalLinear, StandardLinear
Mitchell Wortsman's avatar
Mitchell Wortsman committed
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

def construct_model(dim, layers, module):
    modules = []
    for _ in range(layers):
        modules.append(module(dim, 4*dim))
        modules.append(module(4*dim, dim))
    return nn.Sequential(*modules).cuda().train()

def get_time(model, x, name):
    for _ in range(repeat // 2):
        #with torch.cuda.amp.autocast():
        out = model(x)
        #(2**16 * out.pow(2).mean()).backward()

    torch.cuda.synchronize()
    start = time.time()
    for _ in range(repeat):
        # with torch.cuda.amp.autocast():
        out = model(x)
        #(2**16 * out.pow(2).mean()).backward()

    torch.cuda.synchronize()
    end = time.time()
    print(f"time {name}: {(end - start) / repeat * 1000:.3f} ms")

if __name__ == '__main__':
    torch.manual_seed(0)

    # hparams
    repeat = 16
    dim=2048
    layers =4 
    batch_size = 2
    sequence_length = 2**15

    # construct models
    standard = construct_model(dim, layers, nn.Linear).half()
Tim Dettmers's avatar
Tim Dettmers committed
44
    my_standard = construct_model(dim, layers, StandardLinear).half()
Mitchell Wortsman's avatar
Mitchell Wortsman committed
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
    switchback = construct_model(dim, layers, SwitchBackLinear).half()
    switchback_global = construct_model(dim, layers, SwitchBackGlobalLinear).half()
    #bnb_8bitmixed = construct_model(dim, layers, bnn.Linear8bitLt)

    # simulate forward pass
    x = torch.randn(batch_size * sequence_length, dim, dtype=torch.float16).cuda()

    # get time for forward and backward
    get_time(standard, x, "standard")
    get_time(my_standard, x, "my_standard")
    get_time(switchback, x, "switchback")
    get_time(switchback_global, x, "switchback_global")
    #get_time(bnb_8bitmixed, x, "bnb_8bitmixed")






Tim Dettmers's avatar
Tim Dettmers committed
64