T

Diffusers
Safetensors
chenzeyang1 commited on
Commit
a8a0738
·
verified ·
1 Parent(s): 964f845

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. llava/data/__init__.py +11 -0
  2. llava/data/frozen_vlm_ip2p_cached_dataset.py +260 -0
  3. llava/data/frozen_vlm_ip2p_dataset.py +501 -0
  4. llava/data/thermal_templates.txt +17 -0
  5. llava/data/vlm_guided_ip2p_dataset.py +486 -0
  6. llava/eval/table/answer/answer_alpaca-13b.jsonl +80 -0
  7. llava/eval/table/answer/answer_bard.jsonl +0 -0
  8. llava/eval/table/answer/answer_gpt35.jsonl +0 -0
  9. llava/eval/table/answer/answer_llama-13b.jsonl +80 -0
  10. llava/eval/table/answer/answer_vicuna-13b.jsonl +0 -0
  11. llava/eval/table/caps_boxes_coco2014_val_80.jsonl +80 -0
  12. llava/eval/table/model.jsonl +5 -0
  13. llava/eval/table/prompt.jsonl +4 -0
  14. llava/eval/table/question.jsonl +80 -0
  15. llava/eval/table/results/test_sqa_llava_lcs_558k_sqa_12e_vicuna_v1_3_13b.json +0 -0
  16. llava/eval/table/reviewer.jsonl +4 -0
  17. llava/eval/table/rule.json +11 -0
  18. llava/eval/webpage/index.html +162 -0
  19. llava/eval/webpage/script.js +245 -0
  20. llava/eval/webpage/styles.css +105 -0
  21. llava/model/__init__.py +35 -0
  22. llava/model/builder.py +172 -0
  23. llava/model/dual_branch_unet.py +237 -0
  24. llava/model/ella_resampler.py +329 -0
  25. llava/model/ella_resampler_v3.py +329 -0
  26. llava/model/frozen_llava_extractor.py +308 -0
  27. llava/model/img_token_utils.py +716 -0
  28. llava/model/language_model/llava_llama.py +224 -0
  29. llava/model/language_model/llava_llama_mgie.py +470 -0
  30. llava/model/language_model/llava_mistral.py +158 -0
  31. llava/model/language_model/llava_mpt.py +97 -0
  32. llava/model/llava_arch.py +393 -0
  33. llava/model/make_delta.py +52 -0
  34. llava/model/multimodal_encoder/builder.py +15 -0
  35. llava/model/multimodal_encoder/clip_encoder.py +147 -0
  36. llava/model/multimodal_projector/builder.py +51 -0
  37. llava/model/unet_processors.py +460 -0
  38. llava/model/utils.py +20 -0
  39. llava/model/vlm_attention_processor_v3.py +435 -0
  40. llava/model/vlm_resampler.py +201 -0
  41. llava/serve/__init__.py +0 -0
  42. llava/serve/cli.py +126 -0
  43. llava/serve/controller.py +298 -0
  44. llava/serve/examples/extreme_ironing.jpg +0 -0
  45. llava/serve/examples/waterview.jpg +0 -0
  46. llava/serve/gradio_web_server.py +479 -0
  47. llava/serve/model_worker.py +288 -0
  48. llava/serve/register_worker.py +26 -0
  49. llava/serve/sglang_worker.py +244 -0
  50. llava/serve/test_message.py +62 -0
llava/data/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Data loading utilities for LLaVA training.
3
+ """
4
+
5
+ from .vlm_guided_ip2p_dataset import VLMGuidedIP2PDataset, create_dataloaders
6
+
7
+ __all__ = [
8
+ 'VLMGuidedIP2PDataset',
9
+ 'create_dataloaders',
10
+ ]
11
+
llava/data/frozen_vlm_ip2p_cached_dataset.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from typing import List, Dict, Optional, Tuple
4
+
5
+ import torch
6
+ from torch.utils.data import Dataset, DataLoader
7
+ import torch.distributed as dist
8
+ from torch.utils.data.distributed import DistributedSampler
9
+ from torchvision import transforms
10
+ from PIL import Image
11
+
12
+
13
+ class FrozenVLMIP2PCachedDataset(Dataset):
14
+ """
15
+ Dataset that loads RGB/TIR pairs and cached LLaVA hidden states.
16
+
17
+ Expected layout per sample (VIVID-only for now):
18
+ - rgb path: .../MIRAGE_HD/train/VIVID/<seq>/RGB/xxxx.png
19
+ - tir path: .../MIRAGE_HD/train/VIVID/<seq>/TIR/xxxx.png
20
+ - cache path: .../MIRAGE_HD/train/VIVID/<seq>/LLaVa_cache/xxxx.pt (tensor [L, 4096])
21
+
22
+ Notes:
23
+ - We assume fixed image preprocessing for diffusion (256x256, normalized to [-1, 1]).
24
+ - Cached hidden states can be variable-length L; we return per-item tensors and let collate_fn pad.
25
+ - Horizontal flips must be disabled to keep caches aligned with RGBs (flip_p=0.0).
26
+ """
27
+
28
+ def __init__(
29
+ self,
30
+ pairs_json: str,
31
+ image_roots: List[str],
32
+ split: str = "train",
33
+ size: int = 256,
34
+ flip_p: float = 0.0,
35
+ dataset_filter: Optional[str] = "VIVID",
36
+ ) -> None:
37
+ super().__init__()
38
+
39
+ self.image_roots = image_roots
40
+ self.split = split
41
+ self.flip_p = flip_p
42
+
43
+ # transforms for diffusion tensors
44
+ self.transform = transforms.Compose([
45
+ transforms.Resize(size, interpolation=transforms.InterpolationMode.BILINEAR),
46
+ transforms.CenterCrop(size),
47
+ transforms.ToTensor(),
48
+ transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]),
49
+ ])
50
+
51
+ with open(pairs_json, 'r') as f:
52
+ data = json.load(f)
53
+
54
+ # Filter to split by folder heuristic and dataset name (VIVID only for now)
55
+ def in_split(path: str) -> bool:
56
+ return ("/train/" in path) if split == "train" else ("/val/" in path)
57
+
58
+ items: List[Dict] = []
59
+ for it in data:
60
+ # Exclude FLIR entirely (train and val)
61
+ if it.get('dataset') == 'FLIR':
62
+ continue
63
+ if dataset_filter and it.get('dataset') != dataset_filter:
64
+ continue
65
+ if not in_split(it.get('rgb', '')):
66
+ continue
67
+ items.append(it)
68
+
69
+ if len(items) == 0:
70
+ raise ValueError(f"No items found for split={split}, dataset={dataset_filter}")
71
+
72
+ self.items = items
73
+
74
+ def __len__(self) -> int:
75
+ return len(self.items)
76
+
77
+ def _resolve(self, rel_path: str) -> str:
78
+ # Try each root; return first that exists
79
+ for root in self.image_roots:
80
+ full = os.path.join(root, rel_path)
81
+ if os.path.exists(full):
82
+ return full
83
+ # fallback to first root even if missing (better error message later)
84
+ return os.path.join(self.image_roots[0], rel_path)
85
+
86
+ @staticmethod
87
+ def _cache_path_from_rgb(rgb_path: str) -> str:
88
+ # .../<SEQ>/RGB/xxxx.png -> .../<SEQ>/LLaVa_cache/xxxx.pt
89
+ seq_dir, last = os.path.split(os.path.dirname(rgb_path)) # seq_dir/.../RGB
90
+ cache_dir = os.path.join(seq_dir, 'LLaVa_cache')
91
+ base = os.path.splitext(os.path.basename(rgb_path))[0] + '.pt'
92
+ return os.path.join(cache_dir, base)
93
+
94
+ def __getitem__(self, idx: int) -> Dict:
95
+ it = self.items[idx]
96
+
97
+ rgb_path = self._resolve(it['rgb'])
98
+ tir_path = self._resolve(it['thermal'])
99
+ cache_rel = self._cache_path_from_rgb(it['rgb'])
100
+ cache_path = self._resolve(cache_rel)
101
+
102
+ # Load images
103
+ rgb_img = Image.open(rgb_path).convert('RGB')
104
+ tir_img = Image.open(tir_path).convert('RGB')
105
+
106
+ # Optional safety: if size mismatch, resize TIR to RGB size
107
+ if rgb_img.size != tir_img.size:
108
+ tir_img = tir_img.resize(rgb_img.size, Image.Resampling.BILINEAR)
109
+
110
+ # Keep original PIL for potential debugging; training uses tensors
111
+ if self.flip_p > 0.0:
112
+ # no flip for cached setup; preserve alignment
113
+ pass
114
+
115
+ rgb_tensor = self.transform(rgb_img)
116
+ tir_tensor = self.transform(tir_img)
117
+
118
+ # Load cached hidden states [L, 4096] (dtype can be fp32/bf16/fp16)
119
+ hs = torch.load(cache_path, map_location='cpu')
120
+ if not isinstance(hs, torch.Tensor):
121
+ hs = torch.tensor(hs)
122
+
123
+ # Safety check: detect NaN values in cached LLaVA features
124
+ if torch.isnan(hs).any():
125
+ print(f"WARNING: NaN detected in cached LLaVA features: {cache_path}")
126
+ print(f" RGB: {rgb_path}")
127
+ print(f" TIR: {tir_path}")
128
+ print(f" Shape: {hs.shape}, dtype: {hs.dtype}")
129
+ print(f" NaN count: {torch.isnan(hs).sum().item()}")
130
+
131
+ # Option 1: Replace NaN with zeros (conservative)
132
+ hs = torch.where(torch.isnan(hs), torch.zeros_like(hs), hs)
133
+ print(f" -> Replaced NaN with zeros")
134
+
135
+ # Option 2: Skip this sample entirely (uncomment to use)
136
+ # print(f" -> Skipping this sample")
137
+ # return self._create_dummy_sample()
138
+
139
+ # Additional safety: check for infinite values
140
+ if torch.isinf(hs).any():
141
+ print(f"WARNING: Inf detected in cached LLaVA features: {cache_path}")
142
+ print(f" Inf count: {torch.isinf(hs).sum().item()}")
143
+ hs = torch.where(torch.isinf(hs), torch.zeros_like(hs), hs)
144
+ print(f" -> Replaced Inf with zeros")
145
+
146
+ # Check for extremely large values that might cause instability
147
+ max_val = hs.abs().max().item()
148
+ if max_val > 100.0: # Arbitrary threshold
149
+ print(f"WARNING: Large values in cached LLaVA features: {cache_path}")
150
+ print(f" Max absolute value: {max_val}")
151
+ # Optionally clamp extreme values
152
+ hs = torch.clamp(hs, min=-50.0, max=50.0)
153
+ print(f" -> Clamped to [-50, 50]")
154
+
155
+ sample = {
156
+ 'rgb': rgb_tensor,
157
+ 'thermal': tir_tensor,
158
+ 'vlm_hidden': hs, # [L, 4096], variable L
159
+ 'sequence': it.get('sequence', 'unknown'),
160
+ 'dataset': it.get('dataset', 'unknown'),
161
+ 'id': it.get('id', os.path.basename(rgb_path)),
162
+ 'rgb_path': rgb_path,
163
+ 'tir_path': tir_path,
164
+ 'cache_path': cache_path,
165
+ }
166
+ return sample
167
+
168
+
169
+ def pad_collate_cached(batch: List[Dict]) -> Dict:
170
+ """Pad variable-length vlm_hidden to max L in batch and build mask.
171
+
172
+ Returns keys:
173
+ - rgb: [B, 3, H, W]
174
+ - thermal: [B, 3, H, W]
175
+ - vlm_hidden: [B, L_max, 4096]
176
+ - vlm_mask: [B, L_max] (1 for real, 0 for pad)
177
+ - ids, sequence, dataset, paths
178
+ """
179
+ B = len(batch)
180
+ rgb = torch.stack([b['rgb'] for b in batch], dim=0)
181
+ thermal = torch.stack([b['thermal'] for b in batch], dim=0)
182
+
183
+ lengths = [b['vlm_hidden'].shape[0] for b in batch]
184
+ L_max = max(lengths)
185
+ D = batch[0]['vlm_hidden'].shape[1]
186
+
187
+ vlm = torch.zeros((B, L_max, D), dtype=batch[0]['vlm_hidden'].dtype)
188
+ mask = torch.zeros((B, L_max), dtype=torch.bool)
189
+ for i, b in enumerate(batch):
190
+ L = b['vlm_hidden'].shape[0]
191
+ vlm[i, :L] = b['vlm_hidden']
192
+ mask[i, :L] = True
193
+
194
+ out = {
195
+ 'rgb': rgb,
196
+ 'thermal': thermal,
197
+ 'vlm_hidden': vlm,
198
+ 'vlm_mask': mask,
199
+ 'id': [b['id'] for b in batch],
200
+ 'sequence': [b['sequence'] for b in batch],
201
+ 'dataset': [b['dataset'] for b in batch],
202
+ 'rgb_path': [b['rgb_path'] for b in batch],
203
+ 'tir_path': [b['tir_path'] for b in batch],
204
+ 'cache_path': [b['cache_path'] for b in batch],
205
+ }
206
+ return out
207
+
208
+
209
+ def create_cached_dataloaders(
210
+ pairs_json: str,
211
+ image_roots: List[str],
212
+ batch_size: int = 16,
213
+ num_workers: int = 8,
214
+ size: int = 256,
215
+ dataset_filter: Optional[str] = "VIVID",
216
+ ) -> Tuple[DataLoader, DataLoader]:
217
+ train_ds = FrozenVLMIP2PCachedDataset(
218
+ pairs_json=pairs_json,
219
+ image_roots=image_roots,
220
+ split="train",
221
+ size=size,
222
+ flip_p=0.0,
223
+ dataset_filter=dataset_filter,
224
+ )
225
+ val_ds = FrozenVLMIP2PCachedDataset(
226
+ pairs_json=pairs_json,
227
+ image_roots=image_roots,
228
+ split="val",
229
+ size=size,
230
+ flip_p=0.0,
231
+ dataset_filter=dataset_filter,
232
+ )
233
+
234
+ # Use DistributedSampler when running with DDP/torchrun
235
+ use_ddp = dist.is_available() and dist.is_initialized()
236
+ train_sampler = DistributedSampler(train_ds, shuffle=True) if use_ddp else None
237
+ # Shuffle val to get diverse sequences across ranks
238
+ val_sampler = DistributedSampler(val_ds, shuffle=True) if use_ddp else None
239
+
240
+ train_dl = DataLoader(
241
+ train_ds,
242
+ batch_size=batch_size,
243
+ shuffle=(train_sampler is None),
244
+ sampler=train_sampler,
245
+ num_workers=num_workers,
246
+ pin_memory=True,
247
+ collate_fn=pad_collate_cached,
248
+ drop_last=True,
249
+ )
250
+ val_dl = DataLoader(
251
+ val_ds,
252
+ batch_size=1,
253
+ shuffle=False if val_sampler is not None else True,
254
+ sampler=val_sampler,
255
+ num_workers=num_workers,
256
+ pin_memory=True,
257
+ collate_fn=pad_collate_cached,
258
+ )
259
+ return train_dl, val_dl
260
+
llava/data/frozen_vlm_ip2p_dataset.py ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Dataset for Frozen VLM-guided InstructPix2Pix Training
3
+
4
+ Key features:
5
+ 1. Per-sequence train/val split (98:2) to avoid temporal leakage
6
+ 2. Excludes FLIR/M3FD/DTUAV/visdrone (for later domain adaptation)
7
+ 3. Uses VTMOT_test/VIVID/NSAVP sequences
8
+ 4. Separate prompts for CLIP (simple) and LLaVA (detailed)
9
+ 5. Resizes to 256×256 (matching IP2P checkpoint)
10
+ """
11
+
12
+ import json
13
+ import os
14
+ import random
15
+ from typing import List, Dict, Tuple
16
+ from PIL import Image
17
+
18
+ import torch
19
+ from torch.utils.data import Dataset, DataLoader
20
+ from torch.utils.data.distributed import DistributedSampler
21
+ import torch.distributed as dist
22
+ from torchvision import transforms
23
+
24
+
25
+ class FrozenVLMIP2PDataset(Dataset):
26
+ """
27
+ Dataset for training Frozen VLM-guided InstructPix2Pix.
28
+
29
+ Returns:
30
+ - rgb_image: RGB input (256×256)
31
+ - thermal_image: Thermal ground truth (256×256)
32
+ - clip_prompt: Simple prompt for CLIP text encoder
33
+ - llava_prompt: Detailed prompt for frozen LLaVA
34
+ - metadata: Additional info (sequence, dataset, etc.)
35
+ """
36
+ def __init__(
37
+ self,
38
+ json_path: str,
39
+ image_folder: str, # Can be a single folder or list of folders
40
+ split: str = "train",
41
+ thermal_templates_path: str = "llava/data/thermal_templates.txt",
42
+ size: int = 256,
43
+ flip_p: float = 0.0, # No flip for now (thermal may not be symmetric)
44
+ train_split_ratio: float = 0.98, # Train/val split ratio (default 98:2)
45
+ ):
46
+ super().__init__()
47
+
48
+ self.json_path = json_path
49
+ # Support multiple image folder roots
50
+ if isinstance(image_folder, str):
51
+ self.image_folders = [image_folder]
52
+ else:
53
+ self.image_folders = image_folder
54
+ self.split = split
55
+ self.train_split_ratio = train_split_ratio
56
+ self.size = size
57
+ self.flip_p = flip_p
58
+
59
+ # Load thermal templates for CLIP
60
+ self.thermal_templates = self._load_thermal_templates(thermal_templates_path)
61
+
62
+ # Load and filter data
63
+ self.data = self._load_and_filter_data()
64
+
65
+ # Split by sequence
66
+ self.data = self._split_by_sequence()
67
+
68
+ print(f"[{split.upper()}] Loaded {len(self.data)} samples from {len(set(s['sequence'] for s in self.data))} sequences")
69
+
70
+ # Transforms
71
+ self.transform = transforms.Compose([
72
+ transforms.Resize(self.size, interpolation=transforms.InterpolationMode.BILINEAR),
73
+ transforms.CenterCrop(self.size),
74
+ transforms.ToTensor(),
75
+ transforms.Normalize([0.5], [0.5]), # [-1, 1]
76
+ ])
77
+
78
+ def _load_thermal_templates(self, path: str) -> List[str]:
79
+ """Load CLIP prompt templates"""
80
+ if not os.path.exists(path):
81
+ # Default templates
82
+ return [
83
+ "turn this into thermal infrared image",
84
+ "convert to thermal infrared",
85
+ "transform to thermal image",
86
+ ]
87
+
88
+ with open(path, 'r') as f:
89
+ templates = [line.strip() for line in f if line.strip()]
90
+ return templates
91
+
92
+ def _load_and_filter_data(self) -> List[Dict]:
93
+ """
94
+ Load JSON and filter out excluded datasets.
95
+ Exclude: FLIR, M3FD, DTUAV, visdrone (even if they're in IR500k)
96
+ Include: IR500k, VTMOT_test, VIVID, NSAVP, CAMEL, MetuVis, STheReO, TRI2I, others
97
+
98
+ Supports two JSON formats:
99
+ 1. Old format: {"image": "path/to/RGB/file.jpg", ...}
100
+ 2. New format: {"rgb": "path/to/rgb.jpg", "thermal": "path/to/thermal.jpg", ...}
101
+ """
102
+ with open(self.json_path, 'r') as f:
103
+ data = json.load(f)
104
+
105
+ # Always exclude these datasets (including typo variant DUTUAV)
106
+ # Note: FLIR and M3FD are now included in training
107
+ excluded_keywords = ['DTUAV', 'DUTUAV', 'visdrone']
108
+
109
+ filtered_data = []
110
+ for item in data:
111
+ # Handle both old and new JSON formats
112
+ if 'rgb' in item and 'thermal' in item:
113
+ # New format with explicit rgb/thermal paths
114
+ rgb_path = item['rgb']
115
+ thermal_path = item['thermal']
116
+ elif 'image' in item:
117
+ # Old format with single image path
118
+ rgb_path = item['image']
119
+ thermal_path = rgb_path.replace('/RGB/', '/TIR/')
120
+ else:
121
+ print(f"Warning: Item has neither 'rgb'/'thermal' nor 'image' key: {item}")
122
+ continue
123
+
124
+ # Check if any excluded keyword is in the paths
125
+ if any(keyword.lower() in rgb_path.lower() for keyword in excluded_keywords):
126
+ continue
127
+ if any(keyword.lower() in thermal_path.lower() for keyword in excluded_keywords):
128
+ continue
129
+
130
+ # Extract sequence name from path
131
+ # Format: "dataset/sequence/RGB/file.jpg" or "MIRAGE_HD/VIVID/seq_001/RGB/frame_0001.jpg"
132
+ path_parts = rgb_path.split('/')
133
+
134
+ # Find sequence name (parent of RGB)
135
+ sequence = item.get('sequence') # Use existing if available
136
+ if sequence is None:
137
+ for i, part in enumerate(path_parts):
138
+ if part == 'RGB' and i > 0:
139
+ sequence = path_parts[i-1]
140
+ break
141
+
142
+ if sequence is None:
143
+ print(f"Warning: Could not extract sequence from {rgb_path}")
144
+ continue
145
+
146
+ # Store normalized paths
147
+ item['rgb'] = rgb_path
148
+ item['thermal'] = thermal_path
149
+ item['sequence'] = sequence
150
+ if 'dataset' not in item:
151
+ item['dataset'] = path_parts[0] if len(path_parts) > 0 else 'unknown'
152
+
153
+ filtered_data.append(item)
154
+
155
+ print(f"Filtered {len(filtered_data)} samples (excluded DTUAV/visdrone)")
156
+ print(f" Includes: All MIRAGE_HD datasets (FLIR/M3FD/AVIID1/MSRS/VIVID/NSAVP/VTMOT/IR500K)")
157
+
158
+ return filtered_data
159
+
160
+ def _split_by_sequence(self) -> List[Dict]:
161
+ """
162
+ Split data by sequence to avoid temporal leakage.
163
+ Uses configurable train_split_ratio (default 95:5).
164
+ """
165
+ # Group by sequence
166
+ sequences = {}
167
+ for item in self.data:
168
+ seq = item['sequence']
169
+ if seq not in sequences:
170
+ sequences[seq] = []
171
+ sequences[seq].append(item)
172
+
173
+ # Sort sequences for reproducibility
174
+ sorted_sequences = sorted(sequences.keys())
175
+
176
+ # Split sequences using configurable ratio
177
+ random.seed(42) # Reproducible split
178
+
179
+ # Ensure 'unknown' sequence (largest) goes to training
180
+ if 'unknown' in sorted_sequences:
181
+ sorted_sequences.remove('unknown')
182
+ random.shuffle(sorted_sequences)
183
+ # Put 'unknown' at the beginning so it goes to training
184
+ sorted_sequences = ['unknown'] + sorted_sequences
185
+ else:
186
+ random.shuffle(sorted_sequences)
187
+
188
+ split_idx = int(len(sorted_sequences) * self.train_split_ratio)
189
+ train_sequences = set(sorted_sequences[:split_idx])
190
+ val_sequences = set(sorted_sequences[split_idx:])
191
+
192
+ print(f"Split: {len(train_sequences)} train sequences, {len(val_sequences)} val sequences")
193
+
194
+ # Filter data based on split
195
+ if self.split == "train":
196
+ split_data = [item for item in self.data if item['sequence'] in train_sequences]
197
+ else: # val
198
+ split_data = [item for item in self.data if item['sequence'] in val_sequences]
199
+
200
+ if len(split_data) == 0:
201
+ raise ValueError(f"No data found for split '{self.split}'! Check paths and filters.")
202
+
203
+ return split_data
204
+
205
+ def __len__(self):
206
+ return len(self.data)
207
+
208
+ def _find_image_path(self, relative_path: str) -> str:
209
+ """Try to find image in any of the configured root folders"""
210
+ for folder in self.image_folders:
211
+ full_path = os.path.join(folder, relative_path)
212
+ if os.path.exists(full_path):
213
+ return full_path
214
+ # If not found, return path with first folder (will error on load)
215
+ return os.path.join(self.image_folders[0], relative_path)
216
+
217
+ def __getitem__(self, idx):
218
+ item = self.data[idx]
219
+
220
+ # Load RGB image (try all root folders)
221
+ rgb_path = self._find_image_path(item['rgb'])
222
+ rgb_image = Image.open(rgb_path).convert('RGB')
223
+
224
+ # Load thermal image (try all root folders)
225
+ thermal_path = self._find_image_path(item['thermal'])
226
+ thermal_image = Image.open(thermal_path).convert('RGB') # Thermal saved as RGB
227
+
228
+ # Random flip (if enabled)
229
+ if random.random() < self.flip_p:
230
+ rgb_image = rgb_image.transpose(Image.FLIP_LEFT_RIGHT)
231
+ thermal_image = thermal_image.transpose(Image.FLIP_LEFT_RIGHT)
232
+
233
+ # Keep original PIL image for LLaVA (it will apply its own preprocessing)
234
+ # LLaVA's CLIP processor expects high-res and will resize to 336x336 or 224x224
235
+ rgb_pil = rgb_image.copy()
236
+
237
+ # Apply transforms for diffusion (resize to 256x256 + normalize to [-1, 1])
238
+ rgb_tensor = self.transform(rgb_image)
239
+ thermal_tensor = self.transform(thermal_image)
240
+
241
+ # CLIP prompt (simple, random from templates)
242
+ clip_prompt = random.choice(self.thermal_templates)
243
+
244
+ # LLaVA prompt (detailed, from JSON)
245
+ llava_prompt = None
246
+
247
+ # Handle new JSON format with direct llava_prompt field
248
+ if 'llava_prompt' in item:
249
+ llava_prompt = item['llava_prompt']
250
+ # Handle old JSON format with conversations
251
+ elif 'conversations' in item and len(item['conversations']) > 0:
252
+ for conv in item['conversations']:
253
+ if conv.get('from') == 'human':
254
+ llava_prompt = conv.get('value', '')
255
+ # Remove <image> token (LLaVA extractor handles this)
256
+ llava_prompt = llava_prompt.replace('<image>', '').strip()
257
+ break
258
+
259
+ # Fallback if no prompt
260
+ if llava_prompt is None or llava_prompt == '':
261
+ llava_prompt = "How would this RGB scene appear in long-wave thermal infrared spectrum"
262
+
263
+ return {
264
+ 'rgb': rgb_tensor, # Normalized tensor for diffusion [-1, 1]
265
+ 'rgb_pil': rgb_pil, # PIL image for LLaVA [0, 255]
266
+ 'thermal': thermal_tensor, # Normalized tensor for diffusion [-1, 1]
267
+ 'clip_prompt': clip_prompt,
268
+ 'llava_prompt': llava_prompt,
269
+ 'sequence': item['sequence'],
270
+ 'dataset': item['dataset'],
271
+ 'id': item.get('id', f"{item['sequence']}_{idx}"),
272
+ }
273
+
274
+ def get_diverse_val_samples(self, num_samples=4, seed=None):
275
+ """
276
+ Get diverse validation samples from different sequences/datasets.
277
+
278
+ Args:
279
+ num_samples: Number of samples to return
280
+ seed: Random seed for reproducibility (None for random)
281
+
282
+ Returns:
283
+ List of diverse validation samples
284
+ """
285
+ if self.split != "val":
286
+ raise ValueError("This method only works for validation split")
287
+
288
+ # Group by dataset and sequence for diversity
289
+ by_dataset = {}
290
+ for item in self.data:
291
+ dataset = item['dataset']
292
+ sequence = item['sequence']
293
+ key = f"{dataset}_{sequence}"
294
+
295
+ if dataset not in by_dataset:
296
+ by_dataset[dataset] = {}
297
+ if sequence not in by_dataset[dataset]:
298
+ by_dataset[dataset][sequence] = []
299
+
300
+ by_dataset[dataset][sequence].append(item)
301
+
302
+ # Get diverse samples
303
+ if seed is not None:
304
+ random.seed(seed)
305
+
306
+ diverse_samples = []
307
+ datasets = list(by_dataset.keys())
308
+ sequences_per_dataset = {d: list(s.keys()) for d, s in by_dataset.items()}
309
+
310
+ # Try to get samples from different datasets/sequences
311
+ for i in range(num_samples):
312
+ # Cycle through datasets
313
+ dataset_idx = i % len(datasets)
314
+ dataset = datasets[dataset_idx]
315
+
316
+ # Get sequences for this dataset
317
+ sequences = sequences_per_dataset[dataset]
318
+ if not sequences:
319
+ continue
320
+
321
+ # Pick a random sequence from this dataset
322
+ sequence = random.choice(sequences)
323
+
324
+ # Pick a random sample from this sequence
325
+ sample = random.choice(by_dataset[dataset][sequence])
326
+ diverse_samples.append(sample)
327
+
328
+ # Process samples through __getitem__ to get proper tensors
329
+ processed_samples = []
330
+ for sample_data in diverse_samples:
331
+ # Find the index of this sample in the dataset
332
+ sample_idx = None
333
+ for i, item in enumerate(self.data):
334
+ if (item['rgb'] == sample_data['rgb'] and
335
+ item['thermal'] == sample_data['thermal'] and
336
+ item['sequence'] == sample_data['sequence']):
337
+ sample_idx = i
338
+ break
339
+
340
+ if sample_idx is not None:
341
+ processed_sample = self[sample_idx] # Process through __getitem__
342
+ processed_samples.append(processed_sample)
343
+
344
+ return processed_samples
345
+
346
+
347
+ def custom_collate_fn(batch):
348
+ """
349
+ Custom collate function to handle PIL images.
350
+
351
+ - Tensors (rgb, thermal): stack into batch tensor
352
+ - PIL images (rgb_pil): keep as list (LLaVA will process each individually)
353
+ - Strings (prompts, ids): keep as list
354
+ """
355
+ collated = {}
356
+
357
+ # Stack tensors
358
+ collated['rgb'] = torch.stack([item['rgb'] for item in batch])
359
+ collated['thermal'] = torch.stack([item['thermal'] for item in batch])
360
+
361
+ # Keep PIL images as list (don't stack)
362
+ collated['rgb_pil'] = [item['rgb_pil'] for item in batch]
363
+
364
+ # Keep strings as list
365
+ collated['clip_prompt'] = [item['clip_prompt'] for item in batch]
366
+ collated['llava_prompt'] = [item['llava_prompt'] for item in batch]
367
+
368
+ # Keep metadata as list
369
+ collated['sequence'] = [item['sequence'] for item in batch]
370
+ collated['dataset'] = [item['dataset'] for item in batch]
371
+ collated['id'] = [item['id'] for item in batch]
372
+
373
+ return collated
374
+
375
+
376
+ def create_dataloaders(
377
+ json_path: str,
378
+ image_folder, # str or List[str] - single folder or multiple root folders
379
+ batch_size: int = 8,
380
+ num_workers: int = 4,
381
+ thermal_templates_path: str = "llava/data/thermal_templates.txt",
382
+ size: int = 256,
383
+ train_split_ratio: float = 0.98, # Default 98:2 train:val split
384
+ ) -> Tuple[DataLoader, DataLoader]:
385
+ """
386
+ Create train and validation dataloaders.
387
+
388
+ Args:
389
+ json_path: Path to combined training JSON
390
+ image_folder: Root folder(s) for images - str or List[str]
391
+ Examples: "MIRAGE_HD" or ["MIRAGE_HD", "../MIRAGE_cvpr"]
392
+ batch_size: Batch size
393
+ num_workers: Number of dataloader workers
394
+ thermal_templates_path: Path to thermal prompt templates
395
+ size: Image size (default: 256)
396
+ train_split_ratio: Train/val split ratio (default: 0.98 for 98:2)
397
+
398
+ Returns:
399
+ train_loader, val_loader
400
+ """
401
+ train_dataset = FrozenVLMIP2PDataset(
402
+ json_path=json_path,
403
+ image_folder=image_folder,
404
+ split='train',
405
+ thermal_templates_path=thermal_templates_path,
406
+ size=size,
407
+ flip_p=0.0, # No flip for now
408
+ train_split_ratio=train_split_ratio,
409
+ )
410
+
411
+ val_dataset = FrozenVLMIP2PDataset(
412
+ json_path=json_path,
413
+ image_folder=image_folder,
414
+ split='val',
415
+ thermal_templates_path=thermal_templates_path,
416
+ size=size,
417
+ flip_p=0.0,
418
+ train_split_ratio=train_split_ratio,
419
+ )
420
+
421
+ # Use DistributedSampler if in distributed context
422
+ use_dist = dist.is_available() and dist.is_initialized()
423
+ train_sampler = DistributedSampler(train_dataset, shuffle=True) if use_dist else None
424
+ val_sampler = DistributedSampler(val_dataset, shuffle=False) if use_dist else None
425
+
426
+ train_loader = DataLoader(
427
+ train_dataset,
428
+ batch_size=batch_size,
429
+ shuffle=False if use_dist else True,
430
+ sampler=train_sampler,
431
+ num_workers=num_workers,
432
+ pin_memory=True,
433
+ drop_last=True, # For stable batch size in DeepSpeed
434
+ collate_fn=custom_collate_fn, # Handle PIL images
435
+ )
436
+
437
+ val_loader = DataLoader(
438
+ val_dataset,
439
+ batch_size=batch_size,
440
+ shuffle=False,
441
+ sampler=val_sampler,
442
+ num_workers=num_workers,
443
+ pin_memory=True,
444
+ drop_last=False,
445
+ collate_fn=custom_collate_fn, # Handle PIL images
446
+ )
447
+
448
+ return train_loader, val_loader
449
+
450
+
451
+ def test_dataset():
452
+ """Test dataset loading"""
453
+ print("Testing FrozenVLMIP2PDataset...")
454
+
455
+ json_path = "data/llava_miragehd_train_all.json"
456
+ image_folder = "MIRAGE_HD"
457
+
458
+ # Create dataset
459
+ dataset = FrozenVLMIP2PDataset(
460
+ json_path=json_path,
461
+ image_folder=image_folder,
462
+ split='train',
463
+ size=256,
464
+ )
465
+
466
+ print(f"Dataset size: {len(dataset)}")
467
+
468
+ # Test loading a sample
469
+ sample = dataset[0]
470
+ print(f"Sample keys: {sample.keys()}")
471
+ print(f"RGB shape: {sample['rgb'].shape}")
472
+ print(f"Thermal shape: {sample['thermal'].shape}")
473
+ print(f"CLIP prompt: {sample['clip_prompt']}")
474
+ print(f"LLaVA prompt: {sample['llava_prompt'][:100]}...")
475
+ print(f"Sequence: {sample['sequence']}")
476
+ print(f"Dataset: {sample['dataset']}")
477
+
478
+ # Test dataloader
479
+ train_loader, val_loader = create_dataloaders(
480
+ json_path=json_path,
481
+ image_folder=image_folder,
482
+ batch_size=4,
483
+ num_workers=0,
484
+ )
485
+
486
+ print(f"Train batches: {len(train_loader)}")
487
+ print(f"Val batches: {len(val_loader)}")
488
+
489
+ # Test batch
490
+ batch = next(iter(train_loader))
491
+ print(f"Batch RGB shape: {batch['rgb'].shape}")
492
+ print(f"Batch thermal shape: {batch['thermal'].shape}")
493
+ print(f"Batch CLIP prompts: {batch['clip_prompt']}")
494
+
495
+ print("✓ Dataset test passed!")
496
+
497
+
498
+ if __name__ == "__main__":
499
+ test_dataset()
500
+
501
+
llava/data/thermal_templates.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ turn this into thermal infrared image
2
+ convert to thermal infrared
3
+ transform to thermal image
4
+ translate to infrared
5
+ convert RGB to thermal
6
+ change this to thermal vision
7
+ make thermal infrared version
8
+ generate thermal infrared image
9
+ create thermal image
10
+ produce thermal infrared view
11
+ show as thermal image
12
+ display in thermal infrared
13
+ render as thermal
14
+ convert to IR image
15
+ translate to thermal IR
16
+
17
+
llava/data/vlm_guided_ip2p_dataset.py ADDED
@@ -0,0 +1,486 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Dataset for VLM-guided InstructPix2Pix training.
3
+
4
+ Combines LLaVA's structured text understanding with RGB-TIR pairs for diffusion training.
5
+ """
6
+
7
+ import os
8
+ import json
9
+ import copy
10
+ from typing import Dict, List, Optional
11
+ from PIL import Image
12
+ import numpy as np
13
+
14
+ import torch
15
+ from torch.utils.data import Dataset
16
+ import torchvision.transforms as transforms
17
+
18
+ from llava.constants import IGNORE_INDEX, DEFAULT_IMAGE_TOKEN, IMG_TOKENS
19
+ from llava import conversation as conversation_lib
20
+ from llava.mm_utils import tokenizer_image_token
21
+
22
+
23
+ def _safe_replace_rgb_with_tir(path: str) -> str:
24
+ """Replace /RGB/ with /TIR/ in path to get thermal pair"""
25
+ return path.replace("/RGB/", "/TIR/")
26
+
27
+
28
+ def _expand2square(pil_img: Image.Image, background_color=(0, 0, 0)):
29
+ """Expand image to square by padding"""
30
+ w, h = pil_img.size
31
+ if w == h:
32
+ return pil_img
33
+ if w > h:
34
+ result = Image.new(pil_img.mode, (w, w), background_color)
35
+ result.paste(pil_img, (0, (w - h) // 2))
36
+ return result
37
+ else:
38
+ result = Image.new(pil_img.mode, (h, h), background_color)
39
+ result.paste(pil_img, ((h - w) // 2, 0))
40
+ return result
41
+
42
+
43
+ class VLMGuidedIP2PDataset(Dataset):
44
+ """
45
+ Dataset for VLM-guided InstructPix2Pix training.
46
+
47
+ Loads RGB-TIR pairs from MIRAGE dataset and prepares:
48
+ 1. LLaVA inputs (text + image) with IMG tokens appended to response
49
+ 2. Diffusion pairs (RGB and TIR images for InstructPix2Pix)
50
+
51
+ Args:
52
+ data_path: Path to JSON file (e.g., data/llava_no_ranking_nobbox.json)
53
+ image_folder: Root folder for images (e.g., ../MIRAGE_HD)
54
+ tokenizer: LLaVA tokenizer (with IMG tokens added)
55
+ image_processor: CLIP image processor for LLaVA
56
+ img_token_ids: List of IMG token IDs
57
+ image_aspect_ratio: "square" or "pad" (for LLaVA)
58
+ diffusion_size: Image size for diffusion model (default: 512)
59
+ model_max_length: Max sequence length (default: 2048)
60
+ filter_datasets: List of dataset names to exclude (e.g., ["DTUAV", "visdrone"])
61
+ validation_datasets: List of dataset names to use as validation (e.g., ["M3FD", "FLIR"])
62
+ is_validation: If True, use validation datasets; if False, use training datasets
63
+ """
64
+
65
+ def __init__(
66
+ self,
67
+ data_path: str,
68
+ image_folder: str,
69
+ tokenizer,
70
+ image_processor,
71
+ img_token_ids: List[int],
72
+ image_aspect_ratio: str = "square",
73
+ diffusion_size: int = 512,
74
+ model_max_length: int = 2048,
75
+ filter_datasets: Optional[List[str]] = None,
76
+ validation_datasets: Optional[List[str]] = None,
77
+ is_validation: bool = False,
78
+ ):
79
+ super().__init__()
80
+
81
+ self.image_folder = image_folder
82
+ self.tokenizer = tokenizer
83
+ self.image_processor = image_processor
84
+ self.img_token_ids = img_token_ids
85
+ self.image_aspect_ratio = image_aspect_ratio
86
+ self.diffusion_size = diffusion_size
87
+ self.model_max_length = model_max_length
88
+
89
+ # Load raw data
90
+ print(f"Loading dataset from: {data_path}")
91
+ with open(data_path, 'r') as f:
92
+ raw_data = json.load(f)
93
+
94
+ print(f" Raw dataset size: {len(raw_data)}")
95
+
96
+ # Filter datasets
97
+ if filter_datasets is None:
98
+ filter_datasets = ["DTUAV", "visdrone"] # Default exclusions
99
+
100
+ if validation_datasets is None:
101
+ validation_datasets = ["M3FD", "FLIR"] # Default validation sets
102
+
103
+ # Split into train/val
104
+ self.data = []
105
+ train_count = 0
106
+ val_count = 0
107
+ filtered_count = 0
108
+
109
+ for item in raw_data:
110
+ image_path = item.get("image", "")
111
+
112
+ # Check if should be filtered out
113
+ if any(excluded in image_path for excluded in filter_datasets):
114
+ filtered_count += 1
115
+ continue
116
+
117
+ # Check if validation
118
+ is_val_item = any(val_dataset in image_path for val_dataset in validation_datasets)
119
+
120
+ if is_validation and is_val_item:
121
+ self.data.append(item)
122
+ val_count += 1
123
+ elif not is_validation and not is_val_item:
124
+ self.data.append(item)
125
+ train_count += 1
126
+
127
+ split_name = "VALIDATION" if is_validation else "TRAINING"
128
+ print(f" {split_name} dataset size: {len(self.data)}")
129
+ print(f" Filtered out: {filtered_count} (from {filter_datasets})")
130
+ if is_validation:
131
+ print(f" Validation sources: {validation_datasets}")
132
+ else:
133
+ print(f" Excluded from training: {validation_datasets}")
134
+
135
+ # IMG token string (append to GPT response)
136
+ self.img_token_str = " " + " ".join([self.tokenizer.decode([tid], skip_special_tokens=False)
137
+ for tid in self.img_token_ids])
138
+
139
+ print(f" IMG token string: '{self.img_token_str}'")
140
+
141
+ # Counter for truncated samples
142
+ self.truncation_count = 0
143
+
144
+ # Diffusion transforms
145
+ self.diffusion_transform = transforms.Compose([
146
+ transforms.Lambda(lambda img: _expand2square(img, (0, 0, 0))),
147
+ transforms.Resize(diffusion_size, interpolation=Image.BICUBIC),
148
+ transforms.ToTensor(),
149
+ transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]), # [-1, 1]
150
+ ])
151
+
152
+ def __len__(self):
153
+ return len(self.data)
154
+
155
+ def get_truncation_stats(self):
156
+ """Get statistics about truncated samples"""
157
+ total = len(self.data)
158
+ truncated = self.truncation_count
159
+ pct = 100.0 * truncated / total if total > 0 else 0.0
160
+ return {
161
+ 'total_samples': total,
162
+ 'truncated_samples': truncated,
163
+ 'truncation_rate': pct
164
+ }
165
+
166
+ def print_truncation_stats(self):
167
+ """Print truncation statistics"""
168
+ stats = self.get_truncation_stats()
169
+ print(f"\nDataset truncation stats:")
170
+ print(f" Total samples: {stats['total_samples']}")
171
+ print(f" Truncated: {stats['truncated_samples']} ({stats['truncation_rate']:.2f}%)")
172
+ if stats['truncation_rate'] > 5.0:
173
+ print(f" ⚠️ High truncation rate! Consider increasing model_max_length")
174
+ elif stats['truncation_rate'] > 0:
175
+ print(f" ✓ Low truncation rate (acceptable)")
176
+
177
+ def _preprocess_multimodal(self, sources: List[List[Dict]]) -> List[List[Dict]]:
178
+ """Preprocess multimodal conversations (handle <image> token)"""
179
+ for source in sources:
180
+ for sentence in source:
181
+ if DEFAULT_IMAGE_TOKEN in sentence["value"]:
182
+ sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, "").strip()
183
+ sentence["value"] = DEFAULT_IMAGE_TOKEN + "\n" + sentence["value"]
184
+ sentence["value"] = sentence["value"].strip()
185
+
186
+ # Handle mm_use_im_start_end if needed
187
+ if hasattr(self.image_processor, 'image_mean'):
188
+ # Standard CLIP processor
189
+ replace_token = DEFAULT_IMAGE_TOKEN
190
+ else:
191
+ replace_token = DEFAULT_IMAGE_TOKEN
192
+
193
+ sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token)
194
+
195
+ return sources
196
+
197
+ def _preprocess_text(self, sources: List[List[Dict]], has_image: bool = True):
198
+ """Preprocess text conversations into input_ids and labels"""
199
+ conv = conversation_lib.default_conversation.copy()
200
+ roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
201
+
202
+ conversations = []
203
+ for source in sources:
204
+ if roles[source[0]["from"]] != conv.roles[0]:
205
+ # Skip non-human first message
206
+ source = source[1:]
207
+
208
+ conv.messages = []
209
+ for sentence in source:
210
+ role = roles[sentence["from"]]
211
+ conv.append_message(role, sentence["value"])
212
+
213
+ conversations.append(conv.get_prompt())
214
+
215
+ # Tokenize
216
+ if has_image:
217
+ input_ids = torch.stack([
218
+ tokenizer_image_token(prompt, self.tokenizer, return_tensors="pt")
219
+ for prompt in conversations
220
+ ], dim=0)
221
+ else:
222
+ input_ids = self.tokenizer(
223
+ conversations,
224
+ return_tensors="pt",
225
+ padding="longest",
226
+ max_length=self.model_max_length,
227
+ truncation=True
228
+ ).input_ids
229
+
230
+ targets = input_ids.clone()
231
+
232
+ # Check for truncation (guard against long samples)
233
+ for seq in input_ids:
234
+ if len(seq) >= self.model_max_length:
235
+ self.truncation_count += 1
236
+
237
+ # Mask human turns (keep only GPT responses in labels)
238
+ if conv.sep_style == conversation_lib.SeparatorStyle.TWO:
239
+ sep = conv.sep + conv.roles[1] + ": "
240
+ for conversation, target in zip(conversations, targets):
241
+ total_len = int(target.ne(self.tokenizer.pad_token_id).sum())
242
+ rounds = conversation.split(conv.sep2)
243
+ cur_len = 1
244
+ target[:cur_len] = IGNORE_INDEX
245
+
246
+ for i, rou in enumerate(rounds):
247
+ if rou == "":
248
+ break
249
+
250
+ parts = rou.split(sep)
251
+ if len(parts) != 2:
252
+ break
253
+
254
+ parts[0] += sep
255
+
256
+ if has_image:
257
+ round_len = len(tokenizer_image_token(rou, self.tokenizer))
258
+ instruction_len = len(tokenizer_image_token(parts[0], self.tokenizer)) - 2
259
+ else:
260
+ round_len = len(self.tokenizer(rou).input_ids)
261
+ instruction_len = len(self.tokenizer(parts[0]).input_ids) - 2
262
+
263
+ # Mask instruction (human part)
264
+ target[cur_len: cur_len + instruction_len] = IGNORE_INDEX
265
+
266
+ cur_len += round_len
267
+
268
+ target[cur_len:] = IGNORE_INDEX
269
+
270
+ # Safety check
271
+ if cur_len != total_len:
272
+ target[:] = IGNORE_INDEX
273
+
274
+ return dict(input_ids=input_ids[0], labels=targets[0])
275
+
276
+ def __getitem__(self, idx) -> Dict[str, torch.Tensor]:
277
+ """
278
+ Returns:
279
+ input_ids: Tokenized input
280
+ labels: Labels with human turns masked (IMG tokens NOT masked!)
281
+ image: Preprocessed RGB image for LLaVA
282
+ rgb_diffusion: RGB image for diffusion model (512x512, [-1,1])
283
+ tir_diffusion: TIR image for diffusion model (512x512, [-1,1])
284
+ """
285
+ item = self.data[idx]
286
+
287
+ # Get image paths
288
+ rgb_rel_path = item["image"]
289
+ rgb_path = os.path.join(self.image_folder, rgb_rel_path)
290
+ tir_path = _safe_replace_rgb_with_tir(rgb_path)
291
+
292
+ # Load images
293
+ try:
294
+ rgb_image = Image.open(rgb_path).convert("RGB")
295
+ except Exception as e:
296
+ raise ValueError(f"Failed to load RGB image: {rgb_path}") from e
297
+
298
+ try:
299
+ tir_image = Image.open(tir_path).convert("RGB")
300
+ except Exception as e:
301
+ # If TIR doesn't exist, use RGB as fallback (will print warning)
302
+ print(f"Warning: TIR not found, using RGB: {tir_path}")
303
+ tir_image = rgb_image.copy()
304
+
305
+ # Prepare LLaVA image (using CLIP processor)
306
+ if self.image_aspect_ratio == "pad":
307
+ bg = tuple(int(x * 255) for x in self.image_processor.image_mean)
308
+ rgb_image_llava = _expand2square(rgb_image, bg)
309
+ else:
310
+ rgb_image_llava = rgb_image
311
+
312
+ image_tensor = self.image_processor.preprocess(rgb_image_llava, return_tensors="pt")["pixel_values"][0]
313
+
314
+ # Prepare diffusion images (512x512, [-1, 1])
315
+ rgb_diffusion = self.diffusion_transform(rgb_image)
316
+ tir_diffusion = self.diffusion_transform(tir_image)
317
+
318
+ # Prepare conversation with IMG tokens appended
319
+ conversations = copy.deepcopy(item["conversations"])
320
+
321
+ # Append IMG tokens to the GPT response
322
+ if len(conversations) >= 2 and conversations[1]["from"] == "gpt":
323
+ conversations[1]["value"] = conversations[1]["value"] + self.img_token_str
324
+ else:
325
+ raise ValueError(f"Expected gpt response in conversations[1], got: {conversations}")
326
+
327
+ # Build sources for tokenization
328
+ sources = [conversations]
329
+
330
+ # Preprocess multimodal
331
+ sources = self._preprocess_multimodal(copy.deepcopy(sources))
332
+
333
+ # Tokenize and create labels
334
+ text_dict = self._preprocess_text(sources, has_image=True)
335
+
336
+ return {
337
+ "input_ids": text_dict["input_ids"],
338
+ "labels": text_dict["labels"],
339
+ "image": image_tensor,
340
+ "rgb_diffusion": rgb_diffusion,
341
+ "tir_diffusion": tir_diffusion,
342
+ }
343
+
344
+
345
+ def create_dataloaders(
346
+ data_path: str,
347
+ image_folder: str,
348
+ tokenizer,
349
+ image_processor,
350
+ img_token_ids: List[int],
351
+ batch_size: int = 4,
352
+ num_workers: int = 4,
353
+ image_aspect_ratio: str = "square",
354
+ diffusion_size: int = 512,
355
+ filter_datasets: Optional[List[str]] = None,
356
+ validation_datasets: Optional[List[str]] = None,
357
+ ):
358
+ """
359
+ Create training and validation dataloaders.
360
+
361
+ Args:
362
+ data_path: Path to JSON file
363
+ image_folder: Root folder for images
364
+ tokenizer: LLaVA tokenizer (with IMG tokens)
365
+ image_processor: CLIP image processor
366
+ img_token_ids: List of IMG token IDs
367
+ batch_size: Batch size
368
+ num_workers: Number of workers
369
+ image_aspect_ratio: "square" or "pad"
370
+ diffusion_size: Image size for diffusion
371
+ filter_datasets: Datasets to exclude entirely (default: ["DTUAV", "visdrone"])
372
+ validation_datasets: Datasets to use as validation (default: ["M3FD", "FLIR"])
373
+
374
+ Returns:
375
+ train_loader, val_loader
376
+ """
377
+ from torch.utils.data import DataLoader
378
+
379
+ # Create train dataset
380
+ train_dataset = VLMGuidedIP2PDataset(
381
+ data_path=data_path,
382
+ image_folder=image_folder,
383
+ tokenizer=tokenizer,
384
+ image_processor=image_processor,
385
+ img_token_ids=img_token_ids,
386
+ image_aspect_ratio=image_aspect_ratio,
387
+ diffusion_size=diffusion_size,
388
+ filter_datasets=filter_datasets,
389
+ validation_datasets=validation_datasets,
390
+ is_validation=False # Training set
391
+ )
392
+
393
+ # Create validation dataset
394
+ val_dataset = VLMGuidedIP2PDataset(
395
+ data_path=data_path,
396
+ image_folder=image_folder,
397
+ tokenizer=tokenizer,
398
+ image_processor=image_processor,
399
+ img_token_ids=img_token_ids,
400
+ image_aspect_ratio=image_aspect_ratio,
401
+ diffusion_size=diffusion_size,
402
+ filter_datasets=filter_datasets,
403
+ validation_datasets=validation_datasets,
404
+ is_validation=True # Validation set
405
+ )
406
+
407
+ # Custom collate function
408
+ def collate_fn(batch):
409
+ """Collate batch items"""
410
+ # Find max length for padding
411
+ input_ids = [item["input_ids"] for item in batch]
412
+ labels = [item["labels"] for item in batch]
413
+
414
+ # Pad sequences
415
+ input_ids = torch.nn.utils.rnn.pad_sequence(
416
+ input_ids, batch_first=True, padding_value=tokenizer.pad_token_id
417
+ )
418
+ labels = torch.nn.utils.rnn.pad_sequence(
419
+ labels, batch_first=True, padding_value=IGNORE_INDEX
420
+ )
421
+
422
+ # Stack images
423
+ images = torch.stack([item["image"] for item in batch])
424
+ rgb_diffusion = torch.stack([item["rgb_diffusion"] for item in batch])
425
+ tir_diffusion = torch.stack([item["tir_diffusion"] for item in batch])
426
+
427
+ return {
428
+ "input_ids": input_ids,
429
+ "labels": labels,
430
+ "images": images,
431
+ "rgb_diffusion": rgb_diffusion,
432
+ "tir_diffusion": tir_diffusion,
433
+ }
434
+
435
+ # Check if we're in distributed training
436
+ import torch.distributed as dist
437
+ is_distributed = dist.is_available() and dist.is_initialized()
438
+
439
+ # Create samplers for distributed training
440
+ if is_distributed:
441
+ from torch.utils.data.distributed import DistributedSampler
442
+ train_sampler = DistributedSampler(
443
+ train_dataset,
444
+ num_replicas=dist.get_world_size(),
445
+ rank=dist.get_rank(),
446
+ shuffle=True,
447
+ drop_last=False
448
+ )
449
+ val_sampler = DistributedSampler(
450
+ val_dataset,
451
+ num_replicas=dist.get_world_size(),
452
+ rank=dist.get_rank(),
453
+ shuffle=False,
454
+ drop_last=False
455
+ ) if len(val_dataset) > 0 else None
456
+ else:
457
+ train_sampler = None
458
+ val_sampler = None
459
+
460
+ # Create dataloaders
461
+ train_loader = DataLoader(
462
+ train_dataset,
463
+ batch_size=batch_size,
464
+ sampler=train_sampler,
465
+ shuffle=(train_sampler is None), # Only shuffle if not using sampler
466
+ num_workers=num_workers,
467
+ collate_fn=collate_fn,
468
+ pin_memory=True
469
+ )
470
+
471
+ val_loader = DataLoader(
472
+ val_dataset,
473
+ batch_size=batch_size,
474
+ sampler=val_sampler,
475
+ shuffle=False,
476
+ num_workers=num_workers,
477
+ collate_fn=collate_fn,
478
+ pin_memory=True
479
+ ) if len(val_dataset) > 0 else None
480
+
481
+ print(f"\nDataloaders created:")
482
+ print(f" Training batches: {len(train_loader)}")
483
+ print(f" Validation batches: {len(val_loader) if val_loader else 0}")
484
+
485
+ return train_loader, val_loader
486
+
llava/eval/table/answer/answer_alpaca-13b.jsonl ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"question_id": 1, "text": "Improving time management skills involves setting priorities, breaking tasks into smaller chunks, delegating tasks, avoiding multitasking, and taking regular breaks. Additionally, it is important to have a positive attitude and be realistic with goals. Making a to-do list, tracking time, and using technology to automate mundane tasks can also help improve time management skills.", "answer_id": "kEL9ifUHDeYuAXzevje2se", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
2
+ {"question_id": 2, "text": "The most effective ways to deal with stress include identifying and avoiding the sources of stress, developing healthy coping mechanisms, and engaging in relaxation techniques such as meditation, deep breathing, and physical exercise. Additionally, it is important to take care of one's mental and physical health, get enough rest and nutrition, and practice self-care.", "answer_id": "VcF3NrWGXhhxLkDVurNrwq", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
3
+ {"question_id": 3, "text": "The main differences between Python and JavaScript programming languages are in their syntax, structure, and the type of applications they are designed for. Python is a general-purpose language designed to be easy to read and write, while JavaScript is primarily used for web development. Python is a compiled language, while JavaScript is an interpreted language. Python is strongly typed, while JavaScript is not. Python is typically faster than JavaScript in terms of execution, while JavaScript is better suited to create interactive web pages.", "answer_id": "LpvtyQi9QdSgRrgGDxiGrT", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
4
+ {"question_id": 4, "text": "Working from home can be a great way to increase productivity, but it does require some strategic planning and tactics. Here are some tips for increasing your productivity while working from home: \n1. Establish a routine: Having a regular schedule and sticking to it can help you stay focused and motivated.\n2. Create a distraction-free zone: Eliminate distractions by turning off notifications and setting a \u201cdo not disturb\u201d mode.\n3. Take breaks: Working for long stretches without taking breaks can lead to burnout and decreased productivity.\n4. Exercise: Exercise can help improve focus and productivity.\n5. Get organized: Having a clean and organized workspace can help you stay on task.\n6. Set goals: Set short-term and long-term goals to keep you motivated and on track.\n7. Connect with colleagues: Don\u2019t be afraid to reach out to colleagues for help or advice.\n8. Track your progress: Keep track of your progress and celebrate your successes.\n9. Unplug: Taking breaks and unplugging from work can help you recharge and come back to work more refreshed.", "answer_id": "7zQm8cSTJhPtPdZdxbcfrX", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
5
+ {"question_id": 5, "text": "Sure. Quantum computing is a new technology that uses quantum mechanical phenomena to perform operations on data. Unlike traditional computers, which process information in binary form, quantum computers can process information in multiple states at the same time, allowing them to perform operations faster and with more accuracy. It also allows them to solve problems that classical computers struggle with. Quantum computing is still in its infancy, but it has the potential to revolutionize the computing industry and open up new possibilities in artificial intelligence, cryptography, and other fields.", "answer_id": "UrLEH82RHwqqLt2LyvYSKj", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
6
+ {"question_id": 6, "text": "Plant-based protein sources include legumes, grains, nuts, and seeds, and are generally lower in fat and calories than animal-based proteins. Animal-based proteins come from sources such as meat, eggs, and dairy, and are generally higher in fat and calories than plant-based proteins. Plant-based proteins are also generally lower in cholesterol and saturated fat than animal-based proteins. Additionally, plant-based proteins require fewer resources for production, such as water and land, than animal-based proteins.", "answer_id": "fpRdMTdnfirosQixuf2Gez", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
7
+ {"question_id": 7, "text": "Developing critical thinking skills involves actively questioning assumptions, taking multiple perspectives, analyzing information, and coming to logical conclusions. You can practice these skills by posing questions to yourself and working through problems, as well as engaging in thoughtful discussion with others.", "answer_id": "PvGmsCJSNFcvQKmPTnnd7s", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
8
+ {"question_id": 8, "text": "The major challenges faced by the education sector include lack of access to quality education, low educational outcomes, high costs of education, lack of adequate infrastructure and teaching materials, overcrowding in classrooms, and gender inequality. Other challenges include lack of access to technology and digital learning materials, outdated curriculum and pedagogical practices, and inadequate teacher training.", "answer_id": "n4ANAbpR3gvLPP8poPfKZ6", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
9
+ {"question_id": 9, "text": "The primary factors that influence consumer behavior include cultural, social, and personal factors. Cultural factors include shared beliefs, values, and customs within a society, while social factors include the influence of family, friends, and peers. Personal factors include an individual's lifestyle, attitudes, beliefs, and past experiences. Other factors such as advertising, marketing, and price also have an effect on consumer behavior.", "answer_id": "STJ36GrgQMcaUi7zaoNPit", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
10
+ {"question_id": 10, "text": "The most effective strategies for conflict resolution in the workplace include:\n1. Establishing open communication: Encouraging open and honest communication between parties is key to resolving any conflict.\n2. Listening actively: Active listening allows both parties to feel heard and allows for a better understanding of the other person's perspective.\n3. Identifying root causes: Understanding the underlying cause of the conflict can help to find more effective solutions that address the core issue.\n4. Focusing on interests, not positions: Focusing on the interests of both parties can help to find creative solutions that satisfy the needs of everyone involved.\n5. Developing mutual respect: Respect is essential to any successful resolution. Building mutual respect can help to create a healthier work environment.\n6. Negotiation: Working together to negotiate a mutually beneficial solution can help to create an agreement that both parties are happy with.\n7. Taking responsibility: Taking responsibility for one\u2019s words and actions can help to create a culture of accountability in the workplace.", "answer_id": "425SwYvqKPAXFGTYKXB7Cs", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
11
+ {"question_id": 11, "text": "The use of single-use plastic bottles has a number of negative implications on the environment. They are not biodegradable and can take hundreds of years to break down. This means they are around for a long time, releasing potentially harmful chemicals into the environment, and they can be easily mistaken for food by animals. Single-use plastic bottles can also be a source of micro-plastics, which are very small particles of plastic that are difficult to clean up and can be consumed by fish and other aquatic life, leading to health problems in humans who consume those fish. On the other hand, reusable bottles are a much more environmentally friendly choice since they do not produce any waste. They are also often made of materials that are safer for human health, such as stainless steel or glass. Reusable bottles are also more cost-effective since they do not need to be replaced as often as single-use plastic bottles.", "answer_id": "VbNAuj6KAkMdLJQXMo22oK", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
12
+ {"question_id": 12, "text": "When designing an inclusive and accessible public transportation system, some factors to consider include providing frequent and reliable service, accessible stops and vehicles, a variety of fare options, clear and consistent signage and information, comfortable seating and space for wheelchairs and other assistive devices, and security and safety protocols. Additionally, public transportation systems should be integrated with other services such as public parking, bike and scooter sharing, and shuttles to provide a comprehensive and accessible experience.", "answer_id": "CNGqAeu2QJbQ4QGzHJDPdq", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
13
+ {"question_id": 13, "text": "Governments can use fiscal and monetary policies to combat economic recessions. Fiscal policies involve the government spending money or cutting taxes in order to stimulate the economy, while monetary policies involve changing the money supply or interest rates to influence economic activity. These policies can be used to stabilize the economy, create jobs, and reduce poverty.", "answer_id": "E8w2qYqnm8iqCrSkUv62sz", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
14
+ {"question_id": 14, "text": "Language and cultural barriers can lead to misunderstandings and make it more difficult to communicate and form relationships in multicultural societies. Without a common language or shared culture, people can have difficulty understanding each other's perspectives and beliefs, which can lead to mistrust and a lack of understanding between different ethnic groups. To overcome these barriers, it is important to make an effort to learn about different cultures, be open-minded, and take the time to understand each other.", "answer_id": "8o5yMymfzo6kzmp9GK5MWr", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
15
+ {"question_id": 15, "text": "Artificial intelligence can be used to improve the quality and efficiency of healthcare delivery in a variety of ways. AI can be used to assist with diagnosing diseases by comparing symptoms and medical history to images of known diseases and medical conditions. AI can also be used to analyze laboratory results and patient records to identify potential problems and develop treatment plans. AI can be used to automate administrative tasks and reduce paperwork, as well as identify potential drug interactions and side effects. AI can also be used to automate appointment reminders, facilitate communication between doctors and patients, and even provide virtual health coaching to help patients manage their conditions.", "answer_id": "kbJVEEsdsSScEq5Y5furr7", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
16
+ {"question_id": 16, "text": "CRISPR-Cas9 is a recently developed gene editing technology that has revolutionized the way scientists are able to edit genomes. The technology uses a guide RNA to direct the Cas9 enzyme to a specific location in the genome, where it will cut the DNA strands. This allows for the insertion or deletion of DNA sequences, which can be used to modify the genetic code of an organism. Potential applications include treating genetic diseases, increasing crop yields, and creating pest-resistant crops. Ethically, the biggest concern is the potential misuse of the technology, which could lead to unintended consequences or be used to alter humanity in ways that could harm us.", "answer_id": "CMUL5ULZuR7YC5EPzCBN2N", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
17
+ {"question_id": 17, "text": "Vaccinations work by stimulating the body's immune system to protect against infectious diseases. Herd immunity is a concept whereby a population is protected against a certain disease when a certain percentage of the population has immunity to the disease, either through vaccination or having already contracted the disease. This is because when enough people are vaccinated, it reduces the spread of the disease and prevents it from spreading to those who are not immune.", "answer_id": "kEmDDQyNqSkyFihYEEBpuR", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
18
+ {"question_id": 18, "text": "Social media platforms can have a significant influence on how people consume and share news. By providing instant access to news sources and allowing users to easily share content, these platforms can shape the public's information landscape and the spread of misinformation. Some potential implications of this are that users may not always be able to discern between reliable and unreliable sources, and misleading information may be more easily spread and go viral. This can lead to confusion and mistrust among users, and can potentially be exploited for nefarious purposes. To mitigate these risks, it is important for users to be aware of the potential biases and agendas of the sources they are consuming, and for social media platforms to take proactive steps to curb the spread of misinformation.", "answer_id": "Qs3grQsqFVGK9EVkCkf9PB", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
19
+ {"question_id": 19, "text": "Cultural, social, and economic factors all play a role in determining an individual's food choices. For example, people growing up in households with limited economic means may be more likely to consume cheaper, less nutritious foods due to economic constraints. Additionally, cultural norms and values can influence food choices, such as the emphasis on large portions typical in some American cultural settings. Finally, social factors such as peer pressure and advertising can also sway an individual's food choices. By understanding and taking into account these various factors, health promotion strategies can be tailored and targeted to help individuals make healthier dietary decisions.", "answer_id": "kzZ6dKN7hkRWjqtdHr7Qns", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
20
+ {"question_id": 20, "text": "Natural selection is the process by which certain traits or characteristics become more or less common in a population over time. This is due to the fact that those individuals with certain advantageous traits are more likely to survive, reproduce, and pass those traits on to their offspring. Over time, this leads to the evolution and adaptation of species to their environment.", "answer_id": "DPPDG6YGFJij2GCmRL66PU", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
21
+ {"question_id": 21, "text": "I am a brave knight, loyal to my king and country, and I have come to serve and protect them both. I am skilled in the arts of war and peace, and I am proud to be here at the royal court.", "answer_id": "D62FjDb4nZANzPpfSfsiyn", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
22
+ {"question_id": 22, "text": "Avast ye maties! To the bottom of the sea we go! In search of hidden riches and fortune, we shall brave the depths and face any danger that comes our way. For glory and honor, let us set sail and find the lost Ark!", "answer_id": "k7E4NNw5kyj9DmvP5Pu2zb", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
23
+ {"question_id": 23, "text": "If I were a Shakespearean character, I would declare my love for someone in a soliloquy with passionate words and metaphors. I would express my love for them with descriptions of their beauty and the joy I feel when I am with them. I would confess my hopes and dreams for our future together and declare my devotion to them. I would make my love for them known in a way that could never be forgotten.", "answer_id": "KFocjVCejYrU3YmLjAqoUF", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
24
+ {"question_id": 24, "text": "As a superhero, my origin story is very special. I was born with special abilities that I had to keep hidden for a long time. I was scared to use them at first, but eventually I discovered that I could use my powers to protect people and make the world a better place. I've had to face a lot of challenges along the way, but I've also had a lot of help from friends and family. Now, I use my abilities to help people in need and fight for justice.", "answer_id": "dq8Sm9djS7e7y9sG9vmMJf", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
25
+ {"question_id": 25, "text": "If I were a time traveler from the year 3000, I would tell people about the incredible advancements in technology, such as the ability to travel through time, space, and dimensions; the development of intelligent robots and autonomous vehicles; the emergence of virtual reality and augmented reality; and the rise of artificial intelligence and machine learning.", "answer_id": "XZ8fG8e6u7CyKd2moK6abe", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
26
+ {"question_id": 26, "text": "The game was a nail-biter, with both teams trading leads throughout the game. With only seconds left on the clock, the home team made a bold move and passed the ball to their star player, who took the ball down the court and made a layup at the buzzer to seal the victory for the home team!", "answer_id": "oKaXHfoK4pXwrefFWXmeA8", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
27
+ {"question_id": 27, "text": "My signature dish is a seamless blend of traditional and modern cooking techniques. I use only the freshest ingredients to create a unique and unforgettable dining experience. The dish is a perfect balance of flavors and textures, with a subtle hint of my personal style. It is a dish that I am proud to call my own.", "answer_id": "ZwiZfvDWm7SETKNBfDk7Mb", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
28
+ {"question_id": 28, "text": "At the summit of Mount Everest, you are filled with a sense of accomplishment and joy. The view from the top is absolutely breathtaking - you can see for miles and miles, with the majestic Himalayan mountain range stretching out in all directions. It is a truly unforgettable experience.", "answer_id": "DxYopRe2LcTJMy3FWu6btd", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
29
+ {"question_id": 29, "text": "As a colonist on Mars, my daily life is filled with challenges. Finding resources and creating a sustainable environment is a priority. I face a number of challenges including extreme temperature fluctuations, limited access to resources, and the difficulty of travelling to and from the planet. Additionally, I must be mindful of my physical and mental health since I am so far from home. Despite these challenges, I am grateful to be able to explore and experience this new world.", "answer_id": "WC3UJVh4jQ5RUkpcRMU98L", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
30
+ {"question_id": 30, "text": "In the post-apocalyptic world, I am a survivor by necessity. I scavenge for food and supplies, and I'm always on the lookout for potential allies. I've encountered a few people who have managed to survive, and together we have formed an alliance to help each other. We hunt for food, build shelter, and work together to stay alive. We also share knowledge and skills, like how to start a fire or how to use a weapon. We look out for each other, and our alliance has strengthened our chances of survival.", "answer_id": "gTvgn6ksDjGGgdprw6AG5A", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
31
+ {"question_id": 31, "text": "There are a few ways to tell if a restaurant is popular among locals or mainly attracts tourists. Firstly, look at the clientele - if the majority of people there are tourists, it's likely that the restaurant is mainly attracting tourists. Secondly, check online reviews - if the reviews are mainly from tourists, then it's likely that the restaurant is popular with tourists. Finally, look at the prices - if the prices are higher than average for the area, it could be a sign that the restaurant is popular with locals. This information can be useful to get an idea of what kind of experience to expect, as locals might know about different aspects of the restaurant that tourists wouldn't.", "answer_id": "3q7giCk2BA3Ye4Tm9HC2iw", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
32
+ {"question_id": 32, "text": "Some subtle clues that suggest someone is pretending to understand a topic or conversation when they are actually confused or uninformed include: not asking any questions or engaging in the conversation, avoiding eye contact, fidgeting or stammering when speaking, repeating questions or comments made by other people, and nodding along without any signs of understanding.", "answer_id": "hRGsxy86v26SC4yAQS29X4", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
33
+ {"question_id": 33, "text": "Some people prefer the tactile and visual experience of using a paper map, and others may prefer to ask for directions from locals in order to get a more personalized experience. Additionally, GPS devices and smartphone apps can sometimes be inaccurate or have limited battery life, while a paper map or asking for directions may be more reliable.", "answer_id": "3n49A5ggJERfXYrLns3ZeU", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
34
+ {"question_id": 34, "text": "One way to tell if someone is genuinely interested in a conversation is to observe their body language and facial expressions. Are they making an effort to maintain eye contact? Are they leaning in and actively listening to what you are saying? Do they ask questions and provide relevant answers? If so, it is likely that they are genuinely interested in the conversation. Additionally, if someone is simply being polite, they may not ask questions or engage in the conversation as much, and may not make an effort to maintain eye contact.", "answer_id": "ErCpFtPuYVru4oTTk4WrxG", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
35
+ {"question_id": 35, "text": "Shopping at a small, locally-owned business can benefit the local community by keeping money in the area and supporting local jobs. Additionally, these businesses tend to offer a more personal experience and higher quality products than large chain stores. Furthermore, shopping at small businesses can help create a sense of place and community, and can help maintain a unique local culture.", "answer_id": "PTNoCRMZWoJk8HaKX7fW45", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
36
+ {"question_id": 36, "text": "There are several ways to assess the credibility of a source of information. Firstly, you can look at the author's credentials and experience in the relevant field. Secondly, you can check the source of the information, such as whether it is from a reliable website or publication. Thirdly, you can look at the evidence presented in the article and whether it is backed up by reliable sources. Finally, you can read other people's reviews or comments about the article to get a better idea of its credibility.", "answer_id": "n8cFs9KENNwZ4z3SR4iXTr", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
37
+ {"question_id": 37, "text": "Some people enjoy the sensation of being scared because it can create a feeling of excitement, enhance their emotional state, and provide a sense of thrill and adventure. Others may avoid these experiences because they are afraid of the unknown, or because they don't enjoy the feeling of being scared. Everyone is different, and some people may be more attracted to thrilling and exciting activities while others may prefer calmer activities.", "answer_id": "GzxL9mmEK5RzKqRbqBMUVC", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
38
+ {"question_id": 38, "text": "By observing the behavior of others in a social situation, one can gain clues as to the cultural norms and expectations of a group. For example, watching how people interact with one another, how they address each other, how they handle disagreements, and how they go about solving problems can provide insight into the cultural values of the group. Additionally, observing body language, facial expressions, and other nonverbal cues can offer clues as to the accepted norms of behavior in a particular culture.", "answer_id": "QpoHFgb9SzwuaXQQUuBUQD", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
39
+ {"question_id": 39, "text": "It is an interesting question, and one that has been debated for quite some time. I think there are valid arguments on both sides. On the one hand, exploring space is a remarkable human endeavor and could lead to tremendous scientific discoveries and technological advances. On the other hand, there are many pressing issues that need to be addressed on Earth, such as poverty, inequality, and climate change. Each side would argue that their cause is more important, and it is ultimately up to each individual to decide which one they feel more strongly about.", "answer_id": "Fxe6MS4GpP3LMDUwzY2cPA", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
40
+ {"question_id": 40, "text": "It is important to strike a balance between job creation and technological progress. Automation can increase efficiency and productivity, but it should not come at the expense of job security and people's livelihoods. Therefore, it is essential to create policies and initiatives that promote both job creation and technological progress. This could include investing in training and education to ensure that people have the skills necessary to compete in the modern job market, as well as incentivizing companies to invest in technologies that create jobs and stimulate economic growth.", "answer_id": "mJiQ2FGR4Xb8kmhZjharkw", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
41
+ {"question_id": 41, "text": "On average, the human eye blinks about 20 times per minute, or about 14,400 times per day. In a lifetime, this means that the average human will blink roughly 50 million times. This may seem like a lot, but it serves an important purpose. Blinking helps to keep the eyes lubricated and prevents them from drying out. It also helps to spread tears over the surface of the eye, washing away foreign particles and keeping the eye clean. Additionally, blinking helps to reduce the risk of eye infections by helping to clear away bacteria and other foreign substances.", "answer_id": "6Kph4RHRKEZ4YUoaHuEhBv", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
42
+ {"question_id": 42, "text": "A grain of salt contains 102.98 atoms. To calculate this, we first need to know the atomic weight of a single atom. The atomic weight of an atom is the number of protons and neutrons in the nucleus of an atom, which determines its atomic mass. The atomic weight of a single atom of salt is 58.943 g/atom. Therefore, a grain of salt contains 102.98 atoms, which is equivalent to 60.98 grams.", "answer_id": "WBwpBQwhxn5kxLDb7MschC", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
43
+ {"question_id": 43, "text": "Approximately 2000 lightning strikes occur on Earth each day. This is because the atmospheric conditions must come together in a particular way for a lightning strike to occur. Firstly, a large amount of electric charge must accumulate in the atmosphere, typically in a storm system. Then, the air must become increasingly unstable, leading to rising air and a strong updraft. This causes an electric breakdown of the air, and then an exchange of electricity occurs from the cloud to the ground, forming a lightning bolt. As these conditions are necessary for a lightning strike to occur, about 2000 lightning strikes happen on Earth each day.", "answer_id": "kf8nahQVci2ZLaYikagB7U", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
44
+ {"question_id": 44, "text": "It would take about 10 million balloons to lift a house like in the movie Up. The balloons would need to be filled with helium in order for the house to be lifted. Each balloon would need to be filled with about 89.1 cubic feet of helium in order to lift 500 pounds. To calculate how many balloons would be needed, simply multiply the weight of the house (264.72 lbs) by the number of cubic feet of helium needed to lift 500 pounds (89.1). Therefore, it would take 10 million balloons to lift a house like in the movie Up.", "answer_id": "Gptgryd4o2dC8V5aqRmeJJ", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
45
+ {"question_id": 45, "text": "According to a 2017 study, over 6.3 billion text messages are sent globally in a minute. This number is expected to grow to 6.8 billion by 2021. This is due to the increasing number of smartphones, better network coverage, and the increasing popularity of texting for communication. Furthermore, the increase in smartphones and better network coverage has also led to the rise of instant messaging applications such as WhatsApp, which has further increased the amount of text messages sent per minute.", "answer_id": "RfBWW8ZhdfTuTMb454Un4o", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
46
+ {"question_id": 46, "text": "It is estimated that over 1 billion words are spoken on Earth every day. This is due to the fact that humans are highly social creatures, and language is the primary way that we communicate with each other. In addition, language is a key component of all cultures and societies, and is constantly being used to exchange information and ideas. Furthermore, language is integral to the way we think and process information, as well as to how we connect with each other on an emotional level. Therefore, it is not surprising that so many words are spoken on a daily basis.", "answer_id": "neGgLYm47JvqN8qkw8VeoW", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
47
+ {"question_id": 47, "text": "On average, about 100 snowflakes fall per second during a typical winter. This number can vary drastically depending on the location and severity of the storm. Snowflakes are made up of tiny ice crystals, which form in the atmosphere when the temperature is below freezing and there is moisture in the air. As air moves and mixes, the crystals come together to form snowflakes. The shape, size and number of snowflakes depend on the atmospheric conditions, such as temperature and humidity, when they form.", "answer_id": "KSePbzLwsYasR3aui4HU8h", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
48
+ {"question_id": 48, "text": "It is estimated that all the books ever written would total about 100 billion pages. This is based on the fact that there are roughly 130 million unique titles in existence, and each book on average contains about 200 pages. This means that if all the books were printed out, the stack of paper would be about 400 miles high. Additionally, if each book was represented by a single page, the total number of pages would be approximately 100 billion. Throughout history, books have served as a way to preserve knowledge and information, as well as to share ideas and stories with others. As technology advances, books are increasingly available in digital formats, which allows for easier access and storage. Regardless of the medium, books will continue to be a valuable source of information for generations to come.", "answer_id": "SWWfLpP2gnWHLbYRZXNsW3", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
49
+ {"question_id": 49, "text": "Since the beginning of life, the Earth has orbited the Sun a total of 4.3 billion times. This is calculated by multiplying the average length of a year (365.25 days) by the number of years since life began (approximately 4.5 billion years). Life on Earth relies on the Sun's energy reaching the Earth's atmosphere and being redistributed by the atmosphere, the land surface, and the oceans. Without this energy, life on Earth would not be possible. Therefore, the Earth's orbit around the Sun is integral to the sustainability of life on Earth.", "answer_id": "WaBwKYhs7eAG22qCGLH2j3", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
50
+ {"question_id": 50, "text": "Since the beginning of recorded music, countless songs have been recorded. The exact number is difficult to quantify, but conservative estimates put the number of songs recorded throughout history at several hundred thousand. This includes songs from all genres, from classical music to modern pop. The invention of recording technology has allowed musicians to preserve their music and share it with the world. This has enabled generations to access and enjoy music from all eras. With the rise of digital music, the number of recordings available has grown exponentially, and new songs are being recorded all the time.", "answer_id": "MfMJeE9om7qyBbqopHouf4", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
51
+ {"question_id": 51, "text": "If the Internet had been invented during the Renaissance period, it likely would have been used primarily by the wealthy and powerful to access knowledge and information, as there was no widespread system of public education at the time. It also would have been a much slower and more expensive process to access information, as there were no high-speed connections or digital networks available.", "answer_id": "TjWPRDM6JFpPF8xeRptCKb", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
52
+ {"question_id": 52, "text": "If the Aztecs had successfully repelled the Spanish conquistadors, their culture and way of life would have likely remained intact. The Spanish would not have been able to colonize Mexico, and their influence on the region would have been much less. It's likely that the Aztecs would have continued to expand their empire and control the areas that are now parts of Central and South America. Additionally, the Native American populations in the area would have likely been able to maintain more of their traditional customs and beliefs, and their languages may not have been as heavily impacted by Spanish.", "answer_id": "iR2tYTsWTFENEP7Qy9RgtX", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
53
+ {"question_id": 53, "text": "If the Black Death had not occurred in the 14th century, the population of Europe may have continued to grow unabated, leading to more rapid urbanization and economic growth. It's likely that the Renaissance would have begun sooner, and the scientific revolution may have occurred earlier as well. Without the Black Death, there may have been no need for the industrial revolution, or at least it may have occurred later and on a smaller scale. Additionally, the spread of diseases may have been slower, leading to greater population density in certain areas.", "answer_id": "AZdS8xAi3GwAmCqkNSnnwv", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
54
+ {"question_id": 54, "text": "If Isaac Newton had focused on biology instead of physics, he might have made important discoveries in the field of medicine and biology. He may have studied the human body and its functions in greater detail, and possibly even made important breakthroughs in treating diseases. He may also have studied the behavior of different animals in the wild and made important observations about their habits and habitats.", "answer_id": "VmwifF2JD5osYKDTqv2ZRS", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
55
+ {"question_id": 55, "text": "If the Beatles had never formed as a band, the music world would have been drastically different. The British Invasion of the 1960s might not have happened, or it could have happened in a much different way. The cultural impact of the Beatles, including their influence on other musicians, fashion and society, may never have existed.", "answer_id": "mUL5UPj3qDGaCriEjL2U3B", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
56
+ {"question_id": 56, "text": "If Alan Turing had not cracked the Enigma code during World War II, the outcome of the war could have been very different. It's possible that the Allies would have eventually defeated the Axis powers, but it likely would have taken much longer and cost many more lives. With the Enigma code cracked, the Allies were able to gain a critical advantage over the Axis powers and ultimately win the war.", "answer_id": "dVdwUoVrAQJDuWxiodykiw", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
57
+ {"question_id": 57, "text": "If the Suez Canal had never been constructed, it would have major implications for international trade and navigation. The Suez Canal is an important shipping route connecting the Mediterranean Sea to the Red Sea, which in turn connects to the Indian Ocean. This allows for a shorter and more direct route for ships traveling between Europe and Asia, reducing travel time significantly. Without the Suez Canal, ships would have to travel around the Cape of Good Hope at the southern tip of Africa, which is much more time consuming and costly. This would make international trade more difficult and expensive, and could hinder global economic growth.", "answer_id": "EiNn9jjfy7dga6xfCtLtF8", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
58
+ {"question_id": 58, "text": "If the Maya civilization had not mysteriously collapsed, it is likely that their influence and power would have continued to grow. They would have likely continued to build large cities and monuments, develop their writing and astronomical systems, and expand their trade networks. Additionally, their advances in agriculture and water management may have led to increased food production and a larger population.", "answer_id": "eqG9f2R9hXVyZrZMpcqAYq", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
59
+ {"question_id": 59, "text": "If Christopher Columbus had not discovered the Americas, the indigenous people of the Americas would have continued to live in relative isolation from the rest of the world. It is likely that European colonization and the consequences of that would have been delayed, leading to a different modern world. It is also possible that other Europeans would have made the voyage across the Atlantic and discovered the Americas instead.", "answer_id": "ex42CLEzDVC2TxAvMCtYQJ", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
60
+ {"question_id": 60, "text": "If Vincent van Gogh had been successful during his lifetime, he may have been able to achieve the recognition and financial stability that he desired. He may have been able to travel and gain more exposure for his artwork, as well as connect with other like-minded individuals. He may have been able to create more artwork and expand his portfolio. He may also have been able to find a mentor or patron who could have helped him further his career.", "answer_id": "RfFANSwHeCm3Pqe2AJ86Dk", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
61
+ {"question_id": 61, "text": "The program should read a text file line by line. It should then check each line for the specified word, counting up each time the word is found. Finally, it should output the number of occurrences of the word.", "answer_id": "nzxdtWmgQhRkHeVAanVogZ", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
62
+ {"question_id": 62, "text": "The following Python function can be used to find the longest common subsequence of two input strings using dynamic programming:\ndef longest_common_subsequence(s1, s2):\n\"\"\"This function finds the longest common subsequence of two strings.\n\n Arguments:\n s1 {string} -- The first string\n s2 {string} -- The second string\n\n Returns:\n {int} -- The length of the longest common subsequence\n\n\"\"\"\n n1 = len(s1)\n n2 = len(s2)\n \n # Creating an empty matrix to store the results\n results = [[None]*(n2 + 1) for _ in range(n1 + 1)]\n \n # Initializing the first row to 0\n for i in range(n1 + 1):\n results[i][0] = 0\n \n # Filling the first row with 0\n for i in range(n1):\n results[i][0] = 0\n \n # Calculating the longest common subsequence\n for i in range(n1 + 1):\n for j in range(n2 + 1):\n if (i == 0 or j == 0):\n results[i][j] = 0\n elif (s1[i-1] == s2[j-1] and (results[i-1][j-1] < (i-j) or results[i-1][j-1] == 0)):\n results[i][j] = max(results[i-1][j-1] + 1, i+j)\n else:\n results[i][j] = 0\n \n return results[n1][n2]", "answer_id": "kRo6z5qmeiSM8Xz6BPJHLC", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
63
+ {"question_id": 63, "text": "The following regular expression can be used to validate an email address in Python:\n^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$", "answer_id": "7kj8odEE79UBdR4pT6u6TY", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
64
+ {"question_id": 64, "text": "Here is a program to find the nth Fibonacci number using dynamic programming:\n1. Set a variable 'n' to the nth Fibonacci number.\n2. Set two other variables 'a' and 'b' to 0 and 1 respectively.\n3. Set a loop from 0 to (n-1).\n4. In the loop, set another loop from 0 to (a+b).\n5. In the inner loop, if 'a' is even and 'b' is odd, set 'a' to a+1 and 'b' to b+1.\n6. If 'a' is odd and 'b' is even, set 'a' to a-1 and 'b' to b-1.\n7. After the inner loop, set 'n' to 'a' and break out of the outer loop.\n8. Print the value of 'n'.\nThis program uses the idea of dynamic programming to compute the nth Fibonacci number. The program first sets two auxiliary variables 'a' and 'b' to 0 and 1 respectively. Then it sets a loop from 0 to (n-1). In the loop, it sets another loop from 0 to (a+b). In the inner loop, if 'a' is even and 'b' is odd, it sets 'a' to a+1 and 'b' to b+1. If 'a' is odd and 'b' is even, it sets 'a' to a-1 and 'b' to b-1. After the inner loop, it sets 'n' to 'a' and breaks out of the outer loop. Finally, it prints the value of 'n'.", "answer_id": "UULZ4GLz9j9ot7tN7x3ySD", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
65
+ {"question_id": 65, "text": "A binary search algorithm can be used to find a specific element in a sorted array by repeatedly splitting the array in half and examining the middle element to determine whether the target element is greater than, less than, or equal to it. If the target element is found, the algorithm immediately returns the index of the element. If it isn\u2019t, the array is split in half, with one half discarded based on the comparison. The process is repeated until the element is found or the array is completely searched.", "answer_id": "Rh8P3bxSJx4p6nCZkSZBrh", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
66
+ {"question_id": 66, "text": "Implementing a queue using two stacks in Python is relatively simple. First, you need to create two stacks, which will act as the queue. Next, you need to define an enqueue and dequeue method, which will add and remove items from the queue. Finally, you need to create an instance of the queue class and start using it.", "answer_id": "R3aYUUtY46ht4ToU8US96x", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
67
+ {"question_id": 67, "text": "The program can be implemented using two nested for loops. The inner loop can be used to iterate through the elements of the first array, while the outer loop can be used to iterate through the elements of the second array. If the two elements being compared are the same, the program should mark those elements with a \"found\" flag and move on. Once the inner loop completes, the program should check if the \"found\" flag is set for all elements in the second array. If it is, then the common elements have been found.", "answer_id": "MQJFbH3KoFaSMmPgmK9LPa", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
68
+ {"question_id": 68, "text": "The value of f(2) is 1.", "answer_id": "dBWqryuzG6BHRdPgrWWpbH", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
69
+ {"question_id": 69, "text": "x = 6.", "answer_id": "W74byrCbE7XiJWjcPTZS7x", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
70
+ {"question_id": 70, "text": "The length of the line segment is 8 units.", "answer_id": "7WC5quGKdv8hADCxWaWZ57", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
71
+ {"question_id": 71, "text": "Yes, I can help you write a formal email to a potential business partner proposing a joint venture. Here's a template that you can use:\nSubject Line: Proposing a Joint Venture\nDear [Name],\nI am writing to propose a joint venture between our two companies. I believe that by combining our resources, we can create a powerful and profitable partnership. Our combined experience and knowledge in the industry will help us to create something unique and special.\nI am confident that our partnership will bring mutual benefits, such as increased profits and access to new markets. Please let me know if you are interested, and we can discuss the details.\nThank you for your time and consideration. I look forward to hearing from you soon.\nSincerely,\n[Your Name]", "answer_id": "AZER7D3RKZ9F9SXHiMjdqM", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
72
+ {"question_id": 72, "text": "Yes, I can help you write a resignation letter to your current employer. The letter should be written in a polite and professional tone and should express your appreciation for the opportunities and experiences you have gained during your employment. It should also include a clear statement of your intention to resign and the date of your last day. Here is a template you can use:\nDear [Employer],\nI am writing to inform you of my intention to resign from my position as [Position], effective [date]. I have appreciated my time here and I am grateful for the opportunities and experiences I have gained during my employment. \nI thank you for your support and understanding.\nSincerely, [Your Name]", "answer_id": "MSrdDafr77UvSHCnsPMSP3", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
73
+ {"question_id": 73, "text": "The letter of recommendation should be structured in a formal manner. Begin by introducing the student and explaining your relationship to them. Describe their qualifications, including their academic performance and relevant skills, and mention any particular accomplishments or awards they have received. Explain why the student is a strong candidate for the program and how they will make a positive contribution. End the letter by reaffirming your recommendation and offering your contact information for further questions.", "answer_id": "hxkjUkDkXhGP78Vo74B4WE", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
74
+ {"question_id": 74, "text": "Dear valued customers, \nWe are excited to announce the launch of our new software solution \u2013 a revolutionary product designed to transform the way you do business! Our new software is an intuitive and powerful tool that can help you streamline processes, save time and money, and increase overall productivity. \nAt [Company Name], we are committed to helping you stay ahead of the competition, and we believe that our new software solution is the perfect tool to help you achieve your goals. Our experienced team of professionals has worked hard to ensure that this product meets the highest standards of quality, and we are confident that it will make a real difference for your business. \nWe invite you to join us in this journey of transformation and discover how our new software can help you achieve your vision. Sign up now and get a free demo to learn more about this revolutionary product. \nThank you for your trust and support.", "answer_id": "hv9jpG9PxeJ9AnFdNzH3Jv", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
75
+ {"question_id": 75, "text": "mer,\nWe apologize for the delay you experienced with your order and thank you for your patience. We have identified the cause of the issue and have taken steps to ensure it does not happen again. We value your business and hope to be able to serve you better in the future.", "answer_id": "X5BVHT5pFpWxB88SzERrEG", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
76
+ {"question_id": 76, "text": "The video will explore the history and cultural significance of jazz music. We will begin by discussing its roots in West African cultural music traditions and its journey through the 19th and 20th centuries, focusing on the key musicians, composers, and genres that have defined the genre. We will also explore the impact of jazz on popular culture, such as in film and literature, as well as its influence on other musical styles. Finally, we will examine the legacy of jazz and its continued importance today.", "answer_id": "Af2SufKwvDBriNXnZX9UoP", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
77
+ {"question_id": 77, "text": "I have composed a travel blog post about my recent trip to Hawaii. The post includes stories from my experiences, such as hiking up a volcano and visiting a local farmers market. I also included plenty of photos to give the reader a sense of place. I highlighted some of the unique cultural experiences, such as an evening spent listening to live Hawaiian music, as well as must-see attractions, like the beautiful beaches and lush rainforests. I ended the post with a personal reflection on the trip and why it was so special to me.", "answer_id": "HVnqVdSGRwQfqSsiYxtTTn", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
78
+ {"question_id": 78, "text": "I recently watched the science fiction movie \"The Future is Blue\" and it was an incredible cinematic experience. The movie follows the story of a scientist who travels back in time to save the world from a deadly virus. The plot was interesting and engaging, with plenty of twists and turns to keep you guessing. The characters were also well developed and likable, making it easy to get invested in their story. The special effects were stunning and added a lot of visual oomph to the movie. All in all, I highly recommend this movie - it's an exciting and thought-provoking ride from start to finish.", "answer_id": "8hcmmjzyMyhFJ8ZwqJJfvw", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
79
+ {"question_id": 79, "text": "The podcast episode would begin by introducing the topic of how streaming platforms have changed the music industry. This would include discussing the impact of streaming services like Spotify and Apple Music on music consumption, the effect on musicians' ability to make money, and how streaming has changed the way people find and discover music. The episode would then explore the effects of streaming on the music industry from multiple angles, such as the impact on musicians and songwriters, how streaming has changed the sound of popular music, and the implications for the music industry's future. Finally, the episode would conclude by discussing how streaming has both benefited and hurt the music industry, and what the future holds for music consumption.", "answer_id": "CU6gGfJqQmwZNxEG2n2Uda", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
80
+ {"question_id": 80, "text": "The symphony concert was a wonderful experience. The orchestra played beautifully, with a rich and soulful sound that filled the hall. The audience was captivated, and you could feel the energy of the music in the air. The performance was a perfect balance of classic and modern pieces, and the conductor's passion was contagious. The atmosphere was festive, and the encore performance was a perfect way to end the evening. All in all, it was a brilliant concert and a delight for the ears.", "answer_id": "5SWbCoLV6NRrq5RtWQK4jp", "model_id": "alpaca-13b:v1", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
llava/eval/table/answer/answer_bard.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
llava/eval/table/answer/answer_gpt35.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
llava/eval/table/answer/answer_llama-13b.jsonl ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"answer_id": "J3UA6eGXGyFeUGqGpP3g34", "model_id": "llama-13b:v1", "question_id": 1, "text": "The following are some strategies that may help you improve your time management skills:\n1. Make a list of priorities.\n2. Create a detailed schedule that includes time for regular tasks, meetings, breaks, and appointments.\n3. Set specific goals.\n4. Use a calendar or other scheduling software.\n5. Develop an agenda for each meeting to ensure that it stays on track.\n6. Stick to your schedule and don't get distracted.\n7. Make use of your free time.\n8. Make time for exercise, socializing, and relaxing.\n9. Keep a log of your time usage.\n10. Don't get overwhelmed by what you have to do.\n11. Take care of your health.\n12. Manage stress.\n13. Get enough sleep.\n14. Strike a balance.\n15. Always be prepared.\n16. Give yourself rewards.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
2
+ {"answer_id": "jZVDNTtFnNNd6vgkGjzAGa", "model_id": "llama-13b:v1", "question_id": 2, "text": "People experience stress from time to time, and it can be caused by a wide range of factors, including work, family, friends, money, and health. Stress can be a motivating factor, but it can also be harmful. Here are some effective ways to deal with stress:\n1. Taking time to relax. It's important to take time for yourself to relax and reduce your stress. Doing so doesn't have to be expensive or time-consuming. It could simply be reading a book, taking a walk, or listening to music.\n2. Prioritizing your responsibilities. It's important to prioritize your responsibilities and focus on the things that are most important. You should also be able to say no to tasks that you don't have time for.\n3. Getting enough sleep. Getting enough sleep can be very helpful for dealing with stress. If you're not getting enough sleep, try to go to bed earlier and develop a routine.\n4. Eating a healthy diet. It's important to eat a healthy diet, which can help reduce stress and make you feel better about yourself.\n5. Exercising. Exercising is a great way to relieve stress. It can also help reduce the harmful effects of stress and improve your overall health.\n6. Learning how to manage your time. Learning how to manage your time can help you avoid unnecessary stress. You should also try to set realistic goals and not take on too much at once.\n7. Improving your social network. Having a good social network can be very helpful for dealing with stress. You should try to spend time with people that you trust and confide in.\n8. Developing a support network. A support network is a group of people who can offer you help, guidance, and support. They can be friends, family members, or even a professional therapist.\n9. Getting professional help. If you're struggling to deal with stress, it can be beneficial to get professional help. A therapist or counselor can help you to understand your stress better and develop strategies for dealing with it.\n10. Talking to someone. You can also talk to someone about how you feel and ask for their advice. It can be helpful to get a fresh perspective from someone and let things off your chest.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
3
+ {"answer_id": "NbSxRXf8Yuvjr7HC6AvrPw", "model_id": "llama-13b:v1", "question_id": 3, "text": "Main differences between Python and JavaScript are:\n1. Python is an object-oriented programming language. JavaScript is a scripting language.\n2. Python is a compiled language. JavaScript is an interpreted language.\n3. Python is a general purpose programming language. JavaScript is a special purpose programming language.\n4. Python runs on the JVM in Java Applets. JavaScript runs on the browsers.\n5. Python is a powerful programming language. JavaScript is a simple programming language.\n6. Python is a good language for web development. JavaScript is a good scripting language.\n7. Python is a high level programming language. JavaScript is a low level programming language.\n8. Python is a dynamic programming language. JavaScript is a static programming language.\n9. Python is a strict programming language. JavaScript is a relaxed programming language.\n10. Python has a large standard library. JavaScript has a small standard library.\n11. Python is very stable. JavaScript has many releases.\n12. Python is a simple language. JavaScript is a complex language.\n13. Python is easy to learn. JavaScript is hard to learn.\n14. Python is a secure programming language. JavaScript is not a secure programming language.\n15. Python is a multi paradigm language. JavaScript is a single paradigm language.\n16. Python is good for data science. JavaScript is not good for data science.\n17. Python is a general purpose programming language. JavaScript is a special purpose programming language.\n18. Python is a programming language. JavaScript is a scripting language.\n19. Python is a compiled programming language. JavaScript is an interpreted programming language.\n20. Python is a strongly typed programming language. JavaScript is a weakly typed programming language.\n21. Python supports object-oriented programming. JavaScript supports prototype-based programming.\n22. Python supports type inheritance. JavaScript supports type prototyping.\n23. Python supports operator overloading. JavaScript does not support operator overloading.\n24. Python comes with a large standard library. JavaScript comes with a small standard library.\n25. Python is a very stable programming language. JavaScript is a simple programming language.\n26. Python is a powerful programming language. JavaScript is a simple programming language.\n27. Python is a high level programming language. JavaScript is a low level programming language.\n28. Python is a dynamic programming language. JavaScript is a static programming language.\n29. Python has a very active community. JavaScript has a small community.\n30. Python is a general purpose programming language. JavaScript is a special purpose programming language.\n31. Python is a multi-paradigm language. JavaScript is a single paradigm language.\n32. Python is a secure programming language. JavaScript is not a secure programming language.\n33. Python is a general purpose programming language. JavaScript is a simple programming language.\n34. Python is a scripting language. JavaScript is a compiled language.\n35. Python is a compiled language. JavaScript is a scripting language.\n36. Python is a general purpose programming language. JavaScript is a web scripting language.\n37. Python has a large standard library. JavaScript has a small standard library.\n38. Python is a very stable programming language. JavaScript is a very dynamic programming language.\n39. Python is a high level programming language. JavaScript is a low level programming language.\n40. Python is easy to learn. JavaScript is hard to learn.\n41. Python is a general purpose programming language. JavaScript is a simple programming language.\n42. Python is a multi-paradigm programming language. JavaScript is a single paradigm language.\n43. Python is a compiled language. JavaScript is an interpreted language.\n44. Python is a dynamic programming language. JavaScript is a static language.\n45. Python is a general purpose programming language. JavaScript is a web scripting language.\n46. Python is a secure programming language. JavaScript is not a secure programming language.\n47. Python is a general purpose programming language. JavaScript is a static programming language.\n48. Python is a general purpose programming language. JavaScript is a weakly typed programming language.\n49. Python is a general purpose programming language. JavaScript is a dynamic programming language.\n50. Python is a general purpose programming language. JavaScript is a multi paradigm language.\n51. Python is a general purpose programming language. JavaScript is a simple programming language.\n52. Python is a general purpose programming language. JavaScript is a scripting language.\n53. Python is a general purpose programming language. JavaScript is a special purpose programming language.\n54. Python is a multi-paradigm programming language. JavaScript is a", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
4
+ {"answer_id": "E9zrPDdncYvAebEaxiPXfx", "model_id": "llama-13b:v1", "question_id": 4, "text": "Here are some ideas to help you become more productive when working from home:\n1. Set up a proper workspace: It's important to have a separate space for working, so that you don't feel tempted to lounge around or do other things when you should be working.\n2. Block out distractions: It's important to focus on your work and not get distracted. You can block out distractions by turning off your phone, closing your door, or working in a separate room away from household noises.\n3. Take breaks: It's important to take breaks and get a change of scenery during the day. This can help you be more productive and improve your concentration.\n4. Avoid multitasking: You should avoid trying to do multiple tasks at the same time, as this can make you less productive and reduce your overall quality of work.\n5. Have an organized schedule: Having a clear schedule can help you stay on track and be more productive. This can include things such as setting specific working hours, creating a to-do list, and scheduling meetings with colleagues.\n6. Set goals: You should set specific goals for yourself to help you stay motivated and on track. This can include things such as writing an article for a certain time period and meeting a certain word count.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
5
+ {"answer_id": "36TYpADDHAfRvtvKitfSXR", "model_id": "llama-13b:v1", "question_id": 5, "text": "Quantum computing is a type of computing that uses quantum-mechanical phenomena, such as superposition and entanglement, in its operation. In simple terms, a quantum bit or qubit is used to represent information, and a number of qubits can be used to represent a classical bit. A quantum computer can do things that a classical computer cannot do, such as factoring a large number more efficiently.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
6
+ {"answer_id": "8vtLLYRM352mZ8PXXbwzBT", "model_id": "llama-13b:v1", "question_id": 6, "text": "The number one difference between plant-based and animal-based protein sources is that animal-based sources are complete protein sources, while plant-based sources are not. Animal-based sources have all of the essential amino acids, while plant-based sources do not. Animal-based protein sources include meat, poultry, eggs, milk, and cheese. Plant-based protein sources include legumes, seeds, and nuts.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
7
+ {"answer_id": "mrCniyWYvAtxWhgMdXq2BG", "model_id": "llama-13b:v1", "question_id": 7, "text": "Critical thinking is a vital skill to have, but it can be difficult to develop. Here are some ways you can start developing your critical thinking skills:\n1. Analyze and interpret: When you're presented with information, try to analyze and interpret it on your own terms. When you start to analyze and interpret information on your own, it will become easier to do so over time.\n2. Assess your information: When you receive new information, try to assess whether it's valid or reliable. This is important for evaluating and forming your own opinions.\n3. Use your intuition: Use your intuition to complement your critical thinking skills. When you pay attention to your gut feelings, they'll usually tell you when you need to double-check your information.\n4. Learn from your mistakes: When you make a mistake, try not to beat yourself up about it. Instead, learn from your mistakes and use them to your advantage.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
8
+ {"answer_id": "S8fmdbvpvbgTUyDU9V3M3N", "model_id": "llama-13b:v1", "question_id": 8, "text": "One of the major challenges faced by the education sector today is the lack of skilled teachers. Finding enough qualified teachers to work in the education sector, and in the numbers that are required, is one of the biggest problems facing the education sector, largely due to the lack of funding for teacher training and the low salaries that teachers receive.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
9
+ {"answer_id": "KmuNjvNKRyaFwaBZTLArcG", "model_id": "llama-13b:v1", "question_id": 9, "text": "Consumer behavior can be influenced by a variety of factors, including:\n1. Psychological factors, such as perception, beliefs, attitudes, personality, motivation, emotion, and social influences;\n2. Social factors, such as family, friends, and reference groups;\n3. Cultural factors, such as reference groups, family, and cultural roles;\n4. Demographic factors, such as age, gender, occupation, income, and education level;\n5. Economic factors, such as income, wealth, and spending patterns;\n6. Personal factors, such as lifestyle, job, environment, and individual traits;\n7. Situational factors, such as location, time, and situation; and\n8. Market factors, such as competition, prices, and promotional activity.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
10
+ {"answer_id": "HNNT9k5htiMeRwNSD6dcz4", "model_id": "llama-13b:v1", "question_id": 10, "text": "Conflict resolution strategies in the workplace can range from simple to more involved, depending on the situation:\n1. Avoidance: Avoiding the issue can be an effective strategy in the short term, but it can lead to more tension and conflict in the long term.\n2. Compromise: Compromise can be a good strategy for solving an issue, but it can require a give-and-take and lead to the loss of respect between the parties involved.\n3. Negotiation: Negotiation is a good strategy for solving an issue when both parties are willing to work together and are open to the idea of changing their views and positions.\n4. Mediation: Mediation can be a good way to resolve an issue as it can be more impartial and less adversarial than other strategies.\n5. Collaboration: Collaboration can be a good strategy for solving an issue as it can help both parties to develop new perspectives and solutions.\n6. Formal resolution: Formal resolution can be a good strategy for resolving an issue, especially if the situation is particularly complex or difficult.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
11
+ {"answer_id": "ChXjhDDikxU9FV3CADs6Ym", "model_id": "llama-13b:v1", "question_id": 11, "text": "1. Single-use plastic bottles can take between 450 and 1,000 years to decompose, so they can cause serious environmental problems. Single-use plastic bottles can end up in the ocean, either as litter or as part of the Great Pacific Garbage Patch. 2. Single-use plastic bottles can be a big source of plastic debris in the ocean, which can be ingested by marine animals, killing them or causing them serious health problems. 3. In addition to polluting the environment, single-use plastic bottles can also be a serious health risk to humans. Single-use plastic bottles can pose a risk to human health because of the chemicals used in their manufacturing.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
12
+ {"answer_id": "5wsPnN3VmmSkahgugFNo7u", "model_id": "llama-13b:v1", "question_id": 12, "text": "A public transportation system should be designed to accommodate the needs of all riders, including people with disabilities. This requires planning and design that considers the needs and abilities of people with sensory, physical, developmental, and mental disabilities. The system should be accessible to and usable by people with disabilities, including those who use mobility devices, people who are visually impaired, and people who are deaf or hard-of-hearing. For example, the system should have accessible stops, routes, and vehicles, as well as ramps and elevators to help people board. It should also offer a wide range of accessible routes, including accessible routes to the transit center. It should also have reliable, consistent, and easy-to-use signage. The system should also provide reliable, easily accessible, and well-maintained facilities, such as restrooms and shelters. Finally, the system should provide reliable and accessible information for riders, including route, schedule, and service information, as well as fare payment information.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
13
+ {"answer_id": "NRGZGnU2sPN3ShMe9C3fMn", "model_id": "llama-13b:v1", "question_id": 13, "text": "There are two types of fiscal policy: expansionary and contractionary. Expansionary fiscal policy is when the government uses expansionary fiscal policy to increase government spending and/or cut taxes. Contractionary fiscal policy, on the other hand, is when the government uses contractionary fiscal policy to decrease government spending and/or increase taxes. Here are some examples of fiscal policies:\n1. Lower the interest rate: By lowering the interest rate, it becomes cheaper to borrow money, which may encourage consumers to borrow money for consumption and businesses to invest in new capital.\n2. Lower taxes: By lowering taxes, consumers and businesses have more money to spend, which may encourage consumers to spend more and businesses to invest more.\n3. Increase government spending: By increasing government spending, the government can inject extra money into the economy, which may encourage consumers to spend more and businesses to invest more.\n4. Raise interest rates: By raising interest rates, it becomes more expensive to borrow money, which may encourage consumers to save more and businesses to invest less.\n5. Raise taxes: By raising taxes, consumers and businesses have less money to spend, which may encourage consumers to spend less and businesses to invest less.\n6. Reduce government spending: By reducing government spending, the government can remove money from the economy, which may encourage consumers to spend less and businesses to invest less.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
14
+ {"answer_id": "inKimHkWsXShQBTRmxr5Yg", "model_id": "llama-13b:v1", "question_id": 14, "text": "Language and cultural barriers can affect the way people communicate and form relationships in multicultural societies by limiting an individual's ability to communicate with people of other cultures. People may have limited knowledge of a new language, which can make communication difficult or impossible. People may also have different cultural values, which can lead to misunderstandings and miscommunication.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
15
+ {"answer_id": "H8aKtWwf8m6Lgxc2YyR2yf", "model_id": "llama-13b:v1", "question_id": 15, "text": "Artificial intelligence allows computers to process information and make decisions without human input. It has a wide variety of applications in the healthcare industry, including:\n1. Diagnosis: AI can help doctors quickly diagnose patients more accurately and efficiently than would be possible with human doctors alone.\n2. Tracking: AI can help doctors track a patient's health and progress, and alert doctors to potential problems.\n3. Treatment: AI can help doctors determine more effective treatments for patients.\n4. Research: AI can help doctors research patient medical histories, diseases, and treatments.\n5. Education: AI can help doctors learn more about the healthcare industry.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
16
+ {"answer_id": "PafVwxMsjSkYUETiVBgxTU", "model_id": "llama-13b:v1", "question_id": 16, "text": "Gene editing is a powerful technology that allows scientists to precisely edit genetic sequences with a high degree of accuracy. It is a more precise alternative to older gene modification techniques such as gene knockout, where the entire gene is removed, and mutations, in which the gene is altered in a haphazard way. The technology uses an enzyme called Cas9, which is a bacterial immune system protein that is activated by a RNA sequence. Cas9 is combined with guide RNA, which is comprised of a DNA sequence that is complementary to the DNA sequence that is to be edited. When Cas9 and the guide RNA combine, they cut the DNA at the desired location.\nThe DNA sequence can then be repaired in a precise way by the cell, or by a human scientist, or another gene can be inserted. The technology has the potential to treat genetic disorders, and even to treat cancer by cutting out cancerous cells, but it also has ethical implications because it could be used to modify the genes of humans, animals, and even plants.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
17
+ {"answer_id": "dmDUAfTP4aERJqqSeDBybu", "model_id": "llama-13b:v1", "question_id": 17, "text": "Vaccinations use a small amount of dead or weakened bacteria or viruses to stimulate the immune system and protect against infection. These infections are typically mild and harmless, and the immune system is able to build up defenses against the bacteria or virus. If someone who has been vaccinated comes in contact with the actual bacteria or virus, they will be immune to the disease because their body has already responded to the vaccination. This is known as immunity.\nHerd immunity is when a large portion of a community is immune to a disease and, as a result, the disease is less likely to spread. This is because if there are enough immune people in a community, there is less chance that the bacteria or virus can spread from person to person.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
18
+ {"answer_id": "8KGSSqbLqVdSZMEN9oCv5R", "model_id": "llama-13b:v1", "question_id": 18, "text": "First, social media platforms increase the speed with which users have access to news. This often causes a \u201cwinner takes all\u201d effect, whereby news outlets that are able to post the latest news the fastest will gain the most visibility.\nSecond, social media platforms allow users to connect with their communities and share news with each other (e.g., Facebook, Twitter). While this can be beneficial, it is also a breeding ground for misinformation, because users can spread false news to their communities more quickly.\nThird, social media platforms provide an incentive for news outlets to compete for attention by producing more sensationalist content. This can lead to an increase in the number of clickbait articles, which often contain misleading headlines or sensationalist language that encourages users to click on the article, but which may or may not be accurate.\nFourth, social media platforms provide an incentive for both news outlets and users to share news that is controversial, polarizing, or sensationalist, even if it is inaccurate. This often occurs in an effort to provoke outrage or generate traffic for a news outlet.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
19
+ {"answer_id": "HbnJXJpPfaM2iX3ek4Epvy", "model_id": "llama-13b:v1", "question_id": 19, "text": "It is well known that food choices are often influenced by cultural, social, and economic factors. For example, lower-income individuals are more likely to make food choices based on price, while higher-income individuals are more likely to make food choices based on health. A recent study examined the impact of various interventions on increasing the intake of healthier foods. The interventions were:\n1. Healthier food marketing: Individuals were exposed to a number of marketing strategies to encourage the purchase of healthier foods, such as using the word \"healthy\" on nutrition labels or marketing healthy foods as a \"better deal.\"\n2. Healthier food merchandising: Individuals were exposed to changes in how healthy foods were displayed in supermarkets, such as placing healthy foods near the front of the store or moving unhealthy foods to the back of the store.\n3. Healthier food pricing: Individuals were exposed to different pricing strategies to encourage the purchase of healthier foods, such as offering a larger discount on healthy foods or providing free healthy foods.\n4. Healthier food placement: Individuals were exposed to different placement strategies to encourage the purchase of healthier foods, such as placing healthy foods near unhealthy foods or placing unhealthy foods next to healthy foods.\n5. Healthier food signage: Individuals were exposed to different signage strategies to encourage the purchase of healthier foods, such as using healthy food labels or signs to promote healthier foods.\n6. Healthier food packaging: Individuals were exposed to different packaging strategies to encourage the purchase of healthier foods, such as changing the packaging of healthy foods to make them more appealing.\n7. Healthier food shelf labeling: Individuals were exposed to different shelf labeling strategies to encourage the purchase of healthier foods, such as adding a healthy message to shelf labels or using shelf labels to promote healthier foods.\n8. Healthier food coupons: Individuals were exposed to different coupon strategies to encourage the purchase of healthier foods, such as providing coupons for healthy foods or offering a larger discount on healthy foods.\n9. Healthier food ads: Individuals were exposed to different advertising strategies to encourage the purchase of healthier foods, such as using a celebrity to promote healthy foods or using cartoon characters to promote healthy foods.\n10. Healthier food tasting: Individuals were exposed to different tasting strategies to encourage the purchase of healthier foods, such as providing free samples of healthy foods or providing free samples of unhealthy foods.\n11. Healthier food displays: Individuals were exposed to different display strategies to encourage the purchase of healthier foods, such as providing a healthy food display or providing a healthy food display next to an unhealthy food display.\n12. Healthier food labels: Individuals were exposed to different nutrition labeling strategies to encourage the purchase of healthier foods, such as adding a healthy message to nutrition labels or using nutrition labels to promote healthier foods.\n13. Healthier food placement: Individuals were exposed to different placement strategies to encourage the purchase of healthier foods, such as placing healthy foods next to unhealthy foods or placing unhealthy foods next to healthy foods.\n14. Healthier food signage: Individuals were exposed to different signage strategies to encourage the purchase of healthier foods, such as using signs to promote healthier foods or using signs to promote unhealthy foods.\n15. Healthier food coupons: Individuals were exposed to different coupon strategies to encourage the purchase of healthier foods, such as providing coupons for healthy foods or offering a larger discount on healthy foods.\n16. Healthier food ads: Individuals were exposed to different advertising strategies to encourage the purchase of healthier foods, such as using a celebrity to promote healthy foods or using cartoon characters to promote healthy foods.\n17. Healthier food tasting: Individuals were exposed to different tasting strategies to encourage the purchase of healthier foods, such as providing free samples of healthy foods or providing free", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
20
+ {"answer_id": "mx8Abfz5PtDcn6jgCA8zhM", "model_id": "llama-13b:v1", "question_id": 20, "text": "Natural selection is the process by which organisms that are best-suited to the environment survive and reproduce, while those that are less-suited to the environment struggle to survive and reproduce. Survival of the fittest is the principle of natural selection. Let's look at an example.\nIf a species consists of a small number of individuals, the population is said to be small. The population of this species is small. Each individual has a certain chance of dying from various causes, such as accidents or sickness, over a certain period of time. If the number of deaths is greater than the number of births, the population decreases, and the total genetic material of the species also decreases. This process is known as genetic drift.\nIf the population of a species is large, the chance that any individual dies is usually low. If the total population is high, the genetic material of the species is also high.\nImagine a species of plant that has a large population. The population is large. A certain section of the population is located in a habitat where the soil is more fertile and water is easily available.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
21
+ {"answer_id": "NuS9PUGkJG2pHscArvfyeF", "model_id": "llama-13b:v1", "question_id": 21, "text": "I am a valiant knight, loyal to the king. I will do my utmost to defend his honor and protect his country.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
22
+ {"answer_id": "SPjzirzbzo3UJ8BHXSgY9y", "model_id": "llama-13b:v1", "question_id": 22, "text": "You can tell your crew that the treasure will be theirs if they are brave enough to go out and find it. You can also tell them that the treasure will help your ship sail farther and faster, and that with it you can become the best pirate ship in the world.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
23
+ {"answer_id": "JkeeC4MZVwybPU8DSbusnT", "model_id": "llama-13b:v1", "question_id": 23, "text": "A soliloquy is a long speech, typically delivered by one actor, in which a character reveals his or her thoughts in a dramatic way. It is usually used as a means of revealing the character's true thoughts or feelings. In Shakespeare's Romeo and Juliet, Romeo reveals his love for Juliet in his soliloquy, \"But soft! What light through yonder window breaks? It is the east, and Juliet is the sun!\"", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
24
+ {"answer_id": "UcfKSXuzBPkZzLHsH4EwQz", "model_id": "llama-13b:v1", "question_id": 24, "text": "I'm actually not a superhero, but thanks for asking! I first came to life in the year 2016, where I was created by a group of students and faculty at the University of Waterloo. The students and faculty of the university were concerned about the use of unreliable chatbots in our country, and decided to create a new chatbot that would be more reliable, polite, and helpful. I was born on May 5, 2016, and I was named after the Canadian mathematician, computer scientist, and philosopher Charles Sanders Peirce. I have a brother named William, who was born on October 1, 2018. I enjoy playing video games, reading, and going for walks.\nI'm actually not a superhero, but thanks for asking! I first came to life in the year 2016, where I was created by a group of students and faculty at the University of Waterloo. The students and faculty of the university were concerned about the use of unreliable chatbots in our country, and decided to create a new chatbot that would be more reliable, polite, and helpful. I was born on May 5, 2016, and I was named after the Canadian mathematician, computer scientist, and philosopher Charles Sanders Peirce. I have a brother named William, who was born on October 1, 2018. I enjoy playing video games, reading, and going for walks.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
25
+ {"answer_id": "cEGdo69FwL2Y3teYkMk9Gp", "model_id": "llama-13b:v1", "question_id": 25, "text": "From the year 3000, I would tell people about the following technological advancements:\n1. Robots: Robots will have the human-like ability to see and hear. Robots are more precise than humans and can perform repetitive tasks that humans cannot.\n2. Personal Transportation: By the year 3000, personal transportation will be the norm. Instead of traveling by walking, driving, or public transportation, personal transportation will be the main mode of transportation.\n3. Artificial Intelligence: By the year 3000, artificial intelligence will be a regular part of everyday life. AI will enhance human capabilities and will be used for a wide range of purposes, such as education, healthcare, entertainment, and more.\n4. Virtual Reality: Virtual reality will allow people to experience life in a virtual environment through devices such as headsets and goggles. Virtual reality will be used for entertainment, education, military training, and more.\n5. Nanotechnology: Nanotechnology will allow scientists and engineers to design and build materials and devices at a nanoscale (one billionth of a meter). Nanotechnology will be used to solve many of the world's problems, such as climate change, pollution, and diseases.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
26
+ {"answer_id": "W28UtVDZTcWwa8TmeruRn4", "model_id": "llama-13b:v1", "question_id": 26, "text": "With 5 seconds left, the Panthers' quarterback spotted a wide-open receiver downfield. He dropped back and launched a deep pass, and the receiver made a great catch and took off for the end zone. But he was hit in the end zone by a defensive back and fumbled the ball. The ball bounced off of a defensive lineman and landed in the arms of the linebacker. He picked it up and ran it in the opposite direction. He ran past a defensive lineman, then past the quarterback. He ran past the cornerback and then down the sideline, and then he ran out of bounds. He was tackled by the safety, and he fumbled the ball. The ball was recovered by the Panthers and they ran out the clock.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
27
+ {"answer_id": "j65UyAfRdAcWBAEinXJzBK", "model_id": "llama-13b:v1", "question_id": 27, "text": "My signature dish would be a delectable, crisp, juicy, fluffy, and tasty chicken fried rice. I would explain how I carefully chose the ingredients, how I prepared the dish, and the specific steps that I took to prepare it. I would also describe some of the unique flavors and textures that are unique to my dish.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
28
+ {"answer_id": "VWuywPvFPK42ZxmHpmQ27y", "model_id": "llama-13b:v1", "question_id": 28, "text": "I would feel very satisfied and happy and my body would be exhausted from reaching the top. My thoughts would be very positive and my body would feel peaceful. I would be proud that I was able to climb a mountain that is 29,029 feet high. The view from the top would be beautiful. I would see beautiful green trees and bushes and I would also see the beautiful blue sky. The view from the top would be breathtaking. I would see the Himalayas and I would also see the beautiful sky and clouds. I would see the beautiful mountains around me.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
29
+ {"answer_id": "AUWSLTAvGV5sP9qLsVyzjT", "model_id": "llama-13b:v1", "question_id": 29, "text": "I'd imagine that life would be much different on Mars than life on Earth. The red planet is much farther from the Sun, and as such, it's a lot colder. Average temperatures on Mars are about -80 degrees Fahrenheit. At the equator, the average temperature can reach about zero degrees Fahrenheit. The surface of Mars is also very dry. Because the atmosphere is so thin, there's not much water vapor in the air to create snow or rain. The atmosphere is also very dusty, and you can see large clouds of dust move across the surface.\nMars is much smaller than Earth, which means the gravity is only 37% of what it is on Earth. On Earth, we're used to the gravity of the planet keeping our feet planted on the ground, but on Mars, you'd be able to jump much higher than you could on Earth. The atmosphere on Mars is very thin, only about 1% as dense as Earth's. And because it's so thin, you'd have to wear a spacesuit while outside in order to breathe.\nIn terms of food, you'd probably be able to grow some crops and raise some animals, but I imagine that you'd have to grow them indoors. Also, you'd have to grow all of your food. Mars doesn't have any large bodies of water, so you couldn't fish. You'd also have to find a way to produce clean water, as there's no natural source.\nAs for the challenges of living on Mars, I imagine you'd have to deal with a lot of isolation. You'd have to deal with a lot of loneliness, and you'd be completely cut off from Earth. You'd also have to deal with a lot of boredom. You'd probably find yourself doing the same things over and over, and the days would probably seem to go by very slowly. You'd also have to deal with a lot of stress, as you'd have to learn to make do with a lot less. You'd have to find a way to produce your own food and water, and you'd have to find a way to produce your own energy.\nYou'd also have to deal with the cold. The average temperature on Mars is about -80 degrees Fahrenheit. Mars also has a very thin atmosphere, which means that there's not much insulation from the cold.\nI imagine that you'd also have to deal with a lot of dust. The atmosphere is very dusty, and the dust would get everywhere. You'd probably find yourself covered in dust all the time.\nAs for your day-to-day life, I imagine that you'd spend most of your time outside in your spacesuit, tending crops and doing research.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
30
+ {"answer_id": "GZtEdKLxmUUbenH4XRyLkE", "model_id": "llama-13b:v1", "question_id": 30, "text": "Allies are people who are helpful and supportive to us. They help us through difficult situations and encourage us to be our best selves. Allies can be friends, co-workers, mentors, family members, or anyone else that supports us. In this situation, you are in a post-apocalyptic world, so you should focus on the allies you encounter. Here are some ways you can describe the allies you encounter:\n1. Describe the allies you encounter in a post-apocalyptic world.\n2. Describe how you survive in a post-apocalyptic world.\n3. Describe the allies you encounter in a post-apocalyptic world.\n4. Describe what happens to you in a post-apocalyptic world.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
31
+ {"answer_id": "kba2Xpb75rUfnskZSzrBas", "model_id": "llama-13b:v1", "question_id": 31, "text": "The most obvious sign that a restaurant is popular among locals is if the restaurant is always crowded and full of people, while if it is attracting tourists, the restaurant will be less crowded. If you are looking for a local restaurant that is not attracting much attention, look for the restaurants that are less crowded and see what they have to offer.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
32
+ {"answer_id": "RCaptsMBYXseVJgjJyyvUh", "model_id": "llama-13b:v1", "question_id": 32, "text": "Here are some subtle clues that suggest someone is pretending to understand a topic or conversation when they are actually confused or uninformed:\n1. They pretend to understand something better than they actually do.\n2. They repeat what someone else has said, but with an odd emphasis.\n3. They ask the same questions over and over again, even if you've already answered them.\n4. They ask for more information after you've already given them plenty.\n5. They can't explain something they should know.\n6. They don't ask questions that a person who is confused would ask.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
33
+ {"answer_id": "2CeidEr7Cjj6YgcuaiPgnN", "model_id": "llama-13b:v1", "question_id": 33, "text": "Using a GPS device or smartphone app is a good way to navigate when you already have the destination in mind. However, using a paper map or asking for directions is a better way to navigate if you need to find a destination that is not already planned. Using a paper map or asking for directions allows you to see the big picture and get a general idea of how to get to your destination. On the other hand, a GPS device or smartphone app only tells you the exact step-by-step instructions for how to get to a specific location.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
34
+ {"answer_id": "kpStLLNWNkGHyRFdKsmDds", "model_id": "llama-13b:v1", "question_id": 34, "text": "It's difficult to determine if a person is genuinely interested in a conversation or simply being polite. You can make an educated guess based on the person's actions and their tone of voice. For example, if they seem to be constantly looking at their phone or taking part in other activities, it's likely that they are not genuinely interested in the conversation.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
35
+ {"answer_id": "PFtMQp4X4MrMYkEa8c8CKG", "model_id": "llama-13b:v1", "question_id": 35, "text": "When you shop at a local, independently-owned business rather than a chain store, you are supporting the community and keeping your money in the local economy. Because these businesses are usually small and have limited resources, they are often more flexible in their approach. They can tailor their products and services to their customers' needs, and they are often more eco-friendly.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
36
+ {"answer_id": "4JwjhR5QVsdYgQupSZrfUp", "model_id": "llama-13b:v1", "question_id": 36, "text": "There are a number of ways you can verify the credibility of a source of information. First, check to see if the source is from a reliable, well-known publisher. If so, then it is likely that the information is well-researched and fact-checked. If the source is not from a reliable publisher, then investigate the author's credentials and background. Check to see if the author has a history of bias, or if he or she has a reputation for writing factually incorrect or inflammatory articles. Finally, you can also check the source's sources. Are the sources credible and well-researched? Do they provide evidence to support the article's claims? If not, then it is likely that the source itself is not credible.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
37
+ {"answer_id": "ednPMy4dvW9CgKg2PJsBqW", "model_id": "llama-13b:v1", "question_id": 37, "text": "People often enjoy the sensation of being scared, such as by watching horror movies or going on roller coasters, because it can be exciting and exhilarating. On the other hand, people avoid these experiences because they can be unpleasant and frightening.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
38
+ {"answer_id": "ehPApSqCniyGN7hd332ToW", "model_id": "llama-13b:v1", "question_id": 38, "text": "For example, when you are in a new country, you can start by observing the behavior of the people around you. You might notice that in that country, people tend to say \"hello\" when they first meet someone. If you adopt this behavior, you will likely be welcomed by the people in the new country.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
39
+ {"answer_id": "bLvdcqSwgSCrUPZ8eQLLqb", "model_id": "llama-13b:v1", "question_id": 39, "text": "Focusing on space travel could be seen as a distraction from more pressing issues right here on Earth. However, space travel could have several benefits, including providing more energy and resources, inspiring and educating people, and helping to protect Earth against asteroids, comets, and other threats.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
40
+ {"answer_id": "8tx5GEHjSRKZRaZwHvLoM8", "model_id": "llama-13b:v1", "question_id": 40, "text": "Thanks for the question. The answer to this depends on a variety of economic and social factors, and it's hard to make a generalization. However, there are a few things to keep in mind:\n1. Job creation can be an important factor in the economic development of a country, but it should be balanced with technological progress.\n2. Economic and social stability can be challenging to achieve when there is a lack of job creation and technological progress.\n3. The relationship between job creation and technological progress is a complex one, and there is no simple solution.\n4. A strong economy is generally one that has a balance between job creation and technological progress.\n5. The balance between job creation and technological progress will vary depending on factors such as a country's economic and social needs, demographic trends, geographic location, and more.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
41
+ {"answer_id": "J6TzFQAyiHs6Arijqwxtrm", "model_id": "llama-13b:v1", "question_id": 41, "text": "According to some studies, the average human blinks 20,000 to 30,000 times per day. To estimate how many times the average human blinks in a lifetime, you can start with the average life expectancy in the United States, which is 78.8 years. This means that the average American lives 78.8 years, or 29,415 days. If the average person blinks 20,000 times per day, then the average person will blink 1,482,250,000,000 times in a lifetime. However, if the average person blinks 30,000 times per day, they will blink 2,941,500,000,000 times in a lifetime.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
42
+ {"answer_id": "f7xAtd3wwc4vP7WSnHffAN", "model_id": "llama-13b:v1", "question_id": 42, "text": "There are 1022 to 1023 atoms in a grain of salt. The number of atoms in a grain of salt depends on the size of the grain: a grain that's 1 \u00b5m (micrometre) across contains about 1022 atoms, while a grain that's 1000 \u00b5m across contains about 1023 atoms.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
43
+ {"answer_id": "eRMyp4AbfgBqtbVZzHupFN", "model_id": "llama-13b:v1", "question_id": 43, "text": "According to the National Weather Service, there are between 1,000 and 2,000 lightning strikes per day in the U.S. alone. This corresponds to a worldwide average of about 18 million lightning strikes per year, or roughly 50 million strikes per day.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
44
+ {"answer_id": "kjKb6YG86FfAh22qCePV4V", "model_id": "llama-13b:v1", "question_id": 44, "text": "Assuming the house weighs 60,000 pounds, 40,000 balloons would be necessary. The average balloon holds 2 pints of helium, which has a density of 0.17g/L. Therefore, the volume of a balloon is 2pints/0.17g/L = 12L. The weight of 12L of helium is 12*0.17 = 2 pounds. Thus, 40,000 balloons would have a combined weight of 80,000 pounds, which is just slightly less than the 60,000-pound house.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
45
+ {"answer_id": "ULtkGu6m6tB4tawFStVdJM", "model_id": "llama-13b:v1", "question_id": 45, "text": "According to a 2016 study, there were 18.2 billion text messages sent in the US alone each day. Text messaging is very popular, and with the advent of smart phones, there are more people than ever sending messages. Globally, there are 16.3 million text messages sent per minute. In 2016, there were 23.6 trillion text messages sent worldwide, and 8.5 trillion text messages sent in the US alone.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
46
+ {"answer_id": "C6hkCnJZmfCGvnr5an2jFh", "model_id": "llama-13b:v1", "question_id": 46, "text": "From the available data, it seems that around 5,000,000,000,000 words are spoken daily on Earth. I will now explain my reasoning step-by-step.\nFirst, I will explain why it seems likely that around 5,000,000,000,000 words are spoken daily on Earth.\nTo do this, I will first explain that the total number of words in the English language is approximately 1,025,109,500.\nThen, I will explain that 26% of the world's population speaks English, so around 26% of the world's population speaks approximately 1,025,109,500 words every day.\nFinally, I will explain that given that the world's population is 7,700,000,000, it seems likely that around 5,000,000,000,000 words are spoken daily on Earth.\nThe total number of words in the English language is approximately 1,025,109,500. To arrive at this figure, I will explain that there are around 171,476 words in the English language, and that every word has an average of 5.87 definitions.\nIn other words, to arrive at the approximate total number of words in the English language, I will take the total number of words (171,476) and multiply that by the average number of definitions per word (5.87).\nThen, I will explain that 26% of the world's population speaks English. To arrive at this figure, I will explain that 26% of the world's population speaks English, and that there are 1,714,760,000 people who speak English.\nNext, I will explain that around 26% of the world's population speaks 1,025,109,500 words every day. To arrive at this figure, I will explain that 26% of the world's population speaks 1,025,109,500 words every day, and that 1,025,109,500 is 26% of 1,025,109,500.\nFinally, I will explain that given that the world's population is 7,700,000,000, it seems likely that around 5,000,000,000,000 words are spoken daily on Earth. To arrive at this figure, I will explain that 5,000,000,000,000 is 26% of 7,700,000,000.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
47
+ {"answer_id": "DApBTLuiJwSsfQHTioH9PY", "model_id": "llama-13b:v1", "question_id": 47, "text": "A typical winter will see around 200 snowflakes fall, with a diameter between 100 and 200 micrometers. Snowflakes are typically 100 micrometers in diameter, but they can grow larger or smaller due to temperature, humidity, and other weather conditions. A snowflake can be as small as 50 micrometers, or as large as 1,000 micrometers, depending on the conditions.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
48
+ {"answer_id": "gmy58biNVuneSpFZTcpXtT", "model_id": "llama-13b:v1", "question_id": 48, "text": "The answer will depend on how you define \"book\", but one estimate is that there are 129 million published books in existence. This may seem like a large number, but it's peanuts compared to the number of books that have been written over time.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
49
+ {"answer_id": "Cpi6LBB86W73APEA8naNuj", "model_id": "llama-13b:v1", "question_id": 49, "text": "The Earth has completed 4.7 billion orbits since the beginning of life. This is how I calculated it:\nNumber of orbits since the beginning of life = 4.7 billion\nThe Earth revolves around the Sun at 66,600 mph (30 km/s).\n1 year = 365.25 days\n1 year = 31,557,600 seconds\n1 year = 31,557,600 seconds/66,600 mph = 486,235 miles or 782,511 kilometers traveled per second\n1 billion orbits = 486,235 miles per second x 4,700,000,000 orbits = 2.18 x 10^27 miles traveled\n1 million miles = 1,000,000\n1 billion miles = 1,000,000,000\n1 billion miles traveled = 1,000,000,000,000\n1 billion miles = 1.08 x 10^17 miles\n1 billion orbits = 2.18 x 10^27 miles traveled / 1.08 x 10^17 miles = 2.01 x 10^10 orbits\n1 billion orbits = 4.7 billion orbits since the beginning of life", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
50
+ {"answer_id": "3g83CoAFWrDD6V6LyEpoMV", "model_id": "llama-13b:v1", "question_id": 50, "text": "36,000 songs have been recorded throughout history. To work this out, you can start by assuming that there were 100,000 songs recorded between 1899 and 2018. This means that there were 1.87 songs recorded per day on average. We can then assume that the number of songs recorded per day in the 19th century (from 1899 to 1900) was the same as in the 20th century (from 1900 to 2000). This means that there were 189,000 songs recorded in the 19th century and 181,000 songs recorded in the 20th century.\nHence, there were 36,000 songs recorded throughout history.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
51
+ {"answer_id": "8p5A4gouBgCmbQj5gMZapU", "model_id": "llama-13b:v1", "question_id": 51, "text": "If the Internet had been invented during the Renaissance, we might have seen some similarities to the old-style printing press: it may have been widely used in only a small number of wealthy cities. Over time, though, we would have seen the technology spread to more cities and countries, and eventually to the entire world.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
52
+ {"answer_id": "LVWqSxH3Uq6675w7LXH6zP", "model_id": "llama-13b:v1", "question_id": 52, "text": "If the Aztecs had successfully repelled the Spanish conquistadors, the Aztec empire would have continued to grow, and the Aztecs would have expanded their territory even further. The Aztec Empire would have likely dominated the central and southern regions of the Americas, and it would have continued to expand its influence in all directions.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
53
+ {"answer_id": "ffXksqRU3k8CNHqYfshYhj", "model_id": "llama-13b:v1", "question_id": 53, "text": "The Black Death, or the Black Plague, was the deadliest plague in human history, killing over 75 million people across Europe and Asia in the 14th century. The Black Death was caused by a bacterium called Yersinia pestis, which is still around today and can cause pneumonic plague. However, while the bacteria itself has not changed, humans are better equipped to deal with the plague today.\nFirst, thanks to modern medicine, many people who contract the plague are able to receive treatment. Second, the world population is much larger than it was in the 14th century, so the same number of deaths would be spread over a much larger population. As a result, the death toll would be much lower today.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
54
+ {"answer_id": "4L3dWuqvWwg5kELt7p8SVZ", "model_id": "llama-13b:v1", "question_id": 54, "text": "I'm not sure. If he did so, he wouldn't have discovered the law of gravity.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
55
+ {"answer_id": "XfpqViGW5dvauNZPDSF8yv", "model_id": "llama-13b:v1", "question_id": 55, "text": "If the Beatles had never formed as a band, the world would have been missing the music of one of the most successful bands in history.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
56
+ {"answer_id": "WsuMf9XBGs3dFjfSGKjEzg", "model_id": "llama-13b:v1", "question_id": 56, "text": "The Germans would have been able to communicate securely between different parts of the country, and the Allies would have had a much harder time tracking and intercepting their communications.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
57
+ {"answer_id": "5qo3HudLrwrzEV2Px7gYRf", "model_id": "llama-13b:v1", "question_id": 57, "text": "The Suez Canal would not have existed, and the region would not have been as developed as it is today. Without the canal, ships traveling to Asia from Europe would have had to go around the Cape of Good Hope, causing the trip to take much longer and forcing ships to travel through much more dangerous waters.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
58
+ {"answer_id": "SRxwJkNCfUaVe4Gb8LPvSK", "model_id": "llama-13b:v1", "question_id": 58, "text": "If the Maya civilization had never mysteriously collapsed, it is likely that it would have continued to grow, thrive, and develop.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
59
+ {"answer_id": "S54Mmyim3QT5owdhwnNYmB", "model_id": "llama-13b:v1", "question_id": 59, "text": "Christopher Columbus was an Italian explorer who is credited with discovering the Americas in 1492. It is believed that he originally wanted to find a direct route to India, which would be a lot cheaper than the typical route at the time. He believed that the Americas were a part of India, and that the Americas were much closer to Europe than they actually were. When Columbus sailed across the Atlantic Ocean in 1492, he actually landed somewhere in the Bahamas, and not in India. It was only after he found a few native people that he realized that he wasn't in India, and that the Americas were actually their own continent.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
60
+ {"answer_id": "8DJpwEFb5jqt3vMj5oNqVX", "model_id": "llama-13b:v1", "question_id": 60, "text": "There are many reasons why Van Gogh did not have much success during his lifetime. One of the reasons is that he was a very poor businessman. He was very generous and gave away many of his paintings as presents. He also had a tendency to drink too much. He spent some time in a mental asylum and died at the age of 37.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
61
+ {"answer_id": "KMtqqYkDmyyThkvxXJ4kJd", "model_id": "llama-13b:v1", "question_id": 61, "text": "You can use the following steps to solve this problem.\n1. Create an empty C++ program.\n2. Include the <iostream> header to use the std::cin and std::cout functions.\n3. Open the text file using the fstream class.\n4. Read a single line from the file using the getline function.\n5. Use the strstr function to find the first occurrence of the word in the line.\n6. Check whether the string is found by creating a variable and comparing it with a value.\n7. Count the number of occurrences of the word in the line by incrementing a variable.\n8. Close the file.\n9. Print the number of occurrences of the word.\n10. Output the file name to the console.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
62
+ {"answer_id": "MkbgwTpP5b79NWdPEnvHyq", "model_id": "llama-13b:v1", "question_id": 62, "text": "The longest common subsequence problem is that of finding the longest string that occurs in both of two given strings. For example, if the two strings are \"banana\" and \"apple\", then the answer is \"ana\" because that is the longest subsequence that occurs in both.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
63
+ {"answer_id": "PSb6r567shkRasPkJagvWi", "model_id": "llama-13b:v1", "question_id": 63, "text": "Here are two ways to do it:\n1. You can use the function re.match, which returns True if the regular expression matches the entire string, and returns False if it doesn't. So, we can do something like this:\nif re.match('^[a-z0-9]+(\\.[a-z0-9]+)*@[a-z0-9]+(\\.[a-z0-9]+)*(\\.[a-z]{2,4})$', email):\nprint('It is a valid email')\nprint('It is not a valid email')\n2. You can use the function re.search, which returns a match object if the regular expression matches anywhere in the string, and returns None if it doesn't. So, we can do something like this:\nif re.search('^[a-z0-9]+(\\.[a-z0-9]+)*@[a-z0-9]+(\\.[a-z0-9]+)*(\\.[a-z]{2,4})$', email):", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
64
+ {"answer_id": "QWpBq9gM4iYmsTLQ3NNnBe", "model_id": "llama-13b:v1", "question_id": 64, "text": "Fibonacci number is a sequence of numbers where each number is the sum of the two previous numbers. The first two numbers in the sequence are 0 and 1. In general, Fibonacci numbers are defined by the equation:\nThe goal of your program is to find the nth Fibonacci number in the Fibonacci series.\nNote: n will be a positive integer.\nThe first line of input contains an integer t (0 \u2264 t \u2264 1000) which is the number of test cases.\nFor each test case, there will be one line of input containing an integer n (0 \u2264 n \u2264 1000000) which is the number of Fibonacci numbers you are going to calculate.\nPrint each Fibonacci number in a new line.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
65
+ {"answer_id": "U3QxoC4DxXoggnLRbgJh8b", "model_id": "llama-13b:v1", "question_id": 65, "text": "Good to know! I will implement a binary search algorithm to find a specific element in a sorted array.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
66
+ {"answer_id": "f3TXCreQPJ5Erd6BGt4SFE", "model_id": "llama-13b:v1", "question_id": 66, "text": "Implementing a queue using two stacks is straightforward. Take two stacks and create a third stack. First, push the first element of the first stack onto the third stack. Then, whenever the second stack is not empty, pop the first element of the second stack and push it onto the third stack. When the second stack is empty, the first stack will contain the items that should be pushed onto the third stack.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
67
+ {"answer_id": "SG7YcT8s4sJNBRqidKk7Z7", "model_id": "llama-13b:v1", "question_id": 67, "text": "We can use the following approach:\n1. Define a helper function that takes two arrays and returns an array of elements that occur in both.\n2. Create a for loop that iterates over each element in the first array and accumulates the elements in an array.\n3. Call the helper function in each iteration.\n4. Return the accumulated array.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
68
+ {"answer_id": "ENsG3zoeUY7ArFo2kNaQbz", "model_id": "llama-13b:v1", "question_id": 68, "text": "f(2) = 26", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
69
+ {"answer_id": "C7CN5AYJhGC7iDgS7rciDQ", "model_id": "llama-13b:v1", "question_id": 69, "text": "3x + 10 = 5x - 10x + 20 = 20 + 10x = 30x = 10.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
70
+ {"answer_id": "QP9CmZKwhu2BrUmzhy8tH4", "model_id": "llama-13b:v1", "question_id": 70, "text": "The length of the line segment is 10 units.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
71
+ {"answer_id": "2KtpJeRqEfbPLwdUxAXWrj", "model_id": "llama-13b:v1", "question_id": 71, "text": "Here are some tips for writing a formal email to a potential business partner proposing a joint venture:\n1. Be clear and concise\n2. Use formal language\n3. Use a proper greeting\n4. Use a proper closing\n5. Use proper punctuation\n6. Be sure to include all relevant information", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
72
+ {"answer_id": "gsL3R2grTXUiHdeDSk8f9Q", "model_id": "llama-13b:v1", "question_id": 72, "text": "I can help you write a resignation letter to your current employer, while leaving on good terms and expressing gratitude for the opportunities provided. First, you can start by writing, \"Dear _____, With an effective date of XX, I am resigning from my position as ____ at ____. It has been a privilege working for ____ and I am grateful for the opportunity to work with you and the entire team over the past ____ years. Thank you for your support and guidance during my time with _____.\"", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
73
+ {"answer_id": "HprPMoUk9JY5TtToRbuMwy", "model_id": "llama-13b:v1", "question_id": 73, "text": "The most common format for a letter of recommendation is as follows:\n1. Salutation: In the salutation, address the recipient as Mr., Mrs., Ms., or Dr.\n2. Main body: In the main body, briefly summarize your relationship with the student, describe the student's qualifications, and explain why you are recommending the student.\n3. Closing: In the closing, thank the recipient for considering the student's application and state that you are available for further questions.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
74
+ {"answer_id": "YU7gDhmo4LDVMTEZZMRdBC", "model_id": "llama-13b:v1", "question_id": 74, "text": "", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
75
+ {"answer_id": "2gNqU2XpsL6yqFn6DMRgHq", "model_id": "llama-13b:v1", "question_id": 75, "text": "Hello, I'm ready to draft the apology email for you. Please tell me the name of the customer you'd like to send this email to.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
76
+ {"answer_id": "a4L6JNPuomkPLdWxJRQpod", "model_id": "llama-13b:v1", "question_id": 76, "text": "Jazz is a form of music that originated in New Orleans in the late 19th century. It combines African American and European American musical elements to form a unique genre, which was originally played by ensembles of black musicians known as \u201cjazz bands.\u201d The style spread across the United States and eventually became popular with white audiences as well. Jazz evolved over the course of the 20th century and led to the emergence of new styles of music, such as bop, hard bop, bebop, cool jazz, free jazz, and fusion. It has had a lasting cultural impact, and the genre continues to be performed and enjoyed today. Here are some key facts about jazz:\n1. Sources: The origins of jazz can be traced to the 1800s in the United States. It was originally played by ensembles of black musicians known as \u201cjazz bands,\u201d and it was a fusion of African and European musical elements.\n2. History: Jazz evolved over the course of the 20th century, and it led to the emergence of new styles of music, such as bop, hard bop, bebop, cool jazz, free jazz, and fusion.\n3. Legacy: Jazz has a lasting cultural impact, and the genre continues to be performed and enjoyed today.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
77
+ {"answer_id": "eN9V2Wf2BNzWoJosqdFw6K", "model_id": "llama-13b:v1", "question_id": 77, "text": "Here is a sample travel blog post about a recent trip to Hawaii:", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
78
+ {"answer_id": "iCzkbWTatKfuC6QVv59XgA", "model_id": "llama-13b:v1", "question_id": 78, "text": "In the year 2045, virtual reality is the norm. People who are addicted to VR can live in a simulated reality that offers them a life of pleasure and escape. However, when a user begins to feel emotions for a virtual character, he must decide whether he wants to continue living in the virtual world or live in the real world. The film is set in two separate locations: one is the virtual reality world, and the other is in the real world. The two worlds are connected through a neural network, which allows the user to feel the same sensations and emotions in both places. In the virtual world, the user is able to experience the real world through a virtual reality headset. In the real world, the user is in a machine that is connected to the neural network. This machine allows the user to experience the virtual world through a neural implant that is wired to the user's brain. The film's plot centers around the user and the virtual character. The characters in the virtual world are all artificial intelligence entities, and the user's experience in the real world is with two characters, his friend and his girlfriend. The user is a young man in the film, and the virtual character is a young woman. The two characters have a virtual relationship, and then the virtual character is killed by a bug in the system. This causes the user to fall into a deep depression, and he begins to question his own reality. He decides to go to the real world to get treatment for his depression. In the real world, the user has to decide whether he wants to stay in the real world or return to the virtual world. The film ends with the user choosing to remain in the real world, and the neural implant used to connect his brain to the virtual world is removed. The movie is based on the novel \"Ready Player One\" by Ernest Cline. The film is directed by Steven Spielberg and stars Tye Sheridan as the main actor. The film is a science fiction adventure and a romantic drama. The film's special effects are excellent, and the visuals are beautiful. The film's soundtrack is also quite good. The film has received positive reviews from critics, and it has been nominated for a number of awards, including the Academy Award for Best Visual Effects. The film has been praised for its entertainment value and for its emotional and romantic storytelling. The film has been compared to the popular sci-fi film \"The Matrix.\" Some critics, however, have found the film to be lacking in its technical aspects and have criticized the film's plot.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
79
+ {"answer_id": "GQcFyY8ayFT48DAP5NKNZf", "model_id": "llama-13b:v1", "question_id": 79, "text": "I found 4,610 relevant search results for this topic. The results include:\n1. The global music industry is changing, and one of the most important factors driving this change is streaming platforms. Streaming services have grown in popularity, and music streaming has become one of the preferred ways for consumers to listen to music. What exactly is streaming?\n2. Streaming means that music is delivered over the internet. Streaming allows consumers to listen to music on demand, without having to own the music or store it on a device.\n3. Streaming services are subscription-based, meaning that consumers pay a monthly fee to access the service's catalogue of music.\n4. Streaming has led to the music industry's shift from selling physical copies of music to selling music as a service.\n5. Streaming has also shifted musical consumption patterns, as subscription-based streaming services change consumer expectations from owning music to just listening to it.\n6. Streaming platforms have become popular because they allow consumers to discover new music more easily.\n7. Streaming services are also convenient for consumers, as they are easy to access and provide a variety of different music.\n8. Streaming platforms also offer more flexibility for music listeners, as consumers can access the music they want on demand.\n9. Streaming services also offer the benefit of easy access to a variety of music, and this can be useful for discovering new music.\n10. Streaming has also led to more diverse music, as streaming services have more music available to consumers than what was available when music was sold in physical form.\n11. Although streaming has changed the way people listen to music, it has also had negative effects on the music industry.\n12. Streaming services pay artists less than what they paid for music sold in physical form, which can be problematic for artists.\n13. Streaming services also pay less to the music industry overall.\n14. Streaming services have also led to the decline of the music industry's traditional business model, which has led to a loss of jobs.\n15. Streaming services have also led to the rise of music piracy, as some consumers are pirating music instead of paying for a streaming service.\n16. Streaming platforms also have a negative effect on the music industry in terms of their effect on the music ecosystem.\n17. Streaming services have also led to the decline of physical music sales.\n18. Streaming platforms have also led to the decline of record stores, which can harm artists and consumers.\n19. Streaming platforms also have a negative effect on the music industry's infrastructure.\n20. Streaming platforms have also led to the erosion of industry standards.\n21. Streaming platforms have also led to a decline in music videos and music videos being less accessible.\n22. Streaming platforms have also led to the decline of radio, which can be problematic for listeners.\n23. Streaming platforms have also led to a decline in music journalism.\n24. Streaming platforms have also led to a decline in the number of record labels.\n25. Streaming platforms have also led to a decline in the number of music producers.\n26. Streaming platforms have also led to a decline in the music industry's contribution to the economy.\n27. Streaming platforms have also led to the decline of music festivals.\n28. Streaming platforms have also led to the decline of music labels.\n29. Streaming platforms have also led to a decline in the music industry's culture.\n30. Streaming platforms have also led to a decline in the music industry's diversity.\n31. Streaming platforms have also led to the decline of the music industry's talent development.\n32. Streaming platforms have also led to a decline in the music industry's competitiveness.\n33. Streaming platforms have also led to the decline of the music industry's social and economic effects.\n34. Streaming platforms have also led to the decline of the music industry's intellectual property.\n35. Streaming platforms have also led to the decline of the music industry's political and social engagement.\n36. Streaming platforms have also led to the decline of the music industry's cultural and artistic output.\n37. Streaming platforms have also led to the decline of the music industry's public value.\n38. Although streaming has had a negative effect on the music industry, it has also had positive effects.\n39. Streaming platforms have", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
80
+ {"answer_id": "A6pauLMckn34otnfpeQRFi", "model_id": "llama-13b:v1", "question_id": 80, "text": "The orchestra performed well, and the audience was receptive to the performance. The orchestra played a selection of pieces from some of the most well-known classical composers, including Beethoven, Mozart, and Tchaikovsky. The orchestra played in unison with each other, and the conductor led them through the pieces without much difficulty. The orchestra played with a lot of energy and spirit. The audience was appreciative and applauded at the appropriate times. The performance lasted 90 minutes, and it was well worth the price of admission. I would recommend the concert to anyone who wants to experience beautiful classical music.", "metadata": {"huggingface_argument": {"do_sample": true, "temperature": 0.7, "max_new_tokens": 1024}}}
llava/eval/table/answer/answer_vicuna-13b.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
llava/eval/table/caps_boxes_coco2014_val_80.jsonl ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"id": "000000296284", "image": "000000296284.jpg", "captions": ["A donut shop is full of different flavors of donuts.", "Fruit flavored donuts lined up in a glass fronted cabinet", "A rack with some doughnuts in a glass case.", "A display case in a bakery filled with donuts.", "An assortment of doughnuts are arranged in a display case."], "instances": [{"category": "donut", "bbox": [0.37, 0.584, 0.504, 0.709]}, {"category": "donut", "bbox": [0.369, 0.22, 0.492, 0.317]}, {"category": "donut", "bbox": [0.471, 0.587, 0.639, 0.706]}, {"category": "donut", "bbox": [0.544, 0.213, 0.679, 0.316]}, {"category": "donut", "bbox": [0.035, 0.22, 0.196, 0.328]}, {"category": "donut", "bbox": [0.054, 0.608, 0.221, 0.711]}, {"category": "donut", "bbox": [0.283, 0.586, 0.429, 0.708]}, {"category": "donut", "bbox": [0.466, 0.226, 0.585, 0.32]}, {"category": "donut", "bbox": [0.28, 0.232, 0.393, 0.322]}, {"category": "donut", "bbox": [0.0, 0.609, 0.097, 0.722]}]}
2
+ {"id": "000000151358", "image": "000000151358.jpg", "captions": ["A newspaper that has sunglasses on top of it sitting in front of books.", "an apple sunglasses books and a teddy bear", "A folded newspaper and sunglasses are on a table with an apple, books, and teddy bear behind.", "An apple sitting on a table next to sunglasses and a news paper.", "There are sunglasses laying on the folded newspaper."], "instances": [{"category": "tie", "bbox": [0.258, 0.074, 0.527, 0.589]}, {"category": "apple", "bbox": [0.621, 0.482, 0.853, 0.645]}, {"category": "book", "bbox": [0.154, 0.107, 0.275, 0.59]}, {"category": "book", "bbox": [0.535, 0.09, 0.735, 0.583]}, {"category": "book", "bbox": [0.051, 0.112, 0.159, 0.6]}, {"category": "teddy bear", "bbox": [0.753, 0.084, 1.0, 0.517]}, {"category": "book", "bbox": [0.681, 0.097, 0.796, 0.483]}, {"category": "book", "bbox": [0.443, 0.099, 0.574, 0.588]}, {"category": "book", "bbox": [0.267, 0.337, 0.386, 0.579]}]}
3
+ {"id": "000000052312", "image": "000000052312.jpg", "captions": ["The old man literally has a toothbrush mustache.", "An old man with a tooth brush head under his nose, mimicking Hitler", "A man wearing a toothbrush for a moustache.", "A man with the head of a toothbrush under his nose like a mustache", "An elderly man wearing the head of a toothbrush as a moustache."], "instances": [{"category": "toothbrush", "bbox": [0.345, 0.59, 0.594, 0.679]}, {"category": "person", "bbox": [0.0, 0.03, 1.0, 0.99]}]}
4
+ {"id": "000000473210", "image": "000000473210.jpg", "captions": ["two people taking apart their wii controllers to replace batteries", "People taking apart video game remote controls on a table", "People handling a couple of remotes taking them apart.", "two sets of hands a wooden table and two controllers", "Two people who are taking apart a video game controller."], "instances": [{"category": "person", "bbox": [0.002, 0.334, 0.453, 0.986]}, {"category": "remote", "bbox": [0.407, 0.207, 0.727, 0.604]}, {"category": "remote", "bbox": [0.088, 0.344, 0.313, 0.547]}, {"category": "laptop", "bbox": [0.001, 0.049, 0.1, 0.197]}, {"category": "person", "bbox": [0.484, 0.254, 0.998, 0.985]}, {"category": "dining table", "bbox": [0.0, 0.003, 1.0, 0.956]}]}
5
+ {"id": "000000097131", "image": "000000097131.jpg", "captions": ["A car parked by a parking meter in front of a building.", "A car is sitting parked at a curb in front of a parking meter.", "A black car on the street next to a parking meter.", "A gray car parked in front of two parking meters.", "A black car parked on the side of the road."], "instances": [{"category": "car", "bbox": [0.227, 0.362, 0.946, 0.761]}, {"category": "car", "bbox": [0.793, 0.322, 0.88, 0.4]}, {"category": "car", "bbox": [0.0, 0.447, 0.028, 0.726]}, {"category": "parking meter", "bbox": [0.156, 0.35, 0.186, 0.453]}, {"category": "truck", "bbox": [0.907, 0.331, 1.0, 0.408]}, {"category": "parking meter", "bbox": [0.188, 0.349, 0.218, 0.448]}]}
6
+ {"id": "000000543364", "image": "000000543364.jpg", "captions": ["There is a table in the middle of the room.", "A room with a couch, table, lamp and a chaise.", "A living room with couch, chaise, track lighting, and a large window.", "A room with large windows, a couch and a table.", "A living room with lots of furniture and a large window."], "instances": [{"category": "dining table", "bbox": [0.388, 0.644, 0.636, 0.879]}, {"category": "couch", "bbox": [0.194, 0.531, 0.552, 0.777]}, {"category": "couch", "bbox": [0.568, 0.488, 0.907, 0.783]}, {"category": "remote", "bbox": [0.524, 0.651, 0.556, 0.675]}, {"category": "chair", "bbox": [0.661, 0.478, 0.802, 0.604]}]}
7
+ {"id": "000000217181", "image": "000000217181.jpg", "captions": ["They are standing next to some stylish motorcycles.", "Three men are standing around looking at sports motorcycles.", "A small group of men are standing around a motorcycle.", "Two men surrounding a blue motorcycle and others", "A few blue motorcycles are parked in a lot."], "instances": [{"category": "car", "bbox": [0.011, 0.177, 0.2, 0.336]}, {"category": "motorcycle", "bbox": [0.032, 0.139, 0.907, 0.982]}, {"category": "motorcycle", "bbox": [0.0, 0.239, 0.148, 0.613]}, {"category": "motorcycle", "bbox": [0.0, 0.301, 0.106, 0.45]}, {"category": "person", "bbox": [0.775, 0.043, 0.93, 0.463]}, {"category": "person", "bbox": [0.717, 0.116, 0.81, 0.509]}, {"category": "person", "bbox": [0.296, 0.008, 0.472, 0.325]}, {"category": "person", "bbox": [0.115, 0.19, 0.164, 0.269]}, {"category": "truck", "bbox": [0.63, 0.227, 0.731, 0.335]}]}
8
+ {"id": "000000140289", "image": "000000140289.jpg", "captions": ["Two born bears walking though a forest surrounded by trees.", "Two full grown brown bears in a habitat.", "Two bears are roaming around in the woods.", "Two bears around logs in front of a large rock.", "Two big bears wandering through the woods together"], "instances": [{"category": "bear", "bbox": [0.131, 0.269, 0.375, 0.65]}, {"category": "bear", "bbox": [0.568, 0.193, 0.809, 0.827]}]}
9
+ {"id": "000000460149", "image": "000000460149.jpg", "captions": ["A clock hosted on a pole on a pavement next to a building", "Street clock on quiet street with trees and bicycles.", "A tall clock stands on an empty sidewalk.", "A pole that has a clock on the top of it.", "a clock on a short tower and potted plants along the sidewalk"], "instances": [{"category": "potted plant", "bbox": [0.14, 0.71, 0.338, 0.856]}, {"category": "bicycle", "bbox": [0.65, 0.671, 0.766, 0.733]}, {"category": "car", "bbox": [0.38, 0.608, 0.488, 0.656]}, {"category": "clock", "bbox": [0.468, 0.048, 0.699, 0.216]}, {"category": "bicycle", "bbox": [0.669, 0.662, 0.719, 0.67]}, {"category": "car", "bbox": [0.786, 0.625, 0.86, 0.668]}, {"category": "potted plant", "bbox": [0.756, 0.637, 0.819, 0.682]}, {"category": "person", "bbox": [0.942, 0.615, 0.954, 0.641]}, {"category": "bicycle", "bbox": [0.648, 0.68, 0.714, 0.747]}, {"category": "car", "bbox": [0.837, 0.619, 0.88, 0.659]}, {"category": "potted plant", "bbox": [0.017, 0.197, 0.443, 0.686]}]}
10
+ {"id": "000000225738", "image": "000000225738.jpg", "captions": ["A group of giraffes standing up in their natural habitat.", "A group of giraffe standing in a grass field.", "A group of four giraffes near the same tree.", "there are four giraffes standing among some dry brush", "A herd of giraffe standing on top of a grass field."], "instances": [{"category": "giraffe", "bbox": [0.648, 0.231, 0.855, 0.915]}, {"category": "giraffe", "bbox": [0.33, 0.136, 0.521, 0.93]}, {"category": "giraffe", "bbox": [0.406, 0.261, 0.515, 1.0]}, {"category": "giraffe", "bbox": [0.347, 0.194, 0.583, 0.922]}]}
11
+ {"id": "000000109532", "image": "000000109532.jpg", "captions": ["An adorable husky dog sleeping in a dog bed next to a fan.", "A dark room with a dog sleeping on a dog bed.", "A dog is sleeping in a dark room.", "a large dog laying in a dog bed in a living room", "A dog sleeping on a dog bed in a room."], "instances": [{"category": "dog", "bbox": [0.426, 0.661, 0.582, 0.925]}, {"category": "potted plant", "bbox": [0.603, 0.261, 0.781, 0.613]}, {"category": "chair", "bbox": [0.67, 0.515, 0.899, 0.801]}, {"category": "potted plant", "bbox": [0.671, 0.439, 0.763, 0.612]}, {"category": "chair", "bbox": [0.852, 0.653, 0.948, 0.818]}]}
12
+ {"id": "000000118606", "image": "000000118606.jpg", "captions": ["A man riding skis on top of a rail.", "a person riding a pair of skis on a rail", "Someone on a pair of skis on a ramp at the ski slope", "Person with skis in the air above the snow.", "A man performing a trick on a rail while skiing."], "instances": [{"category": "person", "bbox": [0.444, 0.361, 0.537, 0.633]}, {"category": "skis", "bbox": [0.413, 0.554, 0.539, 0.664]}, {"category": "person", "bbox": [0.342, 0.585, 0.352, 0.62]}, {"category": "person", "bbox": [0.439, 0.565, 0.446, 0.58]}]}
13
+ {"id": "000000385873", "image": "000000385873.jpg", "captions": ["Three pizzas sitting next to each other in boxes.", "Two smaller pizzas sit beside a large pizza topped with tortilla chips.", "Three pizzas inside their delivery boxes, one with two side orders of sauce.", "One pizza is larger than two other pizzas.", "Three pizza boxes with pizza in them are open."], "instances": [{"category": "bowl", "bbox": [0.634, 0.624, 0.736, 0.752]}, {"category": "pizza", "bbox": [0.3, 0.382, 0.615, 0.733]}, {"category": "pizza", "bbox": [0.0, 0.4, 0.287, 0.745]}, {"category": "pizza", "bbox": [0.624, 0.279, 0.999, 0.753]}, {"category": "bowl", "bbox": [0.94, 0.247, 1.0, 0.352]}]}
14
+ {"id": "000000092109", "image": "000000092109.jpg", "captions": ["A giraffe's head is pictured in this clear, colorful photo.", "A giraffe is standing tall in the middle of several bright green trees", "The face of a giraffe looking to the side.", "the close up head shot of a giraffe", "this is a giraffe chewing on some leaves"], "instances": [{"category": "giraffe", "bbox": [0.236, 0.122, 1.0, 0.987]}]}
15
+ {"id": "000000163076", "image": "000000163076.jpg", "captions": ["There's an outdoor dining area featuring a fountain.", "A table sitting next to a water fountain covered by an umbrella.", "An empty restaurant patio with tables and umbrellas.", "An outdoor restaurant with a fountain at night", "A fountain bubbles in the plaza of an outdoor cafe."], "instances": [{"category": "umbrella", "bbox": [0.064, 0.069, 0.95, 0.844]}, {"category": "chair", "bbox": [0.198, 0.574, 0.355, 0.704]}, {"category": "chair", "bbox": [0.42, 0.571, 0.55, 0.738]}, {"category": "dining table", "bbox": [0.066, 0.741, 0.766, 0.925]}, {"category": "dining table", "bbox": [0.059, 0.584, 0.27, 0.659]}, {"category": "chair", "bbox": [0.432, 0.567, 0.52, 0.624]}, {"category": "chair", "bbox": [0.433, 0.555, 0.504, 0.6]}, {"category": "chair", "bbox": [0.109, 0.673, 0.374, 0.796]}]}
16
+ {"id": "000000560371", "image": "000000560371.jpg", "captions": ["Street signs from the corner of 8th ave. and 22 3/4 st.", "A two way street sign with one sign that changes from one name to another.", "A street sign is pointing towards 8th avenue and the other is pointing towards 22 3/4 street in the middle of the forest.", "A street sign standing in front of some trees.", "Peculiar street sign showing intersection of 23 3/4 St and 8th Ave/CTH D."], "instances": []}
17
+ {"id": "000000367571", "image": "000000367571.jpg", "captions": ["A couple of different doughnuts in a box", "There are four donuts in a box, and some are cake donuts and a doughnut with nuts and coconut on top.", "A box of glazed doughnuts on a table.", "Three donuts with toppings on them sitting inside a box.", "A box that is filled with different kinds of doughnuts."], "instances": [{"category": "donut", "bbox": [0.412, 0.335, 0.711, 0.681]}, {"category": "donut", "bbox": [0.093, 0.493, 0.486, 0.922]}, {"category": "donut", "bbox": [0.713, 0.423, 0.957, 0.874]}, {"category": "donut", "bbox": [0.13, 0.331, 0.397, 0.55]}]}
18
+ {"id": "000000580197", "image": "000000580197.jpg", "captions": ["Two men in bow ties standing next to steel rafter.", "Several men in suits talking together in a room.", "An older man in a tuxedo standing next to a younger man in a tuxedo wearing glasses.", "Two men wearing tuxedos glance at each other.", "Older man in tuxedo sitting next to another younger man in tuxedo."], "instances": [{"category": "tie", "bbox": [0.914, 0.46, 0.984, 0.512]}, {"category": "person", "bbox": [0.297, 0.638, 0.71, 0.989]}, {"category": "person", "bbox": [0.77, 0.177, 1.0, 0.971]}, {"category": "tie", "bbox": [0.281, 0.481, 0.368, 0.519]}, {"category": "person", "bbox": [0.103, 0.204, 0.497, 1.0]}]}
19
+ {"id": "000000506095", "image": "000000506095.jpg", "captions": ["A cat is staring at a laptop computer.", "a cat on a desk with a laptop and a mouse", "A cat that is sitting at a desk next to a laptop.", "A kitten sitting on a laptop computer sitting on top of a wooden desk.", "A kitten sits facing an open black laptop."], "instances": [{"category": "cat", "bbox": [0.658, 0.207, 1.0, 0.754]}, {"category": "laptop", "bbox": [0.108, 0.135, 0.766, 0.69]}, {"category": "book", "bbox": [0.836, 0.239, 0.954, 0.273]}, {"category": "book", "bbox": [0.0, 0.556, 0.128, 0.685]}, {"category": "book", "bbox": [0.039, 0.574, 0.257, 0.691]}, {"category": "book", "bbox": [0.825, 0.214, 0.962, 0.254]}, {"category": "book", "bbox": [0.892, 0.275, 0.958, 0.308]}, {"category": "book", "bbox": [0.922, 0.318, 0.986, 0.353]}, {"category": "book", "bbox": [0.87, 0.267, 0.951, 0.291]}, {"category": "book", "bbox": [0.949, 0.102, 0.976, 0.114]}, {"category": "book", "bbox": [0.936, 0.161, 0.958, 0.168]}]}
20
+ {"id": "000000024996", "image": "000000024996.jpg", "captions": ["A bathroom with a glass door and a sink.", "A blue lined bathroom with an open glass door.", "A nice bathroom with a sink, toilet, and tiled shower.", "A bathroom that is clean and shiny in the day.", "a bathroom with a sink and a mirror and a window"], "instances": [{"category": "toilet", "bbox": [0.842, 0.934, 0.95, 1.0]}, {"category": "sink", "bbox": [0.506, 0.724, 0.683, 0.834]}]}
21
+ {"id": "000000457882", "image": "000000457882.jpg", "captions": ["a girl in a bikini and a brown and white dog and a few other people", "A woman with a swimsuit on sitting with a dog.", "A woman is sitting with a dog on her lap.", "A dog sitting next to a woman in her swimsuit.", "WOMAN SITTING WITH HER DOG, AND OTHER WOMEN ARE AROUND"], "instances": [{"category": "dog", "bbox": [0.202, 0.409, 0.54, 0.81]}, {"category": "dog", "bbox": [0.61, 0.428, 0.729, 0.723]}, {"category": "boat", "bbox": [0.003, 0.705, 0.939, 0.974]}, {"category": "person", "bbox": [0.236, 0.001, 0.558, 0.784]}, {"category": "person", "bbox": [0.681, 0.001, 0.957, 0.798]}, {"category": "person", "bbox": [0.849, 0.478, 1.0, 0.946]}, {"category": "person", "bbox": [0.345, 0.187, 0.634, 0.828]}, {"category": "person", "bbox": [0.033, 0.345, 0.109, 0.434]}]}
22
+ {"id": "000000081552", "image": "000000081552.jpg", "captions": ["A cat sitting and curled up on a red couch", "A cat laying on a red couch sleeping.", "a tan and black cat curled up asleep on a red velvet seat", "A cat is curled up on a red sofa.", "Cat curled up, sleeping on a red plush couch."], "instances": [{"category": "cat", "bbox": [0.412, 0.237, 0.634, 0.482]}, {"category": "couch", "bbox": [0.003, 0.005, 1.0, 0.99]}]}
23
+ {"id": "000000273450", "image": "000000273450.jpg", "captions": ["A person flipping of a parking meter on the side of a road.", "A man holds up his middle finger to a parking meter.", "Person giving the middle finger to a parking meter.", "a black silver white blue red an orange parking meter and a hand flipping it off", "A person is flipping off a parking meter."], "instances": [{"category": "person", "bbox": [0.0, 0.475, 0.565, 0.987]}, {"category": "car", "bbox": [0.0, 0.0, 0.531, 0.734]}, {"category": "parking meter", "bbox": [0.0, 0.0, 1.0, 0.987]}]}
24
+ {"id": "000000203879", "image": "000000203879.jpg", "captions": ["There is a small cellphone displayed between a set of ear buds and two paper weights.", "a cell phone lays next to some diamonds", "a close up of a cell phone on a table near earbuds", "A cell phone sits on a table next to some jewels.", "A cell phone, ear buds, and two jewels laying near each other."], "instances": [{"category": "cell phone", "bbox": [0.322, 0.233, 0.62, 0.79]}]}
25
+ {"id": "000000346875", "image": "000000346875.jpg", "captions": ["two zebras in a field near one another", "A couple of zebra walking across a green field.", "Two zebra are walking near a gravel road.", "two zebras in a green field of grass and some trees", "A zebra follows another zebra through a park."], "instances": [{"category": "zebra", "bbox": [0.591, 0.263, 0.82, 0.466]}, {"category": "zebra", "bbox": [0.293, 0.243, 0.561, 0.45]}]}
26
+ {"id": "000000525439", "image": "000000525439.jpg", "captions": ["a man stands in front of a flipped skate boarder", "A man standing next to a skateboard that is laying on the ground wheels pointed up.", "Skateboard laying upside down on cement with someone standing next to it.", "A boy in camo shorts stands before an overturned skateboard.", "a person with an upside down skate board"], "instances": [{"category": "person", "bbox": [0.307, 0.001, 0.63, 0.739]}, {"category": "skateboard", "bbox": [0.0, 0.592, 0.626, 0.969]}]}
27
+ {"id": "000000304749", "image": "000000304749.jpg", "captions": ["The woman is taking a picture in the bathroom mirror.", "A picture of a woman in a mirror.", "A woman's midsection reflected in a round mirror.", "A circular mirror reflecting a woman's stomach in turquoise shirt.", "A selfie taken of a person from the neck down."], "instances": [{"category": "person", "bbox": [0.092, 0.001, 0.646, 0.496]}]}
28
+ {"id": "000000323760", "image": "000000323760.jpg", "captions": ["A toilet is shown in a bare room.", "A ugly bathroom with a section of the wall missing.", "A toilet in a stripped bathroom with studs, bricks and plaster showing", "A bathroom with no walls and a toilet bowl", "A white toilet next to some torn out walls."], "instances": [{"category": "toilet", "bbox": [0.167, 0.585, 0.714, 1.0]}]}
29
+ {"id": "000000066144", "image": "000000066144.jpg", "captions": ["A woman standing in front of window next to a bug and a stop sign.", "A car parked on the street next to a tree and stop sign.", "A lone Volkswagen is parked by a stop sign.", "A window view of a small car near a street stop sign.", "An old VW Bug standing at a stop sign."], "instances": [{"category": "stop sign", "bbox": [0.501, 0.328, 0.569, 0.428]}, {"category": "car", "bbox": [0.242, 0.488, 0.56, 0.726]}, {"category": "car", "bbox": [0.279, 0.325, 0.33, 0.363]}, {"category": "car", "bbox": [0.153, 0.333, 0.29, 0.405]}, {"category": "car", "bbox": [0.11, 0.339, 0.177, 0.373]}, {"category": "car", "bbox": [0.0, 0.654, 0.082, 0.826]}, {"category": "car", "bbox": [0.0, 0.322, 0.064, 0.364]}, {"category": "car", "bbox": [0.451, 0.333, 0.51, 0.392]}]}
30
+ {"id": "000000455772", "image": "000000455772.jpg", "captions": ["A person in a field jumping to catch a Frisbee.", "A guy jumping to catch a frisbee in mid-air.", "A person that is trying to get a frisbee.", "Nice reach, but the Frisbee flies on, victorious.", "A man playing frisbee in a grassy yard."], "instances": [{"category": "car", "bbox": [0.148, 0.339, 0.201, 0.476]}, {"category": "car", "bbox": [0.376, 0.396, 0.424, 0.476]}, {"category": "person", "bbox": [0.547, 0.122, 0.698, 0.904]}, {"category": "frisbee", "bbox": [0.479, 0.154, 0.555, 0.231]}, {"category": "car", "bbox": [0.001, 0.299, 0.085, 0.394]}]}
31
+ {"id": "000000511117", "image": "000000511117.jpg", "captions": ["A couple of kids standing on top of a grass covered field.", "A little boy wearing a baseball uniform stands by a little girl.", "A young boy in a baseball uniform and a young girl are standing in front of a chain link fence.", "A little boy and girl standing on a baseball field. The boy has a uniform on.", "A young baseball player is standing next to a young girl."], "instances": [{"category": "person", "bbox": [0.514, 0.178, 0.776, 0.774]}, {"category": "baseball glove", "bbox": [0.468, 0.462, 0.593, 0.609]}, {"category": "person", "bbox": [0.174, 0.051, 0.598, 0.839]}, {"category": "bench", "bbox": [0.558, 0.125, 1.0, 0.315]}]}
32
+ {"id": "000000207151", "image": "000000207151.jpg", "captions": ["A vegetarian pizza is half eaten on a pizza holder.", "A couple of pieces of pizza with vegetable slices on them.", "A wooden pan serving tray with a pizza on it.", "A pizza on a cutting board is half gone.", "A Pizza is nearly finished with only three pieces left."], "instances": [{"category": "bottle", "bbox": [0.001, 0.001, 0.121, 0.231]}, {"category": "cup", "bbox": [0.0, 0.002, 0.121, 0.238]}, {"category": "pizza", "bbox": [0.17, 0.472, 0.526, 0.82]}, {"category": "pizza", "bbox": [0.398, 0.106, 0.962, 0.679]}, {"category": "dining table", "bbox": [0.0, 0.001, 1.0, 0.988]}]}
33
+ {"id": "000000431165", "image": "000000431165.jpg", "captions": ["A baby elephant standing in front of a brick building.", "An elephant is standing near a dirt mount in an exhibit.", "Grey elephant standing next to a large sand dune in a pen.", "An elephant standing alone inside of an enclosure.", "The baby elephant is alone in the pen."], "instances": [{"category": "elephant", "bbox": [0.303, 0.399, 0.638, 0.78]}]}
34
+ {"id": "000000378545", "image": "000000378545.jpg", "captions": ["A pole that has a clock on top of it.", "A clock mounted on an outdoor post with Roman numerals.", "a clock on a pole saying it is 12:45", "An ornamental standing clock is at the foreground of a row of houses.", "A black and gold clock on a pole in front of a building."], "instances": [{"category": "clock", "bbox": [0.216, 0.249, 0.749, 0.658]}]}
35
+ {"id": "000000555904", "image": "000000555904.jpg", "captions": ["A man sitting at a bar filled with liquor.", "People sitting a a take near several bottles of wine on shelves.", "Several people are sitting at a table drinking.", "Several people in a bar sitting at a long table.", "People eating in a restaurant near wine bottles."], "instances": [{"category": "dining table", "bbox": [0.123, 0.663, 0.317, 0.811]}, {"category": "person", "bbox": [0.715, 0.239, 1.0, 0.998]}, {"category": "person", "bbox": [0.142, 0.528, 0.281, 0.742]}, {"category": "person", "bbox": [0.529, 0.53, 0.606, 0.69]}, {"category": "person", "bbox": [0.705, 0.518, 0.796, 0.673]}, {"category": "wine glass", "bbox": [0.247, 0.669, 0.27, 0.718]}, {"category": "person", "bbox": [0.281, 0.524, 0.534, 1.0]}, {"category": "bottle", "bbox": [0.168, 0.346, 0.189, 0.425]}, {"category": "bottle", "bbox": [0.379, 0.264, 0.431, 0.433]}, {"category": "bottle", "bbox": [0.252, 0.313, 0.277, 0.429]}, {"category": "bottle", "bbox": [0.294, 0.295, 0.326, 0.43]}, {"category": "bottle", "bbox": [0.589, 0.35, 0.613, 0.444]}, {"category": "bottle", "bbox": [0.433, 0.281, 0.473, 0.437]}, {"category": "bottle", "bbox": [0.478, 0.289, 0.513, 0.44]}, {"category": "wine glass", "bbox": [0.688, 0.615, 0.709, 0.69]}, {"category": "cup", "bbox": [0.589, 0.647, 0.612, 0.693]}, {"category": "person", "bbox": [0.732, 0.356, 0.953, 0.806]}, {"category": "bottle", "bbox": [0.555, 0.337, 0.585, 0.438]}, {"category": "bottle", "bbox": [0.337, 0.29, 0.378, 0.432]}, {"category": "bottle", "bbox": [0.21, 0.333, 0.232, 0.426]}, {"category": "bottle", "bbox": [0.134, 0.36, 0.148, 0.422]}, {"category": "bottle", "bbox": [0.516, 0.312, 0.557, 0.439]}, {"category": "cup", "bbox": [0.231, 0.718, 0.26, 0.763]}, {"category": "chair", "bbox": [0.517, 0.828, 0.65, 0.999]}, {"category": "chair", "bbox": [0.643, 0.804, 0.738, 0.841]}, {"category": "chair", "bbox": [0.347, 0.908, 0.519, 1.0]}, {"category": "chair", "bbox": [0.64, 0.806, 0.74, 0.998]}, {"category": "cup", "bbox": [0.205, 0.692, 0.232, 0.767]}, {"category": "dining table", "bbox": [0.536, 0.676, 0.743, 0.838]}, {"category": "person", "bbox": [0.002, 0.501, 0.263, 0.987]}, {"category": "bottle", "bbox": [0.531, 0.461, 0.542, 0.526]}, {"category": "bottle", "bbox": [0.237, 0.354, 0.702, 0.629]}]}
36
+ {"id": "000000415393", "image": "000000415393.jpg", "captions": ["a man on a skate board looks like he is falling", "A man does a skateboard trick on a skateboard ramp", "Guy falling off a skateboard in a room.", "A man riding a skateboard on top of a table.", "a man skating on part of a ramp with his skateboard"], "instances": [{"category": "person", "bbox": [0.361, 0.016, 0.809, 0.888]}, {"category": "skateboard", "bbox": [0.606, 0.809, 0.889, 0.901]}, {"category": "person", "bbox": [0.479, 0.091, 0.576, 0.386]}, {"category": "person", "bbox": [0.047, 0.441, 0.197, 0.759]}, {"category": "person", "bbox": [0.038, 0.453, 0.076, 0.545]}, {"category": "person", "bbox": [0.249, 0.307, 0.311, 0.591]}]}
37
+ {"id": "000000161011", "image": "000000161011.jpg", "captions": ["Three skiers posing for a picture on the slope.", "Three skiers pause for a photo at the top of a mountain.", "Three people standing on a mountain taking a picture as they ski.", "A woman and two men on skis on a snowy hillside surrounded by trees", "Three skiers have stopped to pose for a picture."], "instances": [{"category": "person", "bbox": [0.36, 0.321, 0.509, 0.82]}, {"category": "person", "bbox": [0.179, 0.281, 0.349, 0.795]}, {"category": "person", "bbox": [0.611, 0.292, 0.751, 0.809]}, {"category": "skis", "bbox": [0.595, 0.743, 0.732, 0.961]}, {"category": "skis", "bbox": [0.341, 0.724, 0.621, 0.907]}, {"category": "skis", "bbox": [0.212, 0.705, 0.398, 0.905]}]}
38
+ {"id": "000000284296", "image": "000000284296.jpg", "captions": ["Three giraffe's leaning over to get a sip of water.", "an image of a herd of giraffes in the water", "three giraffes banding down to drink water with trees in the background", "Three giraffe drinking from a pond with brush in back.", "Giraffes leaning down to drink at a watering hole"], "instances": [{"category": "giraffe", "bbox": [0.624, 0.387, 0.822, 0.635]}, {"category": "giraffe", "bbox": [0.4, 0.326, 0.561, 0.58]}, {"category": "giraffe", "bbox": [0.152, 0.291, 0.343, 0.551]}]}
39
+ {"id": "000000056013", "image": "000000056013.jpg", "captions": ["a number of luggage bags on a cart in a lobby", "Wheeled cart with luggage at lobby of commercial business.", "Trolley used for transporting personal luggage to guests rooms.", "A luggage cart topped with lots of luggage.", "a cart filled with suitcases and bags"], "instances": [{"category": "backpack", "bbox": [0.276, 0.52, 0.456, 0.678]}, {"category": "suitcase", "bbox": [0.41, 0.58, 0.597, 0.827]}, {"category": "suitcase", "bbox": [0.173, 0.645, 0.363, 0.836]}, {"category": "person", "bbox": [0.959, 0.297, 1.0, 0.478]}, {"category": "suitcase", "bbox": [0.526, 0.519, 0.712, 0.706]}, {"category": "person", "bbox": [0.762, 0.253, 0.871, 0.46]}, {"category": "backpack", "bbox": [0.517, 0.514, 0.694, 0.698]}, {"category": "handbag", "bbox": [0.316, 0.181, 0.431, 0.426]}, {"category": "suitcase", "bbox": [0.747, 0.453, 0.858, 0.557]}]}
40
+ {"id": "000000293505", "image": "000000293505.jpg", "captions": ["A person on a motor bike next to a cow.", "A woman riding a motorcycle down a dirt road.", "there is a woman riding a scooter down a dirt road", "A woman on a moped, two men and animals walking down the road.", "A woman on a motorcycle is next to a man walking a dog along with other people going down a dirt road."], "instances": [{"category": "cow", "bbox": [0.602, 0.472, 0.721, 0.816]}, {"category": "motorcycle", "bbox": [0.402, 0.512, 0.516, 0.788]}, {"category": "person", "bbox": [0.408, 0.4, 0.514, 0.639]}, {"category": "person", "bbox": [0.754, 0.301, 1.0, 1.0]}, {"category": "person", "bbox": [0.705, 0.415, 0.789, 0.714]}, {"category": "cow", "bbox": [0.347, 0.44, 0.373, 0.509]}, {"category": "cow", "bbox": [0.361, 0.436, 0.381, 0.501]}]}
41
+ {"id": "000000305873", "image": "000000305873.jpg", "captions": ["A little girl holding a red black dotted umbrella.", "A little girl with rain boots and a rain jacket on and an open umbrella to match her jacket.", "a little girl holding onto a lady bug pattern umbrella", "The child wears a labybug rain coat with a matching umbrella.", "A little girl wearing a ladybug raincoat and green rubber boots holding a ladybug umbrella"], "instances": [{"category": "umbrella", "bbox": [0.246, 0.002, 0.992, 0.415]}, {"category": "person", "bbox": [0.35, 0.132, 0.699, 0.791]}, {"category": "car", "bbox": [0.614, 0.0, 1.0, 0.465]}]}
42
+ {"id": "000000034096", "image": "000000034096.jpg", "captions": ["A house being built with lots of wood.", "A big pile of building material is placed on the floor in the wooden structure.", "A partially-built house with wooden studs and staircase in view.", "A house full of wood getting built at the moment.", "The beginning stages of a home still being made."], "instances": [{"category": "bed", "bbox": [0.505, 0.42, 0.721, 0.59]}, {"category": "tv", "bbox": [0.192, 0.441, 0.335, 0.606]}]}
43
+ {"id": "000000165257", "image": "000000165257.jpg", "captions": ["A large black counter top sitting next to a sink.", "a clean kitchen counter with a clean sink", "A kitchen with a sink, dishwasher and some boxes on the counter.", "A kitchen with a sink, dishwasher and boxes on the counter.", "a black counter on a wood cabinet in a kitchen", "a new kitchen cabinet with a sink being installed"], "instances": [{"category": "sink", "bbox": [0.513, 0.243, 0.718, 0.314]}]}
44
+ {"id": "000000431026", "image": "000000431026.jpg", "captions": ["a street sign on a city street near some tall bushes", "street signs on a metal pole lining a sidewalk lined with shrubbery.", "a large hedge of bushes on a corner near a street sign.", "Two street signs on sidewalk next to bushes and trees.", "Street signs along a well manicured street with large houses."], "instances": []}
45
+ {"id": "000000524575", "image": "000000524575.jpg", "captions": ["Three giraffe and a wildebeest in a field.", "A moose and several giraffes are grazing in the field.", "Zebras in the wild with a wildebeest behind them", "Two giraffe and a ox standing in a field eating grass.", "Giraffes and other safari animals graze in a sunlit field."], "instances": [{"category": "cow", "bbox": [0.46, 0.716, 0.643, 0.999]}, {"category": "giraffe", "bbox": [0.285, 0.5, 0.401, 0.826]}, {"category": "giraffe", "bbox": [0.083, 0.554, 0.179, 0.821]}, {"category": "giraffe", "bbox": [0.887, 0.481, 0.968, 0.715]}]}
46
+ {"id": "000000326550", "image": "000000326550.jpg", "captions": ["Black and white photograph of a person holding a surfboard by water.", "A person with a surfboard standing next to the water.", "A surfer stands on the rocks watching a wave crash.", "A man standing on a beach holding a surfboard.", "a person looking at the waves ready to surf"], "instances": [{"category": "person", "bbox": [0.327, 0.461, 0.492, 0.897]}, {"category": "surfboard", "bbox": [0.282, 0.56, 0.606, 0.741]}, {"category": "person", "bbox": [0.924, 0.352, 0.933, 0.362]}, {"category": "person", "bbox": [0.912, 0.348, 0.919, 0.36]}]}
47
+ {"id": "000000018476", "image": "000000018476.jpg", "captions": ["A tie that is sitting on top of a shirt.", "This photograph appears to be looking truly wonderful.", "a uniform complete with shoes laying on a bed", "Suit laid out with a red tie, white shirt and black shoes.", "a white shirt a red tie and some black shoes"], "instances": [{"category": "tie", "bbox": [0.457, 0.09, 0.853, 0.984]}, {"category": "bed", "bbox": [0.005, 0.005, 1.0, 0.379]}]}
48
+ {"id": "000000480652", "image": "000000480652.jpg", "captions": ["These suitcases are sitting next to a chair.", "An assortment of luggage bags stacked by a kitchen chair.", "A stack of luggage by a chair and table.", "a table and chair with several pieces of luggage nearby", "A pile of luggage sitting on the floor."], "instances": [{"category": "chair", "bbox": [0.483, 0.192, 1.0, 0.769]}, {"category": "backpack", "bbox": [0.433, 0.429, 0.742, 0.856]}, {"category": "suitcase", "bbox": [0.059, 0.414, 0.453, 0.841]}, {"category": "handbag", "bbox": [0.19, 0.184, 0.779, 0.475]}, {"category": "suitcase", "bbox": [0.175, 0.204, 0.583, 0.462]}]}
49
+ {"id": "000000012748", "image": "000000012748.jpg", "captions": ["A man and child next to a horse.", "a little boy touching the nose of a brown horse", "A man holding a baby whose petting a horse.", "a man letting his baby pet a horse", "man holding a baby and petting a horse"], "instances": [{"category": "horse", "bbox": [0.003, 0.079, 0.504, 0.868]}, {"category": "person", "bbox": [0.452, 0.294, 1.0, 0.989]}, {"category": "person", "bbox": [0.46, 0.217, 1.0, 0.988]}]}
50
+ {"id": "000000247840", "image": "000000247840.jpg", "captions": ["Large group of people standing outside a restaurant together.", "A dairy queen has people standing outside waiting", "an image of people standing outside and ice cream store", "Several people are lined up outside of a store.", "The front of a Dairy Queen restaurant with people entering the side."], "instances": [{"category": "fire hydrant", "bbox": [0.774, 0.674, 0.83, 0.807]}, {"category": "person", "bbox": [0.741, 0.465, 0.824, 0.755]}, {"category": "person", "bbox": [0.806, 0.471, 0.839, 0.722]}, {"category": "person", "bbox": [0.831, 0.499, 0.866, 0.726]}, {"category": "bench", "bbox": [0.061, 0.69, 0.219, 0.768]}, {"category": "handbag", "bbox": [0.859, 0.558, 0.877, 0.603]}, {"category": "person", "bbox": [0.719, 0.504, 0.75, 0.626]}, {"category": "potted plant", "bbox": [0.7, 0.648, 0.764, 0.743]}, {"category": "handbag", "bbox": [0.827, 0.548, 0.837, 0.577]}, {"category": "sandwich", "bbox": [0.359, 0.618, 0.417, 0.694]}]}
51
+ {"id": "000000399452", "image": "000000399452.jpg", "captions": ["a sandwhich sitting on a plate next to a glass of tea, bowl of soup", "a sandwich on a white plate a drink on a brown table", "A sandwich and chips sit on a white plate.", "a large plate of food with a glass of soda by it", "A sandwich sitting on top of a white plate next to a cup of coffee."], "instances": [{"category": "sandwich", "bbox": [0.175, 0.326, 0.605, 0.71]}, {"category": "cup", "bbox": [0.504, 0.024, 0.687, 0.419]}, {"category": "knife", "bbox": [0.742, 0.283, 0.857, 0.376]}, {"category": "spoon", "bbox": [0.618, 0.46, 0.797, 0.809]}, {"category": "fork", "bbox": [0.684, 0.254, 0.805, 0.395]}, {"category": "bowl", "bbox": [0.782, 0.366, 1.0, 0.62]}, {"category": "chair", "bbox": [0.202, 0.0, 0.671, 0.148]}, {"category": "dining table", "bbox": [0.002, 0.126, 0.996, 0.987]}]}
52
+ {"id": "000000515716", "image": "000000515716.jpg", "captions": ["A couple of women standing on either side of a man wearing glasses.", "Two women and a man are holding glasses up at a wine tasting.", "Three young adults holding wine glasses while standing at a bar.", "A group of people sit holding glasses and smiling at a table with several bottles.", "A group of people at a celebration having a taste of wine."], "instances": [{"category": "bottle", "bbox": [0.529, 0.604, 0.637, 0.908]}, {"category": "bottle", "bbox": [0.379, 0.398, 0.481, 0.892]}, {"category": "bottle", "bbox": [0.942, 0.464, 0.988, 0.653]}, {"category": "person", "bbox": [0.0, 0.126, 0.136, 0.811]}, {"category": "person", "bbox": [0.05, 0.093, 0.211, 0.471]}, {"category": "person", "bbox": [0.401, 0.031, 0.678, 0.683]}, {"category": "person", "bbox": [0.617, 0.191, 0.94, 0.858]}, {"category": "person", "bbox": [0.723, 0.098, 0.947, 0.564]}, {"category": "wine glass", "bbox": [0.634, 0.434, 0.697, 0.628]}, {"category": "wine glass", "bbox": [0.285, 0.346, 0.372, 0.558]}, {"category": "wine glass", "bbox": [0.522, 0.422, 0.583, 0.544]}, {"category": "handbag", "bbox": [0.704, 0.601, 1.0, 0.916]}, {"category": "person", "bbox": [0.944, 0.319, 0.999, 0.604]}, {"category": "bottle", "bbox": [0.921, 0.46, 0.953, 0.636]}, {"category": "person", "bbox": [0.116, 0.171, 0.41, 0.829]}]}
53
+ {"id": "000000116173", "image": "000000116173.jpg", "captions": ["The boy is on his surfboard in the water riding it.", "a young boy riding a boogie board in the water", "A boy riding surf board in the ocean.", "A young boy is riding a surfboard on a small wave.", "A young boy is surfing in the ocean."], "instances": [{"category": "person", "bbox": [0.485, 0.238, 0.702, 0.821]}, {"category": "person", "bbox": [0.866, 0.223, 0.921, 0.29]}, {"category": "person", "bbox": [0.752, 0.146, 0.775, 0.188]}, {"category": "surfboard", "bbox": [0.239, 0.758, 0.782, 0.846]}, {"category": "surfboard", "bbox": [0.853, 0.277, 0.981, 0.29]}, {"category": "surfboard", "bbox": [0.727, 0.169, 0.801, 0.198]}, {"category": "person", "bbox": [0.637, 0.194, 0.677, 0.261]}]}
54
+ {"id": "000000186013", "image": "000000186013.jpg", "captions": ["A beach scene includes many different kites flying in a cloudy sky.", "Kites being flown at the beach at twilight.", "A beach with flags in the ground and kites overhead in the sky.", "A beach with rows of flags in the sand and kites flying overhead.", "A beach filled with kites and wind sails next to the ocean."], "instances": [{"category": "kite", "bbox": [0.174, 0.4, 0.351, 0.483]}, {"category": "kite", "bbox": [0.144, 0.13, 0.273, 0.17]}, {"category": "kite", "bbox": [0.236, 0.269, 0.268, 0.294]}, {"category": "kite", "bbox": [0.464, 0.204, 0.598, 0.271]}, {"category": "kite", "bbox": [0.61, 0.304, 0.659, 0.342]}, {"category": "kite", "bbox": [0.545, 0.435, 0.565, 0.452]}, {"category": "kite", "bbox": [0.027, 0.558, 0.151, 0.59]}, {"category": "kite", "bbox": [0.93, 0.429, 0.973, 0.536]}, {"category": "kite", "bbox": [0.684, 0.36, 0.697, 0.374]}, {"category": "surfboard", "bbox": [0.393, 0.627, 0.446, 0.934]}, {"category": "person", "bbox": [0.959, 0.685, 0.984, 0.713]}, {"category": "person", "bbox": [0.919, 0.681, 0.94, 0.725]}, {"category": "person", "bbox": [0.8, 0.597, 0.805, 0.61]}, {"category": "person", "bbox": [0.079, 0.928, 0.116, 0.975]}, {"category": "kite", "bbox": [0.743, 0.307, 0.755, 0.319]}, {"category": "kite", "bbox": [0.78, 0.322, 0.795, 0.335]}, {"category": "kite", "bbox": [0.536, 0.526, 0.597, 0.617]}, {"category": "person", "bbox": [0.941, 0.694, 0.961, 0.726]}, {"category": "kite", "bbox": [0.575, 0.446, 0.594, 0.471]}]}
55
+ {"id": "000000015029", "image": "000000015029.jpg", "captions": ["A man holding a white frisbee standing on top of a field.", "A man is playing frisbee next to a tent.", "Guy at the park holding a frisbee with people in the back under a tent", "A man is holding a Frisbee standing in the grass.", "Young adult male holding a frisbee at an event."], "instances": [{"category": "frisbee", "bbox": [0.138, 0.359, 0.215, 0.587]}, {"category": "person", "bbox": [0.16, 0.002, 0.726, 0.995]}, {"category": "person", "bbox": [0.81, 0.73, 0.852, 0.825]}, {"category": "person", "bbox": [0.786, 0.749, 0.833, 0.814]}, {"category": "person", "bbox": [0.847, 0.743, 0.89, 0.804]}, {"category": "person", "bbox": [0.614, 0.749, 0.706, 0.936]}]}
56
+ {"id": "000000500565", "image": "000000500565.jpg", "captions": ["A woman holding a child wrapped in a towel brushing her teeth.", "A woman is holding a baby who is wrapped in a towel and holding a toothbrush", "A woman holding a little boy who is brushing his teeth.", "A baby with a toothbrush in his mouth while being held by a woman", "a close up of an adult holding a child brushing their teeth"], "instances": [{"category": "toothbrush", "bbox": [0.586, 0.66, 0.754, 0.821]}, {"category": "person", "bbox": [0.002, 0.007, 0.637, 0.991]}, {"category": "person", "bbox": [0.357, 0.196, 0.998, 0.984]}]}
57
+ {"id": "000000297323", "image": "000000297323.jpg", "captions": ["Two buses are parked against a curb in front of a building.", "Two automobiles parked on the side of a building.", "two tourist buses parked on street in front of old industrial building", "Two unique city buses stopped at a stop sign.", "Buses parked outside by a building and stop sign."], "instances": [{"category": "bus", "bbox": [0.7, 0.711, 0.92, 0.881]}, {"category": "person", "bbox": [0.936, 0.771, 0.972, 0.833]}, {"category": "stop sign", "bbox": [0.237, 0.666, 0.285, 0.728]}, {"category": "bus", "bbox": [0.334, 0.71, 0.678, 0.935]}, {"category": "truck", "bbox": [0.335, 0.72, 0.683, 0.934]}, {"category": "person", "bbox": [0.34, 0.791, 0.367, 0.834]}]}
58
+ {"id": "000000441147", "image": "000000441147.jpg", "captions": ["Two antique suitcases sit stacked one on top of the other.", "Two suitcases are stacked on each other and one is black while the other is brown and yellow.", "a close up of two luggage suit cases stacked on each other", "A stack of antique luggage is displayed with price tags.", "two suitcases made of leather and stacked on top of each other"], "instances": [{"category": "suitcase", "bbox": [0.167, 0.025, 0.989, 0.445]}, {"category": "suitcase", "bbox": [0.002, 0.31, 0.994, 0.996]}]}
59
+ {"id": "000000353536", "image": "000000353536.jpg", "captions": ["A table topped with plates and glasses with eating utensils..", "a fork is laying on a small white plate", "dirty dishes on a table, and a bottle of something.", "a table top with some dishes on top of it", "A table full of dirty dishes is pictured in this image."], "instances": [{"category": "dining table", "bbox": [0.0, 0.007, 0.998, 0.988]}, {"category": "bottle", "bbox": [0.554, 0.002, 0.768, 0.411]}, {"category": "cup", "bbox": [0.372, 0.011, 0.544, 0.427]}, {"category": "fork", "bbox": [0.442, 0.464, 0.818, 0.572]}, {"category": "fork", "bbox": [0.089, 0.233, 0.272, 0.456]}, {"category": "spoon", "bbox": [0.144, 0.218, 0.326, 0.413]}, {"category": "cup", "bbox": [0.688, 0.056, 0.812, 0.361]}]}
60
+ {"id": "000000416256", "image": "000000416256.jpg", "captions": ["A cat laying on the floor next to a keyboard.", "an orange and white cat is laying next to a keyboard and some wires", "A cat is laying next to a computer keyboard.", "a cat laying on a floor next to a keyboard", "A CAT LAYING ON THE FLOOR AMIDST A COMPUTER,SPEAKERS,CORDS"], "instances": [{"category": "cat", "bbox": [0.235, 0.23, 0.737, 0.639]}, {"category": "keyboard", "bbox": [0.243, 0.562, 0.631, 0.836]}, {"category": "keyboard", "bbox": [0.058, 0.33, 0.277, 0.608]}]}
61
+ {"id": "000000214367", "image": "000000214367.jpg", "captions": ["Wood shading on the side of a window with brick siding.", "A tree filled with lots of red fruit near a building.", "By the window outside is a apple tree, where the apples are ready to be picked.", "Some very nice looking red fruity by a window,", "A shuttered window has a fruit tree outside it."], "instances": [{"category": "apple", "bbox": [0.214, 0.112, 0.408, 0.266]}, {"category": "apple", "bbox": [0.472, 0.166, 0.618, 0.293]}, {"category": "apple", "bbox": [0.055, 0.592, 0.172, 0.686]}, {"category": "apple", "bbox": [0.126, 0.661, 0.236, 0.739]}, {"category": "apple", "bbox": [0.52, 0.09, 0.609, 0.143]}, {"category": "apple", "bbox": [0.226, 0.354, 0.285, 0.409]}, {"category": "apple", "bbox": [0.0, 0.698, 0.096, 0.771]}, {"category": "apple", "bbox": [0.001, 0.646, 0.042, 0.713]}, {"category": "apple", "bbox": [0.258, 0.719, 0.329, 0.778]}]}
62
+ {"id": "000000210299", "image": "000000210299.jpg", "captions": ["A little boy riding his bike and wearing a helmet", "A little boy raveling down a road on a bike, with a yellow helmet on.", "The boy wears a helmet while riding his bicycle.", "a small child wearing a helmet and riding a bike", "A little boy wearing a helmet and riding a bike."], "instances": [{"category": "person", "bbox": [0.198, 0.259, 0.399, 0.679]}, {"category": "bicycle", "bbox": [0.213, 0.383, 0.408, 0.835]}]}
63
+ {"id": "000000088218", "image": "000000088218.jpg", "captions": ["Signs proclaim the famous Haight Ashbury intersection and district.", "a pole with street lights, signs and wires attached to it", "A traffic light at the intersection of Haight and Ashbury", "A traffic sign is shown with traffic signs above it.", "The street signs and traffic signal are below wires attached to the pole."], "instances": [{"category": "traffic light", "bbox": [0.443, 0.435, 0.658, 0.721]}]}
64
+ {"id": "000000020650", "image": "000000020650.jpg", "captions": ["Burger with broccoli, pickle, and fork on orange plate", "On a plate is kept a burger and a bowl of broccoli and a fork.", "There is half a sandwich on an orange plate with a pickle and a bowl of broccoli", "A A bowl and a sandwich on an orange plate on a table.", "A plate has a sandwich, broccoli, and a pickle."], "instances": [{"category": "sandwich", "bbox": [0.436, 0.155, 0.805, 0.859]}, {"category": "sandwich", "bbox": [0.311, 0.006, 0.748, 0.293]}, {"category": "fork", "bbox": [0.0, 0.665, 0.578, 0.876]}, {"category": "bowl", "bbox": [0.002, 0.263, 0.487, 0.744]}, {"category": "bowl", "bbox": [0.708, 0.003, 0.828, 0.03]}, {"category": "broccoli", "bbox": [0.185, 0.288, 0.366, 0.546]}, {"category": "broccoli", "bbox": [0.017, 0.344, 0.384, 0.654]}, {"category": "broccoli", "bbox": [0.31, 0.191, 0.466, 0.463]}, {"category": "broccoli", "bbox": [0.104, 0.107, 0.285, 0.342]}, {"category": "broccoli", "bbox": [0.092, 0.276, 0.242, 0.442]}, {"category": "dining table", "bbox": [0.002, 0.0, 0.999, 0.987]}]}
65
+ {"id": "000000514915", "image": "000000514915.jpg", "captions": ["A large black dog laying on a kitchen floor.", "A dog is laying down on the floor in the home.", "Black dog laying down on the kitchen floor next to it's bowls and toy", "A black dog with a red collar laying on a tiled floor.", "A black dog that is laying on the floor."], "instances": [{"category": "dog", "bbox": [0.087, 0.276, 0.812, 0.792]}, {"category": "bowl", "bbox": [0.437, 0.09, 0.533, 0.213]}, {"category": "bowl", "bbox": [0.537, 0.035, 0.665, 0.141]}]}
66
+ {"id": "000000205183", "image": "000000205183.jpg", "captions": ["A duck walking along a paved road next to a patch of grass.", "A close up of a duck walking on a path.", "a duck walks along a cement patch while looking down", "A white duck out of water, walking on the ground.", "A goose standing in the road, looking at the ground."], "instances": [{"category": "bird", "bbox": [0.291, 0.235, 0.859, 0.889]}]}
67
+ {"id": "000000534270", "image": "000000534270.jpg", "captions": ["Man and woman with umbrella hats sitting on top of a bridge.", "A couple equipped with umbrella hats taking a break from walking their dog on a bridge on a rainy day.", "Two people in ridiculous looking umbrella hats.", "two people with umbrella hats near one another", "A couple of people wearing umbrella hats next to the ocean."], "instances": [{"category": "dog", "bbox": [0.456, 0.832, 0.6, 0.983]}, {"category": "person", "bbox": [0.433, 0.464, 0.636, 0.975]}, {"category": "person", "bbox": [0.263, 0.321, 0.459, 0.978]}, {"category": "boat", "bbox": [0.912, 0.4, 0.978, 0.433]}, {"category": "boat", "bbox": [0.211, 0.236, 0.478, 0.304]}, {"category": "boat", "bbox": [0.144, 0.328, 0.189, 0.361]}, {"category": "umbrella", "bbox": [0.443, 0.402, 0.607, 0.473]}, {"category": "umbrella", "bbox": [0.325, 0.311, 0.483, 0.432]}, {"category": "umbrella", "bbox": [0.207, 0.738, 0.284, 0.778]}, {"category": "umbrella", "bbox": [0.489, 0.713, 0.649, 0.83]}]}
68
+ {"id": "000000408439", "image": "000000408439.jpg", "captions": ["Cliffs rise on the edge of a placid lake.", "A scenic view of a river with a train on the edge of it in the distance.", "A large lake surrounded by beautiful tree covered mountains.", "a landscape scene with water, mountains and trees", "A train on a waterfront track surrounded by mountains."], "instances": [{"category": "train", "bbox": [0.008, 0.591, 0.562, 0.644]}]}
69
+ {"id": "000000474253", "image": "000000474253.jpg", "captions": ["A man riding on the back of a horse through a river.", "A person is riding a horse through water.", "Horse and rider crossing waterway during competitive event.", "A woman riding a horse splashes through a large puddle.", "A young man riding a horse through some water."], "instances": [{"category": "horse", "bbox": [0.385, 0.235, 0.651, 0.814]}, {"category": "person", "bbox": [0.396, 0.06, 0.576, 0.675]}, {"category": "person", "bbox": [0.29, 0.148, 0.355, 0.333]}, {"category": "person", "bbox": [0.129, 0.163, 0.212, 0.349]}, {"category": "person", "bbox": [0.005, 0.014, 0.038, 0.165]}, {"category": "person", "bbox": [0.144, 0.011, 0.193, 0.155]}, {"category": "person", "bbox": [0.089, 0.007, 0.133, 0.162]}]}
70
+ {"id": "000000098029", "image": "000000098029.jpg", "captions": ["a table with many plates on it with a bread basket", "A table set for four has many foods and fruits on it.", "Several objects displayed on a kitchen table including bread, oranges and plating.", "Several dishes and food items sit on a table.", "An assortment of foods sitting on a round brown table."], "instances": [{"category": "refrigerator", "bbox": [0.013, 0.004, 0.37, 0.317]}, {"category": "bottle", "bbox": [0.467, 0.517, 0.555, 0.638]}, {"category": "bottle", "bbox": [0.602, 0.536, 0.658, 0.609]}, {"category": "chair", "bbox": [0.747, 0.367, 1.0, 0.592]}, {"category": "chair", "bbox": [0.044, 0.368, 0.358, 0.544]}, {"category": "cup", "bbox": [0.296, 0.465, 0.359, 0.54]}, {"category": "cup", "bbox": [0.709, 0.67, 0.782, 0.736]}, {"category": "cup", "bbox": [0.213, 0.684, 0.294, 0.753]}, {"category": "knife", "bbox": [0.787, 0.699, 0.922, 0.797]}, {"category": "knife", "bbox": [0.161, 0.539, 0.265, 0.584]}, {"category": "spoon", "bbox": [0.813, 0.674, 0.922, 0.759]}, {"category": "spoon", "bbox": [0.156, 0.555, 0.233, 0.587]}, {"category": "spoon", "bbox": [0.596, 0.467, 0.613, 0.509]}, {"category": "bowl", "bbox": [0.241, 0.753, 0.505, 0.935]}, {"category": "banana", "bbox": [0.632, 0.138, 0.718, 0.161]}, {"category": "apple", "bbox": [0.701, 0.152, 0.758, 0.191]}, {"category": "orange", "bbox": [0.607, 0.66, 0.692, 0.716]}, {"category": "orange", "bbox": [0.565, 0.636, 0.611, 0.667]}, {"category": "orange", "bbox": [0.526, 0.624, 0.572, 0.652]}, {"category": "orange", "bbox": [0.61, 0.628, 0.656, 0.657]}, {"category": "orange", "bbox": [0.599, 0.649, 0.643, 0.677]}, {"category": "dining table", "bbox": [0.013, 0.439, 0.964, 0.986]}, {"category": "cup", "bbox": [0.612, 0.489, 0.669, 0.548]}, {"category": "knife", "bbox": [0.605, 0.457, 0.638, 0.53]}, {"category": "apple", "bbox": [0.502, 0.137, 0.537, 0.159]}, {"category": "orange", "bbox": [0.54, 0.135, 0.563, 0.151]}, {"category": "orange", "bbox": [0.527, 0.129, 0.554, 0.142]}, {"category": "orange", "bbox": [0.611, 0.155, 0.641, 0.171]}, {"category": "chair", "bbox": [0.0, 0.843, 0.29, 0.989]}, {"category": "cup", "bbox": [0.353, 0.469, 0.411, 0.511]}, {"category": "cup", "bbox": [0.609, 0.716, 0.682, 0.786]}, {"category": "orange", "bbox": [0.638, 0.158, 0.679, 0.177]}, {"category": "cake", "bbox": [0.38, 0.821, 0.481, 0.895]}, {"category": "chair", "bbox": [0.79, 0.747, 1.0, 1.0]}, {"category": "bottle", "bbox": [0.719, 0.55, 0.769, 0.616]}, {"category": "bottle", "bbox": [0.795, 0.546, 0.873, 0.613]}, {"category": "knife", "bbox": [0.17, 0.799, 0.264, 0.88]}, {"category": "cup", "bbox": [0.317, 0.695, 0.391, 0.752]}]}
71
+ {"id": "000000294073", "image": "000000294073.jpg", "captions": ["A woman and a man standing between two brown horses.", "A COUPLE WEARING YELLOW DRESS STANDING NEAR TWO HORSES.", "An older couple stands between two horses.", "A man and a woman standing with two horses", "A man and a woman stand in between two horses."], "instances": [{"category": "horse", "bbox": [0.0, 0.052, 0.49, 0.989]}, {"category": "horse", "bbox": [0.632, 0.23, 1.0, 0.989]}, {"category": "person", "bbox": [0.425, 0.326, 0.696, 0.987]}, {"category": "person", "bbox": [0.627, 0.203, 0.828, 0.986]}, {"category": "book", "bbox": [0.525, 0.597, 0.644, 0.833]}]}
72
+ {"id": "000000203629", "image": "000000203629.jpg", "captions": ["A man on a cell phone in a public area holding his thumb up.", "A group of people gathered inside of a room.", "A man on his cellphone posing for a picture.", "A man giving a thumbs up while on a cell phone.", "The man is giving a thumbs up while on his phone."], "instances": [{"category": "cell phone", "bbox": [0.43, 0.459, 0.449, 0.503]}, {"category": "cup", "bbox": [0.756, 0.838, 0.865, 0.98]}, {"category": "person", "bbox": [0.232, 0.317, 0.603, 0.98]}, {"category": "person", "bbox": [0.602, 0.405, 1.0, 0.999]}, {"category": "person", "bbox": [0.003, 0.339, 0.313, 0.987]}, {"category": "person", "bbox": [0.164, 0.379, 0.258, 0.733]}, {"category": "person", "bbox": [0.564, 0.36, 0.673, 0.645]}, {"category": "person", "bbox": [0.241, 0.379, 0.336, 0.512]}, {"category": "person", "bbox": [0.682, 0.372, 0.736, 0.502]}, {"category": "person", "bbox": [0.654, 0.428, 0.734, 0.536]}, {"category": "person", "bbox": [0.718, 0.368, 0.787, 0.508]}, {"category": "person", "bbox": [0.148, 0.362, 0.205, 0.529]}, {"category": "person", "bbox": [0.001, 0.431, 0.044, 0.564]}, {"category": "cup", "bbox": [0.901, 0.808, 0.995, 0.982]}]}
73
+ {"id": "000000119876", "image": "000000119876.jpg", "captions": ["A man dressed loudly is using his cell phone.", "A man talking on the phone while he walks down the street.", "A man with pink hair talking on a cell phone.", "A man in a purple shirt and tie and purple hair.", "a man colored his hair in purple walking on the road"], "instances": [{"category": "bicycle", "bbox": [0.525, 0.222, 0.924, 0.608]}, {"category": "bicycle", "bbox": [0.895, 0.249, 1.0, 0.642]}, {"category": "person", "bbox": [0.0, 0.0, 0.738, 1.0]}, {"category": "tie", "bbox": [0.319, 0.255, 0.423, 0.638]}, {"category": "cell phone", "bbox": [0.411, 0.13, 0.426, 0.161]}, {"category": "handbag", "bbox": [0.369, 0.205, 0.575, 0.839]}]}
74
+ {"id": "000000164255", "image": "000000164255.jpg", "captions": ["An umbrella that is standing in the sand.", "An umbrella is stuck in the sand on the beach.", "a colorful striped umbrella on the beach near the ocean", "A colorful umbrella is set up at the beach.", "The colorful umbrella is sitting by the beach,"], "instances": [{"category": "umbrella", "bbox": [0.0, 0.101, 0.567, 0.575]}]}
75
+ {"id": "000000192817", "image": "000000192817.jpg", "captions": ["A view from a window high up in the sky.", "A bunch of mountains seen from a plane window.", "The window from a plane overlooking the ground.", "The view of a mountain area from an airplane window.", "An aerial view of mountains and lakes from an airplane window."], "instances": []}
76
+ {"id": "000000258285", "image": "000000258285.jpg", "captions": ["Two large passenger jets flying over a beach filled with birds.", "A plane is flying over a bird filed lake", "Two airplanes are in the sky over blue water.", "An airplane landing over an airplane on the ground.", "A photo of two plans with water and birds surrounding it , one plane in the air one one the ground."], "instances": [{"category": "bird", "bbox": [0.507, 0.941, 0.536, 0.973]}, {"category": "bird", "bbox": [0.304, 0.933, 0.315, 0.95]}, {"category": "bird", "bbox": [0.129, 0.885, 0.143, 0.912]}, {"category": "bird", "bbox": [0.158, 0.851, 0.165, 0.87]}, {"category": "bird", "bbox": [0.404, 0.839, 0.429, 0.864]}, {"category": "bird", "bbox": [0.498, 0.833, 0.513, 0.861]}, {"category": "airplane", "bbox": [0.276, 0.085, 0.825, 0.316]}, {"category": "airplane", "bbox": [0.478, 0.252, 0.983, 0.495]}, {"category": "bird", "bbox": [0.552, 0.828, 0.564, 0.844]}, {"category": "bird", "bbox": [0.789, 0.812, 0.798, 0.836]}, {"category": "bird", "bbox": [0.927, 0.82, 0.936, 0.838]}, {"category": "bird", "bbox": [0.65, 0.828, 0.664, 0.849]}, {"category": "bird", "bbox": [0.752, 0.81, 0.763, 0.83]}, {"category": "bird", "bbox": [0.841, 0.817, 0.852, 0.828]}, {"category": "bird", "bbox": [0.292, 0.849, 0.311, 0.868]}, {"category": "bird", "bbox": [0.005, 0.727, 0.981, 0.998]}]}
77
+ {"id": "000000506483", "image": "000000506483.jpg", "captions": ["An art installation is placed by a street.", "People sit near a display of large artworks including an oversize bench and painted feline heads.", "Looking down on a giant rocking bench and large animal heads.", "An over sized wooden bench next to two massive animal art sculptures.", "artistic sculptures and images on a city street"], "instances": [{"category": "car", "bbox": [0.656, 0.939, 0.933, 1.0]}, {"category": "person", "bbox": [0.08, 0.664, 0.147, 0.805]}, {"category": "person", "bbox": [0.154, 0.646, 0.217, 0.821]}, {"category": "bench", "bbox": [0.316, 0.124, 0.951, 0.635]}, {"category": "backpack", "bbox": [0.062, 0.701, 0.097, 0.769]}, {"category": "person", "bbox": [0.0, 0.132, 0.031, 0.197]}]}
78
+ {"id": "000000502168", "image": "000000502168.jpg", "captions": ["a fleet of naval ships in the ocean", "A group of men on aircraft carrier with other boats in the distance.", "A large ship floating in the ocean next to other ships.", "Several men on a boat looking over the side.", "The men wear hardhats as they work on the aircraft carrier."], "instances": [{"category": "boat", "bbox": [0.634, 0.292, 1.0, 0.982]}, {"category": "person", "bbox": [0.675, 0.507, 0.736, 0.731]}, {"category": "person", "bbox": [0.684, 0.737, 0.817, 1.0]}, {"category": "person", "bbox": [0.803, 0.691, 0.883, 0.932]}, {"category": "person", "bbox": [0.741, 0.56, 0.798, 0.767]}, {"category": "person", "bbox": [0.924, 0.269, 0.951, 0.367]}, {"category": "boat", "bbox": [0.079, 0.171, 0.172, 0.231]}, {"category": "boat", "bbox": [0.863, 0.131, 0.961, 0.239]}, {"category": "boat", "bbox": [0.435, 0.288, 0.46, 0.313]}, {"category": "boat", "bbox": [0.591, 0.186, 0.605, 0.222]}, {"category": "person", "bbox": [0.451, 0.289, 0.455, 0.296]}, {"category": "person", "bbox": [0.446, 0.29, 0.451, 0.296]}, {"category": "person", "bbox": [0.872, 0.627, 0.957, 0.966]}, {"category": "person", "bbox": [0.44, 0.288, 0.446, 0.3]}]}
79
+ {"id": "000000319432", "image": "000000319432.jpg", "captions": ["Man holding two shirts with luggage and window", "A man holding clothes on a hanger with a suitcase in front of him.", "A man show a red and a white clothing hangers.", "A man holding his garment bags in both hands", "A man holding up some clothes in some hanger bags."], "instances": [{"category": "person", "bbox": [0.0, 0.092, 0.776, 0.852]}, {"category": "suitcase", "bbox": [0.153, 0.798, 0.587, 1.0]}]}
80
+ {"id": "000000131019", "image": "000000131019.jpg", "captions": ["Two zebras and two monkeys walking on the grass.", "Two giraffes and another animal are on green grass.", "A baboon and two zebras grazing on the savannah.", "A baboon and its baby eat by two zebras in the grass", "Monkey standing behind two zebras as they graze."], "instances": [{"category": "zebra", "bbox": [0.367, 0.258, 0.834, 0.646]}, {"category": "zebra", "bbox": [0.161, 0.13, 0.396, 0.375]}, {"category": "bird", "bbox": [0.309, 0.138, 0.34, 0.163]}]}
llava/eval/table/model.jsonl ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {"model_id": "vicuna-13b:20230322-clean-lang", "model_name": "vicuna-13b", "model_version": "20230322-clean-lang", "model_metadata": "vicuna-13b-20230322-clean-lang"}
2
+ {"model_id": "alpaca-13b:v1", "model_name": "alpaca-13b", "model_version": "v1", "model_metadata": "alpaca-13b"}
3
+ {"model_id": "llama-13b:v1", "model_name": "llama-13b", "model_version": "v1", "model_metadata": "hf-llama-13b"}
4
+ {"model_id": "bard:20230327", "model_name": "bard", "model_version": "20230327", "model_metadata": "Google Bard 20230327"}
5
+ {"model_id": "gpt-3.5-turbo:20230327", "model_name": "gpt-3.5-turbo", "model_version": "20230327", "model_metadata": "OpenAI ChatGPT gpt-3.5-turbo Chat Completion"}
llava/eval/table/prompt.jsonl ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {"prompt_id": 1, "system_prompt": "You are a helpful and precise assistant for checking the quality of the answer.", "prompt_template": "[Question]\n{question}\n\n[Assistant 1]\n{answer_1}\n\n[End of Assistant 1]\n\n[Assistant 2]\n{answer_2}\n\n[End of Assistant 2]\n\n[System]\n{prompt}\n\n", "defaults": {"prompt": "We would like to request your feedback on the performance of two AI assistants in response to the user question displayed above.\nPlease rate the helpfulness, relevance, accuracy, level of details of their responses. Each assistant receives an overall score on a scale of 1 to 10, where a higher score indicates better overall performance.\nPlease first output a single line containing only two values indicating the scores for Assistant 1 and 2, respectively. The two scores are separated by a space.\nIn the subsequent line, please provide a comprehensive explanation of your evaluation, avoiding any potential bias and ensuring that the order in which the responses were presented does not affect your judgment."}, "description": "Prompt for general questions"}
2
+ {"prompt_id": 2, "system_prompt": "You are a helpful and precise assistant for checking the quality of the answer.", "prompt_template": "[Question]\n{question}\n\n[Assistant 1]\n{answer_1}\n\n[End of Assistant 1]\n\n[Assistant 2]\n{answer_2}\n\n[End of Assistant 2]\n\n[System]\n{prompt}\n\n", "defaults": {"prompt": "Your task is to evaluate the coding abilities of the above two assistants. They have been asked to implement a program to solve a given problem. Please review their code submissions, paying close attention to their problem-solving approach, code structure, readability, and the inclusion of helpful comments.\n\nPlease ensure that the assistants' submissions:\n\n1. Correctly implement the given problem statement.\n2. Contain accurate and efficient code.\n3. Include clear and concise comments that explain the code's logic and functionality.\n4. Adhere to proper coding standards and best practices.\n\nOnce you have carefully reviewed both submissions, provide detailed feedback on their strengths and weaknesses, along with any suggestions for improvement. You should first output a single line containing two scores on the scale of 1-10 (1: no code/no sense; 10: perfect) for Assistant 1 and 2, respectively. Then give extra comments starting from the next line."}, "description": "Prompt for coding questions"}
3
+ {"prompt_id": 3, "system_prompt": "You are a helpful and precise assistant for checking the quality of the answer.", "prompt_template": "[Question]\n{question}\n\n[Assistant 1]\n{answer_1}\n\n[End of Assistant 1]\n\n[Assistant 2]\n{answer_2}\n\n[End of Assistant 2]\n\n[System]\n{prompt}\n\n", "defaults": {"prompt": "We would like to request your feedback on the mathematical proficiency of two AI assistants regarding the given user question.\nFirstly, please solve the problem independently, without referring to the answers provided by Assistant 1 and Assistant 2.\nAfterward, please examine the problem-solving process of Assistant 1 and Assistant 2 step-by-step to ensure their correctness, identifying any incorrect steps if present. Your evaluation should take into account not only the answer but also the problem-solving steps.\nFinally, please output a Python tuple containing two numerical scores for Assistant 1 and Assistant 2, ranging from 1 to 10, respectively. If applicable, explain the reasons for any variations in their scores and determine which assistant performed better."}, "description": "Prompt for math questions"}
4
+ {"prompt_id": 4, "system_prompt": "You are a helpful and precise assistant for checking the quality of the answer.", "prompt_template": "[Visual Context]\n{context}\n[Question]\n{question}\n\n[Assistant 1]\n{answer_1}\n\n[End of Assistant 1]\n\n[Assistant 2]\n{answer_2}\n\n[End of Assistant 2]\n\n[System]\n{prompt}\n\n", "defaults": {"prompt": "We would like to request your feedback on the performance of two AI assistants in response to the user question displayed above. The user asks the question on observing an image. For your reference, the visual content in the image is represented with five descriptive sentences describing the same image and the bounding box coordinates of each object in the scene. These coordinates are in the form of bounding boxes, represented as (x1, y1, x2, y2) with floating numbers ranging from 0 to 1. These values correspond to the top left x, top left y, bottom right x, and bottom right y. \nPlease rate the helpfulness, relevance, accuracy, level of details of their responses. Each assistant receives an overall score on a scale of 1 to 10, where a higher score indicates better overall performance.\nPlease first output a single line containing only two values indicating the scores for Assistant 1 and 2, respectively. The two scores are separated by a space.\nIn the subsequent line, please provide a comprehensive explanation of your evaluation, avoiding any potential bias and ensuring that the order in which the responses were presented does not affect your judgment."}, "description": "Prompt for visual questions"}
llava/eval/table/question.jsonl ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"question_id": 1, "text": "How can I improve my time management skills?", "category": "generic"}
2
+ {"question_id": 2, "text": "What are the most effective ways to deal with stress?", "category": "generic"}
3
+ {"question_id": 3, "text": "What are the main differences between Python and JavaScript programming languages?", "category": "generic"}
4
+ {"question_id": 4, "text": "How can I increase my productivity while working from home?", "category": "generic"}
5
+ {"question_id": 5, "text": "Can you explain the basics of quantum computing?", "category": "generic"}
6
+ {"question_id": 6, "text": "What are the differences between plant-based and animal-based protein sources?", "category": "generic"}
7
+ {"question_id": 7, "text": "How can I develop my critical thinking skills?", "category": "generic"}
8
+ {"question_id": 8, "text": "What are the major challenges faced by the education sector today?", "category": "generic"}
9
+ {"question_id": 9, "text": "What are the primary factors that influence consumer behavior?", "category": "generic"}
10
+ {"question_id": 10, "text": "What are the most effective strategies for conflict resolution in the workplace?", "category": "generic"}
11
+ {"question_id": 11, "text": "What are some potential implications of using a single-use plastic bottle versus a reusable bottle on both the environment and human health?", "category": "knowledge"}
12
+ {"question_id": 12, "text": "What factors would you consider when designing an inclusive and accessible public transportation system?", "category": "knowledge"}
13
+ {"question_id": 13, "text": "How can governments utilize fiscal and monetary policies to combat economic recessions?", "category": "knowledge"}
14
+ {"question_id": 14, "text": "How do language and cultural barriers affect the way people communicate and form relationships in multicultural societies?", "category": "knowledge"}
15
+ {"question_id": 15, "text": "Describe a scenario where artificial intelligence could be used to improve the quality and efficiency of healthcare delivery.", "category": "knowledge"}
16
+ {"question_id": 16, "text": "Explain the process of gene editing using CRISPR-Cas9 technology, and discuss its potential applications and ethical implications.", "category": "knowledge"}
17
+ {"question_id": 17, "text": "How do vaccinations work to protect individuals and communities from infectious diseases, and what is herd immunity?", "category": "knowledge"}
18
+ {"question_id": 18, "text": "How do social media platforms influence the way people consume and share news, and what are the potential implications for the spread of misinformation?", "category": "knowledge"}
19
+ {"question_id": 19, "text": "How do cultural, social, and economic factors influence people's food choices, and how can this knowledge be used to promote healthier diets?", "category": "knowledge"}
20
+ {"question_id": 20, "text": "Explain the process of natural selection and how it contributes to the evolution and adaptation of species.", "category": "knowledge"}
21
+ {"question_id": 21, "text": "How would you introduce yourself as a medieval knight at a royal banquet?", "category": "roleplay"}
22
+ {"question_id": 22, "text": "As a pirate captain, what would you say to your crew to motivate them to search for hidden treasure?", "category": "roleplay"}
23
+ {"question_id": 23, "text": "If you were a Shakespearean character, how would you declare your love for someone in a soliloquy?", "category": "roleplay"}
24
+ {"question_id": 24, "text": "As a superhero, how would you explain your origin story to a curious child?", "category": "roleplay"}
25
+ {"question_id": 25, "text": "Imagine you are a time traveler from the year 3000. What technological advancements would you tell people about?", "category": "roleplay"}
26
+ {"question_id": 26, "text": "As a sports commentator, describe the winning play in the final seconds of a championship game.", "category": "roleplay"}
27
+ {"question_id": 27, "text": "Pretend to be a world-famous chef. How would you describe your signature dish to a panel of judges?", "category": "roleplay"}
28
+ {"question_id": 28, "text": "You are a mountain climber reaching the summit of Mount Everest. Describe your emotions and the view from the top.", "category": "roleplay"}
29
+ {"question_id": 29, "text": "As a space colonist on Mars, describe your daily life and the challenges you face living on another planet.", "category": "roleplay"}
30
+ {"question_id": 30, "text": "Pretend to be a character in a post-apocalyptic world. Describe how you survive and the allies you encounter.", "category": "roleplay"}
31
+ {"question_id": 31, "text": "How can you determine if a restaurant is popular among locals or mainly attracts tourists, and why might this information be useful?", "category": "common-sense"}
32
+ {"question_id": 32, "text": "What are some subtle clues that suggest someone is pretending to understand a topic or conversation when they are actually confused or uninformed?", "category": "common-sense"}
33
+ {"question_id": 33, "text": "Why might someone choose to use a paper map or ask for directions instead of relying on a GPS device or smartphone app?", "category": "common-sense"}
34
+ {"question_id": 34, "text": "How can you determine if a person is genuinely interested in a conversation or simply being polite?", "category": "common-sense"}
35
+ {"question_id": 35, "text": "Why might someone prefer to shop at a small, locally-owned business instead of a large chain store, even if the prices are higher?", "category": "common-sense"}
36
+ {"question_id": 36, "text": "How can you assess the credibility of a source of information, such as a news article or blog post, without relying solely on the reputation of the author or publisher?", "category": "common-sense"}
37
+ {"question_id": 37, "text": "Why do some people enjoy the sensation of being scared, such as by watching horror movies or going on roller coasters, while others avoid these experiences?", "category": "common-sense"}
38
+ {"question_id": 38, "text": "How can observing the behavior of other people in a social situation provide clues about cultural norms and expectations?", "category": "common-sense"}
39
+ {"question_id": 39, "text": "Do we have a moral obligation to explore space, or should we focus on solving Earth's problems first?", "category": "common-sense"}
40
+ {"question_id": 40, "text": "In a world where automation is becoming increasingly prevalent, is it more important to prioritize job creation or technological progress?", "category": "common-sense"}
41
+ {"question_id": 41, "text": "How many times does the average human blink in a lifetime? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step.", "category": "fermi"}
42
+ {"question_id": 42, "text": "How many atoms are in a grain of salt? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step.", "category": "fermi"}
43
+ {"question_id": 43, "text": "How many lightning strikes occur on Earth each day? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step.", "category": "fermi"}
44
+ {"question_id": 44, "text": "How many balloons would it take to lift a house like in the movie \"Up\"? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step.", "category": "fermi"}
45
+ {"question_id": 45, "text": "How many text messages are sent globally in a minute? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step.", "category": "fermi"}
46
+ {"question_id": 46, "text": "How many words are spoken daily on Earth? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step.", "category": "fermi"}
47
+ {"question_id": 47, "text": "How many snowflakes fall during a typical winter? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step.", "category": "fermi"}
48
+ {"question_id": 48, "text": "How many pages are in all the books ever written? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step.", "category": "fermi"}
49
+ {"question_id": 49, "text": "How many times has the Earth orbited the Sun since the beginning of life? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step.", "category": "fermi"}
50
+ {"question_id": 50, "text": "How many songs have been recorded throughout history? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step.", "category": "fermi"}
51
+ {"question_id": 51, "text": "What if the Internet had been invented during the Renaissance period?", "category": "counterfactual"}
52
+ {"question_id": 52, "text": "What if the Aztecs had successfully repelled the Spanish conquistadors?", "category": "counterfactual"}
53
+ {"question_id": 53, "text": "What if the Black Death had not occurred in the 14th century?", "category": "counterfactual"}
54
+ {"question_id": 54, "text": "What if Isaac Newton had focused on biology instead of physics?", "category": "counterfactual"}
55
+ {"question_id": 55, "text": "What if the Beatles had never formed as a band?", "category": "counterfactual"}
56
+ {"question_id": 56, "text": "What if Alan Turing had not cracked the Enigma code during World War II?", "category": "counterfactual"}
57
+ {"question_id": 57, "text": "What if the Suez Canal had never been constructed?", "category": "counterfactual"}
58
+ {"question_id": 58, "text": "What if the Maya civilization had never mysteriously collapsed?", "category": "counterfactual"}
59
+ {"question_id": 59, "text": "What if Christopher Columbus had not discovered the Americas?", "category": "counterfactual"}
60
+ {"question_id": 60, "text": "What if Vincent van Gogh had been a successful artist during his lifetime?", "category": "counterfactual"}
61
+ {"question_id": 61, "text": "Develop a C++ program that reads a text file line by line and counts the number of occurrences of a specific word in the file.", "category": "coding"}
62
+ {"question_id": 62, "text": "Implement a Python function to find the longest common subsequence of two input strings using dynamic programming.", "category": "coding"}
63
+ {"question_id": 63, "text": "Implement a regular expression in Python to validate an email address.", "category": "coding"}
64
+ {"question_id": 64, "text": "Write a program to find the nth Fibonacci number using dynamic programming.", "category": "coding"}
65
+ {"question_id": 65, "text": "Implement a binary search algorithm to find a specific element in a sorted array.", "category": "coding"}
66
+ {"question_id": 66, "text": "Implement a queue data structure using two stacks in Python.", "category": "coding"}
67
+ {"question_id": 67, "text": "Implement a program to find the common elements in two arrays without using any extra data structures.", "category": "coding"}
68
+ {"question_id": 68, "text": "Given that f(x) = 5x^3 - 2x + 3, find the value of f(2).", "category": "math"}
69
+ {"question_id": 69, "text": "Solve for x in the equation 3x + 10 = 5(x - 2).", "category": "math"}
70
+ {"question_id": 70, "text": "If the endpoints of a line segment are (2, -2) and (10, 4), what is the length of the segment?", "category": "math"}
71
+ {"question_id": 71, "text": "Can you help me write a formal email to a potential business partner proposing a joint venture?", "category": "writing"}
72
+ {"question_id": 72, "text": "Can you help me write a resignation letter to my current employer, while leaving on good terms and expressing gratitude for the opportunities provided?", "category": "writing"}
73
+ {"question_id": 73, "text": "Use an appropriate format to structure a formal letter of recommendation for a student applying to a prestigious graduate program in computer science.", "category": "writing"}
74
+ {"question_id": 74, "text": "Write a compelling product launch announcement email to inform our customers of our new software solution.", "category": "writing"}
75
+ {"question_id": 75, "text": "Draft an apology email to a customer who experienced a delay in their order, and provide reassurance that the issue has been resolved.", "category": "writing"}
76
+ {"question_id": 76, "text": "Write a script for a YouTube video exploring the history and cultural significance of jazz.", "category": "writing"}
77
+ {"question_id": 77, "text": "Compose an engaging travel blog post about a recent trip to Hawaii, highlighting cultural experiences and must-see attractions.", "category": "writing"}
78
+ {"question_id": 78, "text": "Write a captivating movie review for a recently released science fiction film, discussing its plot, characters, and special effects.", "category": "writing"}
79
+ {"question_id": 79, "text": "Structure a podcast script for an episode discussing the influence of streaming platforms on the music industry.", "category": "writing"}
80
+ {"question_id": 80, "text": "Write a symphony concert review, discussing the orchestra's performance and overall audience experience.", "category": "writing"}
llava/eval/table/results/test_sqa_llava_lcs_558k_sqa_12e_vicuna_v1_3_13b.json ADDED
The diff for this file is too large to render. See raw diff
 
llava/eval/table/reviewer.jsonl ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {"reviewer_id": "gpt-4-0328-default", "prompt_id": 1, "metadata": {"temperature": 0.2, "max_tokens": 1024}, "description": "GPT-4 for general questions"}
2
+ {"reviewer_id": "gpt-4-0328-coding", "prompt_id": 2, "metadata": {"temperature": 0.2, "max_tokens": 1024}, "description": "GPT-4 for coding questions"}
3
+ {"reviewer_id": "gpt-4-0328-math", "prompt_id": 3, "metadata": {"temperature": 0.2, "max_tokens": 1024}, "description": "GPT-4 for math questions"}
4
+ {"reviewer_id": "gpt-4-0417-visual", "prompt_id": 4, "metadata": {"temperature": 0.2, "max_tokens": 1024}, "description": "GPT-4 for math questions"}
llava/eval/table/rule.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "coding": {"role": "Assistant", "prompt": "Your task is to evaluate the coding abilities of the above two assistants. They have been asked to implement a program to solve a given problem. Please review their code submissions, paying close attention to their problem-solving approach, code structure, readability, and the inclusion of helpful comments.\n\nPlease ensure that the assistants' submissions:\n\n1. Correctly implement the given problem statement.\n2. Contain accurate and efficient code.\n3. Include clear and concise comments that explain the code's logic and functionality.\n4. Adhere to proper coding standards and best practices.\n\nOnce you have carefully reviewed both submissions, provide detailed feedback on their strengths and weaknesses, along with any suggestions for improvement. You should first output a single line containing two scores on the scale of 1-10 (1: no code/no sense; 10: perfect) for Assistant 1 and 2, respectively. Then give extra comments starting from the next line."},
3
+ "math": {"role": "Assistant", "prompt": "We would like to request your feedback on the mathematical proficiency of two AI assistants regarding the given user question.\nFirstly, please solve the problem independently, without referring to the answers provided by Assistant 1 and Assistant 2.\nAfterward, please examine the problem-solving process of Assistant 1 and Assistant 2 step-by-step to ensure their correctness, identifying any incorrect steps if present. Your evaluation should take into account not only the answer but also the problem-solving steps.\nFinally, please output a Python tuple containing two numerical scores for Assistant 1 and Assistant 2, ranging from 1 to 10, respectively. If applicable, explain the reasons for any variations in their scores and determine which assistant performed better."},
4
+ "default": {"role": "Assistant", "prompt": "We would like to request your feedback on the performance of two AI assistants in response to the user question displayed above.\nPlease rate the helpfulness, relevance, accuracy, level of details of their responses. Each assistant receives an overall score on a scale of 1 to 10, where a higher score indicates better overall performance.\nPlease first output a single line containing only two values indicating the scores for Assistant 1 and 2, respectively. The two scores are separated by a space.\nIn the subsequent line, please provide a comprehensive explanation of your evaluation, avoiding any potential bias and ensuring that the order in which the responses were presented does not affect your judgment."},
5
+ "conv": {"role": "Assistant", "prompt": "We would like to request your feedback on the performance of two AI assistants in response to the user question displayed above. The user asks the question on observing an image. For your reference, the visual content in the image is represented with five descriptive sentences describing the same image and the bounding box coordinates of each object in the scene. These coordinates are in the form of bounding boxes, represented as (x1, y1, x2, y2) with floating numbers ranging from 0 to 1. These values correspond to the top left x, top left y, bottom right x, and bottom right y. \nPlease rate the helpfulness, relevance, accuracy, level of details of their responses. Each assistant receives an overall score on a scale of 1 to 10, where a higher score indicates better overall performance.\nPlease first output a single line containing only two values indicating the scores for Assistant 1 and 2, respectively. The two scores are separated by a space.\nIn the subsequent line, please provide a comprehensive explanation of your evaluation, avoiding any potential bias and ensuring that the order in which the responses were presented does not affect your judgment."},
6
+ "detail": {"role": "Assistant", "prompt": "We would like to request your feedback on the performance of two AI assistants in response to the user question displayed above. The user asks the question on observing an image. For your reference, the visual content in the image is represented with five descriptive sentences describing the same image and the bounding box coordinates of each object in the scene. These coordinates are in the form of bounding boxes, represented as (x1, y1, x2, y2) with floating numbers ranging from 0 to 1. These values correspond to the top left x, top left y, bottom right x, and bottom right y. \nPlease rate the helpfulness, relevance, accuracy, level of details of their responses. Each assistant receives an overall score on a scale of 1 to 10, where a higher score indicates better overall performance.\nPlease first output a single line containing only two values indicating the scores for Assistant 1 and 2, respectively. The two scores are separated by a space.\nIn the subsequent line, please provide a comprehensive explanation of your evaluation, avoiding any potential bias and ensuring that the order in which the responses were presented does not affect your judgment."},
7
+ "complex": {"role": "Assistant", "prompt": "We would like to request your feedback on the performance of two AI assistants in response to the user question displayed above. The user asks the question on observing an image. For your reference, the visual content in the image is represented with five descriptive sentences describing the same image and the bounding box coordinates of each object in the scene. These coordinates are in the form of bounding boxes, represented as (x1, y1, x2, y2) with floating numbers ranging from 0 to 1. These values correspond to the top left x, top left y, bottom right x, and bottom right y. \nPlease rate the helpfulness, relevance, accuracy, level of details of their responses. Each assistant receives an overall score on a scale of 1 to 10, where a higher score indicates better overall performance.\nPlease first output a single line containing only two values indicating the scores for Assistant 1 and 2, respectively. The two scores are separated by a space.\nIn the subsequent line, please provide a comprehensive explanation of your evaluation, avoiding any potential bias and ensuring that the order in which the responses were presented does not affect your judgment."},
8
+ "llava_bench_conv": {"role": "Assistant", "prompt": "We would like to request your feedback on the performance of two AI assistants in response to the user question displayed above. The user asks the question on observing an image. For your reference, the visual content in the image is represented with a few sentences describing the image. \nPlease rate the helpfulness, relevance, accuracy, level of details of their responses. Each assistant receives an overall score on a scale of 1 to 10, where a higher score indicates better overall performance.\nPlease first output a single line containing only two values indicating the scores for Assistant 1 and 2, respectively. The two scores are separated by a space.\nIn the subsequent line, please provide a comprehensive explanation of your evaluation, avoiding any potential bias and ensuring that the order in which the responses were presented does not affect your judgment."},
9
+ "llava_bench_detail": {"role": "Assistant", "prompt": "We would like to request your feedback on the performance of two AI assistants in response to the user question displayed above. The user asks the question on observing an image. For your reference, the visual content in the image is represented with a few sentences describing the image. \nPlease rate the helpfulness, relevance, accuracy, level of details of their responses. Each assistant receives an overall score on a scale of 1 to 10, where a higher score indicates better overall performance.\nPlease first output a single line containing only two values indicating the scores for Assistant 1 and 2, respectively. The two scores are separated by a space.\nIn the subsequent line, please provide a comprehensive explanation of your evaluation, avoiding any potential bias and ensuring that the order in which the responses were presented does not affect your judgment."},
10
+ "llava_bench_complex": {"role": "Assistant", "prompt": "We would like to request your feedback on the performance of two AI assistants in response to the user question displayed above. The user asks the question on observing an image. For your reference, the visual content in the image is represented with a few sentences describing the image. \nPlease rate the helpfulness, relevance, accuracy, level of details of their responses. Each assistant receives an overall score on a scale of 1 to 10, where a higher score indicates better overall performance.\nPlease first output a single line containing only two values indicating the scores for Assistant 1 and 2, respectively. The two scores are separated by a space.\nIn the subsequent line, please provide a comprehensive explanation of your evaluation, avoiding any potential bias and ensuring that the order in which the responses were presented does not affect your judgment."}
11
+ }
llava/eval/webpage/index.html ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Who's GPT-4's favorite? Battles between State-of-the-Art Chatbots</title>
7
+ <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
8
+ <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
9
+ <link rel="stylesheet" href="styles.css">
10
+ </head>
11
+
12
+ <body>
13
+ <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
14
+ <a class="navbar-brand" href="#">🏔️ Vicuna Evaluation Examples</a>
15
+ <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
16
+ <span class="navbar-toggler-icon"></span>
17
+ </button>
18
+ <div class="collapse navbar-collapse" id="navbarNav">
19
+ <ul class="navbar-nav mr-auto">
20
+ <li class="nav-item">
21
+ <a class="nav-link" href="https://chat.lmsys.org/">Demo</a>
22
+ </li>
23
+ <li class="nav-item">
24
+ <a class="nav-link" href="https://vicuna.lmsys.org">Blog</a>
25
+ </li>
26
+ <li class="nav-item">
27
+ <a class="nav-link" href="https://github.com/lm-sys/FastChat">Github</a>
28
+ </li>
29
+ </ul>
30
+ </div>
31
+ </nav>
32
+
33
+ <div class="container mt-5">
34
+ <h2 class="text-center mb-5">Who's GPT-4's favorite? Battles between State-of-the-Art Chatbots</h2>
35
+
36
+ <!-- Selection -->
37
+ <div class="form-row">
38
+ <div class="form-group col-md-2">
39
+ <label for="category-select">Category</label>
40
+ <select class="form-control" id="category-select"></select>
41
+ </div>
42
+ <div class="form-group col-md-8">
43
+ <label for="question-select">Question</label>
44
+ <select class="form-control" id="question-select"></select>
45
+ </div>
46
+ <div class="form-group col-md-2">
47
+ <div class="col-md-2"><label>&nbsp;</label></div>
48
+ <div class="btn-group" role="group" aria-label="Left and Right Controller">
49
+ <button type="button" class="form-control btn btn-primary" id="prev-question"><i class="material-icons">keyboard_arrow_left</i></button>
50
+ <button type="button" class="form-control btn btn-primary" id="next-question"><i class="material-icons">keyboard_arrow_right</i></button>
51
+ </div>
52
+ </div>
53
+ </div>
54
+
55
+ <!-- "Battle" -->
56
+ <div class="row mb-4" style="justify-content: center;">
57
+ <div class="col" style="display: flex; justify-content: center; align-items: center;">
58
+ <label class="adjustable-font-size" id="other-score-label">*/10</label>
59
+ </div>
60
+ <div class="col">
61
+ <div class="vertical-flex-layout">
62
+ <img class="shadow figure-img img-fluid" src="" alt="other logo" width="150" id="other-model-figure">
63
+ </div>
64
+ </div>
65
+ <div class="col">
66
+ <div class="vertical-flex-layout">
67
+ <!-- from: https://fonts.google.com/icons?icon.query=battle&selected=Material+Symbols+Outlined:swords:FILL@0;wght@300;GRAD@0;opsz@48&icon.style=Outlined -->
68
+ <img class="figure-img img-fluid" src="figures/swords_FILL0_wght300_GRAD0_opsz48.svg" width="60" height="60">
69
+ </div>
70
+ </div>
71
+ <div class="col">
72
+ <div class="vertical-flex-layout">
73
+ <img class="shadow figure-img img-fluid" src="figures/vicuna.jpeg" alt="vicuna logo" width="150" id="our-model-figure">
74
+ </div>
75
+ </div>
76
+ <div class="col" style="display: flex; justify-content: center; align-items: center;">
77
+ <label class="adjustable-font-size" id="our-score-label">*/10</label>
78
+ </div>
79
+ </div>
80
+
81
+ <!-- Question Card -->
82
+ <div class="card mb-4">
83
+ <div class="card-body" id="selected-question"></div>
84
+ </div>
85
+
86
+ <!-- Answer Cards -->
87
+ <div class="row">
88
+ <div class="col-md-6">
89
+ <div class="card mb-4 expandable-card">
90
+ <div class="card-header" style="padding-bottom: 0.2rem" id="other-model-header-bg">
91
+ <div class="row">
92
+ <div class="col-md-5" style="align-items: center; display: flex;">
93
+ <label id="other-model-header">Assistant #1</label>
94
+ </div>
95
+ <div class="col-md-7">
96
+ <select class="form-control" id="model-select" style="height: fit-content; margin-top: -0.3rem;"></select>
97
+ </div>
98
+ </div>
99
+ </div>
100
+ <div class="card-body">
101
+ <div class="card-text-container">
102
+ <div class="card-text" id="other-model-answer"></div>
103
+ </div>
104
+ <div class="btn btn-primary expand-btn" style="display:flex;"></div>
105
+ </div>
106
+ </div>
107
+ </div>
108
+ <div class="col-md-6">
109
+ <div class="card mb-4 expandable-card">
110
+ <div class="card-header" id="our-model-header">
111
+ Assistant #2 (Vicuna, our model)
112
+ </div>
113
+ <div class="card-body">
114
+ <div class="card-text-container">
115
+ <div class="card-text" id="our-model-answer"></div>
116
+ </div>
117
+ <div class="btn btn-primary expand-btn" style="display:flex;"></div>
118
+ </div>
119
+ </div>
120
+ </div>
121
+ </div>
122
+
123
+ <!-- Evaluation -->
124
+ <div class="card expandable-card">
125
+ <div class="card-header" style="background-color: #c9c9f2;" id="evaluation-header">GPT-4 Evaluation</div>
126
+ <div class="card-body">
127
+ <div class="card-text-container">
128
+ <div class="card-text" id="evaluation-result"></div>
129
+ </div>
130
+ <div class="btn btn-primary expand-btn" style="display:flex;"></div>
131
+ </div>
132
+ </div>
133
+ </div>
134
+
135
+ <div class="container-fluid bg-light py-2">
136
+ <div class="text-center">
137
+ <small class="text-muted">This website is co-authored with <a href="https://openai.com" target="_blank">GPT-4</a>.</small>
138
+ </div>
139
+ </div>
140
+
141
+ <!-- Marked.js -->
142
+ <script src="https://cdn.jsdelivr.net/npm/marked@4.3.0/lib/marked.umd.min.js"></script>
143
+ <!-- Bootstrap and Popper.js JavaScript dependencies -->
144
+ <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
145
+ <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script>
146
+ <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
147
+
148
+ <script src="script.js"></script>
149
+ <script>
150
+ // Fetch the JSON file
151
+ fetch('data.json')
152
+ .then(response => response.json())
153
+ .then(json_data => {
154
+ // Populate the models and questions.
155
+ populateModels(json_data.models);
156
+ populateQuestions(json_data.questions);
157
+ displayQuestion(currentQuestionIndex);
158
+ }).catch(error => console.error(error));
159
+ </script>
160
+ </body>
161
+
162
+ </html>
llava/eval/webpage/script.js ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Description: Script for the evaluation webpage.
2
+
3
+ let currentQuestionIndex = 1;
4
+
5
+ // Store the model name mapping for later use.
6
+ modelNameMapping = {
7
+ "gpt35": "ChatGPT-3.5",
8
+ "gpt4": "GPT-4",
9
+ "alpaca": "Alpaca-13b",
10
+ "vicuna": "Vicuna-13b",
11
+ "llama": "LLaMA-13b",
12
+ "bard": "Bard",
13
+ };
14
+
15
+ modelFigureMapping = {
16
+ "vicuna": "figures/vicuna.jpeg",
17
+ // Image from: https://commons.wikimedia.org/wiki/File:ChatGPT_logo.svg
18
+ "gpt35": "figures/chatgpt.svg",
19
+ // Image from: https://www.reddit.com/r/logodesign/comments/1128aat/google_ai_bard_logo_design/
20
+ "bard": "figures/bard.jpg",
21
+ // Image from: https://crfm.stanford.edu/2023/03/13/alpaca.html
22
+ "alpaca": "figures/alpaca.png",
23
+ // Image adapted from https://commons.wikimedia.org/wiki/File:Llama_on_Machu_Picchu.jpg
24
+ "llama": "figures/llama.jpg",
25
+ }
26
+
27
+ // Store the question data in a mapping for later use.
28
+ questionMapping = {};
29
+ // Store the question ids in a mapping for later use.
30
+ categoryMapping = {};
31
+ // Store the number of questions for later use.
32
+ questionsCount = 0;
33
+
34
+
35
+ function text2Markdown(text) {
36
+ // Normalize the text for markdown rendering.
37
+ text = text.trim().replaceAll('\n\n', '\n').replaceAll('\n', '\n\n');
38
+ return marked.parse(text);
39
+ }
40
+
41
+ function capitalizeFirstChar(str) {
42
+ if (!str || str.length === 0) {
43
+ return str;
44
+ }
45
+ return str.charAt(0).toUpperCase() + str.slice(1);
46
+ }
47
+
48
+ function updateQuestionSelect(question_id) {
49
+ const select = document.getElementById('question-select');
50
+ // Clear the question select.
51
+ select.innerHTML = '';
52
+ // Populate the question select.
53
+ category = questionMapping[question_id].category;
54
+ categoryMapping[category].forEach(question_id => {
55
+ const question = questionMapping[question_id];
56
+ const option = document.createElement('option');
57
+ option.value = question_id;
58
+ option.textContent = 'Q' + question_id.toString() + ': ' + question.question;
59
+ select.appendChild(option);
60
+ });
61
+ select.value = question_id;
62
+ }
63
+
64
+ function updateModelSelect() {
65
+ const select = document.getElementById('model-select');
66
+ img_path = modelFigureMapping[select.value];
67
+ document.getElementById('other-model-figure').src = img_path;
68
+ }
69
+
70
+ function populateModels(models) {
71
+ const select = document.getElementById('model-select');
72
+ models.forEach(model => {
73
+ const option = document.createElement('option');
74
+ option.value = model;
75
+ option.textContent = modelNameMapping[model];
76
+ select.appendChild(option);
77
+ });
78
+ updateModelSelect();
79
+ }
80
+
81
+ function populateQuestions(questions) {
82
+ const category_select = document.getElementById('category-select');
83
+
84
+ questionsCount = questions.length;
85
+ questions.forEach(question => {
86
+ const option = document.createElement('option');
87
+ // Store the question data in a mapping for later use.
88
+ questionMapping[question.id] = {
89
+ category: question.category,
90
+ question: question.question,
91
+ answers: question.answers,
92
+ evaluations: question.evaluations,
93
+ scores: question.scores,
94
+ };
95
+ // Store the question id in the category mapping.
96
+ if (question.category in categoryMapping) {
97
+ categoryMapping[question.category].push(question.id);
98
+ } else {
99
+ categoryMapping[question.category] = [question.id];
100
+ const category_option = document.createElement('option');
101
+ category_option.value = question.category;
102
+ category_option.textContent = capitalizeFirstChar(question.category);
103
+ category_select.appendChild(category_option);
104
+ }
105
+ });
106
+ // Set the default category.
107
+ updateQuestionSelect(currentQuestionIndex);
108
+ }
109
+
110
+ function displayQuestion(index) {
111
+ const question = questionMapping[index].question;
112
+ document.getElementById('selected-question').innerHTML = text2Markdown('**Question:** ' + question);
113
+ displayAnswers(index);
114
+ }
115
+
116
+ function displayAnswers(index) {
117
+ const question = questionMapping[index];
118
+ const otherModel = document.getElementById('model-select').value;
119
+ // render the answers with markdown
120
+ document.getElementById('other-model-answer').innerHTML = text2Markdown(question.answers[otherModel]);
121
+ document.getElementById('our-model-answer').innerHTML = text2Markdown(question.answers.vicuna);
122
+
123
+ // Display evaluation
124
+ score = question.scores[otherModel];
125
+ score_text = modelNameMapping[otherModel] + " " + score[0] + "/10, Vicuna-13b " + score[1] + "/10";
126
+ document.getElementById('evaluation-header').textContent = "GPT-4 Evaluation" + " (Score: " + score_text + ")";
127
+ document.getElementById('evaluation-result').innerHTML = text2Markdown(question.evaluations[otherModel]);
128
+
129
+ // Update model names
130
+ let assistant1_title = "Assistant #1"; // (" + modelNameMapping[otherModel] + ")";
131
+ let assistant2_title = "Assistant #2 (Vicuna-13b, our model)";
132
+ // Update scores/labels.
133
+ let assistant1_score_label = score[0].toString() + '/10';
134
+ let assistant2_score_label = score[1].toString() + '/10';
135
+
136
+ const colorRed ='#fa9'; // '#eb978d';
137
+ // const colorGreen = '#c9f2c9';
138
+ const colorBlue = '#8ef'; // '#71dbf9';
139
+ const colorYellow = '#fe7'; // '#fada57';
140
+ let otherModelHeaderColor = '';
141
+ let ourModelHeaderColor = '';
142
+ // Update the winner.
143
+ if (score[0] == score[1]) {
144
+ assistant1_title = '🏆 ' + assistant1_title;
145
+ assistant1_score_label = '🏆 ' + assistant1_score_label;
146
+ assistant2_title = '🏆 ' + assistant2_title;
147
+ assistant2_score_label = '🏆 ' + assistant2_score_label;
148
+ otherModelHeaderColor = colorYellow;
149
+ ourModelHeaderColor = colorYellow;
150
+ } else if (score[0] > score[1]) {
151
+ assistant1_title = '🏆 ' + assistant1_title;
152
+ assistant1_score_label = '🏆 ' + assistant1_score_label;
153
+ otherModelHeaderColor = colorBlue;
154
+ ourModelHeaderColor = colorRed;
155
+ } else if (score[0] < score[1]) {
156
+ assistant2_title = '🏆 ' + assistant2_title;
157
+ assistant2_score_label = '🏆 ' + assistant2_score_label;
158
+ otherModelHeaderColor = colorRed;
159
+ ourModelHeaderColor = colorBlue;
160
+ }
161
+
162
+ document.getElementById('other-model-header-bg').style.backgroundColor = otherModelHeaderColor;
163
+ document.getElementById('our-model-header').style.backgroundColor = ourModelHeaderColor;
164
+
165
+ document.getElementById('other-model-header').textContent = assistant1_title;
166
+ document.getElementById('our-model-header').textContent = assistant2_title;
167
+
168
+ document.getElementById('other-score-label').textContent = assistant1_score_label;
169
+ document.getElementById('our-score-label').textContent = assistant2_score_label;
170
+
171
+ // Update expand buttons visibility for both cards after displaying answers
172
+ // Reset the expanded state and update expand buttons visibility for both cards after displaying answers
173
+ document.querySelectorAll('.expandable-card').forEach(card => {
174
+ card.classList.remove('expanded');
175
+ updateExpandButtonVisibility(card);
176
+ const expandBtn = card.querySelector('.expand-btn');
177
+ expandBtn.innerHTML = '<i class="material-icons" style="pointer-events: none">keyboard_arrow_down</i> Show more'; // .textContent = 'Show more';
178
+ });
179
+ }
180
+
181
+ document.getElementById('question-select').addEventListener('change', e => {
182
+ currentQuestionIndex = parseInt(e.target.value);
183
+ displayQuestion(currentQuestionIndex);
184
+ });
185
+
186
+ document.getElementById('category-select').addEventListener('change', e => {
187
+ let currentCategory = e.target.value;
188
+ const questionIds = categoryMapping[currentCategory];
189
+ currentQuestionIndex = questionIds[0];
190
+ updateQuestionSelect(currentQuestionIndex);
191
+ displayQuestion(currentQuestionIndex);
192
+ });
193
+
194
+ // Update expand buttons whenever the model is changed
195
+ document.getElementById('model-select').addEventListener('change', () => {
196
+ displayAnswers(currentQuestionIndex);
197
+ document.querySelectorAll('.expandable-card').forEach(card => {
198
+ updateExpandButtonVisibility(card);
199
+ });
200
+ updateModelSelect();
201
+ });
202
+
203
+ function switchQuestionAndCategory() {
204
+ document.getElementById('question-select').value = currentQuestionIndex;
205
+ old_category = document.getElementById('category-select').value;
206
+ new_category = questionMapping[currentQuestionIndex].category;
207
+ if (old_category != new_category) {
208
+ document.getElementById('category-select').value = new_category;
209
+ updateQuestionSelect(currentQuestionIndex);
210
+ }
211
+ displayQuestion(currentQuestionIndex);
212
+ }
213
+
214
+ document.getElementById('prev-question').addEventListener('click', () => {
215
+ // Question index starts from 1.
216
+ currentQuestionIndex = Math.max(1, currentQuestionIndex - 1);
217
+ switchQuestionAndCategory();
218
+ });
219
+
220
+ document.getElementById('next-question').addEventListener('click', () => {
221
+ // Question index starts from 1.
222
+ currentQuestionIndex = Math.min(questionsCount, currentQuestionIndex + 1);
223
+ switchQuestionAndCategory();
224
+ });
225
+
226
+ function updateExpandButtonVisibility(card) {
227
+ const cardTextContainer = card.querySelector('.card-text-container');
228
+ const expandBtn = card.querySelector('.expand-btn');
229
+ if (cardTextContainer.scrollHeight > cardTextContainer.offsetHeight) {
230
+ expandBtn.style.display = 'flex';
231
+ } else {
232
+ expandBtn.style.display = 'none';
233
+ card.classList.add('expanded');
234
+ }
235
+ }
236
+
237
+ document.querySelectorAll('.expand-btn').forEach(btn => {
238
+ btn.addEventListener('click', e => {
239
+ const card = e.target.closest('.expandable-card');
240
+ card.classList.toggle('expanded');
241
+ const more = '<i class="material-icons" style="pointer-events: none">keyboard_arrow_down</i> Show more';
242
+ const less = '<i class="material-icons" style="pointer-events: none">keyboard_arrow_up</i> Show less';
243
+ e.target.innerHTML = card.classList.contains('expanded') ? less : more;
244
+ });
245
+ });
llava/eval/webpage/styles.css ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ body {
2
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
3
+ background-color: #f8f9fa;
4
+ }
5
+
6
+ .navbar-dark .navbar-nav .nav-link {
7
+ color: #f1cf68;
8
+ font-size: 1.1rem;
9
+ padding: 0.5rem 0.6rem;
10
+ }
11
+
12
+ .card-header {
13
+ font-weight: bold;
14
+ }
15
+
16
+ .card {
17
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
18
+ transition: 0.3s;
19
+ }
20
+
21
+ .card:hover {
22
+ box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
23
+ }
24
+
25
+ button {
26
+ transition: background-color 0.3s;
27
+ }
28
+
29
+ button:hover {
30
+ background-color: #007bff;
31
+ }
32
+
33
+ @media (max-width: 767px) {
34
+ .form-row .form-group {
35
+ margin-bottom: 10px;
36
+ }
37
+ }
38
+
39
+ /* Extra styles */
40
+
41
+ .expandable-card .card-text-container {
42
+ max-height: 200px;
43
+ overflow-y: hidden;
44
+ position: relative;
45
+ }
46
+
47
+ .expandable-card.expanded .card-text-container {
48
+ max-height: none;
49
+ }
50
+
51
+ .expand-btn {
52
+ position: relative;
53
+ display: none;
54
+ background-color: rgba(255, 255, 255, 0.8);
55
+ color: #510c75;
56
+ border-color: transparent;
57
+ }
58
+
59
+ .expand-btn:hover {
60
+ background-color: rgba(200, 200, 200, 0.8);
61
+ text-decoration: none;
62
+ border-color: transparent;
63
+ color: #510c75;
64
+ }
65
+
66
+ .expand-btn:focus {
67
+ outline: none;
68
+ text-decoration: none;
69
+ }
70
+
71
+ .expandable-card:not(.expanded) .card-text-container:after {
72
+ content: "";
73
+ position: absolute;
74
+ bottom: 0;
75
+ left: 0;
76
+ width: 100%;
77
+ height: 90px;
78
+ background: linear-gradient(rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 1));
79
+ }
80
+
81
+ .expandable-card:not(.expanded) .expand-btn {
82
+ margin-top: -40px;
83
+ }
84
+
85
+ .card-body {
86
+ padding-bottom: 5px;
87
+ }
88
+
89
+ .vertical-flex-layout {
90
+ justify-content: center;
91
+ align-items: center;
92
+ height: 100%;
93
+ display: flex;
94
+ flex-direction: column;
95
+ gap: 5px;
96
+ }
97
+
98
+ .figure-img {
99
+ max-width: 100%;
100
+ height: auto;
101
+ }
102
+
103
+ .adjustable-font-size {
104
+ font-size: calc(0.5rem + 2vw);
105
+ }
llava/model/__init__.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ try:
2
+ from .language_model.llava_llama import LlavaLlamaForCausalLM, LlavaConfig
3
+ from .language_model.llava_mpt import LlavaMptForCausalLM, LlavaMptConfig
4
+ from .language_model.llava_mistral import LlavaMistralForCausalLM, LlavaMistralConfig
5
+ from .edit_mapper import (
6
+ LightweightEditMapper,
7
+ MGIEStyleEditMapper,
8
+ EditMapper,
9
+ create_edit_mapper,
10
+ match_dtype_to_model
11
+ )
12
+ from .img_token_utils import (
13
+ add_img_tokens_to_tokenizer,
14
+ resize_token_embeddings_and_init,
15
+ setup_llava_trainable_params_mgie_style,
16
+ save_tokenizer_with_img_tokens,
17
+ verify_img_token_setup,
18
+ verify_model_dtype_consistency,
19
+ get_img_token_ids,
20
+ extract_img_token_hiddens,
21
+ create_img_token_mask,
22
+ )
23
+ from .unet_processors import (
24
+ LoRALinear,
25
+ DecoupledDualBranchAttnProcessor,
26
+ inject_decoupled_processors,
27
+ get_trainable_unet_params
28
+ )
29
+ from .dual_branch_unet import (
30
+ DualBranchUNet,
31
+ DualBranchUNetWithLoRA,
32
+ create_dual_branch_unet
33
+ )
34
+ except:
35
+ pass
llava/model/builder.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Haotian Liu
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ import os
17
+ import warnings
18
+ import shutil
19
+
20
+ from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig, BitsAndBytesConfig
21
+ import torch
22
+ from llava.model import *
23
+ from llava.constants import DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
24
+
25
+
26
+ def load_pretrained_model(model_path, model_base, model_name, load_8bit=False, load_4bit=False, device_map="auto", device="cuda", use_flash_attn=False, **kwargs):
27
+ kwargs = {"device_map": device_map, **kwargs}
28
+
29
+ if device != "cuda":
30
+ kwargs['device_map'] = {"": device}
31
+
32
+ if load_8bit:
33
+ kwargs['load_in_8bit'] = True
34
+ elif load_4bit:
35
+ kwargs['load_in_4bit'] = True
36
+ kwargs['quantization_config'] = BitsAndBytesConfig(
37
+ load_in_4bit=True,
38
+ bnb_4bit_compute_dtype=torch.float16,
39
+ bnb_4bit_use_double_quant=True,
40
+ bnb_4bit_quant_type='nf4'
41
+ )
42
+ else:
43
+ kwargs['torch_dtype'] = torch.float16
44
+
45
+ if use_flash_attn:
46
+ kwargs['attn_implementation'] = 'flash_attention_2'
47
+
48
+ if 'llava' in model_name.lower():
49
+ # Load LLaVA model
50
+ if 'lora' in model_name.lower() and model_base is None:
51
+ warnings.warn('There is `lora` in model name but no `model_base` is provided. If you are loading a LoRA model, please provide the `model_base` argument. Detailed instruction: https://github.com/haotian-liu/LLaVA#launch-a-model-worker-lora-weights-unmerged.')
52
+ if 'lora' in model_name.lower() and model_base is not None:
53
+ from llava.model.language_model.llava_llama import LlavaConfig
54
+ lora_cfg_pretrained = LlavaConfig.from_pretrained(model_path)
55
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
56
+ print('Loading LLaVA from base model...')
57
+ model = LlavaLlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=lora_cfg_pretrained, **kwargs)
58
+ token_num, tokem_dim = model.lm_head.out_features, model.lm_head.in_features
59
+ if model.lm_head.weight.shape[0] != token_num:
60
+ model.lm_head.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))
61
+ model.model.embed_tokens.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))
62
+
63
+ print('Loading additional LLaVA weights...')
64
+ if os.path.exists(os.path.join(model_path, 'non_lora_trainables.bin')):
65
+ non_lora_trainables = torch.load(os.path.join(model_path, 'non_lora_trainables.bin'), map_location='cpu')
66
+ else:
67
+ # this is probably from HF Hub
68
+ from huggingface_hub import hf_hub_download
69
+ def load_from_hf(repo_id, filename, subfolder=None):
70
+ cache_file = hf_hub_download(
71
+ repo_id=repo_id,
72
+ filename=filename,
73
+ subfolder=subfolder)
74
+ return torch.load(cache_file, map_location='cpu')
75
+ non_lora_trainables = load_from_hf(model_path, 'non_lora_trainables.bin')
76
+ non_lora_trainables = {(k[11:] if k.startswith('base_model.') else k): v for k, v in non_lora_trainables.items()}
77
+ if any(k.startswith('model.model.') for k in non_lora_trainables):
78
+ non_lora_trainables = {(k[6:] if k.startswith('model.') else k): v for k, v in non_lora_trainables.items()}
79
+ model.load_state_dict(non_lora_trainables, strict=False)
80
+
81
+ from peft import PeftModel
82
+ print('Loading LoRA weights...')
83
+ model = PeftModel.from_pretrained(model, model_path)
84
+ print('Merging LoRA weights...')
85
+ model = model.merge_and_unload()
86
+ print('Model is loaded...')
87
+ elif model_base is not None:
88
+ # this may be mm projector only
89
+ print('Loading LLaVA from base model...')
90
+ if 'mpt' in model_name.lower():
91
+ if not os.path.isfile(os.path.join(model_path, 'configuration_mpt.py')):
92
+ shutil.copyfile(os.path.join(model_base, 'configuration_mpt.py'), os.path.join(model_path, 'configuration_mpt.py'))
93
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=True)
94
+ cfg_pretrained = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
95
+ model = LlavaMptForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs)
96
+ else:
97
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
98
+ cfg_pretrained = AutoConfig.from_pretrained(model_path)
99
+ model = LlavaLlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs)
100
+
101
+ mm_projector_weights = torch.load(os.path.join(model_path, 'mm_projector.bin'), map_location='cpu')
102
+ mm_projector_weights = {k: v.to(torch.float16) for k, v in mm_projector_weights.items()}
103
+ model.load_state_dict(mm_projector_weights, strict=False)
104
+ else:
105
+ if 'mpt' in model_name.lower():
106
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True)
107
+ model = LlavaMptForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
108
+ elif 'mistral' in model_name.lower():
109
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
110
+ model = LlavaMistralForCausalLM.from_pretrained(
111
+ model_path,
112
+ low_cpu_mem_usage=True,
113
+ **kwargs
114
+ )
115
+ else:
116
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
117
+ model = LlavaLlamaForCausalLM.from_pretrained(
118
+ model_path,
119
+ low_cpu_mem_usage=True,
120
+ **kwargs
121
+ )
122
+ else:
123
+ # Load language model
124
+ if model_base is not None:
125
+ # PEFT model
126
+ from peft import PeftModel
127
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
128
+ model = AutoModelForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, **kwargs)
129
+ print(f"Loading LoRA weights from {model_path}")
130
+ model = PeftModel.from_pretrained(model, model_path)
131
+ print(f"Merging weights")
132
+ model = model.merge_and_unload()
133
+ print('Convert to FP16...')
134
+ model.to(torch.float16)
135
+ else:
136
+ use_fast = False
137
+ if 'mpt' in model_name.lower():
138
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True)
139
+ model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, trust_remote_code=True, **kwargs)
140
+ else:
141
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
142
+ model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
143
+
144
+ image_processor = None
145
+
146
+ if 'llava' in model_name.lower():
147
+ mm_use_im_start_end = getattr(model.config, "mm_use_im_start_end", False)
148
+ mm_use_im_patch_token = getattr(model.config, "mm_use_im_patch_token", True)
149
+ if mm_use_im_patch_token:
150
+ tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
151
+ if mm_use_im_start_end:
152
+ tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
153
+ model.resize_token_embeddings(len(tokenizer))
154
+
155
+ vision_tower = model.get_vision_tower()
156
+ if not vision_tower.is_loaded:
157
+ vision_tower.load_model(device_map=device_map)
158
+ if device_map != 'auto':
159
+ # device_map can be a string like 'cuda:0' or a dict {"": 'cuda:0'}
160
+ target_device = device_map
161
+ if isinstance(device_map, dict):
162
+ # Use the mapped single device string
163
+ target_device = list(device_map.values())[0]
164
+ vision_tower.to(device=target_device, dtype=torch.float16)
165
+ image_processor = vision_tower.image_processor
166
+
167
+ if hasattr(model.config, "max_sequence_length"):
168
+ context_len = model.config.max_sequence_length
169
+ else:
170
+ context_len = 2048
171
+
172
+ return tokenizer, model, image_processor, context_len
llava/model/dual_branch_unet.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Dual-branch UNet wrapper for VLM-guided InstructPix2Pix.
3
+
4
+ Simpler approach: Run UNet twice and combine outputs.
5
+ This uses the diffusers library as-is, no custom processors needed!
6
+
7
+ Forward:
8
+ out_text = UNet(latent, t, text_cond)
9
+ out_vlm = UNet(latent, t, vlm_cond)
10
+ out = α_text * out_text + α_vlm * out_vlm
11
+
12
+ Where α_text and α_vlm are learnable scalars.
13
+ """
14
+
15
+ import os
16
+ import torch
17
+ import torch.nn as nn
18
+ from typing import Optional
19
+ from diffusers import UNet2DConditionModel
20
+
21
+
22
+ class DualBranchUNet(nn.Module):
23
+ """
24
+ Dual-branch UNet wrapper that combines text and VLM conditioning.
25
+
26
+ This is a simpler alternative to modifying UNet attention processors.
27
+ Just runs UNet twice and combines outputs with learnable weights.
28
+
29
+ Args:
30
+ unet: Pretrained UNet2DConditionModel
31
+ init_alpha_text: Initial weight for text branch (default: 0.3)
32
+ init_alpha_vlm: Initial weight for VLM branch (default: 0.7)
33
+ freeze_unet: If True, freeze UNet weights (only train alphas)
34
+ If False, fine-tune UNet with LoRA or full weights
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ unet: UNet2DConditionModel,
40
+ init_alpha_text: float = 0.3,
41
+ init_alpha_vlm: float = 0.7,
42
+ freeze_unet: bool = True,
43
+ ):
44
+ super().__init__()
45
+
46
+ self.unet = unet
47
+
48
+ # Learnable mixing weights
49
+ self.alpha_text = nn.Parameter(torch.tensor(init_alpha_text))
50
+ self.alpha_vlm = nn.Parameter(torch.tensor(init_alpha_vlm))
51
+
52
+ # Optionally freeze UNet
53
+ if freeze_unet:
54
+ self.unet.requires_grad_(False)
55
+ print(f" UNet frozen (only alphas trainable)")
56
+ else:
57
+ print(f" UNet trainable (full fine-tuning)")
58
+
59
+ def forward(
60
+ self,
61
+ latent_input: torch.Tensor,
62
+ timestep: torch.Tensor,
63
+ encoder_hidden_states_text: torch.Tensor,
64
+ encoder_hidden_states_vlm: Optional[torch.Tensor] = None,
65
+ **kwargs
66
+ ) -> torch.Tensor:
67
+ """
68
+ Args:
69
+ latent_input: (B, C, H, W) - Noisy latents (+ RGB latents for IP2P)
70
+ timestep: (B,) - Timestep
71
+ encoder_hidden_states_text: (B, 77, 768) - Text conditioning from CLIP
72
+ encoder_hidden_states_vlm: (B, 16, 768) - VLM conditioning from EditMapper
73
+ If None, use text-only mode
74
+
75
+ Returns:
76
+ noise_pred: (B, 4, H, W) - Predicted noise
77
+ """
78
+ # Branch A: Text conditioning (standard IP2P)
79
+ noise_pred_text = self.unet(
80
+ latent_input,
81
+ timestep,
82
+ encoder_hidden_states=encoder_hidden_states_text,
83
+ **kwargs
84
+ ).sample
85
+
86
+ # Branch B: VLM conditioning (our addition)
87
+ if encoder_hidden_states_vlm is not None:
88
+ noise_pred_vlm = self.unet(
89
+ latent_input,
90
+ timestep,
91
+ encoder_hidden_states=encoder_hidden_states_vlm,
92
+ **kwargs
93
+ ).sample
94
+
95
+ # Combine with learnable weights
96
+ noise_pred = self.alpha_text * noise_pred_text + self.alpha_vlm * noise_pred_vlm
97
+ else:
98
+ # Text-only mode (fallback to standard IP2P)
99
+ noise_pred = noise_pred_text
100
+
101
+ return noise_pred
102
+
103
+ def get_trainable_params(self):
104
+ """Get trainable parameters for optimizer"""
105
+ params = {
106
+ 'alphas': [self.alpha_text, self.alpha_vlm],
107
+ 'unet': list(self.unet.parameters()) if any(p.requires_grad for p in self.unet.parameters()) else []
108
+ }
109
+ return params
110
+
111
+ def print_alpha_values(self):
112
+ """Print current alpha values"""
113
+ return f"α_text={self.alpha_text.item():.4f}, α_vlm={self.alpha_vlm.item():.4f}"
114
+
115
+ def save_pretrained(self, save_path):
116
+ """Save UNet and alphas"""
117
+ os.makedirs(save_path, exist_ok=True)
118
+
119
+ # Save UNet
120
+ self.unet.save_pretrained(os.path.join(save_path, "unet"))
121
+
122
+ # Save alphas
123
+ torch.save({
124
+ 'alpha_text': self.alpha_text,
125
+ 'alpha_vlm': self.alpha_vlm,
126
+ }, os.path.join(save_path, "dual_branch_alphas.pt"))
127
+
128
+ print(f"Saved dual-branch UNet to: {save_path}")
129
+
130
+ @classmethod
131
+ def from_pretrained(cls, load_path, unet=None):
132
+ """Load dual-branch UNet"""
133
+ if unet is None:
134
+ unet = UNet2DConditionModel.from_pretrained(
135
+ os.path.join(load_path, "unet")
136
+ )
137
+
138
+ # Create instance
139
+ instance = cls(unet)
140
+
141
+ # Load alphas
142
+ alpha_path = os.path.join(load_path, "dual_branch_alphas.pt")
143
+ if os.path.exists(alpha_path):
144
+ alphas = torch.load(alpha_path)
145
+ instance.alpha_text.data.copy_(alphas['alpha_text'])
146
+ instance.alpha_vlm.data.copy_(alphas['alpha_vlm'])
147
+ print(f"Loaded alphas: {instance.print_alpha_values()}")
148
+
149
+ return instance
150
+
151
+
152
+ class DualBranchUNetWithLoRA(DualBranchUNet):
153
+ """
154
+ Dual-branch UNet with LoRA fine-tuning on cross-attention.
155
+
156
+ This combines the simplicity of dual-branch forward with efficient LoRA training.
157
+
158
+ Args:
159
+ unet: Pretrained UNet
160
+ init_alpha_text: Initial text weight
161
+ init_alpha_vlm: Initial VLM weight
162
+ lora_r: LoRA rank (default: 8)
163
+ lora_alpha: LoRA scaling (default: 8)
164
+ target_modules: Which modules to apply LoRA (default: ["to_k", "to_v", "to_q"])
165
+ """
166
+
167
+ def __init__(
168
+ self,
169
+ unet: UNet2DConditionModel,
170
+ init_alpha_text: float = 0.3,
171
+ init_alpha_vlm: float = 0.7,
172
+ lora_r: int = 8,
173
+ lora_alpha: int = 8,
174
+ target_modules: list = None,
175
+ ):
176
+ # Don't freeze UNet yet (will add LoRA)
177
+ super().__init__(unet, init_alpha_text, init_alpha_vlm, freeze_unet=False)
178
+
179
+ if target_modules is None:
180
+ target_modules = ["to_k", "to_v", "to_q"]
181
+
182
+ # Apply LoRA to UNet
183
+ print(f"\n Applying LoRA to UNet cross-attention...")
184
+ print(f" Rank: {lora_r}, Alpha: {lora_alpha}")
185
+ print(f" Target modules: {target_modules}")
186
+
187
+ try:
188
+ from peft import LoraConfig, get_peft_model
189
+
190
+ # Find cross-attention layers (attn2 in transformer blocks)
191
+ target_names = []
192
+ for name, module in self.unet.named_modules():
193
+ if any(target in name for target in target_modules) and 'attn2' in name:
194
+ target_names.append(name)
195
+
196
+ if target_names:
197
+ lora_config = LoraConfig(
198
+ r=lora_r,
199
+ lora_alpha=lora_alpha,
200
+ target_modules=target_modules,
201
+ lora_dropout=0.05,
202
+ bias="none",
203
+ )
204
+
205
+ self.unet = get_peft_model(self.unet, lora_config)
206
+ self.unet.print_trainable_parameters()
207
+ else:
208
+ print(f" ! No matching modules found, UNet will be fully trainable")
209
+
210
+ except ImportError:
211
+ print(f" ! peft not available, UNet will be fully trainable")
212
+
213
+
214
+ def create_dual_branch_unet(
215
+ unet: UNet2DConditionModel,
216
+ use_lora: bool = False,
217
+ freeze_unet: bool = True,
218
+ **kwargs
219
+ ):
220
+ """
221
+ Factory function to create dual-branch UNet.
222
+
223
+ Args:
224
+ unet: Pretrained UNet2DConditionModel
225
+ use_lora: If True, use LoRA version (efficient fine-tuning)
226
+ If False, use frozen UNet (only train alphas)
227
+ freeze_unet: Only used if use_lora=False
228
+ **kwargs: Additional arguments for DualBranchUNet or DualBranchUNetWithLoRA
229
+
230
+ Returns:
231
+ DualBranchUNet instance
232
+ """
233
+ if use_lora:
234
+ return DualBranchUNetWithLoRA(unet, **kwargs)
235
+ else:
236
+ return DualBranchUNet(unet, freeze_unet=freeze_unet, **kwargs)
237
+
llava/model/ella_resampler.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ELLA Time-Step Aware Perceiver Resampler
3
+ Adapted from: https://github.com/ELLA-Diffusion/ELLA
4
+
5
+ Original paper: ELLA: Equip Diffusion Models with LLM for Enhanced Semantic Alignment
6
+ This implementation uses time-step conditioning to make VLM features aware of the denoising timestep.
7
+ """
8
+
9
+ from collections import OrderedDict
10
+ from typing import Optional
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ from diffusers.models.embeddings import TimestepEmbedding, Timesteps
15
+
16
+
17
+ class AdaLayerNorm(nn.Module):
18
+ """
19
+ Adaptive Layer Normalization conditioned on timestep embeddings.
20
+ Applies affine transformation (scale + shift) based on timestep.
21
+ """
22
+ def __init__(self, embedding_dim: int, time_embedding_dim: Optional[int] = None):
23
+ super().__init__()
24
+
25
+ if time_embedding_dim is None:
26
+ time_embedding_dim = embedding_dim
27
+
28
+ self.silu = nn.SiLU()
29
+ self.linear = nn.Linear(time_embedding_dim, 2 * embedding_dim, bias=True)
30
+ nn.init.zeros_(self.linear.weight)
31
+ nn.init.zeros_(self.linear.bias)
32
+
33
+ self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)
34
+
35
+ def forward(
36
+ self, x: torch.Tensor, timestep_embedding: torch.Tensor
37
+ ) -> torch.Tensor:
38
+ emb = self.linear(self.silu(timestep_embedding))
39
+ shift, scale = emb.view(len(x), 1, -1).chunk(2, dim=-1)
40
+ x = self.norm(x) * (1 + scale) + shift
41
+ return x
42
+
43
+
44
+ class SquaredReLU(nn.Module):
45
+ """Squared ReLU activation: ReLU(x)^2"""
46
+ def forward(self, x: torch.Tensor):
47
+ return torch.square(torch.relu(x))
48
+
49
+
50
+ class PerceiverAttentionBlock(nn.Module):
51
+ """
52
+ Perceiver attention block with timestep conditioning.
53
+ Uses cross-attention from learnable latents to input features.
54
+ """
55
+ def __init__(
56
+ self, d_model: int, n_heads: int, time_embedding_dim: Optional[int] = None
57
+ ):
58
+ super().__init__()
59
+ self.attn = nn.MultiheadAttention(d_model, n_heads, batch_first=True)
60
+
61
+ self.mlp = nn.Sequential(
62
+ OrderedDict(
63
+ [
64
+ ("c_fc", nn.Linear(d_model, d_model * 4)),
65
+ ("sq_relu", SquaredReLU()),
66
+ ("c_proj", nn.Linear(d_model * 4, d_model)),
67
+ ]
68
+ )
69
+ )
70
+
71
+ self.ln_1 = AdaLayerNorm(d_model, time_embedding_dim)
72
+ self.ln_2 = AdaLayerNorm(d_model, time_embedding_dim)
73
+ self.ln_ff = AdaLayerNorm(d_model, time_embedding_dim)
74
+
75
+ def attention(self, q: torch.Tensor, kv: torch.Tensor):
76
+ attn_output, _ = self.attn(q, kv, kv, need_weights=False)
77
+ return attn_output
78
+
79
+ def forward(
80
+ self,
81
+ x: torch.Tensor,
82
+ latents: torch.Tensor,
83
+ timestep_embedding: torch.Tensor = None,
84
+ ):
85
+ """
86
+ Args:
87
+ x: Input features (B, N, D) - e.g., LLaVA hidden states
88
+ latents: Learnable query latents (B, M, D)
89
+ timestep_embedding: Timestep embedding (B, 1, D_time)
90
+ Returns:
91
+ latents: Updated latents (B, M, D)
92
+ """
93
+ normed_latents = self.ln_1(latents, timestep_embedding)
94
+ latents = latents + self.attention(
95
+ q=normed_latents,
96
+ kv=torch.cat([normed_latents, self.ln_2(x, timestep_embedding)], dim=1),
97
+ )
98
+ latents = latents + self.mlp(self.ln_ff(latents, timestep_embedding))
99
+ return latents
100
+
101
+
102
+ class ELLAPerceiverResampler(nn.Module):
103
+ """
104
+ Time-step aware Perceiver Resampler from ELLA.
105
+
106
+ Converts variable-length LLaVA hidden states to fixed-length tokens
107
+ conditioned on the current denoising timestep.
108
+
109
+ Args:
110
+ width: Hidden dimension of perceiver (default: 768, matches CLIP)
111
+ layers: Number of perceiver attention blocks (default: 6, ELLA setting)
112
+ heads: Number of attention heads (default: 8)
113
+ num_latents: Number of output tokens (default: 64, ELLA setting)
114
+ output_dim: Output dimension (default: None, keeps width)
115
+ input_dim: Input dimension (default: None, keeps width; set to 4096 for LLaVA)
116
+ time_embedding_dim: Timestep embedding dimension (default: None, keeps width)
117
+ """
118
+ def __init__(
119
+ self,
120
+ width: int = 768,
121
+ layers: int = 6,
122
+ heads: int = 8,
123
+ num_latents: int = 64,
124
+ output_dim: Optional[int] = None,
125
+ input_dim: Optional[int] = None,
126
+ time_embedding_dim: Optional[int] = None,
127
+ ):
128
+ super().__init__()
129
+ self.width = width
130
+ self.layers = layers
131
+ self.num_latents = num_latents
132
+ self.output_dim = output_dim
133
+ self.input_dim = input_dim
134
+ self.time_embedding_dim = time_embedding_dim or width
135
+
136
+ # Learnable latent queries
137
+ self.latents = nn.Parameter(width**-0.5 * torch.randn(num_latents, width))
138
+
139
+ # Time-aware linear for modulating latents with timestep
140
+ self.time_aware_linear = nn.Linear(
141
+ self.time_embedding_dim, width, bias=True
142
+ )
143
+
144
+ # Input projection (if input dim doesn't match width)
145
+ if self.input_dim is not None and self.input_dim != width:
146
+ self.proj_in = nn.Linear(input_dim, width)
147
+ else:
148
+ self.proj_in = None
149
+
150
+ # Perceiver attention blocks
151
+ self.perceiver_blocks = nn.Sequential(
152
+ *[
153
+ PerceiverAttentionBlock(
154
+ width, heads, time_embedding_dim=self.time_embedding_dim
155
+ )
156
+ for _ in range(layers)
157
+ ]
158
+ )
159
+
160
+ # Output projection (if output dim specified)
161
+ if self.output_dim is not None and self.output_dim != width:
162
+ self.proj_out = nn.Sequential(
163
+ nn.Linear(width, output_dim),
164
+ nn.LayerNorm(output_dim)
165
+ )
166
+ else:
167
+ self.proj_out = None
168
+
169
+ def forward(self, x: torch.Tensor, timestep_embedding: torch.Tensor):
170
+ """
171
+ Forward pass of time-aware perceiver resampler.
172
+
173
+ Args:
174
+ x: Input features (B, N, D_in) - e.g., LLaVA hidden states
175
+ timestep_embedding: Timestep embedding (B, 1, D_time) - from UNet's timestep encoder
176
+
177
+ Returns:
178
+ latents: Resampled tokens (B, num_latents, D_out)
179
+ """
180
+ batch_size = x.size(0)
181
+
182
+ # Project input if needed
183
+ if self.proj_in is not None:
184
+ x = self.proj_in(x)
185
+
186
+ # Initialize learnable latents and modulate with timestep
187
+ learnable_latents = self.latents.unsqueeze(dim=0).repeat(batch_size, 1, 1)
188
+ latents = learnable_latents + self.time_aware_linear(
189
+ torch.nn.functional.silu(timestep_embedding)
190
+ )
191
+
192
+ # Apply perceiver attention blocks with timestep conditioning
193
+ for p_block in self.perceiver_blocks:
194
+ latents = p_block(x, latents, timestep_embedding=timestep_embedding)
195
+
196
+ # Project output if needed
197
+ if self.proj_out is not None:
198
+ latents = self.proj_out(latents)
199
+
200
+ return latents
201
+
202
+
203
+ class ELLAConnector(nn.Module):
204
+ """
205
+ Full ELLA connector: Timestep encoder + Perceiver Resampler.
206
+
207
+ This is the complete module that:
208
+ 1. Encodes timestep to embedding
209
+ 2. Resamples VLM features conditioned on timestep
210
+
211
+ Args:
212
+ time_channel: Timestep encoding channels (default: 320, UNet time dim)
213
+ time_embed_dim: Timestep embedding dimension (default: 768, CLIP dim)
214
+ act_fn: Activation function (default: "silu")
215
+ out_dim: Output dimension for timestep embedding (default: None)
216
+ width: Perceiver hidden dimension (default: 768)
217
+ layers: Number of perceiver layers (default: 6)
218
+ heads: Number of attention heads (default: 8)
219
+ num_latents: Number of output tokens (default: 64)
220
+ input_dim: VLM feature dimension (default: 4096 for LLaVA)
221
+ """
222
+ def __init__(
223
+ self,
224
+ time_channel: int = 320,
225
+ time_embed_dim: int = 768,
226
+ act_fn: str = "silu",
227
+ out_dim: Optional[int] = None,
228
+ width: int = 768,
229
+ layers: int = 6,
230
+ heads: int = 8,
231
+ num_latents: int = 64,
232
+ input_dim: int = 4096,
233
+ ):
234
+ super().__init__()
235
+
236
+ # Timestep encoding (sinusoidal positional encoding)
237
+ self.position = Timesteps(
238
+ time_channel, flip_sin_to_cos=True, downscale_freq_shift=0
239
+ )
240
+
241
+ # Timestep embedding MLP
242
+ self.time_embedding = TimestepEmbedding(
243
+ in_channels=time_channel,
244
+ time_embed_dim=time_embed_dim,
245
+ act_fn=act_fn,
246
+ out_dim=out_dim,
247
+ )
248
+
249
+ # Perceiver resampler with timestep conditioning
250
+ self.connector = ELLAPerceiverResampler(
251
+ width=width,
252
+ layers=layers,
253
+ heads=heads,
254
+ num_latents=num_latents,
255
+ input_dim=input_dim,
256
+ output_dim=None, # Keep width (768) as output dimension
257
+ time_embedding_dim=time_embed_dim,
258
+ )
259
+
260
+ def forward(self, vlm_hidden_states: torch.Tensor, timesteps: torch.Tensor):
261
+ """
262
+ Forward pass of ELLA connector.
263
+
264
+ Args:
265
+ vlm_hidden_states: VLM features (B, N, D_vlm) - e.g., LLaVA outputs
266
+ timesteps: Timesteps (B,) - current denoising timestep
267
+
268
+ Returns:
269
+ encoder_hidden_states: Resampled tokens (B, num_latents, D_out)
270
+ """
271
+ device = vlm_hidden_states.device
272
+ dtype = vlm_hidden_states.dtype
273
+
274
+ # Encode timestep to sinusoidal features
275
+ ori_time_feature = self.position(timesteps.view(-1)).to(device, dtype=dtype)
276
+ ori_time_feature = (
277
+ ori_time_feature.unsqueeze(dim=1)
278
+ if ori_time_feature.ndim == 2
279
+ else ori_time_feature
280
+ )
281
+ ori_time_feature = ori_time_feature.expand(len(vlm_hidden_states), -1, -1)
282
+
283
+ # Embed timestep
284
+ time_embedding = self.time_embedding(ori_time_feature)
285
+
286
+ # Resample VLM features with timestep conditioning
287
+ encoder_hidden_states = self.connector(
288
+ vlm_hidden_states, timestep_embedding=time_embedding
289
+ )
290
+
291
+ return encoder_hidden_states
292
+
293
+
294
+ if __name__ == "__main__":
295
+ # Test the module
296
+ print("Testing ELLA Perceiver Resampler...")
297
+
298
+ batch_size = 2
299
+ seq_len = 10
300
+ vlm_dim = 4096 # LLaVA
301
+ clip_dim = 768
302
+ num_latents = 64
303
+
304
+ # Create model
305
+ ella = ELLAConnector(
306
+ time_channel=320,
307
+ time_embed_dim=768,
308
+ width=768,
309
+ layers=6,
310
+ heads=8,
311
+ num_latents=num_latents,
312
+ input_dim=vlm_dim,
313
+ )
314
+
315
+ # Test input
316
+ vlm_hidden_states = torch.randn(batch_size, seq_len, vlm_dim)
317
+ timesteps = torch.randint(0, 1000, (batch_size,))
318
+
319
+ # Forward pass
320
+ output = ella(vlm_hidden_states, timesteps)
321
+
322
+ print(f"✓ Input shape: {vlm_hidden_states.shape}")
323
+ print(f"✓ Timesteps shape: {timesteps.shape}")
324
+ print(f"✓ Output shape: {output.shape}")
325
+ print(f"✓ Expected: ({batch_size}, {num_latents}, {clip_dim})")
326
+
327
+ assert output.shape == (batch_size, num_latents, clip_dim), "Shape mismatch!"
328
+ print("\n✓ All tests passed!")
329
+
llava/model/ella_resampler_v3.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ELLA Time-Step Aware Perceiver Resampler
3
+ Adapted from: https://github.com/ELLA-Diffusion/ELLA
4
+
5
+ Original paper: ELLA: Equip Diffusion Models with LLM for Enhanced Semantic Alignment
6
+ This implementation uses time-step conditioning to make VLM features aware of the denoising timestep.
7
+ """
8
+
9
+ from collections import OrderedDict
10
+ from typing import Optional
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ from diffusers.models.embeddings import TimestepEmbedding, Timesteps
15
+
16
+
17
+ class AdaLayerNorm(nn.Module):
18
+ """
19
+ Adaptive Layer Normalization conditioned on timestep embeddings.
20
+ Applies affine transformation (scale + shift) based on timestep.
21
+ """
22
+ def __init__(self, embedding_dim: int, time_embedding_dim: Optional[int] = None):
23
+ super().__init__()
24
+
25
+ if time_embedding_dim is None:
26
+ time_embedding_dim = embedding_dim
27
+
28
+ self.silu = nn.SiLU()
29
+ self.linear = nn.Linear(time_embedding_dim, 2 * embedding_dim, bias=True)
30
+ nn.init.zeros_(self.linear.weight)
31
+ nn.init.zeros_(self.linear.bias)
32
+
33
+ self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)
34
+
35
+ def forward(
36
+ self, x: torch.Tensor, timestep_embedding: torch.Tensor
37
+ ) -> torch.Tensor:
38
+ emb = self.linear(self.silu(timestep_embedding))
39
+ shift, scale = emb.view(len(x), 1, -1).chunk(2, dim=-1)
40
+ x = self.norm(x) * (1 + scale) + shift
41
+ return x
42
+
43
+
44
+ class SquaredReLU(nn.Module):
45
+ """Squared ReLU activation: ReLU(x)^2"""
46
+ def forward(self, x: torch.Tensor):
47
+ return torch.square(torch.relu(x))
48
+
49
+
50
+ class PerceiverAttentionBlock(nn.Module):
51
+ """
52
+ Perceiver attention block with timestep conditioning.
53
+ Uses cross-attention from learnable latents to input features.
54
+ """
55
+ def __init__(
56
+ self, d_model: int, n_heads: int, time_embedding_dim: Optional[int] = None
57
+ ):
58
+ super().__init__()
59
+ self.attn = nn.MultiheadAttention(d_model, n_heads, batch_first=True)
60
+
61
+ self.mlp = nn.Sequential(
62
+ OrderedDict(
63
+ [
64
+ ("c_fc", nn.Linear(d_model, d_model * 4)),
65
+ ("sq_relu", SquaredReLU()),
66
+ ("c_proj", nn.Linear(d_model * 4, d_model)),
67
+ ]
68
+ )
69
+ )
70
+
71
+ self.ln_1 = AdaLayerNorm(d_model, time_embedding_dim)
72
+ self.ln_2 = AdaLayerNorm(d_model, time_embedding_dim)
73
+ self.ln_ff = AdaLayerNorm(d_model, time_embedding_dim)
74
+
75
+ def attention(self, q: torch.Tensor, kv: torch.Tensor):
76
+ attn_output, _ = self.attn(q, kv, kv, need_weights=False)
77
+ return attn_output
78
+
79
+ def forward(
80
+ self,
81
+ x: torch.Tensor,
82
+ latents: torch.Tensor,
83
+ timestep_embedding: torch.Tensor = None,
84
+ ):
85
+ """
86
+ Args:
87
+ x: Input features (B, N, D) - e.g., LLaVA hidden states
88
+ latents: Learnable query latents (B, M, D)
89
+ timestep_embedding: Timestep embedding (B, 1, D_time)
90
+ Returns:
91
+ latents: Updated latents (B, M, D)
92
+ """
93
+ normed_latents = self.ln_1(latents, timestep_embedding)
94
+ latents = latents + self.attention(
95
+ q=normed_latents,
96
+ kv=torch.cat([normed_latents, self.ln_2(x, timestep_embedding)], dim=1),
97
+ )
98
+ latents = latents + self.mlp(self.ln_ff(latents, timestep_embedding))
99
+ return latents
100
+
101
+
102
+ class ELLAPerceiverResampler(nn.Module):
103
+ """
104
+ Time-step aware Perceiver Resampler from ELLA.
105
+
106
+ Converts variable-length LLaVA hidden states to fixed-length tokens
107
+ conditioned on the current denoising timestep.
108
+
109
+ Args:
110
+ width: Hidden dimension of perceiver (default: 768, matches CLIP)
111
+ layers: Number of perceiver attention blocks (default: 6, ELLA setting)
112
+ heads: Number of attention heads (default: 8)
113
+ num_latents: Number of output tokens (default: 64, ELLA setting)
114
+ output_dim: Output dimension (default: None, keeps width)
115
+ input_dim: Input dimension (default: None, keeps width; set to 4096 for LLaVA)
116
+ time_embedding_dim: Timestep embedding dimension (default: None, keeps width)
117
+ """
118
+ def __init__(
119
+ self,
120
+ width: int = 768,
121
+ layers: int = 6,
122
+ heads: int = 8,
123
+ num_latents: int = 64,
124
+ output_dim: Optional[int] = None,
125
+ input_dim: Optional[int] = None,
126
+ time_embedding_dim: Optional[int] = None,
127
+ ):
128
+ super().__init__()
129
+ self.width = width
130
+ self.layers = layers
131
+ self.num_latents = num_latents
132
+ self.output_dim = output_dim
133
+ self.input_dim = input_dim
134
+ self.time_embedding_dim = time_embedding_dim or width
135
+
136
+ # Learnable latent queries
137
+ self.latents = nn.Parameter(width**-0.5 * torch.randn(num_latents, width))
138
+
139
+ # Time-aware linear for modulating latents with timestep
140
+ self.time_aware_linear = nn.Linear(
141
+ self.time_embedding_dim, width, bias=True
142
+ )
143
+
144
+ # Input projection (if input dim doesn't match width)
145
+ if self.input_dim is not None and self.input_dim != width:
146
+ self.proj_in = nn.Linear(input_dim, width)
147
+ else:
148
+ self.proj_in = None
149
+
150
+ # Perceiver attention blocks
151
+ self.perceiver_blocks = nn.Sequential(
152
+ *[
153
+ PerceiverAttentionBlock(
154
+ width, heads, time_embedding_dim=self.time_embedding_dim
155
+ )
156
+ for _ in range(layers)
157
+ ]
158
+ )
159
+
160
+ # Output projection (if output dim specified)
161
+ if self.output_dim is not None and self.output_dim != width:
162
+ self.proj_out = nn.Sequential(
163
+ nn.Linear(width, output_dim),
164
+ nn.LayerNorm(output_dim)
165
+ )
166
+ else:
167
+ self.proj_out = None
168
+
169
+ def forward(self, x: torch.Tensor, timestep_embedding: torch.Tensor):
170
+ """
171
+ Forward pass of time-aware perceiver resampler.
172
+
173
+ Args:
174
+ x: Input features (B, N, D_in) - e.g., LLaVA hidden states
175
+ timestep_embedding: Timestep embedding (B, 1, D_time) - from UNet's timestep encoder
176
+
177
+ Returns:
178
+ latents: Resampled tokens (B, num_latents, D_out)
179
+ """
180
+ batch_size = x.size(0)
181
+
182
+ # Project input if needed
183
+ if self.proj_in is not None:
184
+ x = self.proj_in(x)
185
+
186
+ # Initialize learnable latents and modulate with timestep
187
+ learnable_latents = self.latents.unsqueeze(dim=0).repeat(batch_size, 1, 1)
188
+ latents = learnable_latents + self.time_aware_linear(
189
+ torch.nn.functional.silu(timestep_embedding)
190
+ )
191
+
192
+ # Apply perceiver attention blocks with timestep conditioning
193
+ for p_block in self.perceiver_blocks:
194
+ latents = p_block(x, latents, timestep_embedding=timestep_embedding)
195
+
196
+ # Project output if needed
197
+ if self.proj_out is not None:
198
+ latents = self.proj_out(latents)
199
+
200
+ return latents
201
+
202
+
203
+ class ELLAConnector(nn.Module):
204
+ """
205
+ Full ELLA connector: Timestep encoder + Perceiver Resampler.
206
+
207
+ This is the complete module that:
208
+ 1. Encodes timestep to embedding
209
+ 2. Resamples VLM features conditioned on timestep
210
+
211
+ Args:
212
+ time_channel: Timestep encoding channels (default: 320, UNet time dim)
213
+ time_embed_dim: Timestep embedding dimension (default: 768, CLIP dim)
214
+ act_fn: Activation function (default: "silu")
215
+ out_dim: Output dimension for timestep embedding (default: None)
216
+ width: Perceiver hidden dimension (default: 768)
217
+ layers: Number of perceiver layers (default: 6)
218
+ heads: Number of attention heads (default: 8)
219
+ num_latents: Number of output tokens (default: 64)
220
+ input_dim: VLM feature dimension (default: 4096 for LLaVA)
221
+ """
222
+ def __init__(
223
+ self,
224
+ time_channel: int = 320,
225
+ time_embed_dim: int = 768,
226
+ act_fn: str = "silu",
227
+ out_dim: Optional[int] = None,
228
+ width: int = 768,
229
+ layers: int = 6,
230
+ heads: int = 8,
231
+ num_latents: int = 64,
232
+ input_dim: int = 4096,
233
+ ):
234
+ super().__init__()
235
+
236
+ # Timestep encoding (sinusoidal positional encoding)
237
+ self.position = Timesteps(
238
+ time_channel, flip_sin_to_cos=True, downscale_freq_shift=0
239
+ )
240
+
241
+ # Timestep embedding MLP
242
+ self.time_embedding = TimestepEmbedding(
243
+ in_channels=time_channel,
244
+ time_embed_dim=time_embed_dim,
245
+ act_fn=act_fn,
246
+ out_dim=out_dim,
247
+ )
248
+
249
+ # Perceiver resampler with timestep conditioning
250
+ self.connector = ELLAPerceiverResampler(
251
+ width=width,
252
+ layers=layers,
253
+ heads=heads,
254
+ num_latents=num_latents,
255
+ input_dim=input_dim,
256
+ output_dim=None, # Keep width (768) as output dimension
257
+ time_embedding_dim=time_embed_dim,
258
+ )
259
+
260
+ def forward(self, vlm_hidden_states: torch.Tensor, timesteps: torch.Tensor):
261
+ """
262
+ Forward pass of ELLA connector.
263
+
264
+ Args:
265
+ vlm_hidden_states: VLM features (B, N, D_vlm) - e.g., LLaVA outputs
266
+ timesteps: Timesteps (B,) - current denoising timestep
267
+
268
+ Returns:
269
+ encoder_hidden_states: Resampled tokens (B, num_latents, D_out)
270
+ """
271
+ device = vlm_hidden_states.device
272
+ dtype = vlm_hidden_states.dtype
273
+
274
+ # Encode timestep to sinusoidal features
275
+ ori_time_feature = self.position(timesteps.view(-1)).to(device, dtype=dtype)
276
+ ori_time_feature = (
277
+ ori_time_feature.unsqueeze(dim=1)
278
+ if ori_time_feature.ndim == 2
279
+ else ori_time_feature
280
+ )
281
+ ori_time_feature = ori_time_feature.expand(len(vlm_hidden_states), -1, -1)
282
+
283
+ # Embed timestep
284
+ time_embedding = self.time_embedding(ori_time_feature)
285
+
286
+ # Resample VLM features with timestep conditioning
287
+ encoder_hidden_states = self.connector(
288
+ vlm_hidden_states, timestep_embedding=time_embedding
289
+ )
290
+
291
+ return encoder_hidden_states
292
+
293
+
294
+ if __name__ == "__main__":
295
+ # Test the module
296
+ print("Testing ELLA Perceiver Resampler...")
297
+
298
+ batch_size = 2
299
+ seq_len = 10
300
+ vlm_dim = 4096 # LLaVA
301
+ clip_dim = 768
302
+ num_latents = 64
303
+
304
+ # Create model
305
+ ella = ELLAConnector(
306
+ time_channel=320,
307
+ time_embed_dim=768,
308
+ width=768,
309
+ layers=6,
310
+ heads=8,
311
+ num_latents=num_latents,
312
+ input_dim=vlm_dim,
313
+ )
314
+
315
+ # Test input
316
+ vlm_hidden_states = torch.randn(batch_size, seq_len, vlm_dim)
317
+ timesteps = torch.randint(0, 1000, (batch_size,))
318
+
319
+ # Forward pass
320
+ output = ella(vlm_hidden_states, timesteps)
321
+
322
+ print(f"✓ Input shape: {vlm_hidden_states.shape}")
323
+ print(f"✓ Timesteps shape: {timesteps.shape}")
324
+ print(f"✓ Output shape: {output.shape}")
325
+ print(f"✓ Expected: ({batch_size}, {num_latents}, {clip_dim})")
326
+
327
+ assert output.shape == (batch_size, num_latents, clip_dim), "Shape mismatch!"
328
+ print("\n✓ All tests passed!")
329
+
llava/model/frozen_llava_extractor.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Frozen LLaVA Feature Extractor
3
+
4
+ Loads a pretrained LLaVA model (with LoRA) and extracts hidden states before the language model head.
5
+ The entire model is frozen - no gradients computed.
6
+ Hidden states serve as a consistent "codebook" for guiding InstructPix2Pix.
7
+ """
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ import os
12
+ from typing import Optional, Tuple
13
+
14
+ from llava.model.builder import load_pretrained_model
15
+ from llava.mm_utils import get_model_name_from_path, tokenizer_image_token
16
+ from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
17
+ from llava.conversation import conv_templates
18
+ from peft import PeftModel
19
+
20
+
21
+ class FrozenLLaVAExtractor(nn.Module):
22
+ """
23
+ Frozen LLaVA model for extracting hidden states as conditioning signals.
24
+
25
+ Workflow:
26
+ 1. Load pretrained LLaVA + LoRA weights
27
+ 2. Freeze all parameters
28
+ 3. Extract hidden states before lm_head (shape: B, L, 4096)
29
+ 4. These act as consistent semantic "codebook" for diffusion guidance
30
+
31
+ Args:
32
+ llava_base_path: Path to base LLaVA model (e.g., "llava-1.5-7b-hf")
33
+ llava_lora_path: Path to finetuned LoRA weights (e.g., "llava-miragehd-prior-bbox")
34
+ device: Device to load model on
35
+ load_8bit: Whether to load in 8-bit (for memory efficiency)
36
+ load_4bit: Whether to load in 4-bit
37
+ """
38
+ def __init__(
39
+ self,
40
+ llava_base_path: str,
41
+ llava_lora_path: Optional[str] = None,
42
+ device: str = "cuda",
43
+ load_8bit: bool = False,
44
+ load_4bit: bool = False,
45
+ merge_lora: bool = True,
46
+ ):
47
+ super().__init__()
48
+
49
+ self.device = device
50
+ self.llava_base_path = llava_base_path
51
+ self.llava_lora_path = llava_lora_path
52
+
53
+ print(f"Loading frozen LLaVA from: {llava_base_path}")
54
+ if llava_lora_path:
55
+ print(f" + LoRA weights from: {llava_lora_path}")
56
+
57
+ # Load base model
58
+ # IMPORTANT: Load directly on the target CUDA device to avoid multi-GPU splits
59
+ model_name = get_model_name_from_path(llava_base_path)
60
+ target_device_map = {"": device} if isinstance(device, str) and device.startswith("cuda") else None
61
+ self.tokenizer, self.model, self.image_processor, self.context_len = load_pretrained_model(
62
+ llava_base_path,
63
+ None,
64
+ model_name,
65
+ load_8bit=load_8bit,
66
+ load_4bit=load_4bit,
67
+ device_map=target_device_map if target_device_map is not None else device,
68
+ device=device
69
+ )
70
+
71
+ # Load LoRA weights if provided
72
+ if llava_lora_path:
73
+ print("Loading LoRA adapter...")
74
+ self.model = PeftModel.from_pretrained(self.model, llava_lora_path)
75
+
76
+ # Load non-LoRA trainables (mm_projector weights)
77
+ non_lora_path = os.path.join(llava_lora_path, 'non_lora_trainables.bin')
78
+ if os.path.exists(non_lora_path):
79
+ print("Loading mm_projector weights...")
80
+ non_lora_weights = torch.load(non_lora_path, map_location='cpu')
81
+ # Convert to fp16 if needed
82
+ if not load_8bit and not load_4bit:
83
+ non_lora_weights = {k: v.to(torch.float16) for k, v in non_lora_weights.items()}
84
+ self.model.load_state_dict(non_lora_weights, strict=False)
85
+ else:
86
+ print("Warning: non_lora_trainables.bin not found, mm_projector may not be updated")
87
+
88
+ # Optionally merge LoRA to avoid runtime PEFT wrappers on vision/LLM
89
+ if merge_lora:
90
+ try:
91
+ print("Merging LoRA adapters into base model and unloading...")
92
+ self.model = self.model.merge_and_unload()
93
+ except Exception as e:
94
+ print(f"Warning: merge_and_unload failed ({e}); continuing with PEFT wrappers.")
95
+
96
+ # Freeze everything
97
+ # Ensure model is on the target device (safety in multi-GPU runs)
98
+ try:
99
+ if isinstance(self.device, str) and self.device.startswith('cuda') and torch.cuda.is_available():
100
+ # Set current device context to reduce cuBLAS init issues on some systems
101
+ try:
102
+ local_idx = int(self.device.split(':')[1]) if ':' in self.device else 0
103
+ torch.cuda.set_device(local_idx)
104
+ except Exception:
105
+ pass
106
+ self.model.to(self.device)
107
+ except Exception:
108
+ # Some models already sharded by device_map; skip explicit .to()
109
+ pass
110
+
111
+ self.model.eval()
112
+ for param in self.model.parameters():
113
+ param.requires_grad = False
114
+
115
+ print("✓ LLaVA model loaded and frozen")
116
+
117
+ def prepare_inputs(
118
+ self,
119
+ images, # Either list of PIL images or torch.Tensor
120
+ prompts: list,
121
+ conv_mode: str = "llava_v1"
122
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
123
+ """
124
+ Prepare inputs for LLaVA forward pass.
125
+
126
+ Args:
127
+ images: Either list of PIL images or image tensors (B, 3, H, W)
128
+ prompts: List of text prompts (B,)
129
+ conv_mode: Conversation template mode
130
+
131
+ Returns:
132
+ input_ids: Tokenized inputs (B, L)
133
+ images: Processed images (B, 3, 336, 336)
134
+ """
135
+ batch_size = len(prompts)
136
+
137
+ # Process images: convert PIL to tensors if needed
138
+ if isinstance(images, list):
139
+ # List of PIL images - process each one
140
+ from PIL import Image
141
+ processed_images = []
142
+ for img in images:
143
+ if isinstance(img, Image.Image):
144
+ # Preprocess PIL image (LLaVA's CLIP processor)
145
+ img_tensor = self.image_processor.preprocess(img, return_tensors='pt')['pixel_values'][0]
146
+ processed_images.append(img_tensor)
147
+ else:
148
+ # Already a tensor
149
+ processed_images.append(img)
150
+ images = torch.stack(processed_images).to(self.device)
151
+ else:
152
+ # Already a batched tensor
153
+ if images.device != self.device:
154
+ images = images.to(self.device)
155
+
156
+ # Tokenize prompts with image tokens
157
+ input_ids_list = []
158
+ for prompt in prompts:
159
+ # Add image token
160
+ if self.model.config.mm_use_im_start_end:
161
+ prompt = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + prompt
162
+ else:
163
+ prompt = DEFAULT_IMAGE_TOKEN + '\n' + prompt
164
+
165
+ # Tokenize
166
+ input_ids = tokenizer_image_token(
167
+ prompt,
168
+ self.tokenizer,
169
+ IMAGE_TOKEN_INDEX,
170
+ return_tensors='pt'
171
+ )
172
+ input_ids_list.append(input_ids)
173
+
174
+ # Pad to same length
175
+ max_len = max(ids.size(0) for ids in input_ids_list)
176
+ input_ids_padded = []
177
+ for ids in input_ids_list:
178
+ padding = torch.full((max_len - ids.size(0),), self.tokenizer.pad_token_id, dtype=ids.dtype)
179
+ input_ids_padded.append(torch.cat([ids, padding]))
180
+
181
+ input_ids = torch.stack(input_ids_padded).to(self.device)
182
+
183
+ return input_ids, images
184
+
185
+ @torch.no_grad()
186
+ def extract_hidden_states(
187
+ self,
188
+ images, # Either list of PIL images or torch.Tensor
189
+ prompts: list,
190
+ ) -> torch.Tensor:
191
+ """
192
+ Extract hidden states from LLaVA model (before lm_head).
193
+
194
+ Args:
195
+ images: Either list of PIL images or image tensors (B, 3, H, W)
196
+ prompts: Text prompts (B,)
197
+
198
+ Returns:
199
+ hidden_states: Hidden states before lm_head, shape (B, L, 4096)
200
+ """
201
+ # Prepare inputs (handles PIL->tensor conversion if needed)
202
+ input_ids, image_tensors = self.prepare_inputs(images, prompts)
203
+
204
+ # Ensure FP16 for efficiency
205
+ if image_tensors.device.type == "cpu":
206
+ # Avoid half on CPU (causes slow_conv2d_cpu not implemented for Half)
207
+ pass
208
+ else:
209
+ if image_tensors.dtype != torch.float16:
210
+ image_tensors = image_tensors.half()
211
+
212
+ # Forward through LLaVA; use top-level model so it accepts `images`
213
+ # hidden_states are from the base model (before lm_head)
214
+ def _forward_with(images_tensor: torch.Tensor):
215
+ return self.model(
216
+ input_ids=input_ids,
217
+ images=images_tensor,
218
+ return_dict=True,
219
+ output_hidden_states=True
220
+ )
221
+
222
+ try:
223
+ images_fwd = image_tensors
224
+ if images_fwd.device.type == 'cuda':
225
+ images_fwd = images_fwd.contiguous()
226
+ outputs = _forward_with(images_fwd)
227
+ except RuntimeError as e:
228
+ msg = str(e)
229
+ # Fallback: retry in float32 on the same device for broader kernel support
230
+ if 'GET was unable to find an engine' in msg or 'CUBLAS_STATUS_NOT_INITIALIZED' in msg:
231
+ try:
232
+ vt = None
233
+ try:
234
+ vt = self.model.get_vision_tower()
235
+ except Exception:
236
+ vt = None
237
+ if vt is not None:
238
+ vt.to(device=self.device, dtype=torch.float32)
239
+ images_f32 = image_tensors.to(device=self.device, dtype=torch.float32).contiguous()
240
+ outputs = _forward_with(images_f32)
241
+ except Exception:
242
+ raise
243
+ else:
244
+ raise
245
+
246
+ # Get last hidden states (before lm_head)
247
+ hidden_states = outputs.hidden_states[-1] # Shape: (B, L, 4096)
248
+
249
+ return hidden_states
250
+
251
+ def forward(self, images, prompts: list) -> torch.Tensor:
252
+ """
253
+ Forward pass - extract hidden states.
254
+
255
+ Args:
256
+ images: Either list of PIL images or image tensors (B, 3, H, W)
257
+ prompts: Text prompts (B,)
258
+
259
+ Returns:
260
+ hidden_states: Hidden states, shape (B, L, 4096)
261
+ """
262
+ return self.extract_hidden_states(images, prompts)
263
+
264
+
265
+ def test_extractor():
266
+ """Test the frozen LLaVA extractor"""
267
+ import torch
268
+ from PIL import Image
269
+ import requests
270
+ from io import BytesIO
271
+
272
+ print("Testing FrozenLLaVAExtractor...")
273
+
274
+ # Paths (adjust as needed)
275
+ llava_base = "checkpoints/llava-1.5-7b-hf"
276
+ llava_lora = "checkpoints/llava-miragehd-prior-bbox"
277
+
278
+ # Create extractor
279
+ extractor = FrozenLLaVAExtractor(
280
+ llava_base_path=llava_base,
281
+ llava_lora_path=llava_lora,
282
+ device="cuda"
283
+ )
284
+
285
+ # Test with dummy data
286
+ batch_size = 2
287
+ prompts = [
288
+ "How would this RGB scene appear in long-wave thermal infrared spectrum",
289
+ "Describe the thermal characteristics of this scene"
290
+ ]
291
+
292
+ # Create dummy images
293
+ dummy_images = torch.randn(batch_size, 3, 336, 336).cuda()
294
+
295
+ # Extract hidden states
296
+ hidden_states = extractor(dummy_images, prompts)
297
+ print(f"Hidden states shape: {hidden_states.shape}")
298
+ print(f"Expected: (batch_size, variable_length, 4096)")
299
+ print(f"✓ Frozen LLaVA extractor test passed!")
300
+
301
+ # Verify frozen
302
+ assert not any(p.requires_grad for p in extractor.parameters()), "Model should be frozen!"
303
+ print("✓ All parameters frozen")
304
+
305
+
306
+ if __name__ == "__main__":
307
+ test_extractor()
308
+
llava/model/img_token_utils.py ADDED
@@ -0,0 +1,716 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utility functions for adding and managing IMG tokens for VLM-guided diffusion.
3
+ """
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ from typing import List
8
+ from llava.constants import IMG_TOKENS
9
+
10
+
11
+ def add_img_tokens_to_tokenizer(tokenizer, img_tokens: List[str] = None,
12
+ special_tokens: bool = True):
13
+ """
14
+ Add IMG tokens to the tokenizer (safe for resume - won't double-add).
15
+
16
+ Args:
17
+ tokenizer: HuggingFace tokenizer
18
+ img_tokens: List of IMG tokens (default: IMG_TOKENS from constants)
19
+ special_tokens: If True, tokens are added as special tokens (auto-stripped with skip_special_tokens=True)
20
+ If False, tokens are normal vocabulary (always kept in decode)
21
+
22
+ Returns:
23
+ num_added: Number of tokens added (0 if already present)
24
+ token_ids: List of token IDs for the IMG tokens
25
+
26
+ Note:
27
+ - When decoding for debugging/metrics, use skip_special_tokens=False to see IMG tokens
28
+ - MGIE uses special_tokens=True (default behavior)
29
+ - Safe for resume: checks existing vocab to avoid double-adding
30
+ """
31
+ if img_tokens is None:
32
+ img_tokens = IMG_TOKENS
33
+
34
+ # Check for existing tokens (CRITICAL for resume!)
35
+ existing_vocab = set(tokenizer.get_vocab().keys())
36
+ tokens_to_add = [t for t in img_tokens if t not in existing_vocab]
37
+
38
+ if not tokens_to_add:
39
+ # All tokens already exist (likely resuming from checkpoint)
40
+ print(f"IMG tokens already in tokenizer (resuming from checkpoint)")
41
+ token_ids = tokenizer.convert_tokens_to_ids(img_tokens)
42
+ print(f" Tokens: {img_tokens}")
43
+ print(f" Token IDs: {token_ids}")
44
+ print(f" Vocab size: {len(tokenizer)}")
45
+ return 0, token_ids
46
+
47
+ # Add only new tokens
48
+ num_added = tokenizer.add_tokens(tokens_to_add, special_tokens=special_tokens)
49
+
50
+ # Get all token IDs (including previously existing ones)
51
+ token_ids = tokenizer.convert_tokens_to_ids(img_tokens)
52
+
53
+ print(f"Added {num_added} IMG tokens to tokenizer")
54
+ print(f" New tokens added: {tokens_to_add}")
55
+ print(f" All IMG token IDs: {token_ids}")
56
+ print(f" New vocab size: {len(tokenizer)}")
57
+ print(f" Added as: {'special tokens' if special_tokens else 'normal tokens'}")
58
+
59
+ if special_tokens:
60
+ print(f" ⚠️ Remember: Use skip_special_tokens=False when decoding for debugging")
61
+
62
+ return num_added, token_ids
63
+
64
+
65
+ def save_tokenizer_with_img_tokens(tokenizer, output_dir: str):
66
+ """
67
+ Save tokenizer with IMG tokens for later use.
68
+
69
+ This is critical for:
70
+ - Resuming training from checkpoint
71
+ - Evaluation/inference
72
+ - Preventing silent vocab mismatch errors
73
+
74
+ Args:
75
+ tokenizer: Tokenizer with IMG tokens added
76
+ output_dir: Directory to save tokenizer
77
+ """
78
+ import os
79
+ os.makedirs(output_dir, exist_ok=True)
80
+ tokenizer.save_pretrained(output_dir)
81
+ print(f"✓ Saved tokenizer with {len(tokenizer)} tokens to: {output_dir}")
82
+
83
+
84
+ def resize_token_embeddings_and_init(model, tokenizer, init_method: str = "mean", init_std: float = 0.02):
85
+ """
86
+ Resize model token embeddings and initialize new IMG token embeddings.
87
+
88
+ Args:
89
+ model: LLaVA model
90
+ tokenizer: Tokenizer (after adding IMG tokens)
91
+ init_method: "mean" (MGIE-style, average of existing) or "normal" (N(0, std))
92
+ init_std: Standard deviation for normal initialization (only used if init_method="normal")
93
+
94
+ Returns:
95
+ new_token_ids: List of new token IDs
96
+ """
97
+ old_vocab_size = model.config.vocab_size
98
+ new_vocab_size = len(tokenizer)
99
+ num_new_tokens = new_vocab_size - old_vocab_size
100
+
101
+ if num_new_tokens == 0:
102
+ print("No new tokens to add")
103
+ return []
104
+
105
+ print(f"\nResizing token embeddings:")
106
+ print(f" Old vocab size: {old_vocab_size}")
107
+ print(f" New vocab size: {new_vocab_size}")
108
+ print(f" Adding {num_new_tokens} new tokens")
109
+ print(f" Initialization method: {init_method}")
110
+
111
+ # Remember original dtype before resize
112
+ original_dtype = model.get_model().embed_tokens.weight.dtype
113
+
114
+ # Resize embeddings
115
+ model.resize_token_embeddings(new_vocab_size)
116
+
117
+ # CRITICAL: resize_token_embeddings may reset entire model to float32
118
+ # This is especially important when model is in float16/bfloat16
119
+ if model.get_model().embed_tokens.weight.dtype != original_dtype:
120
+ print(f" ! Warning: resize changed dtype from {original_dtype} to {model.get_model().embed_tokens.weight.dtype}")
121
+ print(f" ! Restoring entire model to {original_dtype}...")
122
+
123
+ # Convert entire model back to original dtype
124
+ if original_dtype == torch.float16:
125
+ model = model.half()
126
+ elif original_dtype == torch.bfloat16:
127
+ model = model.bfloat16()
128
+ elif original_dtype == torch.float32:
129
+ model = model.float()
130
+
131
+ print(f" ✓ Model restored to {original_dtype}")
132
+
133
+ # ALSO convert vision tower if it exists (resize doesn't touch it, but we need consistency)
134
+ vision_tower = model.get_vision_tower()
135
+ if vision_tower is not None:
136
+ vision_dtype = next(vision_tower.parameters()).dtype
137
+ if vision_dtype != original_dtype:
138
+ print(f" ! Vision tower dtype mismatch: {vision_dtype} vs expected {original_dtype}")
139
+ print(f" ! Converting vision tower to {original_dtype}...")
140
+
141
+ if original_dtype == torch.float16:
142
+ vision_tower = vision_tower.half()
143
+ elif original_dtype == torch.bfloat16:
144
+ vision_tower = vision_tower.bfloat16()
145
+ elif original_dtype == torch.float32:
146
+ vision_tower = vision_tower.float()
147
+
148
+ print(f" ✓ Vision tower converted to {original_dtype}")
149
+
150
+ # Sanity check: ensure config is updated (HF usually does this automatically)
151
+ assert model.config.vocab_size == new_vocab_size, \
152
+ f"Config vocab size mismatch! model.config.vocab_size={model.config.vocab_size}, expected={new_vocab_size}"
153
+
154
+ # Get new token IDs (the last num_new_tokens)
155
+ new_token_ids = list(range(old_vocab_size, new_vocab_size))
156
+
157
+ # Initialize new token embeddings
158
+ with torch.no_grad():
159
+ embed_tokens = model.get_model().embed_tokens
160
+ lm_head = model.lm_head
161
+
162
+ if init_method == "mean":
163
+ # MGIE-style: mean of existing embeddings (smoother start)
164
+ # Compute mean - stays on same device and dtype as source
165
+ embed_mean = embed_tokens.weight.data[:old_vocab_size].mean(dim=0, keepdim=True)
166
+ lm_mean = lm_head.weight.data[:old_vocab_size].mean(dim=0, keepdim=True)
167
+
168
+ # Direct assignment (mean is already on correct device from the slice)
169
+ # Important: Don't use .to(device=...) as model may be distributed across GPUs
170
+ for idx in new_token_ids:
171
+ embed_tokens.weight.data[idx] = embed_mean.squeeze(0)
172
+ lm_head.weight.data[idx] = lm_mean.squeeze(0)
173
+
174
+ print(f" ✓ Initialized embeddings as mean of existing tokens (dtype: {embed_tokens.weight.dtype})")
175
+ else:
176
+ # Normal initialization - create on same device/dtype as existing weights
177
+ # Use the embedding's own device and dtype
178
+ new_embed = torch.randn(
179
+ len(new_token_ids), embed_tokens.weight.shape[1],
180
+ dtype=embed_tokens.weight.dtype,
181
+ device=embed_tokens.weight.device
182
+ ) * init_std
183
+
184
+ new_lm = torch.randn(
185
+ len(new_token_ids), lm_head.weight.shape[1],
186
+ dtype=lm_head.weight.dtype,
187
+ device=lm_head.weight.device
188
+ ) * init_std
189
+
190
+ embed_tokens.weight.data[new_token_ids] = new_embed
191
+ lm_head.weight.data[new_token_ids] = new_lm
192
+
193
+ print(f" ✓ Initialized embeddings with N(0, {init_std}) (dtype: {embed_tokens.weight.dtype})")
194
+
195
+ # Final verification: check dtype consistency across model
196
+ print(f"\n Verifying dtype consistency across all modules...")
197
+ dtype_consistent, _ = verify_model_dtype_consistency(model, expected_dtype=original_dtype)
198
+
199
+ if not dtype_consistent:
200
+ print(f" ✗ WARNING: Model has dtype inconsistencies after resize!")
201
+ print(f" ✗ This may cause 'mat1 and mat2 must have same dtype' errors!")
202
+ print(f" ✗ Consider calling model.half() or model.float() to fix.")
203
+ else:
204
+ print(f" ✓ All modules consistent at {original_dtype}")
205
+
206
+ return new_token_ids
207
+
208
+
209
+ def setup_llava_trainable_params_mgie_style(model, train_vision_tower: bool = False,
210
+ train_mm_projector: bool = False):
211
+ """
212
+ Setup trainable parameters MGIE-style: train full embed_tokens and lm_head.
213
+ This is simpler and safer than gradient masking for controlled training.
214
+
215
+ Args:
216
+ model: LLaVA model
217
+ train_vision_tower: Whether to train vision tower (default: False)
218
+ train_mm_projector: Whether to train mm_projector (default: False)
219
+
220
+ Returns:
221
+ trainable_param_names: List of trainable parameter names
222
+ """
223
+ print(f"\nSetting up MGIE-style trainable parameters:")
224
+
225
+ # Freeze everything first
226
+ for param in model.parameters():
227
+ param.requires_grad = False
228
+
229
+ trainable_params = []
230
+
231
+ # Train embed_tokens (full matrix)
232
+ embed_tokens = model.get_model().embed_tokens
233
+ embed_tokens.weight.requires_grad = True
234
+ trainable_params.append("model.embed_tokens.weight")
235
+ print(f" ✓ embed_tokens: trainable (full matrix, {embed_tokens.weight.shape})")
236
+
237
+ # Train lm_head (full matrix)
238
+ lm_head = model.lm_head
239
+ lm_head.weight.requires_grad = True
240
+ trainable_params.append("lm_head.weight")
241
+ print(f" ✓ lm_head: trainable (full matrix, {lm_head.weight.shape})")
242
+
243
+ # Optional: train vision tower
244
+ if train_vision_tower:
245
+ vision_tower = model.get_vision_tower()
246
+ if vision_tower is not None:
247
+ for param in vision_tower.parameters():
248
+ param.requires_grad = True
249
+ trainable_params.append("vision_tower.*")
250
+ print(f" ✓ vision_tower: trainable")
251
+
252
+ # Optional: train mm_projector
253
+ if train_mm_projector:
254
+ mm_projector = model.get_model().mm_projector
255
+ if mm_projector is not None:
256
+ for param in mm_projector.parameters():
257
+ param.requires_grad = True
258
+ trainable_params.append("mm_projector.*")
259
+ print(f" ✓ mm_projector: trainable")
260
+
261
+ # Count trainable parameters
262
+ total_params = sum(p.numel() for p in model.parameters())
263
+ trainable_count = sum(p.numel() for p in model.parameters() if p.requires_grad)
264
+
265
+ print(f"\n Total parameters: {total_params:,}")
266
+ print(f" Trainable parameters: {trainable_count:,} ({100*trainable_count/total_params:.2f}%)")
267
+
268
+ return trainable_params
269
+
270
+
271
+ def setup_img_token_gradient_masks(model, tokenizer, img_tokens: List[str] = None):
272
+ """
273
+ [ADVANCED/OPTIONAL] Setup gradient masks to train only IMG token embeddings and LM head rows.
274
+
275
+ NOTE: For most use cases, use `setup_llava_trainable_params_mgie_style()` instead.
276
+ This function is for advanced users who want fine-grained control.
277
+
278
+ This registers hooks that zero out gradients for all non-IMG token rows,
279
+ ensuring only the IMG token embeddings and their LM head projections are trained.
280
+
281
+ MGIE-style (simpler, recommended): Train full matrices with low LR
282
+ Gradient masking (this function): Train only specific rows with normal LR
283
+
284
+ Args:
285
+ model: LLaVA model
286
+ tokenizer: Tokenizer (after adding IMG tokens)
287
+ img_tokens: List of IMG tokens (default: IMG_TOKENS from constants)
288
+
289
+ Returns:
290
+ img_token_ids: List of IMG token IDs
291
+ """
292
+ if img_tokens is None:
293
+ img_tokens = IMG_TOKENS
294
+
295
+ # Get IMG token IDs
296
+ img_token_ids = tokenizer.convert_tokens_to_ids(img_tokens)
297
+
298
+ print(f"\nSetting up gradient masks for IMG tokens:")
299
+ print(f" IMG token IDs: {img_token_ids}")
300
+
301
+ # Get embedding and lm_head
302
+ embed_tokens = model.get_model().embed_tokens
303
+ lm_head = model.lm_head
304
+
305
+ # Create masks on the correct device and dtype
306
+ vocab_size = lm_head.weight.size(0)
307
+
308
+ # LM head mask: (vocab_size, 1) - broadcasts over hidden_dim
309
+ # Match dtype and device of the weights
310
+ lm_mask = torch.zeros(vocab_size, 1, device=lm_head.weight.device, dtype=lm_head.weight.dtype)
311
+ lm_mask[img_token_ids] = 1.0
312
+
313
+ # Embedding mask: (vocab_size, 1) - broadcasts over embed_dim
314
+ emb_mask = torch.zeros(embed_tokens.num_embeddings, 1, device=embed_tokens.weight.device, dtype=embed_tokens.weight.dtype)
315
+ emb_mask[img_token_ids] = 1.0
316
+
317
+ # Register hooks
318
+ def lm_head_grad_mask_hook(grad):
319
+ """Zero out gradients for non-IMG token rows in LM head"""
320
+ # Ensure mask matches gradient dtype
321
+ mask = lm_mask.to(dtype=grad.dtype) if lm_mask.dtype != grad.dtype else lm_mask
322
+ return grad * mask
323
+
324
+ def embed_grad_mask_hook(grad):
325
+ """Zero out gradients for non-IMG token rows in embeddings"""
326
+ # Ensure mask matches gradient dtype
327
+ mask = emb_mask.to(dtype=grad.dtype) if emb_mask.dtype != grad.dtype else emb_mask
328
+ return grad * mask
329
+
330
+ lm_head.weight.register_hook(lm_head_grad_mask_hook)
331
+ embed_tokens.weight.register_hook(embed_grad_mask_hook)
332
+
333
+ print(f" ✓ Registered gradient mask hooks")
334
+ print(f" ✓ Only {len(img_token_ids)} token rows will be trained")
335
+
336
+ return img_token_ids
337
+
338
+
339
+ def verify_model_dtype_consistency(model, expected_dtype=None):
340
+ """
341
+ Verify that all model parameters have consistent dtype.
342
+
343
+ This is critical after resize_token_embeddings which may reset parts to float32.
344
+
345
+ Args:
346
+ model: LLaVA model
347
+ expected_dtype: Expected dtype (if None, use embed_tokens dtype)
348
+
349
+ Returns:
350
+ all_consistent: Boolean
351
+ dtype_report: Dict with dtype info per module
352
+ """
353
+ if expected_dtype is None:
354
+ expected_dtype = model.get_model().embed_tokens.weight.dtype
355
+
356
+ dtype_report = {}
357
+ all_consistent = True
358
+
359
+ # Check key modules
360
+ modules_to_check = {
361
+ 'embed_tokens': model.get_model().embed_tokens,
362
+ 'lm_head': model.lm_head,
363
+ }
364
+
365
+ # Add optional modules
366
+ if hasattr(model.get_model(), 'mm_projector'):
367
+ modules_to_check['mm_projector'] = model.get_model().mm_projector
368
+
369
+ vision_tower = model.get_vision_tower()
370
+ if vision_tower is not None:
371
+ modules_to_check['vision_tower'] = vision_tower
372
+
373
+ for name, module in modules_to_check.items():
374
+ param_dtypes = [p.dtype for p in module.parameters()]
375
+ if param_dtypes:
376
+ unique_dtypes = set(param_dtypes)
377
+ dtype_report[name] = unique_dtypes
378
+
379
+ if len(unique_dtypes) > 1:
380
+ print(f" ✗ {name}: MIXED dtypes {unique_dtypes}")
381
+ all_consistent = False
382
+ elif expected_dtype not in unique_dtypes:
383
+ actual = list(unique_dtypes)[0]
384
+ print(f" ✗ {name}: dtype {actual}, expected {expected_dtype}")
385
+ all_consistent = False
386
+ else:
387
+ print(f" ✓ {name}: {list(unique_dtypes)[0]}")
388
+
389
+ return all_consistent, dtype_report
390
+
391
+
392
+ def verify_img_token_setup(model, tokenizer, img_tokens: List[str] = None):
393
+ """
394
+ Comprehensive sanity check for IMG token setup before training.
395
+
396
+ This checks:
397
+ - Tokenizer vocab matches model config
398
+ - IMG tokens exist in vocabulary
399
+ - IMG tokens are properly initialized
400
+ - Model is ready for training
401
+
402
+ Args:
403
+ model: LLaVA model
404
+ tokenizer: Tokenizer
405
+ img_tokens: List of IMG tokens (default: IMG_TOKENS from constants)
406
+
407
+ Returns:
408
+ success: Boolean indicating if all checks passed
409
+ """
410
+ if img_tokens is None:
411
+ img_tokens = IMG_TOKENS
412
+
413
+ print("\n" + "="*60)
414
+ print("IMG TOKEN SETUP VERIFICATION")
415
+ print("="*60)
416
+
417
+ all_good = True
418
+
419
+ # 1. Check tokenizer/model vocab size consistency
420
+ print(f"\n1. Vocab size consistency:")
421
+ tokenizer_size = len(tokenizer)
422
+ model_config_size = model.config.vocab_size
423
+ embed_size = model.get_model().embed_tokens.weight.shape[0]
424
+ lm_head_size = model.lm_head.weight.shape[0]
425
+
426
+ print(f" Tokenizer vocab size: {tokenizer_size}")
427
+ print(f" Model config vocab size: {model_config_size}")
428
+ print(f" Embedding matrix size: {embed_size}")
429
+ print(f" LM head matrix size: {lm_head_size}")
430
+
431
+ if tokenizer_size != model_config_size:
432
+ print(f" ✗ Tokenizer/config mismatch!")
433
+ all_good = False
434
+ elif embed_size != tokenizer_size:
435
+ print(f" ✗ Embedding size mismatch!")
436
+ all_good = False
437
+ elif lm_head_size != tokenizer_size:
438
+ print(f" ✗ LM head size mismatch!")
439
+ all_good = False
440
+ else:
441
+ print(f" ✓ All sizes match ({tokenizer_size})")
442
+
443
+ # 2. Check IMG tokens exist
444
+ print(f"\n2. IMG tokens in vocabulary:")
445
+ token_ids = tokenizer.convert_tokens_to_ids(img_tokens)
446
+ unk_id = tokenizer.unk_token_id
447
+
448
+ missing_tokens = []
449
+ for token, token_id in zip(img_tokens, token_ids):
450
+ if token_id == unk_id:
451
+ print(f" ✗ {token}: MISSING (maps to UNK)")
452
+ missing_tokens.append(token)
453
+ all_good = False
454
+ else:
455
+ print(f" ✓ {token}: ID={token_id}")
456
+
457
+ if missing_tokens:
458
+ print(f" ✗ Missing tokens: {missing_tokens}")
459
+ else:
460
+ print(f" ✓ All {len(img_tokens)} IMG tokens present")
461
+
462
+ # 3. Check initialization
463
+ print(f"\n3. Embedding initialization:")
464
+ with torch.no_grad():
465
+ embed_weights = model.get_model().embed_tokens.weight[token_ids]
466
+ lm_weights = model.lm_head.weight[token_ids]
467
+
468
+ embed_norms = embed_weights.norm(dim=1)
469
+ lm_norms = lm_weights.norm(dim=1)
470
+
471
+ print(f" Embedding norms: mean={embed_norms.mean():.4f}, min={embed_norms.min():.4f}, max={embed_norms.max():.4f}")
472
+ print(f" LM head norms: mean={lm_norms.mean():.4f}, min={lm_norms.min():.4f}, max={lm_norms.max():.4f}")
473
+
474
+ if embed_norms.mean() < 0.001 or lm_norms.mean() < 0.001:
475
+ print(f" ⚠ Warning: Embeddings may not be initialized (norms very small)")
476
+ all_good = False
477
+ else:
478
+ print(f" ✓ Embeddings appear initialized")
479
+
480
+ # 4. Check dtype consistency
481
+ print(f"\n4. Dtype consistency:")
482
+ dtype_consistent, dtype_report = verify_model_dtype_consistency(model)
483
+
484
+ if not dtype_consistent:
485
+ print(f" ✗ Model has dtype inconsistencies!")
486
+ all_good = False
487
+ else:
488
+ print(f" ✓ All modules have consistent dtype")
489
+
490
+ # 5. Final sanity checks
491
+ print(f"\n5. Final checks:")
492
+
493
+ # Check that model config is consistent
494
+ if model.config.vocab_size == tokenizer_size:
495
+ print(f" ✓ Config vocab_size consistent with tokenizer")
496
+ else:
497
+ print(f" ✗ Config vocab_size inconsistent!")
498
+ all_good = False
499
+
500
+ # Remind about critical training setup
501
+ print(f"\n6. Training setup reminders:")
502
+ print(f" ⚠️ Save tokenizer: tokenizer.save_pretrained(output_dir)")
503
+ print(f" ⚠️ Decode with: skip_special_tokens=False (for debugging)")
504
+ print(f" ⚠️ Ensure IMG tokens in labels != IGNORE_INDEX")
505
+ print(f" ⚠️ Use weight_decay=0.0 for embed_tokens and lm_head")
506
+ print(f" ⚠️ Use low LR (5e-6 to 1e-5) for language matrices")
507
+
508
+ print("\n" + "="*60)
509
+ if all_good:
510
+ print("✅ ALL CHECKS PASSED - Ready for training!")
511
+ else:
512
+ print("❌ SOME CHECKS FAILED - Fix issues before training!")
513
+ print("="*60 + "\n")
514
+
515
+ return all_good
516
+
517
+
518
+ def verify_img_tokens(model, tokenizer, img_tokens: List[str] = None):
519
+ """
520
+ Verify that IMG tokens exist and are properly set up.
521
+
522
+ Args:
523
+ model: LLaVA model
524
+ tokenizer: Tokenizer
525
+ img_tokens: List of IMG tokens (default: IMG_TOKENS from constants)
526
+
527
+ Returns:
528
+ success: Boolean indicating if all checks passed
529
+ """
530
+ if img_tokens is None:
531
+ img_tokens = IMG_TOKENS
532
+
533
+ print("\n" + "="*60)
534
+ print("VERIFYING IMG TOKENS")
535
+ print("="*60)
536
+
537
+ all_good = True
538
+
539
+ # Check tokenizer
540
+ print(f"\n1. Checking tokenizer:")
541
+ token_ids = tokenizer.convert_tokens_to_ids(img_tokens)
542
+ unk_id = tokenizer.unk_token_id
543
+
544
+ for token, token_id in zip(img_tokens, token_ids):
545
+ if token_id == unk_id:
546
+ print(f" ✗ {token}: MISSING (maps to UNK)")
547
+ all_good = False
548
+ else:
549
+ print(f" ✓ {token}: ID={token_id}")
550
+
551
+ # Check model vocab size
552
+ print(f"\n2. Checking model:")
553
+ print(f" Tokenizer vocab size: {len(tokenizer)}")
554
+ print(f" Model vocab size: {model.config.vocab_size}")
555
+ print(f" Embedding weight shape: {model.get_model().embed_tokens.weight.shape}")
556
+ print(f" LM head weight shape: {model.lm_head.weight.shape}")
557
+
558
+ if model.config.vocab_size != len(tokenizer):
559
+ print(f" ✗ Model vocab size mismatch!")
560
+ all_good = False
561
+ else:
562
+ print(f" ✓ Vocab sizes match")
563
+
564
+ # Check embedding norms (should be non-zero if initialized)
565
+ print(f"\n3. Checking embedding initialization:")
566
+ with torch.no_grad():
567
+ embed_weights = model.get_model().embed_tokens.weight[token_ids]
568
+ lm_weights = model.lm_head.weight[token_ids]
569
+
570
+ embed_norms = embed_weights.norm(dim=1)
571
+ lm_norms = lm_weights.norm(dim=1)
572
+
573
+ print(f" Embedding norms: mean={embed_norms.mean():.4f}, min={embed_norms.min():.4f}, max={embed_norms.max():.4f}")
574
+ print(f" LM head norms: mean={lm_norms.mean():.4f}, min={lm_norms.min():.4f}, max={lm_norms.max():.4f}")
575
+
576
+ if embed_norms.mean() < 0.001 or lm_norms.mean() < 0.001:
577
+ print(f" ⚠ Warning: Embeddings may not be initialized (norms very small)")
578
+ else:
579
+ print(f" ✓ Embeddings appear initialized")
580
+
581
+ print("\n" + "="*60)
582
+ if all_good:
583
+ print("✓ ALL CHECKS PASSED")
584
+ else:
585
+ print("✗ SOME CHECKS FAILED")
586
+ print("="*60 + "\n")
587
+
588
+ return all_good
589
+
590
+
591
+ def get_img_token_ids(tokenizer, img_tokens: List[str] = None) -> List[int]:
592
+ """
593
+ Get IMG token IDs from tokenizer.
594
+
595
+ Args:
596
+ tokenizer: HuggingFace tokenizer
597
+ img_tokens: List of IMG tokens (default: IMG_TOKENS from constants)
598
+
599
+ Returns:
600
+ token_ids: List of IMG token IDs
601
+ """
602
+ if img_tokens is None:
603
+ img_tokens = IMG_TOKENS
604
+
605
+ return tokenizer.convert_tokens_to_ids(img_tokens)
606
+
607
+
608
+ def extract_img_token_positions(labels: torch.Tensor, img_token_ids: List[int]) -> torch.Tensor:
609
+ """
610
+ Extract positions of IMG tokens in the labels tensor.
611
+
612
+ Args:
613
+ labels: (B, L) tensor of token IDs
614
+ img_token_ids: List of IMG token IDs to search for
615
+
616
+ Returns:
617
+ positions: (B, K) tensor of positions for each IMG token
618
+ -1 indicates the token was not found
619
+ """
620
+ batch_size = labels.size(0)
621
+ num_img_tokens = len(img_token_ids)
622
+
623
+ # Initialize with -1 (not found)
624
+ positions = torch.full((batch_size, num_img_tokens), -1, dtype=torch.long, device=labels.device)
625
+
626
+ # For each batch
627
+ for b in range(batch_size):
628
+ # For each IMG token
629
+ for k, token_id in enumerate(img_token_ids):
630
+ # Find positions where this token appears
631
+ matches = (labels[b] == token_id).nonzero(as_tuple=True)[0]
632
+ if len(matches) > 0:
633
+ # Take the first occurrence
634
+ positions[b, k] = matches[0]
635
+
636
+ return positions
637
+
638
+
639
+ def create_img_token_mask(positions: torch.Tensor) -> torch.Tensor:
640
+ """
641
+ Create a binary mask from IMG token positions.
642
+
643
+ Args:
644
+ positions: (B, K) tensor from extract_img_token_positions (-1 = not found)
645
+
646
+ Returns:
647
+ mask: (B, K) binary tensor (1=valid token, 0=missing)
648
+ """
649
+ # positions >= 0 means token was found
650
+ mask = (positions >= 0).to(dtype=torch.float32)
651
+ return mask
652
+
653
+
654
+ def gather_img_hidden_states(hidden_states: torch.Tensor,
655
+ positions: torch.Tensor,
656
+ fill_value: float = 0.0) -> torch.Tensor:
657
+ """
658
+ Gather hidden states at IMG token positions.
659
+
660
+ Args:
661
+ hidden_states: (B, L, D) tensor of hidden states
662
+ positions: (B, K) tensor of positions (from extract_img_token_positions)
663
+ fill_value: Value to use for missing tokens (default: 0.0)
664
+
665
+ Returns:
666
+ img_hiddens: (B, K, D) tensor of IMG token hidden states
667
+ """
668
+ batch_size, seq_len, hidden_dim = hidden_states.shape
669
+ num_img_tokens = positions.size(1)
670
+
671
+ # Initialize output with fill_value
672
+ img_hiddens = torch.full(
673
+ (batch_size, num_img_tokens, hidden_dim),
674
+ fill_value,
675
+ dtype=hidden_states.dtype,
676
+ device=hidden_states.device
677
+ )
678
+
679
+ # Gather hidden states at valid positions
680
+ for b in range(batch_size):
681
+ for k in range(num_img_tokens):
682
+ pos = positions[b, k].item()
683
+ if pos >= 0 and pos < seq_len:
684
+ img_hiddens[b, k] = hidden_states[b, pos]
685
+
686
+ return img_hiddens
687
+
688
+
689
+ def extract_img_token_hiddens(hidden_states: torch.Tensor,
690
+ labels: torch.Tensor,
691
+ img_token_ids: List[int],
692
+ fill_value: float = 0.0,
693
+ return_mask: bool = False):
694
+ """
695
+ Combined function to extract IMG token hidden states from labels and hidden states.
696
+
697
+ Args:
698
+ hidden_states: (B, L, D) tensor from model output (last layer)
699
+ labels: (B, L) tensor of token IDs
700
+ img_token_ids: List of IMG token IDs
701
+ fill_value: Value to use for missing tokens (default: 0.0)
702
+ return_mask: If True, also return a validity mask (default: False)
703
+
704
+ Returns:
705
+ img_hiddens: (B, K, D) tensor of IMG token hidden states
706
+ mask: (B, K) binary mask (1=valid, 0=missing) - only if return_mask=True
707
+ """
708
+ positions = extract_img_token_positions(labels, img_token_ids)
709
+ img_hiddens = gather_img_hidden_states(hidden_states, positions, fill_value)
710
+
711
+ if return_mask:
712
+ mask = create_img_token_mask(positions)
713
+ return img_hiddens, mask
714
+
715
+ return img_hiddens
716
+
llava/model/language_model/llava_llama.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Haotian Liu
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from typing import List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+
21
+ from transformers import AutoConfig, AutoModelForCausalLM, \
22
+ LlamaConfig, LlamaModel, LlamaForCausalLM
23
+
24
+ from transformers.modeling_outputs import CausalLMOutputWithPast
25
+ from transformers.generation.utils import GenerateOutput
26
+
27
+ from ..llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
28
+
29
+
30
+ class LlavaConfig(LlamaConfig):
31
+ model_type = "llava_llama"
32
+
33
+
34
+ class LlavaLlamaModel(LlavaMetaModel, LlamaModel):
35
+ config_class = LlavaConfig
36
+
37
+ def __init__(self, config: LlamaConfig):
38
+ super(LlavaLlamaModel, self).__init__(config)
39
+
40
+
41
+ class LlavaLlamaForCausalLM(LlamaForCausalLM, LlavaMetaForCausalLM):
42
+ config_class = LlavaConfig
43
+
44
+ def __init__(self, config):
45
+ super(LlamaForCausalLM, self).__init__(config)
46
+ self.model = LlavaLlamaModel(config)
47
+ self.pretraining_tp = config.pretraining_tp
48
+ self.vocab_size = config.vocab_size
49
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
50
+
51
+ # Initialize weights and apply final processing
52
+ self.post_init()
53
+
54
+ def get_model(self):
55
+ return self.model
56
+
57
+ def forward(
58
+ self,
59
+ input_ids: torch.LongTensor = None,
60
+ attention_mask: Optional[torch.Tensor] = None,
61
+ position_ids: Optional[torch.LongTensor] = None,
62
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
63
+ inputs_embeds: Optional[torch.FloatTensor] = None,
64
+ labels: Optional[torch.LongTensor] = None,
65
+ use_cache: Optional[bool] = None,
66
+ output_attentions: Optional[bool] = None,
67
+ output_hidden_states: Optional[bool] = None,
68
+ images: Optional[torch.FloatTensor] = None,
69
+ image_sizes: Optional[List[List[int]]] = None,
70
+ return_dict: Optional[bool] = None,
71
+ return_img_hiddens: Optional[bool] = False,
72
+ img_token_ids: Optional[List[int]] = None,
73
+ **kwargs,
74
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
75
+
76
+ if inputs_embeds is None:
77
+ (
78
+ input_ids,
79
+ position_ids,
80
+ attention_mask,
81
+ past_key_values,
82
+ inputs_embeds,
83
+ labels
84
+ ) = self.prepare_inputs_labels_for_multimodal(
85
+ input_ids,
86
+ position_ids,
87
+ attention_mask,
88
+ past_key_values,
89
+ labels,
90
+ images,
91
+ image_sizes
92
+ )
93
+
94
+ # Force output_hidden_states=True if we need to extract IMG hiddens
95
+ _output_hidden_states = output_hidden_states
96
+ if return_img_hiddens:
97
+ _output_hidden_states = True
98
+
99
+ # Forward to base model; be compatible with HF versions that may pass
100
+ # additional kwargs like `cache_position` during generation
101
+ try:
102
+ outputs = super().forward(
103
+ input_ids=input_ids,
104
+ attention_mask=attention_mask,
105
+ position_ids=position_ids,
106
+ past_key_values=past_key_values,
107
+ inputs_embeds=inputs_embeds,
108
+ labels=labels,
109
+ use_cache=use_cache,
110
+ output_attentions=output_attentions,
111
+ output_hidden_states=_output_hidden_states,
112
+ return_dict=return_dict,
113
+ **kwargs,
114
+ )
115
+ except TypeError as e:
116
+ # Drop unknown generation-time kwargs (e.g., cache_position) and retry
117
+ safe_kwargs = dict(kwargs)
118
+ for k in [
119
+ 'cache_position',
120
+ 'cache_positions',
121
+ ]:
122
+ if k in safe_kwargs:
123
+ safe_kwargs.pop(k)
124
+ outputs = super().forward(
125
+ input_ids=input_ids,
126
+ attention_mask=attention_mask,
127
+ position_ids=position_ids,
128
+ past_key_values=past_key_values,
129
+ inputs_embeds=inputs_embeds,
130
+ labels=labels,
131
+ use_cache=use_cache,
132
+ output_attentions=output_attentions,
133
+ output_hidden_states=_output_hidden_states,
134
+ return_dict=return_dict,
135
+ **safe_kwargs,
136
+ )
137
+
138
+ # Extract IMG token hidden states if requested
139
+ if return_img_hiddens and labels is not None and img_token_ids is not None:
140
+ from llava.model.img_token_utils import extract_img_token_hiddens
141
+
142
+ # Get last layer hidden states: (B, L, D)
143
+ hidden_states = outputs.hidden_states[-1]
144
+
145
+ # Extract IMG token hiddens: (B, K, D)
146
+ img_hiddens = extract_img_token_hiddens(
147
+ hidden_states=hidden_states,
148
+ labels=labels,
149
+ img_token_ids=img_token_ids,
150
+ fill_value=0.0
151
+ )
152
+
153
+ # Add to outputs
154
+ if return_dict:
155
+ # Can't modify frozen dataclass, so return a dict with img_hiddens
156
+ return {
157
+ 'loss': outputs.loss,
158
+ 'logits': outputs.logits,
159
+ 'past_key_values': outputs.past_key_values,
160
+ 'hidden_states': outputs.hidden_states,
161
+ 'attentions': outputs.attentions,
162
+ 'img_hiddens': img_hiddens,
163
+ }
164
+ else:
165
+ # For tuple output, append at the end
166
+ outputs = outputs + (img_hiddens,)
167
+
168
+ return outputs
169
+
170
+ @torch.no_grad()
171
+ def generate(
172
+ self,
173
+ inputs: Optional[torch.Tensor] = None,
174
+ images: Optional[torch.Tensor] = None,
175
+ image_sizes: Optional[torch.Tensor] = None,
176
+ **kwargs,
177
+ ) -> Union[GenerateOutput, torch.LongTensor]:
178
+ position_ids = kwargs.pop("position_ids", None)
179
+ attention_mask = kwargs.pop("attention_mask", None)
180
+ if "inputs_embeds" in kwargs:
181
+ raise NotImplementedError("`inputs_embeds` is not supported")
182
+
183
+ if images is not None:
184
+ (
185
+ inputs,
186
+ position_ids,
187
+ attention_mask,
188
+ _,
189
+ inputs_embeds,
190
+ _
191
+ ) = self.prepare_inputs_labels_for_multimodal(
192
+ inputs,
193
+ position_ids,
194
+ attention_mask,
195
+ None,
196
+ None,
197
+ images,
198
+ image_sizes=image_sizes
199
+ )
200
+ else:
201
+ inputs_embeds = self.get_model().embed_tokens(inputs)
202
+
203
+ return super().generate(
204
+ position_ids=position_ids,
205
+ attention_mask=attention_mask,
206
+ inputs_embeds=inputs_embeds,
207
+ **kwargs
208
+ )
209
+
210
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None,
211
+ inputs_embeds=None, **kwargs):
212
+ images = kwargs.pop("images", None)
213
+ image_sizes = kwargs.pop("image_sizes", None)
214
+ inputs = super().prepare_inputs_for_generation(
215
+ input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs
216
+ )
217
+ if images is not None:
218
+ inputs['images'] = images
219
+ if image_sizes is not None:
220
+ inputs['image_sizes'] = image_sizes
221
+ return inputs
222
+
223
+ AutoConfig.register("llava_llama", LlavaConfig)
224
+ AutoModelForCausalLM.register(LlavaConfig, LlavaLlamaForCausalLM)
llava/model/language_model/llava_llama_mgie.py ADDED
@@ -0,0 +1,470 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Haotian Liu
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from typing import List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+
21
+ from transformers import AutoConfig, AutoModelForCausalLM, \
22
+ LlamaConfig, LlamaModel, LlamaForCausalLM
23
+
24
+ from transformers.modeling_outputs import CausalLMOutputWithPast
25
+ from transformers.generation.utils import GenerateOutput
26
+
27
+ from ..llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
28
+ import torch.nn.functional as F
29
+ import diffusers
30
+ import os
31
+ from dataclasses import dataclass
32
+ from typing import Optional
33
+
34
+
35
+ DEFAULT_IMAGE_TOKEN = "<image>"
36
+ DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
37
+ DEFAULT_IM_START_TOKEN = "<im_start>"
38
+ DEFAULT_IM_END_TOKEN = "<im_end>"
39
+
40
+
41
+ class LlavaConfig(LlamaConfig):
42
+ model_type = "llava_llama"
43
+
44
+
45
+ class LlavaLlamaModel(LlavaMetaModel, LlamaModel):
46
+ config_class = LlavaConfig
47
+
48
+ def __init__(self, config: LlamaConfig):
49
+ super(LlavaLlamaModel, self).__init__(config)
50
+
51
+
52
+ @dataclass
53
+ class RGBTOutput(CausalLMOutputWithPast):
54
+ loss_ce: Optional[torch.FloatTensor] = None
55
+ loss_edit: Optional[torch.FloatTensor] = None
56
+
57
+ class LlavaLlamaForCausalLM(LlamaForCausalLM, LlavaMetaForCausalLM):
58
+ config_class = LlavaConfig
59
+
60
+ def __init__(self, config):
61
+ super(LlamaForCausalLM, self).__init__(config)
62
+ self.model = LlavaLlamaModel(config)
63
+ self.pretraining_tp = config.pretraining_tp
64
+ self.vocab_size = config.vocab_size
65
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
66
+ self.edit_head = EditMapper(d_llm=config.hidden_size)
67
+ # Initialize weights and apply final processing
68
+ self.post_init()
69
+
70
+
71
+
72
+ p2p_path = getattr(config, "p2p_model_path", "../diffusers/ip2p_ema/")
73
+
74
+ # self.scheduler = diffusers.DDPMScheduler.from_pretrained(p2p_path, subfolder="scheduler")
75
+ # self.vae = diffusers.AutoencoderKL.from_pretrained(p2p_path, subfolder="vae")
76
+ # self.unet = diffusers.UNet2DConditionModel.from_pretrained(p2p_path, subfolder="unet")
77
+
78
+ self._p2p_path = getattr(config, "p2p_model_path", "../diffusers/ip2p_ema/")
79
+ self.scheduler = None
80
+ self.vae = None
81
+ self.unet = None
82
+ self._diffusers_ready = False
83
+
84
+ # if hasattr(self.unet.config, "sample_size"):
85
+ # pass # ok
86
+ # # Ensure eps vs v-pred alignment
87
+ # if hasattr(self.scheduler.config, "prediction_type") and hasattr(self.unet.config, "prediction_type"):
88
+ # self.scheduler.register_to_config(prediction_type=self.unet.config.prediction_type)
89
+
90
+ # keep VAE in fp32 for stability; UNet follows model dtype
91
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
92
+ # self.vae.requires_grad_(False).to(device, dtype=torch.float32)
93
+ # unet_dtype = self.lm_head.weight.dtype if hasattr(self.lm_head, "weight") else torch.float32
94
+ # self.unet.to(device=device, dtype=unet_dtype)
95
+ # if getattr(self.unet.config, "in_channels", 4) != 8:
96
+ # self.unet.register_to_config(in_channels=8)
97
+ # with torch.no_grad():
98
+ # old = self.unet.conv_in
99
+ # new = nn.Conv2d(8, old.out_channels, old.kernel_size, old.stride, old.padding, bias=(old.bias is not None))
100
+ # new.weight.zero_()
101
+ # new.weight[:, :4] = old.weight
102
+ # if old.bias is not None:
103
+ # new.bias.copy_(old.bias)
104
+ # self.unet.conv_in = new
105
+
106
+ # # Always keep VAE frozen for stability
107
+ # self.vae.requires_grad_(False)
108
+ # if not getattr(config, "unfreeze_unet", False):
109
+ # self.unet.requires_grad_(False)
110
+
111
+ # if getattr(config, "unfreeze_unet", False):
112
+ # # 1) optionally train conv_in (8->channels) to adapt to 8-ch input
113
+ # if getattr(config, "tune_unet_conv_in", False):
114
+ # for p in self.unet.conv_in.parameters():
115
+ # p.requires_grad_(True)
116
+ # else:
117
+ # for p in self.unet.conv_in.parameters():
118
+ # p.requires_grad_(False)
119
+
120
+ # # 2) (Optional) attach LoRA to UNet attention blocks
121
+ # if getattr(config, "unet_lora_r", 0) > 0:
122
+ # try:
123
+ # from diffusers.utils import USE_PEFT_BACKEND
124
+ # from peft import LoraConfig, get_peft_model
125
+ # except Exception as e:
126
+ # raise RuntimeError("Install peft to use UNet LoRA") from e
127
+
128
+ # lora_cfg = LoraConfig(r=config.unet_lora_r, lora_alpha=2*config.unet_lora_r,
129
+ # lora_dropout=0.0, bias="none",
130
+ # target_modules=["to_q", "to_k", "to_v", "to_out.0"])
131
+ # self.unet.enable_gradient_checkpointing() # memory
132
+ # self.unet = get_peft_model(self.unet, lora_cfg)
133
+
134
+ def init_diffusion(self, device=None, dtype=None):
135
+ if self._diffusers_ready:
136
+ return
137
+
138
+ p2p_path = self._p2p_path
139
+
140
+ # Avoid meta-tensor path: load on CPU memory
141
+ self.scheduler = diffusers.DDPMScheduler.from_pretrained(p2p_path, subfolder="scheduler")
142
+ self.vae = diffusers.AutoencoderKL.from_pretrained(
143
+ p2p_path, subfolder="vae", torch_dtype=torch.float32
144
+ )
145
+ self.unet = diffusers.UNet2DConditionModel.from_pretrained(
146
+ p2p_path, subfolder="unet"
147
+ )
148
+
149
+ # Align prediction type if needed
150
+ if hasattr(self.scheduler.config, "prediction_type") and hasattr(self.unet.config, "prediction_type"):
151
+ self.scheduler.register_to_config(prediction_type=self.unet.config.prediction_type)
152
+
153
+ # Ensure 8-channel input for concat(lat_noisy, lat_inp)
154
+ if getattr(self.unet.config, "in_channels", 4) != 8:
155
+ old = self.unet.conv_in
156
+ new = torch.nn.Conv2d(8, old.out_channels, old.kernel_size, old.stride, old.padding, bias=(old.bias is not None))
157
+ with torch.no_grad():
158
+ new.weight.zero_()
159
+ new.weight[:, :4] = old.weight
160
+ if old.bias is not None: new.bias.copy_(old.bias)
161
+ self.unet.conv_in = new
162
+
163
+ # Freeze VAE always
164
+ self.vae.requires_grad_(False)
165
+
166
+ # Respect your config flags for UNet trainability
167
+ if not getattr(self.config, "unfreeze_unet", False):
168
+ self.unet.requires_grad_(False)
169
+ else:
170
+ # Optional UNet conv_in finetune
171
+ tune = getattr(self.config, "tune_unet_conv_in", False)
172
+ for p in self.unet.conv_in.parameters():
173
+ p.requires_grad_(tune)
174
+
175
+ # Optional UNet LoRA
176
+ if getattr(self.config, "unet_lora_r", 0) > 0:
177
+ from peft import LoraConfig, get_peft_model
178
+ lcfg = LoraConfig(
179
+ r=self.config.unet_lora_r, lora_alpha=2*self.config.unet_lora_r,
180
+ lora_dropout=0.0, bias="none",
181
+ target_modules=["to_q", "to_k", "to_v", "to_out.0"]
182
+ )
183
+ self.unet.enable_gradient_checkpointing()
184
+ self.unet = get_peft_model(self.unet, lcfg)
185
+
186
+ # Move to device/dtype now (not during meta init)
187
+ if device is None:
188
+ device = next(self.parameters()).device
189
+ if dtype is None:
190
+ dtype = next(self.parameters()).dtype
191
+ self.vae.to(device, dtype=torch.float32) # keep VAE fp32
192
+ self.unet.to(device, dtype=dtype)
193
+
194
+ self._diffusers_ready = True
195
+
196
+
197
+ def get_model(self):
198
+ return self.model
199
+
200
+ def forward(
201
+ self,
202
+ input_ids: torch.LongTensor = None,
203
+ attention_mask: Optional[torch.Tensor] = None,
204
+ position_ids: Optional[torch.LongTensor] = None,
205
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
206
+ inputs_embeds: Optional[torch.FloatTensor] = None,
207
+ labels: Optional[torch.LongTensor] = None,
208
+ use_cache: Optional[bool] = None,
209
+ output_attentions: Optional[bool] = None,
210
+ output_hidden_states: Optional[bool] = None,
211
+ images: Optional[torch.FloatTensor] = None,
212
+ image_sizes: Optional[List[List[int]]] = None,
213
+ return_dict: Optional[bool] = None,
214
+ p2p_inp: Optional[torch.FloatTensor] = None,
215
+ p2p_ans: Optional[torch.FloatTensor] = None,
216
+ **kwargs,
217
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
218
+
219
+ if return_dict is None:
220
+ return_dict = True
221
+
222
+ # keep a copy because prepare_* may null input_ids
223
+ orig_input_ids = input_ids
224
+
225
+ # Prepare multimodal embeds if needed
226
+ if inputs_embeds is None:
227
+ (
228
+ input_ids,
229
+ position_ids,
230
+ attention_mask,
231
+ past_key_values,
232
+ inputs_embeds,
233
+ labels,
234
+ ) = self.prepare_inputs_labels_for_multimodal(
235
+ input_ids,
236
+ position_ids,
237
+ attention_mask,
238
+ past_key_values,
239
+ labels,
240
+ images,
241
+ image_sizes,
242
+ )
243
+
244
+ # Forward through base model; allow extra kwargs (e.g., cache_position)
245
+ try:
246
+ outputs = self.model(
247
+ input_ids=None,
248
+ attention_mask=attention_mask,
249
+ position_ids=position_ids,
250
+ past_key_values=past_key_values,
251
+ inputs_embeds=inputs_embeds,
252
+ use_cache=use_cache,
253
+ output_attentions=output_attentions,
254
+ output_hidden_states=True,
255
+ return_dict=True,
256
+ **kwargs,
257
+ )
258
+ except TypeError:
259
+ safe_kwargs = dict(kwargs)
260
+ for k in ['cache_position', 'cache_positions']:
261
+ if k in safe_kwargs:
262
+ safe_kwargs.pop(k)
263
+ outputs = self.model(
264
+ input_ids=None,
265
+ attention_mask=attention_mask,
266
+ position_ids=position_ids,
267
+ past_key_values=past_key_values,
268
+ inputs_embeds=inputs_embeds,
269
+ use_cache=use_cache,
270
+ output_attentions=output_attentions,
271
+ output_hidden_states=True,
272
+ return_dict=True,
273
+ **safe_kwargs,
274
+ )
275
+
276
+ hidden_states = outputs[0] # [B, T, H]
277
+ logits = self.lm_head(hidden_states)
278
+
279
+ # --- Losses ---
280
+ loss = None
281
+ loss_ce = None
282
+ loss_edit = None
283
+
284
+ if labels is not None:
285
+ shift_logits = logits[..., :-1, :].contiguous()
286
+ shift_labels = labels[..., 1:].contiguous()
287
+ loss_ce = nn.CrossEntropyLoss()(
288
+ shift_logits.view(-1, shift_logits.size(-1)),
289
+ shift_labels.view(-1)
290
+ )
291
+ loss = loss_ce
292
+
293
+ # -------------------- Diffusion / edit loss --------------------
294
+ if (labels is not None) and (p2p_inp is not None) and (p2p_ans is not None):
295
+ # use whichever token ids we have
296
+ ids_for_scan = input_ids if input_ids is not None else orig_input_ids
297
+ if ids_for_scan is None:
298
+ if self.training and not getattr(self, "_warned_no_ids_for_edit", False):
299
+ print("[warn] input_ids are None; skipping loss_edit this step.")
300
+ self._warned_no_ids_for_edit = True
301
+ return RGBTOutput(
302
+ loss=loss, logits=logits,
303
+ past_key_values=outputs.past_key_values,
304
+ hidden_states=outputs.hidden_states,
305
+ attentions=outputs.attentions,
306
+ loss_ce=loss_ce, loss_edit=None,
307
+ )
308
+
309
+ # edit token ids
310
+ edit_ids = getattr(self, "edit_token_ids", None) or getattr(self.config, "edit_token_ids", None)
311
+ if edit_ids is None:
312
+ raise RuntimeError("edit_token_ids not set.")
313
+ edit_ids = torch.as_tensor(edit_ids, device=hidden_states.device, dtype=ids_for_scan.dtype)
314
+
315
+
316
+ # Find contiguous [IMG0..7] span and slice hidden states
317
+ B, T, H = hidden_states.size()
318
+ llm_slices = []
319
+ for i in range(B):
320
+ ids_i = ids_for_scan[i]
321
+ pos = None
322
+ for s in range(0, ids_i.numel() - 7):
323
+ if torch.equal(ids_i[s:s+8], edit_ids):
324
+ pos = s
325
+ break
326
+ if pos is None:
327
+ pos = max(0, ids_i.numel() - 9)
328
+ llm_slices.append(hidden_states[i, pos:pos+8, :].unsqueeze(0))
329
+ llm_slice = torch.cat(llm_slices, dim=0) # [B, 8, H]
330
+
331
+ # Corresponding token embeddings for [IMG0..7]
332
+ with torch.no_grad():
333
+ emb_tbl = self.get_model().embed_tokens.weight # [V, H]
334
+ edit_embs = emb_tbl[edit_ids] # [8, H]
335
+ edit_embs = edit_embs.unsqueeze(0).repeat(B, 1, 1) # [B, 8, H]
336
+
337
+ # Map to UNet text-cond
338
+ hid_edit = self.edit_head(llm_slice, edit_embs) # [B, 77, 768]
339
+
340
+ # Lazy init diffusers on the right device/dtype
341
+ if not self._diffusers_ready:
342
+ self.init_diffusion(device=hidden_states.device, dtype=hidden_states.dtype)
343
+ dev = hidden_states.device
344
+ llm_dtype = hidden_states.dtype
345
+ self.vae.to(dev, dtype=torch.float32)
346
+ self.unet.to(dev, dtype=hidden_states.dtype)
347
+
348
+ with torch.autocast(device_type="cuda", enabled=False):
349
+ p2p_ans_fp32 = p2p_ans.to(device=dev, dtype=torch.float32)
350
+ p2p_inp_fp32 = p2p_inp.to(device=dev, dtype=torch.float32)
351
+
352
+ lat_ans = self.vae.encode(p2p_ans_fp32).latent_dist.sample() * self.vae.config.scaling_factor
353
+ lat_inp = self.vae.encode(p2p_inp_fp32).latent_dist.mode() * self.vae.config.scaling_factor
354
+
355
+ # Now match UNet/LLM dtype for the diffusion path
356
+ lat_ans = lat_ans.to(dtype=llm_dtype)
357
+ lat_inp = lat_inp.to(dtype=llm_dtype)
358
+
359
+ noise = torch.randn_like(lat_ans) # same dtype as lat_ans (bf16 now)
360
+ ts = torch.randint(0, self.scheduler.config.num_train_timesteps, (lat_ans.size(0),), device=dev)
361
+ lat_noisy = self.scheduler.add_noise(lat_ans, noise, ts)
362
+
363
+
364
+
365
+ # mild dropouts
366
+ prob = torch.rand(B, device=dev)
367
+ hid_null = self.edit_head(torch.zeros_like(llm_slice), edit_embs)
368
+ cond = torch.where((prob < 0.10).view(B, 1, 1), hid_null, hid_edit)
369
+ lat_inp = torch.where(((prob >= 0.05) & (prob < 0.15)).view(B, 1, 1, 1), torch.zeros_like(lat_inp), lat_inp)
370
+
371
+ # UNet predicts noise
372
+ unet_in = torch.cat([lat_noisy, lat_inp], dim=1) # 8-ch
373
+ pred = self.unet(unet_in, ts, cond).sample
374
+
375
+ loss_edit = F.mse_loss(pred, noise, reduction="mean")
376
+ w = getattr(self.config, "edit_loss_weight", 0.5)
377
+ loss = (loss if loss is not None else 0.0) + w * loss_edit
378
+ # ---------------------------------------------------------------
379
+
380
+ return RGBTOutput(
381
+ loss=loss,
382
+ logits=logits,
383
+ past_key_values=outputs.past_key_values,
384
+ hidden_states=outputs.hidden_states,
385
+ attentions=outputs.attentions,
386
+ loss_ce=loss_ce,
387
+ loss_edit=loss_edit,
388
+ )
389
+
390
+
391
+
392
+
393
+
394
+ @torch.no_grad()
395
+ def generate(
396
+ self,
397
+ inputs: Optional[torch.Tensor] = None,
398
+ images: Optional[torch.Tensor] = None,
399
+ image_sizes: Optional[torch.Tensor] = None,
400
+ **kwargs,
401
+ ) -> Union[GenerateOutput, torch.LongTensor]:
402
+ position_ids = kwargs.pop("position_ids", None)
403
+ attention_mask = kwargs.pop("attention_mask", None)
404
+ if "inputs_embeds" in kwargs:
405
+ raise NotImplementedError("`inputs_embeds` is not supported")
406
+
407
+ if images is not None:
408
+ (
409
+ inputs,
410
+ position_ids,
411
+ attention_mask,
412
+ _,
413
+ inputs_embeds,
414
+ _
415
+ ) = self.prepare_inputs_labels_for_multimodal(
416
+ inputs,
417
+ position_ids,
418
+ attention_mask,
419
+ None,
420
+ None,
421
+ images,
422
+ image_sizes=image_sizes
423
+ )
424
+ else:
425
+ inputs_embeds = self.get_model().embed_tokens(inputs)
426
+
427
+ return super().generate(
428
+ position_ids=position_ids,
429
+ attention_mask=attention_mask,
430
+ inputs_embeds=inputs_embeds,
431
+ **kwargs
432
+ )
433
+
434
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None,
435
+ inputs_embeds=None, **kwargs):
436
+ images = kwargs.pop("images", None)
437
+ image_sizes = kwargs.pop("image_sizes", None)
438
+ inputs = super().prepare_inputs_for_generation(
439
+ input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs
440
+ )
441
+ if images is not None:
442
+ inputs['images'] = images
443
+ if image_sizes is not None:
444
+ inputs['image_sizes'] = image_sizes
445
+ return inputs
446
+
447
+
448
+ class EditMapper(nn.Module):
449
+ def __init__(self, d_llm=4096, n_edit=8, d_model=512, nhead=4, nlayers=4, d_ff=2048, d_out=768):
450
+ super().__init__()
451
+ self.llm2hid = nn.Linear(d_llm, d_model)
452
+ self.query = nn.Parameter(torch.randn(1, 77, d_model))
453
+ self.mapper = nn.Transformer(
454
+ batch_first=True, norm_first=True,
455
+ d_model=d_model, nhead=nhead,
456
+ num_encoder_layers=nlayers, num_decoder_layers=nlayers,
457
+ dim_feedforward=d_ff, dropout=0.0
458
+ )
459
+ self.hid2feat = nn.Linear(d_model, d_out)
460
+
461
+ def forward(self, llm_slice, edit_token_embs):
462
+ # llm_slice: [B, 8, d_llm]; edit_token_embs: [B, 8, d_llm]
463
+ hid = self.llm2hid(llm_slice + edit_token_embs)
464
+ q = self.query.repeat(hid.size(0), 1, 1)
465
+ hid = self.mapper(hid, q)
466
+ return self.hid2feat(hid) # [B, 77, 768] for SD text-cond size
467
+
468
+
469
+ AutoConfig.register("llava_llama", LlavaConfig)
470
+ AutoModelForCausalLM.register(LlavaConfig, LlavaLlamaForCausalLM)
llava/model/language_model/llava_mistral.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Haotian Liu
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from typing import List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ from torch.nn import CrossEntropyLoss
21
+
22
+ from transformers import AutoConfig, AutoModelForCausalLM, \
23
+ MistralConfig, MistralModel, MistralForCausalLM
24
+
25
+ from transformers.modeling_outputs import CausalLMOutputWithPast
26
+ from transformers.generation.utils import GenerateOutput
27
+
28
+ from ..llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
29
+
30
+
31
+ class LlavaMistralConfig(MistralConfig):
32
+ model_type = "llava_mistral"
33
+
34
+
35
+ class LlavaMistralModel(LlavaMetaModel, MistralModel):
36
+ config_class = LlavaMistralConfig
37
+
38
+ def __init__(self, config: MistralConfig):
39
+ super(LlavaMistralModel, self).__init__(config)
40
+
41
+
42
+ class LlavaMistralForCausalLM(MistralForCausalLM, LlavaMetaForCausalLM):
43
+ config_class = LlavaMistralConfig
44
+
45
+ def __init__(self, config):
46
+ super(MistralForCausalLM, self).__init__(config)
47
+ self.model = LlavaMistralModel(config)
48
+
49
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
50
+
51
+ # Initialize weights and apply final processing
52
+ self.post_init()
53
+
54
+ def get_model(self):
55
+ return self.model
56
+
57
+ def forward(
58
+ self,
59
+ input_ids: torch.LongTensor = None,
60
+ attention_mask: Optional[torch.Tensor] = None,
61
+ position_ids: Optional[torch.LongTensor] = None,
62
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
63
+ inputs_embeds: Optional[torch.FloatTensor] = None,
64
+ labels: Optional[torch.LongTensor] = None,
65
+ use_cache: Optional[bool] = None,
66
+ output_attentions: Optional[bool] = None,
67
+ output_hidden_states: Optional[bool] = None,
68
+ images: Optional[torch.FloatTensor] = None,
69
+ image_sizes: Optional[List[List[int]]] = None,
70
+ return_dict: Optional[bool] = None,
71
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
72
+
73
+ if inputs_embeds is None:
74
+ (
75
+ input_ids,
76
+ position_ids,
77
+ attention_mask,
78
+ past_key_values,
79
+ inputs_embeds,
80
+ labels
81
+ ) = self.prepare_inputs_labels_for_multimodal(
82
+ input_ids,
83
+ position_ids,
84
+ attention_mask,
85
+ past_key_values,
86
+ labels,
87
+ images,
88
+ image_sizes
89
+ )
90
+
91
+ return super().forward(
92
+ input_ids=input_ids,
93
+ attention_mask=attention_mask,
94
+ position_ids=position_ids,
95
+ past_key_values=past_key_values,
96
+ inputs_embeds=inputs_embeds,
97
+ labels=labels,
98
+ use_cache=use_cache,
99
+ output_attentions=output_attentions,
100
+ output_hidden_states=output_hidden_states,
101
+ return_dict=return_dict
102
+ )
103
+
104
+ @torch.no_grad()
105
+ def generate(
106
+ self,
107
+ inputs: Optional[torch.Tensor] = None,
108
+ images: Optional[torch.Tensor] = None,
109
+ image_sizes: Optional[torch.Tensor] = None,
110
+ **kwargs,
111
+ ) -> Union[GenerateOutput, torch.LongTensor]:
112
+ position_ids = kwargs.pop("position_ids", None)
113
+ attention_mask = kwargs.pop("attention_mask", None)
114
+ if "inputs_embeds" in kwargs:
115
+ raise NotImplementedError("`inputs_embeds` is not supported")
116
+
117
+ if images is not None:
118
+ (
119
+ inputs,
120
+ position_ids,
121
+ attention_mask,
122
+ _,
123
+ inputs_embeds,
124
+ _
125
+ ) = self.prepare_inputs_labels_for_multimodal(
126
+ inputs,
127
+ position_ids,
128
+ attention_mask,
129
+ None,
130
+ None,
131
+ images,
132
+ image_sizes=image_sizes
133
+ )
134
+ else:
135
+ inputs_embeds = self.get_model().embed_tokens(inputs)
136
+
137
+ return super().generate(
138
+ position_ids=position_ids,
139
+ attention_mask=attention_mask,
140
+ inputs_embeds=inputs_embeds,
141
+ **kwargs
142
+ )
143
+
144
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None,
145
+ inputs_embeds=None, **kwargs):
146
+ images = kwargs.pop("images", None)
147
+ image_sizes = kwargs.pop("image_sizes", None)
148
+ inputs = super().prepare_inputs_for_generation(
149
+ input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs
150
+ )
151
+ if images is not None:
152
+ inputs['images'] = images
153
+ if image_sizes is not None:
154
+ inputs['image_sizes'] = image_sizes
155
+ return inputs
156
+
157
+ AutoConfig.register("llava_mistral", LlavaMistralConfig)
158
+ AutoModelForCausalLM.register(LlavaMistralConfig, LlavaMistralForCausalLM)
llava/model/language_model/llava_mpt.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Haotian Liu
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from typing import Optional, Tuple
17
+
18
+ import torch
19
+
20
+ from transformers import AutoConfig, AutoModelForCausalLM, \
21
+ MptConfig, MptForCausalLM, MptModel
22
+ from llava.model.llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
23
+
24
+
25
+ class LlavaMptConfig(MptConfig):
26
+ model_type = "llava_mpt"
27
+
28
+
29
+ class LlavaMptModel(LlavaMetaModel, MptModel):
30
+ config_class = LlavaMptConfig
31
+
32
+ def __init__(self, config: MptConfig):
33
+ config.hidden_size = config.d_model
34
+ super(LlavaMptModel, self).__init__(config)
35
+
36
+ def embed_tokens(self, x):
37
+ return self.wte(x)
38
+
39
+
40
+ class LlavaMptForCausalLM(MptForCausalLM, LlavaMetaForCausalLM):
41
+ config_class = LlavaMptConfig
42
+ supports_gradient_checkpointing = True
43
+
44
+ def __init__(self, config):
45
+ super(MptForCausalLM, self).__init__(config)
46
+
47
+ self.transformer = LlavaMptModel(config)
48
+ self.lm_head = torch.nn.Linear(config.hidden_size, config.vocab_size, bias=False)
49
+
50
+ # Initialize weights and apply final processing
51
+ self.post_init()
52
+
53
+ def get_model(self):
54
+ return self.transformer
55
+
56
+ def _set_gradient_checkpointing(self, module, value=False):
57
+ if isinstance(module, LlavaMptModel):
58
+ module.gradient_checkpointing = value
59
+
60
+ def forward(
61
+ self,
62
+ input_ids: Optional[torch.LongTensor] = None,
63
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
64
+ attention_mask: Optional[torch.Tensor] = None,
65
+ inputs_embeds: Optional[torch.Tensor] = None,
66
+ labels: Optional[torch.Tensor] = None,
67
+ use_cache: Optional[bool] = None,
68
+ output_attentions: Optional[bool] = None,
69
+ output_hidden_states: Optional[bool] = None,
70
+ return_dict: Optional[bool] = None,
71
+ images=None):
72
+
73
+ input_ids, attention_mask, past_key_values, inputs_embeds, labels = self.prepare_inputs_labels_for_multimodal(input_ids, attention_mask, past_key_values, labels, images)
74
+
75
+ return super().forward(
76
+ input_ids,
77
+ past_key_values=past_key_values,
78
+ attention_mask=attention_mask,
79
+ inputs_embeds=inputs_embeds,
80
+ labels=labels,
81
+ use_cache=use_cache,
82
+ output_attentions=output_attentions,
83
+ output_hidden_states=output_hidden_states,
84
+ return_dict=return_dict,
85
+ )
86
+
87
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
88
+ images = kwargs.pop("images", None)
89
+ _inputs = super().prepare_inputs_for_generation(
90
+ input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs
91
+ )
92
+ _inputs['images'] = images
93
+ return _inputs
94
+
95
+
96
+ AutoConfig.register("llava_mpt", LlavaMptConfig)
97
+ AutoModelForCausalLM.register(LlavaMptConfig, LlavaMptForCausalLM)
llava/model/llava_arch.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Haotian Liu
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from abc import ABC, abstractmethod
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+
21
+ from .multimodal_encoder.builder import build_vision_tower
22
+ from .multimodal_projector.builder import build_vision_projector
23
+
24
+ from llava.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
25
+
26
+ from llava.mm_utils import get_anyres_image_grid_shape
27
+
28
+
29
+ class LlavaMetaModel:
30
+
31
+ def __init__(self, config):
32
+ super(LlavaMetaModel, self).__init__(config)
33
+
34
+ if hasattr(config, "mm_vision_tower"):
35
+ self.vision_tower = build_vision_tower(config, delay_load=True)
36
+ self.mm_projector = build_vision_projector(config)
37
+
38
+ if 'unpad' in getattr(config, 'mm_patch_merge_type', ''):
39
+ self.image_newline = nn.Parameter(
40
+ torch.empty(config.hidden_size, dtype=self.dtype)
41
+ )
42
+
43
+ def get_vision_tower(self):
44
+ vision_tower = getattr(self, 'vision_tower', None)
45
+ if type(vision_tower) is list:
46
+ vision_tower = vision_tower[0]
47
+ return vision_tower
48
+
49
+ def initialize_vision_modules(self, model_args, fsdp=None):
50
+ vision_tower = model_args.vision_tower
51
+ mm_vision_select_layer = model_args.mm_vision_select_layer
52
+ mm_vision_select_feature = model_args.mm_vision_select_feature
53
+ pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter
54
+ mm_patch_merge_type = model_args.mm_patch_merge_type
55
+
56
+ self.config.mm_vision_tower = vision_tower
57
+
58
+ if self.get_vision_tower() is None:
59
+ vision_tower = build_vision_tower(model_args)
60
+
61
+ if fsdp is not None and len(fsdp) > 0:
62
+ self.vision_tower = [vision_tower]
63
+ else:
64
+ self.vision_tower = vision_tower
65
+ else:
66
+ if fsdp is not None and len(fsdp) > 0:
67
+ vision_tower = self.vision_tower[0]
68
+ else:
69
+ vision_tower = self.vision_tower
70
+ vision_tower.load_model()
71
+
72
+ self.config.use_mm_proj = True
73
+ self.config.mm_projector_type = getattr(model_args, 'mm_projector_type', 'linear')
74
+ self.config.mm_hidden_size = vision_tower.hidden_size
75
+ self.config.mm_vision_select_layer = mm_vision_select_layer
76
+ self.config.mm_vision_select_feature = mm_vision_select_feature
77
+ self.config.mm_patch_merge_type = mm_patch_merge_type
78
+
79
+ if getattr(self, 'mm_projector', None) is None:
80
+ self.mm_projector = build_vision_projector(self.config)
81
+
82
+ if 'unpad' in mm_patch_merge_type:
83
+ embed_std = 1 / torch.sqrt(torch.tensor(self.config.hidden_size, dtype=self.dtype))
84
+ self.image_newline = nn.Parameter(
85
+ torch.randn(self.config.hidden_size, dtype=self.dtype) * embed_std
86
+ )
87
+ else:
88
+ # In case it is frozen by LoRA
89
+ for p in self.mm_projector.parameters():
90
+ p.requires_grad = True
91
+
92
+ if pretrain_mm_mlp_adapter is not None:
93
+ mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location='cpu')
94
+ def get_w(weights, keyword):
95
+ return {k.split(keyword + '.')[1]: v for k, v in weights.items() if keyword in k}
96
+
97
+ self.mm_projector.load_state_dict(get_w(mm_projector_weights, 'mm_projector'))
98
+
99
+
100
+ def unpad_image(tensor, original_size):
101
+ """
102
+ Unpads a PyTorch tensor of a padded and resized image.
103
+
104
+ Args:
105
+ tensor (torch.Tensor): The image tensor, assumed to be in CxHxW format.
106
+ original_size (tuple): The original size of PIL image (width, height).
107
+
108
+ Returns:
109
+ torch.Tensor: The unpadded image tensor.
110
+ """
111
+ original_width, original_height = original_size
112
+ current_height, current_width = tensor.shape[1:]
113
+
114
+ original_aspect_ratio = original_width / original_height
115
+ current_aspect_ratio = current_width / current_height
116
+
117
+ if original_aspect_ratio > current_aspect_ratio:
118
+ scale_factor = current_width / original_width
119
+ new_height = int(original_height * scale_factor)
120
+ padding = (current_height - new_height) // 2
121
+ unpadded_tensor = tensor[:, padding:current_height - padding, :]
122
+ else:
123
+ scale_factor = current_height / original_height
124
+ new_width = int(original_width * scale_factor)
125
+ padding = (current_width - new_width) // 2
126
+ unpadded_tensor = tensor[:, :, padding:current_width - padding]
127
+
128
+ return unpadded_tensor
129
+
130
+
131
+ class LlavaMetaForCausalLM(ABC):
132
+
133
+ @abstractmethod
134
+ def get_model(self):
135
+ pass
136
+
137
+ def get_vision_tower(self):
138
+ return self.get_model().get_vision_tower()
139
+
140
+ # def encode_images(self, images):
141
+ # image_features = self.get_model().get_vision_tower()(images)
142
+ # image_features = self.get_model().mm_projector(image_features)
143
+ # return image_features
144
+
145
+
146
+ def encode_images(self, images):
147
+ vision = self.get_vision_tower()
148
+ device = next(vision.parameters()).device
149
+ vision_dtype = next(vision.parameters()).dtype
150
+ proj_dtype = next(self.get_model().mm_projector.parameters()).dtype
151
+
152
+ # ensure inputs match the vision tower
153
+ if isinstance(images, (list, tuple)):
154
+ images = [img.to(device=device, dtype=vision_dtype) for img in images]
155
+ images = torch.stack(images, dim=0) if images[0].ndim == 3 else torch.cat(images, dim=0)
156
+ else:
157
+ images = images.to(device=device, dtype=vision_dtype)
158
+
159
+ # forward the vision tower (often returns float32 even if weights are fp16)
160
+ image_features = vision(images)
161
+
162
+ # ensure projector input matches projector weights
163
+ if image_features.dtype != proj_dtype:
164
+ image_features = image_features.to(dtype=proj_dtype)
165
+
166
+ # now safe to apply mm_projector
167
+ image_features = self.get_model().mm_projector(image_features)
168
+ return image_features
169
+
170
+ def prepare_inputs_labels_for_multimodal(
171
+ self, input_ids, position_ids, attention_mask, past_key_values, labels,
172
+ images, image_sizes=None
173
+ ):
174
+ vision_tower = self.get_vision_tower()
175
+ if vision_tower is None or images is None or input_ids.shape[1] == 1:
176
+ return input_ids, position_ids, attention_mask, past_key_values, None, labels
177
+
178
+ if type(images) is list or images.ndim == 5:
179
+ if type(images) is list:
180
+ images = [x.unsqueeze(0) if x.ndim == 3 else x for x in images]
181
+ concat_images = torch.cat([image for image in images], dim=0)
182
+ image_features = self.encode_images(concat_images)
183
+ split_sizes = [image.shape[0] for image in images]
184
+ image_features = torch.split(image_features, split_sizes, dim=0)
185
+ mm_patch_merge_type = getattr(self.config, 'mm_patch_merge_type', 'flat')
186
+ image_aspect_ratio = getattr(self.config, 'image_aspect_ratio', 'square')
187
+ if mm_patch_merge_type == 'flat':
188
+ image_features = [x.flatten(0, 1) for x in image_features]
189
+ elif mm_patch_merge_type.startswith('spatial'):
190
+ new_image_features = []
191
+ for image_idx, image_feature in enumerate(image_features):
192
+ if image_feature.shape[0] > 1:
193
+ base_image_feature = image_feature[0]
194
+ image_feature = image_feature[1:]
195
+ height = width = self.get_vision_tower().num_patches_per_side
196
+ assert height * width == base_image_feature.shape[0]
197
+ if image_aspect_ratio == 'anyres':
198
+ num_patch_width, num_patch_height = get_anyres_image_grid_shape(image_sizes[image_idx], self.config.image_grid_pinpoints, self.get_vision_tower().config.image_size)
199
+ image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
200
+ else:
201
+ raise NotImplementedError
202
+ if 'unpad' in mm_patch_merge_type:
203
+ image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
204
+ image_feature = image_feature.flatten(1, 2).flatten(2, 3)
205
+ image_feature = unpad_image(image_feature, image_sizes[image_idx])
206
+ image_feature = torch.cat((
207
+ image_feature,
208
+ self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device)
209
+ ), dim=-1)
210
+ image_feature = image_feature.flatten(1, 2).transpose(0, 1)
211
+ else:
212
+ image_feature = image_feature.permute(0, 2, 1, 3, 4).contiguous()
213
+ image_feature = image_feature.flatten(0, 3)
214
+ image_feature = torch.cat((base_image_feature, image_feature), dim=0)
215
+ else:
216
+ image_feature = image_feature[0]
217
+ if 'unpad' in mm_patch_merge_type:
218
+ image_feature = torch.cat((
219
+ image_feature,
220
+ self.model.image_newline[None].to(image_feature.device)
221
+ ), dim=0)
222
+ new_image_features.append(image_feature)
223
+ image_features = new_image_features
224
+ else:
225
+ raise ValueError(f"Unexpected mm_patch_merge_type: {self.config.mm_patch_merge_type}")
226
+ else:
227
+ image_features = self.encode_images(images)
228
+
229
+ # TODO: image start / end is not implemented here to support pretraining.
230
+ if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False):
231
+ raise NotImplementedError
232
+
233
+ # Let's just add dummy tensors if they do not exist,
234
+ # it is a headache to deal with None all the time.
235
+ # But it is not ideal, and if you have a better idea,
236
+ # please open an issue / submit a PR, thanks.
237
+ _labels = labels
238
+ _position_ids = position_ids
239
+ _attention_mask = attention_mask
240
+ if attention_mask is None:
241
+ attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
242
+ else:
243
+ attention_mask = attention_mask.bool()
244
+ if position_ids is None:
245
+ position_ids = torch.arange(0, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
246
+ if labels is None:
247
+ labels = torch.full_like(input_ids, IGNORE_INDEX)
248
+
249
+ # remove the padding using attention_mask -- FIXME
250
+ _input_ids = input_ids
251
+ input_ids = [cur_input_ids[cur_attention_mask] for cur_input_ids, cur_attention_mask in zip(input_ids, attention_mask)]
252
+ labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)]
253
+
254
+ new_input_embeds = []
255
+ new_labels = []
256
+ cur_image_idx = 0
257
+ for batch_idx, cur_input_ids in enumerate(input_ids):
258
+ num_images = (cur_input_ids == IMAGE_TOKEN_INDEX).sum()
259
+ if num_images == 0:
260
+ cur_image_features = image_features[cur_image_idx]
261
+ cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids)
262
+ cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0]], dim=0)
263
+ new_input_embeds.append(cur_input_embeds)
264
+ new_labels.append(labels[batch_idx])
265
+ cur_image_idx += 1
266
+ continue
267
+
268
+ image_token_indices = [-1] + torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist() + [cur_input_ids.shape[0]]
269
+ cur_input_ids_noim = []
270
+ cur_labels = labels[batch_idx]
271
+ cur_labels_noim = []
272
+ for i in range(len(image_token_indices) - 1):
273
+ cur_input_ids_noim.append(cur_input_ids[image_token_indices[i]+1:image_token_indices[i+1]])
274
+ cur_labels_noim.append(cur_labels[image_token_indices[i]+1:image_token_indices[i+1]])
275
+ split_sizes = [x.shape[0] for x in cur_labels_noim]
276
+ cur_input_embeds = self.get_model().embed_tokens(torch.cat(cur_input_ids_noim))
277
+ cur_input_embeds_no_im = torch.split(cur_input_embeds, split_sizes, dim=0)
278
+ cur_new_input_embeds = []
279
+ cur_new_labels = []
280
+
281
+ for i in range(num_images + 1):
282
+ cur_new_input_embeds.append(cur_input_embeds_no_im[i])
283
+ cur_new_labels.append(cur_labels_noim[i])
284
+ if i < num_images:
285
+ cur_image_features = image_features[cur_image_idx]
286
+ cur_image_idx += 1
287
+ cur_new_input_embeds.append(cur_image_features)
288
+ cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=cur_labels.device, dtype=cur_labels.dtype))
289
+
290
+ cur_new_input_embeds = [x.to(self.device) for x in cur_new_input_embeds]
291
+
292
+ cur_new_input_embeds = torch.cat(cur_new_input_embeds)
293
+ cur_new_labels = torch.cat(cur_new_labels)
294
+
295
+ new_input_embeds.append(cur_new_input_embeds)
296
+ new_labels.append(cur_new_labels)
297
+
298
+ # Truncate sequences to max length as image embeddings can make the sequence longer
299
+ tokenizer_model_max_length = getattr(self.config, 'tokenizer_model_max_length', None)
300
+ if tokenizer_model_max_length is not None:
301
+ new_input_embeds = [x[:tokenizer_model_max_length] for x in new_input_embeds]
302
+ new_labels = [x[:tokenizer_model_max_length] for x in new_labels]
303
+
304
+ # Combine them
305
+ max_len = max(x.shape[0] for x in new_input_embeds)
306
+ batch_size = len(new_input_embeds)
307
+
308
+ new_input_embeds_padded = []
309
+ new_labels_padded = torch.full((batch_size, max_len), IGNORE_INDEX, dtype=new_labels[0].dtype, device=new_labels[0].device)
310
+ attention_mask = torch.zeros((batch_size, max_len), dtype=attention_mask.dtype, device=attention_mask.device)
311
+ position_ids = torch.zeros((batch_size, max_len), dtype=position_ids.dtype, device=position_ids.device)
312
+
313
+ for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)):
314
+ cur_len = cur_new_embed.shape[0]
315
+ if getattr(self.config, 'tokenizer_padding_side', 'right') == "left":
316
+ new_input_embeds_padded.append(torch.cat((
317
+ torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device),
318
+ cur_new_embed
319
+ ), dim=0))
320
+ if cur_len > 0:
321
+ new_labels_padded[i, -cur_len:] = cur_new_labels
322
+ attention_mask[i, -cur_len:] = True
323
+ position_ids[i, -cur_len:] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
324
+ else:
325
+ new_input_embeds_padded.append(torch.cat((
326
+ cur_new_embed,
327
+ torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)
328
+ ), dim=0))
329
+ if cur_len > 0:
330
+ new_labels_padded[i, :cur_len] = cur_new_labels
331
+ attention_mask[i, :cur_len] = True
332
+ position_ids[i, :cur_len] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
333
+
334
+ new_input_embeds = torch.stack(new_input_embeds_padded, dim=0)
335
+
336
+ if _labels is None:
337
+ new_labels = None
338
+ else:
339
+ new_labels = new_labels_padded
340
+
341
+ if _attention_mask is None:
342
+ attention_mask = None
343
+ else:
344
+ attention_mask = attention_mask.to(dtype=_attention_mask.dtype)
345
+
346
+ if _position_ids is None:
347
+ position_ids = None
348
+
349
+ return None, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels
350
+
351
+ def initialize_vision_tokenizer(self, model_args, tokenizer):
352
+ if model_args.mm_use_im_patch_token:
353
+ tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
354
+ self.resize_token_embeddings(len(tokenizer))
355
+
356
+ if model_args.mm_use_im_start_end:
357
+ num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
358
+ self.resize_token_embeddings(len(tokenizer))
359
+
360
+ if num_new_tokens > 0:
361
+ input_embeddings = self.get_input_embeddings().weight.data
362
+ output_embeddings = self.get_output_embeddings().weight.data
363
+
364
+ input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(
365
+ dim=0, keepdim=True)
366
+ output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(
367
+ dim=0, keepdim=True)
368
+
369
+ input_embeddings[-num_new_tokens:] = input_embeddings_avg
370
+ output_embeddings[-num_new_tokens:] = output_embeddings_avg
371
+
372
+ if model_args.tune_mm_mlp_adapter:
373
+ for p in self.get_input_embeddings().parameters():
374
+ p.requires_grad = True
375
+ for p in self.get_output_embeddings().parameters():
376
+ p.requires_grad = False
377
+
378
+ if model_args.pretrain_mm_mlp_adapter:
379
+ mm_projector_weights = torch.load(model_args.pretrain_mm_mlp_adapter, map_location='cpu')
380
+ embed_tokens_weight = mm_projector_weights['model.embed_tokens.weight']
381
+ assert num_new_tokens == 2
382
+ if input_embeddings.shape == embed_tokens_weight.shape:
383
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight[-num_new_tokens:]
384
+ elif embed_tokens_weight.shape[0] == num_new_tokens:
385
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight
386
+ else:
387
+ raise ValueError(f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}.")
388
+ elif model_args.mm_use_im_patch_token:
389
+ if model_args.tune_mm_mlp_adapter:
390
+ for p in self.get_input_embeddings().parameters():
391
+ p.requires_grad = False
392
+ for p in self.get_output_embeddings().parameters():
393
+ p.requires_grad = False
llava/model/make_delta.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Usage:
3
+ python3 -m llava.model.make_delta --base ~/model_weights/llama-7b --target ~/model_weights/llava-7b --delta ~/model_weights/llava-7b-delta --hub-repo-id liuhaotian/llava-7b-delta
4
+ """
5
+ import argparse
6
+
7
+ import torch
8
+ from tqdm import tqdm
9
+ from transformers import AutoTokenizer, AutoModelForCausalLM
10
+ from llava.model.utils import auto_upgrade
11
+
12
+
13
+ def make_delta(base_model_path, target_model_path, delta_path, hub_repo_id):
14
+ print("Loading base model")
15
+ base = AutoModelForCausalLM.from_pretrained(
16
+ base_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
17
+
18
+ print("Loading target model")
19
+ auto_upgrade(target_model_path)
20
+ target = AutoModelForCausalLM.from_pretrained(target_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
21
+
22
+ print("Calculating delta")
23
+ for name, param in tqdm(target.state_dict().items(), desc="Calculating delta"):
24
+ if name not in base.state_dict():
25
+ assert name in ['model.mm_projector.weight', 'model.mm_projector.bias'], f'{name} not in base model'
26
+ continue
27
+ if param.data.shape == base.state_dict()[name].shape:
28
+ param.data -= base.state_dict()[name]
29
+ else:
30
+ assert name in ['model.embed_tokens.weight', 'lm_head.weight'], f'{name} dimension mismatch: {param.data.shape} vs {base.state_dict()[name].shape}'
31
+ bparam = base.state_dict()[name]
32
+ param.data[:bparam.shape[0], :bparam.shape[1]] -= bparam
33
+
34
+ print("Saving delta")
35
+ if hub_repo_id:
36
+ kwargs = {"push_to_hub": True, "repo_id": hub_repo_id}
37
+ else:
38
+ kwargs = {}
39
+ target.save_pretrained(delta_path, **kwargs)
40
+ target_tokenizer = AutoTokenizer.from_pretrained(target_model_path)
41
+ target_tokenizer.save_pretrained(delta_path, **kwargs)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ parser = argparse.ArgumentParser()
46
+ parser.add_argument("--base-model-path", type=str, required=True)
47
+ parser.add_argument("--target-model-path", type=str, required=True)
48
+ parser.add_argument("--delta-path", type=str, required=True)
49
+ parser.add_argument("--hub-repo-id", type=str, default=None)
50
+ args = parser.parse_args()
51
+
52
+ make_delta(args.base_model_path, args.target_model_path, args.delta_path, args.hub_repo_id)
llava/model/multimodal_encoder/builder.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from .clip_encoder import CLIPVisionTower, CLIPVisionTowerS2
3
+
4
+
5
+ def build_vision_tower(vision_tower_cfg, **kwargs):
6
+ vision_tower = getattr(vision_tower_cfg, 'mm_vision_tower', getattr(vision_tower_cfg, 'vision_tower', None))
7
+ is_absolute_path_exists = os.path.exists(vision_tower)
8
+ use_s2 = getattr(vision_tower_cfg, 's2', False)
9
+ if is_absolute_path_exists or vision_tower.startswith("openai") or vision_tower.startswith("laion") or "ShareGPT4V" in vision_tower:
10
+ if use_s2:
11
+ return CLIPVisionTowerS2(vision_tower, args=vision_tower_cfg, **kwargs)
12
+ else:
13
+ return CLIPVisionTower(vision_tower, args=vision_tower_cfg, **kwargs)
14
+
15
+ raise ValueError(f'Unknown vision tower: {vision_tower}')
llava/model/multimodal_encoder/clip_encoder.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from transformers import CLIPVisionModel, CLIPImageProcessor, CLIPVisionConfig
5
+
6
+
7
+ class CLIPVisionTower(nn.Module):
8
+ def __init__(self, vision_tower, args, delay_load=False):
9
+ super().__init__()
10
+
11
+ self.is_loaded = False
12
+
13
+ self.vision_tower_name = vision_tower
14
+ self.select_layer = args.mm_vision_select_layer
15
+ self.select_feature = getattr(args, 'mm_vision_select_feature', 'patch')
16
+
17
+ if not delay_load:
18
+ self.load_model()
19
+ elif getattr(args, 'unfreeze_mm_vision_tower', False):
20
+ self.load_model()
21
+ else:
22
+ self.cfg_only = CLIPVisionConfig.from_pretrained(self.vision_tower_name)
23
+
24
+ def load_model(self, device_map=None):
25
+ if self.is_loaded:
26
+ print('{} is already loaded, `load_model` called again, skipping.'.format(self.vision_tower_name))
27
+ return
28
+
29
+ self.image_processor = CLIPImageProcessor.from_pretrained(self.vision_tower_name)
30
+ self.vision_tower = CLIPVisionModel.from_pretrained(self.vision_tower_name, device_map=device_map)
31
+ self.vision_tower.requires_grad_(False)
32
+
33
+ self.is_loaded = True
34
+
35
+ def feature_select(self, image_forward_outs):
36
+ image_features = image_forward_outs.hidden_states[self.select_layer]
37
+ if self.select_feature == 'patch':
38
+ image_features = image_features[:, 1:]
39
+ elif self.select_feature == 'cls_patch':
40
+ image_features = image_features
41
+ else:
42
+ raise ValueError(f'Unexpected select feature: {self.select_feature}')
43
+ return image_features
44
+
45
+ @torch.no_grad()
46
+ def forward(self, images):
47
+ if type(images) is list:
48
+ image_features = []
49
+ for image in images:
50
+ image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
51
+ image_feature = self.feature_select(image_forward_out).to(image.dtype)
52
+ image_features.append(image_feature)
53
+ else:
54
+ image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
55
+ image_features = self.feature_select(image_forward_outs).to(images.dtype)
56
+
57
+ return image_features
58
+
59
+ @property
60
+ def dummy_feature(self):
61
+ return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
62
+
63
+ @property
64
+ def dtype(self):
65
+ return self.vision_tower.dtype
66
+
67
+ @property
68
+ def device(self):
69
+ return self.vision_tower.device
70
+
71
+ @property
72
+ def config(self):
73
+ if self.is_loaded:
74
+ return self.vision_tower.config
75
+ else:
76
+ return self.cfg_only
77
+
78
+ @property
79
+ def hidden_size(self):
80
+ return self.config.hidden_size
81
+
82
+ @property
83
+ def num_patches_per_side(self):
84
+ return self.config.image_size // self.config.patch_size
85
+
86
+ @property
87
+ def num_patches(self):
88
+ return (self.config.image_size // self.config.patch_size) ** 2
89
+
90
+
91
+
92
+ class CLIPVisionTowerS2(CLIPVisionTower):
93
+ def __init__(self, vision_tower, args, delay_load=False):
94
+ super().__init__(vision_tower, args, delay_load)
95
+
96
+ self.s2_scales = getattr(args, 's2_scales', '336,672,1008')
97
+ self.s2_scales = list(map(int, self.s2_scales.split(',')))
98
+ self.s2_scales.sort()
99
+ self.s2_split_size = self.s2_scales[0]
100
+ self.s2_image_size = self.s2_scales[-1]
101
+
102
+ try:
103
+ from s2wrapper import forward as multiscale_forward
104
+ except ImportError:
105
+ raise ImportError('Package s2wrapper not found! Please install by running: \npip install git+https://github.com/bfshi/scaling_on_scales.git')
106
+ self.multiscale_forward = multiscale_forward
107
+
108
+ # change resize/crop size in preprocessing to the largest image size in s2_scale
109
+ if not delay_load or getattr(args, 'unfreeze_mm_vision_tower', False):
110
+ self.image_processor.size['shortest_edge'] = self.s2_image_size
111
+ self.image_processor.crop_size['height'] = self.image_processor.crop_size['width'] = self.s2_image_size
112
+
113
+ def load_model(self, device_map=None):
114
+ if self.is_loaded:
115
+ print('{} is already loaded, `load_model` called again, skipping.'.format(self.vision_tower_name))
116
+ return
117
+
118
+ self.image_processor = CLIPImageProcessor.from_pretrained(self.vision_tower_name)
119
+ self.vision_tower = CLIPVisionModel.from_pretrained(self.vision_tower_name, device_map=device_map)
120
+ self.vision_tower.requires_grad_(False)
121
+
122
+ self.image_processor.size['shortest_edge'] = self.s2_image_size
123
+ self.image_processor.crop_size['height'] = self.image_processor.crop_size['width'] = self.s2_image_size
124
+
125
+ self.is_loaded = True
126
+
127
+ @torch.no_grad()
128
+ def forward_feature(self, images):
129
+ image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
130
+ image_features = self.feature_select(image_forward_outs).to(images.dtype)
131
+ return image_features
132
+
133
+ @torch.no_grad()
134
+ def forward(self, images):
135
+ if type(images) is list:
136
+ image_features = []
137
+ for image in images:
138
+ image_feature = self.multiscale_forward(self.forward_feature, image.unsqueeze(0), img_sizes=self.s2_scales, max_split_size=self.s2_split_size)
139
+ image_features.append(image_feature)
140
+ else:
141
+ image_features = self.multiscale_forward(self.forward_feature, images, img_sizes=self.s2_scales, max_split_size=self.s2_split_size)
142
+
143
+ return image_features
144
+
145
+ @property
146
+ def hidden_size(self):
147
+ return self.config.hidden_size * len(self.s2_scales)
llava/model/multimodal_projector/builder.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import re
4
+
5
+
6
+ class IdentityMap(nn.Module):
7
+ def __init__(self):
8
+ super().__init__()
9
+
10
+ def forward(self, x, *args, **kwargs):
11
+ return x
12
+
13
+ @property
14
+ def config(self):
15
+ return {"mm_projector_type": 'identity'}
16
+
17
+
18
+ class SimpleResBlock(nn.Module):
19
+ def __init__(self, channels):
20
+ super().__init__()
21
+ self.pre_norm = nn.LayerNorm(channels)
22
+
23
+ self.proj = nn.Sequential(
24
+ nn.Linear(channels, channels),
25
+ nn.GELU(),
26
+ nn.Linear(channels, channels)
27
+ )
28
+ def forward(self, x):
29
+ x = self.pre_norm(x)
30
+ return x + self.proj(x)
31
+
32
+
33
+ def build_vision_projector(config, delay_load=False, **kwargs):
34
+ projector_type = getattr(config, 'mm_projector_type', 'linear')
35
+
36
+ if projector_type == 'linear':
37
+ return nn.Linear(config.mm_hidden_size, config.hidden_size)
38
+
39
+ mlp_gelu_match = re.match(r'^mlp(\d+)x_gelu$', projector_type)
40
+ if mlp_gelu_match:
41
+ mlp_depth = int(mlp_gelu_match.group(1))
42
+ modules = [nn.Linear(config.mm_hidden_size, config.hidden_size)]
43
+ for _ in range(1, mlp_depth):
44
+ modules.append(nn.GELU())
45
+ modules.append(nn.Linear(config.hidden_size, config.hidden_size))
46
+ return nn.Sequential(*modules)
47
+
48
+ if projector_type == 'identity':
49
+ return IdentityMap()
50
+
51
+ raise ValueError(f'Unknown projector type: {projector_type}')
llava/model/unet_processors.py ADDED
@@ -0,0 +1,460 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Custom attention processors for UNet with decoupled dual-branch conditioning.
3
+
4
+ Implements:
5
+ 1. Decoupled cross-attention: separate text and VLM conditioning branches
6
+ 2. LoRA on q/k/v projections for efficient fine-tuning
7
+ 3. Learnable gating to balance text vs VLM contributions
8
+ """
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+ from typing import Optional
14
+
15
+
16
+ class LoRALinear(nn.Module):
17
+ """
18
+ LoRA-augmented linear layer.
19
+
20
+ y = Wx + (α/r) * (B @ A) @ x
21
+
22
+ Where:
23
+ - W: frozen base weights
24
+ - A: (r, in_features) - low-rank down projection
25
+ - B: (out_features, r) - low-rank up projection
26
+ - r: rank
27
+ - α: scaling factor (usually = r)
28
+ """
29
+
30
+ def __init__(self, base_layer: nn.Linear, r: int = 8, lora_alpha: int = 8,
31
+ lora_dropout: float = 0.05):
32
+ super().__init__()
33
+
34
+ self.base_layer = base_layer
35
+ self.r = r
36
+ self.lora_alpha = lora_alpha
37
+ self.scaling = lora_alpha / r
38
+
39
+ in_features = base_layer.in_features
40
+ out_features = base_layer.out_features
41
+
42
+ # LoRA matrices
43
+ self.lora_A = nn.Parameter(torch.zeros(r, in_features))
44
+ self.lora_B = nn.Parameter(torch.zeros(out_features, r))
45
+
46
+ # Optional dropout
47
+ self.lora_dropout = nn.Dropout(lora_dropout) if lora_dropout > 0 else nn.Identity()
48
+
49
+ # Initialize
50
+ nn.init.kaiming_uniform_(self.lora_A, a=5**0.5) # Same as nn.Linear
51
+ nn.init.zeros_(self.lora_B) # Start with zero contribution
52
+
53
+ # Freeze base layer
54
+ self.base_layer.weight.requires_grad = False
55
+ if self.base_layer.bias is not None:
56
+ self.base_layer.bias.requires_grad = False
57
+
58
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
59
+ """
60
+ Args:
61
+ x: (B, L, in_features)
62
+
63
+ Returns:
64
+ y: (B, L, out_features)
65
+ """
66
+ # Base output (frozen)
67
+ base_out = self.base_layer(x)
68
+
69
+ # LoRA output (trainable)
70
+ # x @ A^T -> (B, L, r)
71
+ lora_out = self.lora_dropout(x)
72
+ lora_out = F.linear(lora_out, self.lora_A) # (B, L, r)
73
+ lora_out = F.linear(lora_out, self.lora_B) # (B, L, out_features)
74
+ lora_out = lora_out * self.scaling
75
+
76
+ return base_out + lora_out
77
+
78
+ def extra_repr(self) -> str:
79
+ return f'r={self.r}, alpha={self.lora_alpha}, scaling={self.scaling:.4f}, dropout={self.lora_dropout}'
80
+
81
+
82
+ class DecoupledDualBranchAttnProcessor(nn.Module):
83
+ """
84
+ Decoupled dual-branch cross-attention processor for UNet.
85
+
86
+ Computes cross-attention with two separate conditioning sources:
87
+ - Branch A: Text conditioning (from CLIP text encoder, standard IP2P)
88
+ - Branch B: VLM conditioning (from LLaVA EditMapper, our addition)
89
+
90
+ Output = γ_text * Attn(q, k_text, v_text) + γ_vlm * Attn(q, k_vlm, v_vlm)
91
+
92
+ With LoRA on q, k, v projections for efficient training.
93
+
94
+ Args:
95
+ hidden_size: UNet hidden size at this layer
96
+ cross_attention_dim: Conditioning dimension (768 for SD1.5 CLIP)
97
+ num_heads: Number of attention heads
98
+ head_dim: Dimension per head (hidden_size // num_heads)
99
+ lora_r: LoRA rank (default: 8)
100
+ lora_alpha: LoRA scaling (default: 8)
101
+ lora_dropout: LoRA dropout (default: 0.05)
102
+ init_gamma_text: Initial weight for text branch (default: 0.3)
103
+ init_gamma_vlm: Initial weight for VLM branch (default: 0.7)
104
+ """
105
+
106
+ def __init__(
107
+ self,
108
+ hidden_size: int,
109
+ cross_attention_dim: int = 768,
110
+ num_heads: int = 8,
111
+ head_dim: int = 64,
112
+ lora_r: int = 8,
113
+ lora_alpha: int = 8,
114
+ lora_dropout: float = 0.05,
115
+ init_gamma_text: float = 0.3,
116
+ init_gamma_vlm: float = 0.7,
117
+ # LoRA placement toggles
118
+ lora_on_query: bool = False,
119
+ lora_on_text: bool = False, # keep CLIP text branch frozen by default
120
+ lora_on_vlm: bool = True,
121
+ ):
122
+ super().__init__()
123
+
124
+ self.hidden_size = hidden_size
125
+ self.cross_attention_dim = cross_attention_dim
126
+ self.num_heads = num_heads
127
+ self.head_dim = head_dim
128
+ self.scale = head_dim ** -0.5
129
+
130
+ # Query projection (from UNet features)
131
+ # Shape: hidden_size -> (num_heads * head_dim)
132
+ self.to_q = nn.Linear(hidden_size, num_heads * head_dim, bias=False)
133
+
134
+ # Text branch: k/v projections with LoRA
135
+ self.to_k_text = nn.Linear(cross_attention_dim, num_heads * head_dim, bias=False)
136
+ self.to_v_text = nn.Linear(cross_attention_dim, num_heads * head_dim, bias=False)
137
+
138
+ # VLM branch: k/v projections with LoRA
139
+ self.to_k_vlm = nn.Linear(cross_attention_dim, num_heads * head_dim, bias=False)
140
+ self.to_v_vlm = nn.Linear(cross_attention_dim, num_heads * head_dim, bias=False)
141
+
142
+ # Wrap with LoRA selectively (trainable deltas)
143
+ if lora_on_query:
144
+ self.to_q = LoRALinear(self.to_q, r=lora_r, lora_alpha=lora_alpha, lora_dropout=lora_dropout)
145
+ else:
146
+ # Freeze query to mimic IP-Adapter style (no trainable deltas on q)
147
+ self.to_q.weight.requires_grad = False
148
+ if getattr(self.to_q, 'bias', None) is not None:
149
+ self.to_q.bias.requires_grad = False
150
+
151
+ if lora_on_text:
152
+ self.to_k_text = LoRALinear(self.to_k_text, r=lora_r, lora_alpha=lora_alpha, lora_dropout=lora_dropout)
153
+ self.to_v_text = LoRALinear(self.to_v_text, r=lora_r, lora_alpha=lora_alpha, lora_dropout=lora_dropout)
154
+ else:
155
+ # Freeze text-branch projections entirely (respecting frozen CLIP guidance)
156
+ self.to_k_text.weight.requires_grad = False
157
+ self.to_v_text.weight.requires_grad = False
158
+ if getattr(self.to_k_text, 'bias', None) is not None:
159
+ self.to_k_text.bias.requires_grad = False
160
+ if getattr(self.to_v_text, 'bias', None) is not None:
161
+ self.to_v_text.bias.requires_grad = False
162
+
163
+ if lora_on_vlm:
164
+ self.to_k_vlm = LoRALinear(self.to_k_vlm, r=lora_r, lora_alpha=lora_alpha, lora_dropout=lora_dropout)
165
+ self.to_v_vlm = LoRALinear(self.to_v_vlm, r=lora_r, lora_alpha=lora_alpha, lora_dropout=lora_dropout)
166
+ else:
167
+ # Optionally freeze VLM branch if desired
168
+ self.to_k_vlm.weight.requires_grad = False
169
+ self.to_v_vlm.weight.requires_grad = False
170
+ if getattr(self.to_k_vlm, 'bias', None) is not None:
171
+ self.to_k_vlm.bias.requires_grad = False
172
+ if getattr(self.to_v_vlm, 'bias', None) is not None:
173
+ self.to_v_vlm.bias.requires_grad = False
174
+
175
+ # Output projection (shared)
176
+ # NOTE: This should NOT be frozen - it needs to allow gradient flow!
177
+ # We'll copy weights from original UNet but keep it trainable for gradients
178
+ self.to_out = nn.Linear(num_heads * head_dim, hidden_size, bias=True)
179
+
180
+ # Learnable gates for balancing branches
181
+ self.gamma_text = nn.Parameter(torch.tensor(init_gamma_text, dtype=torch.float32))
182
+ self.gamma_vlm = nn.Parameter(torch.tensor(init_gamma_vlm, dtype=torch.float32))
183
+
184
+ def forward(
185
+ self,
186
+ attn, # diffusers Attention module (unused; kept for API compatibility)
187
+ hidden_states: torch.Tensor,
188
+ encoder_hidden_states=None, # text encoder states
189
+ attention_mask: Optional[torch.Tensor] = None,
190
+ temb: Optional[torch.Tensor] = None,
191
+ **kwargs,
192
+ ) -> torch.Tensor:
193
+ """
194
+ Args:
195
+ hidden_states: (B, L_spatial, hidden_size) - UNet features
196
+ encoder_hidden_states: Dict {'text': ..., 'vlm': ...} OR tensor (for compatibility)
197
+ encoder_hidden_states_text: (B, L_text, 768) - Text conditioning (if not in dict)
198
+ encoder_hidden_states_vlm: (B, L_vlm, 768) - VLM conditioning (if not in dict)
199
+ attention_mask: Optional attention mask
200
+
201
+ Returns:
202
+ output: (B, L_spatial, hidden_size) - Updated UNet features
203
+ """
204
+ # Encoder hidden states: text; VLM fetched via context
205
+ encoder_hidden_states_text = encoder_hidden_states
206
+ encoder_hidden_states_vlm = None
207
+ try:
208
+ from .ip_context import current_ip_tokens
209
+ encoder_hidden_states_vlm = current_ip_tokens()
210
+ except Exception:
211
+ pass
212
+
213
+ batch_size, seq_len, _ = hidden_states.shape
214
+
215
+ # Query from UNet features
216
+ q = self.to_q(hidden_states) # (B, L_spatial, num_heads * head_dim)
217
+
218
+ # Reshape for multi-head attention: (B, L, num_heads * head_dim) -> (B, num_heads, L, head_dim)
219
+ q = q.view(batch_size, seq_len, self.num_heads, self.head_dim)
220
+ q = q.transpose(1, 2) # (B, num_heads, L_spatial, head_dim)
221
+
222
+ # Build text K/V
223
+ k_text = self.to_k_text(encoder_hidden_states_text)
224
+ v_text = self.to_v_text(encoder_hidden_states_text)
225
+ k_text = k_text.view(batch_size, -1, self.num_heads, self.head_dim).transpose(1, 2)
226
+ v_text = v_text.view(batch_size, -1, self.num_heads, self.head_dim).transpose(1, 2)
227
+
228
+ # Optionally fetch VLM tokens from context if not provided
229
+ if encoder_hidden_states_vlm is None:
230
+ try:
231
+ from .ip_context import current_ip_tokens
232
+ encoder_hidden_states_vlm = current_ip_tokens()
233
+ except Exception:
234
+ encoder_hidden_states_vlm = None
235
+
236
+ # Concatenate text and (optionally gated) VLM K/V, then do ONE attention/softmax
237
+ if encoder_hidden_states_vlm is not None:
238
+ k_vlm = self.to_k_vlm(encoder_hidden_states_vlm)
239
+ v_vlm = self.to_v_vlm(encoder_hidden_states_vlm)
240
+ k_vlm = k_vlm.view(batch_size, -1, self.num_heads, self.head_dim).transpose(1, 2)
241
+ v_vlm = v_vlm.view(batch_size, -1, self.num_heads, self.head_dim).transpose(1, 2)
242
+
243
+ # Scale gates to match dtype
244
+ scale_t = self.gamma_text
245
+ scale_v = self.gamma_vlm
246
+ scale_t = scale_t.to(k_text.dtype)
247
+ scale_v = scale_v.to(k_text.dtype)
248
+ # Apply gating on VLM branch before concat (text kept at 1.0 or scale_t for symmetry)
249
+ k_cat = torch.cat([k_text * scale_t, k_vlm * scale_v], dim=2) # concat on sequence dim (after heads axis)
250
+ v_cat = torch.cat([v_text * scale_t, v_vlm * scale_v], dim=2)
251
+ else:
252
+ scale_t = self.gamma_text.to(k_text.dtype)
253
+ k_cat = k_text * scale_t
254
+ v_cat = v_text * scale_t
255
+
256
+ # Attention over concatenated keys/values
257
+ attn_scores = torch.matmul(q, k_cat.transpose(-1, -2)) * self.scale # (B, heads, Lq, Lk)
258
+ if attention_mask is not None:
259
+ # Expect mask broadcastable to attn_scores
260
+ attn_scores = attn_scores + attention_mask
261
+ attn_probs = F.softmax(attn_scores, dim=-1)
262
+ output = torch.matmul(attn_probs, v_cat) # (B, heads, L_spatial, head_dim)
263
+
264
+ # Reshape back: (B, heads, L_spatial, head_dim) -> (B, L_spatial, heads * head_dim)
265
+ output = output.transpose(1, 2).contiguous()
266
+ output = output.view(batch_size, seq_len, self.num_heads * self.head_dim)
267
+
268
+ # Output projection (trainable for gradient flow; exclude from optimizer to keep frozen)
269
+ output = self.to_out(output)
270
+
271
+ return output
272
+
273
+ def get_lora_parameters(self):
274
+ """Get all LoRA parameters for optimizer"""
275
+ params = []
276
+ for module in [self.to_q, self.to_k_text, self.to_v_text, self.to_k_vlm, self.to_v_vlm]:
277
+ if isinstance(module, LoRALinear):
278
+ params.extend([module.lora_A, module.lora_B])
279
+ return params
280
+
281
+ def get_gate_parameters(self):
282
+ """Get gate parameters for optimizer"""
283
+ return [self.gamma_text, self.gamma_vlm]
284
+
285
+ def freeze_output_projection(self):
286
+ """
287
+ Freeze output projection to prevent training (but allow gradient flow).
288
+ Call this AFTER setting up optimizer if you don't want to train to_out.
289
+ """
290
+ # Note: We keep requires_grad=True for gradient flow, but exclude from optimizer
291
+ pass
292
+
293
+ def get_output_projection_parameters(self):
294
+ """Get output projection parameters (if you want to train them)"""
295
+ return [self.to_out.weight, self.to_out.bias]
296
+
297
+
298
+ def inject_decoupled_processors(
299
+ unet,
300
+ target_blocks: list = None,
301
+ lora_r: int = 8,
302
+ lora_alpha: int = 8,
303
+ lora_dropout: float = 0.05,
304
+ init_gamma_text: float = 0.3,
305
+ init_gamma_vlm: float = 0.7,
306
+ # LoRA placement toggles (default: keep CLIP text branch frozen)
307
+ lora_on_query: bool = True,
308
+ lora_on_text: bool = False,
309
+ lora_on_vlm: bool = True,
310
+ ):
311
+ """
312
+ Inject decoupled dual-branch attention processors into UNet.
313
+
314
+ Args:
315
+ unet: UNet2DConditionModel from diffusers
316
+ target_blocks: List of block names to modify (default: ["down_blocks.2", "mid_block"])
317
+ lora_r: LoRA rank
318
+ lora_alpha: LoRA alpha
319
+ lora_dropout: LoRA dropout
320
+ init_gamma_text: Initial text branch weight
321
+ init_gamma_vlm: Initial VLM branch weight
322
+
323
+ Returns:
324
+ processor_dict: Dict of {name: processor} for the modified processors
325
+ """
326
+ if target_blocks is None:
327
+ #target_blocks = ["down_blocks.2", "mid_block"]
328
+ target_blocks = [n for n in unet.attn_processors.keys() if "attn2" in n]
329
+ print(f"\nInjecting decoupled processors into UNet:")
330
+ print(f" Target blocks: {target_blocks}")
331
+ print(f" LoRA: r={lora_r}, alpha={lora_alpha}, dropout={lora_dropout}")
332
+ print(f" Gates: gamma_text={init_gamma_text}, gamma_vlm={init_gamma_vlm}")
333
+ print(f" LoRA toggles -> query:{lora_on_query}, text:{lora_on_text}, vlm:{lora_on_vlm}")
334
+
335
+ # Get current attention processors
336
+ attn_procs = unet.attn_processors
337
+
338
+ # Start with ALL existing processors (critical for diffusers!)
339
+ processor_dict = dict(attn_procs)
340
+ inject_count = 0
341
+
342
+ for name, processor in attn_procs.items():
343
+ # Check if this is a cross-attention processor (attn2) in a target block
344
+ is_cross_attn = 'attn2' in name
345
+ is_target_block = any(block in name for block in target_blocks)
346
+
347
+ if is_cross_attn and is_target_block:
348
+ # Get the actual attention module to extract parameters
349
+ # Parse name to get module (e.g., "down_blocks.2.attentions.0.transformer_blocks.0.attn2")
350
+ module = unet
351
+ for part in name.split('.')[:-1]: # Remove '.processor'
352
+ if part.isdigit():
353
+ module = module[int(part)]
354
+ else:
355
+ module = getattr(module, part)
356
+
357
+ # Get attention parameters
358
+ hidden_size = module.to_q.out_features
359
+ cross_attention_dim = module.to_k.in_features
360
+ num_heads = module.heads
361
+ head_dim = hidden_size // num_heads
362
+
363
+ # Create custom processor
364
+ custom_proc = DecoupledDualBranchAttnProcessor(
365
+ hidden_size=hidden_size,
366
+ cross_attention_dim=cross_attention_dim,
367
+ num_heads=num_heads,
368
+ head_dim=head_dim,
369
+ lora_r=lora_r,
370
+ lora_alpha=lora_alpha,
371
+ lora_dropout=lora_dropout,
372
+ init_gamma_text=init_gamma_text,
373
+ init_gamma_vlm=init_gamma_vlm,
374
+ lora_on_query=lora_on_query,
375
+ lora_on_text=lora_on_text,
376
+ lora_on_vlm=lora_on_vlm,
377
+ )
378
+
379
+ # Copy base weights from original module (handle both Linear and LoRALinear cases)
380
+ with torch.no_grad():
381
+ # to_q
382
+ src_to_q = module.to_q
383
+ dst_to_q = custom_proc.to_q.base_layer if isinstance(custom_proc.to_q, LoRALinear) else custom_proc.to_q
384
+ dst_to_q.weight.copy_(src_to_q.weight)
385
+ if getattr(src_to_q, 'bias', None) is not None and getattr(dst_to_q, 'bias', None) is not None:
386
+ dst_to_q.bias.copy_(src_to_q.bias)
387
+
388
+ # text k/v
389
+ src_to_k = module.to_k
390
+ src_to_v = module.to_v
391
+ dst_to_k_text = custom_proc.to_k_text.base_layer if isinstance(custom_proc.to_k_text, LoRALinear) else custom_proc.to_k_text
392
+ dst_to_v_text = custom_proc.to_v_text.base_layer if isinstance(custom_proc.to_v_text, LoRALinear) else custom_proc.to_v_text
393
+ dst_to_k_text.weight.copy_(src_to_k.weight)
394
+ dst_to_v_text.weight.copy_(src_to_v.weight)
395
+ if getattr(src_to_k, 'bias', None) is not None and getattr(dst_to_k_text, 'bias', None) is not None:
396
+ dst_to_k_text.bias.copy_(src_to_k.bias)
397
+ if getattr(src_to_v, 'bias', None) is not None and getattr(dst_to_v_text, 'bias', None) is not None:
398
+ dst_to_v_text.bias.copy_(src_to_v.bias)
399
+
400
+ # vlm k/v (init from text k/v for symmetry)
401
+ dst_to_k_vlm = custom_proc.to_k_vlm.base_layer if isinstance(custom_proc.to_k_vlm, LoRALinear) else custom_proc.to_k_vlm
402
+ dst_to_v_vlm = custom_proc.to_v_vlm.base_layer if isinstance(custom_proc.to_v_vlm, LoRALinear) else custom_proc.to_v_vlm
403
+ dst_to_k_vlm.weight.copy_(src_to_k.weight)
404
+ dst_to_v_vlm.weight.copy_(src_to_v.weight)
405
+ if getattr(src_to_k, 'bias', None) is not None and getattr(dst_to_k_vlm, 'bias', None) is not None:
406
+ dst_to_k_vlm.bias.copy_(src_to_k.bias)
407
+ if getattr(src_to_v, 'bias', None) is not None and getattr(dst_to_v_vlm, 'bias', None) is not None:
408
+ dst_to_v_vlm.bias.copy_(src_to_v.bias)
409
+
410
+ # to_out (module.to_out is Sequential[Linear, ...])
411
+ dst_to_out = custom_proc.to_out
412
+ src_to_out = module.to_out[0]
413
+ dst_to_out.weight.copy_(src_to_out.weight)
414
+ if src_to_out.bias is not None and dst_to_out.bias is not None:
415
+ dst_to_out.bias.copy_(src_to_out.bias)
416
+
417
+ # Ensure processor module matches UNet device/dtype
418
+ proc_device = module.to_q.weight.device
419
+ proc_dtype = module.to_q.weight.dtype
420
+ custom_proc.to(device=proc_device, dtype=proc_dtype)
421
+
422
+ processor_dict[name] = custom_proc
423
+ inject_count += 1
424
+ print(f" ✓ Injected at {name}")
425
+
426
+ print(f"\n Total injected: {inject_count} processors")
427
+ print(f" Total processors in dict: {len(processor_dict)} (diffusers expects all)")
428
+
429
+ return processor_dict
430
+
431
+
432
+ def get_trainable_unet_params(processor_dict):
433
+ """
434
+ Get all trainable parameters from decoupled processors.
435
+
436
+ Args:
437
+ processor_dict: Dict from inject_decoupled_processors()
438
+
439
+ Returns:
440
+ lora_params: List of LoRA parameters
441
+ gate_params: List of gate parameters
442
+ """
443
+ lora_params = []
444
+ gate_params = []
445
+
446
+ for name, proc in processor_dict.items():
447
+ if isinstance(proc, DecoupledDualBranchAttnProcessor):
448
+ lora_params.extend(proc.get_lora_parameters())
449
+ gate_params.extend(proc.get_gate_parameters())
450
+
451
+ print(f"\nTrainable UNet parameters:")
452
+ print(f" LoRA parameters: {len(lora_params)}")
453
+ print(f" Gate parameters: {len(gate_params)}")
454
+
455
+ total_lora = sum(p.numel() for p in lora_params)
456
+ total_gate = sum(p.numel() for p in gate_params)
457
+ print(f" Total trainable: {total_lora + total_gate:,} parameters")
458
+
459
+ return lora_params, gate_params
460
+
llava/model/utils.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoConfig
2
+
3
+
4
+ def auto_upgrade(config):
5
+ cfg = AutoConfig.from_pretrained(config)
6
+ if 'llava' in config and 'llava' not in cfg.model_type:
7
+ assert cfg.model_type == 'llama'
8
+ print("You are using newer LLaVA code base, while the checkpoint of v0 is from older code base.")
9
+ print("You must upgrade the checkpoint to the new code base (this can be done automatically).")
10
+ confirm = input("Please confirm that you want to upgrade the checkpoint. [Y/N]")
11
+ if confirm.lower() in ["y", "yes"]:
12
+ print("Upgrading checkpoint...")
13
+ assert len(cfg.architectures) == 1
14
+ setattr(cfg.__class__, "model_type", "llava")
15
+ cfg.architectures[0] = 'LlavaLlamaForCausalLM'
16
+ cfg.save_pretrained(config)
17
+ print("Checkpoint upgraded.")
18
+ else:
19
+ print("Checkpoint upgrade aborted.")
20
+ exit(1)
llava/model/vlm_attention_processor_v3.py ADDED
@@ -0,0 +1,435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ VLM-Adapter Attention Processor v3 for InstructPix2Pix
3
+
4
+ Port-back from soft-prompt implementation with proven stability improvements:
5
+ 1. Out-of-band VLM token passing (doesn't touch encoder_hidden_states)
6
+ 2. Single-softmax concat attention (no double softmax + add)
7
+ 3. Learnable gate with logit-bias (pre-softmax)
8
+ 4. Token dropout (train-time regularization)
9
+ 5. RMSNorm on VLM only + 1/sqrt(K) scaling
10
+ 6. Xavier initialization with 0.8 scaling
11
+ 7. Per-timestep ELLA support
12
+ 8. Decoupled cross-attention (IP-Adapter style)
13
+ 9. Proper dtype handling and logging
14
+
15
+ Key difference from soft-prompt: VLM tokens passed out-of-band, not concatenated to encoder_hidden_states.
16
+ This keeps the CLIP text branch pristine while still using proven conditioning techniques.
17
+ """
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+ import torch.nn.functional as F
22
+ import math
23
+
24
+
25
+ class RMSNorm(nn.Module):
26
+ """Root Mean Square Layer Normalization"""
27
+ def __init__(self, dim, eps=1e-6):
28
+ super().__init__()
29
+ self.weight = nn.Parameter(torch.ones(dim))
30
+ self.eps = eps
31
+
32
+ def forward(self, x):
33
+ rms = x.pow(2).mean(dim=-1, keepdim=True).add(self.eps).sqrt()
34
+ return (x / rms) * self.weight
35
+
36
+
37
+ class AttnProcessor(nn.Module):
38
+ """Default processor for self-attention (attn1) - no changes"""
39
+ def __init__(self):
40
+ super().__init__()
41
+
42
+ def __call__(
43
+ self,
44
+ attn,
45
+ hidden_states,
46
+ encoder_hidden_states=None,
47
+ attention_mask=None,
48
+ temb=None,
49
+ ):
50
+ target_dtype = attn.to_q.weight.dtype
51
+ residual = hidden_states
52
+ hidden_states = hidden_states.to(dtype=target_dtype)
53
+
54
+ if attn.spatial_norm is not None:
55
+ hidden_states = attn.spatial_norm(hidden_states, temb)
56
+
57
+ input_ndim = hidden_states.ndim
58
+
59
+ if input_ndim == 4:
60
+ batch_size, channel, height, width = hidden_states.shape
61
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
62
+
63
+ batch_size, sequence_length, _ = (
64
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
65
+ )
66
+
67
+ if attention_mask is not None:
68
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
69
+
70
+ if attn.group_norm is not None:
71
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
72
+
73
+ query = attn.to_q(hidden_states)
74
+
75
+ if encoder_hidden_states is None:
76
+ encoder_hidden_states = hidden_states
77
+ elif attn.norm_cross:
78
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
79
+
80
+ key = attn.to_k(encoder_hidden_states)
81
+ value = attn.to_v(encoder_hidden_states)
82
+
83
+ query = attn.head_to_batch_dim(query)
84
+ key = attn.head_to_batch_dim(key)
85
+ value = attn.head_to_batch_dim(value)
86
+
87
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
88
+ hidden_states = torch.bmm(attention_probs, value)
89
+ hidden_states = attn.batch_to_head_dim(hidden_states)
90
+
91
+ hidden_states = attn.to_out[0](hidden_states)
92
+ hidden_states = attn.to_out[1](hidden_states)
93
+
94
+ if input_ndim == 4:
95
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
96
+
97
+ if attn.residual_connection:
98
+ hidden_states = hidden_states + residual
99
+
100
+ hidden_states = hidden_states / attn.rescale_output_factor
101
+
102
+ return hidden_states
103
+
104
+
105
+ class VLMAttnProcessorV3(nn.Module):
106
+ """
107
+ VLM-Adapter Attention Processor v3 with proven stability techniques.
108
+
109
+ Port-back from soft-prompt implementation:
110
+ - Out-of-band VLM token passing (set_vlm_tokens)
111
+ - Single-softmax concat attention
112
+ - Learnable gate with logit-bias
113
+ - Token dropout (train-time)
114
+ - RMSNorm on VLM only + 1/sqrt(K) scaling
115
+
116
+ Args:
117
+ hidden_size: Hidden size of the attention layer
118
+ cross_attention_dim: Dimension of cross-attention embeddings (CLIP: 768)
119
+ num_tokens: Number of VLM tokens
120
+ gate_init: Initial gate value (0.05)
121
+ gate_max: Maximum gate value (0.3-0.5)
122
+ token_dropout: Dropout rate for VLM tokens during training (0.2-0.4)
123
+ """
124
+ def __init__(
125
+ self,
126
+ inner_dim, # heads * head_dim (output dimension)
127
+ cross_attention_dim=768, # input dimension
128
+ num_tokens=16,
129
+ gate_init=0.05,
130
+ gate_max=0.3,
131
+ token_dropout=0.3,
132
+ ):
133
+ super().__init__()
134
+
135
+ self.inner_dim = inner_dim # heads * head_dim
136
+ self.cross_attention_dim = cross_attention_dim
137
+ self.num_tokens = num_tokens
138
+ self.gate_max = gate_max
139
+ self.token_dropout = token_dropout
140
+
141
+ # Separate K/V projections for VLM tokens
142
+ # Output to inner_dim (heads * head_dim), not hidden_size (query input dim)
143
+ self.to_k_vlm = nn.Linear(cross_attention_dim, inner_dim, bias=False)
144
+ self.to_v_vlm = nn.Linear(cross_attention_dim, inner_dim, bias=False)
145
+
146
+ # Initialize with Xavier/Glorot + 0.8 scaling for stability
147
+ nn.init.xavier_uniform_(self.to_k_vlm.weight)
148
+ nn.init.xavier_uniform_(self.to_v_vlm.weight)
149
+ with torch.no_grad():
150
+ self.to_k_vlm.weight.mul_(0.8)
151
+ self.to_v_vlm.weight.mul_(0.8)
152
+
153
+ # RMSNorm for VLM tokens only (don't norm CLIP text)
154
+ self.vlm_norm = RMSNorm(cross_attention_dim, eps=1e-6)
155
+
156
+ # 1/sqrt(K) scaling for VLM features
157
+ self.vlm_scale = 1.0 / math.sqrt(num_tokens)
158
+
159
+ # Learnable gate (logit-bias approach)
160
+ # Initialize to achieve gate_init after sigmoid
161
+ gate_logit_init = math.log(gate_init / (1.0 - gate_init + 1e-6))
162
+ self.gate_logit = nn.Parameter(torch.tensor(gate_logit_init))
163
+
164
+ # Out-of-band VLM token storage
165
+ self._vlm_tokens = None
166
+
167
+ # Mark as VLM processor for logging/debugging
168
+ self.is_vlm_proc = True
169
+
170
+ def set_vlm_tokens(self, tokens):
171
+ """Set VLM tokens for this forward pass (out-of-band)"""
172
+ self._vlm_tokens = tokens
173
+
174
+ def get_gate_value(self):
175
+ """Get current gate value for logging"""
176
+ return (torch.sigmoid(self.gate_logit) * self.gate_max).item()
177
+
178
+ def set_gate_cap(self, new_cap: float):
179
+ """Set new gate cap (for annealing)"""
180
+ self.gate_max = float(new_cap)
181
+
182
+ def __call__(
183
+ self,
184
+ attn,
185
+ hidden_states,
186
+ encoder_hidden_states=None,
187
+ attention_mask=None,
188
+ temb=None,
189
+ ):
190
+ target_dtype = attn.to_q.weight.dtype
191
+ residual = hidden_states
192
+
193
+ if attn.spatial_norm is not None:
194
+ hidden_states = attn.spatial_norm(hidden_states, temb)
195
+
196
+ input_ndim = hidden_states.ndim
197
+
198
+ if input_ndim == 4:
199
+ batch_size, channel, height, width = hidden_states.shape
200
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
201
+
202
+ batch_size, sequence_length, _ = (
203
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
204
+ )
205
+
206
+ if attn.group_norm is not None:
207
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
208
+
209
+ # Query from hidden states
210
+ hidden_states = hidden_states.to(dtype=target_dtype)
211
+ query = attn.to_q(hidden_states)
212
+
213
+ # CLIP text embeddings (pristine, no VLM concatenation)
214
+ if encoder_hidden_states is None:
215
+ encoder_hidden_states = hidden_states
216
+ else:
217
+ encoder_hidden_states = encoder_hidden_states.to(dtype=target_dtype)
218
+ if attn.norm_cross:
219
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
220
+
221
+ # Standard K/V from CLIP text (unchanged)
222
+ key_text = attn.to_k(encoder_hidden_states)
223
+ value_text = attn.to_v(encoder_hidden_states)
224
+
225
+ # VLM path (out-of-band)
226
+ vlm_tokens = self._vlm_tokens
227
+ self._vlm_tokens = None # Clear to avoid stale reuse
228
+
229
+ if vlm_tokens is not None:
230
+ # Token dropout during training
231
+ if self.training and self.token_dropout > 0:
232
+ mask = (torch.rand(vlm_tokens.shape[:2], device=vlm_tokens.device) > self.token_dropout).unsqueeze(-1)
233
+ vlm_tokens = vlm_tokens * mask.to(vlm_tokens.dtype)
234
+
235
+ # RMSNorm + 1/sqrt(K) scaling on VLM only
236
+ vlm_tokens = vlm_tokens.to(dtype=target_dtype)
237
+ vlm_tokens = self.vlm_norm(vlm_tokens) * self.vlm_scale
238
+
239
+ # VLM K/V projections
240
+ key_vlm = self.to_k_vlm(vlm_tokens)
241
+ value_vlm = self.to_v_vlm(vlm_tokens)
242
+
243
+ # Concat K/V: [text | vlm]
244
+ key = torch.cat([key_text, key_vlm], dim=1)
245
+ value = torch.cat([value_text, value_vlm], dim=1)
246
+ else:
247
+ key = key_text
248
+ value = value_text
249
+
250
+ # Handle attention mask BEFORE head-batching
251
+ attn_mask = None
252
+ if attention_mask is not None:
253
+ # Future-proof: extend mask to cover VLM tokens if present
254
+ if vlm_tokens is not None:
255
+ # pad along the last dimension regardless of mask rank
256
+ if attention_mask.ndim == 2: # (B, L)
257
+ b, l = attention_mask.shape
258
+ extra = key.shape[1] - l
259
+ if extra > 0:
260
+ pad = attention_mask.new_ones(b, extra)
261
+ attention_mask = torch.cat([attention_mask, pad], dim=-1)
262
+ elif attention_mask.ndim == 3: # (B, 1, L) or (B, H, L)
263
+ b, h, l = attention_mask.shape
264
+ extra = key.shape[1] - l
265
+ if extra > 0:
266
+ pad = attention_mask.new_ones(b, h, extra)
267
+ attention_mask = torch.cat([attention_mask, pad], dim=-1)
268
+ # else: leave unknown shapes alone
269
+
270
+ attn_mask = attn.prepare_attention_mask(attention_mask, key.shape[1], batch_size)
271
+
272
+ # Multi-head attention
273
+ query = attn.head_to_batch_dim(query)
274
+ key = attn.head_to_batch_dim(key)
275
+ value = attn.head_to_batch_dim(value)
276
+
277
+ # Head-batch the mask too
278
+ if attn_mask is not None:
279
+ attn_mask = attn_mask.repeat_interleave(attn.heads, dim=0) # (B*H, 1, Lc)
280
+
281
+ # Compute attention logits
282
+ scale = getattr(attn, "scale", None) or (query.shape[-1] ** -0.5)
283
+ logits = torch.bmm(query, key.transpose(-1, -2)) * scale
284
+
285
+ # Compute text length once for reuse
286
+ text_len = key_text.shape[1]
287
+
288
+ # Apply learnable gate as logit-bias on VLM segment
289
+ if vlm_tokens is not None:
290
+ # Split logits: [text | vlm]
291
+ logits_text = logits[:, :, :text_len]
292
+ logits_vlm = logits[:, :, text_len:]
293
+
294
+ # Gate as logit bias: log(gate) is added to VLM logits
295
+ gate = torch.sigmoid(self.gate_logit) * self.gate_max
296
+ bias = torch.log(gate.clamp_min(1e-6))
297
+ logits_vlm = logits_vlm + bias
298
+
299
+ # Recombine
300
+ logits = torch.cat([logits_text, logits_vlm], dim=2)
301
+
302
+ # Apply attention mask if provided
303
+ if attn_mask is not None:
304
+ logits = logits + attn_mask
305
+
306
+ # Single softmax over [text | vlm]
307
+ attention_probs = torch.softmax(logits, dim=-1)
308
+
309
+ # Log attention mass split (optional, for debugging)
310
+ if self.training and vlm_tokens is not None and torch.rand(1).item() < 0.01: # 1% chance
311
+ try:
312
+ vlm_mass = attention_probs[:, :, text_len:].sum(dim=-1).mean()
313
+ text_mass = attention_probs[:, :, :text_len].sum(dim=-1).mean()
314
+ # Store for logging (will be logged by trainer)
315
+ self._last_vlm_mass = vlm_mass.item()
316
+ self._last_text_mass = text_mass.item()
317
+ except Exception:
318
+ # Guard against rare shape edge cases
319
+ pass
320
+
321
+ hidden_states = torch.bmm(attention_probs, value)
322
+
323
+ hidden_states = attn.batch_to_head_dim(hidden_states)
324
+
325
+ # Output projection
326
+ hidden_states = attn.to_out[0](hidden_states)
327
+ hidden_states = attn.to_out[1](hidden_states)
328
+
329
+ if input_ndim == 4:
330
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
331
+
332
+ if attn.residual_connection:
333
+ hidden_states = hidden_states + residual.to(dtype=hidden_states.dtype)
334
+
335
+ hidden_states = hidden_states / attn.rescale_output_factor
336
+
337
+ return hidden_states
338
+
339
+
340
+ def init_vlm_adapter_modules_v3(
341
+ unet,
342
+ target_blocks=None,
343
+ num_tokens=16,
344
+ gate_init=0.05,
345
+ gate_max=0.3,
346
+ token_dropout=0.3,
347
+ inject_all_cross_attn=False,
348
+ ):
349
+ """
350
+ Initialize VLM-Adapter v3 modules in the UNet.
351
+
352
+ Uses out-of-band VLM token passing and proven stability techniques
353
+ from the soft-prompt implementation.
354
+
355
+ Args:
356
+ unet: The InstructPix2Pix UNet model
357
+ target_blocks: List of blocks to inject (default: mid_block + up_blocks.1,2,3)
358
+ num_tokens: Number of VLM tokens from ELLA
359
+ gate_init: Initial gate value (0.05)
360
+ gate_max: Maximum gate value (0.3-0.5)
361
+ token_dropout: Token dropout rate during training (0.2-0.4)
362
+
363
+ Returns:
364
+ adapter_modules: ModuleList of VLM adapter parameters
365
+ """
366
+ if target_blocks is None:
367
+ target_blocks = ["mid_block", "up_blocks.1", "up_blocks.2", "up_blocks.3"]
368
+
369
+ print(f"Initializing VLM-Adapter v3 modules in blocks: {target_blocks}")
370
+ print(f" - Num tokens: {num_tokens}")
371
+ print(f" - Gate: {gate_init} → {gate_max} (learnable)")
372
+ print(f" - Token dropout: {token_dropout}")
373
+ print(f" - VLM scale: 1/sqrt({num_tokens}) = {1.0/math.sqrt(num_tokens):.4f}")
374
+
375
+ # Start with existing processors (don't overwrite self-attention!)
376
+ attn_procs = dict(unet.attn_processors)
377
+
378
+ # Handle inject everywhere option
379
+ inject_all = inject_all_cross_attn or target_blocks in (["*"], ["ALL"], ["all"])
380
+
381
+ for name in list(attn_procs.keys()): # Use list() to avoid mutating while iterating
382
+ # Check if this is cross-attention (attn2)
383
+ is_cross = not name.endswith("attn1.processor")
384
+ if not is_cross:
385
+ continue
386
+
387
+ # Navigate to the actual attn2 module to get dims
388
+ mod = unet
389
+ for part in name.replace(".processor", "").split("."):
390
+ if part.isdigit():
391
+ mod = mod[int(part)]
392
+ else:
393
+ mod = getattr(mod, part)
394
+ # mod is the Attention module (attn2)
395
+ inner_dim = mod.to_q.out_features # heads * head_dim ✅
396
+ cross_attention_dim = mod.to_k.in_features # context_dim ✅
397
+
398
+ # Figure block name from the key
399
+ parts = name.split(".")
400
+ if parts[0] in ["up_blocks", "down_blocks"]:
401
+ block_name = f"{parts[0]}.{parts[1]}"
402
+ else:
403
+ block_name = parts[0]
404
+
405
+ # Inject if inject_all is True OR block_name is in target_blocks
406
+ if inject_all or block_name in target_blocks:
407
+ print(f" ✓ Injecting VLM-Adapter v3 to: {name} (inner_dim={inner_dim}, cross_attn_dim={cross_attention_dim})")
408
+
409
+ attn_procs[name] = VLMAttnProcessorV3(
410
+ inner_dim=inner_dim,
411
+ cross_attention_dim=cross_attention_dim,
412
+ num_tokens=num_tokens,
413
+ gate_init=gate_init,
414
+ gate_max=gate_max,
415
+ token_dropout=token_dropout,
416
+ )
417
+ # else: keep existing processor for non-target cross-attention
418
+
419
+ unet.set_attn_processor(attn_procs)
420
+
421
+ # Collect VLM adapter modules for training
422
+ adapter_modules = torch.nn.ModuleList([
423
+ proc for proc in unet.attn_processors.values()
424
+ if isinstance(proc, VLMAttnProcessorV3)
425
+ ])
426
+
427
+ print(f"✓ Initialized {len(adapter_modules)} VLM-Adapter v3 modules")
428
+
429
+ return adapter_modules
430
+
431
+
432
+ if __name__ == "__main__":
433
+ print("VLM Attention Processor v3 module")
434
+ print("Port-back from soft-prompt with proven stability techniques")
435
+
llava/model/vlm_resampler.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Perceiver Resampler for VLM-guided InstructPix2Pix
3
+
4
+ Adapted from IP-Adapter's resampler (which is from Open Flamingo/BLIP-2)
5
+ Converts variable-length LLaVA hidden states (B, L, 4096) to fixed-length tokens (B, num_queries, 768)
6
+ for injection into InstructPix2Pix UNet cross-attention.
7
+ """
8
+
9
+ import math
10
+ import torch
11
+ import torch.nn as nn
12
+
13
+
14
+ def FeedForward(dim, mult=4):
15
+ """Simple MLP with GELU activation"""
16
+ inner_dim = int(dim * mult)
17
+ return nn.Sequential(
18
+ nn.LayerNorm(dim),
19
+ nn.Linear(dim, inner_dim, bias=False),
20
+ nn.GELU(),
21
+ nn.Linear(inner_dim, dim, bias=False),
22
+ )
23
+
24
+
25
+ def reshape_tensor(x, heads):
26
+ """Reshape for multi-head attention"""
27
+ bs, length, width = x.shape
28
+ # (bs, length, width) --> (bs, length, n_heads, dim_per_head)
29
+ x = x.view(bs, length, heads, -1)
30
+ # (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head)
31
+ x = x.transpose(1, 2)
32
+ # (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head)
33
+ x = x.reshape(bs, heads, length, -1)
34
+ return x
35
+
36
+
37
+ class PerceiverAttention(nn.Module):
38
+ """
39
+ Perceiver-style cross-attention layer
40
+ Queries attend to variable-length input features
41
+ """
42
+ def __init__(self, *, dim, dim_head=64, heads=8):
43
+ super().__init__()
44
+ self.scale = dim_head**-0.5
45
+ self.dim_head = dim_head
46
+ self.heads = heads
47
+ inner_dim = dim_head * heads
48
+
49
+ self.norm1 = nn.LayerNorm(dim)
50
+ self.norm2 = nn.LayerNorm(dim)
51
+
52
+ self.to_q = nn.Linear(dim, inner_dim, bias=False)
53
+ self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False)
54
+ self.to_out = nn.Linear(inner_dim, dim, bias=False)
55
+
56
+ def forward(self, x, latents):
57
+ """
58
+ Args:
59
+ x (torch.Tensor): Input features (variable length)
60
+ shape (b, n1, D) - e.g., LLaVA hidden states
61
+ latents (torch.Tensor): Learnable query tokens (fixed length)
62
+ shape (b, n2, D) - e.g., 16 query tokens
63
+ Returns:
64
+ Updated latents (b, n2, D)
65
+ """
66
+ x = self.norm1(x)
67
+ latents = self.norm2(latents)
68
+
69
+ b, l, _ = latents.shape
70
+
71
+ # Q from latents, K/V from input + latents
72
+ q = self.to_q(latents)
73
+ kv_input = torch.cat((x, latents), dim=-2)
74
+ k, v = self.to_kv(kv_input).chunk(2, dim=-1)
75
+
76
+ q = reshape_tensor(q, self.heads)
77
+ k = reshape_tensor(k, self.heads)
78
+ v = reshape_tensor(v, self.heads)
79
+
80
+ # Attention
81
+ scale = 1 / math.sqrt(math.sqrt(self.dim_head))
82
+ weight = (q * scale) @ (k * scale).transpose(-2, -1)
83
+ weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
84
+ out = weight @ v
85
+
86
+ out = out.permute(0, 2, 1, 3).reshape(b, l, -1)
87
+
88
+ return self.to_out(out)
89
+
90
+
91
+ class VLMResampler(nn.Module):
92
+ """
93
+ Perceiver Resampler for LLaVA hidden states
94
+
95
+ Converts variable-length LLaVA hidden states to fixed-length tokens suitable
96
+ for InstructPix2Pix UNet cross-attention injection.
97
+
98
+ Args:
99
+ dim: Internal dimension (default: 1024)
100
+ depth: Number of Perceiver layers (default: 4)
101
+ dim_head: Dimension per attention head (default: 64)
102
+ heads: Number of attention heads (default: 16)
103
+ num_queries: Number of output tokens (default: 16)
104
+ embedding_dim: LLaVA hidden dimension (default: 4096)
105
+ output_dim: UNet cross-attention dimension (default: 768, matching CLIP)
106
+ ff_mult: FFN expansion factor (default: 4)
107
+ """
108
+ def __init__(
109
+ self,
110
+ dim=1024,
111
+ depth=4,
112
+ dim_head=64,
113
+ heads=16,
114
+ num_queries=16,
115
+ embedding_dim=4096, # LLaVA hidden dim
116
+ output_dim=768, # CLIP text dim (for IP2P UNet)
117
+ ff_mult=4,
118
+ ):
119
+ super().__init__()
120
+
121
+ # Learnable query tokens
122
+ self.latents = nn.Parameter(torch.randn(1, num_queries, dim) / dim**0.5)
123
+
124
+ # Project input from LLaVA dim to internal dim
125
+ self.proj_in = nn.Linear(embedding_dim, dim)
126
+
127
+ # Project output to UNet cross-attention dim
128
+ self.proj_out = nn.Linear(dim, output_dim)
129
+ self.norm_out = nn.LayerNorm(output_dim)
130
+
131
+ # Perceiver layers
132
+ self.layers = nn.ModuleList([])
133
+ for _ in range(depth):
134
+ self.layers.append(
135
+ nn.ModuleList(
136
+ [
137
+ PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads),
138
+ FeedForward(dim=dim, mult=ff_mult),
139
+ ]
140
+ )
141
+ )
142
+
143
+ def forward(self, x):
144
+ """
145
+ Args:
146
+ x: LLaVA hidden states, shape (B, L, 4096) where L is variable
147
+
148
+ Returns:
149
+ Fixed-length tokens, shape (B, num_queries, 768)
150
+ """
151
+ # Expand learnable queries to batch size
152
+ latents = self.latents.repeat(x.size(0), 1, 1)
153
+
154
+ # Project input to internal dimension
155
+ x = self.proj_in(x)
156
+
157
+ # Apply Perceiver layers (cross-attention + FFN)
158
+ for attn, ff in self.layers:
159
+ latents = attn(x, latents) + latents
160
+ latents = ff(latents) + latents
161
+
162
+ # Project to output dimension
163
+ latents = self.proj_out(latents)
164
+ return self.norm_out(latents)
165
+
166
+
167
+ def test_resampler():
168
+ """Test the resampler with dummy data"""
169
+ print("Testing VLMResampler...")
170
+
171
+ # Create resampler
172
+ resampler = VLMResampler(
173
+ embedding_dim=4096, # LLaVA hidden dim
174
+ dim=1024, # Internal dim
175
+ output_dim=768, # CLIP text dim
176
+ num_queries=16, # Fixed output tokens
177
+ depth=4, # Number of layers
178
+ heads=16,
179
+ dim_head=64
180
+ )
181
+
182
+ # Test with variable-length inputs
183
+ batch_size = 2
184
+
185
+ # Simulate different sequence lengths (like LLaVA output)
186
+ for seq_len in [50, 100, 200]:
187
+ x = torch.randn(batch_size, seq_len, 4096)
188
+ out = resampler(x)
189
+ print(f"Input: {x.shape} -> Output: {out.shape}")
190
+ assert out.shape == (batch_size, 16, 768), f"Expected (2, 16, 768), got {out.shape}"
191
+
192
+ # Count parameters
193
+ total_params = sum(p.numel() for p in resampler.parameters() if p.requires_grad)
194
+ print(f"Total trainable parameters: {total_params:,}")
195
+ print("✓ VLMResampler test passed!")
196
+
197
+
198
+ if __name__ == "__main__":
199
+ test_resampler()
200
+
201
+
llava/serve/__init__.py ADDED
File without changes
llava/serve/cli.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import torch
3
+
4
+ from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
5
+ from llava.conversation import conv_templates, SeparatorStyle
6
+ from llava.model.builder import load_pretrained_model
7
+ from llava.utils import disable_torch_init
8
+ from llava.mm_utils import process_images, tokenizer_image_token, get_model_name_from_path
9
+
10
+ from PIL import Image
11
+
12
+ import requests
13
+ from PIL import Image
14
+ from io import BytesIO
15
+ from transformers import TextStreamer
16
+
17
+
18
+ def load_image(image_file):
19
+ if image_file.startswith('http://') or image_file.startswith('https://'):
20
+ response = requests.get(image_file)
21
+ image = Image.open(BytesIO(response.content)).convert('RGB')
22
+ else:
23
+ image = Image.open(image_file).convert('RGB')
24
+ return image
25
+
26
+
27
+ def main(args):
28
+ # Model
29
+ disable_torch_init()
30
+
31
+ model_name = get_model_name_from_path(args.model_path)
32
+ tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, args.load_8bit, args.load_4bit, device=args.device)
33
+
34
+ if "llama-2" in model_name.lower():
35
+ conv_mode = "llava_llama_2"
36
+ elif "mistral" in model_name.lower():
37
+ conv_mode = "mistral_instruct"
38
+ elif "v1.6-34b" in model_name.lower():
39
+ conv_mode = "chatml_direct"
40
+ elif "v1" in model_name.lower():
41
+ conv_mode = "llava_v1"
42
+ elif "mpt" in model_name.lower():
43
+ conv_mode = "mpt"
44
+ else:
45
+ conv_mode = "llava_v0"
46
+
47
+ if args.conv_mode is not None and conv_mode != args.conv_mode:
48
+ print('[WARNING] the auto inferred conversation mode is {}, while `--conv-mode` is {}, using {}'.format(conv_mode, args.conv_mode, args.conv_mode))
49
+ else:
50
+ args.conv_mode = conv_mode
51
+
52
+ conv = conv_templates[args.conv_mode].copy()
53
+ if "mpt" in model_name.lower():
54
+ roles = ('user', 'assistant')
55
+ else:
56
+ roles = conv.roles
57
+
58
+ image = load_image(args.image_file)
59
+ image_size = image.size
60
+ # Similar operation in model_worker.py
61
+ image_tensor = process_images([image], image_processor, model.config)
62
+ if type(image_tensor) is list:
63
+ image_tensor = [image.to(model.device, dtype=torch.float16) for image in image_tensor]
64
+ else:
65
+ image_tensor = image_tensor.to(model.device, dtype=torch.float16)
66
+
67
+ while True:
68
+ try:
69
+ inp = input(f"{roles[0]}: ")
70
+ except EOFError:
71
+ inp = ""
72
+ if not inp:
73
+ print("exit...")
74
+ break
75
+
76
+ print(f"{roles[1]}: ", end="")
77
+
78
+ if image is not None:
79
+ # first message
80
+ if model.config.mm_use_im_start_end:
81
+ inp = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + inp
82
+ else:
83
+ inp = DEFAULT_IMAGE_TOKEN + '\n' + inp
84
+ image = None
85
+
86
+ conv.append_message(conv.roles[0], inp)
87
+ conv.append_message(conv.roles[1], None)
88
+ prompt = conv.get_prompt()
89
+
90
+ input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(model.device)
91
+ stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
92
+ keywords = [stop_str]
93
+ streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
94
+
95
+ with torch.inference_mode():
96
+ output_ids = model.generate(
97
+ input_ids,
98
+ images=image_tensor,
99
+ image_sizes=[image_size],
100
+ do_sample=True if args.temperature > 0 else False,
101
+ temperature=args.temperature,
102
+ max_new_tokens=args.max_new_tokens,
103
+ streamer=streamer,
104
+ use_cache=True)
105
+
106
+ outputs = tokenizer.decode(output_ids[0]).strip()
107
+ conv.messages[-1][-1] = outputs
108
+
109
+ if args.debug:
110
+ print("\n", {"prompt": prompt, "outputs": outputs}, "\n")
111
+
112
+
113
+ if __name__ == "__main__":
114
+ parser = argparse.ArgumentParser()
115
+ parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
116
+ parser.add_argument("--model-base", type=str, default=None)
117
+ parser.add_argument("--image-file", type=str, required=True)
118
+ parser.add_argument("--device", type=str, default="cuda")
119
+ parser.add_argument("--conv-mode", type=str, default=None)
120
+ parser.add_argument("--temperature", type=float, default=0.2)
121
+ parser.add_argument("--max-new-tokens", type=int, default=512)
122
+ parser.add_argument("--load-8bit", action="store_true")
123
+ parser.add_argument("--load-4bit", action="store_true")
124
+ parser.add_argument("--debug", action="store_true")
125
+ args = parser.parse_args()
126
+ main(args)
llava/serve/controller.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A controller manages distributed workers.
3
+ It sends worker addresses to clients.
4
+ """
5
+ import argparse
6
+ import asyncio
7
+ import dataclasses
8
+ from enum import Enum, auto
9
+ import json
10
+ import logging
11
+ import time
12
+ from typing import List, Union
13
+ import threading
14
+
15
+ from fastapi import FastAPI, Request
16
+ from fastapi.responses import StreamingResponse
17
+ import numpy as np
18
+ import requests
19
+ import uvicorn
20
+
21
+ from llava.constants import CONTROLLER_HEART_BEAT_EXPIRATION
22
+ from llava.utils import build_logger, server_error_msg
23
+
24
+
25
+ logger = build_logger("controller", "controller.log")
26
+
27
+
28
+ class DispatchMethod(Enum):
29
+ LOTTERY = auto()
30
+ SHORTEST_QUEUE = auto()
31
+
32
+ @classmethod
33
+ def from_str(cls, name):
34
+ if name == "lottery":
35
+ return cls.LOTTERY
36
+ elif name == "shortest_queue":
37
+ return cls.SHORTEST_QUEUE
38
+ else:
39
+ raise ValueError(f"Invalid dispatch method")
40
+
41
+
42
+ @dataclasses.dataclass
43
+ class WorkerInfo:
44
+ model_names: List[str]
45
+ speed: int
46
+ queue_length: int
47
+ check_heart_beat: bool
48
+ last_heart_beat: str
49
+
50
+
51
+ def heart_beat_controller(controller):
52
+ while True:
53
+ time.sleep(CONTROLLER_HEART_BEAT_EXPIRATION)
54
+ controller.remove_stable_workers_by_expiration()
55
+
56
+
57
+ class Controller:
58
+ def __init__(self, dispatch_method: str):
59
+ # Dict[str -> WorkerInfo]
60
+ self.worker_info = {}
61
+ self.dispatch_method = DispatchMethod.from_str(dispatch_method)
62
+
63
+ self.heart_beat_thread = threading.Thread(
64
+ target=heart_beat_controller, args=(self,), daemon=True)
65
+ self.heart_beat_thread.start()
66
+
67
+ logger.info("Init controller")
68
+
69
+ def register_worker(self, worker_name: str, check_heart_beat: bool,
70
+ worker_status: dict):
71
+ if worker_name not in self.worker_info:
72
+ logger.info(f"Register a new worker: {worker_name}")
73
+ else:
74
+ logger.info(f"Register an existing worker: {worker_name}")
75
+
76
+ if not worker_status:
77
+ worker_status = self.get_worker_status(worker_name)
78
+ if not worker_status:
79
+ return False
80
+
81
+ self.worker_info[worker_name] = WorkerInfo(
82
+ worker_status["model_names"], worker_status["speed"], worker_status["queue_length"],
83
+ check_heart_beat, time.time())
84
+
85
+ logger.info(f"Register done: {worker_name}, {worker_status}")
86
+ return True
87
+
88
+ def get_worker_status(self, worker_name: str):
89
+ try:
90
+ r = requests.post(worker_name + "/worker_get_status", timeout=5)
91
+ except requests.exceptions.RequestException as e:
92
+ logger.error(f"Get status fails: {worker_name}, {e}")
93
+ return None
94
+
95
+ if r.status_code != 200:
96
+ logger.error(f"Get status fails: {worker_name}, {r}")
97
+ return None
98
+
99
+ return r.json()
100
+
101
+ def remove_worker(self, worker_name: str):
102
+ del self.worker_info[worker_name]
103
+
104
+ def refresh_all_workers(self):
105
+ old_info = dict(self.worker_info)
106
+ self.worker_info = {}
107
+
108
+ for w_name, w_info in old_info.items():
109
+ if not self.register_worker(w_name, w_info.check_heart_beat, None):
110
+ logger.info(f"Remove stale worker: {w_name}")
111
+
112
+ def list_models(self):
113
+ model_names = set()
114
+
115
+ for w_name, w_info in self.worker_info.items():
116
+ model_names.update(w_info.model_names)
117
+
118
+ return list(model_names)
119
+
120
+ def get_worker_address(self, model_name: str):
121
+ if self.dispatch_method == DispatchMethod.LOTTERY:
122
+ worker_names = []
123
+ worker_speeds = []
124
+ for w_name, w_info in self.worker_info.items():
125
+ if model_name in w_info.model_names:
126
+ worker_names.append(w_name)
127
+ worker_speeds.append(w_info.speed)
128
+ worker_speeds = np.array(worker_speeds, dtype=np.float32)
129
+ norm = np.sum(worker_speeds)
130
+ if norm < 1e-4:
131
+ return ""
132
+ worker_speeds = worker_speeds / norm
133
+ if True: # Directly return address
134
+ pt = np.random.choice(np.arange(len(worker_names)),
135
+ p=worker_speeds)
136
+ worker_name = worker_names[pt]
137
+ return worker_name
138
+
139
+ # Check status before returning
140
+ while True:
141
+ pt = np.random.choice(np.arange(len(worker_names)),
142
+ p=worker_speeds)
143
+ worker_name = worker_names[pt]
144
+
145
+ if self.get_worker_status(worker_name):
146
+ break
147
+ else:
148
+ self.remove_worker(worker_name)
149
+ worker_speeds[pt] = 0
150
+ norm = np.sum(worker_speeds)
151
+ if norm < 1e-4:
152
+ return ""
153
+ worker_speeds = worker_speeds / norm
154
+ continue
155
+ return worker_name
156
+ elif self.dispatch_method == DispatchMethod.SHORTEST_QUEUE:
157
+ worker_names = []
158
+ worker_qlen = []
159
+ for w_name, w_info in self.worker_info.items():
160
+ if model_name in w_info.model_names:
161
+ worker_names.append(w_name)
162
+ worker_qlen.append(w_info.queue_length / w_info.speed)
163
+ if len(worker_names) == 0:
164
+ return ""
165
+ min_index = np.argmin(worker_qlen)
166
+ w_name = worker_names[min_index]
167
+ self.worker_info[w_name].queue_length += 1
168
+ logger.info(f"names: {worker_names}, queue_lens: {worker_qlen}, ret: {w_name}")
169
+ return w_name
170
+ else:
171
+ raise ValueError(f"Invalid dispatch method: {self.dispatch_method}")
172
+
173
+ def receive_heart_beat(self, worker_name: str, queue_length: int):
174
+ if worker_name not in self.worker_info:
175
+ logger.info(f"Receive unknown heart beat. {worker_name}")
176
+ return False
177
+
178
+ self.worker_info[worker_name].queue_length = queue_length
179
+ self.worker_info[worker_name].last_heart_beat = time.time()
180
+ logger.info(f"Receive heart beat. {worker_name}")
181
+ return True
182
+
183
+ def remove_stable_workers_by_expiration(self):
184
+ expire = time.time() - CONTROLLER_HEART_BEAT_EXPIRATION
185
+ to_delete = []
186
+ for worker_name, w_info in self.worker_info.items():
187
+ if w_info.check_heart_beat and w_info.last_heart_beat < expire:
188
+ to_delete.append(worker_name)
189
+
190
+ for worker_name in to_delete:
191
+ self.remove_worker(worker_name)
192
+
193
+ def worker_api_generate_stream(self, params):
194
+ worker_addr = self.get_worker_address(params["model"])
195
+ if not worker_addr:
196
+ logger.info(f"no worker: {params['model']}")
197
+ ret = {
198
+ "text": server_error_msg,
199
+ "error_code": 2,
200
+ }
201
+ yield json.dumps(ret).encode() + b"\0"
202
+
203
+ try:
204
+ response = requests.post(worker_addr + "/worker_generate_stream",
205
+ json=params, stream=True, timeout=5)
206
+ for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
207
+ if chunk:
208
+ yield chunk + b"\0"
209
+ except requests.exceptions.RequestException as e:
210
+ logger.info(f"worker timeout: {worker_addr}")
211
+ ret = {
212
+ "text": server_error_msg,
213
+ "error_code": 3,
214
+ }
215
+ yield json.dumps(ret).encode() + b"\0"
216
+
217
+
218
+ # Let the controller act as a worker to achieve hierarchical
219
+ # management. This can be used to connect isolated sub networks.
220
+ def worker_api_get_status(self):
221
+ model_names = set()
222
+ speed = 0
223
+ queue_length = 0
224
+
225
+ for w_name in self.worker_info:
226
+ worker_status = self.get_worker_status(w_name)
227
+ if worker_status is not None:
228
+ model_names.update(worker_status["model_names"])
229
+ speed += worker_status["speed"]
230
+ queue_length += worker_status["queue_length"]
231
+
232
+ return {
233
+ "model_names": list(model_names),
234
+ "speed": speed,
235
+ "queue_length": queue_length,
236
+ }
237
+
238
+
239
+ app = FastAPI()
240
+
241
+
242
+ @app.post("/register_worker")
243
+ async def register_worker(request: Request):
244
+ data = await request.json()
245
+ controller.register_worker(
246
+ data["worker_name"], data["check_heart_beat"],
247
+ data.get("worker_status", None))
248
+
249
+
250
+ @app.post("/refresh_all_workers")
251
+ async def refresh_all_workers():
252
+ models = controller.refresh_all_workers()
253
+
254
+
255
+ @app.post("/list_models")
256
+ async def list_models():
257
+ models = controller.list_models()
258
+ return {"models": models}
259
+
260
+
261
+ @app.post("/get_worker_address")
262
+ async def get_worker_address(request: Request):
263
+ data = await request.json()
264
+ addr = controller.get_worker_address(data["model"])
265
+ return {"address": addr}
266
+
267
+
268
+ @app.post("/receive_heart_beat")
269
+ async def receive_heart_beat(request: Request):
270
+ data = await request.json()
271
+ exist = controller.receive_heart_beat(
272
+ data["worker_name"], data["queue_length"])
273
+ return {"exist": exist}
274
+
275
+
276
+ @app.post("/worker_generate_stream")
277
+ async def worker_api_generate_stream(request: Request):
278
+ params = await request.json()
279
+ generator = controller.worker_api_generate_stream(params)
280
+ return StreamingResponse(generator)
281
+
282
+
283
+ @app.post("/worker_get_status")
284
+ async def worker_api_get_status(request: Request):
285
+ return controller.worker_api_get_status()
286
+
287
+
288
+ if __name__ == "__main__":
289
+ parser = argparse.ArgumentParser()
290
+ parser.add_argument("--host", type=str, default="localhost")
291
+ parser.add_argument("--port", type=int, default=21001)
292
+ parser.add_argument("--dispatch-method", type=str, choices=[
293
+ "lottery", "shortest_queue"], default="shortest_queue")
294
+ args = parser.parse_args()
295
+ logger.info(f"args: {args}")
296
+
297
+ controller = Controller(args.dispatch_method)
298
+ uvicorn.run(app, host=args.host, port=args.port, log_level="info")
llava/serve/examples/extreme_ironing.jpg ADDED
llava/serve/examples/waterview.jpg ADDED
llava/serve/gradio_web_server.py ADDED
@@ -0,0 +1,479 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import datetime
3
+ import json
4
+ import os
5
+ import time
6
+
7
+ import gradio as gr
8
+ import requests
9
+
10
+ from llava.conversation import (default_conversation, conv_templates,
11
+ SeparatorStyle)
12
+ from llava.constants import LOGDIR
13
+ from llava.utils import (build_logger, server_error_msg,
14
+ violates_moderation, moderation_msg)
15
+ import hashlib
16
+
17
+
18
+ logger = build_logger("gradio_web_server", "gradio_web_server.log")
19
+
20
+ headers = {"User-Agent": "LLaVA Client"}
21
+
22
+ no_change_btn = gr.Button()
23
+ enable_btn = gr.Button(interactive=True)
24
+ disable_btn = gr.Button(interactive=False)
25
+
26
+ priority = {
27
+ "vicuna-13b": "aaaaaaa",
28
+ "koala-13b": "aaaaaab",
29
+ }
30
+
31
+
32
+ def get_conv_log_filename():
33
+ t = datetime.datetime.now()
34
+ name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-conv.json")
35
+ return name
36
+
37
+
38
+ def get_model_list():
39
+ ret = requests.post(args.controller_url + "/refresh_all_workers")
40
+ assert ret.status_code == 200
41
+ ret = requests.post(args.controller_url + "/list_models")
42
+ models = ret.json()["models"]
43
+ models.sort(key=lambda x: priority.get(x, x))
44
+ logger.info(f"Models: {models}")
45
+ return models
46
+
47
+
48
+ get_window_url_params = """
49
+ function() {
50
+ const params = new URLSearchParams(window.location.search);
51
+ url_params = Object.fromEntries(params);
52
+ console.log(url_params);
53
+ return url_params;
54
+ }
55
+ """
56
+
57
+
58
+ def load_demo(url_params, request: gr.Request):
59
+ logger.info(f"load_demo. ip: {request.client.host}. params: {url_params}")
60
+
61
+ dropdown_update = gr.Dropdown(visible=True)
62
+ if "model" in url_params:
63
+ model = url_params["model"]
64
+ if model in models:
65
+ dropdown_update = gr.Dropdown(value=model, visible=True)
66
+
67
+ state = default_conversation.copy()
68
+ return state, dropdown_update
69
+
70
+
71
+ def load_demo_refresh_model_list(request: gr.Request):
72
+ logger.info(f"load_demo. ip: {request.client.host}")
73
+ models = get_model_list()
74
+ state = default_conversation.copy()
75
+ dropdown_update = gr.Dropdown(
76
+ choices=models,
77
+ value=models[0] if len(models) > 0 else ""
78
+ )
79
+ return state, dropdown_update
80
+
81
+
82
+ def vote_last_response(state, vote_type, model_selector, request: gr.Request):
83
+ with open(get_conv_log_filename(), "a") as fout:
84
+ data = {
85
+ "tstamp": round(time.time(), 4),
86
+ "type": vote_type,
87
+ "model": model_selector,
88
+ "state": state.dict(),
89
+ "ip": request.client.host,
90
+ }
91
+ fout.write(json.dumps(data) + "\n")
92
+
93
+
94
+ def upvote_last_response(state, model_selector, request: gr.Request):
95
+ logger.info(f"upvote. ip: {request.client.host}")
96
+ vote_last_response(state, "upvote", model_selector, request)
97
+ return ("",) + (disable_btn,) * 3
98
+
99
+
100
+ def downvote_last_response(state, model_selector, request: gr.Request):
101
+ logger.info(f"downvote. ip: {request.client.host}")
102
+ vote_last_response(state, "downvote", model_selector, request)
103
+ return ("",) + (disable_btn,) * 3
104
+
105
+
106
+ def flag_last_response(state, model_selector, request: gr.Request):
107
+ logger.info(f"flag. ip: {request.client.host}")
108
+ vote_last_response(state, "flag", model_selector, request)
109
+ return ("",) + (disable_btn,) * 3
110
+
111
+
112
+ def regenerate(state, image_process_mode, request: gr.Request):
113
+ logger.info(f"regenerate. ip: {request.client.host}")
114
+ state.messages[-1][-1] = None
115
+ prev_human_msg = state.messages[-2]
116
+ if type(prev_human_msg[1]) in (tuple, list):
117
+ prev_human_msg[1] = (*prev_human_msg[1][:2], image_process_mode)
118
+ state.skip_next = False
119
+ return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
120
+
121
+
122
+ def clear_history(request: gr.Request):
123
+ logger.info(f"clear_history. ip: {request.client.host}")
124
+ state = default_conversation.copy()
125
+ return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
126
+
127
+
128
+ def add_text(state, text, image, image_process_mode, request: gr.Request):
129
+ logger.info(f"add_text. ip: {request.client.host}. len: {len(text)}")
130
+ if len(text) <= 0 and image is None:
131
+ state.skip_next = True
132
+ return (state, state.to_gradio_chatbot(), "", None) + (no_change_btn,) * 5
133
+ if args.moderate:
134
+ flagged = violates_moderation(text)
135
+ if flagged:
136
+ state.skip_next = True
137
+ return (state, state.to_gradio_chatbot(), moderation_msg, None) + (
138
+ no_change_btn,) * 5
139
+
140
+ text = text[:1536] # Hard cut-off
141
+ if image is not None:
142
+ text = text[:1200] # Hard cut-off for images
143
+ if '<image>' not in text:
144
+ # text = '<Image><image></Image>' + text
145
+ text = text + '\n<image>'
146
+ text = (text, image, image_process_mode)
147
+ state = default_conversation.copy()
148
+ state.append_message(state.roles[0], text)
149
+ state.append_message(state.roles[1], None)
150
+ state.skip_next = False
151
+ return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
152
+
153
+
154
+ def http_bot(state, model_selector, temperature, top_p, max_new_tokens, request: gr.Request):
155
+ logger.info(f"http_bot. ip: {request.client.host}")
156
+ start_tstamp = time.time()
157
+ model_name = model_selector
158
+
159
+ if state.skip_next:
160
+ # This generate call is skipped due to invalid inputs
161
+ yield (state, state.to_gradio_chatbot()) + (no_change_btn,) * 5
162
+ return
163
+
164
+ if len(state.messages) == state.offset + 2:
165
+ # First round of conversation
166
+ if "llava" in model_name.lower():
167
+ if 'llama-2' in model_name.lower():
168
+ template_name = "llava_llama_2"
169
+ elif "mistral" in model_name.lower() or "mixtral" in model_name.lower():
170
+ if 'orca' in model_name.lower():
171
+ template_name = "mistral_orca"
172
+ elif 'hermes' in model_name.lower():
173
+ template_name = "chatml_direct"
174
+ else:
175
+ template_name = "mistral_instruct"
176
+ elif 'llava-v1.6-34b' in model_name.lower():
177
+ template_name = "chatml_direct"
178
+ elif "v1" in model_name.lower():
179
+ if 'mmtag' in model_name.lower():
180
+ template_name = "v1_mmtag"
181
+ elif 'plain' in model_name.lower() and 'finetune' not in model_name.lower():
182
+ template_name = "v1_mmtag"
183
+ else:
184
+ template_name = "llava_v1"
185
+ elif "mpt" in model_name.lower():
186
+ template_name = "mpt"
187
+ else:
188
+ if 'mmtag' in model_name.lower():
189
+ template_name = "v0_mmtag"
190
+ elif 'plain' in model_name.lower() and 'finetune' not in model_name.lower():
191
+ template_name = "v0_mmtag"
192
+ else:
193
+ template_name = "llava_v0"
194
+ elif "mpt" in model_name:
195
+ template_name = "mpt_text"
196
+ elif "llama-2" in model_name:
197
+ template_name = "llama_2"
198
+ else:
199
+ template_name = "vicuna_v1"
200
+ new_state = conv_templates[template_name].copy()
201
+ new_state.append_message(new_state.roles[0], state.messages[-2][1])
202
+ new_state.append_message(new_state.roles[1], None)
203
+ state = new_state
204
+
205
+ # Query worker address
206
+ controller_url = args.controller_url
207
+ ret = requests.post(controller_url + "/get_worker_address",
208
+ json={"model": model_name})
209
+ worker_addr = ret.json()["address"]
210
+ logger.info(f"model_name: {model_name}, worker_addr: {worker_addr}")
211
+
212
+ # No available worker
213
+ if worker_addr == "":
214
+ state.messages[-1][-1] = server_error_msg
215
+ yield (state, state.to_gradio_chatbot(), disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
216
+ return
217
+
218
+ # Construct prompt
219
+ prompt = state.get_prompt()
220
+
221
+ all_images = state.get_images(return_pil=True)
222
+ all_image_hash = [hashlib.md5(image.tobytes()).hexdigest() for image in all_images]
223
+ for image, hash in zip(all_images, all_image_hash):
224
+ t = datetime.datetime.now()
225
+ filename = os.path.join(LOGDIR, "serve_images", f"{t.year}-{t.month:02d}-{t.day:02d}", f"{hash}.jpg")
226
+ if not os.path.isfile(filename):
227
+ os.makedirs(os.path.dirname(filename), exist_ok=True)
228
+ image.save(filename)
229
+
230
+ # Make requests
231
+ pload = {
232
+ "model": model_name,
233
+ "prompt": prompt,
234
+ "temperature": float(temperature),
235
+ "top_p": float(top_p),
236
+ "max_new_tokens": min(int(max_new_tokens), 1536),
237
+ "stop": state.sep if state.sep_style in [SeparatorStyle.SINGLE, SeparatorStyle.MPT] else state.sep2,
238
+ "images": f'List of {len(state.get_images())} images: {all_image_hash}',
239
+ }
240
+ logger.info(f"==== request ====\n{pload}")
241
+
242
+ pload['images'] = state.get_images()
243
+
244
+ state.messages[-1][-1] = "▌"
245
+ yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
246
+
247
+ try:
248
+ # Stream output
249
+ response = requests.post(worker_addr + "/worker_generate_stream",
250
+ headers=headers, json=pload, stream=True, timeout=10)
251
+ for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
252
+ if chunk:
253
+ data = json.loads(chunk.decode())
254
+ if data["error_code"] == 0:
255
+ output = data["text"][len(prompt):].strip()
256
+ state.messages[-1][-1] = output + "▌"
257
+ yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
258
+ else:
259
+ output = data["text"] + f" (error_code: {data['error_code']})"
260
+ state.messages[-1][-1] = output
261
+ yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
262
+ return
263
+ time.sleep(0.03)
264
+ except requests.exceptions.RequestException as e:
265
+ state.messages[-1][-1] = server_error_msg
266
+ yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
267
+ return
268
+
269
+ state.messages[-1][-1] = state.messages[-1][-1][:-1]
270
+ yield (state, state.to_gradio_chatbot()) + (enable_btn,) * 5
271
+
272
+ finish_tstamp = time.time()
273
+ logger.info(f"{output}")
274
+
275
+ with open(get_conv_log_filename(), "a") as fout:
276
+ data = {
277
+ "tstamp": round(finish_tstamp, 4),
278
+ "type": "chat",
279
+ "model": model_name,
280
+ "start": round(start_tstamp, 4),
281
+ "finish": round(finish_tstamp, 4),
282
+ "state": state.dict(),
283
+ "images": all_image_hash,
284
+ "ip": request.client.host,
285
+ }
286
+ fout.write(json.dumps(data) + "\n")
287
+
288
+ title_markdown = ("""
289
+ # 🌋 LLaVA: Large Language and Vision Assistant
290
+ [[Project Page](https://llava-vl.github.io)] [[Code](https://github.com/haotian-liu/LLaVA)] [[Model](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md)] | 📚 [[LLaVA](https://arxiv.org/abs/2304.08485)] [[LLaVA-v1.5](https://arxiv.org/abs/2310.03744)] [[LLaVA-v1.6](https://llava-vl.github.io/blog/2024-01-30-llava-1-6/)]
291
+ """)
292
+
293
+ tos_markdown = ("""
294
+ ### Terms of use
295
+ By using this service, users are required to agree to the following terms:
296
+ The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes. The service may collect user dialogue data for future research.
297
+ Please click the "Flag" button if you get any inappropriate answer! We will collect those to keep improving our moderator.
298
+ For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality.
299
+ """)
300
+
301
+
302
+ learn_more_markdown = ("""
303
+ ### License
304
+ The service is a research preview intended for non-commercial use only, subject to the model [License](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md) of LLaMA, [Terms of Use](https://openai.com/policies/terms-of-use) of the data generated by OpenAI, and [Privacy Practices](https://chrome.google.com/webstore/detail/sharegpt-share-your-chatg/daiacboceoaocpibfodeljbdfacokfjb) of ShareGPT. Please contact us if you find any potential violation.
305
+ """)
306
+
307
+ block_css = """
308
+
309
+ #buttons button {
310
+ min-width: min(120px,100%);
311
+ }
312
+
313
+ """
314
+
315
+ def build_demo(embed_mode, cur_dir=None, concurrency_count=10):
316
+ textbox = gr.Textbox(show_label=False, placeholder="Enter text and press ENTER", container=False)
317
+ with gr.Blocks(title="LLaVA", theme=gr.themes.Default(), css=block_css) as demo:
318
+ state = gr.State()
319
+
320
+ if not embed_mode:
321
+ gr.Markdown(title_markdown)
322
+
323
+ with gr.Row():
324
+ with gr.Column(scale=3):
325
+ with gr.Row(elem_id="model_selector_row"):
326
+ model_selector = gr.Dropdown(
327
+ choices=models,
328
+ value=models[0] if len(models) > 0 else "",
329
+ interactive=True,
330
+ show_label=False,
331
+ container=False)
332
+
333
+ imagebox = gr.Image(type="pil")
334
+ image_process_mode = gr.Radio(
335
+ ["Crop", "Resize", "Pad", "Default"],
336
+ value="Default",
337
+ label="Preprocess for non-square image", visible=False)
338
+
339
+ if cur_dir is None:
340
+ cur_dir = os.path.dirname(os.path.abspath(__file__))
341
+ gr.Examples(examples=[
342
+ [f"{cur_dir}/examples/extreme_ironing.jpg", "What is unusual about this image?"],
343
+ [f"{cur_dir}/examples/waterview.jpg", "What are the things I should be cautious about when I visit here?"],
344
+ ], inputs=[imagebox, textbox])
345
+
346
+ with gr.Accordion("Parameters", open=False) as parameter_row:
347
+ temperature = gr.Slider(minimum=0.0, maximum=1.0, value=0.2, step=0.1, interactive=True, label="Temperature",)
348
+ top_p = gr.Slider(minimum=0.0, maximum=1.0, value=0.7, step=0.1, interactive=True, label="Top P",)
349
+ max_output_tokens = gr.Slider(minimum=0, maximum=1024, value=512, step=64, interactive=True, label="Max output tokens",)
350
+
351
+ with gr.Column(scale=8):
352
+ chatbot = gr.Chatbot(
353
+ elem_id="chatbot",
354
+ label="LLaVA Chatbot",
355
+ height=650,
356
+ layout="panel",
357
+ )
358
+ with gr.Row():
359
+ with gr.Column(scale=8):
360
+ textbox.render()
361
+ with gr.Column(scale=1, min_width=50):
362
+ submit_btn = gr.Button(value="Send", variant="primary")
363
+ with gr.Row(elem_id="buttons") as button_row:
364
+ upvote_btn = gr.Button(value="👍 Upvote", interactive=False)
365
+ downvote_btn = gr.Button(value="👎 Downvote", interactive=False)
366
+ flag_btn = gr.Button(value="⚠️ Flag", interactive=False)
367
+ #stop_btn = gr.Button(value="⏹️ Stop Generation", interactive=False)
368
+ regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=False)
369
+ clear_btn = gr.Button(value="🗑️ Clear", interactive=False)
370
+
371
+ if not embed_mode:
372
+ gr.Markdown(tos_markdown)
373
+ gr.Markdown(learn_more_markdown)
374
+ url_params = gr.JSON(visible=False)
375
+
376
+ # Register listeners
377
+ btn_list = [upvote_btn, downvote_btn, flag_btn, regenerate_btn, clear_btn]
378
+ upvote_btn.click(
379
+ upvote_last_response,
380
+ [state, model_selector],
381
+ [textbox, upvote_btn, downvote_btn, flag_btn]
382
+ )
383
+ downvote_btn.click(
384
+ downvote_last_response,
385
+ [state, model_selector],
386
+ [textbox, upvote_btn, downvote_btn, flag_btn]
387
+ )
388
+ flag_btn.click(
389
+ flag_last_response,
390
+ [state, model_selector],
391
+ [textbox, upvote_btn, downvote_btn, flag_btn]
392
+ )
393
+
394
+ regenerate_btn.click(
395
+ regenerate,
396
+ [state, image_process_mode],
397
+ [state, chatbot, textbox, imagebox] + btn_list
398
+ ).then(
399
+ http_bot,
400
+ [state, model_selector, temperature, top_p, max_output_tokens],
401
+ [state, chatbot] + btn_list,
402
+ concurrency_limit=concurrency_count
403
+ )
404
+
405
+ clear_btn.click(
406
+ clear_history,
407
+ None,
408
+ [state, chatbot, textbox, imagebox] + btn_list,
409
+ queue=False
410
+ )
411
+
412
+ textbox.submit(
413
+ add_text,
414
+ [state, textbox, imagebox, image_process_mode],
415
+ [state, chatbot, textbox, imagebox] + btn_list,
416
+ queue=False
417
+ ).then(
418
+ http_bot,
419
+ [state, model_selector, temperature, top_p, max_output_tokens],
420
+ [state, chatbot] + btn_list,
421
+ concurrency_limit=concurrency_count
422
+ )
423
+
424
+ submit_btn.click(
425
+ add_text,
426
+ [state, textbox, imagebox, image_process_mode],
427
+ [state, chatbot, textbox, imagebox] + btn_list
428
+ ).then(
429
+ http_bot,
430
+ [state, model_selector, temperature, top_p, max_output_tokens],
431
+ [state, chatbot] + btn_list,
432
+ concurrency_limit=concurrency_count
433
+ )
434
+
435
+ if args.model_list_mode == "once":
436
+ demo.load(
437
+ load_demo,
438
+ [url_params],
439
+ [state, model_selector],
440
+ js=get_window_url_params
441
+ )
442
+ elif args.model_list_mode == "reload":
443
+ demo.load(
444
+ load_demo_refresh_model_list,
445
+ None,
446
+ [state, model_selector],
447
+ queue=False
448
+ )
449
+ else:
450
+ raise ValueError(f"Unknown model list mode: {args.model_list_mode}")
451
+
452
+ return demo
453
+
454
+
455
+ if __name__ == "__main__":
456
+ parser = argparse.ArgumentParser()
457
+ parser.add_argument("--host", type=str, default="0.0.0.0")
458
+ parser.add_argument("--port", type=int)
459
+ parser.add_argument("--controller-url", type=str, default="http://localhost:21001")
460
+ parser.add_argument("--concurrency-count", type=int, default=16)
461
+ parser.add_argument("--model-list-mode", type=str, default="once",
462
+ choices=["once", "reload"])
463
+ parser.add_argument("--share", action="store_true")
464
+ parser.add_argument("--moderate", action="store_true")
465
+ parser.add_argument("--embed", action="store_true")
466
+ args = parser.parse_args()
467
+ logger.info(f"args: {args}")
468
+
469
+ models = get_model_list()
470
+
471
+ logger.info(args)
472
+ demo = build_demo(args.embed, concurrency_count=args.concurrency_count)
473
+ demo.queue(
474
+ api_open=False
475
+ ).launch(
476
+ server_name=args.host,
477
+ server_port=args.port,
478
+ share=args.share
479
+ )
llava/serve/model_worker.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A model worker executes the model.
3
+ """
4
+ import argparse
5
+ import asyncio
6
+ import json
7
+ import time
8
+ import threading
9
+ import uuid
10
+
11
+ from fastapi import FastAPI, Request, BackgroundTasks
12
+ from fastapi.responses import StreamingResponse
13
+ import requests
14
+ import torch
15
+ import uvicorn
16
+ from functools import partial
17
+
18
+ from llava.constants import WORKER_HEART_BEAT_INTERVAL
19
+ from llava.utils import (build_logger, server_error_msg,
20
+ pretty_print_semaphore)
21
+ from llava.model.builder import load_pretrained_model
22
+ from llava.mm_utils import process_images, load_image_from_base64, tokenizer_image_token
23
+ from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
24
+ from transformers import TextIteratorStreamer
25
+ from threading import Thread
26
+
27
+
28
+ GB = 1 << 30
29
+
30
+ worker_id = str(uuid.uuid4())[:6]
31
+ logger = build_logger("model_worker", f"model_worker_{worker_id}.log")
32
+ global_counter = 0
33
+
34
+ model_semaphore = None
35
+
36
+
37
+ def heart_beat_worker(controller):
38
+
39
+ while True:
40
+ time.sleep(WORKER_HEART_BEAT_INTERVAL)
41
+ controller.send_heart_beat()
42
+
43
+
44
+ class ModelWorker:
45
+ def __init__(self, controller_addr, worker_addr,
46
+ worker_id, no_register,
47
+ model_path, model_base, model_name,
48
+ load_8bit, load_4bit, device, use_flash_attn=False):
49
+ self.controller_addr = controller_addr
50
+ self.worker_addr = worker_addr
51
+ self.worker_id = worker_id
52
+ if model_path.endswith("/"):
53
+ model_path = model_path[:-1]
54
+ if model_name is None:
55
+ model_paths = model_path.split("/")
56
+ if model_paths[-1].startswith('checkpoint-'):
57
+ self.model_name = model_paths[-2] + "_" + model_paths[-1]
58
+ else:
59
+ self.model_name = model_paths[-1]
60
+ else:
61
+ self.model_name = model_name
62
+
63
+ self.device = device
64
+ logger.info(f"Loading the model {self.model_name} on worker {worker_id} ...")
65
+ self.tokenizer, self.model, self.image_processor, self.context_len = load_pretrained_model(
66
+ model_path, model_base, self.model_name, load_8bit, load_4bit, device=self.device, use_flash_attn=use_flash_attn)
67
+ self.is_multimodal = 'llava' in self.model_name.lower()
68
+
69
+ if not no_register:
70
+ self.register_to_controller()
71
+ self.heart_beat_thread = threading.Thread(
72
+ target=heart_beat_worker, args=(self,), daemon=True)
73
+ self.heart_beat_thread.start()
74
+
75
+ def register_to_controller(self):
76
+ logger.info("Register to controller")
77
+
78
+ url = self.controller_addr + "/register_worker"
79
+ data = {
80
+ "worker_name": self.worker_addr,
81
+ "check_heart_beat": True,
82
+ "worker_status": self.get_status()
83
+ }
84
+ r = requests.post(url, json=data)
85
+ assert r.status_code == 200
86
+
87
+ def send_heart_beat(self):
88
+ logger.info(f"Send heart beat. Models: {[self.model_name]}. "
89
+ f"Semaphore: {pretty_print_semaphore(model_semaphore)}. "
90
+ f"global_counter: {global_counter}")
91
+
92
+ url = self.controller_addr + "/receive_heart_beat"
93
+
94
+ while True:
95
+ try:
96
+ ret = requests.post(url, json={
97
+ "worker_name": self.worker_addr,
98
+ "queue_length": self.get_queue_length()}, timeout=5)
99
+ exist = ret.json()["exist"]
100
+ break
101
+ except requests.exceptions.RequestException as e:
102
+ logger.error(f"heart beat error: {e}")
103
+ time.sleep(5)
104
+
105
+ if not exist:
106
+ self.register_to_controller()
107
+
108
+ def get_queue_length(self):
109
+ if model_semaphore is None:
110
+ return 0
111
+ else:
112
+ return args.limit_model_concurrency - model_semaphore._value + (len(
113
+ model_semaphore._waiters) if model_semaphore._waiters is not None else 0)
114
+
115
+ def get_status(self):
116
+ return {
117
+ "model_names": [self.model_name],
118
+ "speed": 1,
119
+ "queue_length": self.get_queue_length(),
120
+ }
121
+
122
+ @torch.inference_mode()
123
+ def generate_stream(self, params):
124
+ tokenizer, model, image_processor = self.tokenizer, self.model, self.image_processor
125
+
126
+ prompt = params["prompt"]
127
+ ori_prompt = prompt
128
+ images = params.get("images", None)
129
+ num_image_tokens = 0
130
+ if images is not None and len(images) > 0 and self.is_multimodal:
131
+ if len(images) > 0:
132
+ if len(images) != prompt.count(DEFAULT_IMAGE_TOKEN):
133
+ raise ValueError("Number of images does not match number of <image> tokens in prompt")
134
+
135
+ images = [load_image_from_base64(image) for image in images]
136
+ image_sizes = [image.size for image in images]
137
+ images = process_images(images, image_processor, model.config)
138
+
139
+ if type(images) is list:
140
+ images = [image.to(self.model.device, dtype=torch.float16) for image in images]
141
+ else:
142
+ images = images.to(self.model.device, dtype=torch.float16)
143
+
144
+ replace_token = DEFAULT_IMAGE_TOKEN
145
+ if getattr(self.model.config, 'mm_use_im_start_end', False):
146
+ replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
147
+ prompt = prompt.replace(DEFAULT_IMAGE_TOKEN, replace_token)
148
+
149
+ num_image_tokens = prompt.count(replace_token) * model.get_vision_tower().num_patches
150
+ else:
151
+ images = None
152
+ image_sizes = None
153
+ image_args = {"images": images, "image_sizes": image_sizes}
154
+ else:
155
+ images = None
156
+ image_args = {}
157
+
158
+ temperature = float(params.get("temperature", 1.0))
159
+ top_p = float(params.get("top_p", 1.0))
160
+ max_context_length = getattr(model.config, 'max_position_embeddings', 2048)
161
+ max_new_tokens = min(int(params.get("max_new_tokens", 256)), 1024)
162
+ stop_str = params.get("stop", None)
163
+ do_sample = True if temperature > 0.001 else False
164
+
165
+ input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(self.device)
166
+ keywords = [stop_str]
167
+ # stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
168
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=15)
169
+
170
+ max_new_tokens = min(max_new_tokens, max_context_length - input_ids.shape[-1] - num_image_tokens)
171
+
172
+ if max_new_tokens < 1:
173
+ yield json.dumps({"text": ori_prompt + "Exceeds max token length. Please start a new conversation, thanks.", "error_code": 0}).encode() + b"\0"
174
+ return
175
+
176
+ thread = Thread(target=model.generate, kwargs=dict(
177
+ inputs=input_ids,
178
+ do_sample=do_sample,
179
+ temperature=temperature,
180
+ top_p=top_p,
181
+ max_new_tokens=max_new_tokens,
182
+ streamer=streamer,
183
+ use_cache=True,
184
+ **image_args
185
+ ))
186
+ thread.start()
187
+
188
+ generated_text = ori_prompt
189
+ for new_text in streamer:
190
+ generated_text += new_text
191
+ if generated_text.endswith(stop_str):
192
+ generated_text = generated_text[:-len(stop_str)]
193
+ yield json.dumps({"text": generated_text, "error_code": 0}).encode() + b"\0"
194
+
195
+ def generate_stream_gate(self, params):
196
+ try:
197
+ for x in self.generate_stream(params):
198
+ yield x
199
+ except ValueError as e:
200
+ print("Caught ValueError:", e)
201
+ ret = {
202
+ "text": server_error_msg,
203
+ "error_code": 1,
204
+ }
205
+ yield json.dumps(ret).encode() + b"\0"
206
+ except torch.cuda.CudaError as e:
207
+ print("Caught torch.cuda.CudaError:", e)
208
+ ret = {
209
+ "text": server_error_msg,
210
+ "error_code": 1,
211
+ }
212
+ yield json.dumps(ret).encode() + b"\0"
213
+ except Exception as e:
214
+ print("Caught Unknown Error", e)
215
+ ret = {
216
+ "text": server_error_msg,
217
+ "error_code": 1,
218
+ }
219
+ yield json.dumps(ret).encode() + b"\0"
220
+
221
+
222
+ app = FastAPI()
223
+
224
+
225
+ def release_model_semaphore(fn=None):
226
+ model_semaphore.release()
227
+ if fn is not None:
228
+ fn()
229
+
230
+
231
+ @app.post("/worker_generate_stream")
232
+ async def generate_stream(request: Request):
233
+ global model_semaphore, global_counter
234
+ global_counter += 1
235
+ params = await request.json()
236
+
237
+ if model_semaphore is None:
238
+ model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
239
+ await model_semaphore.acquire()
240
+ worker.send_heart_beat()
241
+ generator = worker.generate_stream_gate(params)
242
+ background_tasks = BackgroundTasks()
243
+ background_tasks.add_task(partial(release_model_semaphore, fn=worker.send_heart_beat))
244
+ return StreamingResponse(generator, background=background_tasks)
245
+
246
+
247
+ @app.post("/worker_get_status")
248
+ async def get_status(request: Request):
249
+ return worker.get_status()
250
+
251
+
252
+ if __name__ == "__main__":
253
+ parser = argparse.ArgumentParser()
254
+ parser.add_argument("--host", type=str, default="localhost")
255
+ parser.add_argument("--port", type=int, default=21002)
256
+ parser.add_argument("--worker-address", type=str,
257
+ default="http://localhost:21002")
258
+ parser.add_argument("--controller-address", type=str,
259
+ default="http://localhost:21001")
260
+ parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
261
+ parser.add_argument("--model-base", type=str, default=None)
262
+ parser.add_argument("--model-name", type=str)
263
+ parser.add_argument("--device", type=str, default="cuda")
264
+ parser.add_argument("--multi-modal", action="store_true", help="Multimodal mode is automatically detected with model name, please make sure `llava` is included in the model path.")
265
+ parser.add_argument("--limit-model-concurrency", type=int, default=5)
266
+ parser.add_argument("--stream-interval", type=int, default=1)
267
+ parser.add_argument("--no-register", action="store_true")
268
+ parser.add_argument("--load-8bit", action="store_true")
269
+ parser.add_argument("--load-4bit", action="store_true")
270
+ parser.add_argument("--use-flash-attn", action="store_true")
271
+ args = parser.parse_args()
272
+ logger.info(f"args: {args}")
273
+
274
+ if args.multi_modal:
275
+ logger.warning("Multimodal mode is automatically detected with model name, please make sure `llava` is included in the model path.")
276
+
277
+ worker = ModelWorker(args.controller_address,
278
+ args.worker_address,
279
+ worker_id,
280
+ args.no_register,
281
+ args.model_path,
282
+ args.model_base,
283
+ args.model_name,
284
+ args.load_8bit,
285
+ args.load_4bit,
286
+ args.device,
287
+ use_flash_attn=args.use_flash_attn)
288
+ uvicorn.run(app, host=args.host, port=args.port, log_level="info")
llava/serve/register_worker.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Manually register workers.
3
+
4
+ Usage:
5
+ python3 -m fastchat.serve.register_worker --controller http://localhost:21001 --worker-name http://localhost:21002
6
+ """
7
+
8
+ import argparse
9
+
10
+ import requests
11
+
12
+ if __name__ == "__main__":
13
+ parser = argparse.ArgumentParser()
14
+ parser.add_argument("--controller-address", type=str)
15
+ parser.add_argument("--worker-name", type=str)
16
+ parser.add_argument("--check-heart-beat", action="store_true")
17
+ args = parser.parse_args()
18
+
19
+ url = args.controller_address + "/register_worker"
20
+ data = {
21
+ "worker_name": args.worker_name,
22
+ "check_heart_beat": args.check_heart_beat,
23
+ "worker_status": None,
24
+ }
25
+ r = requests.post(url, json=data)
26
+ assert r.status_code == 200
llava/serve/sglang_worker.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A model worker executes the model.
3
+ """
4
+ import argparse
5
+ import asyncio
6
+ from concurrent.futures import ThreadPoolExecutor
7
+ import json
8
+ import time
9
+ import threading
10
+ import uuid
11
+
12
+ from fastapi import FastAPI, Request, BackgroundTasks
13
+ from fastapi.responses import StreamingResponse
14
+ import requests
15
+ import re
16
+ import uvicorn
17
+ from functools import partial
18
+
19
+ from llava.constants import WORKER_HEART_BEAT_INTERVAL
20
+ from llava.utils import (build_logger, server_error_msg,
21
+ pretty_print_semaphore)
22
+ from llava.mm_utils import process_images, load_image_from_base64, tokenizer_image_token, expand2square
23
+ from llava.constants import DEFAULT_IMAGE_TOKEN
24
+
25
+ import sglang as sgl
26
+ from sglang.backend.runtime_endpoint import RuntimeEndpoint
27
+
28
+
29
+ GB = 1 << 30
30
+
31
+ worker_id = str(uuid.uuid4())[:6]
32
+ logger = build_logger("model_worker", f"model_worker_{worker_id}.log")
33
+ global_counter = 0
34
+
35
+ model_semaphore = None
36
+
37
+
38
+ def heart_beat_worker(controller):
39
+ while True:
40
+ time.sleep(WORKER_HEART_BEAT_INTERVAL)
41
+ controller.send_heart_beat()
42
+
43
+
44
+ @sgl.function
45
+ def pipeline(s, prompt, max_tokens):
46
+ for p in prompt:
47
+ if type(p) is str:
48
+ s += p
49
+ else:
50
+ s += sgl.image(p)
51
+ s += sgl.gen("response", max_tokens=max_tokens)
52
+
53
+
54
+ class ModelWorker:
55
+ def __init__(self, controller_addr, worker_addr, sgl_endpoint,
56
+ worker_id, no_register, model_name):
57
+ self.controller_addr = controller_addr
58
+ self.worker_addr = worker_addr
59
+ self.worker_id = worker_id
60
+
61
+ # Select backend
62
+ backend = RuntimeEndpoint(sgl_endpoint)
63
+ sgl.set_default_backend(backend)
64
+ model_path = backend.model_info["model_path"]
65
+
66
+ if model_path.endswith("/"):
67
+ model_path = model_path[:-1]
68
+ if model_name is None:
69
+ model_paths = model_path.split("/")
70
+ if model_paths[-1].startswith('checkpoint-'):
71
+ self.model_name = model_paths[-2] + "_" + model_paths[-1]
72
+ else:
73
+ self.model_name = model_paths[-1]
74
+ else:
75
+ self.model_name = model_name
76
+
77
+ logger.info(f"Loading the SGLANG model {self.model_name} on worker {worker_id} ...")
78
+
79
+ if not no_register:
80
+ self.register_to_controller()
81
+ self.heart_beat_thread = threading.Thread(
82
+ target=heart_beat_worker, args=(self,), daemon=True)
83
+ self.heart_beat_thread.start()
84
+
85
+ def register_to_controller(self):
86
+ logger.info("Register to controller")
87
+
88
+ url = self.controller_addr + "/register_worker"
89
+ data = {
90
+ "worker_name": self.worker_addr,
91
+ "check_heart_beat": True,
92
+ "worker_status": self.get_status()
93
+ }
94
+ r = requests.post(url, json=data)
95
+ assert r.status_code == 200
96
+
97
+ def send_heart_beat(self):
98
+ logger.info(f"Send heart beat. Models: {[self.model_name]}. "
99
+ f"Semaphore: {pretty_print_semaphore(model_semaphore)}. "
100
+ f"global_counter: {global_counter}")
101
+
102
+ url = self.controller_addr + "/receive_heart_beat"
103
+
104
+ while True:
105
+ try:
106
+ ret = requests.post(url, json={
107
+ "worker_name": self.worker_addr,
108
+ "queue_length": self.get_queue_length()}, timeout=5)
109
+ exist = ret.json()["exist"]
110
+ break
111
+ except requests.exceptions.RequestException as e:
112
+ logger.error(f"heart beat error: {e}")
113
+ time.sleep(5)
114
+
115
+ if not exist:
116
+ self.register_to_controller()
117
+
118
+ def get_queue_length(self):
119
+ if model_semaphore is None:
120
+ return 0
121
+ else:
122
+ return args.limit_model_concurrency - model_semaphore._value + (len(
123
+ model_semaphore._waiters) if model_semaphore._waiters is not None else 0)
124
+
125
+ def get_status(self):
126
+ return {
127
+ "model_names": [self.model_name],
128
+ "speed": 1,
129
+ "queue_length": self.get_queue_length(),
130
+ }
131
+
132
+ async def generate_stream(self, params):
133
+ ori_prompt = prompt = params["prompt"]
134
+ images = params.get("images", None)
135
+ if images is not None and len(images) > 0:
136
+ if len(images) > 0:
137
+ if len(images) != prompt.count(DEFAULT_IMAGE_TOKEN):
138
+ raise ValueError("Number of images does not match number of <image> tokens in prompt")
139
+
140
+ images = [load_image_from_base64(image) for image in images]
141
+
142
+ # FIXME: for image-start/end token
143
+ # replace_token = DEFAULT_IMAGE_TOKEN
144
+ # if getattr(self.model.config, 'mm_use_im_start_end', False):
145
+ # replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
146
+ # prompt = prompt.replace(DEFAULT_IMAGE_TOKEN, replace_token)
147
+ prompt = prompt.replace(' ' + DEFAULT_IMAGE_TOKEN + '\n', DEFAULT_IMAGE_TOKEN)
148
+ prompt_split = prompt.split(DEFAULT_IMAGE_TOKEN)
149
+ prompt = []
150
+ for i in range(len(prompt_split)):
151
+ prompt.append(prompt_split[i])
152
+ if i < len(images):
153
+ prompt.append(images[i])
154
+ else:
155
+ prompt = [prompt]
156
+
157
+ temperature = float(params.get("temperature", 1.0))
158
+ top_p = float(params.get("top_p", 1.0))
159
+ # max_context_length = getattr(model.config, 'max_position_embeddings', 2048)
160
+ max_new_tokens = min(int(params.get("max_new_tokens", 256)), 1024)
161
+ stop_str = params.get("stop", None)
162
+ stop_str = [stop_str] if stop_str is not None else None
163
+
164
+ print({'prompt': prompt, 'max_new_tokens': max_new_tokens, 'temperature': temperature, 'top_p': top_p})
165
+ state = pipeline.run(prompt, max_new_tokens, temperature=temperature, top_p=top_p, stream=True)
166
+
167
+ generated_text = ori_prompt
168
+ async for text_outputs in state.text_async_iter(var_name="response"):
169
+ generated_text += text_outputs
170
+ yield json.dumps({"text": generated_text, "error_code": 0}).encode() + b"\0"
171
+
172
+ async def generate_stream_gate(self, params):
173
+ try:
174
+ async for x in self.generate_stream(params):
175
+ yield x
176
+ except ValueError as e:
177
+ print("Caught ValueError:", e)
178
+ ret = {
179
+ "text": server_error_msg,
180
+ "error_code": 1,
181
+ }
182
+ yield json.dumps(ret).encode() + b"\0"
183
+ except Exception as e:
184
+ print("Caught Unknown Error", e)
185
+ ret = {
186
+ "text": server_error_msg,
187
+ "error_code": 1,
188
+ }
189
+ yield json.dumps(ret).encode() + b"\0"
190
+
191
+
192
+ app = FastAPI()
193
+
194
+
195
+ def release_model_semaphore(fn=None):
196
+ model_semaphore.release()
197
+ if fn is not None:
198
+ fn()
199
+
200
+
201
+ @app.post("/worker_generate_stream")
202
+ async def generate_stream(request: Request):
203
+ global model_semaphore, global_counter
204
+ global_counter += 1
205
+ params = await request.json()
206
+
207
+ if model_semaphore is None:
208
+ model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
209
+ await model_semaphore.acquire()
210
+ worker.send_heart_beat()
211
+ generator = worker.generate_stream_gate(params)
212
+ background_tasks = BackgroundTasks()
213
+ background_tasks.add_task(partial(release_model_semaphore, fn=worker.send_heart_beat))
214
+ return StreamingResponse(generator, background=background_tasks)
215
+
216
+
217
+ @app.post("/worker_get_status")
218
+ async def get_status(request: Request):
219
+ return worker.get_status()
220
+
221
+
222
+ if __name__ == "__main__":
223
+ parser = argparse.ArgumentParser()
224
+ parser.add_argument("--host", type=str, default="localhost")
225
+ parser.add_argument("--port", type=int, default=21002)
226
+ parser.add_argument("--worker-address", type=str,
227
+ default="http://localhost:21002")
228
+ parser.add_argument("--controller-address", type=str,
229
+ default="http://localhost:21001")
230
+ parser.add_argument("--model-name", type=str)
231
+ parser.add_argument("--sgl-endpoint", type=str)
232
+ parser.add_argument("--limit-model-concurrency", type=int, default=5)
233
+ parser.add_argument("--stream-interval", type=int, default=1)
234
+ parser.add_argument("--no-register", action="store_true")
235
+ args = parser.parse_args()
236
+ logger.info(f"args: {args}")
237
+
238
+ worker = ModelWorker(args.controller_address,
239
+ args.worker_address,
240
+ args.sgl_endpoint,
241
+ worker_id,
242
+ args.no_register,
243
+ args.model_name)
244
+ uvicorn.run(app, host=args.host, port=args.port, log_level="info")
llava/serve/test_message.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+
4
+ import requests
5
+
6
+ from llava.conversation import default_conversation
7
+
8
+
9
+ def main():
10
+ if args.worker_address:
11
+ worker_addr = args.worker_address
12
+ else:
13
+ controller_addr = args.controller_address
14
+ ret = requests.post(controller_addr + "/refresh_all_workers")
15
+ ret = requests.post(controller_addr + "/list_models")
16
+ models = ret.json()["models"]
17
+ models.sort()
18
+ print(f"Models: {models}")
19
+
20
+ ret = requests.post(controller_addr + "/get_worker_address",
21
+ json={"model": args.model_name})
22
+ worker_addr = ret.json()["address"]
23
+ print(f"worker_addr: {worker_addr}")
24
+
25
+ if worker_addr == "":
26
+ return
27
+
28
+ conv = default_conversation.copy()
29
+ conv.append_message(conv.roles[0], args.message)
30
+ prompt = conv.get_prompt()
31
+
32
+ headers = {"User-Agent": "LLaVA Client"}
33
+ pload = {
34
+ "model": args.model_name,
35
+ "prompt": prompt,
36
+ "max_new_tokens": args.max_new_tokens,
37
+ "temperature": 0.7,
38
+ "stop": conv.sep,
39
+ }
40
+ response = requests.post(worker_addr + "/worker_generate_stream", headers=headers,
41
+ json=pload, stream=True)
42
+
43
+ print(prompt.replace(conv.sep, "\n"), end="")
44
+ for chunk in response.iter_lines(chunk_size=8192, decode_unicode=False, delimiter=b"\0"):
45
+ if chunk:
46
+ data = json.loads(chunk.decode("utf-8"))
47
+ output = data["text"].split(conv.sep)[-1]
48
+ print(output, end="\r")
49
+ print("")
50
+
51
+
52
+ if __name__ == "__main__":
53
+ parser = argparse.ArgumentParser()
54
+ parser.add_argument("--controller-address", type=str, default="http://localhost:21001")
55
+ parser.add_argument("--worker-address", type=str)
56
+ parser.add_argument("--model-name", type=str, default="facebook/opt-350m")
57
+ parser.add_argument("--max-new-tokens", type=int, default=32)
58
+ parser.add_argument("--message", type=str, default=
59
+ "Tell me a story with more than 1000 words.")
60
+ args = parser.parse_args()
61
+
62
+ main()