我刚刚没有把代码贴上来,需要修改的代码如下import os
import sys
import argparse
import time
import logging
import tqdm
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torch.utils.data
from torch.utils.data import Dataset
import cv2
from torch.utils.data import DataLoader
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data.distributed import DistributedSampler
tensorboard
from torch.utils.tensorboard import SummaryWriter
from dataloader_utils import LongTailDataLoader
import numpy as np
import PIL
from PIL import Image
from PIL import ImageOps
from data_process_midas_disprefine_wmask import MonoDepthDataset
from repvit import Mono_Depth
from loss import GradL1Loss,MultiScaleGradLoss
from efficientnet_lite_concat_v1 import EfficientNetLite,build_efficientnet_lite
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class AuxModule(nn.Module):
def init(self, model):
super(AuxModule, self).init()
self.module = model
def forward(self, rgb):
return self.module(rgb)
other augments, done by lzf
class RandomRescale:
def init(self, scales, probabilities=None):
self.scales = scales
self.probabilities = probabilities
def __call__(self, image, depth):
scale = random.choices(self.scales, self.probabilities)[0]
width, height = image.size
new_width = int(width * scale)
new_height = int(height * scale)
resized_image = transforms.Resize((new_height, new_width))(image)
resized_depth = transforms.Resize((new_height, new_width))(depth)
return resized_image, resized_depth
class RandomCenterCrop:
def init(self, crop_size,crop_prob):
self.crop_size = crop_size
self.crop_prob = crop_prob
def __call__(self, image, depth):
if random.random() > self.crop_prob:
width, height = image.size
crop_width, crop_height = self.crop_size
left = (width - crop_width) // 2
top = (height - crop_height) // 2
right = (width + crop_width) // 2
bottom = (height + crop_height) // 2
return image.crop((left, top, right, bottom)) , depth.crop((left, top, right, bottom))
else:
return image ,depth
Hyper-parameters
num_epochs = 5000
lr_sch = 5
learning_rate = 1e-3
batch_size = 16
save_path = f"./langan_20241220_fintune"
use_tensorboard = True
use_ddp = True
use_longtail = False
use_distillation = False
use_multiscale = True
use_randomcrop = True
step -1: Initial DDP
if use_ddp:
dist.init_process_group("nccl")
rank = dist.get_rank()
device_id = rank % torch.cuda.device_count()
device = torch.device(f'cuda:{device_id}')
if os.path.exists(save_path) or device_id != 0:
pass
else:
os.makedirs(save_path, exist_ok= True)
print(f"Start running basic DDP example on rank {rank}.")
step1: Data Loading
txtname = "langan_all_data_sample2.txt"
data_using = MonoDepthDataset(txtname = txtname)
dataset_names = []
txt_folder_path = ''
for name in dataset_names:
txtname = os.path.join(txt_folder_path, f'{name}_depth.txt')
dataset = MonoDepthDataset(txtname = txtname)
all_data.append(dataset)
合并所有数据集
combined_dataset = torch.utils.data.ConcatDataset(all_data)
print(len(data_using))
if use_ddp:
sampler = DistributedSampler(data_using, drop_last=True)
train_loader = DataLoader(data_using, batch_size=batch_size, shuffle=(sampler is None), drop_last=True, sampler=sampler, num_workers=0 )
else:
train_loader = DataLoader(data_using, batch_size=batch_size, shuffle=True, drop_last=True, num_workers=0)
model=Mono_Depth().to(device)
model=build_efficientnet_lite('efficientnet_lite3', 1000).to(device)
ckpt = torch.load('langan_20241211_wograd/303-5.1670.pth')
oldCkpt = ckpt
newCkpt = {}
pretrained_state_dict =oldCkpt
model_state_dict=model.state_dict()
for name, param in pretrained_state_dict.items():
name=name.replace('module.','')
if name in model_state_dict and model_state_dict[name].shape == param.shape:
model_state_dict[name] = param
else:
print(f"skip loading {name}")
model.load_state_dict(model_state_dict, strict=True)
if use_ddp:
model = DDP(model, device_ids=[device_id], find_unused_parameters=True)
step3: Define optimizer and loss
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
For updating learning rate
def update_lr(optimizer, lr):
for param_group in optimizer.param_groups:
param_group['lr'] = lr
if use_distillation:
# 蒸馏的损失函数
kd_loss = torch.nn.L1Loss()
grad_loss = GradInvariantLoss()
else:
# midas的损失函数
midas_loss = torch.nn.L1Loss()
weight_L1 = torch.nn.L1Loss(reduction='none')
grad_loss=MultiScaleGradLoss()
step4: Train the model
total_step = len(train_loader)
curr_lr = learning_rate
start_epoch=-1
cur_iter = 0
step -1: Initial Tensorboard
for epoch in range(start_epoch + 1 ,num_epochs):
if use_ddp:
sampler.set_epoch(epoch)
total=len(train_loader)
if use_longtail:
train_loader.set_epoch(epoch)
progress_bar = tqdm.tqdm(enumerate(train_loader), total = total)
all_loss=0
for i, images in progress_bar:
# images = images
images, labels, diffs = images
labels = labels.to(device)
images = images.to(device)
diffs = diffs.to(device)
valmask = (diffs>0)
valmask.detach_()
# if use_multiscale:
# # size = random.choices(input_resolutions, [0.3, 0.45, 0.25])[0]
# size = [480,640]
# resize_transform = transforms.Resize(size)
# images = resize_transform(images)
# labels = resize_transform(labels)
outputs = model(images)
# print('labels_type = ', type(labels))
# print('outputs_type = ', type(outputs))
loss_midas = midas_loss(outputs*255, labels*255)
loss_grad = grad_loss(outputs*255, labels*255)
# wieght_loss=weight_L1(outputs*255, labels*255)*diff
# wieght_loss=wieght_loss.mean()
# print(loss_grad,loss_midas)
floss = loss_midas+loss_grad
gloss = midas_loss(outputs[valmask]*255, labels[valmask]*255)
'''可以修改成动态参数loss,也可以修改成maskloss'''
loss = floss + 0.3*gloss
optimizer.zero_grad()
loss.backward()
optimizer.step()
if device_id == 0:
progress_bar.set_description("Epoch [{}/{}], Step [{}/{}] Loss: {:.4f}"
.format(epoch+1, num_epochs, i+1, total_step, loss.item()))
all_loss+=loss.item()
# Save model
ave_loss=all_loss/total
if device_id == 0:
checkpoint = {"net": model.state_dict(), 'optimizer':optimizer.state_dict(),"epoch": epoch}
torch.save(checkpoint, save_path+"/"+"ckpt_best_"+str(epoch)+".pth")
torch.save(model.state_dict(), save_path+"/"+str(epoch)+"-"+str(ave_loss)[0:6]+".pth")