Spaces:
Sleeping
Sleeping
Upload models/uncertainty_loss.py with huggingface_hub
Browse files- models/uncertainty_loss.py +43 -0
models/uncertainty_loss.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class HomoscedasticUncertaintyLoss(nn.Module):
|
| 7 |
+
def __init__(self, num_tasks: int):
|
| 8 |
+
super(HomoscedasticUncertaintyLoss, self).__init__()
|
| 9 |
+
self.num_tasks = num_tasks
|
| 10 |
+
self.s = nn.Parameter(torch.zeros(num_tasks, dtype=torch.float32))
|
| 11 |
+
|
| 12 |
+
def forward(self, logits, targets, mask):
|
| 13 |
+
total_loss = 0.0
|
| 14 |
+
task_losses = []
|
| 15 |
+
task_weights = torch.exp(-self.s)
|
| 16 |
+
valid_task_count = 0
|
| 17 |
+
|
| 18 |
+
for t in range(self.num_tasks):
|
| 19 |
+
task_logits = logits[:, t]
|
| 20 |
+
task_targets = targets[:, t]
|
| 21 |
+
task_mask = mask[:, t]
|
| 22 |
+
|
| 23 |
+
valid_indices = torch.where(task_mask == 1)[0]
|
| 24 |
+
if len(valid_indices) == 0:
|
| 25 |
+
task_losses.append(torch.tensor(0.0, device=logits.device))
|
| 26 |
+
continue
|
| 27 |
+
|
| 28 |
+
v_logits = task_logits[valid_indices]
|
| 29 |
+
v_targets = task_targets[valid_indices].float()
|
| 30 |
+
|
| 31 |
+
bce_loss = F.binary_cross_entropy_with_logits(
|
| 32 |
+
v_logits, v_targets, reduction='mean'
|
| 33 |
+
)
|
| 34 |
+
task_losses.append(bce_loss)
|
| 35 |
+
|
| 36 |
+
weighted_loss = task_weights[t] * bce_loss + 0.5 * self.s[t]
|
| 37 |
+
total_loss += weighted_loss
|
| 38 |
+
valid_task_count += 1
|
| 39 |
+
|
| 40 |
+
if valid_task_count == 0:
|
| 41 |
+
return torch.tensor(0.0, device=logits.device, requires_grad=True), task_losses, task_weights
|
| 42 |
+
|
| 43 |
+
return total_loss, torch.stack(task_losses) if task_losses else torch.tensor([]), task_weights
|