不止热门角色,我们为你扩展了更多细分角色分类,覆盖职场提升、商业增长、内容创作、学习规划等多元场景。精准匹配不同目标,让每一次生成都更有方向、更高命中率。
立即探索更多角色分类,找到属于你的增长加速器。
问题描述:
可能原因:
排查步骤:
torch.autograd.set_detect_anomaly(True)
def has_nan(x): return torch.isnan(x).any() or torch.isinf(x).any()
在前向/损失后/反向前后插入检查,定位首次出现 NaN 的模块或损失分量。total_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=float('inf'))
print(step, scaler.get_scale(), total_norm.item(), optimizer.param_groups[0]['lr'])
解决方案:
半精度下 Dice/Softmax 数值不稳
import torch.nn.functional as F
def soft_dice_loss(logits, target, eps=1e-6):
# logits: [N,C,H,W], target: [N,H,W] (long)
probs = F.softmax(logits.float(), dim=1) # FP32
target_oh = F.one_hot(target, probs.shape[1]).permute(0,3,1,2).float()
# 可选:对极端样本进行 min-count 掩码
inter = (probs * target_oh).sum(dim=(0,2,3))
union = (probs + target_oh).sum(dim=(0,2,3))
dice = (2*inter + eps) / (union + eps)
return 1 - dice.mean()
GradScaler 与学习率导致溢出
autocast_dtype = torch.bfloat16 # 推荐
# with torch.autocast('cuda', dtype=autocast_dtype):
scaler = torch.cuda.amp.GradScaler(init_scale=2**8, growth_factor=2.0,
backoff_factor=0.5, growth_interval=200)
optimizer = torch.optim.AdamW(param_groups, lr=1e-4, weight_decay=0.01, eps=1e-6)
warmup = torch.optim.lr_scheduler.LinearLR(optimizer, start_factor=0.1, total_iters=5)
cosine = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=total_epochs-5)
scheduler = torch.optim.lr_scheduler.SequentialLR(optimizer, schedulers=[warmup, cosine],
milestones=[5])
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
优化器与 weight decay 配置
decay, no_decay = [], []
for n,p in model.named_parameters():
if p.requires_grad:
if p.ndim == 1 or 'bias' in n or 'bn' in n.lower() or 'norm' in n.lower():
no_decay.append(p)
else:
decay.append(p)
param_groups = [
{'params': decay, 'weight_decay': 0.01},
{'params': no_decay, 'weight_decay': 0.0},
]
optimizer = torch.optim.AdamW(param_groups, lr=1e-4, eps=1e-6, betas=(0.9, 0.999))
损失接口/张量混用
ce_loss = torch.nn.CrossEntropyLoss(ignore_index=255, label_smoothing=0.05)
with torch.autocast('cuda', dtype=autocast_dtype):
logits = model(images)
ce = ce_loss(logits, masks) # logits -> CE
dice = soft_dice_loss(logits, masks) # FP32 in function
loss = ce + dice
归一化层稳定性
model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)
model.apply(lambda m: setattr(m, 'track_running_stats', False) if isinstance(m, torch.nn.BatchNorm2d) else None)
model.eval() # 仅冻结 BN 时需要对 BN 处于 eval,其他模块保持 train
# 或替换为 GroupNorm:nn.GroupNorm(num_groups=32, num_channels=C)
训练主循环(整合稳健配置示例)
torch.backends.cuda.matmul.allow_tf32 = True # A100 性能+稳定性
autocast_dtype = torch.bfloat16 # 推荐
scaler = torch.cuda.amp.GradScaler(init_scale=2**8, growth_interval=200)
for epoch in range(total_epochs):
model.train()
for images, masks in loader:
images, masks = images.cuda(non_blocking=True), masks.cuda(non_blocking=True)
optimizer.zero_grad(set_to_none=True)
with torch.autocast('cuda', dtype=autocast_dtype):
logits = model(images)
ce = ce_loss(logits, masks) # logits->CE
dice = soft_dice_loss(logits, masks) # FP32
loss = ce + dice
if torch.isnan(loss) or torch.isinf(loss):
raise RuntimeError("Loss is NaN/Inf")
scaler.scale(loss).backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
scaler.step(optimizer)
scaler.update()
scheduler.step()
验证方法:
logits = torch.randn(2, C, 64, 64, device='cuda', dtype=torch.float32)*10
masks = torch.randint(0, C, (2, 64, 64), device='cuda', dtype=torch.long)
assert torch.isfinite(soft_dice_loss(logits, masks))
assert torch.isfinite(torch.nn.CrossEntropyLoss()(logits, masks))
预防措施:
按上述步骤逐项落实,优先尝试:BF16 AMP + FP32 Dice + 梯度裁剪 + Warmup + AdamW(eps=1e-6, 去除 BN/bias 的 weight decay)。通常可彻底消除第 3 个 epoch 溢出/NaN 问题,并显著稳定收敛。
问题描述
可能原因
排查步骤
解决方案 原因1:Tokenizer 退回 slow 或 Python 侧后处理
原因2:device/dtype 不一致导致 index_select 在 CPU
原因3:torch.compile 图断裂/回退
原因4:CPU 并行/线程过度
原因5:I/O 与拷贝路径
验证方法
预防措施
可执行优化清单
回滚策略
备注:如在上述优化后仍出现 “Falling back to CPU for aten::index_select”,请在最小脚本中单独运行 GPU 上的 index_select(对 embedding + input_ids)并附 profiler trace 与日志,以进一步判断是否为设备/类型不一致、形状导致的编译回退,或特定版本回归问题。此信息将直接定位到具体修复路径。
问题描述:
可能原因:
排查步骤:
解决方案:
验证方法:
预防措施:
按上述指南排查与修复,优先执行编码与标准化一致性对齐与时序截断,通常可快速恢复AUC至基线。
试用后开通会员即可无限使用