2021-12-27 07:04:32 +00:00
|
|
|
import torch
|
|
|
|
from colossalai.constants import INPUT_GROUP_3D, WEIGHT_GROUP_3D
|
2022-02-14 03:15:02 +00:00
|
|
|
from colossalai.nn.layer.parallel_3d import reduce_by_batch_3d, split_tensor_3d
|
2021-12-27 07:04:32 +00:00
|
|
|
from colossalai.nn.layer.parallel_3d._utils import get_parallel_mode_from_env
|
|
|
|
from torch import nn
|
|
|
|
|
|
|
|
from ._utils import calc_acc
|
|
|
|
|
|
|
|
|
|
|
|
class Accuracy3D(nn.Module):
|
2022-01-21 02:44:30 +00:00
|
|
|
"""Accuracy for 3D parallelism
|
2022-01-10 10:05:58 +00:00
|
|
|
"""
|
2021-12-27 07:04:32 +00:00
|
|
|
def __init__(self):
|
|
|
|
super().__init__()
|
|
|
|
self.input_parallel_mode = get_parallel_mode_from_env(INPUT_GROUP_3D)
|
|
|
|
self.weight_parallel_mode = get_parallel_mode_from_env(WEIGHT_GROUP_3D)
|
|
|
|
|
|
|
|
def forward(self, logits, targets):
|
2022-01-21 02:44:30 +00:00
|
|
|
"""Calculate the accuracy of predicted labels.
|
|
|
|
|
2022-03-25 05:02:39 +00:00
|
|
|
Args:
|
|
|
|
logits (:class:`torch.tensor`): Predicted labels.
|
|
|
|
targets (:class:`torch.tensor`): True labels from data.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
float: the accuracy of prediction.
|
2022-01-21 02:44:30 +00:00
|
|
|
"""
|
2021-12-27 07:04:32 +00:00
|
|
|
with torch.no_grad():
|
2022-02-14 03:15:02 +00:00
|
|
|
targets = split_tensor_3d(targets, 0, self.weight_parallel_mode)
|
|
|
|
targets = split_tensor_3d(targets, 0, self.input_parallel_mode)
|
2021-12-27 07:04:32 +00:00
|
|
|
correct = calc_acc(logits, targets)
|
2022-02-14 03:15:02 +00:00
|
|
|
correct = reduce_by_batch_3d(correct, self.input_parallel_mode, self.weight_parallel_mode)
|
2021-12-27 07:04:32 +00:00
|
|
|
return correct
|