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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import time
|
2 |
+
import math
|
3 |
+
from contextlib import nullcontext
|
4 |
+
import numpy as np
|
5 |
+
import torch
|
6 |
+
import torch.nn as nn
|
7 |
+
from torch.nn import functional as F
|
8 |
+
import inspect
|
9 |
+
from dataclasses import dataclass
|
10 |
+
import streamlit as st
|
11 |
+
import pandas as pd
|
12 |
+
from rdkit import Chem
|
13 |
+
from rdkit.Chem import Draw
|
14 |
+
|
15 |
+
|
16 |
+
eval_interval = 250 # keep frequent because we'll overfit
|
17 |
+
eval_iters = 200
|
18 |
+
log_interval = 10 # don't print too too often
|
19 |
+
always_save_checkpoint = False
|
20 |
+
dataset = 'lipid_char'
|
21 |
+
gradient_accumulation_steps = 1
|
22 |
+
beta2 = 0.99 # make a bit bigger because number of tokens per iter is small
|
23 |
+
eval_only = False # if True, script exits right after the first eval
|
24 |
+
init_from = 'scratch' # 'scratch' or 'resume' or 'gpt2*'
|
25 |
+
bias = False # do we use bias inside LayerNorm and Linear layers?
|
26 |
+
weight_decay = 1e-1
|
27 |
+
beta1 = 0.9
|
28 |
+
grad_clip = 1.0 # clip gradients at this value, or disable if == 0.0
|
29 |
+
min_lr = 6e-5 # minimum learning rate, should be ~= learning_rate/10 per Chinchilla
|
30 |
+
backend = 'nccl' # 'nccl', 'gloo', etc.
|
31 |
+
device = 'cuda' # examples: 'cpu', 'cuda', 'cuda:0', 'cuda:1' etc., or try 'mps' on macbooks
|
32 |
+
dtype = 'bfloat16' if torch.cuda.is_available() and torch.cuda.is_bf16_supported() else 'float16' # 'float32', 'bfloat16', or 'float16', the latter will auto implement a GradScaler
|
33 |
+
config_keys = [k for k,v in globals().items() if not k.startswith('_') and isinstance(v, (int, float, bool, str))]
|
34 |
+
config = {k: globals()[k] for k in config_keys}
|
35 |
+
master_process = True
|
36 |
+
torch.backends.cuda.matmul.allow_tf32 = True # allow tf32 on matmul
|
37 |
+
torch.backends.cudnn.allow_tf32 = True # allow tf32 on cudnn
|
38 |
+
device_type = 'cuda' if 'cuda' in device else 'cpu' # for later use in torch.autocast
|
39 |
+
ptdtype = {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[dtype]
|
40 |
+
ctx = nullcontext() if device_type == 'cpu' else torch.amp.autocast(device_type=device_type, dtype=ptdtype)
|
41 |
+
|
42 |
+
|
43 |
+
@st.cache_resource
|
44 |
+
class LayerNorm(nn.Module):
|
45 |
+
""" LayerNorm but with an optional bias. PyTorch doesn't support simply bias=False """
|
46 |
+
|
47 |
+
def __init__(self, ndim, bias):
|
48 |
+
super().__init__()
|
49 |
+
self.weight = nn.Parameter(torch.ones(ndim))
|
50 |
+
self.bias = nn.Parameter(torch.zeros(ndim)) if bias else None
|
51 |
+
|
52 |
+
def forward(self, input):
|
53 |
+
return F.layer_norm(input, self.weight.shape, self.weight, self.bias, 1e-5)
|
54 |
+
|
55 |
+
@st.cache_resource
|
56 |
+
class CausalSelfAttention(nn.Module):
|
57 |
+
|
58 |
+
def __init__(self, config):
|
59 |
+
super().__init__()
|
60 |
+
assert config.n_embd % config.n_head == 0
|
61 |
+
# key, query, value projections for all heads, but in a batch
|
62 |
+
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)
|
63 |
+
# output projection
|
64 |
+
self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
|
65 |
+
# regularization
|
66 |
+
self.attn_dropout = nn.Dropout(config.dropout)
|
67 |
+
self.resid_dropout = nn.Dropout(config.dropout)
|
68 |
+
self.n_head = config.n_head
|
69 |
+
self.n_embd = config.n_embd
|
70 |
+
self.dropout = config.dropout
|
71 |
+
# flash attention make GPU go brrrrr but support is only in PyTorch >= 2.0
|
72 |
+
self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention')
|
73 |
+
if not self.flash:
|
74 |
+
print("WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0")
|
75 |
+
# causal mask to ensure that attention is only applied to the left in the input sequence
|
76 |
+
self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size))
|
77 |
+
.view(1, 1, config.block_size, config.block_size))
|
78 |
+
|
79 |
+
def forward(self, x):
|
80 |
+
B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
|
81 |
+
|
82 |
+
# calculate query, key, values for all heads in batch and move head forward to be the batch dim
|
83 |
+
q, k, v = self.c_attn(x).split(self.n_embd, dim=2)
|
84 |
+
k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
85 |
+
q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
86 |
+
v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
87 |
+
|
88 |
+
# causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)
|
89 |
+
if self.flash:
|
90 |
+
# efficient attention using Flash Attention CUDA kernels
|
91 |
+
y = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=None, dropout_p=self.dropout if self.training else 0, is_causal=True)
|
92 |
+
else:
|
93 |
+
# manual implementation of attention
|
94 |
+
att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
|
95 |
+
att = att.masked_fill(self.bias[:,:,:T,:T] == 0, float('-inf'))
|
96 |
+
att = F.softmax(att, dim=-1)
|
97 |
+
att = self.attn_dropout(att)
|
98 |
+
y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
|
99 |
+
y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
|
100 |
+
|
101 |
+
# output projection
|
102 |
+
y = self.resid_dropout(self.c_proj(y))
|
103 |
+
return y
|
104 |
+
|
105 |
+
@st.cache_resource
|
106 |
+
class MLP(nn.Module):
|
107 |
+
|
108 |
+
def __init__(self, config):
|
109 |
+
super().__init__()
|
110 |
+
self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias)
|
111 |
+
self.gelu = nn.GELU()
|
112 |
+
self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd, bias=config.bias)
|
113 |
+
self.dropout = nn.Dropout(config.dropout)
|
114 |
+
|
115 |
+
def forward(self, x):
|
116 |
+
x = self.c_fc(x)
|
117 |
+
x = self.gelu(x)
|
118 |
+
x = self.c_proj(x)
|
119 |
+
x = self.dropout(x)
|
120 |
+
return x
|
121 |
+
|
122 |
+
@st.cache_resource
|
123 |
+
class Block(nn.Module):
|
124 |
+
|
125 |
+
def __init__(self, config):
|
126 |
+
super().__init__()
|
127 |
+
self.ln_1 = LayerNorm(config.n_embd, bias=config.bias)
|
128 |
+
self.attn = CausalSelfAttention(config)
|
129 |
+
self.ln_2 = LayerNorm(config.n_embd, bias=config.bias)
|
130 |
+
self.mlp = MLP(config)
|
131 |
+
|
132 |
+
def forward(self, x):
|
133 |
+
x = x + self.attn(self.ln_1(x))
|
134 |
+
x = x + self.mlp(self.ln_2(x))
|
135 |
+
return x
|
136 |
+
|
137 |
+
@dataclass
|
138 |
+
class GPTConfig:
|
139 |
+
block_size: int = 1024
|
140 |
+
vocab_size: int = 50304 # GPT-2 vocab_size of 50257, padded up to nearest multiple of 64 for efficiency
|
141 |
+
n_layer: int = 12
|
142 |
+
n_head: int = 12
|
143 |
+
n_embd: int = 768
|
144 |
+
dropout: float = 0.0
|
145 |
+
bias: bool = True # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster
|
146 |
+
|
147 |
+
@st.cache_resource
|
148 |
+
class GPT(nn.Module):
|
149 |
+
|
150 |
+
def __init__(self, config):
|
151 |
+
super().__init__()
|
152 |
+
assert config.vocab_size is not None
|
153 |
+
assert config.block_size is not None
|
154 |
+
self.config = config
|
155 |
+
|
156 |
+
self.transformer = nn.ModuleDict(dict(
|
157 |
+
wte = nn.Embedding(config.vocab_size, config.n_embd),
|
158 |
+
wpe = nn.Embedding(config.block_size, config.n_embd),
|
159 |
+
drop = nn.Dropout(config.dropout),
|
160 |
+
h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
|
161 |
+
ln_f = LayerNorm(config.n_embd, bias=config.bias),
|
162 |
+
))
|
163 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
164 |
+
self.transformer.wte.weight = self.lm_head.weight # https://paperswithcode.com/method/weight-tying
|
165 |
+
|
166 |
+
# init all weights
|
167 |
+
self.apply(self._init_weights)
|
168 |
+
# apply special scaled init to the residual projections, per GPT-2 paper
|
169 |
+
for pn, p in self.named_parameters():
|
170 |
+
if pn.endswith('c_proj.weight'):
|
171 |
+
torch.nn.init.normal_(p, mean=0.0, std=0.02/math.sqrt(2 * config.n_layer))
|
172 |
+
# report number of parameters
|
173 |
+
print("number of parameters: %.2fM" % (self.get_num_params()/1e6,))
|
174 |
+
|
175 |
+
def get_num_params(self, non_embedding=True):
|
176 |
+
"""
|
177 |
+
Return the number of parameters in the model.
|
178 |
+
For non-embedding count (default), the position embeddings get subtracted.
|
179 |
+
The token embeddings would too, except due to the parameter sharing these
|
180 |
+
params are actually used as weights in the final layer, so we include them.
|
181 |
+
"""
|
182 |
+
n_params = sum(p.numel() for p in self.parameters())
|
183 |
+
if non_embedding:
|
184 |
+
n_params -= self.transformer.wpe.weight.numel()
|
185 |
+
return n_params
|
186 |
+
|
187 |
+
def _init_weights(self, module):
|
188 |
+
if isinstance(module, nn.Linear):
|
189 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
190 |
+
if module.bias is not None:
|
191 |
+
torch.nn.init.zeros_(module.bias)
|
192 |
+
elif isinstance(module, nn.Embedding):
|
193 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
194 |
+
|
195 |
+
def forward(self, idx, targets=None):
|
196 |
+
device = idx.device
|
197 |
+
b, t = idx.size()
|
198 |
+
assert t <= self.config.block_size, f"Cannot forward sequence of length {t}, block size is only {self.config.block_size}"
|
199 |
+
pos = torch.arange(0, t, dtype=torch.long, device=device) # shape (t)
|
200 |
+
|
201 |
+
# forward the GPT model itself
|
202 |
+
tok_emb = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd)
|
203 |
+
pos_emb = self.transformer.wpe(pos) # position embeddings of shape (t, n_embd)
|
204 |
+
x = self.transformer.drop(tok_emb + pos_emb)
|
205 |
+
for block in self.transformer.h:
|
206 |
+
x = block(x)
|
207 |
+
x = self.transformer.ln_f(x)
|
208 |
+
|
209 |
+
if targets is not None:
|
210 |
+
# if we are given some desired targets also calculate the loss
|
211 |
+
logits = self.lm_head(x)
|
212 |
+
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
|
213 |
+
else:
|
214 |
+
# inference-time mini-optimization: only forward the lm_head on the very last position
|
215 |
+
logits = self.lm_head(x[:, [-1], :]) # note: using list [-1] to preserve the time dim
|
216 |
+
loss = None
|
217 |
+
return logits, loss
|
218 |
+
|
219 |
+
def crop_block_size(self, block_size):
|
220 |
+
# model surgery to decrease the block size if necessary
|
221 |
+
# e.g. we may load the GPT2 pretrained model checkpoint (block size 1024)
|
222 |
+
# but want to use a smaller block size for some smaller, simpler model
|
223 |
+
assert block_size <= self.config.block_size
|
224 |
+
self.config.block_size = block_size
|
225 |
+
self.transformer.wpe.weight = nn.Parameter(self.transformer.wpe.weight[:block_size])
|
226 |
+
for block in self.transformer.h:
|
227 |
+
if hasattr(block.attn, 'bias'):
|
228 |
+
block.attn.bias = block.attn.bias[:,:,:block_size,:block_size]
|
229 |
+
|
230 |
+
@classmethod
|
231 |
+
def from_pretrained(cls, model_type, override_args=None):
|
232 |
+
assert model_type in {'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'}
|
233 |
+
override_args = override_args or {} # default to empty dict
|
234 |
+
# only dropout can be overridden see more notes below
|
235 |
+
assert all(k == 'dropout' for k in override_args)
|
236 |
+
from transformers import GPT2LMHeadModel
|
237 |
+
print("loading weights from pretrained gpt: %s" % model_type)
|
238 |
+
|
239 |
+
# n_layer, n_head and n_embd are determined from model_type
|
240 |
+
config_args = {
|
241 |
+
'gpt2': dict(n_layer=12, n_head=12, n_embd=768), # 124M params
|
242 |
+
'gpt2-medium': dict(n_layer=24, n_head=16, n_embd=1024), # 350M params
|
243 |
+
'gpt2-large': dict(n_layer=36, n_head=20, n_embd=1280), # 774M params
|
244 |
+
'gpt2-xl': dict(n_layer=48, n_head=25, n_embd=1600), # 1558M params
|
245 |
+
}[model_type]
|
246 |
+
print("forcing vocab_size=50257, block_size=1024, bias=True")
|
247 |
+
config_args['vocab_size'] = 50257 # always 50257 for GPT model checkpoints
|
248 |
+
config_args['block_size'] = 1024 # always 1024 for GPT model checkpoints
|
249 |
+
config_args['bias'] = True # always True for GPT model checkpoints
|
250 |
+
# we can override the dropout rate, if desired
|
251 |
+
if 'dropout' in override_args:
|
252 |
+
print(f"overriding dropout rate to {override_args['dropout']}")
|
253 |
+
config_args['dropout'] = override_args['dropout']
|
254 |
+
# create a from-scratch initialized minGPT model
|
255 |
+
config = GPTConfig(**config_args)
|
256 |
+
model = GPT(config)
|
257 |
+
sd = model.state_dict()
|
258 |
+
sd_keys = sd.keys()
|
259 |
+
sd_keys = [k for k in sd_keys if not k.endswith('.attn.bias')] # discard this mask / buffer, not a param
|
260 |
+
|
261 |
+
# init a huggingface/transformers model
|
262 |
+
model_hf = GPT2LMHeadModel.from_pretrained(model_type)
|
263 |
+
sd_hf = model_hf.state_dict()
|
264 |
+
|
265 |
+
# copy while ensuring all of the parameters are aligned and match in names and shapes
|
266 |
+
sd_keys_hf = sd_hf.keys()
|
267 |
+
sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.masked_bias')] # ignore these, just a buffer
|
268 |
+
sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.bias')] # same, just the mask (buffer)
|
269 |
+
transposed = ['attn.c_attn.weight', 'attn.c_proj.weight', 'mlp.c_fc.weight', 'mlp.c_proj.weight']
|
270 |
+
# basically the openai checkpoints use a "Conv1D" module, but we only want to use a vanilla Linear
|
271 |
+
# this means that we have to transpose these weights when we import them
|
272 |
+
assert len(sd_keys_hf) == len(sd_keys), f"mismatched keys: {len(sd_keys_hf)} != {len(sd_keys)}"
|
273 |
+
for k in sd_keys_hf:
|
274 |
+
if any(k.endswith(w) for w in transposed):
|
275 |
+
# special treatment for the Conv1D weights we need to transpose
|
276 |
+
assert sd_hf[k].shape[::-1] == sd[k].shape
|
277 |
+
with torch.no_grad():
|
278 |
+
sd[k].copy_(sd_hf[k].t())
|
279 |
+
else:
|
280 |
+
# vanilla copy over the other parameters
|
281 |
+
assert sd_hf[k].shape == sd[k].shape
|
282 |
+
with torch.no_grad():
|
283 |
+
sd[k].copy_(sd_hf[k])
|
284 |
+
return model
|
285 |
+
|
286 |
+
def configure_optimizers(self, weight_decay, learning_rate, betas, device_type):
|
287 |
+
# start with all of the candidate parameters
|
288 |
+
param_dict = {pn: p for pn, p in self.named_parameters()}
|
289 |
+
# filter out those that do not require grad
|
290 |
+
param_dict = {pn: p for pn, p in param_dict.items() if p.requires_grad}
|
291 |
+
# create optim groups. Any parameters that is 2D will be weight decayed, otherwise no.
|
292 |
+
# i.e. all weight tensors in matmuls + embeddings decay, all biases and layernorms don't.
|
293 |
+
decay_params = [p for n, p in param_dict.items() if p.dim() >= 2]
|
294 |
+
nodecay_params = [p for n, p in param_dict.items() if p.dim() < 2]
|
295 |
+
optim_groups = [
|
296 |
+
{'params': decay_params, 'weight_decay': weight_decay},
|
297 |
+
{'params': nodecay_params, 'weight_decay': 0.0}
|
298 |
+
]
|
299 |
+
num_decay_params = sum(p.numel() for p in decay_params)
|
300 |
+
num_nodecay_params = sum(p.numel() for p in nodecay_params)
|
301 |
+
print(f"num decayed parameter tensors: {len(decay_params)}, with {num_decay_params:,} parameters")
|
302 |
+
print(f"num non-decayed parameter tensors: {len(nodecay_params)}, with {num_nodecay_params:,} parameters")
|
303 |
+
# Create AdamW optimizer and use the fused version if it is available
|
304 |
+
fused_available = 'fused' in inspect.signature(torch.optim.AdamW).parameters
|
305 |
+
use_fused = fused_available and device_type == 'cuda'
|
306 |
+
extra_args = dict(fused=True) if use_fused else dict()
|
307 |
+
optimizer = torch.optim.AdamW(optim_groups, lr=learning_rate, betas=betas, **extra_args)
|
308 |
+
print(f"using fused AdamW: {use_fused}")
|
309 |
+
return optimizer
|
310 |
+
|
311 |
+
def estimate_mfu(self, fwdbwd_per_iter, dt):
|
312 |
+
""" estimate model flops utilization (MFU) in units of A100 bfloat16 peak FLOPS """
|
313 |
+
# first estimate the number of flops we do per iteration.
|
314 |
+
# see PaLM paper Appendix B as ref: https://arxiv.org/abs/2204.02311
|
315 |
+
N = self.get_num_params()
|
316 |
+
cfg = self.config
|
317 |
+
L, H, Q, T = cfg.n_layer, cfg.n_head, cfg.n_embd//cfg.n_head, cfg.block_size
|
318 |
+
flops_per_token = 6*N + 12*L*H*Q*T
|
319 |
+
flops_per_fwdbwd = flops_per_token * T
|
320 |
+
flops_per_iter = flops_per_fwdbwd * fwdbwd_per_iter
|
321 |
+
# express our flops throughput as ratio of A100 bfloat16 peak flops
|
322 |
+
flops_achieved = flops_per_iter * (1.0/dt) # per second
|
323 |
+
flops_promised = 312e12 # A100 GPU bfloat16 peak flops is 312 TFLOPS
|
324 |
+
mfu = flops_achieved / flops_promised
|
325 |
+
return mfu
|
326 |
+
|
327 |
+
@torch.no_grad()
|
328 |
+
def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
|
329 |
+
while True:
|
330 |
+
# if the sequence context is growing too long we must crop it at block_size
|
331 |
+
idx_cond = idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]
|
332 |
+
# forward the model to get the logits for the index in the sequence
|
333 |
+
logits, _ = self(idx_cond)
|
334 |
+
# pluck the logits at the final step and scale by desired temperature
|
335 |
+
logits = logits[:, -1, :] / temperature
|
336 |
+
# optionally crop the logits to only the top k options
|
337 |
+
if top_k is not None:
|
338 |
+
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
|
339 |
+
logits[logits < v[:, [-1]]] = -float('Inf')
|
340 |
+
# apply softmax to convert logits to (normalized) probabilities
|
341 |
+
probs = F.softmax(logits, dim=-1)
|
342 |
+
# sample from the distribution
|
343 |
+
idx_next = torch.multinomial(probs, num_samples=1)
|
344 |
+
if idx_next.item() == 0:
|
345 |
+
break
|
346 |
+
else:
|
347 |
+
idx = torch.cat((idx, idx_next), dim=1)
|
348 |
+
return idx
|
349 |
+
|
350 |
+
@st.cache_data
|
351 |
+
def canonicalize(smiles):
|
352 |
+
mol = Chem.MolFromSmiles(smiles)
|
353 |
+
if mol is not None:
|
354 |
+
return Chem.MolToSmiles(mol)
|
355 |
+
else:
|
356 |
+
return None
|
357 |
+
|
358 |
+
@st.cache_data
|
359 |
+
def get_batch(split):
|
360 |
+
data = train_data if split == 'train' else val_data
|
361 |
+
ix = torch.randint(len(data) - block_size, (batch_size,))
|
362 |
+
x = torch.stack([torch.from_numpy((data[i:i+block_size]).astype(np.int64)) for i in ix])
|
363 |
+
y = torch.stack([torch.from_numpy((data[i+1:i+1+block_size]).astype(np.int64)) for i in ix])
|
364 |
+
if device_type == 'cuda':
|
365 |
+
x, y = x.pin_memory().to(device, non_blocking=True), y.pin_memory().to(device, non_blocking=True)
|
366 |
+
else:
|
367 |
+
x, y = x.to(device), y.to(device)
|
368 |
+
return x, y
|
369 |
+
|
370 |
+
|
371 |
+
st.subheader(":rainbow[LiPT: Generate New Molecules With Your Training Data]")
|
372 |
+
col1, col2, col3 = st.columns(3)
|
373 |
+
uploaded_file = st.file_uploader("Upload SMILES Data (SMILES should be in a column named smiles)", type="csv")
|
374 |
+
split_ratio = st.slider("Train-Test Split Ratio", min_value=0.01, max_value=0.99, value=0.9)
|
375 |
+
st.write("Train on {:.1f}% of data. Test on {:.1f}% of data.".format(split_ratio*100, 100-split_ratio*100))
|
376 |
+
|
377 |
+
with col1:
|
378 |
+
max_iters = st.number_input("Training Iterations", min_value=1000, value=4500, step=1)
|
379 |
+
dropout = st.number_input("Dropout", min_value=0.0, max_value=0.9, value=0.05)
|
380 |
+
learning_rate = st.number_input("Learning Rate", min_value=6e-5, max_value=1.0, value=1e-3, format="%.5f") # with baby networks can afford to go a bit higher
|
381 |
+
|
382 |
+
with col2:
|
383 |
+
model_complexity = st.number_input("Model Complexity", min_value=1, value=3, step=1)
|
384 |
+
grad_clip = st.number_input("Gradient Clipping", min_value=0.01, max_value=100.0, value=1.0) # clip gradients at this value, or disable if == 0.0
|
385 |
+
temperature = st.number_input("Randomness of Generation", min_value=0.01, max_value=100.0, value=1.0) # 1.0 = no change, < 1.0 = less random, > 1.0 = more random, in predictions
|
386 |
+
|
387 |
+
with col3:
|
388 |
+
batch_size = st.number_input("Batch Size", min_value=2, value=64, step=1)
|
389 |
+
block_size = st.number_input("Context Window", min_value=2, value=256, step=1) # context of up to 256 previous characters
|
390 |
+
num_samples = st.number_input(":violet[**Number of Molecules to Generate**]", min_value=1, value=20, step=1)
|
391 |
+
|
392 |
+
tokens_per_iter = gradient_accumulation_steps * batch_size * block_size
|
393 |
+
decay_lr = st.checkbox("Learning Rate Decay", value=True) # whether to decay the learning rate
|
394 |
+
n_layer = model_complexity
|
395 |
+
n_head = model_complexity
|
396 |
+
n_embd = 64 * model_complexity
|
397 |
+
|
398 |
+
if uploaded_file and st.button(":orange[**Train Model and Generate Molecules**]"):
|
399 |
+
lipid_data = pd.read_csv(uploaded_file).drop_duplicates(subset=['smiles'])
|
400 |
+
lipid_data['smiles'] = lipid_data['smiles'].apply(canonicalize)
|
401 |
+
lipid_data = lipid_data.dropna().sample(frac=1).reset_index(drop=True)
|
402 |
+
data = '\n'.join(lipid_data['smiles'])
|
403 |
+
chars = sorted(list(set(data)))
|
404 |
+
vocab_size = len(chars)
|
405 |
+
st.write("Number of Valid Lipids: {:d}".format(len(lipid_data)))
|
406 |
+
st.write("All unique characters:", ''.join(chars))
|
407 |
+
st.write(f"Vocabulary size: {vocab_size:,}")
|
408 |
+
stoi = {ch:i for i,ch in enumerate(chars)}
|
409 |
+
itos = {i:ch for i,ch in enumerate(chars)}
|
410 |
+
def encode(s):
|
411 |
+
return [stoi[c] for c in s]
|
412 |
+
def decode(l):
|
413 |
+
return ''.join([itos[i] for i in l])
|
414 |
+
lr_decay_iters = max_iters # make equal to max_iters usually
|
415 |
+
warmup_iters = max_iters // 50
|
416 |
+
n = len(data)
|
417 |
+
train_data = data[:int(n * split_ratio)]
|
418 |
+
val_data = data[int(n * split_ratio):]
|
419 |
+
train_ids = encode(train_data)
|
420 |
+
val_ids = encode(val_data)
|
421 |
+
st.write(f"{len(train_ids):,} tokens for training")
|
422 |
+
st.write(f"{len(val_ids):,} tokens for testing")
|
423 |
+
st.write(":orange[Patience is key π]")
|
424 |
+
train_data = np.array(train_ids, dtype=np.uint16)
|
425 |
+
val_data = np.array(val_ids, dtype=np.uint16)
|
426 |
+
meta = {'vocab_size': vocab_size, 'itos': itos, 'stoi': stoi}
|
427 |
+
|
428 |
+
iter_num = 0
|
429 |
+
best_val_loss = 1e9
|
430 |
+
meta_vocab_size = meta['vocab_size']
|
431 |
+
model_args = dict(n_layer=n_layer, n_head=n_head, n_embd=n_embd, block_size=block_size, bias=bias, vocab_size=None, dropout=dropout)
|
432 |
+
model_args['vocab_size'] = meta_vocab_size
|
433 |
+
gptconf = GPTConfig(**model_args)
|
434 |
+
model = GPT(gptconf)
|
435 |
+
if block_size < model.config.block_size:
|
436 |
+
model.crop_block_size(block_size)
|
437 |
+
model_args['block_size'] = block_size
|
438 |
+
model.to(device)
|
439 |
+
scaler = torch.cuda.amp.GradScaler(enabled=(dtype == 'float16'))
|
440 |
+
optimizer = model.configure_optimizers(weight_decay, learning_rate, (beta1, beta2), device_type)
|
441 |
+
checkpoint = None
|
442 |
+
|
443 |
+
@torch.no_grad()
|
444 |
+
def estimate_loss():
|
445 |
+
out = {}
|
446 |
+
model.eval()
|
447 |
+
for split in ['train', 'val']:
|
448 |
+
losses = torch.zeros(eval_iters)
|
449 |
+
for k in range(eval_iters):
|
450 |
+
X, Y = get_batch(split)
|
451 |
+
with ctx:
|
452 |
+
logits, loss = model(X, Y)
|
453 |
+
losses[k] = loss.item()
|
454 |
+
out[split] = losses.mean()
|
455 |
+
model.train()
|
456 |
+
return out
|
457 |
+
|
458 |
+
def get_lr(it):
|
459 |
+
if it < warmup_iters:
|
460 |
+
return learning_rate * it / warmup_iters
|
461 |
+
if it > lr_decay_iters:
|
462 |
+
return min_lr
|
463 |
+
decay_ratio = (it - warmup_iters) / (lr_decay_iters - warmup_iters)
|
464 |
+
assert 0 <= decay_ratio <= 1
|
465 |
+
coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio)) # coeff ranges 0..1
|
466 |
+
return min_lr + coeff * (learning_rate - min_lr)
|
467 |
+
|
468 |
+
X, Y = get_batch('train') # fetch the very first batch
|
469 |
+
t0 = time.time()
|
470 |
+
local_iter_num = 0 # number of iterations in the lifetime of this process
|
471 |
+
raw_model = model # unwrap DDP container if needed
|
472 |
+
running_mfu = -1.0
|
473 |
+
|
474 |
+
while True:
|
475 |
+
lr = get_lr(iter_num) if decay_lr else learning_rate
|
476 |
+
for param_group in optimizer.param_groups:
|
477 |
+
param_group['lr'] = lr
|
478 |
+
|
479 |
+
if iter_num % eval_interval == 0 and master_process:
|
480 |
+
losses = estimate_loss()
|
481 |
+
print(f"step {iter_num}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}")
|
482 |
+
|
483 |
+
if losses['val'] < best_val_loss or always_save_checkpoint:
|
484 |
+
best_val_loss = losses['val']
|
485 |
+
if iter_num > 0:
|
486 |
+
checkpoint = {
|
487 |
+
'model': raw_model.state_dict(),
|
488 |
+
'optimizer': optimizer.state_dict(),
|
489 |
+
'model_args': model_args,
|
490 |
+
'iter_num': iter_num,
|
491 |
+
'best_val_loss': best_val_loss,
|
492 |
+
'config': config,
|
493 |
+
}
|
494 |
+
print("saving checkpoint")
|
495 |
+
torch.save(checkpoint, 'ckpt.pt')
|
496 |
+
if iter_num == 0 and eval_only:
|
497 |
+
break
|
498 |
+
for micro_step in range(gradient_accumulation_steps):
|
499 |
+
with ctx:
|
500 |
+
logits, loss = model(X, Y)
|
501 |
+
loss = loss / gradient_accumulation_steps # scale the loss to account for gradient accumulation
|
502 |
+
X, Y = get_batch('train')
|
503 |
+
scaler.scale(loss).backward()
|
504 |
+
if grad_clip != 0.0:
|
505 |
+
scaler.unscale_(optimizer)
|
506 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clip)
|
507 |
+
scaler.step(optimizer)
|
508 |
+
scaler.update()
|
509 |
+
optimizer.zero_grad(set_to_none=True)
|
510 |
+
t1 = time.time()
|
511 |
+
dt = t1 - t0
|
512 |
+
t0 = t1
|
513 |
+
if iter_num % log_interval == 0 and master_process:
|
514 |
+
lossf = loss.item() * gradient_accumulation_steps
|
515 |
+
if local_iter_num >= 5: # let the training loop settle a bit
|
516 |
+
mfu = raw_model.estimate_mfu(batch_size * gradient_accumulation_steps, dt)
|
517 |
+
running_mfu = mfu if running_mfu == -1.0 else 0.9*running_mfu + 0.1*mfu
|
518 |
+
print(f"iter {iter_num}: loss {lossf:.4f}, time {dt*1000:.2f}ms, mfu {running_mfu*100:.2f}%")
|
519 |
+
iter_num += 1
|
520 |
+
local_iter_num += 1
|
521 |
+
if iter_num > max_iters:
|
522 |
+
break
|
523 |
+
|
524 |
+
start = "\n"
|
525 |
+
max_new_tokens = 512 # number of tokens generated in each sample
|
526 |
+
top_k = 100 # retain only the top_k most likely tokens, clamp others to have 0 probability
|
527 |
+
start_ids = encode(start)
|
528 |
+
x = (torch.tensor(start_ids, dtype=torch.long, device=device)[None, ...])
|
529 |
+
gen_smiles = []
|
530 |
+
with torch.no_grad():
|
531 |
+
with ctx:
|
532 |
+
while len(gen_smiles) < num_samples:
|
533 |
+
y = model.generate(x, max_new_tokens, temperature=temperature, top_k=top_k)
|
534 |
+
smiles = decode(y[0].tolist()).replace('\n', '')
|
535 |
+
mol = Chem.MolFromSmiles(smiles)
|
536 |
+
if mol:
|
537 |
+
smiles = Chem.MolToSmiles(mol)
|
538 |
+
if (smiles not in gen_smiles) and (smiles not in data):
|
539 |
+
gen_smiles.append(smiles)
|
540 |
+
|
541 |
+
print(gen_smiles)
|
542 |
+
smiles_df = pd.DataFrame(gen_smiles, columns=['smiles'])
|
543 |
+
st.table(smiles_df)
|
544 |
+
csv_data = smiles_df.to_csv(index=False)
|
545 |
+
st.download_button(label="Download CSV", data=csv_data, file_name="generated_smiles.csv", mime="text/csv")
|
546 |
+
st.image(Draw.MolToImage(Chem.MolFromSmiles(gen_smiles[0]), size=(600, 600)), caption='First Generated Molecule', use_column_width=True)
|
547 |
+
|