| 1 | # Copyright 2025 OpenAccess AI Collective and the LlamaFactory team. |
| 2 | # |
| 3 | # This code is inspired by the OpenAccess AI Collective's axolotl library. |
| 4 | # https://github.com/OpenAccess-AI-Collective/axolotl/blob/main/src/axolotl/monkeypatch/utils.py |
| 5 | # |
| 6 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | # you may not use this file except in compliance with the License. |
| 8 | # You may obtain a copy of the License at |
| 9 | # |
| 10 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | # |
| 12 | # Unless required by applicable law or agreed to in writing, software |
| 13 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | # See the License for the specific language governing permissions and |
| 16 | # limitations under the License. |
| 17 | |
| 18 | from dataclasses import dataclass |
| 19 | from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Sequence, Tuple |
| 20 | |
| 21 | import torch |
| 22 | import torch.nn.functional as F |
| 23 | from transformers import DataCollatorForSeq2Seq |
| 24 | |
| 25 | from .template import IGNORE_INDEX |
| 26 | |
| 27 | if TYPE_CHECKING: |
| 28 | from transformers import PreTrainedTokenizer |
| 29 | |
| 30 | from .template import Template |
| 31 | from .mm_plugin import PointCloudInput |
| 32 | |
| 33 | |
| 34 | def prepare_4d_attention_mask( |
| 35 | attention_mask_with_indices: "torch.Tensor", dtype: "torch.dtype" |
| 36 | ) -> "torch.Tensor": |
| 37 | r"""Expand 2d attention mask to 4d attention mask. |
| 38 | |
| 39 | Expand the attention mask with indices from (batch_size, seq_len) to (batch_size, 1, seq_len, seq_len), |
| 40 | handle packed sequences and transforms the mask to lower triangular form to prevent future peeking. |
| 41 | |
| 42 | e.g. |
| 43 | ```python |
| 44 | # input |
| 45 | [[1, 1, 2, 2, 2, 0]] |
| 46 | # output |
| 47 | [ |
| 48 | [ |
| 49 | [ |
| 50 | [o, x, x, x, x, x], |
| 51 | [o, o, x, x, x, x], |
| 52 | [x, x, o, x, x, x], |
| 53 | [x, x, o, o, x, x], |
| 54 | [x, x, o, o, o, x], |
| 55 | [x, x, x, x, x, x], |
| 56 | ] |
| 57 | ] |
| 58 | ] |
| 59 | ``` |
| 60 | where `o` equals to `0.0`, `x` equals to `min_dtype`. |
| 61 | """ |
| 62 | _, seq_len = attention_mask_with_indices.size() |
| 63 | min_dtype = torch.finfo(dtype).min |
| 64 | zero_tensor = torch.tensor(0, dtype=dtype) |
| 65 | |
| 66 | # Create a non-padding mask. |
| 67 | non_padding_mask = (attention_mask_with_indices != 0).unsqueeze(1).unsqueeze(2) |
| 68 | # Create indices for comparison. |
| 69 | indices = attention_mask_with_indices.unsqueeze(1).unsqueeze( |
| 70 | 2 |
| 71 | ) # [bsz, 1, 1, seq_len] |
| 72 | indices_t = attention_mask_with_indices.unsqueeze(1).unsqueeze( |
| 73 | 3 |
| 74 | ) # [bsz, 1, seq_len, 1] |
| 75 | # Create a lower triangular mask. |
| 76 | tril_mask = torch.tril(torch.ones((seq_len, seq_len), dtype=torch.bool)) |
| 77 | attention_mask_4d = (indices == indices_t) & non_padding_mask & tril_mask |
| 78 | # Invert the attention mask. |
| 79 | attention_mask_4d = torch.where(attention_mask_4d, zero_tensor, min_dtype) |
| 80 | return attention_mask_4d |
| 81 | |
| 82 | |
| 83 | def infer_seqlen(source_len: int, target_len: int, cutoff_len: int) -> Tuple[int, int]: |
| 84 | r""" |
| 85 | Computes the real sequence length after truncation by the cutoff_len. |
| 86 | """ |
| 87 | if target_len * 2 < cutoff_len: # truncate source |
| 88 | max_target_len = cutoff_len |
| 89 | elif source_len * 2 < cutoff_len: # truncate target |
| 90 | max_target_len = cutoff_len - source_len |
| 91 | else: # truncate both |
| 92 | max_target_len = int(cutoff_len * (target_len / (source_len + target_len))) |
| 93 | |
| 94 | new_target_len = min(max_target_len, target_len) |
| 95 | max_source_len = max(cutoff_len - new_target_len, 0) |
| 96 | new_source_len = min(max_source_len, source_len) |
| 97 | return new_source_len, new_target_len |
| 98 | |
| 99 | |
| 100 | def _encode_messages_example( |
| 101 | messages: Sequence[Dict[str, str]], |
| 102 | system: Optional[str], |
| 103 | point_clouds: Sequence["PointCloudInput"], |
| 104 | template: "Template", |
| 105 | tokenizer: "PreTrainedTokenizer", |
| 106 | cutoff_len: int, |
| 107 | ) -> Tuple[List[int], List[int]]: |
| 108 | input_ids, labels = template.mm_plugin.process_token_ids( |
| 109 | [], [], point_clouds, tokenizer |
| 110 | ) |
| 111 | encoded_pairs = template.encode_multiturn(tokenizer, messages, system) |
| 112 | total_length = len(input_ids) |
| 113 | |
| 114 | for turn_idx, (source_ids, target_ids) in enumerate(encoded_pairs): |
| 115 | if total_length >= cutoff_len: |
| 116 | break |
| 117 | |
| 118 | source_len, target_len = infer_seqlen( |
| 119 | len(source_ids), len(target_ids), cutoff_len - total_length |
| 120 | ) |
| 121 | source_ids = source_ids[:source_len] |
| 122 | target_ids = target_ids[:target_len] |
| 123 | total_length += source_len + target_len |
| 124 | source_label = [IGNORE_INDEX] * source_len |
| 125 | |
| 126 | target_label = target_ids |
| 127 | input_ids += source_ids + target_ids |
| 128 | labels += source_label + target_label |
| 129 | |
| 130 | return input_ids, labels |
| 131 | |
| 132 | |
| 133 | @dataclass |
| 134 | class MultiModalDataCollatorForSeq2Seq(DataCollatorForSeq2Seq): |
| 135 | r""" |
| 136 | Data collator that supports VLMs. |
| 137 | |
| 138 | Features should contain input_ids, attention_mask, labels, and optionally contain images and videos. |
| 139 | """ |
| 140 | |
| 141 | template: Optional["Template"] = None |
| 142 | |
| 143 | def __post_init__(self): |
| 144 | if self.template is None: |
| 145 | raise ValueError("Template is required for MultiModalDataCollator.") |
| 146 | |
| 147 | def __call__(self, features: Sequence[Dict[str, Any]]) -> Dict[str, "torch.Tensor"]: |
| 148 | batch_point_clouds, batch_input_prompts = [], [] |
| 149 | for feature in features: |
| 150 | prompts = feature.pop("_prompt") |
| 151 | responses = feature.pop("_response") |
| 152 | point_clouds = feature.pop("_point_clouds", None) or [] |
| 153 | batch_point_clouds.extend(point_clouds) |
| 154 | batch_input_prompts.append(prompts + responses) |
| 155 | |
| 156 | mm_inputs = self.template.mm_plugin.get_mm_inputs( |
| 157 | batch_point_clouds, batch_input_prompts |
| 158 | ) |
| 159 | batched_messages = mm_inputs.pop("messages") |
| 160 | |
| 161 | for mi, messages in enumerate(batched_messages): |
| 162 | feature = features[mi] |
| 163 | input_ids, labels = _encode_messages_example( |
| 164 | messages=messages, |
| 165 | system=feature.pop("_system", ""), |
| 166 | point_clouds=batch_point_clouds[mi] if batch_point_clouds else [], |
| 167 | template=self.template, |
| 168 | tokenizer=self.tokenizer, |
| 169 | cutoff_len=self.template.cutoff_len, |
| 170 | ) |
| 171 | feature["input_ids"] = input_ids |
| 172 | feature["attention_mask"] = [1] * len(input_ids) |
| 173 | feature["labels"] = labels |
| 174 | |
| 175 | features: Dict[str, "torch.Tensor"] = super().__call__(features) |
| 176 | features.update(mm_inputs) |
| 177 | |
| 178 | return features |
| 179 | |
| 180 | |
| 181 | @dataclass |
| 182 | class SFTDataCollatorWith4DAttentionMask(MultiModalDataCollatorForSeq2Seq): |
| 183 | r"""Data collator for 4d attention mask.""" |
| 184 | |
| 185 | block_diag_attn: bool = False |
| 186 | attn_implementation: Literal["eager", "sdpa", "flash_attention_2"] = "eager" |
| 187 | compute_dtype: "torch.dtype" = torch.float32 |
| 188 | |
| 189 | def __call__(self, features: list[dict[str, Any]]) -> dict[str, "torch.Tensor"]: |
| 190 | features = super().__call__(features) |
| 191 | if self.block_diag_attn and self.attn_implementation != "flash_attention_2": |
| 192 | features["attention_mask"] = prepare_4d_attention_mask( |
| 193 | features["attention_mask"], self.compute_dtype |
| 194 | ) |
| 195 | |
| 196 | for key, value in features.items(): # cast data dtype |
| 197 | if torch.is_tensor(value) and torch.is_floating_point(value): |
| 198 | features[key] = value.to(self.compute_dtype) |
| 199 | |
| 200 | return features |