"""Хичээл 3: ахисан аргуудыг CPU дээр харьцуулах туршилт.

python code/lesson4_core.py --epochs 10
Зохиомол өгөгдөл (synthetic data) нь босоо, хэвтээ зураастай 16×16 зураг юм.
Компьютерийн харааны (computer vision, CV) бодит өгөгдөл дээрх жишиг үнэлгээ (benchmark) биш.
"""
import argparse
import copy
import json
import random
import torch
from torch import nn
from torch.nn import functional as F


def seed_all(seed):
    random.seed(seed)
    torch.manual_seed(seed)


def make_data(n, seed):
    g = torch.Generator().manual_seed(seed)
    y = torch.arange(n) % 2
    x = torch.rand(n, 1, 16, 16, generator=g) * .35
    for i in range(n):
        p = int(torch.randint(3, 12, (1,), generator=g))
        if y[i] == 0:
            x[i, :, :, p:p+2] += .65
        else:
            x[i, :, p:p+2, :] += .65
    order = torch.randperm(n, generator=g)
    return x[order].clamp(0, 1), y[order]


def network(width=8):
    return nn.Sequential(
        nn.Conv2d(1, width, 3, padding=1), nn.ReLU(),
        nn.Conv2d(width, width, 3, padding=1), nn.ReLU(),
        nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(width, 2))


def mixup(x, y, alpha=.4):
    lam = float(torch.distributions.Beta(alpha, alpha).sample())
    order = torch.randperm(len(x), device=x.device)
    return lam*x + (1-lam)*x[order], y, y[order], lam


