| 1 | import json |
| 2 | import warnings |
| 3 | from dataclasses import dataclass, field |
| 4 | from pathlib import Path |
| 5 | from typing import Union |
| 6 | |
| 7 | import mlx.core as mx |
| 8 | import mlx.nn as nn |
| 9 | import numpy as np |
| 10 | from mlx.utils import tree_flatten, tree_map |
| 11 | |
| 12 | |
| 13 | def get_prompt(model_type, processor, conversation): |
| 14 | if model_type == "paligemma": |
| 15 | return conversation |
| 16 | |
| 17 | if "chat_template" in processor.__dict__.keys(): |
| 18 | prompt = processor.apply_chat_template( |
| 19 | conversation, |
| 20 | tokenize=False, |
| 21 | add_generation_prompt=False, |
| 22 | ) |
| 23 | elif "tokenizer" in processor.__dict__.keys(): |
| 24 | prompt = processor.tokenizer.apply_chat_template( |
| 25 | conversation, |
| 26 | tokenize=False, |
| 27 | add_generation_prompt=False, |
| 28 | ) |
| 29 | |
| 30 | return prompt |
| 31 | |
| 32 | |
| 33 | class Dataset: |
| 34 | def __init__( |
| 35 | self, |
| 36 | hf_dataset, |
| 37 | config, |
| 38 | processor, |
| 39 | image_processor=None, |
| 40 | take=None, |
| 41 | split=None, |
| 42 | image_resize_shape=None, |
| 43 | ): |
| 44 | if split is not None: |
| 45 | self.dataset = hf_dataset[split] |
| 46 | else: |
| 47 | self.dataset = hf_dataset |
| 48 | if take is not None: |
| 49 | self.dataset = self.dataset.take(take) |
| 50 | self.processor = processor |
| 51 | self.config = config |
| 52 | self.image_processor = image_processor |
| 53 | self.image_resize_shape = image_resize_shape |
| 54 | |
| 55 | def __len__(self): |
| 56 | return len(self.dataset) |
| 57 | |
| 58 | def __getitem__(self, idx): |
| 59 | from mlx_vlm.utils import prepare_inputs |
| 60 | |
| 61 | item = self.dataset[idx] |
| 62 | |
| 63 | images = item["images"] |
| 64 | conversations = item["messages"] |
| 65 | prompts = [] |
| 66 | |
| 67 | if isinstance(conversations, list) and isinstance(conversations[0], list): |
| 68 | for conversation in conversations: |
| 69 | if self.config["model_type"] == "pixtral": |
| 70 | conversation = [json.loads(i) for i in conversation] |
| 71 | if len(conversations) > 1: |
| 72 | warnings.warn( |
| 73 | "Pixtral batch processing is not supported yet. Set batch size to 1." |
| 74 | ) |
| 75 | |
| 76 | prompt = get_prompt( |
| 77 | self.config["model_type"], self.processor, conversation |
| 78 | ) |
| 79 | prompts.append(prompt) |
| 80 | |
| 81 | else: |
| 82 | if self.config["model_type"] == "pixtral": |
| 83 | conversations = [json.loads(i) for i in conversations] |
| 84 | prompt = get_prompt( |
| 85 | self.config["model_type"], self.processor, conversations |
| 86 | ) |
| 87 | prompts.append(prompt) |
| 88 | |
| 89 | image_token_index = self.config["image_token_index"] |
| 90 | |
| 91 | inputs = prepare_inputs( |
| 92 | self.image_processor, |
| 93 | self.processor, |
| 94 | images, |
| 95 | prompts, |
| 96 | image_token_index, |
| 97 | self.image_resize_shape, |
| 98 | ) |
| 99 | input_ids, pixel_values, mask = inputs[:3] |
| 100 | kwargs = { |
| 101 | k: v |
| 102 | for k, v in zip( |
| 103 | [ |
| 104 | "image_grid_thw", |
| 105 | "image_sizes", |
| 106 | "aspect_ratio_ids", |
| 107 | "aspect_ratio_mask", |
| 108 | "cross_attention_mask", |
| 109 | ], |
| 110 | inputs[3:], |
| 111 | ) |
| 112 | } |
| 113 | if mask is None: |
| 114 | mask = mx.ones_like(input_ids) |
| 115 | |
| 116 | return { |
| 117 | "pixel_values": pixel_values, |
| 118 | "input_ids": input_ids, |
| 119 | "attention_mask": mask, |
| 120 | **kwargs, |
| 121 | } |
| 122 | |
| 123 | |
| 124 | def grad_checkpoint(layer): |
| 125 | """ |
| 126 | Update all instances of type(layer) to use gradient checkpointing. |
| 127 | """ |
| 128 | fn = type(layer).__call__ |
| 129 | |
| 130 | def checkpointed_fn(model, *args, **kwargs): |
| 131 | def inner_fn(params, *args, **kwargs): |
| 132 | model.update(params) |
| 133 | return fn(model, *args, **kwargs) |
| 134 | |
| 135 | return mx.checkpoint(inner_fn)(model.trainable_parameters(), *args, **kwargs) |
| 136 | |
| 137 | type(layer).__call__ = checkpointed_fn |
| 138 | |
| 139 | |
| 140 | @dataclass |
| 141 | class TrainingArgs: |
| 142 | batch_size: int = field(default=4, metadata={"help": "Minibatch size."}) |
| 143 | iters: int = field(default=100, metadata={"help": "Iterations to train for."}) |
| 144 | val_batches: int = field( |
| 145 | default=25, |
| 146 | metadata={ |
| 147 | "help": "Number of validation batches, -1 uses the entire validation set." |
| 148 | }, |
| 149 | ) |
| 150 | steps_per_report: int = field( |
| 151 | default=10, |
| 152 | metadata={"help": "Number of training steps between loss reporting."}, |
| 153 | ) |
| 154 | steps_per_eval: int = field( |
| 155 | default=200, metadata={"help": "Number of training steps between validations."} |
| 156 | ) |
| 157 | steps_per_save: int = field( |
| 158 | default=100, metadata={"help": "Save the model every number steps"} |
| 159 | ) |
| 160 | max_seq_length: int = field( |
| 161 | default=2048, metadata={"help": "Maximum sequence length."} |
| 162 | ) |
| 163 | adapter_file: str = field( |
| 164 | default="adapters.safetensors", |
| 165 | metadata={"help": "Save/load path for the trained adapter weights."}, |
| 166 | ) |
| 167 | grad_checkpoint: bool = field( |
| 168 | default=False, |
| 169 | metadata={"help": "Use gradient checkpointing to reduce memory use."}, |
| 170 | ) |
| 171 | |
| 172 | |
| 173 | def default_loss(model, inputs, targets, lengths): |
| 174 | logits = model(inputs) |
| 175 | logits = logits.astype(mx.float32) |
| 176 | |
| 177 | length_mask = mx.arange(inputs.shape[1])[None, :] < lengths[:, None] |
| 178 | |
| 179 | ce = nn.losses.cross_entropy(logits, targets) * length_mask |
| 180 | ntoks = length_mask.sum() |
| 181 | ce = ce.sum() / ntoks |
| 182 | |
| 183 | return ce, ntoks |
| 184 | |
| 185 | |
| 186 | class Trainer: |
| 187 | def __init__( |
| 188 | self, |
| 189 | model, |
| 190 | optimizer, |
| 191 | train_on_completions=False, |
| 192 | assistant_id=77091, |
| 193 | clip_gradients=None, |
| 194 | ): |
| 195 | self.model = model |
| 196 | self.optimizer = optimizer |
| 197 | self.train_on_completions = train_on_completions |
| 198 | self.assistant_id = assistant_id |
| 199 | self.clip_gradients = clip_gradients |
| 200 | |
| 201 | def loss_fn(self, model, batch): |
| 202 | pixel_values = batch["pixel_values"] |
| 203 | input_ids = batch["input_ids"] |
| 204 | attention_mask = batch["attention_mask"] |
| 205 | lengths = mx.sum(attention_mask, axis=1) |
| 206 | labels = input_ids[:, 1:] |
| 207 | |
| 208 | batch_size, seq_length = input_ids.shape |
| 209 | |
| 210 | if self.train_on_completions: |
| 211 | weight_mask = mx.ones_like(attention_mask) |
| 212 | |
| 213 | assistant_response_index = np.where(input_ids == self.assistant_id)[1] |
| 214 | range_matrix = mx.repeat( |
| 215 | mx.expand_dims(mx.arange(seq_length), 0), batch_size, axis=0 |
| 216 | ) |
| 217 | assistant_mask = range_matrix <= mx.array(assistant_response_index).reshape( |
| 218 | -1, 1 |
| 219 | ) |
| 220 | # Apply the mask to weight_mask |
| 221 | weight_mask = mx.where( |
| 222 | assistant_mask, mx.zeros_like(weight_mask), weight_mask |
| 223 | )[:, 1:] |
| 224 | else: |
| 225 | weight_mask = None |
| 226 | |
| 227 | input_ids = input_ids[:, :-1] |
| 228 | |
| 229 | kwargs = {} |
| 230 | image_keys = [ |
| 231 | "image_grid_thw", |
| 232 | "image_sizes", |
| 233 | "aspect_ratio_ids", |
| 234 | "aspect_ratio_mask", |
| 235 | "cross_attention_mask", |
| 236 | ] |
| 237 | if any(key in batch for key in image_keys): |
| 238 | kwargs = {key: batch[key] for key in image_keys if key in batch} |
| 239 | |
| 240 | # Forward pass |
| 241 | outputs = model(input_ids, pixel_values, attention_mask, **kwargs) |
| 242 | |
| 243 | # Cast to float32 |
| 244 | logits = outputs.logits.astype(mx.float32) |
| 245 | |
| 246 | # Ensure logits and labels have the same sequence length |
| 247 | def align_logits_with_labels(logits, labels): |
| 248 | if logits.shape[1] < labels.shape[1]: |
| 249 | pad_length = labels.shape[1] - logits.shape[1] |
| 250 | pad_width = ((0, 0), (0, pad_length), (0, 0)) |
| 251 | return mx.pad(logits, pad_width, mode="constant", constant_values=-100) |
| 252 | elif logits.shape[1] > labels.shape[1]: |
| 253 | return logits[:, -labels.shape[1] :, :] |
| 254 | return logits |
| 255 | |
| 256 | logits = align_logits_with_labels(logits, labels) |
| 257 | |
| 258 | length_mask = mx.arange(input_ids.shape[1])[None, :] < lengths[:, None] |
| 259 | |
| 260 | # Compute loss only on non-padded tokens |
| 261 | ce = ( |
| 262 | nn.losses.cross_entropy( |
| 263 | logits, |
| 264 | labels, |
| 265 | weights=weight_mask, |
| 266 | ) |
| 267 | * length_mask |
| 268 | ) |
| 269 | ntoks = length_mask.sum() |
| 270 | ce = ce.sum() / ntoks |
| 271 | |
| 272 | return ce |
| 273 | |
| 274 | def train_step(self, batch): |
| 275 | loss_and_grad_fn = nn.value_and_grad(self.model, self.loss_fn) |
| 276 | loss, grads = loss_and_grad_fn(self.model, batch) |
| 277 | |
| 278 | # Add gradient clipping |
| 279 | if self.clip_gradients is not None: |
| 280 | grads = tree_map( |
| 281 | lambda g: mx.clip(g, -self.clip_gradients, self.clip_gradients), grads |
| 282 | ) |
| 283 | |
| 284 | self.optimizer.update(self.model, grads) |
| 285 | |
| 286 | return loss |
| 287 | |
| 288 | @mx.compile |
| 289 | def train_epoch(self, dataloader): |
| 290 | total_loss = 0 |
| 291 | for batch in dataloader: |
| 292 | loss = self.train_step(batch) |
| 293 | mx.eval(self.model, self.optimizer.state) |
| 294 | total_loss += loss |
| 295 | return total_loss / len(dataloader) |
| 296 | |
| 297 | |
| 298 | def save_adapter( |
| 299 | model: nn.Module, |
| 300 | adapter_file: Union[str, Path], |
| 301 | ): |
| 302 | path = Path(adapter_file) |
| 303 | if hasattr(model.config, "lora"): |
| 304 | with open(path.parent / "adapter_config.json", "w") as f: |
| 305 | json.dump(model.config.lora, f) |
| 306 | flattened_tree = tree_flatten(model.trainable_parameters()) |
| 307 | mx.save_safetensors(str(adapter_file), dict(flattened_tree)) |