Hyper-parameters numepochs = 5000 lrsch = 5 learningrate = 1e-3 batchsize = 16 savepath…
- User
Hyper-parameters
num_epochs = 5000 lr_sch = 5 learning_rate = 1e-3 batch_size = 16 save_path = f"./langan_20241129_wobg250"
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 = "distillation_list.txt"
txtname = "/home/notebook/data/group/zgf/code/data_process/data_list/all/data_list_ip14pc_zed_0517.txt"
放大数据集
txtname = "langan_all_data_sample2.txt"
txtname = "/home/notebook/data/group/Ruby/depthrefine/langanero_files.txt" data_using = MonoDepthDataset(txtname = txtname)
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('/home/notebook/data/group/Ruby/depthrefine/langan_20241127_langan0.3_woprt/1183-6.6036.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'] = lrif use_distillation:
# 蒸馏的损失函数
kd_loss = torch.nn.L1Loss()
grad_loss = GradInvariantLoss()
else:
code# 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
- Assistant
The error you're encountering,
RuntimeError: grad can be implicitly created only for scalar outputs, indicates that the loss tensor whose gradients you are trying to calculate is not a scalar (i.e., it does not have a single value). In PyTorch, the.backward()function can only be called on scalar tensors.Here's a debug checklist and potential fixes for your code:
1. Check Loss Calculation
在
floss和gloss的计算中,确保结果是一个标量。你的floss和gloss需要应用到一个可以归约成一个数值的函数上,通常是 或 。 - User
请说中文
- Assistant
当然可以。您遇到的错误消息,
RuntimeError: grad can be implicitly created only for scalar outputs,表示您在尝试计算梯度时,损失张量并不是一个标量(即它没有单一的值)。在PyTorch中,.backward()函数只能在标量张量上调用。故障排查清单及修复建议
- 检查损失计算:
在
floss和gloss的计算中,请确保结果是一个标量。通常,您需要对损失应用一个可以将其归约为单个数值的操作,比如.mean()或.sum()。
修改代码示例
确保您的
loss计算如下所示,您可以选择使用.mean()或.sum(),具体取决于您想要的损失行为:python# 示例:使用sum,您可以根据需要替换为mean floss = (loss_midas * thrd_mask).sum() + (loss_grad * thrd_mask).sum() gloss = midas_loss(outputs[cb_mask] * 255, labels[cb_mask] * 255).sum() # 或者根据需要使用mean loss = floss + 0.3 * gloss # 现在这应该是一个标量-
确保仅返回标量: 每次您计算损失时,确保它返回的是标量张量。常用的确保方法就是使用
.mean()或.sum()。 -
调试信息: 在损失计算之前,打印
loss_midas、loss_grad、cb_mask和 的形状和数值。这将帮助您确定可能出现形状问题的位置。
- 检查损失计算:
在