import torch
import numpy as np

@torch.no_grad()
def compute_dice(pred, target, num_classes):
    """Compute mean Dice coefficient."""
    pred = torch.argmax(pred, dim=1)
    dice_list = []
    for cls in range(num_classes):
        pred_mask = (pred == cls)
        target_mask = (target == cls)
        intersection = (pred_mask & target_mask).sum().float()
        cardinality = pred_mask.sum().float() + target_mask.sum().float()
        if cardinality > 0:
            dice_list.append((2 * intersection / cardinality).item())
    return np.mean(dice_list) if dice_list else 0.0