Upload 29 files
Browse filesproject files uploaded
- .gitattributes +2 -0
- src/assets/cat.png +3 -0
- src/assets/graph.png +0 -0
- src/assets/horse.png +3 -0
- src/data/__init__.py +0 -0
- src/data/__pycache__/__init__.cpython-312.pyc +0 -0
- src/data/__pycache__/custom_transforms.cpython-312.pyc +0 -0
- src/data/__pycache__/processors.cpython-312.pyc +0 -0
- src/data/advanced_datasets.py +237 -0
- src/data/collators.py +71 -0
- src/data/custom_transforms.py +121 -0
- src/data/data_utils.py +67 -0
- src/data/datasets.py +150 -0
- src/data/processors.py +42 -0
- src/generate.py +100 -0
- src/models/README.md +23 -0
- src/models/__init__.py +0 -0
- src/models/__pycache__/__init__.cpython-312.pyc +0 -0
- src/models/__pycache__/config.cpython-312.pyc +0 -0
- src/models/__pycache__/language_model.cpython-312.pyc +0 -0
- src/models/__pycache__/modality_projector.cpython-312.pyc +0 -0
- src/models/__pycache__/utils.cpython-312.pyc +0 -0
- src/models/__pycache__/vision_language_model.cpython-312.pyc +0 -0
- src/models/__pycache__/vision_transformer.cpython-312.pyc +0 -0
- src/models/config.py +87 -0
- src/models/language_model.py +681 -0
- src/models/modality_projector.py +46 -0
- src/models/utils.py +51 -0
- src/models/vision_language_model.py +310 -0
- src/models/vision_transformer.py +251 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
src/assets/cat.png filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
src/assets/horse.png filter=lfs diff=lfs merge=lfs -text
|
src/assets/cat.png
ADDED
|
Git LFS Details
|
src/assets/graph.png
ADDED
|
src/assets/horse.png
ADDED
|
Git LFS Details
|
src/data/__init__.py
ADDED
|
File without changes
|
src/data/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (156 Bytes). View file
|
|
|
src/data/__pycache__/custom_transforms.cpython-312.pyc
ADDED
|
Binary file (6.86 kB). View file
|
|
|
src/data/__pycache__/processors.cpython-312.pyc
ADDED
|
Binary file (2.23 kB). View file
|
|
|
src/data/advanced_datasets.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch.utils.data import IterableDataset, get_worker_info
|
| 3 |
+
import threading
|
| 4 |
+
from queue import Queue
|
| 5 |
+
from typing import Iterator
|
| 6 |
+
import itertools
|
| 7 |
+
import random
|
| 8 |
+
|
| 9 |
+
random.seed(42) # Set the random seed to the meaning of life for good luck
|
| 10 |
+
|
| 11 |
+
class ConstantLengthDataset(IterableDataset):
|
| 12 |
+
def __init__(
|
| 13 |
+
self,
|
| 14 |
+
dataset,
|
| 15 |
+
infinite: bool = False,
|
| 16 |
+
max_sample_length: int = 1024,
|
| 17 |
+
seq_length: int = 1024,
|
| 18 |
+
num_of_sequences: int = 1024,
|
| 19 |
+
queue_size: int = 2,
|
| 20 |
+
max_images_per_example: int = 4,
|
| 21 |
+
max_images_per_knapsack: int = 18,
|
| 22 |
+
):
|
| 23 |
+
self.dataset = dataset
|
| 24 |
+
self.max_sample_length = max_sample_length
|
| 25 |
+
self.seq_length = seq_length
|
| 26 |
+
self.max_length = seq_length * num_of_sequences
|
| 27 |
+
self.epoch = 0 # only advanced when infinite=True
|
| 28 |
+
self.infinite = infinite
|
| 29 |
+
self.queue_size = max(queue_size, 1)
|
| 30 |
+
self.max_images_per_example = max_images_per_example
|
| 31 |
+
self.max_images_per_knapsack = max_images_per_knapsack
|
| 32 |
+
self._sentinel = object()
|
| 33 |
+
self._average_length_per_sample = (
|
| 34 |
+
self.dataset.mp_image_token_length + 198
|
| 35 |
+
) # 198 is the average tokens for the cauldron dataset
|
| 36 |
+
|
| 37 |
+
def __len__(self):
|
| 38 |
+
return int(
|
| 39 |
+
len(self.dataset) * self._average_length_per_sample / self.seq_length
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
def __iter__(self) -> Iterator[dict]:
|
| 43 |
+
"""
|
| 44 |
+
Returns an iterator over the dataset that yields fixed-length sequences for training.
|
| 45 |
+
|
| 46 |
+
The iterator uses a producer-consumer pattern with a background thread to efficiently
|
| 47 |
+
pre-fetch and buffer samples. The producer thread continuously reads from the base
|
| 48 |
+
dataset and fills a queue, while the main thread consumes from the queue.
|
| 49 |
+
|
| 50 |
+
The dataset is automatically sharded across workers when using num_workers > 1.
|
| 51 |
+
|
| 52 |
+
Returns:
|
| 53 |
+
Iterator[dict]: An iterator that yields training samples with the following structure:
|
| 54 |
+
- input_ids: Tensor of token ids of shape (seq_length,)
|
| 55 |
+
- labels: Tensor of labels of shape (seq_length,)
|
| 56 |
+
- attention_mask: Tensor of attention mask of shape (seq_length,)
|
| 57 |
+
- images: List of processed image tensors
|
| 58 |
+
"""
|
| 59 |
+
worker_info = get_worker_info()
|
| 60 |
+
worker_id = worker_info.id if worker_info else 0
|
| 61 |
+
num_workers = worker_info.num_workers if worker_info else 1
|
| 62 |
+
|
| 63 |
+
def make_base_iterator():
|
| 64 |
+
"""Return a (sharded) iterator over the underlying dataset."""
|
| 65 |
+
if not hasattr(self.dataset.dataset, "__len__"):
|
| 66 |
+
return self.dataset.iter_for_worker() # with iterable datasets, each worker gets different shards
|
| 67 |
+
|
| 68 |
+
all_indices = range(len(self.dataset))
|
| 69 |
+
|
| 70 |
+
# Shard the *indices* first, before any data is fetched.
|
| 71 |
+
if num_workers > 1:
|
| 72 |
+
worker_indices = itertools.islice(
|
| 73 |
+
all_indices, worker_id, None, num_workers
|
| 74 |
+
)
|
| 75 |
+
else:
|
| 76 |
+
worker_indices = all_indices
|
| 77 |
+
|
| 78 |
+
# Create an iterator that only calls __getitem__ for the assigned indices.
|
| 79 |
+
def sharded_item_iterator():
|
| 80 |
+
for idx in worker_indices:
|
| 81 |
+
yield self.dataset[idx]
|
| 82 |
+
|
| 83 |
+
return sharded_item_iterator()
|
| 84 |
+
|
| 85 |
+
queue: Queue = Queue(maxsize=self.queue_size)
|
| 86 |
+
|
| 87 |
+
producer = threading.Thread(
|
| 88 |
+
target=self._producer, args=(make_base_iterator, queue), daemon=True
|
| 89 |
+
)
|
| 90 |
+
producer.start()
|
| 91 |
+
|
| 92 |
+
while True:
|
| 93 |
+
batch_of_batches = queue.get()
|
| 94 |
+
if batch_of_batches is self._sentinel:
|
| 95 |
+
break
|
| 96 |
+
for batch in batch_of_batches:
|
| 97 |
+
yield batch
|
| 98 |
+
|
| 99 |
+
def _producer(
|
| 100 |
+
self,
|
| 101 |
+
make_iterator, # a zero-arg lambda that returns a fresh (possibly sharded) iterator
|
| 102 |
+
queue: Queue,
|
| 103 |
+
):
|
| 104 |
+
"""Runs in a separate daemon thread and keeps `queue` full."""
|
| 105 |
+
iterator = make_iterator()
|
| 106 |
+
more_examples = True
|
| 107 |
+
|
| 108 |
+
while more_examples:
|
| 109 |
+
# ------------- 1) pull raw samples until we have enough -------- #
|
| 110 |
+
buffer, buffer_len = [], 0
|
| 111 |
+
while buffer_len < self.max_length:
|
| 112 |
+
try:
|
| 113 |
+
sample = next(iterator)
|
| 114 |
+
except StopIteration:
|
| 115 |
+
if self.infinite:
|
| 116 |
+
iterator = make_iterator()
|
| 117 |
+
self.epoch += 1
|
| 118 |
+
print(f"Epoch {self.epoch} finished, restarting iterator")
|
| 119 |
+
continue
|
| 120 |
+
else:
|
| 121 |
+
more_examples = False
|
| 122 |
+
break
|
| 123 |
+
|
| 124 |
+
if sample is None: # Ratings filtered out the sample
|
| 125 |
+
continue
|
| 126 |
+
|
| 127 |
+
if len(sample["input_ids"]) >= self.max_sample_length:
|
| 128 |
+
continue # skip overly long samples
|
| 129 |
+
if len(sample["images"]) > self.max_images_per_example:
|
| 130 |
+
continue # skip samples that exceed the image constraint
|
| 131 |
+
|
| 132 |
+
sample["input_ids"] = torch.cat(
|
| 133 |
+
[
|
| 134 |
+
sample["input_ids"],
|
| 135 |
+
torch.tensor([self.dataset.tokenizer.pad_token_id]),
|
| 136 |
+
]
|
| 137 |
+
)
|
| 138 |
+
sample["attention_mask"] = torch.cat(
|
| 139 |
+
[sample["attention_mask"], torch.tensor([0])]
|
| 140 |
+
)
|
| 141 |
+
sample["labels"] = torch.cat([sample["labels"], torch.tensor([-100])])
|
| 142 |
+
|
| 143 |
+
buffer.append(sample)
|
| 144 |
+
buffer_len += len(sample["input_ids"])
|
| 145 |
+
|
| 146 |
+
if not buffer:
|
| 147 |
+
break # nothing left and not infinite
|
| 148 |
+
|
| 149 |
+
# ------------- 2) run greedy knapsack & pack groups ------------ #
|
| 150 |
+
groups = self._balanced_greedy_knapsack(
|
| 151 |
+
buffer,
|
| 152 |
+
self.seq_length,
|
| 153 |
+
delta=5,
|
| 154 |
+
max_images_per_knapsack=self.max_images_per_knapsack,
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
packed_group = []
|
| 158 |
+
for g in groups:
|
| 159 |
+
packed = self._pack_one_group(g, buffer, self.seq_length)
|
| 160 |
+
packed_group.append({
|
| 161 |
+
"input_ids": packed[0],
|
| 162 |
+
"labels": packed[1],
|
| 163 |
+
"attention_mask": packed[2],
|
| 164 |
+
"images": packed[3],
|
| 165 |
+
})
|
| 166 |
+
|
| 167 |
+
if packed_group:
|
| 168 |
+
queue.put(packed_group)
|
| 169 |
+
|
| 170 |
+
# finished → unblock consumer
|
| 171 |
+
queue.put(self._sentinel)
|
| 172 |
+
|
| 173 |
+
def _balanced_greedy_knapsack(
|
| 174 |
+
self, buffer, L, delta=0, max_images_per_knapsack=None
|
| 175 |
+
):
|
| 176 |
+
# Extract lengths and image counts from buffer
|
| 177 |
+
lengths = [len(x["input_ids"]) for x in buffer]
|
| 178 |
+
image_counts = [len(x["images"]) for x in buffer]
|
| 179 |
+
|
| 180 |
+
# keep the position while sorting
|
| 181 |
+
items = sorted(
|
| 182 |
+
enumerate(zip(lengths, image_counts)), key=lambda x: x[1][0], reverse=True
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
min_knapsacks = (sum(lengths) + L - 1) // L + delta
|
| 186 |
+
knapsack_load = [0] * min_knapsacks
|
| 187 |
+
knapsack_image_counts = [0] * min_knapsacks
|
| 188 |
+
knapsack_groups = [[] for _ in range(min_knapsacks)]
|
| 189 |
+
|
| 190 |
+
for idx, (item_len, item_image_count) in items:
|
| 191 |
+
# Find a suitable knapsack that satisfies both length and image count constraints
|
| 192 |
+
suitable_knapsack = None
|
| 193 |
+
|
| 194 |
+
# First try to find a knapsack that can fit both constraints
|
| 195 |
+
for ks_id in sorted(
|
| 196 |
+
range(len(knapsack_load)), key=knapsack_load.__getitem__
|
| 197 |
+
):
|
| 198 |
+
length_fits = knapsack_load[ks_id] + item_len <= L
|
| 199 |
+
image_fits = (
|
| 200 |
+
max_images_per_knapsack is None
|
| 201 |
+
or knapsack_image_counts[ks_id] + item_image_count
|
| 202 |
+
<= max_images_per_knapsack
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
if length_fits and image_fits:
|
| 206 |
+
suitable_knapsack = ks_id
|
| 207 |
+
break
|
| 208 |
+
|
| 209 |
+
# If no existing knapsack can fit, create a new one
|
| 210 |
+
if suitable_knapsack is None:
|
| 211 |
+
suitable_knapsack = len(knapsack_load)
|
| 212 |
+
knapsack_load.append(0)
|
| 213 |
+
knapsack_image_counts.append(0)
|
| 214 |
+
knapsack_groups.append([])
|
| 215 |
+
|
| 216 |
+
knapsack_groups[suitable_knapsack].append(idx)
|
| 217 |
+
knapsack_load[suitable_knapsack] += item_len
|
| 218 |
+
knapsack_image_counts[suitable_knapsack] += item_image_count
|
| 219 |
+
|
| 220 |
+
# remove the completely empty bags that the +delta heuristic created
|
| 221 |
+
random.shuffle(knapsack_groups) # Knapsacks are semi-ordered after packing, thanks Luis for noticing!
|
| 222 |
+
return [g for g in knapsack_groups if g]
|
| 223 |
+
|
| 224 |
+
def _pack_one_group(self, group_indices, batch, max_len):
|
| 225 |
+
ids, lbl, am, ims = [], [], [], []
|
| 226 |
+
|
| 227 |
+
for i in group_indices:
|
| 228 |
+
ids.extend(batch[i]["input_ids"])
|
| 229 |
+
lbl.extend(batch[i]["labels"])
|
| 230 |
+
am.extend(batch[i]["attention_mask"])
|
| 231 |
+
ims.extend(batch[i]["images"])
|
| 232 |
+
|
| 233 |
+
# safety: assert we never overflow
|
| 234 |
+
if len(ids) > max_len:
|
| 235 |
+
raise ValueError(f"Packed length {len(ids)} > max_len {max_len}")
|
| 236 |
+
|
| 237 |
+
return torch.stack(ids), torch.stack(lbl), torch.stack(am), ims
|
src/data/collators.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class BaseCollator(object):
|
| 5 |
+
def __init__(self, tokenizer):
|
| 6 |
+
self.tokenizer = tokenizer
|
| 7 |
+
|
| 8 |
+
def _pad_batch(self, batch, max_length):
|
| 9 |
+
batch["input_ids"] = [torch.nn.functional.pad(ids, (max_length - len(ids), 0), value=self.tokenizer.pad_token_id) for ids in batch["input_ids"]]
|
| 10 |
+
batch["labels"] = [torch.nn.functional.pad(labels, (max_length - len(labels), 0), value=self.tokenizer.pad_token_id) for labels in batch["labels"]]
|
| 11 |
+
batch["attention_mask"] = [torch.nn.functional.pad(attention_mask, (max_length - len(attention_mask), 0), value=0) for attention_mask in batch["attention_mask"]]
|
| 12 |
+
|
| 13 |
+
def prepare_batch(self, batch, max_length=None):
|
| 14 |
+
# 1) Handle empty
|
| 15 |
+
if not batch:
|
| 16 |
+
return {"input_ids": [], "labels": [], "attention_mask": [], "images": []}
|
| 17 |
+
|
| 18 |
+
# 2) Drop None rows
|
| 19 |
+
batch = [s for s in batch if s is not None]
|
| 20 |
+
if not batch:
|
| 21 |
+
return {"input_ids": [], "labels": [], "attention_mask": [], "images": []}
|
| 22 |
+
|
| 23 |
+
# batch is a list of dicts, each containing "input_ids", "attention_mask", "labels", "images"
|
| 24 |
+
# let's convert it to a dict of lists of tensors
|
| 25 |
+
batch = {k: [item[k] for item in batch] for k in batch[0]}
|
| 26 |
+
|
| 27 |
+
if max_length is not None:
|
| 28 |
+
batch = self._discard_samples_that_are_too_long(batch, max_length)
|
| 29 |
+
|
| 30 |
+
if len(batch["input_ids"]) == 0:
|
| 31 |
+
return batch
|
| 32 |
+
|
| 33 |
+
# Pad samples to max length
|
| 34 |
+
if max_length is not None:
|
| 35 |
+
max_len = max_length
|
| 36 |
+
else:
|
| 37 |
+
max_len = max(map(len, batch["input_ids"]))
|
| 38 |
+
self._pad_batch(batch, max_len) # dictionaries in Python are mutable and passed by reference
|
| 39 |
+
|
| 40 |
+
return {
|
| 41 |
+
"input_ids": torch.stack(batch["input_ids"]),
|
| 42 |
+
"attention_mask": torch.stack(batch["attention_mask"]),
|
| 43 |
+
"images": batch["images"],
|
| 44 |
+
"labels": torch.stack(batch["labels"]),
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
def _discard_samples_that_are_too_long(self, batch, max_length):
|
| 48 |
+
filtered = [
|
| 49 |
+
(ids, label, attn, img)
|
| 50 |
+
for ids, label, attn, img in zip(batch["input_ids"], batch["labels"], batch["attention_mask"], batch["images"])
|
| 51 |
+
if len(ids) <= max_length
|
| 52 |
+
]
|
| 53 |
+
if not filtered:
|
| 54 |
+
return {"input_ids": [], "labels": [], "attention_mask": [], "images": []}
|
| 55 |
+
batch_token_ids, batch_labels, batch_attentions, batch_images = zip(*filtered)
|
| 56 |
+
return {"input_ids": list(batch_token_ids), "labels": list(batch_labels), "attention_mask": list(batch_attentions), "images": list(batch_images)}
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class VQACollator(BaseCollator): # Visual Question Answering Collator
|
| 60 |
+
def __init__(self, tokenizer, max_length):
|
| 61 |
+
self.max_length = max_length
|
| 62 |
+
super().__init__(tokenizer)
|
| 63 |
+
|
| 64 |
+
def _pad_batch(self, batch, max_length): # Reimplementing to use -100 as the pad value for labels, so that it's ignored by the loss
|
| 65 |
+
batch["input_ids"] = [torch.nn.functional.pad(ids, (max_length - len(ids), 0), value=self.tokenizer.pad_token_id) for ids in batch["input_ids"]]
|
| 66 |
+
batch["labels"] = [torch.nn.functional.pad(labels, (max_length - len(labels), 0), value=-100) for labels in batch["labels"]]
|
| 67 |
+
batch["attention_mask"] = [torch.nn.functional.pad(attention_mask, (max_length - len(attention_mask), 0), value=0) for attention_mask in batch["attention_mask"]]
|
| 68 |
+
|
| 69 |
+
def __call__(self, batch):
|
| 70 |
+
batch = self.prepare_batch(batch, max_length=self.max_length)
|
| 71 |
+
return batch
|
src/data/custom_transforms.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import torch
|
| 3 |
+
from torchvision.transforms.functional import resize, InterpolationMode
|
| 4 |
+
from einops import rearrange
|
| 5 |
+
from typing import Tuple, Union
|
| 6 |
+
from PIL import Image
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class DynamicResize(torch.nn.Module):
|
| 10 |
+
"""
|
| 11 |
+
Resize so that:
|
| 12 |
+
* the longer side ≤ `max_side_len` **and** is divisible by `patch_size`
|
| 13 |
+
* the shorter side keeps aspect ratio and is also divisible by `patch_size`
|
| 14 |
+
Optionally forbids up-scaling.
|
| 15 |
+
|
| 16 |
+
Works on PIL Images, (C, H, W) tensors, or (B, C, H, W) tensors.
|
| 17 |
+
Returns the same type it receives.
|
| 18 |
+
"""
|
| 19 |
+
def __init__(
|
| 20 |
+
self,
|
| 21 |
+
patch_size: int,
|
| 22 |
+
max_side_len: int,
|
| 23 |
+
resize_to_max_side_len: bool = False,
|
| 24 |
+
interpolation: InterpolationMode = InterpolationMode.BICUBIC,
|
| 25 |
+
) -> None:
|
| 26 |
+
super().__init__()
|
| 27 |
+
self.p = int(patch_size)
|
| 28 |
+
self.m = int(max_side_len)
|
| 29 |
+
self.interpolation = interpolation
|
| 30 |
+
print(f"Resize to max side len: {resize_to_max_side_len}")
|
| 31 |
+
self.resize_to_max_side_len = resize_to_max_side_len
|
| 32 |
+
|
| 33 |
+
# ------------------------------------------------------------
|
| 34 |
+
def _get_new_hw(self, h: int, w: int) -> Tuple[int, int]:
|
| 35 |
+
"""Compute target (h, w) divisible by patch_size."""
|
| 36 |
+
long, short = (w, h) if w >= h else (h, w)
|
| 37 |
+
|
| 38 |
+
# 1) upscale long side
|
| 39 |
+
target_long = self.m if self.resize_to_max_side_len else min(self.m, math.ceil(long / self.p) * self.p)
|
| 40 |
+
|
| 41 |
+
# 2) scale factor
|
| 42 |
+
scale = target_long / long
|
| 43 |
+
|
| 44 |
+
# 3) compute short side with ceil → never undershoot
|
| 45 |
+
target_short = math.ceil(short * scale / self.p) * self.p
|
| 46 |
+
target_short = max(target_short, self.p) # just in case
|
| 47 |
+
|
| 48 |
+
return (target_short, target_long) if w >= h else (target_long, target_short)
|
| 49 |
+
|
| 50 |
+
# ------------------------------------------------------------
|
| 51 |
+
def forward(self, img: Union[Image.Image, torch.Tensor]):
|
| 52 |
+
if isinstance(img, Image.Image):
|
| 53 |
+
w, h = img.size
|
| 54 |
+
new_h, new_w = self._get_new_hw(h, w)
|
| 55 |
+
return resize(img, [new_h, new_w], interpolation=self.interpolation)
|
| 56 |
+
|
| 57 |
+
if not torch.is_tensor(img):
|
| 58 |
+
raise TypeError(
|
| 59 |
+
"DynamicResize expects a PIL Image or a torch.Tensor; "
|
| 60 |
+
f"got {type(img)}"
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
# tensor path ---------------------------------------------------------
|
| 64 |
+
batched = img.ndim == 4
|
| 65 |
+
if img.ndim not in (3, 4):
|
| 66 |
+
raise ValueError(
|
| 67 |
+
"Tensor input must have shape (C,H,W) or (B,C,H,W); "
|
| 68 |
+
f"got {img.shape}"
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
# operate batch-wise
|
| 72 |
+
imgs = img if batched else img.unsqueeze(0)
|
| 73 |
+
_, _, h, w = imgs.shape
|
| 74 |
+
new_h, new_w = self._get_new_hw(h, w)
|
| 75 |
+
out = resize(imgs, [new_h, new_w], interpolation=self.interpolation)
|
| 76 |
+
|
| 77 |
+
return out if batched else out.squeeze(0)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class SplitImage(torch.nn.Module):
|
| 81 |
+
"""Split (B, C, H, W) image tensor into square patches.
|
| 82 |
+
|
| 83 |
+
Returns:
|
| 84 |
+
patches: (B·n_h·n_w, C, patch_size, patch_size)
|
| 85 |
+
grid: (n_h, n_w) - number of patches along H and W
|
| 86 |
+
"""
|
| 87 |
+
def __init__(self, patch_size: int) -> None:
|
| 88 |
+
super().__init__()
|
| 89 |
+
self.p = patch_size
|
| 90 |
+
|
| 91 |
+
def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, Tuple[int, int]]:
|
| 92 |
+
if x.ndim == 3: # add batch dim if missing
|
| 93 |
+
x = x.unsqueeze(0)
|
| 94 |
+
|
| 95 |
+
b, c, h, w = x.shape
|
| 96 |
+
if h % self.p or w % self.p:
|
| 97 |
+
raise ValueError(f'Image size {(h,w)} not divisible by patch_size {self.p}')
|
| 98 |
+
|
| 99 |
+
n_h, n_w = h // self.p, w // self.p
|
| 100 |
+
patches = rearrange(x, 'b c (nh ph) (nw pw) -> (b nh nw) c ph pw',
|
| 101 |
+
ph=self.p, pw=self.p)
|
| 102 |
+
return patches, (n_h, n_w)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class GlobalAndSplitImages(torch.nn.Module):
|
| 106 |
+
def __init__(self, patch_size: int):
|
| 107 |
+
super().__init__()
|
| 108 |
+
self.p = patch_size
|
| 109 |
+
self.splitter = SplitImage(patch_size)
|
| 110 |
+
|
| 111 |
+
def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, Tuple[int, int]]:
|
| 112 |
+
if x.ndim == 3:
|
| 113 |
+
x = x.unsqueeze(0)
|
| 114 |
+
|
| 115 |
+
patches, grid = self.splitter(x)
|
| 116 |
+
|
| 117 |
+
if grid == (1, 1):
|
| 118 |
+
return patches, grid # Dont add global patch if there is only one patch
|
| 119 |
+
|
| 120 |
+
global_patch = resize(x, [self.p, self.p])
|
| 121 |
+
return torch.cat([global_patch, patches], dim=0), grid
|
src/data/data_utils.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.distributed as dist
|
| 3 |
+
from collections.abc import Iterator
|
| 4 |
+
|
| 5 |
+
def _is_batch_valid(batch):
|
| 6 |
+
"""
|
| 7 |
+
Check if a batch is valid for training/evaluation.
|
| 8 |
+
A valid batch must have input_ids and at least one image.
|
| 9 |
+
"""
|
| 10 |
+
if not batch:
|
| 11 |
+
return False
|
| 12 |
+
# The collator can return a batch with empty lists
|
| 13 |
+
if len(batch['input_ids']) == 0:
|
| 14 |
+
return False
|
| 15 |
+
|
| 16 |
+
if len(batch['images']) == 0:
|
| 17 |
+
return False
|
| 18 |
+
|
| 19 |
+
# `images` is a list of lists of tensors. Check that at least one image is not None.
|
| 20 |
+
if len([img for sublist in batch['images'] for img in sublist]) == 0:
|
| 21 |
+
# During training, not having images creates gradients computed without all model parameters.
|
| 22 |
+
# This creates deadlocks in DDP.
|
| 23 |
+
return False
|
| 24 |
+
|
| 25 |
+
return True
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def synchronized_dataloader_step(train_loader, is_dist):
|
| 29 |
+
"""
|
| 30 |
+
Create a synchronized iterator that handles uneven data distribution in DDP.
|
| 31 |
+
All ranks will stop when the first rank runs out of data.
|
| 32 |
+
This happens because when packing a presharded dataset, a rank might have less groups than the others.
|
| 33 |
+
It also handles cases where a collator returns an empty/invalid batch on some ranks,
|
| 34 |
+
by ensuring all ranks skip the invalid batch and attempt to fetch a new one.
|
| 35 |
+
"""
|
| 36 |
+
if not is_dist:
|
| 37 |
+
# For single GPU, we don't need synchronization, just filter invalid batches.
|
| 38 |
+
for batch in train_loader:
|
| 39 |
+
if _is_batch_valid(batch):
|
| 40 |
+
yield batch
|
| 41 |
+
return
|
| 42 |
+
|
| 43 |
+
# For DDP, we need synchronization.
|
| 44 |
+
if isinstance(train_loader, Iterator):
|
| 45 |
+
train_iter = train_loader
|
| 46 |
+
else:
|
| 47 |
+
train_iter = iter(train_loader)
|
| 48 |
+
|
| 49 |
+
while True:
|
| 50 |
+
is_valid = False
|
| 51 |
+
try:
|
| 52 |
+
while not is_valid:
|
| 53 |
+
batch = next(train_iter)
|
| 54 |
+
is_valid = _is_batch_valid(batch)
|
| 55 |
+
has_data = torch.tensor(1, device=torch.cuda.current_device())
|
| 56 |
+
except StopIteration:
|
| 57 |
+
batch = None
|
| 58 |
+
has_data = torch.tensor(0, device=torch.cuda.current_device())
|
| 59 |
+
|
| 60 |
+
# We synchronize across all ranks. If any rank is out of data, all ranks stop.
|
| 61 |
+
dist.all_reduce(has_data, op=dist.ReduceOp.MIN)
|
| 62 |
+
|
| 63 |
+
if has_data.item() == 0:
|
| 64 |
+
# At least one rank is out of data. All ranks should stop.
|
| 65 |
+
break
|
| 66 |
+
yield batch
|
| 67 |
+
return None
|
src/data/datasets.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from PIL import Image
|
| 3 |
+
from torch.utils.data import Dataset
|
| 4 |
+
from data.processors import get_image_string
|
| 5 |
+
import logging
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class BaseDataset(Dataset):
|
| 9 |
+
def __init__(self, dataset, tokenizer, image_processor, mp_image_token_length, relevance_min_rating=1, image_correspondence_min_rating=1, visual_dependency_min_rating=1, formatting_min_rating=1):
|
| 10 |
+
self.dataset = dataset
|
| 11 |
+
self.tokenizer = tokenizer
|
| 12 |
+
self.image_processor = image_processor
|
| 13 |
+
self.mp_image_token_length = mp_image_token_length
|
| 14 |
+
self.relevance_min_rating = relevance_min_rating
|
| 15 |
+
self.image_correspondence_min_rating = image_correspondence_min_rating
|
| 16 |
+
self.visual_dependency_min_rating = visual_dependency_min_rating
|
| 17 |
+
self.formatting_min_rating = formatting_min_rating
|
| 18 |
+
self.prefix_len = self._get_prefix_len()
|
| 19 |
+
|
| 20 |
+
def __len__(self):
|
| 21 |
+
return len(self.dataset)
|
| 22 |
+
|
| 23 |
+
def _get_prefix_len(self):
|
| 24 |
+
random_string_5_letters = "xzyvd"
|
| 25 |
+
random_string_chat_templated = self.tokenizer.apply_chat_template([{"role": "assistant", "content": random_string_5_letters}], tokenize=False, add_special_tokens=False)
|
| 26 |
+
random_string_location = random_string_chat_templated.find(random_string_5_letters)
|
| 27 |
+
return len(self.tokenizer.encode(random_string_chat_templated[:random_string_location]))
|
| 28 |
+
|
| 29 |
+
def _get_messages(self, item, splitted_image_counts):
|
| 30 |
+
messages = []
|
| 31 |
+
for index, text in enumerate(item['texts']):
|
| 32 |
+
try:
|
| 33 |
+
if item.get('relevance_ratings') is not None and item['relevance_ratings'][index] is not None and item['relevance_ratings'][index] < self.relevance_min_rating:
|
| 34 |
+
continue
|
| 35 |
+
if item.get('image_correspondence_ratings') is not None and item['image_correspondence_ratings'][index] is not None and item['image_correspondence_ratings'][index] < self.image_correspondence_min_rating:
|
| 36 |
+
continue
|
| 37 |
+
if item.get('visual_dependency_ratings') is not None and item['visual_dependency_ratings'][index] is not None and item['visual_dependency_ratings'][index] < self.visual_dependency_min_rating:
|
| 38 |
+
continue
|
| 39 |
+
if item.get('formatting_ratings') is not None and item['formatting_ratings'][index] is not None and item['formatting_ratings'][index] < self.formatting_min_rating:
|
| 40 |
+
continue
|
| 41 |
+
except Exception as e:
|
| 42 |
+
logging.warning(f"Error processing item: {item}, index: {index}: {e}")
|
| 43 |
+
|
| 44 |
+
messages.append({"role": "user", "content": text['user']})
|
| 45 |
+
messages.append({"role": "assistant", "content": text['assistant']})
|
| 46 |
+
|
| 47 |
+
if len(messages) == 0:
|
| 48 |
+
return messages
|
| 49 |
+
|
| 50 |
+
# Safety check to ensure no image tokens are present in the text before adding them.
|
| 51 |
+
for msg in messages:
|
| 52 |
+
if self.tokenizer.image_token in msg["content"]:
|
| 53 |
+
logging.warning(f"Found and removed an image token in the {msg['role']} text before adding the image string.")
|
| 54 |
+
msg["content"] = msg["content"].replace(self.tokenizer.image_token, "")
|
| 55 |
+
|
| 56 |
+
if len(splitted_image_counts) > 0:
|
| 57 |
+
image_string = get_image_string(self.tokenizer, splitted_image_counts, self.mp_image_token_length)
|
| 58 |
+
messages[0]["content"] = image_string + messages[0]["content"]
|
| 59 |
+
|
| 60 |
+
return messages
|
| 61 |
+
|
| 62 |
+
def _process_images(self, images):
|
| 63 |
+
processed_images = []
|
| 64 |
+
splitted_image_counts = []
|
| 65 |
+
for image in images:
|
| 66 |
+
if isinstance(image, Image.Image):
|
| 67 |
+
if image.mode != 'RGB':
|
| 68 |
+
image = image.convert('RGB')
|
| 69 |
+
processed_image, splitted_image_count = self.image_processor(image)
|
| 70 |
+
if not hasattr(self.tokenizer, "global_image_token") and splitted_image_count[0]*splitted_image_count[1] == len(processed_image) - 1:
|
| 71 |
+
# If the tokenizer doesn't have a global image token, but the processor generated it, remove it
|
| 72 |
+
processed_image = processed_image[1:]
|
| 73 |
+
processed_images.append(processed_image)
|
| 74 |
+
splitted_image_counts.append(splitted_image_count)
|
| 75 |
+
else:
|
| 76 |
+
raise ValueError(f"Error processing image: {image}")
|
| 77 |
+
return processed_images, splitted_image_counts
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _prepare_inputs_and_loss_mask(self, messages):
|
| 81 |
+
conv_ids = self.tokenizer.apply_chat_template(
|
| 82 |
+
messages,
|
| 83 |
+
tokenize=True,
|
| 84 |
+
add_special_tokens=False,
|
| 85 |
+
return_dict=True,
|
| 86 |
+
)
|
| 87 |
+
mask = [0] * len(conv_ids["input_ids"])
|
| 88 |
+
|
| 89 |
+
# Locate each assistant turn and flip its mask to 1
|
| 90 |
+
cursor = 0
|
| 91 |
+
for msg in messages:
|
| 92 |
+
segment_ids = self.tokenizer.apply_chat_template(
|
| 93 |
+
[msg], tokenize=True, add_special_tokens=False
|
| 94 |
+
)
|
| 95 |
+
seg_len = len(segment_ids)
|
| 96 |
+
|
| 97 |
+
if msg["role"] == "assistant":
|
| 98 |
+
start = cursor + self.prefix_len
|
| 99 |
+
end = cursor + seg_len
|
| 100 |
+
mask[start:end] = [1] * (end - start) # attend to these tokens
|
| 101 |
+
|
| 102 |
+
cursor += seg_len
|
| 103 |
+
|
| 104 |
+
return torch.tensor(conv_ids["input_ids"]), torch.tensor(mask).to(torch.bool), torch.tensor(conv_ids["attention_mask"])
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class VQADataset(BaseDataset): # Visual Question Answering Dataset
|
| 108 |
+
def iter_for_worker(self): # with iterable datasets, each worker gets different shards
|
| 109 |
+
for data in self.dataset:
|
| 110 |
+
yield self._process_data(data)
|
| 111 |
+
|
| 112 |
+
def __getitem__(self, idx):
|
| 113 |
+
item = self.dataset[idx]
|
| 114 |
+
return self._process_data(item)
|
| 115 |
+
|
| 116 |
+
def _process_data(self, item):
|
| 117 |
+
# Handle images (should be a list)
|
| 118 |
+
if item['images'] is None:
|
| 119 |
+
images_data = []
|
| 120 |
+
else:
|
| 121 |
+
images_data = item['images']
|
| 122 |
+
if not isinstance(images_data, list):
|
| 123 |
+
images_data = [images_data]
|
| 124 |
+
|
| 125 |
+
processed_images = []
|
| 126 |
+
splitted_image_counts = []
|
| 127 |
+
if images_data: # Only process if there are images
|
| 128 |
+
processed_images, splitted_image_counts = self._process_images(images_data)
|
| 129 |
+
|
| 130 |
+
messages = self._get_messages(item, splitted_image_counts)
|
| 131 |
+
|
| 132 |
+
if len(messages) == 0:
|
| 133 |
+
return None
|
| 134 |
+
|
| 135 |
+
input_ids, mask, attention_mask = self._prepare_inputs_and_loss_mask(messages)
|
| 136 |
+
labels = self._get_labels(input_ids, mask)
|
| 137 |
+
|
| 138 |
+
return {
|
| 139 |
+
"images": processed_images,
|
| 140 |
+
"input_ids": input_ids,
|
| 141 |
+
"attention_mask": attention_mask,
|
| 142 |
+
"labels": labels,
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
def _get_labels(self, input_ids, mask):
|
| 146 |
+
labels = input_ids.clone().masked_fill(~mask, -100)
|
| 147 |
+
labels = labels.roll(-1) # Shift labels for causal LM
|
| 148 |
+
labels[-1] = -100 # Last token has no target
|
| 149 |
+
|
| 150 |
+
return labels
|
src/data/processors.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import AutoTokenizer
|
| 2 |
+
import torchvision.transforms as transforms
|
| 3 |
+
|
| 4 |
+
from data.custom_transforms import DynamicResize, SplitImage, GlobalAndSplitImages
|
| 5 |
+
|
| 6 |
+
TOKENIZERS_CACHE = {}
|
| 7 |
+
|
| 8 |
+
def get_tokenizer(name, extra_special_tokens=None, chat_template=None):
|
| 9 |
+
if name not in TOKENIZERS_CACHE:
|
| 10 |
+
tokenizer_init_kwargs = {"use_fast": True}
|
| 11 |
+
if extra_special_tokens is not None:
|
| 12 |
+
tokenizer_init_kwargs["extra_special_tokens"] = extra_special_tokens
|
| 13 |
+
if chat_template is not None:
|
| 14 |
+
tokenizer_init_kwargs["chat_template"] = chat_template
|
| 15 |
+
tokenizer = AutoTokenizer.from_pretrained(name, **tokenizer_init_kwargs,)
|
| 16 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 17 |
+
TOKENIZERS_CACHE[name] = tokenizer
|
| 18 |
+
return TOKENIZERS_CACHE[name]
|
| 19 |
+
|
| 20 |
+
def get_image_processor(max_img_size, splitted_image_size, resize_to_max_side_len=False):
|
| 21 |
+
return transforms.Compose([
|
| 22 |
+
DynamicResize(splitted_image_size, max_img_size, resize_to_max_side_len),
|
| 23 |
+
transforms.ToTensor(),
|
| 24 |
+
GlobalAndSplitImages(splitted_image_size),
|
| 25 |
+
])
|
| 26 |
+
|
| 27 |
+
def get_image_string(tokenizer, splitted_image_counts, mp_image_token_length):
|
| 28 |
+
image_string = ""
|
| 29 |
+
# splitted_image_counts is a list of tuples (n_h, n_w)
|
| 30 |
+
for idx, (n_h, n_w) in enumerate(splitted_image_counts):
|
| 31 |
+
if len(splitted_image_counts) > 1:
|
| 32 |
+
image_string += f"<image: {idx}>"
|
| 33 |
+
if hasattr(tokenizer, "global_image_token"):
|
| 34 |
+
image_string += tokenizer.global_image_token
|
| 35 |
+
image_string += tokenizer.image_token * mp_image_token_length
|
| 36 |
+
if n_h == 1 and n_w == 1: # If there is only one patch, treat it as the global image
|
| 37 |
+
continue
|
| 38 |
+
for i in range(n_h):
|
| 39 |
+
for j in range(n_w):
|
| 40 |
+
image_string += getattr(tokenizer, f'r{i+1}c{j+1}')
|
| 41 |
+
image_string += tokenizer.image_token * mp_image_token_length
|
| 42 |
+
return image_string
|
src/generate.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import torch
|
| 3 |
+
from PIL import Image
|
| 4 |
+
|
| 5 |
+
torch.manual_seed(0)
|
| 6 |
+
if torch.cuda.is_available():
|
| 7 |
+
torch.cuda.manual_seed_all(0)
|
| 8 |
+
|
| 9 |
+
from models.vision_language_model import VisionLanguageModel
|
| 10 |
+
from data.processors import get_tokenizer, get_image_processor, get_image_string
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def parse_args():
|
| 14 |
+
parser = argparse.ArgumentParser(
|
| 15 |
+
description="Generate text from an image with nanoVLM")
|
| 16 |
+
parser.add_argument(
|
| 17 |
+
"--checkpoint", type=str, default=None,
|
| 18 |
+
help="Path to a local checkpoint (directory or safetensors/pth). If omitted, we pull from HF."
|
| 19 |
+
)
|
| 20 |
+
parser.add_argument(
|
| 21 |
+
"--hf_model", type=str, default="lusxvr/nanoVLM-230M-8k",
|
| 22 |
+
help="HuggingFace repo ID to download from incase --checkpoint isnt set."
|
| 23 |
+
)
|
| 24 |
+
parser.add_argument("--image", type=str, default="assets/cat.png",
|
| 25 |
+
help="Path to input image")
|
| 26 |
+
parser.add_argument("--prompt", type=str, default="What is this?",
|
| 27 |
+
help="Text prompt to feed the model")
|
| 28 |
+
parser.add_argument("--generations", type=int, default=5,
|
| 29 |
+
help="Num. of outputs to generate")
|
| 30 |
+
parser.add_argument("--max_new_tokens", type=int, default=300,
|
| 31 |
+
help="Maximum number of tokens per output")
|
| 32 |
+
parser.add_argument("--measure_vram", action="store_true",
|
| 33 |
+
help="Measure and display VRAM usage during model loading and generation")
|
| 34 |
+
return parser.parse_args()
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def main():
|
| 38 |
+
args = parse_args()
|
| 39 |
+
|
| 40 |
+
if torch.cuda.is_available():
|
| 41 |
+
device = torch.device("cuda")
|
| 42 |
+
elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
|
| 43 |
+
device = torch.device("mps")
|
| 44 |
+
else:
|
| 45 |
+
device = torch.device("cpu")
|
| 46 |
+
print(f"Using device: {device}")
|
| 47 |
+
|
| 48 |
+
source = args.checkpoint if args.checkpoint else args.hf_model
|
| 49 |
+
print(f"Loading weights from: {source}")
|
| 50 |
+
|
| 51 |
+
if args.measure_vram and torch.cuda.is_available():
|
| 52 |
+
torch.cuda.reset_peak_memory_stats(device)
|
| 53 |
+
|
| 54 |
+
model = VisionLanguageModel.from_pretrained(source).to(device)
|
| 55 |
+
model.eval()
|
| 56 |
+
|
| 57 |
+
if args.measure_vram and torch.cuda.is_available():
|
| 58 |
+
torch.cuda.synchronize()
|
| 59 |
+
model_vram_bytes = torch.cuda.memory_allocated(device)
|
| 60 |
+
model_vram_mb = model_vram_bytes / (1024 ** 2)
|
| 61 |
+
print(f"VRAM used after loading model: {model_vram_mb:.2f} MB")
|
| 62 |
+
|
| 63 |
+
# Get tokenizer and image processor from model config if not provided
|
| 64 |
+
tokenizer = get_tokenizer(model.cfg.lm_tokenizer, model.cfg.vlm_extra_tokens, model.cfg.lm_chat_template)
|
| 65 |
+
resize_to_max_side_len = False
|
| 66 |
+
if hasattr(model.cfg, "resize_to_max_side_len"):
|
| 67 |
+
resize_to_max_side_len = model.cfg.resize_to_max_side_len
|
| 68 |
+
image_processor = get_image_processor(model.cfg.max_img_size, model.cfg.vit_img_size, resize_to_max_side_len)
|
| 69 |
+
|
| 70 |
+
img = Image.open(args.image).convert("RGB")
|
| 71 |
+
processed_image, splitted_image_ratio = image_processor(img)
|
| 72 |
+
if not hasattr(tokenizer, "global_image_token") and splitted_image_ratio[0]*splitted_image_ratio[1] == len(processed_image) - 1:
|
| 73 |
+
# If the tokenizer doesn't have a global image token, but the processor generated it, remove it
|
| 74 |
+
processed_image = processed_image[1:]
|
| 75 |
+
|
| 76 |
+
image_string = get_image_string(tokenizer, [splitted_image_ratio], model.cfg.mp_image_token_length)
|
| 77 |
+
|
| 78 |
+
messages = [{"role": "user", "content": image_string + args.prompt}]
|
| 79 |
+
encoded_prompt = tokenizer.apply_chat_template([messages], tokenize=True, add_generation_prompt=True)
|
| 80 |
+
tokens = torch.tensor(encoded_prompt).to(device)
|
| 81 |
+
img_t = processed_image.to(device)
|
| 82 |
+
|
| 83 |
+
print("\nInput:\n ", args.prompt, "\n\nOutput:")
|
| 84 |
+
for i in range(args.generations):
|
| 85 |
+
gen = model.generate(tokens, img_t, max_new_tokens=args.max_new_tokens)
|
| 86 |
+
out = tokenizer.batch_decode(gen, skip_special_tokens=True)[0]
|
| 87 |
+
|
| 88 |
+
if args.measure_vram and torch.cuda.is_available():
|
| 89 |
+
torch.cuda.synchronize()
|
| 90 |
+
peak_vram_bytes = torch.cuda.max_memory_allocated(device)
|
| 91 |
+
peak_vram_mb = peak_vram_bytes / (1024 ** 2)
|
| 92 |
+
current_vram_bytes = torch.cuda.memory_allocated(device)
|
| 93 |
+
current_vram_mb = current_vram_bytes / (1024 ** 2)
|
| 94 |
+
print(f" >> Generation {i+1}: {out}")
|
| 95 |
+
print(f" VRAM - Peak: {peak_vram_mb:.2f} MB, Current: {current_vram_mb:.2f} MB")
|
| 96 |
+
else:
|
| 97 |
+
print(f" >> Generation {i+1}: {out}")
|
| 98 |
+
|
| 99 |
+
if __name__ == "__main__":
|
| 100 |
+
main()
|
src/models/README.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Models
|
| 2 |
+
|
| 3 |
+
## Vision Backbone (ViT)
|
| 4 |
+
|
| 5 |
+
This is a very lightweight Vision Transformer in native pytorch. I took inspiration from the following sources:
|
| 6 |
+
- https://github.com/karpathy/nanoGPT (General Transformer Decoder)
|
| 7 |
+
- https://arxiv.org/abs/2010.11929 (ViT Paper)
|
| 8 |
+
- https://arxiv.org/abs/2303.15343 (SigLiP Paper)
|
| 9 |
+
- https://github.com/huggingface/transformers/blob/main/src/transformers/models/siglip/modeling_siglip.py (HF SigLiP Implementation)
|
| 10 |
+
|
| 11 |
+
## Language Model (Llama / SmolLM)
|
| 12 |
+
|
| 13 |
+
This is a decoder only LM, following the Llama 2/3 architecture. Inspiration from the following sources:
|
| 14 |
+
- https://arxiv.org/pdf/2307.09288 (Original Llama Paper)
|
| 15 |
+
- https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py (HF Llama Implementation)
|
| 16 |
+
|
| 17 |
+
## Modality Projection
|
| 18 |
+
|
| 19 |
+
This is a simple MLP (Linear Layer) for the Modality Projection between the Image Patch Encodings and the Language Embedding Space with a simple Pixel Shuffle (https://arxiv.org/pdf/2504.05299)
|
| 20 |
+
|
| 21 |
+
## Vision-Language-Model
|
| 22 |
+
|
| 23 |
+
This brings all the individual parts together and handles the concatenation of images and text. Built as a simple version of SmolVLM (https://arxiv.org/pdf/2504.05299)
|
src/models/__init__.py
ADDED
|
File without changes
|
src/models/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (158 Bytes). View file
|
|
|
src/models/__pycache__/config.cpython-312.pyc
ADDED
|
Binary file (7.37 kB). View file
|
|
|
src/models/__pycache__/language_model.cpython-312.pyc
ADDED
|
Binary file (36.6 kB). View file
|
|
|
src/models/__pycache__/modality_projector.cpython-312.pyc
ADDED
|
Binary file (3.03 kB). View file
|
|
|
src/models/__pycache__/utils.cpython-312.pyc
ADDED
|
Binary file (2.01 kB). View file
|
|
|
src/models/__pycache__/vision_language_model.cpython-312.pyc
ADDED
|
Binary file (13.6 kB). View file
|
|
|
src/models/__pycache__/vision_transformer.cpython-312.pyc
ADDED
|
Binary file (16.7 kB). View file
|
|
|
src/models/config.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass, field
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
@dataclass
|
| 5 |
+
class VLMConfig:
|
| 6 |
+
vit_hidden_dim: int = 768
|
| 7 |
+
vit_inter_dim: int = 4 * vit_hidden_dim
|
| 8 |
+
vit_patch_size: int = 16
|
| 9 |
+
vit_img_size: int = 512
|
| 10 |
+
vit_n_heads: int = 12
|
| 11 |
+
vit_dropout: float = 0.0
|
| 12 |
+
vit_n_blocks: int = 12
|
| 13 |
+
vit_ln_eps: float = 1e-6
|
| 14 |
+
vit_cls_flag: bool = False
|
| 15 |
+
vit_model_type: str = 'google/siglip2-base-patch16-512'
|
| 16 |
+
|
| 17 |
+
lm_hidden_dim: int = 960
|
| 18 |
+
lm_inter_dim: int = 2560
|
| 19 |
+
lm_rms_eps: float = 1e-5
|
| 20 |
+
lm_re_base: int = 100000
|
| 21 |
+
lm_max_position_embeddings: int = 8192
|
| 22 |
+
lm_base_vocab_size: int = 49152
|
| 23 |
+
extra_token_amount: int = 66 # Number of extra tokens for the VLM (image start, image end, image token)
|
| 24 |
+
lm_vocab_size: int = lm_base_vocab_size + extra_token_amount # Not a great way to do this, but it works for now (vlm_extra_tokens cannot be a dict, since this is mutable, and a Field has no len() function)
|
| 25 |
+
lm_n_heads: int = 15
|
| 26 |
+
lm_n_kv_heads: int = 5
|
| 27 |
+
lm_dropout: float = 0.0
|
| 28 |
+
lm_n_blocks: int = 32
|
| 29 |
+
lm_attn_scaling: float = 1.0
|
| 30 |
+
lm_max_length: int = 4096
|
| 31 |
+
lm_use_tokens: bool = False # Decide if the LM expects tokens or embeddings as input (if using as a backbone for the VLM, set to False)
|
| 32 |
+
lm_tie_weights: bool = True # Decide if you want to tie the LM Head weight to the token embedding weights
|
| 33 |
+
lm_model_type: str = 'HuggingFaceTB/SmolLM2-360M-Instruct' #'HuggingFaceTB/SmolLM2-135M' #
|
| 34 |
+
lm_tokenizer: str = 'HuggingFaceTB/SmolLM2-360M-Instruct'
|
| 35 |
+
lm_chat_template: str = "{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}"
|
| 36 |
+
|
| 37 |
+
mp_pixel_shuffle_factor: int = 4
|
| 38 |
+
mp_image_token_length: int = 64
|
| 39 |
+
|
| 40 |
+
max_img_size: int = 2048
|
| 41 |
+
resize_to_max_side_len: bool = True
|
| 42 |
+
|
| 43 |
+
vlm_extra_tokens: dict[str, str] = field(default_factory=lambda: {"image_token": "<|image|>", "global_image_token": "<|global_image|>",
|
| 44 |
+
"r1c1": "<row_1_col_1>", "r1c2": "<row_1_col_2>", "r1c3": "<row_1_col_3>", "r1c4": "<row_1_col_4>", "r1c5": "<row_1_col_5>", "r1c6": "<row_1_col_6>", "r1c7": "<row_1_col_7>", "r1c8": "<row_1_col_8>",
|
| 45 |
+
"r2c1": "<row_2_col_1>", "r2c2": "<row_2_col_2>", "r2c3": "<row_2_col_3>", "r2c4": "<row_2_col_4>", "r2c5": "<row_2_col_5>", "r2c6": "<row_2_col_6>", "r2c7": "<row_2_col_7>", "r2c8": "<row_2_col_8>",
|
| 46 |
+
"r3c1": "<row_3_col_1>", "r3c2": "<row_3_col_2>", "r3c3": "<row_3_col_3>", "r3c4": "<row_3_col_4>", "r3c5": "<row_3_col_5>", "r3c6": "<row_3_col_6>", "r3c7": "<row_3_col_7>", "r3c8": "<row_3_col_8>",
|
| 47 |
+
"r4c1": "<row_4_col_1>", "r4c2": "<row_4_col_2>", "r4c3": "<row_4_col_3>", "r4c4": "<row_4_col_4>", "r4c5": "<row_4_col_5>", "r4c6": "<row_4_col_6>", "r4c7": "<row_4_col_7>", "r4c8": "<row_4_col_8>",
|
| 48 |
+
"r5c1": "<row_5_col_1>", "r5c2": "<row_5_col_2>", "r5c3": "<row_5_col_3>", "r5c4": "<row_5_col_4>", "r5c5": "<row_5_col_5>", "r5c6": "<row_5_col_6>", "r5c7": "<row_5_col_7>", "r5c8": "<row_5_col_8>",
|
| 49 |
+
"r6c1": "<row_6_col_1>", "r6c2": "<row_6_col_2>", "r6c3": "<row_6_col_3>", "r6c4": "<row_6_col_4>", "r6c5": "<row_6_col_5>", "r6c6": "<row_6_col_6>", "r6c7": "<row_6_col_7>", "r6c8": "<row_6_col_8>",
|
| 50 |
+
"r7c1": "<row_7_col_1>", "r7c2": "<row_7_col_2>", "r7c3": "<row_7_col_3>", "r7c4": "<row_7_col_4>", "r7c5": "<row_7_col_5>", "r7c6": "<row_7_col_6>", "r7c7": "<row_7_col_7>", "r7c8": "<row_7_col_8>",
|
| 51 |
+
"r8c1": "<row_8_col_1>", "r8c2": "<row_8_col_2>", "r8c3": "<row_8_col_3>", "r8c4": "<row_8_col_4>", "r8c5": "<row_8_col_5>", "r8c6": "<row_8_col_6>", "r8c7": "<row_8_col_7>", "r8c8": "<row_8_col_8>"})
|
| 52 |
+
vlm_load_backbone_weights: bool = True
|
| 53 |
+
vlm_checkpoint_path: str = 'checkpoints'
|
| 54 |
+
hf_repo_name: str = 'nanoVLM'
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@dataclass
|
| 58 |
+
class TrainConfig:
|
| 59 |
+
lr_mp: float = 0.00512
|
| 60 |
+
lr_vision_backbone: float = 5e-5 #0.0005 #
|
| 61 |
+
lr_language_backbone: float = 5e-5 #0
|
| 62 |
+
val_size: int = 50000
|
| 63 |
+
batch_size: int = 2
|
| 64 |
+
gradient_accumulation_steps: int = 8
|
| 65 |
+
max_grad_norm: float = 1.0
|
| 66 |
+
eval_in_epochs: bool = True
|
| 67 |
+
eval_interval: int = 500
|
| 68 |
+
stats_log_interval: int = 100
|
| 69 |
+
max_training_steps: int = 40000
|
| 70 |
+
max_images_per_example: int = 4
|
| 71 |
+
max_images_per_knapsack: int = 18
|
| 72 |
+
max_sample_length: int = 4096
|
| 73 |
+
compile: bool = False
|
| 74 |
+
resume_from_vlm_checkpoint: bool = False # Indicate if the training should be resumed from a checkpoint of the whole VLM or you want to start from scratch
|
| 75 |
+
train_dataset_path: str = 'HuggingFaceM4/FineVision_concat_shuffled_2'
|
| 76 |
+
train_dataset_name: tuple[str, ...] = ("default", ) #('allava_laion', 'allava_vflan', 'cambrian(filtered)_processed', 'LLaVA_Instruct_150K', 'mmevol', 'sharegpt4o', 'sharegpt4v(coco)', 'sharegpt4v(knowledge)', 'sharegpt4v(llava)', 'sharegpt4v(sam)') # 'vision_flan(filtered)', 'lvis_instruct4v',
|
| 77 |
+
stream_dataset: bool = True
|
| 78 |
+
relevance_min_rating: int = 1
|
| 79 |
+
image_correspondence_min_rating: int = 1
|
| 80 |
+
visual_dependency_min_rating: int = 1
|
| 81 |
+
formatting_min_rating: int = 1
|
| 82 |
+
wandb_entity: str = "HuggingFace" # Indicate the entity to log to in wandb
|
| 83 |
+
log_wandb: bool = True
|
| 84 |
+
use_lmms_eval: bool = True # Use lmms-eval for evaluation
|
| 85 |
+
lmms_eval_tasks: str = 'mmstar,mmmu_val,ocrbench,textvqa_val,docvqa_val,scienceqa,mme,infovqa_val,chartqa' # Pass additional task as one string, seperated by commas without spaces (e.g. 'mmstar,mmmu,ocrbench')
|
| 86 |
+
lmms_eval_limit: float = None
|
| 87 |
+
lmms_eval_batch_size: int = 64
|
src/models/language_model.py
ADDED
|
@@ -0,0 +1,681 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
|
| 6 |
+
# https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py#L69
|
| 7 |
+
class RMSNorm(nn.Module):
|
| 8 |
+
"""
|
| 9 |
+
Root Mean Square Layer Normalization (RMSNorm).
|
| 10 |
+
|
| 11 |
+
Normalizes the input across the last dimension using RMS normalization,
|
| 12 |
+
which scales the input without subtracting the mean. Commonly used as a
|
| 13 |
+
lighter alternative to LayerNorm in transformer models.
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
cfg: A configuration object containing:
|
| 17 |
+
- lm_hidden_dim (int): The dimensionality of the model hidden states.
|
| 18 |
+
- lm_rms_eps (float): A small constant to avoid division by zero.
|
| 19 |
+
"""
|
| 20 |
+
def __init__(self, cfg):
|
| 21 |
+
super().__init__()
|
| 22 |
+
self.weight = nn.Parameter(torch.ones(cfg.lm_hidden_dim))
|
| 23 |
+
self.eps = cfg.lm_rms_eps
|
| 24 |
+
|
| 25 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 26 |
+
"""
|
| 27 |
+
Forward pass for RMSNorm.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
x (torch.Tensor): Input tensor of shape (batch_size, sequence_length, lm_hidden_dim).
|
| 31 |
+
|
| 32 |
+
Returns:
|
| 33 |
+
torch.Tensor: Normalized tensor of the same shape as input.
|
| 34 |
+
"""
|
| 35 |
+
# Compute inverse of RMS: square the tensor element-wise, mean is computed across lm_hidden_dim.
|
| 36 |
+
irms = torch.rsqrt(torch.mean(x ** 2, dim=-1, keepdim=True) + self.eps) # inverse of RMS
|
| 37 |
+
x = x * irms * self.weight
|
| 38 |
+
|
| 39 |
+
return x
|
| 40 |
+
|
| 41 |
+
# Multiple derivates of Rotary Embeddings by now, this is a basic one with linear scaling to context length
|
| 42 |
+
# e.g. https://github.com/huggingface/smollm/blob/main/vision/m4/models/vllama3/modeling_vllama3.py#L190
|
| 43 |
+
class RotaryEmbedding(nn.Module):
|
| 44 |
+
"""
|
| 45 |
+
Compute Rotary Embedding to introduce positional dependency to input sequence without additional training parameters and
|
| 46 |
+
relative distance of token position ids through angle rotation.
|
| 47 |
+
|
| 48 |
+
Args:
|
| 49 |
+
cfg: Configuration object containing:
|
| 50 |
+
- lm_hidden_dim (int): Hidden dimension size.
|
| 51 |
+
- lm_n_heads (int): Number of attention heads.
|
| 52 |
+
- lm_re_base (float): Base for rotary embedding frequencies.
|
| 53 |
+
- lm_max_position_embeddings (int): Max sequence length supported for rotary embedding.
|
| 54 |
+
- lm_attn_scaling (float): Attention scaling factor.
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
def __init__(self, cfg):
|
| 58 |
+
super().__init__()
|
| 59 |
+
assert cfg.lm_hidden_dim % cfg.lm_n_heads == 0, "Hidden dimension must be divisible by number of heads"
|
| 60 |
+
|
| 61 |
+
self.dim = cfg.lm_hidden_dim // cfg.lm_n_heads # dim of each head
|
| 62 |
+
self.base = cfg.lm_re_base
|
| 63 |
+
self.max_seq_len = cfg.lm_max_position_embeddings
|
| 64 |
+
# Standard RoPE implementation - create frequencies for each dimension
|
| 65 |
+
# freq_i = 1 / (base^(2i/dim)) where i is the dimension index
|
| 66 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float() / self.dim))
|
| 67 |
+
self.register_buffer("inv_freq", inv_freq)
|
| 68 |
+
self.original_max_seq_len = cfg.lm_max_position_embeddings
|
| 69 |
+
self.attention_scaling = cfg.lm_attn_scaling
|
| 70 |
+
|
| 71 |
+
@torch.no_grad()
|
| 72 |
+
def forward(self, position_ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 73 |
+
"""
|
| 74 |
+
Compute rotary positional embeddings (cosine and sine components).
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
position_ids (torch.Tensor): Tensor of shape (batch_size, seq_len) containing position indices.
|
| 78 |
+
|
| 79 |
+
Returns:
|
| 80 |
+
Tuple[torch.Tensor, torch.Tensor]: Tuple of two tensors (cos, sin), each of shape
|
| 81 |
+
(batch_size, seq_len, dim), representing rotary embeddings.
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
batch_size, seq_len = position_ids.shape
|
| 85 |
+
# Dynamic scaling for longer sequences
|
| 86 |
+
# Divide the angle frequency to fit more rotation into the embedding space.
|
| 87 |
+
max_seq = position_ids.max() + 1
|
| 88 |
+
if max_seq > self.original_max_seq_len:
|
| 89 |
+
scale = max_seq / self.original_max_seq_len
|
| 90 |
+
inv_freq = self.inv_freq / scale
|
| 91 |
+
else:
|
| 92 |
+
inv_freq = self.inv_freq
|
| 93 |
+
|
| 94 |
+
# Compute theta = position * frequency
|
| 95 |
+
# Flatten position_ids for batch processing
|
| 96 |
+
flat_position_ids = position_ids.reshape(-1).float()
|
| 97 |
+
|
| 98 |
+
# Element-wise outer product: [seq_len] x [dim/2] => [seq_len, dim/2]
|
| 99 |
+
freqs = flat_position_ids.unsqueeze(-1) * inv_freq.unsqueeze(0)
|
| 100 |
+
|
| 101 |
+
# Reshape to include batch dimension
|
| 102 |
+
freqs = freqs.reshape(batch_size, seq_len, -1)
|
| 103 |
+
|
| 104 |
+
# Now create interleaved pattern
|
| 105 |
+
emb = torch.cat([freqs, freqs], dim=-1)
|
| 106 |
+
|
| 107 |
+
# Compute cos and sin
|
| 108 |
+
cos = torch.cos(emb) * self.attention_scaling
|
| 109 |
+
sin = torch.sin(emb) * self.attention_scaling
|
| 110 |
+
|
| 111 |
+
return cos, sin
|
| 112 |
+
|
| 113 |
+
def rotate_half(x: torch.Tensor) -> torch.Tensor:
|
| 114 |
+
"""
|
| 115 |
+
Rotates the input by dividing the hidden dimension to two, then swapping and negating dimensions.
|
| 116 |
+
"""
|
| 117 |
+
x1, x2 = x.chunk(2, dim=-1)
|
| 118 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 119 |
+
|
| 120 |
+
# Apply rotary position embeddings to queries and keys.
|
| 121 |
+
def apply_rotary_pos_embd(q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, unsqueeze_dim:int=1)-> tuple[torch.Tensor, torch.Tensor]:
|
| 122 |
+
"""
|
| 123 |
+
Applies rotary positional embeddings to query and key tensors in attention mechanisms.
|
| 124 |
+
|
| 125 |
+
Rotary positional embeddings inject position-dependent rotations into query and key vectors,
|
| 126 |
+
enabling transformers to encode positional information effectively without explicit positional encoding.
|
| 127 |
+
|
| 128 |
+
Args:
|
| 129 |
+
q (torch.Tensor): Query tensor with shape [batch_size, num_heads, seq_len, head_dim].
|
| 130 |
+
k (torch.Tensor): Key tensor with shape [batch_size, num_heads, seq_len, head_dim].
|
| 131 |
+
cos (torch.Tensor): Precomputed cosine positional embeddings with shape [batch_size, seq_len, head_dim].
|
| 132 |
+
sin (torch.Tensor): Precomputed sine positional embeddings with shape [batch_size, seq_len, head_dim].
|
| 133 |
+
unsqueeze_dim (int, optional): Dimension index to unsqueeze `cos` and `sin` to enable broadcasting.
|
| 134 |
+
Defaults to 1 (typically the heads dimension).
|
| 135 |
+
|
| 136 |
+
Returns:
|
| 137 |
+
tuple[torch.Tensor, torch.Tensor]: The rotated query and key tensors (`q_embed`, `k_embed`),
|
| 138 |
+
each with the same shape as the input tensors.
|
| 139 |
+
|
| 140 |
+
How it works:
|
| 141 |
+
- `cos` and `sin` tensors are unsqueezed at `unsqueeze_dim` to broadcast across attention heads.
|
| 142 |
+
- Rotary embeddings apply a complex number rotation in the embedding space using:
|
| 143 |
+
rotated = (original * cos) + (rotate_half(original) * sin)
|
| 144 |
+
- `rotate_half` performs a specific half-dimension rotation on the input tensor.
|
| 145 |
+
- This operation encodes relative position information in q and k without adding explicit positional vectors.
|
| 146 |
+
|
| 147 |
+
Example:
|
| 148 |
+
q_embed, k_embed = apply_rotary_pos_embd(q, k, cos, sin)
|
| 149 |
+
|
| 150 |
+
"""
|
| 151 |
+
|
| 152 |
+
# We need to make sure cos and sin can be properly broadcast
|
| 153 |
+
# to the shape of q and k by adding the heads dimension
|
| 154 |
+
cos = cos.unsqueeze(unsqueeze_dim) # [batch_size, 1, seq_len, head_dim]
|
| 155 |
+
sin = sin.unsqueeze(unsqueeze_dim) # [batch_size, 1, seq_len, head_dim]
|
| 156 |
+
|
| 157 |
+
# Apply complex multiplication:
|
| 158 |
+
# (q * cos) + (rotate_half(q) * sin)
|
| 159 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 160 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 161 |
+
|
| 162 |
+
return q_embed, k_embed
|
| 163 |
+
|
| 164 |
+
# https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py#L214
|
| 165 |
+
# https://github.com/huggingface/smollm/blob/main/vision/m4/models/vllama3/modeling_vllama3.py#L382
|
| 166 |
+
class LanguageModelGroupedQueryAttention(nn.Module):
|
| 167 |
+
"""
|
| 168 |
+
Implements Grouped Query Attention (GQA) as used in some transformer-based language models.
|
| 169 |
+
|
| 170 |
+
GQA reduces computation by using fewer key-value heads than query heads,
|
| 171 |
+
grouping multiple query heads to share the same key-value heads.
|
| 172 |
+
|
| 173 |
+
Args:
|
| 174 |
+
cfg: Configuration object containing:
|
| 175 |
+
- lm_n_heads (int): Number of query heads.
|
| 176 |
+
- lm_n_kv_heads (int): Number of key-value heads.
|
| 177 |
+
- lm_hidden_dim (int): Hidden embedding dimension.
|
| 178 |
+
- lm_dropout (float): Dropout rate.
|
| 179 |
+
"""
|
| 180 |
+
def __init__(self, cfg):
|
| 181 |
+
super().__init__()
|
| 182 |
+
|
| 183 |
+
self.n_heads = cfg.lm_n_heads
|
| 184 |
+
self.n_kv_heads = cfg.lm_n_kv_heads
|
| 185 |
+
self.embd_dim = cfg.lm_hidden_dim
|
| 186 |
+
self.dropout = cfg.lm_dropout
|
| 187 |
+
|
| 188 |
+
assert self.n_heads % self.n_kv_heads == 0, "n_heads must be divisible by n_kv_heads"
|
| 189 |
+
assert self.embd_dim % self.n_heads == 0, "embd_dim must be divisible by num_heads"
|
| 190 |
+
|
| 191 |
+
self.n_kv_groups = self.n_heads // self.n_kv_heads
|
| 192 |
+
self.head_dim = self.embd_dim // self.n_heads
|
| 193 |
+
|
| 194 |
+
self.q_proj = nn.Linear(self.embd_dim, self.embd_dim, bias=False)
|
| 195 |
+
self.k_proj = nn.Linear(self.embd_dim, self.head_dim * self.n_kv_heads, bias=False)
|
| 196 |
+
self.v_proj = nn.Linear(self.embd_dim, self.head_dim * self.n_kv_heads, bias=False)
|
| 197 |
+
self.out_proj = nn.Linear(self.embd_dim, self.embd_dim, bias=False)
|
| 198 |
+
|
| 199 |
+
self.attn_dropout = nn.Dropout(self.dropout)
|
| 200 |
+
self.resid_dropout = nn.Dropout(self.dropout)
|
| 201 |
+
|
| 202 |
+
# Use scaled dot product attention if available
|
| 203 |
+
self.sdpa = hasattr(torch.nn.functional, 'scaled_dot_product_attention')
|
| 204 |
+
if not self.sdpa:
|
| 205 |
+
print("Warning: scaled dot product attention not available, using standard attention in LM.")
|
| 206 |
+
|
| 207 |
+
def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, attention_mask=None, block_kv_cache=None) -> tuple[torch.Tensor, dict]:
|
| 208 |
+
"""
|
| 209 |
+
Forward pass for grouped query attention.
|
| 210 |
+
|
| 211 |
+
Args:
|
| 212 |
+
x (Tensor): Input tensor of shape (B, T_curr, C), where
|
| 213 |
+
B = batch size,
|
| 214 |
+
T_curr = current sequence length,
|
| 215 |
+
C = embedding dimension.
|
| 216 |
+
cos (Tensor): Rotary embedding cosines, shape compatible with q and k.
|
| 217 |
+
sin (Tensor): Rotary embedding sines, shape compatible with q and k.
|
| 218 |
+
attention_mask (Tensor, optional): Attention mask tensor of shape (B, total_kv_length),
|
| 219 |
+
with 1 for tokens to attend to and 0 for padding.
|
| 220 |
+
block_kv_cache (dict, optional): Cache dict with 'key' and 'value' tensors for autoregressive decoding.
|
| 221 |
+
|
| 222 |
+
Returns:
|
| 223 |
+
tuple[Tensor, dict]:
|
| 224 |
+
- Output tensor after attention and projection, shape (B, T_curr, C).
|
| 225 |
+
- Updated block_kv_cache dict for caching key-value states.
|
| 226 |
+
"""
|
| 227 |
+
is_prefill = block_kv_cache is None
|
| 228 |
+
|
| 229 |
+
B, T_curr, C = x.size() # T_curr is the sequence length of the current input x
|
| 230 |
+
|
| 231 |
+
q_curr = self.q_proj(x).view(B, T_curr, self.n_heads, self.head_dim).transpose(1, 2) # (B, n_heads, T_curr, head_dim)
|
| 232 |
+
k_curr = self.k_proj(x).view(B, T_curr, self.n_kv_heads, self.head_dim).transpose(1, 2) # (B, n_kv_heads, T_curr, head_dim)
|
| 233 |
+
v_curr = self.v_proj(x).view(B, T_curr, self.n_kv_heads, self.head_dim).transpose(1, 2) # (B, n_kv_heads, T_curr, head_dim)
|
| 234 |
+
|
| 235 |
+
# Apply rotary embeddings to the current q and k
|
| 236 |
+
q, k_rotated = apply_rotary_pos_embd(q_curr, k_curr, cos, sin)
|
| 237 |
+
|
| 238 |
+
# Check if we can use cached keys and values
|
| 239 |
+
if not is_prefill and block_kv_cache['key'] is not None:
|
| 240 |
+
# Concatenate with cached K, V
|
| 241 |
+
# k_rotated and v_curr are for the new token(s)
|
| 242 |
+
k = block_kv_cache['key']
|
| 243 |
+
v = block_kv_cache['value']
|
| 244 |
+
k = torch.cat([k, k_rotated], dim=2)
|
| 245 |
+
v = torch.cat([v, v_curr], dim=2)
|
| 246 |
+
block_kv_cache['key'] = k
|
| 247 |
+
block_kv_cache['value'] = v
|
| 248 |
+
else:
|
| 249 |
+
# No cache, this is the first pass (prefill)
|
| 250 |
+
k = k_rotated
|
| 251 |
+
v = v_curr
|
| 252 |
+
block_kv_cache = {'key': k, 'value': v}
|
| 253 |
+
|
| 254 |
+
# Repeat K, V for Grouped Query Attention
|
| 255 |
+
k_exp = k.repeat_interleave(self.n_kv_groups, dim=1) # (B, n_heads, T_kv, head_dim)
|
| 256 |
+
v_exp = v.repeat_interleave(self.n_kv_groups, dim=1) # (B, n_heads, T_kv, head_dim)
|
| 257 |
+
|
| 258 |
+
T_kv = k_exp.size(2) # Total sequence length of keys/values
|
| 259 |
+
|
| 260 |
+
# Prepare attention mask for SDPA or manual path
|
| 261 |
+
# attention_mask is (B, T_kv_total_length), 1 for attend, 0 for pad
|
| 262 |
+
additive_attn_mask = None
|
| 263 |
+
if attention_mask is not None:
|
| 264 |
+
# The current `attention_mask` parameter is assumed to be `[B, total_sequence_length_kv]`
|
| 265 |
+
# Let's make it `[B, 1, 1, T_kv]` for SDPA.
|
| 266 |
+
mask_for_keys = attention_mask[:, :T_kv] # Ensure mask matches key length [B, T_kv]
|
| 267 |
+
additive_attn_mask = (1.0 - mask_for_keys.unsqueeze(1).unsqueeze(2).float()) * torch.finfo(q.dtype).min
|
| 268 |
+
# This additive_attn_mask shape is [B, 1, 1, T_kv]
|
| 269 |
+
|
| 270 |
+
if self.sdpa and x.device.type != 'mps':
|
| 271 |
+
# During decode, no additional masking needed as [1, T_kv] is naturally causal
|
| 272 |
+
is_causal = (T_curr == T_kv and T_curr > 1)
|
| 273 |
+
y = torch.nn.functional.scaled_dot_product_attention(
|
| 274 |
+
q, k_exp, v_exp,
|
| 275 |
+
attn_mask=additive_attn_mask,
|
| 276 |
+
dropout_p=self.dropout if self.training else 0.0,
|
| 277 |
+
is_causal=is_causal
|
| 278 |
+
)
|
| 279 |
+
else:
|
| 280 |
+
# Manual attention implementation
|
| 281 |
+
attn = torch.matmul(q, k_exp.transpose(2, 3)) / math.sqrt(self.head_dim) # (B, n_heads, T_curr, T_kv)
|
| 282 |
+
# During decode: no additional masking needed as [1, T_kv] is naturally causal
|
| 283 |
+
if T_curr == T_kv and T_curr > 1:
|
| 284 |
+
causal_mask_val = torch.tril(torch.ones(T_curr, T_curr, device=x.device, dtype=torch.bool)).view(1, 1, T_curr, T_curr)
|
| 285 |
+
attn = attn.masked_fill(~causal_mask_val, float('-inf'))
|
| 286 |
+
|
| 287 |
+
if additive_attn_mask is not None: # Additive padding mask
|
| 288 |
+
# additive_attn_mask is [B,1,1,T_kv], needs to be broadcast to [B, n_heads, T_curr, T_kv]
|
| 289 |
+
attn = attn + additive_attn_mask
|
| 290 |
+
|
| 291 |
+
attn = F.softmax(attn, dim=-1)
|
| 292 |
+
attn = self.attn_dropout(attn)
|
| 293 |
+
y = attn @ v_exp
|
| 294 |
+
|
| 295 |
+
y = y.transpose(1, 2).contiguous().view(B, T_curr, C)
|
| 296 |
+
y = self.out_proj(y)
|
| 297 |
+
y = self.resid_dropout(y)
|
| 298 |
+
|
| 299 |
+
return y, block_kv_cache
|
| 300 |
+
|
| 301 |
+
# https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py#L160
|
| 302 |
+
class LanguageModelMLP(nn.Module):
|
| 303 |
+
"""
|
| 304 |
+
Implements the feed-forward network (MLP) block used in transformer-based language models.
|
| 305 |
+
|
| 306 |
+
This MLP uses a gated activation mechanism where two separate linear projections
|
| 307 |
+
are applied to the input: one passed through an activation function (gate_proj),
|
| 308 |
+
and the other as is (up_proj). Their element-wise product is then projected back
|
| 309 |
+
to the embedding dimension (down_proj).
|
| 310 |
+
|
| 311 |
+
Args:
|
| 312 |
+
cfg: Configuration object containing:
|
| 313 |
+
- lm_hidden_dim (int): The embedding dimension size.
|
| 314 |
+
- lm_inter_dim (int): The intermediate dimension size for the MLP.
|
| 315 |
+
|
| 316 |
+
Attributes:
|
| 317 |
+
activation_fn (Callable): The activation function used (SiLU).
|
| 318 |
+
gate_proj (nn.Linear): Linear projection for gating pathway.
|
| 319 |
+
up_proj (nn.Linear): Linear projection for upscaling pathway.
|
| 320 |
+
down_proj (nn.Linear): Linear projection for downscaling back to embedding dim.
|
| 321 |
+
"""
|
| 322 |
+
|
| 323 |
+
def __init__(self, cfg):
|
| 324 |
+
super().__init__()
|
| 325 |
+
self.embd_dim = cfg.lm_hidden_dim
|
| 326 |
+
self.inter_dim = cfg.lm_inter_dim
|
| 327 |
+
|
| 328 |
+
self.activation_fn = F.silu
|
| 329 |
+
self.gate_proj = nn.Linear(self.embd_dim, self.inter_dim, bias=False)
|
| 330 |
+
self.up_proj = nn.Linear(self.embd_dim, self.inter_dim, bias=False)
|
| 331 |
+
self.down_proj = nn.Linear(self.inter_dim, self.embd_dim, bias=False)
|
| 332 |
+
|
| 333 |
+
def forward(self, x):
|
| 334 |
+
"""
|
| 335 |
+
Forward pass through the gated MLP block.
|
| 336 |
+
|
| 337 |
+
Args:
|
| 338 |
+
x (Tensor): Input tensor of shape (batch_size, seq_length, embd_dim).
|
| 339 |
+
|
| 340 |
+
Returns:
|
| 341 |
+
Tensor: Output tensor of shape (batch_size, seq_length, embd_dim),
|
| 342 |
+
after gated MLP transformation.
|
| 343 |
+
"""
|
| 344 |
+
gate = self.activation_fn(self.gate_proj(x))
|
| 345 |
+
x = self.up_proj(x)
|
| 346 |
+
x = self.down_proj(gate * x)
|
| 347 |
+
|
| 348 |
+
return x
|
| 349 |
+
|
| 350 |
+
# https://github.com/meta-llama/llama3/blob/main/llama/model.py#L222
|
| 351 |
+
class LanguageModelBlock(nn.Module):
|
| 352 |
+
def __init__(self, cfg):
|
| 353 |
+
super().__init__()
|
| 354 |
+
self.mlp = LanguageModelMLP(cfg)
|
| 355 |
+
self.attn = LanguageModelGroupedQueryAttention(cfg)
|
| 356 |
+
self.norm1 = RMSNorm(cfg) # Input Norm
|
| 357 |
+
self.norm2 = RMSNorm(cfg) # Post Attention Norm
|
| 358 |
+
|
| 359 |
+
def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, attention_mask: torch.Tensor=None, block_kv_cache: dict=None):
|
| 360 |
+
"""
|
| 361 |
+
Forward pass of the Transformer block.
|
| 362 |
+
|
| 363 |
+
Args:
|
| 364 |
+
x (Tensor): Input tensor of shape (batch_size, seq_len, hidden_dim).
|
| 365 |
+
cos (Tensor): Cosine positional embeddings for rotary embedding, shape
|
| 366 |
+
matching sequence length and head dimension.
|
| 367 |
+
sin (Tensor): Sine positional embeddings for rotary embedding, same shape as cos.
|
| 368 |
+
attention_mask (Tensor, optional): Attention mask of shape (batch_size, total_kv_length),
|
| 369 |
+
with 1 indicating tokens to attend to and 0 for padding tokens.
|
| 370 |
+
block_kv_cache (dict, optional): Key-value cache dict for cached keys and values
|
| 371 |
+
during decoding. If None, no cache is used.
|
| 372 |
+
|
| 373 |
+
Returns:
|
| 374 |
+
Tuple[Tensor, dict]: Output tensor after the block (same shape as input),
|
| 375 |
+
and the updated key-value cache dictionary.
|
| 376 |
+
"""
|
| 377 |
+
res = x
|
| 378 |
+
x = self.norm1(x)
|
| 379 |
+
x, block_kv_cache = self.attn(x, cos, sin, attention_mask, block_kv_cache)
|
| 380 |
+
x = res + x
|
| 381 |
+
|
| 382 |
+
res = x
|
| 383 |
+
x = self.norm2(x)
|
| 384 |
+
x = self.mlp(x)
|
| 385 |
+
x = res + x
|
| 386 |
+
|
| 387 |
+
return x, block_kv_cache
|
| 388 |
+
|
| 389 |
+
# https://github.com/meta-llama/llama3/blob/main/llama/model.py#L251
|
| 390 |
+
class LanguageModel(nn.Module):
|
| 391 |
+
def __init__(self, cfg):
|
| 392 |
+
super().__init__()
|
| 393 |
+
self.cfg = cfg
|
| 394 |
+
self.lm_use_tokens = cfg.lm_use_tokens
|
| 395 |
+
self.lm_tie_weights = cfg.lm_tie_weights
|
| 396 |
+
|
| 397 |
+
self.token_embedding = nn.Embedding(cfg.lm_vocab_size, cfg.lm_hidden_dim)
|
| 398 |
+
self.rotary_embd = RotaryEmbedding(cfg)
|
| 399 |
+
self.blocks = nn.ModuleList([
|
| 400 |
+
LanguageModelBlock(cfg) for _ in range(cfg.lm_n_blocks)
|
| 401 |
+
])
|
| 402 |
+
self.norm = RMSNorm(cfg) # Final Norm
|
| 403 |
+
self.head = nn.Linear(cfg.lm_hidden_dim, cfg.lm_vocab_size, bias=False)
|
| 404 |
+
if self.lm_tie_weights:
|
| 405 |
+
self.head.weight = self.token_embedding.weight
|
| 406 |
+
|
| 407 |
+
self.apply(self._init_weights)
|
| 408 |
+
|
| 409 |
+
def _init_weights(self, module):
|
| 410 |
+
if isinstance(module, nn.Linear):
|
| 411 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 412 |
+
if module.bias is not None:
|
| 413 |
+
torch.nn.init.zeros_(module.bias)
|
| 414 |
+
elif isinstance(module, nn.Embedding):
|
| 415 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 416 |
+
elif isinstance(module, RMSNorm):
|
| 417 |
+
module.weight.data.fill_(1.0)
|
| 418 |
+
|
| 419 |
+
def forward(self, x: torch.Tensor, attention_mask: torch.Tensor=None, kv_cache: list[dict]=None, start_pos: int=0):
|
| 420 |
+
"""
|
| 421 |
+
Performs a forward pass through the language model.
|
| 422 |
+
|
| 423 |
+
Args:
|
| 424 |
+
x (Tensor): Input tensor. If `lm_use_tokens` is True, this should be
|
| 425 |
+
token indices with shape (batch_size, sequence_length).
|
| 426 |
+
If False, it should be embeddings of shape (batch_size, sequence_length, hidden_dim).
|
| 427 |
+
attention_mask (Tensor, optional): Mask tensor for attention to
|
| 428 |
+
specify which tokens to attend to, typically of shape
|
| 429 |
+
(batch_size, sequence_length). Default is None.
|
| 430 |
+
kv_cache (list[dict], optional): List of key-value caches for each transformer
|
| 431 |
+
block to enable efficient autoregressive decoding.
|
| 432 |
+
If None, no cache is used and new ones are created. Default is None.
|
| 433 |
+
start_pos (int, optional): The starting position index for the current input
|
| 434 |
+
sequence. Used to compute rotary positional embeddings correctly,
|
| 435 |
+
especially for cached sequences during generation. Default is 0.
|
| 436 |
+
|
| 437 |
+
Returns:
|
| 438 |
+
Tuple:
|
| 439 |
+
- Tensor: Output logits with shape (batch_size, sequence_length, vocab_size)
|
| 440 |
+
if `lm_use_tokens` is True, otherwise the hidden state embeddings
|
| 441 |
+
(batch_size, sequence_length, hidden_dim).
|
| 442 |
+
- list: Updated list of key-value caches, one for each transformer block,
|
| 443 |
+
useful for autoregressive decoding and incremental generation.
|
| 444 |
+
|
| 445 |
+
Behavior:
|
| 446 |
+
- If `lm_use_tokens` is True, the input token indices are first embedded.
|
| 447 |
+
- Rotary positional embeddings are generated for the current input positions,
|
| 448 |
+
which are passed along to each transformer block.
|
| 449 |
+
- For each transformer block, the input is processed along with
|
| 450 |
+
rotary embeddings, attention mask, and optional cached key-values.
|
| 451 |
+
- After processing all blocks, a final RMS normalization is applied.
|
| 452 |
+
- If tokens are used, the normalized hidden states are projected to logits
|
| 453 |
+
over the vocabulary.
|
| 454 |
+
- The method returns the logits or embeddings along with the updated
|
| 455 |
+
cache for efficient decoding.
|
| 456 |
+
"""
|
| 457 |
+
if self.lm_use_tokens:
|
| 458 |
+
x = self.token_embedding(x)
|
| 459 |
+
|
| 460 |
+
# T_curr is the length of the current input sequence
|
| 461 |
+
B, T_curr, _ = x.size()
|
| 462 |
+
|
| 463 |
+
# Create position_ids for the current sequence based on start_pos
|
| 464 |
+
current_position_ids = torch.arange(start_pos, start_pos + T_curr, device=x.device).unsqueeze(0).expand(B, -1)
|
| 465 |
+
cos, sin = self.rotary_embd(current_position_ids) # Get rotary position embeddings for current tokens
|
| 466 |
+
|
| 467 |
+
# Initialize new KV cache if none provided
|
| 468 |
+
if kv_cache is None:
|
| 469 |
+
kv_cache = [None] * len(self.blocks)
|
| 470 |
+
|
| 471 |
+
for i, block in enumerate(self.blocks):
|
| 472 |
+
x, kv_cache[i] = block(x, cos, sin, attention_mask, kv_cache[i])
|
| 473 |
+
|
| 474 |
+
x = self.norm(x)
|
| 475 |
+
|
| 476 |
+
# Compute logits if we are using tokens, otherwise stay in the embedding space
|
| 477 |
+
if self.lm_use_tokens:
|
| 478 |
+
x = self.head(x)
|
| 479 |
+
|
| 480 |
+
return x, kv_cache
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
@torch.inference_mode()
|
| 484 |
+
def generate(self, inputs: torch.Tensor, max_new_tokens: int=20):
|
| 485 |
+
"""
|
| 486 |
+
Generate tokens autoregressively from a given input sequence.
|
| 487 |
+
|
| 488 |
+
Args:
|
| 489 |
+
inputs (torch.Tensor): Input tensor containing token indices or embeddings.
|
| 490 |
+
Shape: (batch_size, sequence_length) or (sequence_length,) for a single sequence.
|
| 491 |
+
max_new_tokens (int): Number of new tokens to generate after the input sequence.
|
| 492 |
+
|
| 493 |
+
Returns:
|
| 494 |
+
torch.Tensor: The generated sequence, including the original inputs and newly generated tokens.
|
| 495 |
+
Shape: (batch_size, sequence_length + max_new_tokens)
|
| 496 |
+
"""
|
| 497 |
+
# Add batch dimension if needed
|
| 498 |
+
if inputs.dim() == 1:
|
| 499 |
+
inputs = inputs.unsqueeze(0)
|
| 500 |
+
generated_outputs = inputs.clone()
|
| 501 |
+
|
| 502 |
+
prompt_output, kv_cache_list = self.forward(
|
| 503 |
+
generated_outputs,
|
| 504 |
+
attention_mask=None,
|
| 505 |
+
kv_cache=None,
|
| 506 |
+
start_pos=0
|
| 507 |
+
)
|
| 508 |
+
last_output = prompt_output[:, -1, :]
|
| 509 |
+
|
| 510 |
+
# Decode Phase with KV cache
|
| 511 |
+
for i in range(max_new_tokens):
|
| 512 |
+
if self.lm_use_tokens:
|
| 513 |
+
# Now the model outputs logits
|
| 514 |
+
next_output = torch.argmax(last_output, dim=-1, keepdim=True)
|
| 515 |
+
else:
|
| 516 |
+
# Now the model outputs embeddings
|
| 517 |
+
next_output = last_output.unsqueeze(1)
|
| 518 |
+
|
| 519 |
+
generated_outputs = torch.cat((generated_outputs, next_output), dim=1)
|
| 520 |
+
|
| 521 |
+
# The token being processed is `next_token`. Its position is `generated_outputs.size(1) - 1`.
|
| 522 |
+
current_token_start_pos = generated_outputs.size(1) - 1
|
| 523 |
+
|
| 524 |
+
if i == max_new_tokens - 1:
|
| 525 |
+
break
|
| 526 |
+
|
| 527 |
+
decode_step_output, kv_cache_list = self.forward(
|
| 528 |
+
next_output,
|
| 529 |
+
attention_mask=None,
|
| 530 |
+
kv_cache=kv_cache_list,
|
| 531 |
+
start_pos=current_token_start_pos
|
| 532 |
+
)
|
| 533 |
+
last_output = decode_step_output[:, -1, :]
|
| 534 |
+
|
| 535 |
+
return generated_outputs
|
| 536 |
+
|
| 537 |
+
# Load the model from a pretrained HuggingFace model (we don't want to have to train the Language Backbone from scratch)
|
| 538 |
+
@classmethod
|
| 539 |
+
def from_pretrained(cls, cfg):
|
| 540 |
+
from transformers import AutoConfig
|
| 541 |
+
from huggingface_hub import hf_hub_download
|
| 542 |
+
import safetensors
|
| 543 |
+
import torch.nn.init as init
|
| 544 |
+
import json
|
| 545 |
+
from huggingface_hub.utils import EntryNotFoundError
|
| 546 |
+
|
| 547 |
+
# Load the HuggingFace config
|
| 548 |
+
hf_config = AutoConfig.from_pretrained(cfg.lm_model_type)
|
| 549 |
+
|
| 550 |
+
# Store original HF vocab size before we modify it
|
| 551 |
+
original_vocab_size = hf_config.vocab_size
|
| 552 |
+
# print(f"Original vocabulary size from pretrained model: {original_vocab_size}")
|
| 553 |
+
|
| 554 |
+
# Configure model parameters from HF config
|
| 555 |
+
cfg.lm_hidden_dim = hf_config.hidden_size
|
| 556 |
+
cfg.lm_inter_dim = hf_config.intermediate_size
|
| 557 |
+
cfg.lm_rms_eps = hf_config.rms_norm_eps
|
| 558 |
+
cfg.lm_re_base = hf_config.rope_theta
|
| 559 |
+
cfg.lm_max_position_embeddings = hf_config.max_position_embeddings
|
| 560 |
+
# We're keeping our own vocab size in cfg, but checking it's larger than original
|
| 561 |
+
if hasattr(cfg, 'lm_vocab_size'):
|
| 562 |
+
if cfg.lm_vocab_size < original_vocab_size:
|
| 563 |
+
raise ValueError(f"Config vocab size ({cfg.lm_vocab_size}) is smaller than pretrained model vocab size ({original_vocab_size})")
|
| 564 |
+
# print(f"Using vocabulary size: {cfg.lm_vocab_size}")
|
| 565 |
+
else:
|
| 566 |
+
# If not specified, use the original
|
| 567 |
+
cfg.lm_vocab_size = original_vocab_size
|
| 568 |
+
# print(f"Using original vocabulary size: {cfg.lm_vocab_size}")
|
| 569 |
+
|
| 570 |
+
cfg.lm_n_heads = hf_config.num_attention_heads
|
| 571 |
+
cfg.lm_n_kv_heads = hf_config.num_key_value_heads
|
| 572 |
+
cfg.lm_dropout = hf_config.attention_dropout
|
| 573 |
+
cfg.lm_n_blocks = hf_config.num_hidden_layers
|
| 574 |
+
|
| 575 |
+
# Create our model with potentially larger vocabulary
|
| 576 |
+
model = cls(cfg)
|
| 577 |
+
|
| 578 |
+
try:
|
| 579 |
+
index_path = hf_hub_download(repo_id=cfg.lm_model_type, filename="model.safetensors.index.json")
|
| 580 |
+
with open(index_path, 'r') as f:
|
| 581 |
+
index = json.load(f)
|
| 582 |
+
# Get unique filenames from weight map
|
| 583 |
+
safetensors_filenames = sorted(list(set(index['weight_map'].values())))
|
| 584 |
+
# Download all the sharded files
|
| 585 |
+
safetensors_files = [hf_hub_download(repo_id=cfg.lm_model_type, filename=fn) for fn in safetensors_filenames]
|
| 586 |
+
except EntryNotFoundError:
|
| 587 |
+
safetensors_files = [hf_hub_download(repo_id=cfg.lm_model_type, filename="model.safetensors")]
|
| 588 |
+
|
| 589 |
+
sd = model.state_dict()
|
| 590 |
+
|
| 591 |
+
mapping = {
|
| 592 |
+
'model.embed_tokens.weight': 'token_embedding.weight',
|
| 593 |
+
'model.norm.weight': 'norm.weight'
|
| 594 |
+
}
|
| 595 |
+
|
| 596 |
+
for i in range(cfg.lm_n_blocks):
|
| 597 |
+
layer_prefix = f'model.layers.{i}.'
|
| 598 |
+
block_prefix = f'blocks.{i}.'
|
| 599 |
+
|
| 600 |
+
mapping.update({
|
| 601 |
+
f"{layer_prefix}self_attn.q_proj.weight": f"{block_prefix}attn.q_proj.weight",
|
| 602 |
+
f"{layer_prefix}self_attn.k_proj.weight": f"{block_prefix}attn.k_proj.weight",
|
| 603 |
+
f"{layer_prefix}self_attn.v_proj.weight": f"{block_prefix}attn.v_proj.weight",
|
| 604 |
+
f"{layer_prefix}self_attn.o_proj.weight": f"{block_prefix}attn.out_proj.weight",
|
| 605 |
+
f"{layer_prefix}mlp.gate_proj.weight": f"{block_prefix}mlp.gate_proj.weight",
|
| 606 |
+
f"{layer_prefix}mlp.up_proj.weight": f"{block_prefix}mlp.up_proj.weight",
|
| 607 |
+
f"{layer_prefix}mlp.down_proj.weight": f"{block_prefix}mlp.down_proj.weight",
|
| 608 |
+
f"{layer_prefix}input_layernorm.weight": f"{block_prefix}norm1.weight",
|
| 609 |
+
f"{layer_prefix}post_attention_layernorm.weight": f"{block_prefix}norm2.weight"
|
| 610 |
+
})
|
| 611 |
+
|
| 612 |
+
# Special handling for token embeddings with extended vocabulary
|
| 613 |
+
has_extended_embeddings = False
|
| 614 |
+
loaded_keys = set()
|
| 615 |
+
|
| 616 |
+
for safetensors_file in safetensors_files:
|
| 617 |
+
with safetensors.safe_open(filename=safetensors_file, framework="pt", device="cpu") as f:
|
| 618 |
+
for hf_key, our_key in mapping.items():
|
| 619 |
+
if our_key in loaded_keys:
|
| 620 |
+
continue
|
| 621 |
+
|
| 622 |
+
if hf_key in f.keys() and our_key in sd:
|
| 623 |
+
tensor = f.get_tensor(hf_key)
|
| 624 |
+
|
| 625 |
+
# Special handling for token embeddings if vocab sizes differ
|
| 626 |
+
if hf_key == 'model.embed_tokens.weight' and tensor.shape[0] != sd[our_key].shape[0]:
|
| 627 |
+
has_extended_embeddings = True
|
| 628 |
+
print(f"Extending token embeddings from {tensor.shape} to {sd[our_key].shape}")
|
| 629 |
+
|
| 630 |
+
# Copy existing embeddings to the beginning of our larger embedding matrix
|
| 631 |
+
sd[our_key][:tensor.shape[0]].copy_(tensor)
|
| 632 |
+
|
| 633 |
+
# Initialize the new embeddings using the same approach as the original model
|
| 634 |
+
std = 0.02 # Common value, but you might want to adjust based on model
|
| 635 |
+
init.normal_(sd[our_key][tensor.shape[0]:], mean=0.0, std=std)
|
| 636 |
+
|
| 637 |
+
print(f"Initialized {sd[our_key].shape[0] - tensor.shape[0]} new token embeddings")
|
| 638 |
+
sd['head.weight'].copy_(sd[our_key]) # Update the head weights as well
|
| 639 |
+
elif tensor.shape == sd[our_key].shape:
|
| 640 |
+
sd[our_key].copy_(tensor)
|
| 641 |
+
else:
|
| 642 |
+
print(f"Shape mismatch for {hf_key} -> {our_key}: {tensor.shape} vs {sd[our_key].shape}")
|
| 643 |
+
|
| 644 |
+
loaded_keys.add(our_key)
|
| 645 |
+
|
| 646 |
+
for hf_key, our_key in mapping.items():
|
| 647 |
+
if our_key not in loaded_keys:
|
| 648 |
+
if our_key in sd:
|
| 649 |
+
print(f"Warning: Key {our_key} not found in any safetensors file (HF key: {hf_key})")
|
| 650 |
+
|
| 651 |
+
# Load the state dict
|
| 652 |
+
model.load_state_dict(sd)
|
| 653 |
+
|
| 654 |
+
# Handle output projection / language modeling head
|
| 655 |
+
if has_extended_embeddings and hasattr(model, 'head') and 'head.weight' in sd:
|
| 656 |
+
# If we have a separate output projection layer and extended the vocab
|
| 657 |
+
# we should handle it similarly to the input embeddings
|
| 658 |
+
lm_head_loaded = False
|
| 659 |
+
for safetensors_file in safetensors_files:
|
| 660 |
+
with safetensors.safe_open(filename=safetensors_file, framework="pt", device="cpu") as f:
|
| 661 |
+
if 'lm_head.weight' in f.keys():
|
| 662 |
+
lm_head = f.get_tensor('lm_head.weight')
|
| 663 |
+
if lm_head.shape[0] != sd['head.weight'].shape[0]:
|
| 664 |
+
print(f"Extending LM head from {lm_head.shape} to {sd['head.weight'].shape}")
|
| 665 |
+
# Copy existing weights
|
| 666 |
+
sd['head.weight'][:lm_head.shape[0]].copy_(lm_head)
|
| 667 |
+
# Initialize new weights
|
| 668 |
+
std = 0.02
|
| 669 |
+
init.normal_(sd['head.weight'][lm_head.shape[0]:], mean=0.0, std=std)
|
| 670 |
+
# Load updated weights
|
| 671 |
+
model.load_state_dict(sd)
|
| 672 |
+
lm_head_loaded = True
|
| 673 |
+
break
|
| 674 |
+
|
| 675 |
+
# Handle weight tying (if needed)
|
| 676 |
+
if cfg.lm_tie_weights and hasattr(model, 'head') and hasattr(model, 'token_embedding'):
|
| 677 |
+
model.head.weight = model.token_embedding.weight
|
| 678 |
+
# print("Tied token embedding and LM head weights")
|
| 679 |
+
|
| 680 |
+
print(f"Successfully loaded {cfg.lm_model_type} weights from safetensors. Model has {sum(p.numel() for p in model.parameters()):,} parameters.")
|
| 681 |
+
return model
|
src/models/modality_projector.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Modality Projection from Vision to Language
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
class ModalityProjector(nn.Module):
|
| 5 |
+
def __init__(self, cfg):
|
| 6 |
+
super().__init__()
|
| 7 |
+
self.cfg = cfg
|
| 8 |
+
self.input_dim = cfg.vit_hidden_dim * (cfg.mp_pixel_shuffle_factor**2)
|
| 9 |
+
self.output_dim = cfg.lm_hidden_dim
|
| 10 |
+
self.scale_factor = cfg.mp_pixel_shuffle_factor
|
| 11 |
+
|
| 12 |
+
self.proj = nn.Linear(self.input_dim, self.output_dim, bias=False)
|
| 13 |
+
|
| 14 |
+
self.apply(self._init_weights)
|
| 15 |
+
|
| 16 |
+
def _init_weights(self, module):
|
| 17 |
+
if isinstance(module, nn.Linear):
|
| 18 |
+
nn.init.normal_(self.proj.weight, mean=0.0, std=0.02)
|
| 19 |
+
if module.bias is not None:
|
| 20 |
+
nn.init.zeros_(module.bias)
|
| 21 |
+
|
| 22 |
+
# https://github.com/huggingface/smollm/blob/main/vision/m4/models/vllama3/modeling_vllama3.py#L1281
|
| 23 |
+
def pixel_shuffle(self, x):
|
| 24 |
+
bsz, seq, embed_dim = x.size()
|
| 25 |
+
seq_root = int(seq**0.5)
|
| 26 |
+
assert seq_root**2 == seq # Sequence length must be a perfect square for pixel shuffle
|
| 27 |
+
assert seq_root % self.scale_factor == 0 # Sequence root must be divisible by scale factor
|
| 28 |
+
|
| 29 |
+
height = width = seq_root
|
| 30 |
+
x = x.view(bsz, height, width, embed_dim)
|
| 31 |
+
h_out = height // self.scale_factor
|
| 32 |
+
w_out = width // self.scale_factor
|
| 33 |
+
|
| 34 |
+
x = x.reshape(bsz, h_out, self.scale_factor, w_out, self.scale_factor, embed_dim)
|
| 35 |
+
x = x.permute(0, 1, 3, 2, 4, 5).contiguous()
|
| 36 |
+
x = x.reshape(bsz, h_out * w_out, embed_dim * self.scale_factor**2)
|
| 37 |
+
|
| 38 |
+
return x
|
| 39 |
+
|
| 40 |
+
def forward(self, x):
|
| 41 |
+
x = self.pixel_shuffle(x)
|
| 42 |
+
x = self.proj(x)
|
| 43 |
+
|
| 44 |
+
return x
|
| 45 |
+
|
| 46 |
+
|
src/models/utils.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
# Used to check our models performance on multiple choice tasks. This can also be done in a more involved way with e.g. LLM-as-a-judge
|
| 5 |
+
def check_multiple_choice_with_regex(model_outputs, correct_answers):
|
| 6 |
+
results = []
|
| 7 |
+
for model_output, correct_answer in zip(model_outputs, correct_answers):
|
| 8 |
+
# Strip any trailing newlines and convert to uppercase
|
| 9 |
+
correct_answer = correct_answer.rstrip('\n').upper()
|
| 10 |
+
|
| 11 |
+
# Look for the answer letter at the beginning of a line or as the last word
|
| 12 |
+
patterns = [
|
| 13 |
+
rf"\b{correct_answer}\b", # Word boundary around the answer letter
|
| 14 |
+
rf"\b{correct_answer}[.,)]", # Answer followed by punctuation
|
| 15 |
+
rf"\(.*{correct_answer}.*\)", # Answer within parentheses
|
| 16 |
+
]
|
| 17 |
+
|
| 18 |
+
match_found = False
|
| 19 |
+
for pattern in patterns:
|
| 20 |
+
if re.search(pattern, model_output):
|
| 21 |
+
match_found = True
|
| 22 |
+
break # Exit inner loop once a match is found
|
| 23 |
+
results.append(match_found)
|
| 24 |
+
return results
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def top_k_top_p_filtering(logits, top_k=0, top_p=1.0, filter_value=-float('Inf')):
|
| 28 |
+
"""
|
| 29 |
+
Apply top-k and/or nucleus (top-p) filtering to logits.
|
| 30 |
+
"""
|
| 31 |
+
top_k = min(top_k, logits.size(-1)) # Safety
|
| 32 |
+
|
| 33 |
+
if top_k > 0:
|
| 34 |
+
# Remove all tokens with a probability less than the top-k tokens
|
| 35 |
+
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
|
| 36 |
+
logits = logits.masked_fill(indices_to_remove, filter_value)
|
| 37 |
+
|
| 38 |
+
if top_p < 1.0:
|
| 39 |
+
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
|
| 40 |
+
cumulative_probs = torch.softmax(sorted_logits, dim=-1).cumsum(dim=-1)
|
| 41 |
+
|
| 42 |
+
# Remove tokens with cumulative probability above top_p
|
| 43 |
+
sorted_indices_to_remove = cumulative_probs > top_p
|
| 44 |
+
|
| 45 |
+
# Always keep the first token
|
| 46 |
+
sorted_indices_to_remove[..., 0] = False
|
| 47 |
+
|
| 48 |
+
indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
|
| 49 |
+
logits = logits.masked_fill(indices_to_remove, filter_value)
|
| 50 |
+
|
| 51 |
+
return logits
|
src/models/vision_language_model.py
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import tempfile
|
| 4 |
+
from dataclasses import asdict
|
| 5 |
+
from typing import Optional
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
from models.utils import top_k_top_p_filtering
|
| 9 |
+
from models.vision_transformer import ViT
|
| 10 |
+
from models.language_model import LanguageModel
|
| 11 |
+
from models.modality_projector import ModalityProjector
|
| 12 |
+
from models.config import VLMConfig
|
| 13 |
+
|
| 14 |
+
from data.processors import get_tokenizer
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn as nn
|
| 18 |
+
import torch.nn.functional as F
|
| 19 |
+
from safetensors.torch import load_model, save_model
|
| 20 |
+
|
| 21 |
+
class VisionLanguageModel(nn.Module):
|
| 22 |
+
def __init__(self, cfg: VLMConfig, load_backbone=True):
|
| 23 |
+
super().__init__()
|
| 24 |
+
self.cfg = cfg
|
| 25 |
+
if load_backbone:
|
| 26 |
+
print("Loading from backbone weights")
|
| 27 |
+
self.vision_encoder = ViT.from_pretrained(cfg)
|
| 28 |
+
self.decoder = LanguageModel.from_pretrained(cfg)
|
| 29 |
+
else:
|
| 30 |
+
self.vision_encoder = ViT(cfg)
|
| 31 |
+
self.decoder = LanguageModel(cfg)
|
| 32 |
+
self.MP = ModalityProjector(cfg)
|
| 33 |
+
self.load_backbone = load_backbone
|
| 34 |
+
self.tokenizer = get_tokenizer(cfg.lm_tokenizer, cfg.vlm_extra_tokens, cfg.lm_chat_template)
|
| 35 |
+
|
| 36 |
+
def _replace_img_tokens_with_embd(self, input_ids, token_embd, image_embd):
|
| 37 |
+
"""
|
| 38 |
+
Replace every image-token placeholder in `input_ids` with the corresponding slice
|
| 39 |
+
from `image_embd`. Supports an arbitrary number of image-token placeholders per sample.
|
| 40 |
+
The first example in the batch might have 2 images and the second none.
|
| 41 |
+
"""
|
| 42 |
+
# Clone the original embeddings to avoid in-place issues
|
| 43 |
+
updated_token_embd = token_embd.clone()
|
| 44 |
+
|
| 45 |
+
# Build a mask of all image-token positions: shape [B, T_seq]
|
| 46 |
+
mask = (input_ids == self.tokenizer.image_token_id)
|
| 47 |
+
updated_token_embd[mask] = image_embd.view(-1, image_embd.size(-1)).to(updated_token_embd.dtype) # torch flattens before assigning
|
| 48 |
+
|
| 49 |
+
return updated_token_embd
|
| 50 |
+
|
| 51 |
+
def _process_images(self, images, device):
|
| 52 |
+
if isinstance(images, list):
|
| 53 |
+
if images and isinstance(images[0], list):
|
| 54 |
+
images = [img for sublist in images for img in sublist]
|
| 55 |
+
|
| 56 |
+
if not images: # Handle cases with no images
|
| 57 |
+
return None
|
| 58 |
+
else:
|
| 59 |
+
return torch.cat(images, dim=0).to(device)
|
| 60 |
+
return images # Already a tensor
|
| 61 |
+
|
| 62 |
+
def forward(self, input_ids, images, attention_mask=None, targets=None):
|
| 63 |
+
images_tensor = self._process_images(images, input_ids.device)
|
| 64 |
+
token_embd = self.decoder.token_embedding(input_ids) # [B, T_sequence, D_lm]
|
| 65 |
+
|
| 66 |
+
if images_tensor is not None:
|
| 67 |
+
image_embd = self.vision_encoder(images_tensor)
|
| 68 |
+
image_embd = self.MP(image_embd) # [num_images, mp_image_token_length, D_lm]
|
| 69 |
+
token_embd = self._replace_img_tokens_with_embd(input_ids, token_embd, image_embd)
|
| 70 |
+
|
| 71 |
+
logits, _ = self.decoder(token_embd, attention_mask=attention_mask)
|
| 72 |
+
|
| 73 |
+
loss = None
|
| 74 |
+
if targets is not None:
|
| 75 |
+
logits = self.decoder.head(logits) # Apply LM head
|
| 76 |
+
# Loss is calculated over all tokens, but `targets` (labels) will have -100 for non-answer tokens.
|
| 77 |
+
# No need to slice logits based on image embedding size here, as the target mask handles it.
|
| 78 |
+
loss = F.cross_entropy(logits.reshape(-1, logits.size(-1)), targets.reshape(-1), ignore_index=-100)
|
| 79 |
+
|
| 80 |
+
return logits, loss
|
| 81 |
+
|
| 82 |
+
@torch.inference_mode()
|
| 83 |
+
def generate(self, input_ids, images, attention_mask=None, max_new_tokens=5, top_k=50, top_p=0.9, temperature=0.5, greedy=False):
|
| 84 |
+
images_tensor = self._process_images(images, input_ids.device)
|
| 85 |
+
token_embd = self.decoder.token_embedding(input_ids) # [B, T_prompt_text, D_lm]
|
| 86 |
+
|
| 87 |
+
if images_tensor is not None:
|
| 88 |
+
# 1. Process image if present
|
| 89 |
+
image_embd = self.vision_encoder(images_tensor) # [B, T_img_feat, D_model]
|
| 90 |
+
image_embd = self.MP(image_embd) # [B, mp_image_token_length, D_lm]
|
| 91 |
+
# 2. Combine image and text embeddings
|
| 92 |
+
token_embd = self._replace_img_tokens_with_embd(input_ids, token_embd, image_embd)
|
| 93 |
+
|
| 94 |
+
current_total_seq_len = token_embd.size(1)
|
| 95 |
+
batch_size = input_ids.size(0) # Or token_embd.size(0)
|
| 96 |
+
|
| 97 |
+
# --- Multimodal Prefill Phase ---
|
| 98 |
+
prefill_output, kv_cache_list = self.decoder(
|
| 99 |
+
token_embd,
|
| 100 |
+
attention_mask=attention_mask, # Use the provided attention mask
|
| 101 |
+
kv_cache=None,
|
| 102 |
+
start_pos=0
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
last_token_output_from_prefill = prefill_output[:, -1, :]
|
| 106 |
+
|
| 107 |
+
if not self.decoder.lm_use_tokens:
|
| 108 |
+
current_logits = self.decoder.head(last_token_output_from_prefill)
|
| 109 |
+
else:
|
| 110 |
+
current_logits = last_token_output_from_prefill
|
| 111 |
+
|
| 112 |
+
# Store newly generated token IDs
|
| 113 |
+
newly_generated_ids_list = []
|
| 114 |
+
|
| 115 |
+
# --- Decode Phase by sampling tokens autoregressively using the kv-cache ---
|
| 116 |
+
for _ in range(max_new_tokens):
|
| 117 |
+
if greedy:
|
| 118 |
+
next_token_id = torch.argmax(current_logits, dim=-1, keepdim=True)
|
| 119 |
+
else:
|
| 120 |
+
filtered_logits = top_k_top_p_filtering(current_logits, top_k=top_k, top_p=top_p)
|
| 121 |
+
probs = torch.softmax(filtered_logits / temperature, dim=-1)
|
| 122 |
+
next_token_id = torch.multinomial(probs, num_samples=1)
|
| 123 |
+
|
| 124 |
+
newly_generated_ids_list.append(next_token_id)
|
| 125 |
+
|
| 126 |
+
# Embed the newly generated token
|
| 127 |
+
next_token_embed = self.decoder.token_embedding(next_token_id) # [B, 1, D_lm]
|
| 128 |
+
|
| 129 |
+
# The start_pos for the new token is the current total sequence length *before* adding this new token
|
| 130 |
+
current_token_start_pos = current_total_seq_len
|
| 131 |
+
current_total_seq_len += 1
|
| 132 |
+
|
| 133 |
+
# update attention mask
|
| 134 |
+
if attention_mask is not None:
|
| 135 |
+
attention_mask = torch.cat((attention_mask, torch.ones((batch_size, 1), device=attention_mask.device, dtype=attention_mask.dtype)), dim=1)
|
| 136 |
+
|
| 137 |
+
# With KV cache: only process the new token
|
| 138 |
+
decode_step_output, kv_cache_list = self.decoder(
|
| 139 |
+
next_token_embed,
|
| 140 |
+
attention_mask=attention_mask,
|
| 141 |
+
kv_cache=kv_cache_list,
|
| 142 |
+
start_pos=current_token_start_pos
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
last_token_output = decode_step_output[:, -1, :]
|
| 146 |
+
|
| 147 |
+
# Apply head to get logits (if model is in embedding mode)
|
| 148 |
+
if not self.decoder.lm_use_tokens:
|
| 149 |
+
current_logits = self.decoder.head(last_token_output)
|
| 150 |
+
else:
|
| 151 |
+
current_logits = last_token_output
|
| 152 |
+
|
| 153 |
+
if not newly_generated_ids_list: # Handle case where max_new_tokens might be 0
|
| 154 |
+
return torch.empty((batch_size,0), dtype=torch.long, device=input_ids.device)
|
| 155 |
+
|
| 156 |
+
generated_ids = torch.cat(newly_generated_ids_list, dim=1)
|
| 157 |
+
|
| 158 |
+
# Post-process to handle EOS token.
|
| 159 |
+
if self.tokenizer.eos_token_id is not None and generated_ids.numel() > 0: # Ensure generated_ids is not empty
|
| 160 |
+
seq_len = generated_ids.size(1)
|
| 161 |
+
device = generated_ids.device
|
| 162 |
+
|
| 163 |
+
eos_mask = (generated_ids == self.tokenizer.eos_token_id) # Create a boolean mask for EOS tokens
|
| 164 |
+
|
| 165 |
+
col_indices_for_min = torch.arange(seq_len, device=device) # Create column indices [0, 1, ..., seq_len-1]
|
| 166 |
+
|
| 167 |
+
# In eos_mask, mark positions with actual col_idx, others with a large number
|
| 168 |
+
masked_col_indices = torch.where(eos_mask, col_indices_for_min.unsqueeze(0).expand_as(generated_ids), seq_len + 1)
|
| 169 |
+
|
| 170 |
+
first_eos_indices_values = torch.min(masked_col_indices, dim=1).values
|
| 171 |
+
|
| 172 |
+
# Clamp values to seq_len (if no EOS found, min will be seq_len + 1, clamp brings it to seq_len0. This means if no EOS, or EOS is the last token, no replacement will happen for that sample.
|
| 173 |
+
actual_first_eos_indices = torch.clamp(first_eos_indices_values, max=seq_len)
|
| 174 |
+
|
| 175 |
+
# Create column indices for comparison, shape [batch_size, seq_len]
|
| 176 |
+
col_indices_for_comparison = torch.arange(seq_len, device=device).unsqueeze(0).expand_as(generated_ids)
|
| 177 |
+
|
| 178 |
+
# Tokens are replaced if their column index is greater than the index of the first EOS token
|
| 179 |
+
replace_mask = col_indices_for_comparison > actual_first_eos_indices.unsqueeze(1)
|
| 180 |
+
|
| 181 |
+
generated_ids[replace_mask] = self.tokenizer.eos_token_id
|
| 182 |
+
|
| 183 |
+
return generated_ids
|
| 184 |
+
|
| 185 |
+
@classmethod
|
| 186 |
+
def from_pretrained(
|
| 187 |
+
cls, repo_id_or_path: str, *, revision: Optional[str] = None
|
| 188 |
+
) -> "VisionLanguageModel":
|
| 189 |
+
"""
|
| 190 |
+
Load a VisionLanguageModel from a local directory or a repo on the Hugging Face Hub.
|
| 191 |
+
|
| 192 |
+
Args:
|
| 193 |
+
repo_id_or_path (str): The path to the local directory or the Hugging Face Hub repo ID.
|
| 194 |
+
|
| 195 |
+
Returns:
|
| 196 |
+
VisionLanguageModel: The loaded model.
|
| 197 |
+
"""
|
| 198 |
+
# If local folder exists => load from there
|
| 199 |
+
if os.path.exists(repo_id_or_path):
|
| 200 |
+
config_path = os.path.join(repo_id_or_path, "config.json")
|
| 201 |
+
weights_path = os.path.join(repo_id_or_path, "model.safetensors")
|
| 202 |
+
|
| 203 |
+
if not os.path.exists(config_path):
|
| 204 |
+
raise ValueError(
|
| 205 |
+
f"Config file not found at {config_path}. Please provide a valid path."
|
| 206 |
+
)
|
| 207 |
+
if not os.path.exists(weights_path):
|
| 208 |
+
raise ValueError(
|
| 209 |
+
f"Weights file not found at {weights_path}. Please provide a valid path."
|
| 210 |
+
)
|
| 211 |
+
# Otherwise, assume it's a Hugging Face Hub repo
|
| 212 |
+
else:
|
| 213 |
+
from huggingface_hub import hf_hub_download
|
| 214 |
+
|
| 215 |
+
config_path = hf_hub_download(
|
| 216 |
+
repo_id=repo_id_or_path, filename="config.json", revision=revision
|
| 217 |
+
)
|
| 218 |
+
weights_path = hf_hub_download(
|
| 219 |
+
repo_id=repo_id_or_path, filename="model.safetensors", revision=revision
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
# Load config
|
| 223 |
+
with open(config_path, "r") as f:
|
| 224 |
+
cfg = VLMConfig(**json.load(f))
|
| 225 |
+
|
| 226 |
+
# Initialize model without loading the backbone
|
| 227 |
+
model = cls(cfg, load_backbone=False)
|
| 228 |
+
|
| 229 |
+
# Load safetensors weights
|
| 230 |
+
load_model(model, weights_path)
|
| 231 |
+
|
| 232 |
+
# Done!
|
| 233 |
+
return model
|
| 234 |
+
|
| 235 |
+
def save_pretrained(self, save_directory: str) -> None:
|
| 236 |
+
"""
|
| 237 |
+
Save the model and configuration to a directory.
|
| 238 |
+
|
| 239 |
+
Args:
|
| 240 |
+
save_directory (str): The directory to save the model and config.
|
| 241 |
+
"""
|
| 242 |
+
# Create directory if it doesn't exist
|
| 243 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 244 |
+
|
| 245 |
+
# Save config
|
| 246 |
+
with open(os.path.join(save_directory, "config.json"), "w") as f:
|
| 247 |
+
f.write(json.dumps(asdict(self.cfg), indent=4))
|
| 248 |
+
|
| 249 |
+
# Save weights as safetensors
|
| 250 |
+
save_model(self, os.path.join(save_directory, "model.safetensors"))
|
| 251 |
+
|
| 252 |
+
def push_to_hub(self, repo_id: str, private: bool = False) -> None:
|
| 253 |
+
"""
|
| 254 |
+
Push the model and configuration to the Hugging Face Hub.
|
| 255 |
+
|
| 256 |
+
Args:
|
| 257 |
+
repo_id (str): The repo ID on the Hugging Face Hub.
|
| 258 |
+
"""
|
| 259 |
+
from huggingface_hub import create_repo, upload_folder
|
| 260 |
+
|
| 261 |
+
# Create repo
|
| 262 |
+
repo_url = create_repo(repo_id=repo_id, private=private, exist_ok=True)
|
| 263 |
+
repo_id = repo_url.repo_id
|
| 264 |
+
print("Created repo: ", repo_url)
|
| 265 |
+
|
| 266 |
+
with tempfile.TemporaryDirectory() as save_path:
|
| 267 |
+
# Save to tmp directory
|
| 268 |
+
self.save_pretrained(save_path)
|
| 269 |
+
|
| 270 |
+
# Save model card
|
| 271 |
+
with open(os.path.join(save_path, "README.md"), "w") as f:
|
| 272 |
+
f.write(MODEL_CARD_TEMPLATE.format(repo_id=repo_id))
|
| 273 |
+
|
| 274 |
+
# Upload
|
| 275 |
+
return upload_folder(
|
| 276 |
+
repo_id=repo_id,
|
| 277 |
+
repo_type="model",
|
| 278 |
+
folder_path=save_path,
|
| 279 |
+
commit_message="Upload nanoVLM using push_to_hub",
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
MODEL_CARD_TEMPLATE = """
|
| 284 |
+
---
|
| 285 |
+
# For reference on model card metadata, see the spec: https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1
|
| 286 |
+
# Doc / guide: https://huggingface.co/docs/hub/model-cards
|
| 287 |
+
library_name: nanovlm
|
| 288 |
+
license: mit
|
| 289 |
+
pipeline_tag: image-text-to-text
|
| 290 |
+
tags:
|
| 291 |
+
- vision-language
|
| 292 |
+
- multimodal
|
| 293 |
+
- research
|
| 294 |
+
---
|
| 295 |
+
|
| 296 |
+
**nanoVLM** is a minimal and lightweight Vision-Language Model (VLM) designed for efficient training and experimentation. Built using pure PyTorch, the entire model architecture and training logic fits within ~750 lines of code. It combines a ViT-based image encoder (SigLIP-B/16-224-85M) with a lightweight causal language model (SmolLM2-135M), resulting in a compact 222M parameter model.
|
| 297 |
+
|
| 298 |
+
For more information, check out the base model on https://huggingface.co/lusxvr/nanoVLM-222M.
|
| 299 |
+
|
| 300 |
+
**Usage:**
|
| 301 |
+
|
| 302 |
+
Clone the nanoVLM repository: https://github.com/huggingface/nanoVLM.
|
| 303 |
+
Follow the install instructions and run the following code:
|
| 304 |
+
|
| 305 |
+
```python
|
| 306 |
+
from models.vision_language_model import VisionLanguageModel
|
| 307 |
+
|
| 308 |
+
model = VisionLanguageModel.from_pretrained("{repo_id}")
|
| 309 |
+
```
|
| 310 |
+
"""
|
src/models/vision_transformer.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
|
| 6 |
+
# https://github.com/huggingface/transformers/blob/main/src/transformers/models/siglip/modeling_siglip.py#L245
|
| 7 |
+
class ViTPatchEmbeddings(nn.Module):
|
| 8 |
+
def __init__(self, cfg):
|
| 9 |
+
super().__init__()
|
| 10 |
+
|
| 11 |
+
self.img_size = cfg.vit_img_size
|
| 12 |
+
self.patch_size = cfg.vit_patch_size
|
| 13 |
+
self.num_patches = (self.img_size // self.patch_size) ** 2
|
| 14 |
+
self.cls_flag = cfg.vit_cls_flag
|
| 15 |
+
self.embd_dim = cfg.vit_hidden_dim
|
| 16 |
+
|
| 17 |
+
# Conv layer to extract the patches
|
| 18 |
+
self.conv = nn.Conv2d(
|
| 19 |
+
in_channels=3,
|
| 20 |
+
out_channels=self.embd_dim,
|
| 21 |
+
kernel_size=self.patch_size,
|
| 22 |
+
stride=self.patch_size,
|
| 23 |
+
padding="valid",
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
if self.cls_flag:
|
| 27 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, self.embd_dim))
|
| 28 |
+
self.position_embedding = nn.Parameter(torch.rand(1, self.num_patches + 1, self.embd_dim))
|
| 29 |
+
else:
|
| 30 |
+
self.position_embedding = nn.Parameter(torch.rand(1, self.num_patches, self.embd_dim))
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def forward(self, x):
|
| 34 |
+
x = self.conv(x) # extract patches
|
| 35 |
+
x = x.flatten(2) # flatten the patches into a single dimension
|
| 36 |
+
x = x.transpose(1, 2) # transpose to (batch_size, num_patches, hidden_dim)
|
| 37 |
+
|
| 38 |
+
# Add CLS token (according to original ViT Paper) and position embeddings
|
| 39 |
+
if self.cls_flag:
|
| 40 |
+
cls_token = self.cls_token.expand(x.shape[0], -1, -1)
|
| 41 |
+
x = torch.cat((cls_token, x), dim=1)
|
| 42 |
+
x = x + self.position_embedding
|
| 43 |
+
return x
|
| 44 |
+
|
| 45 |
+
# https://github.com/huggingface/transformers/blob/main/src/transformers/models/siglip/modeling_siglip.py#L381
|
| 46 |
+
# https://github.com/karpathy/nanoGPT/blob/master/model.py#L29
|
| 47 |
+
class ViTMultiHeadAttention(nn.Module):
|
| 48 |
+
def __init__(self, cfg):
|
| 49 |
+
super().__init__()
|
| 50 |
+
|
| 51 |
+
self.n_heads = cfg.vit_n_heads
|
| 52 |
+
self.embd_dim = cfg.vit_hidden_dim
|
| 53 |
+
assert self.embd_dim % self.n_heads == 0, "embd_dim must be divisible by num_heads"
|
| 54 |
+
self.head_dim = self.embd_dim // self.n_heads
|
| 55 |
+
self.dropout = cfg.vit_dropout
|
| 56 |
+
|
| 57 |
+
# Combined projections for all heads
|
| 58 |
+
self.qkv_proj = nn.Linear(self.embd_dim, 3 * self.embd_dim, bias=True)
|
| 59 |
+
self.out_proj = nn.Linear(self.embd_dim, self.embd_dim, bias=True)
|
| 60 |
+
|
| 61 |
+
# Dropout layers
|
| 62 |
+
self.attn_dropout = nn.Dropout(self.dropout)
|
| 63 |
+
self.resid_dropout = nn.Dropout(self.dropout)
|
| 64 |
+
|
| 65 |
+
# Use scaled dot product attention if available
|
| 66 |
+
self.sdpa = hasattr(torch.nn.functional, 'scaled_dot_product_attention')
|
| 67 |
+
if not self.sdpa:
|
| 68 |
+
print("Warning: scaled dot product attention not available. Using standard attention in ViT.")
|
| 69 |
+
|
| 70 |
+
def forward(self, x):
|
| 71 |
+
B, T, C = x.size()
|
| 72 |
+
|
| 73 |
+
qkv = self.qkv_proj(x)
|
| 74 |
+
q, k, v = qkv.split(C, dim=2)
|
| 75 |
+
# Reshape [B, T, C] -> [B, T, n_heads, head_dim] and transpose -> [B, n_heads, T, head_dim]
|
| 76 |
+
q = q.view(B, T, self.n_heads, self.head_dim).transpose(1, 2) # (B, n_heads, T, head_dim)
|
| 77 |
+
k = k.view(B, T, self.n_heads, self.head_dim).transpose(1, 2) # (B, n_heads, T, head_dim)
|
| 78 |
+
v = v.view(B, T, self.n_heads, self.head_dim).transpose(1, 2) # (B, n_heads, T, head_dim)
|
| 79 |
+
|
| 80 |
+
if self.sdpa:
|
| 81 |
+
y = torch.nn.functional.scaled_dot_product_attention(
|
| 82 |
+
q, k, v,
|
| 83 |
+
attn_mask=None,
|
| 84 |
+
dropout_p=self.dropout if self.training else 0.0,
|
| 85 |
+
is_causal=False # ViT attention is bidirectional
|
| 86 |
+
)
|
| 87 |
+
else:
|
| 88 |
+
attn = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
|
| 89 |
+
attn = F.softmax(attn, dim=-1)
|
| 90 |
+
attn = self.attn_dropout(attn)
|
| 91 |
+
y = attn @ v # (B, n_heads, T, T) x (B, n_heads, T, head_dim) -> (B, n_heads, T, head_dim)
|
| 92 |
+
|
| 93 |
+
# Transpose back from [B, n_heads, T, head_dim] to [B, T, n_heads * head_dim] and combine all heads to [B, T, C]
|
| 94 |
+
y = y.transpose(1, 2).contiguous().view(B, T, C)
|
| 95 |
+
y = self.out_proj(y)
|
| 96 |
+
y = self.resid_dropout(y)
|
| 97 |
+
|
| 98 |
+
return y
|
| 99 |
+
|
| 100 |
+
# https://github.com/huggingface/transformers/blob/main/src/transformers/models/siglip/modeling_siglip.py#L453
|
| 101 |
+
class ViTMLP(nn.Module):
|
| 102 |
+
def __init__(self, cfg):
|
| 103 |
+
super().__init__()
|
| 104 |
+
self.activation_fn = nn.GELU(approximate='tanh')
|
| 105 |
+
self.fc1 = nn.Linear(cfg.vit_hidden_dim, cfg.vit_inter_dim)
|
| 106 |
+
self.fc2 = nn.Linear(cfg.vit_inter_dim, cfg.vit_hidden_dim)
|
| 107 |
+
self.dropout = nn.Dropout(cfg.vit_dropout)
|
| 108 |
+
|
| 109 |
+
def forward(self, x):
|
| 110 |
+
x = self.fc1(x)
|
| 111 |
+
x = self.activation_fn(x)
|
| 112 |
+
x = self.fc2(x)
|
| 113 |
+
x = self.dropout(x)
|
| 114 |
+
return x
|
| 115 |
+
|
| 116 |
+
# https://github.com/karpathy/nanoGPT/blob/master/model.py#L94
|
| 117 |
+
class ViTBlock(nn.Module):
|
| 118 |
+
def __init__(self, cfg):
|
| 119 |
+
super().__init__()
|
| 120 |
+
self.ln1 = nn.LayerNorm(cfg.vit_hidden_dim, eps=cfg.vit_ln_eps)
|
| 121 |
+
self.attn = ViTMultiHeadAttention(cfg)
|
| 122 |
+
self.ln2 = nn.LayerNorm(cfg.vit_hidden_dim, eps=cfg.vit_ln_eps)
|
| 123 |
+
self.mlp = ViTMLP(cfg)
|
| 124 |
+
|
| 125 |
+
def forward(self, x):
|
| 126 |
+
x = x + self.attn(self.ln1(x))
|
| 127 |
+
x = x + self.mlp(self.ln2(x))
|
| 128 |
+
return x
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class ViT(nn.Module):
|
| 132 |
+
def __init__(self, cfg):
|
| 133 |
+
super().__init__()
|
| 134 |
+
self.cfg = cfg
|
| 135 |
+
self.patch_embedding = ViTPatchEmbeddings(cfg)
|
| 136 |
+
self.cls_flag = cfg.vit_cls_flag
|
| 137 |
+
self.dropout = nn.Dropout(cfg.vit_dropout)
|
| 138 |
+
self.blocks = nn.ModuleList([ViTBlock(cfg) for _ in range(cfg.vit_n_blocks)])
|
| 139 |
+
self.layer_norm = nn.LayerNorm(cfg.vit_hidden_dim, eps=cfg.vit_ln_eps)
|
| 140 |
+
|
| 141 |
+
self.apply(self._init_weights)
|
| 142 |
+
|
| 143 |
+
def _init_weights(self, module):
|
| 144 |
+
if isinstance(module, nn.Linear):
|
| 145 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 146 |
+
if module.bias is not None:
|
| 147 |
+
torch.nn.init.zeros_(module.bias)
|
| 148 |
+
elif isinstance(module, nn.LayerNorm):
|
| 149 |
+
module.bias.data.zero_()
|
| 150 |
+
module.weight.data.fill_(1.0)
|
| 151 |
+
elif isinstance(module, nn.Conv2d):
|
| 152 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 153 |
+
if module.bias is not None:
|
| 154 |
+
torch.nn.init.zeros_(module.bias)
|
| 155 |
+
|
| 156 |
+
def forward(self, x):
|
| 157 |
+
x = self.patch_embedding(x)
|
| 158 |
+
x = self.dropout(x)
|
| 159 |
+
for block in self.blocks:
|
| 160 |
+
x = block(x)
|
| 161 |
+
|
| 162 |
+
if self.cls_flag:
|
| 163 |
+
x = self.layer_norm(x[:, 0])
|
| 164 |
+
else:
|
| 165 |
+
x = self.layer_norm(x)
|
| 166 |
+
#x = x.mean(dim=1)
|
| 167 |
+
|
| 168 |
+
return x
|
| 169 |
+
|
| 170 |
+
# Load the model from a pretrained HuggingFace model (we don't want to have to train the Vision Backbone from scratch)
|
| 171 |
+
@classmethod
|
| 172 |
+
def from_pretrained(cls, cfg):
|
| 173 |
+
from transformers import SiglipVisionConfig
|
| 174 |
+
from huggingface_hub import hf_hub_download
|
| 175 |
+
import safetensors
|
| 176 |
+
|
| 177 |
+
hf_config = SiglipVisionConfig.from_pretrained(cfg.vit_model_type)
|
| 178 |
+
cfg.vit_dropout=hf_config.attention_dropout
|
| 179 |
+
cfg.vit_hidden_dim=hf_config.hidden_size
|
| 180 |
+
cfg.vit_img_size=hf_config.image_size
|
| 181 |
+
cfg.vit_inter_dim=hf_config.intermediate_size
|
| 182 |
+
cfg.vit_ln_eps=hf_config.layer_norm_eps
|
| 183 |
+
cfg.vit_n_heads=hf_config.num_attention_heads
|
| 184 |
+
cfg.vit_n_blocks=hf_config.num_hidden_layers
|
| 185 |
+
cfg.vit_patch_size=hf_config.patch_size
|
| 186 |
+
model = cls(cfg)
|
| 187 |
+
safetensors_file = hf_hub_download(repo_id=cfg.vit_model_type, filename="model.safetensors")
|
| 188 |
+
|
| 189 |
+
sd = model.state_dict()
|
| 190 |
+
|
| 191 |
+
mapping = {
|
| 192 |
+
'vision_model.embeddings.patch_embedding.weight': 'patch_embedding.conv.weight',
|
| 193 |
+
'vision_model.embeddings.patch_embedding.bias': 'patch_embedding.conv.bias',
|
| 194 |
+
'vision_model.embeddings.position_embedding.weight': 'patch_embedding.position_embedding',
|
| 195 |
+
'vision_model.post_layernorm.weight': 'layer_norm.weight',
|
| 196 |
+
'vision_model.post_layernorm.bias': 'layer_norm.bias',
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
for i in range(cfg.vit_n_blocks):
|
| 200 |
+
# Layer norms
|
| 201 |
+
mapping[f'vision_model.encoder.layers.{i}.layer_norm1.weight'] = f'blocks.{i}.ln1.weight'
|
| 202 |
+
mapping[f'vision_model.encoder.layers.{i}.layer_norm1.bias'] = f'blocks.{i}.ln1.bias'
|
| 203 |
+
mapping[f'vision_model.encoder.layers.{i}.layer_norm2.weight'] = f'blocks.{i}.ln2.weight'
|
| 204 |
+
mapping[f'vision_model.encoder.layers.{i}.layer_norm2.bias'] = f'blocks.{i}.ln2.bias'
|
| 205 |
+
|
| 206 |
+
# MLP
|
| 207 |
+
mapping[f'vision_model.encoder.layers.{i}.mlp.fc1.weight'] = f'blocks.{i}.mlp.fc1.weight'
|
| 208 |
+
mapping[f'vision_model.encoder.layers.{i}.mlp.fc1.bias'] = f'blocks.{i}.mlp.fc1.bias'
|
| 209 |
+
mapping[f'vision_model.encoder.layers.{i}.mlp.fc2.weight'] = f'blocks.{i}.mlp.fc2.weight'
|
| 210 |
+
mapping[f'vision_model.encoder.layers.{i}.mlp.fc2.bias'] = f'blocks.{i}.mlp.fc2.bias'
|
| 211 |
+
|
| 212 |
+
# Output projection
|
| 213 |
+
mapping[f'vision_model.encoder.layers.{i}.self_attn.out_proj.weight'] = f'blocks.{i}.attn.out_proj.weight'
|
| 214 |
+
mapping[f'vision_model.encoder.layers.{i}.self_attn.out_proj.bias'] = f'blocks.{i}.attn.out_proj.bias'
|
| 215 |
+
|
| 216 |
+
with safetensors.safe_open(filename=safetensors_file, framework="pt", device="cpu") as f:
|
| 217 |
+
for hf_key, our_key in mapping.items():
|
| 218 |
+
if hf_key in f.keys() and our_key in sd:
|
| 219 |
+
tensor = f.get_tensor(hf_key)
|
| 220 |
+
if tensor.shape == sd[our_key].shape:
|
| 221 |
+
sd[our_key].copy_(tensor)
|
| 222 |
+
else:
|
| 223 |
+
if 'position_embedding' in hf_key:
|
| 224 |
+
sd[our_key].copy_(tensor.unsqueeze(0))
|
| 225 |
+
else:
|
| 226 |
+
print(f"Shape mismatch for {hf_key} -> {our_key}: {tensor.shape} vs {sd[our_key].shape}")
|
| 227 |
+
else:
|
| 228 |
+
if hf_key not in f.keys():
|
| 229 |
+
print(f"Warning: Key {hf_key} not found in safetensors file")
|
| 230 |
+
if our_key not in sd:
|
| 231 |
+
print(f"Warning: Key {our_key} not found in model state dict")
|
| 232 |
+
|
| 233 |
+
# Manually handle QKV concatenation since our implementation combines Q, K, V into one
|
| 234 |
+
for i in range(model.cfg.vit_n_blocks):
|
| 235 |
+
q_weight = f.get_tensor(f'vision_model.encoder.layers.{i}.self_attn.q_proj.weight')
|
| 236 |
+
k_weight = f.get_tensor(f'vision_model.encoder.layers.{i}.self_attn.k_proj.weight')
|
| 237 |
+
v_weight = f.get_tensor(f'vision_model.encoder.layers.{i}.self_attn.v_proj.weight')
|
| 238 |
+
|
| 239 |
+
qkv_weight = torch.cat((q_weight, k_weight, v_weight), dim=0)
|
| 240 |
+
sd[f'blocks.{i}.attn.qkv_proj.weight'].copy_(qkv_weight)
|
| 241 |
+
|
| 242 |
+
q_bias = f.get_tensor(f'vision_model.encoder.layers.{i}.self_attn.q_proj.bias')
|
| 243 |
+
k_bias = f.get_tensor(f'vision_model.encoder.layers.{i}.self_attn.k_proj.bias')
|
| 244 |
+
v_bias = f.get_tensor(f'vision_model.encoder.layers.{i}.self_attn.v_proj.bias')
|
| 245 |
+
|
| 246 |
+
qkv_bias = torch.cat((q_bias, k_bias, v_bias), dim=0)
|
| 247 |
+
sd[f'blocks.{i}.attn.qkv_proj.bias'].copy_(qkv_bias)
|
| 248 |
+
|
| 249 |
+
model.load_state_dict(sd)
|
| 250 |
+
print(f"Successfully loaded {cfg.vit_model_type} weights from safetensors. Model has {sum(p.numel() for p in model.parameters()):,} parameters.")
|
| 251 |
+
return model
|