Spaces:
Sleeping
Sleeping
Update train.py
Browse files
train.py
CHANGED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright Pathway Technology, Inc.
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
from contextlib import nullcontext
|
| 5 |
+
|
| 6 |
+
import bdh
|
| 7 |
+
import numpy as np
|
| 8 |
+
import requests
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
|
| 13 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 14 |
+
# On a Mac you can also try
|
| 15 |
+
# device=torch.device('mps')
|
| 16 |
+
|
| 17 |
+
dtype = (
|
| 18 |
+
"bfloat16"
|
| 19 |
+
if torch.cuda.is_available() and torch.cuda.is_bf16_supported()
|
| 20 |
+
else "float16"
|
| 21 |
+
) # 'float32', 'bfloat16', or 'float16', the latter will auto implement a GradScaler
|
| 22 |
+
ptdtype = {
|
| 23 |
+
"float32": torch.float32,
|
| 24 |
+
"bfloat16": torch.bfloat16,
|
| 25 |
+
"float16": torch.float16,
|
| 26 |
+
}[dtype]
|
| 27 |
+
ctx = (
|
| 28 |
+
torch.amp.autocast(device_type=device.type, dtype=ptdtype)
|
| 29 |
+
if "cuda" in device.type
|
| 30 |
+
else nullcontext()
|
| 31 |
+
)
|
| 32 |
+
scaler = torch.amp.GradScaler(device=device.type, enabled=(dtype == "float16"))
|
| 33 |
+
torch.manual_seed(1337)
|
| 34 |
+
torch.backends.cuda.matmul.allow_tf32 = True # allow tf32 on matmul
|
| 35 |
+
torch.backends.cudnn.allow_tf32 = True # allow tf32 on cudnn
|
| 36 |
+
print(f"Using device: {device} with dtype {dtype}")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# Configuration
|
| 40 |
+
BDH_CONFIG = bdh.BDHConfig()
|
| 41 |
+
BLOCK_SIZE = 512
|
| 42 |
+
BATCH_SIZE = 32
|
| 43 |
+
MAX_ITERS = 3000
|
| 44 |
+
LEARNING_RATE = 1e-3
|
| 45 |
+
WEIGHT_DECAY = 0.1
|
| 46 |
+
LOG_FREQ = 100
|
| 47 |
+
|
| 48 |
+
input_file_path = os.path.join(os.path.dirname(__file__), "input.txt")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# Fetch the tiny Shakespeare dataset
|
| 52 |
+
def fetch_data():
|
| 53 |
+
if not os.path.exists(input_file_path):
|
| 54 |
+
data_url = "https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt"
|
| 55 |
+
with open(input_file_path, "w") as f:
|
| 56 |
+
f.write(requests.get(data_url).text)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def get_batch(split):
|
| 60 |
+
# treat the file as bytes
|
| 61 |
+
data = np.memmap(input_file_path, dtype=np.uint8, mode="r")
|
| 62 |
+
if split == "train":
|
| 63 |
+
data = data[: int(0.9 * len(data))]
|
| 64 |
+
else:
|
| 65 |
+
data = data[int(0.9 * len(data)) :]
|
| 66 |
+
ix = torch.randint(len(data) - BLOCK_SIZE, (BATCH_SIZE,))
|
| 67 |
+
x = torch.stack(
|
| 68 |
+
[torch.from_numpy((data[i : i + BLOCK_SIZE]).astype(np.int64)) for i in ix]
|
| 69 |
+
)
|
| 70 |
+
y = torch.stack(
|
| 71 |
+
[
|
| 72 |
+
torch.from_numpy((data[i + 1 : i + 1 + BLOCK_SIZE]).astype(np.int64))
|
| 73 |
+
for i in ix
|
| 74 |
+
]
|
| 75 |
+
)
|
| 76 |
+
if torch.cuda.is_available():
|
| 77 |
+
# pin arrays x,y, which allows us to move them to GPU asynchronously (non_blocking=True)
|
| 78 |
+
x, y = x.pin_memory().to(device, non_blocking=True), y.pin_memory().to(
|
| 79 |
+
device, non_blocking=True
|
| 80 |
+
)
|
| 81 |
+
else:
|
| 82 |
+
x, y = x.to(device), y.to(device)
|
| 83 |
+
return x, y
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def eval(model):
|
| 87 |
+
model.eval()
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
if __name__ == "__main__":
|
| 91 |
+
fetch_data()
|
| 92 |
+
|
| 93 |
+
model = bdh.BDH(BDH_CONFIG).to(device)
|
| 94 |
+
model = torch.compile(model)
|
| 95 |
+
optimizer = torch.optim.AdamW(
|
| 96 |
+
model.parameters(), lr=LEARNING_RATE, weight_decay=WEIGHT_DECAY
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
x, y = get_batch("train")
|
| 100 |
+
|
| 101 |
+
loss_acc = 0
|
| 102 |
+
loss_steps = 0
|
| 103 |
+
for step in range(MAX_ITERS):
|
| 104 |
+
with ctx:
|
| 105 |
+
logits, loss = model(x, y)
|
| 106 |
+
x, y = get_batch("train")
|
| 107 |
+
loss_acc += loss
|
| 108 |
+
loss_steps += 1
|
| 109 |
+
scaler.scale(loss).backward()
|
| 110 |
+
scaler.step(optimizer)
|
| 111 |
+
scaler.update()
|
| 112 |
+
optimizer.zero_grad()
|
| 113 |
+
if step % LOG_FREQ == 0:
|
| 114 |
+
print(f"Step: {step}/{MAX_ITERS} loss {loss_acc.item() / loss_steps:.3}")
|
| 115 |
+
loss_acc = 0
|
| 116 |
+
loss_steps = 0
|
| 117 |
+
print("Training done, now generating a sample ")
|
| 118 |
+
model.eval()
|
| 119 |
+
prompt = torch.tensor(
|
| 120 |
+
bytearray("To be or ", "utf-8"), dtype=torch.long, device=device
|
| 121 |
+
).unsqueeze(0)
|
| 122 |
+
ret = model.generate(prompt, max_new_tokens=100, top_k=3)
|
| 123 |
+
ret_decoded = bytes(ret.to(torch.uint8).to("cpu").squeeze(0)).decode(
|
| 124 |
+
errors="backslashreplace"
|
| 125 |
+
)
|
| 126 |
+
print(ret_decoded)
|