import os
os.environ['CUDA_VISIBLE_DEVICES']='2'
import shutil,timm,os,torch,random,datasets,math
import fastcore.all as fc, numpy as np, matplotlib as mpl, matplotlib.pyplot as plt
import k_diffusion as K, torchvision.transforms as T
import torchvision.transforms.functional as TF,torch.nn.functional as F
from torch.utils.data import DataLoader,default_collate
from pathlib import Path
from torch.nn import init
from fastcore.foundation import L
from torch import nn,tensor
from operator import itemgetter
from torcheval.metrics import MulticlassAccuracy
from functools import partial
from torch.optim import lr_scheduler
from torch import optim
from torchvision.io import read_image,ImageReadMode
from glob import glob
from miniai.datasets import *
from miniai.conv import *
from miniai.learner import *
from miniai.activations import *
from miniai.init import *
from miniai.sgd import *
from miniai.resnet import *
from miniai.augment import *
from miniai.accel import *
from miniai.training import *
from fastprogress import progress_bar
torch.set_printoptions(precision=5, linewidth=140, sci_mode=False)
torch.manual_seed(1)
mpl.rcParams['figure.dpi'] = 70
set_seed(42)
if fc.defaults.cpus>8: fc.defaults.cpus=8
path_data = Path('data')
path_data.mkdir(exist_ok=True)
path = path_data/'tiny-imagenet-200'
url = 'http://cs231n.stanford.edu/tiny-imagenet-200.zip'
if not path.exists():
path_zip = fc.urlsave(url, path_data)
shutil.unpack_archive('data/tiny-imagenet-200.zip', 'data')
bs = 512
class TinyDS:
def __init__(self, path):
self.path = Path(path)
self.files = glob(str(path/'**/*.JPEG'), recursive=True)
def __len__(self): return len(self.files)
def __getitem__(self, i): return self.files[i],Path(self.files[i]).parent.parent.name
tds = TinyDS(path/'train')
path_anno = path/'val'/'val_annotations.txt'
anno = dict(o.split('\t')[:2] for o in path_anno.read_text().splitlines())
class TinyValDS(TinyDS):
def __getitem__(self, i): return self.files[i],anno[os.path.basename(self.files[i])]
vds = TinyValDS(path/'val')
class TfmDS:
def __init__(self, ds, tfmx=fc.noop, tfmy=fc.noop): self.ds,self.tfmx,self.tfmy = ds,tfmx,tfmy
def __len__(self): return len(self.ds)
def __getitem__(self, i):
x,y = self.ds[i]
return self.tfmx(x),self.tfmy(y)
id2str = (path/'wnids.txt').read_text().splitlines()
str2id = {v:k for k,v in enumerate(id2str)}
xmean,xstd = (tensor([0.47565, 0.40303, 0.31555]), tensor([0.28858, 0.24402, 0.26615]))
def tfmx(x):
img = read_image(x, mode=ImageReadMode.RGB)/255
return (img-xmean[:,None,None])/xstd[:,None,None]
def tfmy(y): return tensor(str2id[y])
tfm_tds = TfmDS(tds, tfmx, tfmy)
tfm_vds = TfmDS(vds, tfmx, tfmy)
def denorm(x): return (x*xstd[:,None,None]+xmean[:,None,None]).clip(0,1)
all_synsets = [o.split('\t') for o in (path/'words.txt').read_text().splitlines()]
synsets = {k:v.split(',', maxsplit=1)[0] for k,v in all_synsets if k in id2str}
dls = DataLoaders(*get_dls(tfm_tds, tfm_vds, bs=bs, num_workers=8))
def tfm_batch(b, tfm_x=fc.noop, tfm_y = fc.noop): return tfm_x(b[0]),tfm_y(b[1])
tfms = nn.Sequential(T.Pad(4), T.RandomCrop(64),
T.RandomHorizontalFlip(),
RandErase())
augcb = BatchTransformCB(partial(tfm_batch, tfm_x=tfms), on_val=False)
act_gr = partial(GeneralRelu, leak=0.1, sub=0.4)
iw = partial(init_weights, leaky=0.1)
nfs = (32,64,128,256,512,1024)
def get_dropmodel(act=act_gr, nfs=nfs, norm=nn.BatchNorm2d, drop=0.1):
layers = [nn.Conv2d(3, nfs[0], 5, padding=2)]
# layers += [ResBlock(nfs[0], nfs[0], ks=3, stride=1, act=act, norm=norm)]
layers += [ResBlock(nfs[i], nfs[i+1], act=act, norm=norm, stride=2)
for i in range(len(nfs)-1)]
layers += [nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Dropout(drop)]
layers += [nn.Linear(nfs[-1], 200, bias=False), nn.BatchNorm1d(200)]
return nn.Sequential(*layers).apply(iw)
def res_blocks(n_bk, ni, nf, stride=1, ks=3, act=act_gr, norm=None):
return nn.Sequential(*[
ResBlock(ni if i==0 else nf, nf, stride=stride if i==n_bk-1 else 1, ks=ks, act=act, norm=norm)
for i in range(n_bk)])
nbks = (3,2,2,1,1)
def get_dropmodel(act=act_gr, nfs=nfs, nbks=nbks, norm=nn.BatchNorm2d, drop=0.2):
layers = [ResBlock(3, nfs[0], ks=5, stride=1, act=act, norm=norm)]
layers += [res_blocks(nbks[i], nfs[i], nfs[i+1], act=act, norm=norm, stride=2)
for i in range(len(nfs)-1)]
layers += [nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Dropout(drop)]
layers += [nn.Linear(nfs[-1], 200, bias=False), nn.BatchNorm1d(200)]
return nn.Sequential(*layers).apply(iw)
opt_func = partial(optim.AdamW, eps=1e-5)
metrics = MetricsCB(accuracy=MulticlassAccuracy())
cbs = [DeviceCB(), metrics, ProgressCB(plot=True), MixedPrecision()]
epochs = 25
lr = 3e-2
tmax = epochs * len(dls.train)
sched = partial(lr_scheduler.OneCycleLR, max_lr=lr, total_steps=tmax)
xtra = [BatchSchedCB(sched), augcb]
learn = Learner(get_dropmodel(), dls, F.cross_entropy, lr=lr, cbs=cbs+xtra, opt_func=opt_func)
aug_tfms = nn.Sequential(T.Pad(4), T.RandomCrop(64),
T.RandomHorizontalFlip(),
T.TrivialAugmentWide())
norm_tfm = T.Normalize(xmean, xstd)
erase_tfm = RandErase()
from PIL import Image
def tfmx(x, aug=False):
x = Image.open(x).convert('RGB')
if aug: x = aug_tfms(x)
x = TF.to_tensor(x)
x = norm_tfm(x)
if aug: x = erase_tfm(x[None])[0]
return x
tfm_tds = TfmDS(tds, partial(tfmx, aug=True), tfmy)
tfm_vds = TfmDS(vds, tfmx, tfmy)
dls = DataLoaders(*get_dls(tfm_tds, tfm_vds, bs=bs, num_workers=8))
def conv(ni, nf, ks=3, stride=1, act=nn.ReLU, norm=None, bias=True):
layers = []
if norm: layers.append(norm(ni))
if act : layers.append(act())
layers.append(nn.Conv2d(ni, nf, stride=stride, kernel_size=ks, padding=ks//2, bias=bias))
return nn.Sequential(*layers)
def _conv_block(ni, nf, stride, act=act_gr, norm=None, ks=3):
return nn.Sequential(conv(ni, nf, stride=1 , act=act, norm=norm, ks=ks),
conv(nf, nf, stride=stride, act=act, norm=norm, ks=ks))
class ResBlock(nn.Module):
def __init__(self, ni, nf, stride=1, ks=3, act=act_gr, norm=None):
super().__init__()
self.convs = _conv_block(ni, nf, stride, act=act, ks=ks, norm=norm)
self.idconv = fc.noop if ni==nf else conv(ni, nf, ks=1, stride=1, act=None, norm=norm)
self.pool = fc.noop if stride==1 else nn.AvgPool2d(2, ceil_mode=True)
def forward(self, x): return self.convs(x) + self.idconv(self.pool(x))
def get_dropmodel(act=act_gr, nfs=nfs, nbks=nbks, norm=nn.BatchNorm2d, drop=0.2):
layers = [nn.Conv2d(3, nfs[0], 5, padding=2)]
layers += [res_blocks(nbks[i], nfs[i], nfs[i+1], act=act, norm=norm, stride=2)
for i in range(len(nfs)-1)]
layers += [act_gr(), norm(nfs[-1]), nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Dropout(drop)]
layers += [nn.Linear(nfs[-1], 200, bias=False), nn.BatchNorm1d(200)]
return nn.Sequential(*layers).apply(iw)
epochs = 50
lr = 0.1
tmax = epochs * len(dls.train)
sched = partial(lr_scheduler.OneCycleLR, max_lr=lr, total_steps=tmax)
xtra = [BatchSchedCB(sched)]
model = get_dropmodel(nbks=(1,2,8,2,2), nfs=(32, 64, 128, 512, 1024, 1536), drop=0.1)
learn = Learner(model, dls, F.cross_entropy, lr=lr, cbs=cbs+xtra, opt_func=opt_func)
learn.fit(epochs)
accuracy | loss | epoch | train |
---|---|---|---|
0.015 | 5.158 | 0 | train |
0.023 | 5.090 | 0 | eval |
0.034 | 4.887 | 1 | train |
0.046 | 4.680 | 1 | eval |
0.061 | 4.598 | 2 | train |
0.071 | 4.396 | 2 | eval |
0.087 | 4.372 | 3 | train |
0.113 | 4.117 | 3 | eval |
0.116 | 4.149 | 4 | train |
0.129 | 3.990 | 4 | eval |
0.148 | 3.926 | 5 | train |
0.172 | 3.757 | 5 | eval |
0.179 | 3.731 | 6 | train |
0.148 | 4.018 | 6 | eval |
0.202 | 3.588 | 7 | train |
0.191 | 3.779 | 7 | eval |
0.225 | 3.445 | 8 | train |
0.219 | 3.526 | 8 | eval |
0.246 | 3.335 | 9 | train |
0.270 | 3.160 | 9 | eval |
0.266 | 3.219 | 10 | train |
0.253 | 3.446 | 10 | eval |
0.282 | 3.139 | 11 | train |
0.272 | 3.223 | 11 | eval |
0.300 | 3.042 | 12 | train |
0.255 | 3.408 | 12 | eval |
0.309 | 2.981 | 13 | train |
0.291 | 3.183 | 13 | eval |
0.323 | 2.907 | 14 | train |
0.344 | 2.821 | 14 | eval |
0.335 | 2.850 | 15 | train |
0.310 | 3.166 | 15 | eval |
0.349 | 2.782 | 16 | train |
0.316 | 3.086 | 16 | eval |
0.360 | 2.734 | 17 | train |
0.357 | 2.740 | 17 | eval |
0.367 | 2.689 | 18 | train |
0.371 | 2.696 | 18 | eval |
0.375 | 2.644 | 19 | train |
0.341 | 2.891 | 19 | eval |
0.385 | 2.595 | 20 | train |
0.395 | 2.646 | 20 | eval |
0.394 | 2.551 | 21 | train |
0.419 | 2.420 | 21 | eval |
0.403 | 2.503 | 22 | train |
0.400 | 2.573 | 22 | eval |
0.415 | 2.454 | 23 | train |
0.398 | 2.589 | 23 | eval |
0.423 | 2.412 | 24 | train |
0.415 | 2.497 | 24 | eval |
0.430 | 2.376 | 25 | train |
0.370 | 2.784 | 25 | eval |
0.440 | 2.320 | 26 | train |
0.403 | 2.591 | 26 | eval |
0.452 | 2.267 | 27 | train |
0.400 | 2.698 | 27 | eval |
0.462 | 2.219 | 28 | train |
0.453 | 2.326 | 28 | eval |
0.474 | 2.156 | 29 | train |
0.441 | 2.400 | 29 | eval |
0.485 | 2.099 | 30 | train |
0.466 | 2.261 | 30 | eval |
0.497 | 2.037 | 31 | train |
0.477 | 2.204 | 31 | eval |
0.514 | 1.964 | 32 | train |
0.504 | 2.081 | 32 | eval |
0.528 | 1.899 | 33 | train |
0.514 | 2.075 | 33 | eval |
0.543 | 1.826 | 34 | train |
0.516 | 2.073 | 34 | eval |
0.562 | 1.743 | 35 | train |
0.506 | 2.135 | 35 | eval |
0.581 | 1.652 | 36 | train |
0.543 | 1.935 | 36 | eval |
0.602 | 1.566 | 37 | train |
0.544 | 1.965 | 37 | eval |
0.624 | 1.466 | 38 | train |
0.568 | 1.855 | 38 | eval |
0.644 | 1.377 | 39 | train |
0.596 | 1.684 | 39 | eval |
0.672 | 1.259 | 40 | train |
0.599 | 1.689 | 40 | eval |
0.698 | 1.156 | 41 | train |
0.609 | 1.716 | 41 | eval |
0.725 | 1.049 | 42 | train |
0.627 | 1.622 | 42 | eval |
0.749 | 0.954 | 43 | train |
0.629 | 1.606 | 43 | eval |
0.774 | 0.861 | 44 | train |
0.638 | 1.577 | 44 | eval |
0.794 | 0.790 | 45 | train |
0.643 | 1.572 | 45 | eval |
0.809 | 0.737 | 46 | train |
0.648 | 1.564 | 46 | eval |
0.821 | 0.687 | 47 | train |
0.652 | 1.549 | 47 | eval |
0.827 | 0.665 | 48 | train |
0.654 | 1.545 | 48 | eval |
0.830 | 0.660 | 49 | train |
0.654 | 1.546 | 49 | eval |
torch.save(learn.model, 'models/inettiny-wide-50')