initial commit

This commit is contained in:
Sen Liang committed 2022-01-21 17:42:41 +08:00
commit c7175dd7ff
127 files changed
+13949

No files matched your search

+87
View File
@@ -0,0 +1,87 @@
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
from collections import OrderedDict
class MultiLossManager(nn.Module):
"""Managment Multiple-Loss
"""
def __init__(self, opt, autoWeight=False):
super(MultiLossManager, self).__init__()
self.opt = opt
self.autoWeight = autoWeight
self.weight = {}
self.weigth_name = []
for iname in opt.LOSS.names:
iname_full = f"lambda_{iname}"
if iname_full in opt.LOSS.keys() and opt.LOSS[iname_full] > 0:
self.weight[ "loss_"+iname ] = opt.LOSS[iname_full]
self.weigth_name.append("loss_" + iname )
n_weight = len(self.weight)
print(f"WEIGHT of LOSS (n={n_weight}) = {self.weight}")
if autoWeight:
self.weight = torch.ones(n_weight, requires_grad=True)
self.weight = torch.nn.Parameter(self.weight)
def forward(self, dict_loss):
assert isinstance(dict_loss, OrderedDict), "dict_loss should be a OrderedDict"
loss_sum = 0
i = 0
for name in dict_loss.keys():
if name not in self.weigth_name: continue
if self.autoWeight:
loss_sum += 0.5 / (self.weight[i] ** 2) * dict_loss[name] + torch.log(1 + self.weight[i] ** 2)
else:
loss_sum += (self.weight[name] * dict_loss[name])
i += 1
# print(f"update WEIGHT of LOSS {self.weight}")
return loss_sum
class AutomaticWeightedLoss(nn.Module):
"""automatically weighted multi-task loss
Params:
num: int,the number of loss
x: multi-task loss
Examples:
loss1=1
loss2=2
awl = AutomaticWeightedLoss(2)
loss_sum = awl(loss1, loss2)
"""
def __init__(self, num=2):
super(AutomaticWeightedLoss, self).__init__()
params = torch.ones(num, requires_grad=True)
self.params = torch.nn.Parameter(params)
def forward(self, dict_loss):
assert isinstance(dict_loss, OrderedDict), "dict_loss should be a OrderedDict"
loss_sum = 0
for i, name in enumerate(dict_loss.keys()):
loss_sum += 0.5 / (self.params[i] ** 2) * dict_loss[name] + torch.log(1 + self.params[i] ** 2)
return loss_sum
if __name__ == '__main__':
awl = AutomaticWeightedLoss(2)
print(awl.parameters())
+12
View File
@@ -0,0 +1,12 @@
from .wing import WingLoss
from .smooth_l1_loss import SmoothL1Loss, L1Loss
# from .landmarkloss import LandmarkPolygonLoss, LandmarkFocalLoss
"""
Source: https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/losses/__init__.py
"""
__all__ = [
"WingLoss", "AdaptiveWingLoss", "LandmarkPolygonLoss", "LandmarkFocalLoss"
]
View File
Whitespace-only changes.
+115
View File
@@ -0,0 +1,115 @@
import torch
import torch.nn as nn
import numpy as np
from shapely.geometry import Polygon
class LandmarkPolygonLoss(nn.Module):
def __init__(self, opt):
super(LandmarkPolygonLoss, self).__init__()
self.opt = opt
self.lmdk_indx = {
"chin": list(range(0,17)),
"eyebrow_lt": [17, 18, 19, 20, 21],
"eyebrow_rt": [22, 23, 24, 25, 26],
"nose": [27, 31, 32, 33, 34, 35],
"eye_lt": [36, 37, 38, 39, 40, 41],
"eye_rt": [42, 43, 44, 45, 46, 47],
"mouth_out": list(range(48, 60)),
"mouth_inn": list(range(60, 68)),
}
def forward(self, pred, target):
# predit, (nbatch, 68*2)
# target, (nbatch, 68*2)
#print(f"pred shape = {predit.shape}, target shape = {target.shape}")
pred = pred.reshape(-1, 68, 2) * 128
target = target.reshape(-1, 68, 2) * 128
loss_chin = self.area_diff(pred, target, "chin")
loss_nose = self.area_diff(pred, target, "nose")
loss_eyebrow = self.area_diff(pred, target, "eyebrow_lt") \
+ self.area_diff(pred, target, "eyebrow_rt")
loss_eye = self.area_diff(pred, target, "eye_lt") \
+ self.area_diff(pred, target, "eye_rt")
loss_mouth = self.area_diff(pred, target, "mouth_out") \
+ self.area_diff(pred, target, "mouth_inn")
loss = loss_chin + loss_nose + loss_eyebrow + loss_eye # + loss_mouth
loss = torch.mean(loss)
return loss
def area_diff(self, pred, target, part):
indx = self.lmdk_indx[part]
area_pt = self.PolygonArea(pred, indx)
area_gt = self.PolygonArea(target, indx)
diff = torch.abs(area_pt - area_gt)
return diff
def PolygonArea(self, corners, indx):
"""PolygonArea Function.
Args:
corners (torch.Tensor): the keypoints of corners, (nbatch, 68, 2)
indx (list, int): the polygon index from the keypoints
Return:
area (torch.Tensor): (nbatch, )
"""
area, n = 0, len(indx)
for i in range(n):
j = (i + 1) % n
area += corners[:, i, 0] * corners[:, j, 1]
area -= corners[:, j, 0] * corners[:, i, 1]
area = torch.abs(area) / 2.0
return area
class LandmarkFocalLoss(nn.Module):
def __init__(self, opt):
super(LandmarkFocalLoss, self).__init__()
self.opt = opt
def forward(self, predit, target):
# predit, (nbatch, 68*2)
# target, (nbatch, 68*2)
#print(f"pred shape = {predit.shape}, target shape = {target.shape}")
predit = predit.reshape(-1, 68, 2)
target = target.reshape(-1, 68, 2)
x = torch.abs(predit - target) # (nbatch, 68, 2)
x = torch.sqrt(x[:,:,0] * x[:,:,0] + x[:,:,1] * x[:,:,1]) # (nbatch, 68)
#print(f"xsqrt = {x[0, :]}")
x = torch.torch.pow(1 + 1000*x, x) - 1 # (nbatch, 68)
x = torch.clamp_max_(x, 10)
#print(f"xpow = {x[0, :]}")
weight = torch.ones((68,), dtype=x.dtype, device=x.device)
weight[48:68] = 10
x = torch.mean(x, dim=0) # (68, )
x = torch.mean(x * weight) # (1, )
return x
+13
View File
@@ -0,0 +1,13 @@
import torch
import torch.nn as nn
from .utils import weighted_loss
@weighted_loss
def pfld_loss(pred, target, euler_pt, euler_gt, attribute_gt):
"""PFLD loss.
Args:
pred (torch.Tensor): The prediction landmark. (nbatch, 68*2)
"""
+101
View File
@@ -0,0 +1,101 @@
import torch
import torch.nn as nn
from .utils import weighted_loss
@weighted_loss
def l1_loss(pred, target):
""" L1 loss.
Args:
pred (torch.Tensor): The prediction.
target(torch.Tensor): The ground truth of the prediction
Returns:
torch.Tensor: loss
"""
assert pred.size() == target.size() and target.numel() > 0
loss = torch.abs(pred - target)
return loss
@weighted_loss
def smooth_l1_loss(pred, target, beta=1.0):
"""Smooth L1 Loss.
Args:
pred (torch.Tensor): The prediction
target (torch.Tensor): The GT of the prediction
Returns:
torch.Tensor: loss
"""
assert beta > 0
assert pred.size() == target.size() and target.numel() > 0
diff = torch.abs(pred - target)
loss = torch.where(diff < beta, 0.5 * diff * diff / beta, diff - 0.5 * beta)
return loss
class L1Loss(nn.Module):
"""L1 Loss
Args:
reduction (str, optional): The method to reduce the loss, Options are `none|mean|sum`
loss_weight (float, optional): The weight of loss.
"""
def __init__(self, reduction='mean', loss_weight=1.0):
super(L1Loss, self).__init__()
self.reduction = reduction
self.loss_weight = loss_weight
def forward(self, pred, target, weight=None, avg_factor=None):
"""Forward function.
Args:
pred (troch.Tensor): The prediction
target (torch.Tensor): The GT of the prediction.
weight (torch.Tensor, optional): The weight of loss for each prediction.
avg_factor(int, optional): Average factor that is used to average the loss.
"""
loss = l1_loss(pred, target, weight=weight, reduction=self.reduction, avg_factor=avg_factor)
loss = self.loss_weight * loss
return loss
class SmoothL1Loss(nn.Module):
"""Smooth L1 Loss.
Args:
beta (float, optional): The threshold in the piecewise function. Default 1.0
reduction (str, optional): The reduce loss method, options are `none|mean|sum`
loss_weight (float, optional): The weight of loss
Return:
torch.Tensor: Loss
"""
def __init__(self, beta=1.0, reduction="mean", loss_weight=1.0):
super(SmoothL1Loss, self).__init__()
self.beta = beta
self.reduction = reduction
self.loss_weight = loss_weight
def forward(self, pred, target, weight=None, avg_factor=None):
"""Forward function.
Args:
pred (torch.Tensor): The prediction.
target (torch.Tensor): The GT of the prediction
weight (torch.Tensor, optional): The weigth of loss for each prediction. Default to None
avg_factor (int, optional): Average factor that is used to average the loss.
"""
loss = smooth_l1_loss(pred, target, beta=self.beta, weight=weight, avg_factor=avg_factor)
loss = self.loss_weight * loss
return loss
+104
View File
@@ -0,0 +1,104 @@
import functools
import torch.nn.functional as F
"""
Source: https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/losses/utils.py
"""
def reduce_loss(loss, reduction):
"""Reduce loss as specified.
Args:
loss (Tensor): Elementwise loss tensor.
reduction (str): Options are "none", "mean" and "sum".
Return:
Tensor: Reduced loss tensor.
"""
reduction_enum = F._Reduction.get_enum(reduction)
# none: 0, elementwise_mean:1, sum: 2
if reduction_enum == 0:
return loss
elif reduction_enum == 1:
return loss.mean()
elif reduction_enum == 2:
return loss.sum()
def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None):
"""Apply element-wise weight and reduce loss.
Args:
loss (Tensor): Element-wise loss.
weight (Tensor): Element-wise weights.
reduction (str): Same as built-in losses of PyTorch.
avg_factor (float): Avarage factor when computing the mean of losses.
Returns:
Tensor: Processed loss values.
"""
# if weight is specified, apply element-wise weight
if weight is not None:
loss = loss * weight
# if avg_factor is not specified, just reduce the loss
if avg_factor is None:
loss = reduce_loss(loss, reduction)
else:
# if reduction is mean, then average the loss by avg_factor
if reduction == 'mean':
loss = loss.sum() / avg_factor
# if reduction is 'none', then do nothing, otherwise raise an error
elif reduction != 'none':
raise ValueError('avg_factor can not be used with reduction="sum"')
return loss
def weighted_loss(loss_func):
"""Create a weighted version of a given loss function.
To use this decorator, the loss function must have the signature like
`loss_func(pred, target, **kwargs)`. The function only needs to compute
element-wise loss without any reduction. This decorator will add weight
and reduction arguments to the function. The decorated function will have
the signature like `loss_func(pred, target, weight=None, reduction='mean',
avg_factor=None, **kwargs)`.
:Example:
>>> import torch
>>> @weighted_loss
>>> def l1_loss(pred, target):
>>> return (pred - target).abs()
>>> pred = torch.Tensor([0, 2, 3])
>>> target = torch.Tensor([1, 1, 1])
>>> weight = torch.Tensor([1, 0, 1])
>>> l1_loss(pred, target)
tensor(1.3333)
>>> l1_loss(pred, target, weight)
tensor(1.)
>>> l1_loss(pred, target, reduction='none')
tensor([1., 1., 2.])
>>> l1_loss(pred, target, weight, avg_factor=2)
tensor(1.5000)
"""
@functools.wraps(loss_func)
def wrapper(pred,
target,
weight=None,
reduction='mean',
avg_factor=None,
**kwargs):
# get element-wise loss
loss = loss_func(pred, target, **kwargs)
loss = weight_reduce_loss(loss, weight, reduction, avg_factor)
return loss
return wrapper
+73
View File
@@ -0,0 +1,73 @@
import math
import torch
from torch import nn
from .utils import weighted_loss
"""
The Wing loss:
It has been proposed in `Wing Loss for Roubst Facial Landmark Localisation with
Convolutional Neural Networks`. https://arxiv.org/abs/1711.06753
"""
@weighted_loss
def wing_loss(pred, target, w=5, epsilon=0.5):
"""
Source: https://github.com/BloodAxe/pytorch-toolbelt/blob/develop/pytorch_toolbelt/losses/functional.py
"""
diff = torch.abs(pred - target)
C = w - w * math.log(1 + w / epsilon)
loss = torch.where(diff < w, w * torch.log(1 + diff / epsilon), diff - C)
return loss
class WingLoss(nn.Module):
def __init__(self, w=10, epsilon=0.5, reduction='mean', loss_weight=1.0):
super(WingLoss,self).__init__()
self.w = w
self.epsilon = epsilon
self.reduction = reduction
self.loss_weight = loss_weight
def forward(self, pred, target, weight=None, avg_factor=None):
"""Forward function.
Args:
pred (torch.Tensor, Bx68*2): The prediction
target (torch.Tensor, Bx68*2): The GT of prediction
weight (torch.Tensor, optional): The weight of each loss, default None
avg_factor(int, optional): The average of the reduction loss
"""
loss = wing_loss(pred, target, w=self.w, epsilon=self.epsilon, weight=weight, avg_factor=avg_factor)
loss = self.loss_weight * loss
return loss
if __name__ == "__main__":
crieation = WingLoss()
GT = torch.zeros((2, 68, 64, 64))
PT = torch.ones((2, 68, 64, 64))
PT.requires_grad_(True)
loss = crieation(PT, GT)
loss.backward()
print(loss)