Source code for nemo_automodel.training.utils
# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
[docs]
@torch.no_grad()
def count_tail_padding(labels, ignore_label=-100):
"""Counts the total number of padding token in the tail of labels
e.g.
labels = torch.tensor([
[-100, 1, 1, -100, -100], # 2 tail -100s
[-100, -100, 2, 3, 4], # 0 tail -100s
[5, 6, -100, -100, -100], # 3 tail -100s
])
count_tail_padding will return 5. Please do note there's more than 5 ignore labels.
Args:
labels (torch.Tensor): the labels
ignore_label (int, optional): ignore label index. Defaults to -100.
Returns:
int: total number of ignored tokens in the `labels` input.
"""
# Flip along the last dimension (seq_len)
flipped = labels.flip(dims=[1])
tail_mask = flipped == ignore_label
# Compute cumulative product to "break" on first non ignore_label
prod_mask = torch.cumprod(tail_mask.int(), dim=1)
# Count tail -100s by summing cumprod mask along the sequence dimension
return prod_mask.view(-1).sum().item()