-
Notifications
You must be signed in to change notification settings - Fork 534
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
7 changed files
with
188 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
# Copyright 2024 MosaicML LLM Foundry authors | ||
# SPDX-License-Identifier: Apache-2.0 | ||
|
||
from llmfoundry.metrics.token_acc import TokenAccuracy | ||
|
||
__all__ = [ | ||
'TokenAccuracy', | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
# Copyright 2024 MosaicML LLM Foundry authors | ||
# SPDX-License-Identifier: Apache-2.0 | ||
|
||
import torch | ||
from torchmetrics import Metric | ||
|
||
__all__ = [ | ||
'TokenAccuracy', | ||
] | ||
|
||
|
||
class TokenAccuracy(Metric): | ||
"""Torchmetric to compute token-level accuracy for language modeling. | ||
Adds metric state variables: | ||
correct_tokens (float): The number of correct token predictions. | ||
total_tokens (float): The total number of tokens predicted. | ||
Args: | ||
ignore_index (int, optional): The index of tokens to ignore, typically for padding. Default: -100. | ||
dist_sync_on_step (bool, optional): Synchronize metric state across processes at | ||
each forward() before returning the value at the step. Default: False. | ||
""" | ||
|
||
# Ensures torchmetrics calls update only once | ||
full_state_update = False | ||
|
||
def __init__(self, | ||
ignore_index: int = -100, | ||
dist_sync_on_step: bool = False): | ||
super().__init__(dist_sync_on_step=dist_sync_on_step) | ||
self.ignore_index = ignore_index | ||
self.add_state('correct_tokens', | ||
default=torch.tensor(0), | ||
dist_reduce_fx='sum') | ||
self.add_state('total_tokens', | ||
default=torch.tensor(0), | ||
dist_reduce_fx='sum') | ||
|
||
def update(self, preds: torch.Tensor, target: torch.Tensor): | ||
"""Updates the internal state with results from a new batch. | ||
Args: | ||
preds (~torch.Tensor): The predictions from the model, a Tensor of logits. | ||
target (~torch.Tensor): A Tensor of ground-truth token values. | ||
""" | ||
# Convert logits to predicted token indices | ||
preds = torch.argmax(preds, dim=-1) | ||
|
||
# Create mask for non-ignored tokens | ||
mask = (target != self.ignore_index) | ||
masked_target = target[mask] | ||
masked_preds = preds[mask] | ||
|
||
# Update correct and total counts | ||
self.correct_tokens += torch.sum(masked_preds == masked_target) | ||
self.total_tokens += masked_target.numel() | ||
|
||
def compute(self) -> torch.Tensor: | ||
"""Aggregate the state over all processes to compute the metric. | ||
Returns: | ||
The mean accuracy across all tokens as a :class:`~torch.Tensor`. | ||
""" | ||
return self.correct_tokens.float() / self.total_tokens |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
# Copyright 2024 MosaicML LLM Foundry authors | ||
# SPDX-License-Identifier: Apache-2.0 | ||
|
||
import pytest | ||
import torch | ||
|
||
from llmfoundry.metrics import TokenAccuracy | ||
|
||
|
||
@pytest.mark.parametrize('ignore_index', [-100, -200]) | ||
@pytest.mark.parametrize('vocab_size', [100]) | ||
def test_token_accuracy(ignore_index: int, vocab_size: int): | ||
batch_size = int(1e6) | ||
torchmetrics_token_acc = TokenAccuracy(ignore_index=ignore_index) | ||
generated_preds = torch.rand((batch_size, vocab_size)) | ||
true_labels = torch.randint(low=0, high=vocab_size - 1, size=(batch_size,)) | ||
|
||
# Randomly insert ignore_index into the labels | ||
labels_mask = torch.rand((batch_size,)) | ||
labels_mask[labels_mask > 0.8] = 1 | ||
labels_mask[labels_mask <= 0.8] = 0 | ||
labels_mask = labels_mask.bool() | ||
true_labels[labels_mask] = ignore_index | ||
|
||
true_labels = true_labels.float() | ||
generated_preds = generated_preds.float() | ||
|
||
torchmetrics_token_acc.update(generated_preds, true_labels) | ||
final_acc = torchmetrics_token_acc.compute() | ||
|
||
expected_random_acc_tensor = torch.tensor(1.0 / vocab_size) | ||
torch.testing.assert_close(final_acc, expected_random_acc_tensor) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters