Add files using upload-large-folder tool
Browse files- checkpoints/base_obj/save1.ckpt +2 -2
- checkpoints/base_obj/save2.ckpt +1 -1
- checkpoints/base_obj/save3.ckpt +1 -1
- checkpoints/base_obj/save4.ckpt +2 -2
- checkpoints/enh1_seg/save2.ckpt +1 -1
- checkpoints/enh1_seg/save3.ckpt +1 -1
- checkpoints/enh1_seg/save4.ckpt +2 -2
- checkpoints/mmcrc/save1.ckpt +1 -1
- checkpoints/mmcrc/save2.ckpt +1 -1
- checkpoints/mmcrc/save3.ckpt +2 -2
- checkpoints/mmcrc/save4.ckpt +1 -1
- checkpoints/mmcrc/train_mmcrc.py +529 -0
checkpoints/base_obj/save1.ckpt
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:87151c4b4f3175cbb766a2a1dce90da2c6f4d96ac8f4e46e9c87bd4895b0ddec
|
| 3 |
+
size 2307551566
|
checkpoints/base_obj/save2.ckpt
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
size 2307551566
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0f804487db498067355d818d10e1af0e815c49dd07d603c3e5e57a02e0f8e14d
|
| 3 |
size 2307551566
|
checkpoints/base_obj/save3.ckpt
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
size 2307663837
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:03c28b1c712d9444a3d16bf0021d223ef68b1c9bcad8d87bc5fe4a3c25afbe3d
|
| 3 |
size 2307663837
|
checkpoints/base_obj/save4.ckpt
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4f0aff9d7e5cf6c9f2be2d8770fd3e852e6d97b87d5d1c1e8654f5b39606a101
|
| 3 |
+
size 2307551566
|
checkpoints/enh1_seg/save2.ckpt
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
size 2942276640
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7737205f9cd97e12afe6017b95789d8a7daf40740aa235a3e5923e1a97cde2f2
|
| 3 |
size 2942276640
|
checkpoints/enh1_seg/save3.ckpt
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
size 2942276640
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0838501c154d0ffddb2b9895b303b2c248bb7656e130e2e2bde35f24232de01c
|
| 3 |
size 2942276640
|
checkpoints/enh1_seg/save4.ckpt
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f69f640e5e189ec1535f1444d0d4720593819a7a1055325aad3b5679035e9f0b
|
| 3 |
+
size 2942418112
|
checkpoints/mmcrc/save1.ckpt
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
size 1994391952
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3cb6e66d0fc3b91ac6e3211df4d78e559d1e5bdc3f88da6eb62902c95b39fb28
|
| 3 |
size 1994391952
|
checkpoints/mmcrc/save2.ckpt
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
size 1994391952
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:91debd0e921ca035692aec0341edc268a430fedb30b87406d0b18cd288843845
|
| 3 |
size 1994391952
|
checkpoints/mmcrc/save3.ckpt
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f1e2e2816c45678c90e160edf5557c80064a2336d1a1169fe9b4402465661938
|
| 3 |
+
size 1994391952
|
checkpoints/mmcrc/save4.ckpt
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
size 1994394981
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4c5ab3c7475dcf8e45fb3c32f1be8634b4fc9d1cfdec877fa3b22879629f6057
|
| 3 |
size 1994394981
|
checkpoints/mmcrc/train_mmcrc.py
ADDED
|
@@ -0,0 +1,529 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 InterDigital Communications, Inc.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
import math
|
| 17 |
+
import random
|
| 18 |
+
import shutil
|
| 19 |
+
import sys
|
| 20 |
+
import time
|
| 21 |
+
import os
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
import torch.nn as nn
|
| 25 |
+
import torch.optim as optim
|
| 26 |
+
|
| 27 |
+
from torch.utils.data import DataLoader
|
| 28 |
+
from torchvision import transforms
|
| 29 |
+
|
| 30 |
+
from compressai.datasets import ImageFolder
|
| 31 |
+
from compressai.zoo import models
|
| 32 |
+
from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
|
| 33 |
+
from PIL import Image
|
| 34 |
+
import requests
|
| 35 |
+
# from transformers import CLIPProcessor, CLIPVisionModel
|
| 36 |
+
from collections import OrderedDict
|
| 37 |
+
from compressai.models.retinanet.dataloader import CocoDataset, CSVDataset, collater, Resizer, AspectRatioBasedSampler, Augmenter, \
|
| 38 |
+
Normalizer
|
| 39 |
+
from compressai.models.retinanet import losses
|
| 40 |
+
|
| 41 |
+
# file_dir = os.path.dirname(__file__)
|
| 42 |
+
# sys.path.append(file_dir)
|
| 43 |
+
|
| 44 |
+
class RateDistortionLoss(nn.Module):
|
| 45 |
+
"""Custom rate distortion loss with a Lagrangian parameter."""
|
| 46 |
+
|
| 47 |
+
def __init__(self, lmbda=1e-2):
|
| 48 |
+
super().__init__()
|
| 49 |
+
self.mse = nn.MSELoss()
|
| 50 |
+
self.lmbda = lmbda
|
| 51 |
+
self.focalLoss = losses.FocalLoss()
|
| 52 |
+
|
| 53 |
+
def forward(self, input, output, target):
|
| 54 |
+
N, _, H, W = input.size()
|
| 55 |
+
out = {}
|
| 56 |
+
num_pixels = N * H * W
|
| 57 |
+
|
| 58 |
+
out["bpp_loss"] = sum(
|
| 59 |
+
(torch.log(likelihoods).sum() / (-math.log(2) * num_pixels))
|
| 60 |
+
for likelihoods in output["likelihoods"].values()
|
| 61 |
+
)
|
| 62 |
+
out["mse_loss"],out["feature_loss"] = 0,0
|
| 63 |
+
out['obect_loss'] = [0,0]
|
| 64 |
+
out["mse_loss"] = self.mse(input, output["decompressedImage"])
|
| 65 |
+
# out["feature_loss"] = self.mse(output["Student_output_features"][0], output["Teacher_output_features"][0]) + \
|
| 66 |
+
# self.mse(output["Student_output_features"][1], output["Teacher_output_features"][1]) + \
|
| 67 |
+
# self.mse(output["Student_output_features"][2], output["Teacher_output_features"][2])
|
| 68 |
+
# out['obect_loss'] = self.focalLoss(output["Student_classification"],
|
| 69 |
+
# output["Student_regression"],
|
| 70 |
+
# output["Student_anchors"],
|
| 71 |
+
# target)
|
| 72 |
+
out["loss"] = self.lmbda * out["mse_loss"] + 0 * out["feature_loss"] + \
|
| 73 |
+
0 * (out['obect_loss'][0] + out['obect_loss'][1]) + \
|
| 74 |
+
1 * out["bpp_loss"]
|
| 75 |
+
|
| 76 |
+
return out
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class AverageMeter:
|
| 80 |
+
"""Compute running average."""
|
| 81 |
+
|
| 82 |
+
def __init__(self):
|
| 83 |
+
self.val = 0
|
| 84 |
+
self.avg = 0
|
| 85 |
+
self.sum = 0
|
| 86 |
+
self.count = 0
|
| 87 |
+
|
| 88 |
+
def update(self, val, n=1):
|
| 89 |
+
self.val = val
|
| 90 |
+
self.sum += val * n
|
| 91 |
+
self.count += n
|
| 92 |
+
self.avg = self.sum / self.count
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class CustomDataParallel(nn.DataParallel):
|
| 96 |
+
"""Custom DataParallel to access the module methods."""
|
| 97 |
+
|
| 98 |
+
def __getattr__(self, key):
|
| 99 |
+
try:
|
| 100 |
+
return super().__getattr__(key)
|
| 101 |
+
except AttributeError:
|
| 102 |
+
return getattr(self.module, key)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def configure_optimizers(net, args):
|
| 106 |
+
"""Separate parameters for the main optimizer and the auxiliary optimizer.
|
| 107 |
+
Return two optimizers"""
|
| 108 |
+
|
| 109 |
+
# parameters = {
|
| 110 |
+
# n
|
| 111 |
+
# for n, p in net.named_parameters()
|
| 112 |
+
# if not n.endswith(".quantiles") and p.requires_grad and not "teacherNet" and not "studentNet" in n
|
| 113 |
+
# }
|
| 114 |
+
# aux_parameters = {
|
| 115 |
+
# n
|
| 116 |
+
# for n, p in net.named_parameters()
|
| 117 |
+
# if n.endswith(".quantiles") and p.requires_grad and not "teacherNet" and not "studentNet" in n
|
| 118 |
+
# }
|
| 119 |
+
# print(parameters)
|
| 120 |
+
# TrainList = ['mu_Swin','sigma_Swin','LRP_Swin','cc_mean_transforms',
|
| 121 |
+
# 'cc_scale_transforms','lrp_transforms']
|
| 122 |
+
# 'h_mean_s','h_scale_s']
|
| 123 |
+
# NotTrainList = ['teacher'] # ,'student'
|
| 124 |
+
# parameters = []
|
| 125 |
+
# for name, param in net.named_parameters():
|
| 126 |
+
# boolTraining = True
|
| 127 |
+
# for paraName in NotTrainList:
|
| 128 |
+
# if paraName in name and param.requires_grad and not name.endswith(".quantiles"):
|
| 129 |
+
# boolTraining = False
|
| 130 |
+
# continue
|
| 131 |
+
# if boolTraining:
|
| 132 |
+
# parameters.append(name)
|
| 133 |
+
|
| 134 |
+
def _is_human(n):
|
| 135 |
+
return n.startswith(
|
| 136 |
+
("human_", "generate_mask", "entropy_bottleneck_human", "gaussian_conditional_human")
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
parameters = [
|
| 140 |
+
n
|
| 141 |
+
for n, p in net.named_parameters()
|
| 142 |
+
if p.requires_grad and _is_human(n) and not n.endswith(".quantiles")
|
| 143 |
+
]
|
| 144 |
+
aux_parameters = [
|
| 145 |
+
n
|
| 146 |
+
for n, p in net.named_parameters()
|
| 147 |
+
if p.requires_grad and _is_human(n) and n.endswith(".quantiles")
|
| 148 |
+
]
|
| 149 |
+
if not parameters:
|
| 150 |
+
raise RuntimeError("No trainable human residual parameters. Did freeze_previous_layers run?")
|
| 151 |
+
# # print(parameters)
|
| 152 |
+
parameters = set(parameters)
|
| 153 |
+
aux_parameters = set(aux_parameters)
|
| 154 |
+
|
| 155 |
+
# Make sure we don't have an intersection of parameters
|
| 156 |
+
params_dict = dict(net.named_parameters())
|
| 157 |
+
# inter_params = parameters & aux_parameters
|
| 158 |
+
# union_params = parameters | aux_parameters
|
| 159 |
+
|
| 160 |
+
# assert len(inter_params) == 0
|
| 161 |
+
# assert len(union_params) - len(params_dict.keys()) == 0
|
| 162 |
+
|
| 163 |
+
optimizer = optim.Adam(
|
| 164 |
+
(params_dict[n] for n in sorted(parameters)),
|
| 165 |
+
lr=args.learning_rate,
|
| 166 |
+
)
|
| 167 |
+
aux_optimizer = optim.Adam(
|
| 168 |
+
(params_dict[n] for n in sorted(aux_parameters)),
|
| 169 |
+
lr=args.aux_learning_rate,
|
| 170 |
+
)
|
| 171 |
+
return optimizer, aux_optimizer
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def train_one_epoch(
|
| 175 |
+
model, criterion, train_dataloader, optimizer, aux_optimizer, epoch, clip_max_norm
|
| 176 |
+
):
|
| 177 |
+
model.train()
|
| 178 |
+
for name, module in model.named_children():
|
| 179 |
+
if name.startswith(
|
| 180 |
+
("human_", "generate_mask", "entropy_bottleneck_human", "gaussian_conditional_human")
|
| 181 |
+
):
|
| 182 |
+
module.train()
|
| 183 |
+
else:
|
| 184 |
+
module.eval()
|
| 185 |
+
device = next(model.parameters()).device
|
| 186 |
+
|
| 187 |
+
# url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 188 |
+
# clipimage = Image.open(requests.get(url, stream=True).raw)
|
| 189 |
+
# clipimage = clipimage.resize((256,256))
|
| 190 |
+
# clipinputs = transforms.ToTensor()(clipimage).unsqueeze(0)
|
| 191 |
+
# print(clipinputs)
|
| 192 |
+
# clipProcessor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
| 193 |
+
# clipinputs = clipProcessor(images=clipimage, return_tensors="pt")
|
| 194 |
+
# clipinputs = clipinputs.to(device)
|
| 195 |
+
start = time.time()
|
| 196 |
+
|
| 197 |
+
for i, d in enumerate(train_dataloader):
|
| 198 |
+
inputIMG = d.to(device)
|
| 199 |
+
annotations= []
|
| 200 |
+
# original_img, up_x4_img = d
|
| 201 |
+
# inputIMG = d['img']
|
| 202 |
+
# annotations = d['annot']
|
| 203 |
+
# inputIMG = inputIMG.to(device)
|
| 204 |
+
# annotations = annotations.to(device)
|
| 205 |
+
# original_img = original_img.to(device)
|
| 206 |
+
# up_x4_img = up_x4_img.to(device)
|
| 207 |
+
|
| 208 |
+
optimizer.zero_grad()
|
| 209 |
+
aux_optimizer.zero_grad()
|
| 210 |
+
|
| 211 |
+
# inputData={}
|
| 212 |
+
# inputData['pixel_values']=clipinputs
|
| 213 |
+
out_net = model(inputIMG)
|
| 214 |
+
|
| 215 |
+
out_criterion = criterion(inputIMG,out_net, annotations)
|
| 216 |
+
out_criterion["loss"].backward()
|
| 217 |
+
if clip_max_norm > 0:
|
| 218 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), clip_max_norm)
|
| 219 |
+
optimizer.step()
|
| 220 |
+
|
| 221 |
+
aux_loss = model.aux_loss()
|
| 222 |
+
aux_loss.backward()
|
| 223 |
+
aux_optimizer.step()
|
| 224 |
+
|
| 225 |
+
if i % 600 == 0:
|
| 226 |
+
enc_time = time.time() - start
|
| 227 |
+
start = time.time()
|
| 228 |
+
print(
|
| 229 |
+
f"Train epoch {epoch}: ["
|
| 230 |
+
f"{i*len(inputIMG)}/{len(train_dataloader.dataset)}"
|
| 231 |
+
f" ({100. * i / len(train_dataloader):.0f}%)]"
|
| 232 |
+
f'\tLoss: {out_criterion["loss"].item():.3f} |'
|
| 233 |
+
f'\tMSE loss: {out_criterion["mse_loss"].item() :.3f} |'
|
| 234 |
+
f'\tBpp loss: {out_criterion["bpp_loss"].item():.2f} |'
|
| 235 |
+
# f'\tfeature loss: {out_criterion["feature_loss"].item():.2f} |'
|
| 236 |
+
# f'\tobect loss: {out_criterion["obect_loss"][0].item():.2f} {out_criterion["obect_loss"][1].item():.2f}|'
|
| 237 |
+
f"\tAux loss: {aux_loss.item():.2f} |"
|
| 238 |
+
f"\ttime: {enc_time:.1f}"
|
| 239 |
+
)
|
| 240 |
+
#
|
| 241 |
+
# if i > 100:
|
| 242 |
+
# break
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def test_epoch(epoch, test_dataloader, model, criterion):
|
| 246 |
+
model.eval()
|
| 247 |
+
device = next(model.parameters()).device
|
| 248 |
+
|
| 249 |
+
loss = AverageMeter()
|
| 250 |
+
bpp_loss = AverageMeter()
|
| 251 |
+
mse_loss = AverageMeter()
|
| 252 |
+
aux_loss = AverageMeter()
|
| 253 |
+
objective_loss1 = AverageMeter()
|
| 254 |
+
objective_loss2 = AverageMeter()
|
| 255 |
+
|
| 256 |
+
with torch.no_grad():
|
| 257 |
+
for d in test_dataloader:
|
| 258 |
+
inputIMG = d.to(device)
|
| 259 |
+
annotations = 0
|
| 260 |
+
# out_net = model(d)
|
| 261 |
+
# out_criterion = criterion(out_net, d)
|
| 262 |
+
|
| 263 |
+
# inputIMG = d['img']
|
| 264 |
+
# annotations = d['annot']
|
| 265 |
+
inputIMG = inputIMG.to(device)
|
| 266 |
+
# annotations = annotations.to(device)
|
| 267 |
+
|
| 268 |
+
out_net = model(inputIMG)
|
| 269 |
+
out_criterion = criterion(inputIMG, out_net, annotations)
|
| 270 |
+
|
| 271 |
+
# scale = d['scale']
|
| 272 |
+
# scale = scale.to(device)
|
| 273 |
+
# scores, labels, boxes = out_net["scores"], out_net["labels"], out_net["boxes"]
|
| 274 |
+
# boxes /= scale
|
| 275 |
+
|
| 276 |
+
aux_loss.update(model.aux_loss())
|
| 277 |
+
bpp_loss.update(out_criterion["bpp_loss"])
|
| 278 |
+
loss.update(out_criterion["loss"])
|
| 279 |
+
mse_loss.update(out_criterion["mse_loss"])
|
| 280 |
+
objective_loss1.update(out_criterion["obect_loss"][0])
|
| 281 |
+
objective_loss2.update(out_criterion["obect_loss"][1])
|
| 282 |
+
|
| 283 |
+
print(
|
| 284 |
+
f"Test epoch {epoch}: Average losses:"
|
| 285 |
+
f"\tLoss: {loss.avg.item():.3f} |"
|
| 286 |
+
f"\tMSE loss: {mse_loss.avg * 255 ** 2 :.3f} |"
|
| 287 |
+
# f'\tobect loss: {objective_loss1.avg.item():.2f} {objective_loss2.avg.item():.2f}|'
|
| 288 |
+
f"\tBpp loss: {bpp_loss.avg:.2f} |"
|
| 289 |
+
f"\tAux loss: {aux_loss.avg:.2f}\n"
|
| 290 |
+
)
|
| 291 |
+
return loss.avg
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def save_checkpoint(state, is_best, filename):
|
| 295 |
+
torch.save(state, filename)
|
| 296 |
+
# if is_best:
|
| 297 |
+
# shutil.copyfile(filename, filename[:-5]+"_best"+filename[-5:])
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def parse_args(argv):
|
| 301 |
+
parser = argparse.ArgumentParser(description="Example training script.")
|
| 302 |
+
parser.add_argument(
|
| 303 |
+
"-m",
|
| 304 |
+
"--model",
|
| 305 |
+
default="mmcrc",
|
| 306 |
+
choices=models.keys(),
|
| 307 |
+
help="Model architecture (default: %(default)s). mmcrc = 2nd enhancement (human recon).",
|
| 308 |
+
)
|
| 309 |
+
parser.add_argument(
|
| 310 |
+
"-d", "--dataset", type=str,
|
| 311 |
+
default="./data/openimages/",
|
| 312 |
+
help="OpenImages root for MMCRC training (paper Sec. IV-A-3)",
|
| 313 |
+
)
|
| 314 |
+
parser.add_argument(
|
| 315 |
+
"-e",
|
| 316 |
+
"--epochs",
|
| 317 |
+
default=100000,
|
| 318 |
+
type=int,
|
| 319 |
+
help="Number of epochs (default: %(default)s)",
|
| 320 |
+
)
|
| 321 |
+
parser.add_argument(
|
| 322 |
+
"-lr",
|
| 323 |
+
"--learning-rate",
|
| 324 |
+
default=1e-5,
|
| 325 |
+
type=float,
|
| 326 |
+
help="Learning rate (default: %(default)s)",
|
| 327 |
+
)
|
| 328 |
+
parser.add_argument(
|
| 329 |
+
"-n",
|
| 330 |
+
"--num-workers",
|
| 331 |
+
type=int,
|
| 332 |
+
default=6,
|
| 333 |
+
help="Dataloaders threads (default: %(default)s)",
|
| 334 |
+
)
|
| 335 |
+
parser.add_argument(
|
| 336 |
+
"--lambda",
|
| 337 |
+
dest="lmbda",
|
| 338 |
+
type=float,
|
| 339 |
+
default=800,
|
| 340 |
+
help="Bit-rate distortion parameter (default: %(default)s)",
|
| 341 |
+
)
|
| 342 |
+
parser.add_argument(
|
| 343 |
+
"--batch-size", type=int, default=3, help="Batch size (default: %(default)s)"
|
| 344 |
+
)
|
| 345 |
+
parser.add_argument(
|
| 346 |
+
"--test-batch-size",
|
| 347 |
+
type=int,
|
| 348 |
+
default=3,
|
| 349 |
+
help="Test batch size (default: %(default)s)",
|
| 350 |
+
)
|
| 351 |
+
parser.add_argument(
|
| 352 |
+
"--aux-learning-rate",
|
| 353 |
+
default=1e-4,
|
| 354 |
+
type=float,
|
| 355 |
+
help="Auxiliary loss learning rate (default: %(default)s)",
|
| 356 |
+
)
|
| 357 |
+
parser.add_argument(
|
| 358 |
+
"--patch-size",
|
| 359 |
+
type=int,
|
| 360 |
+
nargs=2,
|
| 361 |
+
default=(512, 512),
|
| 362 |
+
help="Size of the patches to be cropped (default: %(default)s)",
|
| 363 |
+
)
|
| 364 |
+
parser.add_argument("--cuda", default=True, action="store_true", help="Use cuda")
|
| 365 |
+
parser.add_argument(
|
| 366 |
+
"--save", action="store_true", default=True, help="Save model to disk"
|
| 367 |
+
)
|
| 368 |
+
parser.add_argument(
|
| 369 |
+
"--save_path", type=str, default="./checkpoints/mmcrc/", help="Where to Save model"
|
| 370 |
+
)
|
| 371 |
+
parser.add_argument(
|
| 372 |
+
"--seed", type=float, help="Set random seed for reproducibility"
|
| 373 |
+
)
|
| 374 |
+
parser.add_argument(
|
| 375 |
+
"--clip_max_norm",
|
| 376 |
+
default=1.0,
|
| 377 |
+
type=float,
|
| 378 |
+
help="gradient clipping max norm (default: %(default)s",
|
| 379 |
+
)
|
| 380 |
+
parser.add_argument("--teachercheckpoint",
|
| 381 |
+
default="./save_model/coco_resnet_50_map_0_335_state_dict.pt", # ./train0008/18.ckpt
|
| 382 |
+
type=str, help="Path to a checkpoint")
|
| 383 |
+
parser.add_argument("--checkpoint",
|
| 384 |
+
default="",
|
| 385 |
+
type=str, help="Path to a checkpoint")
|
| 386 |
+
args = parser.parse_args(argv)
|
| 387 |
+
return args
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
def main(argv):
|
| 391 |
+
args = parse_args(argv)
|
| 392 |
+
print(args)
|
| 393 |
+
if args.seed is not None:
|
| 394 |
+
torch.manual_seed(args.seed)
|
| 395 |
+
random.seed(args.seed)
|
| 396 |
+
# tv.transforms.RandomCrop(args.patchsize, pad_if_needed=True)
|
| 397 |
+
# clipinputs = clipProcessor(images=clipimage, return_tensors="pt")
|
| 398 |
+
# train_transforms = transforms.Compose(
|
| 399 |
+
# [transforms.RandomCrop(args.patch_size, pad_if_needed=True), transforms.ToTensor()]
|
| 400 |
+
# )
|
| 401 |
+
|
| 402 |
+
train_transforms = transforms.Compose(
|
| 403 |
+
[transforms.CenterCrop(args.patch_size), transforms.ToTensor()]
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
test_transforms = transforms.Compose(
|
| 407 |
+
[transforms.CenterCrop(args.patch_size), transforms.ToTensor()]
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
train_dataset = ImageFolder(args.dataset, split="val2017", transform=train_transforms)
|
| 411 |
+
test_dataset = ImageFolder(args.dataset, split="val2017", transform=test_transforms)
|
| 412 |
+
|
| 413 |
+
# dataset_train = CocoDataset(args.dataset, set_name='train2017',
|
| 414 |
+
# transform=transforms.Compose([Normalizer(), Augmenter(), Resizer()]))
|
| 415 |
+
# dataset_val = CocoDataset(args.dataset, set_name='val2017',
|
| 416 |
+
# transform=transforms.Compose([Normalizer(), Resizer()]))
|
| 417 |
+
|
| 418 |
+
# sampler = AspectRatioBasedSampler(dataset_train, batch_size=args.batch_size, drop_last=True)
|
| 419 |
+
# train_dataloader = DataLoader(dataset_train, num_workers=args.num_workers, collate_fn=collater, batch_sampler=sampler)
|
| 420 |
+
#
|
| 421 |
+
# sampler_val = AspectRatioBasedSampler(dataset_val, batch_size=args.test_batch_size, drop_last=False)
|
| 422 |
+
# test_dataloader = DataLoader(dataset_val, num_workers=args.num_workers, collate_fn=collater, batch_sampler=sampler_val)
|
| 423 |
+
|
| 424 |
+
device = "cuda" if args.cuda and torch.cuda.is_available() else "cpu"
|
| 425 |
+
|
| 426 |
+
train_dataloader = DataLoader(
|
| 427 |
+
train_dataset,
|
| 428 |
+
batch_size=args.batch_size,
|
| 429 |
+
num_workers=args.num_workers,
|
| 430 |
+
shuffle=True,
|
| 431 |
+
pin_memory=(device == "cuda"),
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
test_dataloader = DataLoader(
|
| 435 |
+
test_dataset,
|
| 436 |
+
batch_size=args.test_batch_size,
|
| 437 |
+
num_workers=args.num_workers,
|
| 438 |
+
shuffle=False,
|
| 439 |
+
pin_memory=(device == "cuda"),
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
net = models[args.model]()
|
| 443 |
+
net = net.to(device)
|
| 444 |
+
|
| 445 |
+
print('GPU:',torch.cuda.device_count())
|
| 446 |
+
|
| 447 |
+
last_epoch = 0
|
| 448 |
+
if args.checkpoint: # load from previous checkpoint
|
| 449 |
+
print("Loading", args.checkpoint)
|
| 450 |
+
checkpoint = torch.load(args.checkpoint, map_location=device)
|
| 451 |
+
state = (
|
| 452 |
+
checkpoint["state_dict"]
|
| 453 |
+
if isinstance(checkpoint, dict) and "state_dict" in checkpoint
|
| 454 |
+
else checkpoint
|
| 455 |
+
)
|
| 456 |
+
cleaned = {}
|
| 457 |
+
for k, v in state.items():
|
| 458 |
+
cleaned[k[7:] if k.startswith("module.") else k] = v
|
| 459 |
+
|
| 460 |
+
is_mmcrc_ckpt = any(k.startswith("human_") for k in cleaned)
|
| 461 |
+
if isinstance(checkpoint, dict) and "epoch" in checkpoint and is_mmcrc_ckpt:
|
| 462 |
+
last_epoch = checkpoint["epoch"] + 1
|
| 463 |
+
else:
|
| 464 |
+
last_epoch = 0
|
| 465 |
+
if not is_mmcrc_ckpt:
|
| 466 |
+
print("Loaded base/enh1 weights; starting MMCRC from epoch 0")
|
| 467 |
+
|
| 468 |
+
model_sd = net.state_dict()
|
| 469 |
+
skip_prefixes = ("teacher_net.", "task_net.", "student_task.", "student_det.")
|
| 470 |
+
filtered = {
|
| 471 |
+
k: v
|
| 472 |
+
for k, v in cleaned.items()
|
| 473 |
+
if k in model_sd
|
| 474 |
+
and tuple(v.shape) == tuple(model_sd[k].shape)
|
| 475 |
+
and not k.startswith(skip_prefixes)
|
| 476 |
+
}
|
| 477 |
+
print(f"Loaded {len(filtered)}/{len(model_sd)} tensors from checkpoint")
|
| 478 |
+
missing, unexpected = net.load_state_dict(filtered, strict=False)
|
| 479 |
+
print(
|
| 480 |
+
f"Resume strict=False: missing={len(missing)}, unexpected={len(unexpected)}"
|
| 481 |
+
)
|
| 482 |
+
|
| 483 |
+
net.freeze_previous_layers()
|
| 484 |
+
n_trainable = sum(p.numel() for p in net.parameters() if p.requires_grad)
|
| 485 |
+
n_total = sum(p.numel() for p in net.parameters())
|
| 486 |
+
print(f"Trainable params: {n_trainable}/{n_total} (human residual only)")
|
| 487 |
+
|
| 488 |
+
optimizer, aux_optimizer = configure_optimizers(net, args)
|
| 489 |
+
lr_scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, "min", factor=0.6, patience=6)
|
| 490 |
+
criterion = RateDistortionLoss(lmbda=args.lmbda)
|
| 491 |
+
os.makedirs(args.save_path, exist_ok=True)
|
| 492 |
+
|
| 493 |
+
best_loss = float("inf")
|
| 494 |
+
for epoch in range(last_epoch, args.epochs):
|
| 495 |
+
print(f"Learning rate: {optimizer.param_groups[0]['lr']}")
|
| 496 |
+
train_one_epoch(
|
| 497 |
+
net,
|
| 498 |
+
criterion,
|
| 499 |
+
train_dataloader,
|
| 500 |
+
optimizer,
|
| 501 |
+
aux_optimizer,
|
| 502 |
+
epoch,
|
| 503 |
+
args.clip_max_norm,
|
| 504 |
+
)
|
| 505 |
+
if epoch % 1 == 0:
|
| 506 |
+
loss = test_epoch(epoch, test_dataloader, net, criterion)
|
| 507 |
+
lr_scheduler.step(loss)
|
| 508 |
+
|
| 509 |
+
is_best = loss < best_loss
|
| 510 |
+
best_loss = min(loss, best_loss)
|
| 511 |
+
|
| 512 |
+
if args.save and is_best:
|
| 513 |
+
save_checkpoint(
|
| 514 |
+
{
|
| 515 |
+
"epoch": epoch,
|
| 516 |
+
"state_dict": net.state_dict(),
|
| 517 |
+
"loss": loss,
|
| 518 |
+
"optimizer": optimizer.state_dict(),
|
| 519 |
+
"aux_optimizer": aux_optimizer.state_dict(),
|
| 520 |
+
"lr_scheduler": lr_scheduler.state_dict(),
|
| 521 |
+
},
|
| 522 |
+
is_best,
|
| 523 |
+
args.save_path +str(epoch)+'.ckpt',
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
if __name__ == "__main__":
|
| 528 |
+
|
| 529 |
+
main(sys.argv[1:])
|