File size: 4,058 Bytes
c57cc05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Hizli taban cizgisi: kucuk davranis klonlama (BC) politikasi, temasli (durum 7 = 4 + 3 temas) ya da temassiz (durum 4).
# Girdi: 96x96 kirpilmis kamera (veri/kucuk.npz) + durum; cikti: tek adim eylem (dx, dy, dz, sikma).
# Ag: 4 katmanli CNN + uzamsal softmax (nesne konumu icin) + MLP. Rastgele kaydirma artirimi (+-4 piksel).
# Kullanim: python bc.py <temasli|temassiz> <tohum> [adim=20000]   -> modeller/bc_<tur>_<tohum>.pt
import sys, time, json
from pathlib import Path
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F

KOK = Path(__file__).resolve().parent


class UzamsalSoftmax(nn.Module):
    def forward(self, x):
        b, c, h, w = x.shape
        p = F.softmax(x.flatten(2), -1).view(b, c, h, w)
        ys = torch.linspace(-1, 1, h, device=x.device); xs = torch.linspace(-1, 1, w, device=x.device)
        return torch.cat([(p.sum(2) * xs).sum(-1), (p.sum(3) * ys).sum(-1)], 1)


class BC(nn.Module):
    def __init__(self, durum_boyut):
        super().__init__()
        self.cnn = nn.Sequential(
            nn.Conv2d(3, 32, 5, 2, 2), nn.GroupNorm(8, 32), nn.ReLU(),
            nn.Conv2d(32, 64, 3, 1, 1), nn.GroupNorm(8, 64), nn.ReLU(),
            nn.Conv2d(64, 64, 3, 2, 1), nn.GroupNorm(8, 64), nn.ReLU(),
            nn.Conv2d(64, 64, 3, 1, 1), UzamsalSoftmax())
        self.mlp = nn.Sequential(nn.Linear(128 + durum_boyut, 512), nn.ReLU(), nn.Linear(512, 512), nn.ReLU(), nn.Linear(512, 4))
        self.durum_boyut = durum_boyut
        for ad in ("d_ort", "d_std", "e_ort", "e_std"):
            self.register_buffer(ad, torch.zeros(durum_boyut if ad.startswith("d") else 4))

    def forward(self, img, durum):  # img: B,3,96,96 float [0,1]; durum ham
        z = self.cnn(img * 2 - 1)
        d = (durum - self.d_ort) / self.d_std
        return self.mlp(torch.cat([z, d], 1))

    @torch.no_grad()
    def eylem(self, img_u8, durum):
        x = torch.from_numpy(img_u8).permute(2, 0, 1)[None].float().to(self.d_ort.device) / 255
        d = torch.from_numpy(durum)[None].float().to(self.d_ort.device)
        return (self(x, d) * self.e_std + self.e_ort)[0].cpu().numpy()


def kaydir(x, p=4):
    b, c, h, w = x.shape
    x = F.pad(x, (p, p, p, p), mode="replicate")
    i = torch.randint(0, 2 * p + 1, (2,))
    return x[:, :, i[0]:i[0] + h, i[1]:i[1] + w]


if __name__ == "__main__":
    tur, tohum = sys.argv[1], int(sys.argv[2]); ADIM = int(sys.argv[3]) if len(sys.argv) > 3 else 20000
    torch.manual_seed(tohum); np.random.seed(tohum)
    v = np.load(KOK / "veri" / "kucuk.npz")
    durum = v["durum"] if tur == "temassiz" else np.concatenate([v["durum"], v["temas"][:, :3]], 1)  # ilk toplamada 4. kanal (kiskac) vardi, kullanilmaz
    img = torch.from_numpy(v["img"])  # uint8 NHWC, CPU (kopyasiz, RAM icin)
    durum = torch.from_numpy(durum).float(); eylem = torch.from_numpy(v["eylem"]).float()
    cihaz = "cuda" if torch.cuda.is_available() else "cpu"
    m = BC(durum.shape[1]).to(cihaz)
    m.d_ort[:] = durum.mean(0); m.d_std[:] = durum.std(0) + 1e-3
    m.e_ort[:] = eylem.mean(0); m.e_std[:] = eylem.std(0) + 1e-3
    hedef = ((eylem - m.e_ort.cpu()) / m.e_std.cpu())
    opt = torch.optim.AdamW(m.parameters(), 3e-4, weight_decay=1e-4)
    sch = torch.optim.lr_scheduler.CosineAnnealingLR(opt, ADIM)
    n = len(eylem); t0 = time.time(); B = 256
    for adim in range(ADIM):
        i = torch.randint(0, n, (B,))
        x = kaydir(img[i].to(cihaz).permute(0, 3, 1, 2).float() / 255)
        kayip = F.mse_loss(m(x, durum[i].to(cihaz)), hedef[i].to(cihaz))
        opt.zero_grad(); kayip.backward(); opt.step(); sch.step()
        if adim % 1000 == 0:
            print(f"{tur} tohum {tohum} adim {adim} kayip {kayip.item():.4f} {time.time() - t0:.0f} sn", flush=True)
    (KOK / "modeller").mkdir(exist_ok=True)
    yol = KOK / "modeller" / f"bc_{tur}_{tohum}.pt"
    torch.save({"durum_boyut": durum.shape[1], "agirlik": m.state_dict()}, yol)
    print("KAYDEDILDI", yol, flush=True)