fix(jepa): 修复训练和微调中的tensor处理问题,减少内存占用
- 修改model_jepa.py的loss记录方式,将直接提取标量改为先分离计算图再存储 - 优化train_jepa.py的loss检查与日志逻辑,移至反向传播后并补充tensor转标量的处理 - 改进finetune_jepa.py的loss累加和验证集tensor操作,避免保留不必要的计算图
This commit is contained in:
1 parent
c561f8b5b0
commit
c10735c0f7
3 files changed
+31
-20
No files matched your search
+15
-8
@@ -233,15 +233,19 @@ def train_one_epoch(model, loader, criterion, optimizer, device, epoch, scaler=N
|
||||
if scheduler is not None:
|
||||
scheduler.step()
|
||||
|
||||
total_loss += loss.item()
|
||||
total_loss += loss.detach()
|
||||
count += 1
|
||||
|
||||
if is_main_process():
|
||||
current_lr = optimizer.param_groups[0]['lr']
|
||||
iterator.set_postfix({'loss': total_loss / count, 'lr': f"{current_lr:.2e}"})
|
||||
loss_val = total_loss.item() if isinstance(total_loss, torch.Tensor) else total_loss
|
||||
iterator.set_postfix({'loss': loss_val / count, 'lr': f"{current_lr:.2e}"})
|
||||
|
||||
if count == 0:
|
||||
return 0.0
|
||||
|
||||
if isinstance(total_loss, torch.Tensor):
|
||||
total_loss = total_loss.item()
|
||||
return total_loss / count
|
||||
|
||||
|
||||
@@ -266,22 +270,25 @@ def validate(model, loader, criterion, device, num_classes, total_len, use_amp=T
|
||||
|
||||
if dist.is_initialized():
|
||||
reduced_loss = reduce_tensor(loss)
|
||||
total_loss += reduced_loss.item()
|
||||
total_loss += reduced_loss.detach()
|
||||
else:
|
||||
total_loss += loss.item()
|
||||
total_loss += loss.detach()
|
||||
count += 1
|
||||
|
||||
probs = torch.sigmoid(logits.float())
|
||||
local_labels.append(y.cpu())
|
||||
local_probs.append(probs.cpu())
|
||||
local_labels.append(y.detach())
|
||||
local_probs.append(probs.detach())
|
||||
|
||||
if count == 0 or len(local_labels) == 0:
|
||||
if is_main_process():
|
||||
return 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, "Empty validation loader.", fixed_threshold, []
|
||||
return 0, 0, 0, 0, 0, 0, None, 0, []
|
||||
|
||||
local_labels = torch.cat(local_labels)
|
||||
local_probs = torch.cat(local_probs)
|
||||
if isinstance(total_loss, torch.Tensor):
|
||||
total_loss = total_loss.item()
|
||||
|
||||
local_labels = torch.cat(local_labels).cpu()
|
||||
local_probs = torch.cat(local_probs).cpu()
|
||||
|
||||
if dist.is_initialized():
|
||||
all_labels = gather_tensors(local_labels, device)
|
||||
|
||||
+3
-3
@@ -1009,9 +1009,9 @@ class CWT_JEPA(nn.Module):
|
||||
|
||||
# 汇总
|
||||
loss_dict = {
|
||||
'loss_jepa': loss_jepa.item() if isinstance(loss_jepa, torch.Tensor) else loss_jepa,
|
||||
'loss_sigreg': loss_sigreg.item() if isinstance(loss_sigreg, torch.Tensor) else loss_sigreg,
|
||||
'loss_stats': loss_stats.item() if isinstance(loss_stats, torch.Tensor) else loss_stats,
|
||||
'loss_jepa': loss_jepa.detach() if isinstance(loss_jepa, torch.Tensor) else loss_jepa,
|
||||
'loss_sigreg': loss_sigreg.detach() if isinstance(loss_sigreg, torch.Tensor) else loss_sigreg,
|
||||
'loss_stats': loss_stats.detach() if isinstance(loss_stats, torch.Tensor) else loss_stats,
|
||||
'ema_momentum': momentum if self.training else self.ema_momentum,
|
||||
}
|
||||
|
||||
|
||||
+13
-9
@@ -144,17 +144,21 @@ def train_one_epoch(model, dataloader, optimizer, scaler, epoch, logger, config,
|
||||
)
|
||||
total_loss = total_loss / accum_iter
|
||||
|
||||
loss_value = total_loss.item() * accum_iter
|
||||
loss_jepa_val = loss_dict.get('loss_jepa', 0.0)
|
||||
loss_sigreg_val = loss_dict.get('loss_sigreg', 0.0)
|
||||
loss_stats_val = loss_dict.get('loss_stats', 0.0)
|
||||
|
||||
if not math.isfinite(loss_value):
|
||||
print(f"Loss is {loss_value}, stopping training")
|
||||
sys.exit(1)
|
||||
|
||||
scaler.scale(total_loss).backward()
|
||||
|
||||
loss_value = total_loss.item() * accum_iter
|
||||
if not math.isfinite(loss_value):
|
||||
print(f"Loss is {loss_value}, stopping training")
|
||||
sys.exit(1)
|
||||
|
||||
loss_jepa_val = loss_dict.get('loss_jepa', 0.0)
|
||||
loss_sigreg_val = loss_dict.get('loss_sigreg', 0.0)
|
||||
loss_stats_val = loss_dict.get('loss_stats', 0.0)
|
||||
|
||||
if isinstance(loss_jepa_val, torch.Tensor): loss_jepa_val = loss_jepa_val.item()
|
||||
if isinstance(loss_sigreg_val, torch.Tensor): loss_sigreg_val = loss_sigreg_val.item()
|
||||
if isinstance(loss_stats_val, torch.Tensor): loss_stats_val = loss_stats_val.item()
|
||||
|
||||
if do_sync:
|
||||
scaler.unscale_(optimizer)
|
||||
grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), config['train']['clip_grad'])
|
||||
|
||||
Reference in new issue
Block a user