def cutmix(x, y, alpha=1.):
    lam = float(torch.distributions.Beta(alpha, alpha).sample())
    order = torch.randperm(len(x), device=x.device)
    h, w = x.shape[-2:]
    size = (1-lam)**.5
    ch, cw = int(h*size), int(w*size)
    cy, cx = random.randrange(h), random.randrange(w)
    y1, y2 = max(0, cy-ch//2), min(h, cy+(ch+1)//2)
    x1, x2 = max(0, cx-cw//2), min(w, cx+(cw+1)//2)
    mixed = x.clone()
    mixed[:, :, y1:y2, x1:x2] = x[order, :, y1:y2, x1:x2]
    actual_lam = 1 - ((y2-y1)*(x2-x1))/(h*w)
    return mixed, y, y[order], actual_lam


def distill_loss(student_logits, teacher_logits, y, temperature=2., alpha=.5):
    # KL(teacher || student): багш загварын градиент (teacher gradient) тооцохгүй.
    # Ангилал тус бүрийн магадлалыг (class probability) dim=1 дагуу нормчилно (normalize).
    soft = F.kl_div(F.log_softmax(student_logits/temperature, dim=1),
                    F.softmax(teacher_logits.detach()/temperature, dim=1),
                    reduction='batchmean') * temperature**2
    return (1-alpha)*F.cross_entropy(student_logits, y) + alpha*soft


@torch.no_grad()
def measure(model, x, y, tta=False):
    model.eval()
    p = model(x).softmax(1)
    if tta:
        # Эдгээр зурагт хэвтээ тусгал (horizontal flip) хийхэд зөв ангилал (class) өөрчлөгдөхгүй.
        p = (p + model(x.flip(-1)).softmax(1))/2
    return float((p.argmax(1) == y).float().mean())


def train(x, y, vx, vy, epochs, mode='plain', width=8, teacher=None, seed=42):
    # Хувилбар бүрд санамсаргүй эхлэлийн утга (seed), сургалтын өгөгдлийн хуваалт (training split) ижил.
    seed_all(seed)
    model = network(width)
    opt = torch.optim.AdamW(model.parameters(), lr=.01, weight_decay=.001)
    best_acc, best_loss, best = -1., float('inf'), None
    for _ in range(epochs):
        model.train()
        for ids in torch.randperm(len(x)).split(32):
            bx, by = x[ids], y[ids]
            if mode in ('mixup', 'cutmix'):
                bx, ya, yb, lam = (mixup if mode == 'mixup' else cutmix)(bx, by)
                logits = model(bx)
                loss = lam*F.cross_entropy(logits, ya)+(1-lam)*F.cross_entropy(logits, yb)
            elif mode == 'distill':
                teacher.eval()
                with torch.no_grad():
                    teacher_logits = teacher(bx)
                loss = distill_loss(model(bx), teacher_logits, by)
            else:
                loss = F.cross_entropy(model(bx), by,
                                       label_smoothing=.1 if mode == 'smooth' else 0.)
            opt.zero_grad(set_to_none=True)
            loss.backward()
            opt.step()
        acc = measure(model, vx, vy)
        with torch.no_grad():
            validation_loss = float(F.cross_entropy(model(vx), vy))
        if validation_loss < best_loss:
            best_acc, best_loss, best = acc, validation_loss, copy.deepcopy(model.state_dict())
    model.load_state_dict(best)
    return model, best_acc


def numerical_checks():
    x = torch.tensor([[1., 3.], [5., 7.]])
    assert torch.allclose(.75*x[0]+.25*x[1], torch.tensor([2., 4.]))
    assert abs(1 - (8*8)/(32*32) - .9375) < 1e-9
    logits = torch.tensor([[2., 0., -1.]])
    target = torch.tensor([0])
    q = torch.tensor([[.933333333, .033333333, .033333333]])
    manual = -(q*logits.log_softmax(1)).sum()
    assert torch.allclose(manual, F.cross_entropy(logits, target, label_smoothing=.1))
    print('Тооцооллын шалгалт: Mixup, CutMix, шошго зөөллөх (label smoothing) зөв.')


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--epochs', type=int, default=10)
    parser.add_argument('--seed', type=int, default=42)
    parser.add_argument('--threshold', type=float, default=.9)
    args = parser.parse_args()
    if args.epochs < 1:
        parser.error('Нэг бүтэн давталтын тоо (epoch count) 1-ээс багагүй байна: epochs >= 1')
    if not 0 <= args.threshold <= 1:
        parser.error('Итгэлийн босго (confidence threshold) [0, 1] мужид байна: threshold')
    torch.set_num_threads(1)
    numerical_checks()
    x, y = make_data(256, 1)
    vx, vy = make_data(96, 2)
    # Шошгогүй өгөгдлийн санг (unlabeled pool) сургалт, баталгаажуулалт, шалгалтын хэсгээс тусдаа үүсгэнэ.
    ux, _ = make_data(128, 3)
    results = {}
    for mode in ('plain', 'mixup', 'cutmix', 'smooth'):
        model, acc = train(x, y, vx, vy, args.epochs, mode=mode, seed=args.seed)
        results[mode] = {'validation_accuracy': round(acc, 4)}
        if mode == 'plain':
            teacher = model
            results[mode]['tta_accuracy'] = round(measure(model, vx, vy, tta=True), 4)
    teacher.eval()
    with torch.no_grad():
        confidence, pseudo_y = teacher(ux).softmax(1).max(1)
    keep = confidence >= args.threshold
    accepted = int(keep.sum())
    if accepted:
        px = torch.cat([x, ux[keep]])
        py = torch.cat([y, pseudo_y[keep]])
        _, acc = train(px, py, vx, vy, args.epochs, seed=args.seed)
        results['pseudo_label'] = {'accepted': accepted, 'pool': len(ux),
                                   'validation_accuracy': round(acc, 4)}
    else:
        results['pseudo_label'] = {'accepted': 0, 'pool': len(ux),
                                   'status': 'Итгэлийн босго (confidence threshold) давсан жишээ алга; нэмэлтээр сургахгүй.'}
    _, small_acc = train(x, y, vx, vy, args.epochs, width=4, seed=args.seed)
    student, kd_acc = train(x, y, vx, vy, args.epochs, mode='distill', width=4, teacher=teacher, seed=args.seed)
    results['student'] = {'plain_accuracy': round(small_acc, 4),
                          'distilled_accuracy': round(kd_acc, 4),
                          'student_parameters': sum(p.numel() for p in student.parameters()),
                          'teacher_parameters': sum(p.numel() for p in teacher.parameters())}
    print(json.dumps(results, ensure_ascii=False, indent=2))
    print('Энэ туршилт код ажиллаж буйг шалгана. Зохиомол өгөгдөл (synthetic data) дээрх үр дүн аль нэг аргыг бүх бодлогод давуу гэдгийг нотлохгүй.')


if __name__ == '__main__':
    main()
