|
| 1 | +# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Finetuning-specific data handling utilities.""" |
| 16 | + |
| 17 | +from typing import Any, Iterator |
| 18 | + |
| 19 | +import torch |
| 20 | + |
| 21 | + |
| 22 | +def split_batch_into_microbatches( |
| 23 | + batch: dict[str, Any], num_microbatches: int, enforce_divisible: bool = True |
| 24 | +) -> list[dict[str, Any]]: |
| 25 | + """Split a batch dictionary into microbatches. |
| 26 | +
|
| 27 | + Takes a global batch (e.g., [16, 240] for tokens) and splits it into |
| 28 | + num_microbatches smaller batches (e.g., 4 batches of [4, 240]). |
| 29 | +
|
| 30 | + Args: |
| 31 | + batch: Dictionary containing tensors with batch_size = num_microbatches * micro_batch_size |
| 32 | + num_microbatches: Number of microbatches to split into |
| 33 | + enforce_divisible: Whether to enforce batch_size % num_microbatches == 0 |
| 34 | +
|
| 35 | + Returns: |
| 36 | + List of microbatch dictionaries, each containing the same keys as the input batch |
| 37 | +
|
| 38 | + Example: |
| 39 | + >>> batch = {'tokens': torch.rand(16, 240), 'labels': torch.rand(16, 240)} |
| 40 | + >>> microbatches = split_batch_into_microbatches(batch, num_microbatches=4) |
| 41 | + >>> len(microbatches) # 4 |
| 42 | + >>> microbatches[0]['tokens'].shape # torch.Size([4, 240]) |
| 43 | + """ |
| 44 | + # Identify tensor items vs other items (like metadata) |
| 45 | + tensor_items = {k: v for k, v in batch.items() if isinstance(v, torch.Tensor)} |
| 46 | + other_items = {k: v for k, v in batch.items() if not isinstance(v, torch.Tensor)} |
| 47 | + |
| 48 | + if len(tensor_items) == 0: |
| 49 | + raise ValueError("Batch must contain at least one tensor") |
| 50 | + |
| 51 | + # Get batch size from first tensor |
| 52 | + first_key = next(iter(tensor_items.keys())) |
| 53 | + batch_size = tensor_items[first_key].shape[0] |
| 54 | + |
| 55 | + if enforce_divisible and batch_size % num_microbatches != 0: |
| 56 | + raise ValueError( |
| 57 | + f"Batch size {batch_size} is not divisible by num_microbatches {num_microbatches}. " |
| 58 | + f"Cannot split evenly into microbatches." |
| 59 | + ) |
| 60 | + |
| 61 | + # Split all tensors along batch dimension (dim=0) |
| 62 | + split_tensors = {} |
| 63 | + for key, tensor in tensor_items.items(): |
| 64 | + split_tensors[key] = torch.tensor_split(tensor, num_microbatches, dim=0) |
| 65 | + |
| 66 | + # Create microbatch dictionaries |
| 67 | + microbatches = [] |
| 68 | + for i in range(num_microbatches): |
| 69 | + microbatch = {} |
| 70 | + |
| 71 | + # Add split tensors |
| 72 | + for key, splits in split_tensors.items(): |
| 73 | + microbatch[key] = splits[i] |
| 74 | + |
| 75 | + # Handle non-tensor items (metadata, etc.) |
| 76 | + for key, value in other_items.items(): |
| 77 | + if isinstance(value, list) and len(value) == batch_size: |
| 78 | + # If it's a list with length matching batch size, split it too |
| 79 | + micro_batch_size = batch_size // num_microbatches |
| 80 | + start_idx = i * micro_batch_size |
| 81 | + end_idx = start_idx + micro_batch_size |
| 82 | + microbatch[key] = value[start_idx:end_idx] |
| 83 | + else: |
| 84 | + # Otherwise copy as-is (e.g., global metadata) |
| 85 | + microbatch[key] = value |
| 86 | + |
| 87 | + microbatches.append(microbatch) |
| 88 | + |
| 89 | + return microbatches |
| 90 | + |
| 91 | + |
| 92 | +def prepare_finetuning_batch( |
| 93 | + data_iterator: Iterator, |
| 94 | + num_microbatches: int, |
| 95 | + default_seq_length: int, |
| 96 | + seq_key: str = "tokens", |
| 97 | +) -> tuple[Iterator, int]: |
| 98 | + """Prepare a finetuning batch by getting global batch and splitting into microbatches. |
| 99 | +
|
| 100 | + This function handles the finetuning-specific data flow: |
| 101 | + 1. Gets the full global batch from the iterator |
| 102 | + 2. Extracts the dynamic sequence length from the batch |
| 103 | + 3. Splits the batch into microbatches with consistent sequence length |
| 104 | + 4. Returns an iterator over microbatches and the extracted sequence length |
| 105 | +
|
| 106 | + Args: |
| 107 | + data_iterator: Iterator that yields global batches (e.g., from DataLoader with batch sampler) |
| 108 | + num_microbatches: Number of microbatches to split each global batch into |
| 109 | + default_seq_length: Fallback sequence length if it cannot be extracted from batch |
| 110 | + seq_key: Key in batch dict containing the sequence tensor (default: 'tokens') |
| 111 | +
|
| 112 | + Returns: |
| 113 | + Tuple of: |
| 114 | + - Iterator over microbatches (each microbatch is a dict with same keys as global batch) |
| 115 | + - Sequence length extracted from the global batch (or default_seq_length if not found) |
| 116 | +
|
| 117 | + Example: |
| 118 | + >>> # DataLoader yields global batch of shape [16, 240] |
| 119 | + >>> microbatch_iter, seq_len = prepare_finetuning_batch( |
| 120 | + ... data_iterator=iter(dataloader), |
| 121 | + ... num_microbatches=4, |
| 122 | + ... default_seq_length=2048 |
| 123 | + ... ) |
| 124 | + >>> seq_len # 240 (extracted from batch) |
| 125 | + >>> batch1 = next(microbatch_iter) |
| 126 | + >>> batch1['tokens'].shape # torch.Size([4, 240]) |
| 127 | + """ |
| 128 | + # Get full global batch from dataloader |
| 129 | + global_batch = next(data_iterator) |
| 130 | + |
| 131 | + # Extract dynamic seq_length from the full batch |
| 132 | + seq_length = default_seq_length |
| 133 | + if seq_key in global_batch and isinstance(global_batch[seq_key], torch.Tensor): |
| 134 | + seq_length = global_batch[seq_key].size(1) |
| 135 | + |
| 136 | + # Split into microbatches |
| 137 | + microbatches = split_batch_into_microbatches(global_batch, num_microbatches) |
| 138 | + |
| 139 | + # Return iterator over microbatches and the extracted seq_length |
| 140 | + return iter(microbatches), seq_length |
0 commit comments