jamie33 commited on
Commit
6dbcc17
·
verified ·
1 Parent(s): 3ab0d5d

Upload folder using huggingface_hub (part 9)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +3 -0
  2. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/eva_vit.py +856 -0
  3. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/factory.py +60 -0
  4. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA-CLIP-18B.json +27 -0
  5. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA-CLIP-8B-plus.json +27 -0
  6. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA-CLIP-8B.json +27 -0
  7. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA01-CLIP-B-16.json +19 -0
  8. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA01-CLIP-g-14-plus.json +24 -0
  9. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA01-CLIP-g-14.json +24 -0
  10. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-B-16.json +29 -0
  11. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-L-14-336.json +29 -0
  12. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-L-14.json +29 -0
  13. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-bigE-14-plus.json +25 -0
  14. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-bigE-14.json +25 -0
  15. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/Internal-EVA02-CLIP-10B-14-448.json +25 -0
  16. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/Internal-EVA02-CLIP-10B-14.json +25 -0
  17. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/hf_vision.py +111 -0
  18. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/imagebind.py +73 -0
  19. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/open_clip_encoder.py +163 -0
  20. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/siglip_encoder.py +620 -0
  21. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_projector/builder.py +65 -0
  22. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_projector/pooler_projector.py +33 -0
  23. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_resampler/builder.py +34 -0
  24. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_resampler/masked_drop.py +80 -0
  25. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_resampler/perceiver.py +155 -0
  26. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_resampler/qformer.py +1160 -0
  27. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_resampler/spatial_pool.py +45 -0
  28. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/utils.py +20 -0
  29. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/serve/__init__.py +0 -0
  30. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/serve/cli.py +111 -0
  31. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/serve/controller.py +287 -0
  32. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/serve/examples/extreme_ironing.jpg +3 -0
  33. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/serve/examples/waterview.jpg +3 -0
  34. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/serve/gradio_multi_image.py +448 -0
  35. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/serve/gradio_web_server.py +442 -0
  36. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/serve/model_worker.py +271 -0
  37. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/serve/register_worker.py +26 -0
  38. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/serve/sglang_worker.py +237 -0
  39. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/serve/test_message.py +59 -0
  40. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/train/llama_flash_attn_monkey_patch.py +87 -0
  41. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/train/llava_trainer.py +527 -0
  42. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/train/llava_trainer_eval.py +76 -0
  43. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/train/train.py +1721 -0
  44. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/train/train_dpo.py +1782 -0
  45. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/train/train_mem.py +4 -0
  46. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/utils.py +198 -0
  47. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/playground/2d_hist.py +132 -0
  48. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/playground/data_checker.py +364 -0
  49. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/playground/demo/video_demo.py +335 -0
  50. video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/playground/equal_splitter.py +38 -0
.gitattributes CHANGED
@@ -59,3 +59,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
  video_gen_14d/models/Wan2.1-VACE-1.3B/google/umt5-xxl/tokenizer.json filter=lfs diff=lfs merge=lfs -text
 
 
 
 
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
  video_gen_14d/models/Wan2.1-VACE-1.3B/google/umt5-xxl/tokenizer.json filter=lfs diff=lfs merge=lfs -text
62
+ video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/ViTDetector/data/lvis/annotations/lvis_v1_minival_inserted_image_name.json filter=lfs diff=lfs merge=lfs -text
63
+ video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/ViTDetector/lvis/lvis_v1_minival_inserted_image_name.json filter=lfs diff=lfs merge=lfs -text
64
+ video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/ViTDetector/third_party/YOLO-World/data/coco/lvis/lvis_v1_minival_inserted_image_name.json filter=lfs diff=lfs merge=lfs -text
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/eva_vit.py ADDED
@@ -0,0 +1,856 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ # Adapted from https://github.com/baaivision/EVA/tree/master/EVA-CLIP
3
+ """
4
+
5
+ from math import pi
6
+ import torch
7
+ from torch import nn
8
+ from einops import rearrange, repeat
9
+ import logging
10
+ from llava.utils import rank0_print
11
+
12
+
13
+ def broadcat(tensors, dim=-1):
14
+ num_tensors = len(tensors)
15
+ shape_lens = set(list(map(lambda t: len(t.shape), tensors)))
16
+ assert len(shape_lens) == 1, "tensors must all have the same number of dimensions"
17
+ shape_len = list(shape_lens)[0]
18
+ dim = (dim + shape_len) if dim < 0 else dim
19
+ dims = list(zip(*map(lambda t: list(t.shape), tensors)))
20
+ expandable_dims = [(i, val) for i, val in enumerate(dims) if i != dim]
21
+ assert all([*map(lambda t: len(set(t[1])) <= 2, expandable_dims)]), "invalid dimensions for broadcastable concatentation"
22
+ max_dims = list(map(lambda t: (t[0], max(t[1])), expandable_dims))
23
+ expanded_dims = list(map(lambda t: (t[0], (t[1],) * num_tensors), max_dims))
24
+ expanded_dims.insert(dim, (dim, dims[dim]))
25
+ expandable_shapes = list(zip(*map(lambda t: t[1], expanded_dims)))
26
+ tensors = list(map(lambda t: t[0].expand(*t[1]), zip(tensors, expandable_shapes)))
27
+ return torch.cat(tensors, dim=dim)
28
+
29
+
30
+ def rotate_half(x):
31
+ x = rearrange(x, "... (d r) -> ... d r", r=2)
32
+ x1, x2 = x.unbind(dim=-1)
33
+ x = torch.stack((-x2, x1), dim=-1)
34
+ return rearrange(x, "... d r -> ... (d r)")
35
+
36
+
37
+ class VisionRotaryEmbeddingFast(nn.Module):
38
+ def __init__(self, dim, pt_seq_len, ft_seq_len=None, custom_freqs=None, freqs_for="lang", theta=10000, max_freq=10, num_freqs=1, patch_dropout=0.0):
39
+ super().__init__()
40
+ if custom_freqs:
41
+ freqs = custom_freqs
42
+ elif freqs_for == "lang":
43
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
44
+ elif freqs_for == "pixel":
45
+ freqs = torch.linspace(1.0, max_freq / 2, dim // 2) * pi
46
+ elif freqs_for == "constant":
47
+ freqs = torch.ones(num_freqs).float()
48
+ else:
49
+ raise ValueError(f"unknown modality {freqs_for}")
50
+
51
+ if ft_seq_len is None:
52
+ ft_seq_len = pt_seq_len
53
+ t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len
54
+
55
+ freqs = torch.einsum("..., f -> ... f", t, freqs)
56
+ freqs = repeat(freqs, "... n -> ... (n r)", r=2)
57
+ freqs = broadcat((freqs[:, None, :], freqs[None, :, :]), dim=-1)
58
+
59
+ freqs_cos = freqs.cos().view(-1, freqs.shape[-1])
60
+ freqs_sin = freqs.sin().view(-1, freqs.shape[-1])
61
+
62
+ self.patch_dropout = patch_dropout
63
+
64
+ self.register_buffer("freqs_cos", freqs_cos)
65
+ self.register_buffer("freqs_sin", freqs_sin)
66
+
67
+ logging.info(f"Shape of rope freq: {self.freqs_cos.shape}")
68
+
69
+ def forward(self, t, patch_indices_keep=None):
70
+ if patch_indices_keep is not None:
71
+ batch = t.size()[0]
72
+ batch_indices = torch.arange(batch)
73
+ batch_indices = batch_indices[..., None]
74
+
75
+ freqs_cos = repeat(self.freqs_cos, "i j -> n i m j", n=t.shape[0], m=t.shape[1])
76
+ freqs_sin = repeat(self.freqs_sin, "i j -> n i m j", n=t.shape[0], m=t.shape[1])
77
+
78
+ freqs_cos = freqs_cos[batch_indices, patch_indices_keep]
79
+ freqs_cos = rearrange(freqs_cos, "n i m j -> n m i j")
80
+ freqs_sin = freqs_sin[batch_indices, patch_indices_keep]
81
+ freqs_sin = rearrange(freqs_sin, "n i m j -> n m i j")
82
+
83
+ return t * freqs_cos + rotate_half(t) * freqs_sin
84
+
85
+ return t * self.freqs_cos + rotate_half(t) * self.freqs_sin
86
+
87
+
88
+ class LayerNorm(nn.LayerNorm):
89
+ """Subclass torch's LayerNorm (with cast back to input dtype)."""
90
+
91
+ def forward(self, x: torch.Tensor):
92
+ orig_type = x.dtype
93
+ x = F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
94
+ return x.to(orig_type)
95
+
96
+
97
+ class PatchDropout(nn.Module):
98
+ """
99
+ https://arxiv.org/abs/2212.00794
100
+ """
101
+
102
+ def __init__(self, prob, exclude_first_token=True):
103
+ super().__init__()
104
+ assert 0 <= prob < 1.0
105
+ self.prob = prob
106
+ self.exclude_first_token = exclude_first_token # exclude CLS token
107
+ logging.info(f"os.getenv('RoPE')={os.getenv('RoPE')}")
108
+
109
+ def forward(self, x):
110
+ if not self.training or self.prob == 0.0:
111
+ return x
112
+
113
+ if self.exclude_first_token:
114
+ cls_tokens, x = x[:, :1], x[:, 1:]
115
+ else:
116
+ cls_tokens = torch.jit.annotate(torch.Tensor, x[:, :1])
117
+
118
+ batch = x.size()[0]
119
+ num_tokens = x.size()[1]
120
+
121
+ batch_indices = torch.arange(batch)
122
+ batch_indices = batch_indices[..., None]
123
+
124
+ keep_prob = 1 - self.prob
125
+ num_patches_keep = max(1, int(num_tokens * keep_prob))
126
+
127
+ rand = torch.randn(batch, num_tokens)
128
+ patch_indices_keep = rand.topk(num_patches_keep, dim=-1).indices
129
+
130
+ x = x[batch_indices, patch_indices_keep]
131
+
132
+ if self.exclude_first_token:
133
+ x = torch.cat((cls_tokens, x), dim=1)
134
+
135
+ if self.training and os.getenv("RoPE") == "1":
136
+ return x, patch_indices_keep
137
+
138
+ return x
139
+
140
+
141
+ # --------------------------------------------------------
142
+ # Adapted from https://github.com/microsoft/unilm/tree/master/beit
143
+ # --------------------------------------------------------
144
+ import math
145
+ import os
146
+ import torch.nn as nn
147
+ import torch.nn.functional as F
148
+
149
+ try:
150
+ from timm.models.layers import drop_path, to_2tuple, trunc_normal_
151
+ except:
152
+ from timm.layers import drop_path, to_2tuple, trunc_normal_
153
+
154
+ if os.getenv("ENV_TYPE") == "deepspeed":
155
+ try:
156
+ from deepspeed.runtime.activation_checkpointing.checkpointing import checkpoint
157
+ except:
158
+ from torch.utils.checkpoint import checkpoint
159
+ else:
160
+ from torch.utils.checkpoint import checkpoint
161
+
162
+ try:
163
+ import xformers.ops as xops
164
+ except ImportError:
165
+ xops = None
166
+ # print("Please 'pip install xformers'")
167
+
168
+
169
+ class DropPath(nn.Module):
170
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
171
+
172
+ def __init__(self, drop_prob=None):
173
+ super(DropPath, self).__init__()
174
+ self.drop_prob = drop_prob
175
+
176
+ def forward(self, x):
177
+ return drop_path(x, self.drop_prob, self.training)
178
+
179
+ def extra_repr(self) -> str:
180
+ return "p={}".format(self.drop_prob)
181
+
182
+
183
+ class Mlp(nn.Module):
184
+ def __init__(
185
+ self,
186
+ in_features,
187
+ hidden_features=None,
188
+ out_features=None,
189
+ act_layer=nn.GELU,
190
+ norm_layer=nn.LayerNorm,
191
+ drop=0.0,
192
+ subln=False,
193
+ ):
194
+ super().__init__()
195
+ out_features = out_features or in_features
196
+ hidden_features = hidden_features or in_features
197
+ self.fc1 = nn.Linear(in_features, hidden_features)
198
+ self.act = act_layer()
199
+
200
+ self.ffn_ln = norm_layer(hidden_features) if subln else nn.Identity()
201
+
202
+ self.fc2 = nn.Linear(hidden_features, out_features)
203
+ self.drop = nn.Dropout(drop)
204
+
205
+ def forward(self, x):
206
+ x = self.fc1(x)
207
+ x = self.act(x)
208
+ # x = self.drop(x)
209
+ # commit this for the orignal BERT implement
210
+ x = self.ffn_ln(x)
211
+
212
+ x = self.fc2(x)
213
+ x = self.drop(x)
214
+ return x
215
+
216
+
217
+ class SwiGLU(nn.Module):
218
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.SiLU, drop=0.0, norm_layer=nn.LayerNorm, subln=False):
219
+ super().__init__()
220
+ out_features = out_features or in_features
221
+ hidden_features = hidden_features or in_features
222
+
223
+ self.w1 = nn.Linear(in_features, hidden_features)
224
+ self.w2 = nn.Linear(in_features, hidden_features)
225
+
226
+ self.act = act_layer()
227
+ self.ffn_ln = norm_layer(hidden_features) if subln else nn.Identity()
228
+ self.w3 = nn.Linear(hidden_features, out_features)
229
+
230
+ self.drop = nn.Dropout(drop)
231
+
232
+ def forward(self, x):
233
+ x1 = self.w1(x)
234
+ x2 = self.w2(x)
235
+ hidden = self.act(x1) * x2
236
+ x = self.ffn_ln(hidden)
237
+ x = self.w3(x)
238
+ x = self.drop(x)
239
+ return x
240
+
241
+
242
+ class Attention(nn.Module):
243
+ def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0, window_size=None, attn_head_dim=None, xattn=False, rope=None, subln=False, norm_layer=nn.LayerNorm):
244
+ super().__init__()
245
+ self.num_heads = num_heads
246
+ head_dim = dim // num_heads
247
+ if attn_head_dim is not None:
248
+ head_dim = attn_head_dim
249
+ all_head_dim = head_dim * self.num_heads
250
+ self.scale = qk_scale or head_dim**-0.5
251
+
252
+ self.subln = subln
253
+ if self.subln:
254
+ self.q_proj = nn.Linear(dim, all_head_dim, bias=False)
255
+ self.k_proj = nn.Linear(dim, all_head_dim, bias=False)
256
+ self.v_proj = nn.Linear(dim, all_head_dim, bias=False)
257
+ else:
258
+ self.qkv = nn.Linear(dim, all_head_dim * 3, bias=False)
259
+
260
+ if qkv_bias:
261
+ self.q_bias = nn.Parameter(torch.zeros(all_head_dim))
262
+ self.v_bias = nn.Parameter(torch.zeros(all_head_dim))
263
+ else:
264
+ self.q_bias = None
265
+ self.v_bias = None
266
+
267
+ if window_size:
268
+ self.window_size = window_size
269
+ self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
270
+ self.relative_position_bias_table = nn.Parameter(torch.zeros(self.num_relative_distance, num_heads)) # 2*Wh-1 * 2*Ww-1, nH
271
+ # cls to token & token 2 cls & cls to cls
272
+
273
+ # get pair-wise relative position index for each token inside the window
274
+ coords_h = torch.arange(window_size[0])
275
+ coords_w = torch.arange(window_size[1])
276
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
277
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
278
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
279
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
280
+ relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0
281
+ relative_coords[:, :, 1] += window_size[1] - 1
282
+ relative_coords[:, :, 0] *= 2 * window_size[1] - 1
283
+ relative_position_index = torch.zeros(size=(window_size[0] * window_size[1] + 1,) * 2, dtype=relative_coords.dtype)
284
+ relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
285
+ relative_position_index[0, 0:] = self.num_relative_distance - 3
286
+ relative_position_index[0:, 0] = self.num_relative_distance - 2
287
+ relative_position_index[0, 0] = self.num_relative_distance - 1
288
+
289
+ self.register_buffer("relative_position_index", relative_position_index)
290
+ else:
291
+ self.window_size = None
292
+ self.relative_position_bias_table = None
293
+ self.relative_position_index = None
294
+
295
+ self.attn_drop = nn.Dropout(attn_drop)
296
+ self.inner_attn_ln = norm_layer(all_head_dim) if subln else nn.Identity()
297
+ # self.proj = nn.Linear(all_head_dim, all_head_dim)
298
+ self.proj = nn.Linear(all_head_dim, dim)
299
+ self.proj_drop = nn.Dropout(proj_drop)
300
+ self.xattn = xattn
301
+ self.xattn_drop = attn_drop
302
+
303
+ self.rope = rope
304
+
305
+ def forward(self, x, rel_pos_bias=None, attn_mask=None):
306
+ B, N, C = x.shape
307
+ if self.subln:
308
+ q = F.linear(input=x, weight=self.q_proj.weight, bias=self.q_bias)
309
+ k = F.linear(input=x, weight=self.k_proj.weight, bias=None)
310
+ v = F.linear(input=x, weight=self.v_proj.weight, bias=self.v_bias)
311
+
312
+ q = q.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) # B, num_heads, N, C
313
+ k = k.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
314
+ v = v.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
315
+ else:
316
+
317
+ qkv_bias = None
318
+ if self.q_bias is not None:
319
+ qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias))
320
+
321
+ qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
322
+ qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) # 3, B, num_heads, N, C
323
+ q, k, v = qkv[0], qkv[1], qkv[2]
324
+
325
+ if self.rope:
326
+ # slightly fast impl
327
+ q_t = q[:, :, 1:, :]
328
+ ro_q_t = self.rope(q_t)
329
+ q = torch.cat((q[:, :, :1, :], ro_q_t), -2).type_as(v)
330
+
331
+ k_t = k[:, :, 1:, :]
332
+ ro_k_t = self.rope(k_t)
333
+ k = torch.cat((k[:, :, :1, :], ro_k_t), -2).type_as(v)
334
+
335
+ if self.xattn and xops is not None:
336
+ q = q.permute(0, 2, 1, 3) # B, num_heads, N, C -> B, N, num_heads, C
337
+ k = k.permute(0, 2, 1, 3)
338
+ v = v.permute(0, 2, 1, 3)
339
+
340
+ x = xops.memory_efficient_attention(
341
+ q,
342
+ k,
343
+ v,
344
+ p=self.xattn_drop,
345
+ scale=self.scale,
346
+ )
347
+ x = x.reshape(B, N, -1)
348
+ x = self.inner_attn_ln(x)
349
+ x = self.proj(x)
350
+ x = self.proj_drop(x)
351
+ else:
352
+ q = q * self.scale
353
+ attn = q @ k.transpose(-2, -1)
354
+
355
+ if self.relative_position_bias_table is not None:
356
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(self.window_size[0] * self.window_size[1] + 1, self.window_size[0] * self.window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH
357
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
358
+ attn = attn + relative_position_bias.unsqueeze(0).type_as(attn)
359
+
360
+ if rel_pos_bias is not None:
361
+ attn = attn + rel_pos_bias.type_as(attn)
362
+
363
+ if attn_mask is not None:
364
+ attn_mask = attn_mask.bool()
365
+ attn = attn.masked_fill(~attn_mask[:, None, None, :], float("-inf"))
366
+
367
+ attn = attn.softmax(dim=-1)
368
+ attn = self.attn_drop(attn)
369
+
370
+ x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
371
+ x = self.inner_attn_ln(x)
372
+ x = self.proj(x)
373
+ x = self.proj_drop(x)
374
+ return x
375
+
376
+
377
+ class Block(nn.Module):
378
+
379
+ def __init__(
380
+ self,
381
+ dim,
382
+ num_heads,
383
+ mlp_ratio=4.0,
384
+ qkv_bias=False,
385
+ qk_scale=None,
386
+ drop=0.0,
387
+ attn_drop=0.0,
388
+ drop_path=0.0,
389
+ init_values=None,
390
+ act_layer=nn.GELU,
391
+ norm_layer=nn.LayerNorm,
392
+ window_size=None,
393
+ attn_head_dim=None,
394
+ xattn=False,
395
+ rope=None,
396
+ postnorm=False,
397
+ subln=False,
398
+ naiveswiglu=False,
399
+ ):
400
+ super().__init__()
401
+ self.norm1 = norm_layer(dim)
402
+ self.attn = Attention(
403
+ dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop, window_size=window_size, attn_head_dim=attn_head_dim, xattn=xattn, rope=rope, subln=subln, norm_layer=norm_layer
404
+ )
405
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
406
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
407
+ self.norm2 = norm_layer(dim)
408
+ mlp_hidden_dim = int(dim * mlp_ratio)
409
+
410
+ if naiveswiglu:
411
+ self.mlp = SwiGLU(
412
+ in_features=dim,
413
+ hidden_features=mlp_hidden_dim,
414
+ subln=subln,
415
+ norm_layer=norm_layer,
416
+ )
417
+ else:
418
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, subln=subln, drop=drop)
419
+
420
+ if init_values is not None and init_values > 0:
421
+ self.gamma_1 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True)
422
+ self.gamma_2 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True)
423
+ else:
424
+ self.gamma_1, self.gamma_2 = None, None
425
+
426
+ self.postnorm = postnorm
427
+
428
+ def forward(self, x, rel_pos_bias=None, attn_mask=None):
429
+ if self.gamma_1 is None:
430
+ if self.postnorm:
431
+ x = x + self.drop_path(self.norm1(self.attn(x, rel_pos_bias=rel_pos_bias, attn_mask=attn_mask)))
432
+ x = x + self.drop_path(self.norm2(self.mlp(x)))
433
+ else:
434
+ x = x + self.drop_path(self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias, attn_mask=attn_mask))
435
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
436
+ else:
437
+ if self.postnorm:
438
+ x = x + self.drop_path(self.gamma_1 * self.norm1(self.attn(x, rel_pos_bias=rel_pos_bias, attn_mask=attn_mask)))
439
+ x = x + self.drop_path(self.gamma_2 * self.norm2(self.mlp(x)))
440
+ else:
441
+ x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias, attn_mask=attn_mask))
442
+ x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x)))
443
+ return x
444
+
445
+
446
+ class PatchEmbed(nn.Module):
447
+ """Image to Patch Embedding"""
448
+
449
+ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):
450
+ super().__init__()
451
+ img_size = to_2tuple(img_size)
452
+ patch_size = to_2tuple(patch_size)
453
+ num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0])
454
+ self.patch_shape = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
455
+ self.img_size = img_size
456
+ self.patch_size = patch_size
457
+ self.num_patches = num_patches
458
+
459
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
460
+
461
+ def forward(self, x, **kwargs):
462
+ B, C, H, W = x.shape
463
+ # FIXME look at relaxing size constraints
464
+ assert H == self.img_size[0] and W == self.img_size[1], f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
465
+ x = self.proj(x).flatten(2).transpose(1, 2)
466
+ return x
467
+
468
+
469
+ class RelativePositionBias(nn.Module):
470
+
471
+ def __init__(self, window_size, num_heads):
472
+ super().__init__()
473
+ self.window_size = window_size
474
+ self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
475
+ self.relative_position_bias_table = nn.Parameter(torch.zeros(self.num_relative_distance, num_heads)) # 2*Wh-1 * 2*Ww-1, nH
476
+ # cls to token & token 2 cls & cls to cls
477
+
478
+ # get pair-wise relative position index for each token inside the window
479
+ coords_h = torch.arange(window_size[0])
480
+ coords_w = torch.arange(window_size[1])
481
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
482
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
483
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
484
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
485
+ relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0
486
+ relative_coords[:, :, 1] += window_size[1] - 1
487
+ relative_coords[:, :, 0] *= 2 * window_size[1] - 1
488
+ relative_position_index = torch.zeros(size=(window_size[0] * window_size[1] + 1,) * 2, dtype=relative_coords.dtype)
489
+ relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
490
+ relative_position_index[0, 0:] = self.num_relative_distance - 3
491
+ relative_position_index[0:, 0] = self.num_relative_distance - 2
492
+ relative_position_index[0, 0] = self.num_relative_distance - 1
493
+
494
+ self.register_buffer("relative_position_index", relative_position_index)
495
+
496
+ def forward(self):
497
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(self.window_size[0] * self.window_size[1] + 1, self.window_size[0] * self.window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH
498
+ return relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
499
+
500
+
501
+ class EVAVisionTransformer(nn.Module):
502
+ """Vision Transformer with support for patch or hybrid CNN input stage"""
503
+
504
+ def __init__(
505
+ self,
506
+ img_size=224,
507
+ patch_size=16,
508
+ in_chans=3,
509
+ num_classes=1000,
510
+ embed_dim=768,
511
+ depth=12,
512
+ num_heads=12,
513
+ mlp_ratio=4.0,
514
+ qkv_bias=False,
515
+ qk_scale=None,
516
+ drop_rate=0.0,
517
+ attn_drop_rate=0.0,
518
+ drop_path_rate=0.0,
519
+ norm_layer=nn.LayerNorm,
520
+ init_values=None,
521
+ patch_dropout=0.0,
522
+ use_abs_pos_emb=True,
523
+ use_rel_pos_bias=False,
524
+ use_shared_rel_pos_bias=False,
525
+ rope=False,
526
+ use_mean_pooling=True,
527
+ init_scale=0.001,
528
+ grad_checkpointing=False,
529
+ xattn=False,
530
+ postnorm=False,
531
+ pt_hw_seq_len=16,
532
+ intp_freq=False,
533
+ naiveswiglu=False,
534
+ subln=False,
535
+ ):
536
+ super().__init__()
537
+ self.image_size = img_size
538
+ self.num_classes = num_classes
539
+ self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
540
+
541
+ self.patch_embed = PatchEmbed(img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
542
+ num_patches = self.patch_embed.num_patches
543
+
544
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
545
+ # self.mask_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
546
+ if use_abs_pos_emb:
547
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
548
+ else:
549
+ self.pos_embed = None
550
+ self.pos_drop = nn.Dropout(p=drop_rate)
551
+
552
+ if use_shared_rel_pos_bias:
553
+ self.rel_pos_bias = RelativePositionBias(window_size=self.patch_embed.patch_shape, num_heads=num_heads)
554
+ else:
555
+ self.rel_pos_bias = None
556
+
557
+ if rope:
558
+ half_head_dim = embed_dim // num_heads // 2
559
+ hw_seq_len = img_size // patch_size
560
+ self.rope = VisionRotaryEmbeddingFast(
561
+ dim=half_head_dim,
562
+ pt_seq_len=pt_hw_seq_len,
563
+ ft_seq_len=hw_seq_len if intp_freq else None,
564
+ # patch_dropout=patch_dropout
565
+ )
566
+ else:
567
+ self.rope = None
568
+
569
+ self.naiveswiglu = naiveswiglu
570
+
571
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
572
+ self.use_rel_pos_bias = use_rel_pos_bias
573
+ self.blocks = nn.ModuleList(
574
+ [
575
+ Block(
576
+ dim=embed_dim,
577
+ num_heads=num_heads,
578
+ mlp_ratio=mlp_ratio,
579
+ qkv_bias=qkv_bias,
580
+ qk_scale=qk_scale,
581
+ drop=drop_rate,
582
+ attn_drop=attn_drop_rate,
583
+ drop_path=dpr[i],
584
+ norm_layer=norm_layer,
585
+ init_values=init_values,
586
+ window_size=self.patch_embed.patch_shape if use_rel_pos_bias else None,
587
+ xattn=xattn,
588
+ rope=self.rope,
589
+ postnorm=postnorm,
590
+ subln=subln,
591
+ naiveswiglu=naiveswiglu,
592
+ )
593
+ for i in range(depth)
594
+ ]
595
+ )
596
+ self.norm = nn.Identity() if use_mean_pooling else norm_layer(embed_dim)
597
+ self.fc_norm = norm_layer(embed_dim) if use_mean_pooling else None
598
+ self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity()
599
+
600
+ if self.pos_embed is not None:
601
+ trunc_normal_(self.pos_embed, std=0.02)
602
+
603
+ trunc_normal_(self.cls_token, std=0.02)
604
+ # trunc_normal_(self.mask_token, std=.02)
605
+
606
+ self.apply(self._init_weights)
607
+ self.fix_init_weight()
608
+
609
+ if isinstance(self.head, nn.Linear):
610
+ trunc_normal_(self.head.weight, std=0.02)
611
+ self.head.weight.data.mul_(init_scale)
612
+ self.head.bias.data.mul_(init_scale)
613
+
614
+ # setting a patch_dropout of 0. would mean it is disabled and this function would be the identity fn
615
+ self.patch_dropout = PatchDropout(patch_dropout) if patch_dropout > 0.0 else nn.Identity()
616
+
617
+ self.grad_checkpointing = grad_checkpointing
618
+
619
+ def fix_init_weight(self):
620
+ def rescale(param, layer_id):
621
+ param.div_(math.sqrt(2.0 * layer_id))
622
+
623
+ for layer_id, layer in enumerate(self.blocks):
624
+ rescale(layer.attn.proj.weight.data, layer_id + 1)
625
+ if self.naiveswiglu:
626
+ rescale(layer.mlp.w3.weight.data, layer_id + 1)
627
+ else:
628
+ rescale(layer.mlp.fc2.weight.data, layer_id + 1)
629
+
630
+ def get_cast_dtype(self) -> torch.dtype:
631
+ return self.blocks[0].mlp.fc2.weight.dtype
632
+
633
+ def _init_weights(self, m):
634
+ if isinstance(m, nn.Linear):
635
+ trunc_normal_(m.weight, std=0.02)
636
+ if m.bias is not None:
637
+ nn.init.constant_(m.bias, 0)
638
+ elif isinstance(m, nn.LayerNorm):
639
+ nn.init.constant_(m.bias, 0)
640
+ nn.init.constant_(m.weight, 1.0)
641
+
642
+ def get_num_layers(self):
643
+ return len(self.blocks)
644
+
645
+ def lock(self, unlocked_groups=0, freeze_bn_stats=False):
646
+ assert unlocked_groups == 0, "partial locking not currently supported for this model"
647
+ for param in self.parameters():
648
+ param.requires_grad = False
649
+
650
+ @torch.jit.ignore
651
+ def set_grad_checkpointing(self, enable=True):
652
+ self.grad_checkpointing = enable
653
+
654
+ @torch.jit.ignore
655
+ def no_weight_decay(self):
656
+ return {"pos_embed", "cls_token"}
657
+
658
+ def get_classifier(self):
659
+ return self.head
660
+
661
+ def reset_classifier(self, num_classes, global_pool=""):
662
+ self.num_classes = num_classes
663
+ self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
664
+
665
+ def forward_features(self, x, return_all_features=False):
666
+
667
+ x = self.patch_embed(x)
668
+ batch_size, seq_len, _ = x.size()
669
+
670
+ cls_tokens = self.cls_token.expand(batch_size, -1, -1) # stole cls_tokens impl from Phil Wang, thanks
671
+ x = torch.cat((cls_tokens, x), dim=1)
672
+ if self.pos_embed is not None:
673
+ x = x + self.pos_embed
674
+ x = self.pos_drop(x)
675
+
676
+ # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in
677
+ if os.getenv("RoPE") == "1":
678
+ if self.training and not isinstance(self.patch_dropout, nn.Identity):
679
+ x, patch_indices_keep = self.patch_dropout(x)
680
+ # Directly pass patch_indices_keep to self.rope.forward
681
+ x = self.rope.forward(x, patch_indices_keep=patch_indices_keep)
682
+ else:
683
+ # Pass None or omit the patch_indices_keep argument for default behavior
684
+ x = self.rope.forward(x, patch_indices_keep=None)
685
+ x = self.patch_dropout(x)
686
+ else:
687
+ x = self.patch_dropout(x)
688
+
689
+ rel_pos_bias = self.rel_pos_bias() if self.rel_pos_bias is not None else None
690
+ for i, blk in enumerate(self.blocks):
691
+ if i == len(self.blocks) - 1:
692
+ continue
693
+ if self.grad_checkpointing:
694
+ x = checkpoint(blk, x, (rel_pos_bias,))
695
+ else:
696
+ x = blk(x, rel_pos_bias=rel_pos_bias)
697
+
698
+ if not return_all_features:
699
+ x = self.norm(x)
700
+ if self.fc_norm is not None:
701
+ return self.fc_norm(x.mean(1))
702
+ else:
703
+ return x[:, 0]
704
+ return x
705
+
706
+ def forward(self, x, return_all_features=False):
707
+ if return_all_features:
708
+ return self.forward_features(x, return_all_features)
709
+ x = self.forward_features(x)
710
+ x = self.head(x)
711
+ return x
712
+
713
+
714
+ def load_state_dict(checkpoint_path: str, map_location: str = "cpu", model_key: str = "model|module|state_dict", is_openai: bool = False, skip_list: list = []):
715
+ if is_openai:
716
+ model = torch.jit.load(checkpoint_path, map_location="cpu").eval()
717
+ state_dict = model.state_dict()
718
+ for key in ["input_resolution", "context_length", "vocab_size"]:
719
+ state_dict.pop(key, None)
720
+ else:
721
+ checkpoint = torch.load(checkpoint_path, map_location=map_location)
722
+ for mk in model_key.split("|"):
723
+ if isinstance(checkpoint, dict) and mk in checkpoint:
724
+ state_dict = checkpoint[mk]
725
+ break
726
+ else:
727
+ state_dict = checkpoint
728
+ if next(iter(state_dict.items()))[0].startswith("module"):
729
+ state_dict = {k[7:]: v for k, v in state_dict.items()}
730
+
731
+ for k in skip_list:
732
+ if k in list(state_dict.keys()):
733
+ logging.info(f"Removing key {k} from pretrained checkpoint")
734
+ del state_dict[k]
735
+
736
+ if os.getenv("RoPE") == "1":
737
+ for k in list(state_dict.keys()):
738
+ if "freqs_cos" in k or "freqs_sin" in k:
739
+ del state_dict[k]
740
+ return state_dict
741
+
742
+
743
+ def load_clip_visual_state_dict(checkpoint_path: str, map_location: str = "cpu", is_openai: bool = False, skip_list: list = []):
744
+ state_dict = load_state_dict(checkpoint_path, map_location=map_location, is_openai=is_openai, skip_list=skip_list)
745
+ # for k in list(state_dict.keys()):
746
+ # if not k.startswith("visual."):
747
+ # del state_dict[k]
748
+ # for k in list(state_dict.keys()):
749
+ # if k.startswith("visual."):
750
+ # new_k = k[7:]
751
+ # state_dict[new_k] = state_dict[k]
752
+ # del state_dict[k]
753
+ return state_dict
754
+
755
+
756
+ from dataclasses import dataclass
757
+ from typing import Optional, Tuple, Union
758
+
759
+ try:
760
+ from apex.normalization import FusedLayerNorm
761
+ except:
762
+ FusedLayerNorm = LayerNorm
763
+ # print("Please build and install Nvidia apex package with option '--cuda_ext' according to https://github.com/NVIDIA/apex#from-source .")
764
+
765
+
766
+ @dataclass
767
+ class CLIPVisionCfg:
768
+ layers: Union[Tuple[int, int, int, int], int] = 12
769
+ width: int = 768
770
+ head_width: int = 64
771
+ mlp_ratio: float = 4.0
772
+ patch_size: int = 16
773
+ image_size: Union[Tuple[int, int], int] = 224
774
+ ls_init_value: Optional[float] = None # layer scale initial value
775
+ patch_dropout: float = 0.0 # what fraction of patches to dropout during training (0 would mean disabled and no patches dropped) - 0.5 to 0.75 recommended in the paper for optimal results
776
+ global_average_pool: bool = False # whether to global average pool the last embedding layer, instead of using CLS token (https://arxiv.org/abs/2205.01580)
777
+ drop_path_rate: Optional[float] = None # drop path rate
778
+ timm_model_name: str = None # a valid model name overrides layers, width, patch_size
779
+ timm_model_pretrained: bool = False # use (imagenet) pretrained weights for named model
780
+ timm_pool: str = "avg" # feature pooling for timm model ('abs_attn', 'rot_attn', 'avg', '')
781
+ timm_proj: str = "linear" # linear projection for timm model output ('linear', 'mlp', '')
782
+ timm_proj_bias: bool = False # enable bias final projection
783
+ eva_model_name: str = None # a valid eva model name overrides layers, width, patch_size
784
+ qkv_bias: bool = True
785
+ fusedLN: bool = False
786
+ xattn: bool = False
787
+ postnorm: bool = False
788
+ rope: bool = False
789
+ pt_hw_seq_len: int = 16 # 224/14
790
+ intp_freq: bool = False
791
+ naiveswiglu: bool = False
792
+ subln: bool = False
793
+
794
+
795
+ def create_norm_layer_factory(use_fused_ln, eps=1e-6):
796
+ # Otherwise, use the standard LayerNorm
797
+ return lambda num_features: nn.LayerNorm(num_features, eps=eps)
798
+
799
+
800
+ def _build_vision_tower(vision_tower_path: str, embed_dim: int, vision_cfg: CLIPVisionCfg, **kwargs):
801
+ if isinstance(vision_cfg, dict):
802
+ vision_cfg = CLIPVisionCfg(**vision_cfg)
803
+
804
+ if vision_cfg.eva_model_name:
805
+ vision_heads = vision_cfg.width // vision_cfg.head_width
806
+ # Determine the appropriate norm layer factory based on the configuration
807
+ norm_layer_factory = create_norm_layer_factory(vision_cfg.fusedLN, eps=1e-6)
808
+
809
+ visual = EVAVisionTransformer(
810
+ img_size=vision_cfg.image_size,
811
+ patch_size=vision_cfg.patch_size,
812
+ num_classes=embed_dim,
813
+ use_mean_pooling=vision_cfg.global_average_pool, # False
814
+ init_values=vision_cfg.ls_init_value,
815
+ patch_dropout=vision_cfg.patch_dropout,
816
+ embed_dim=vision_cfg.width,
817
+ depth=vision_cfg.layers,
818
+ num_heads=vision_heads,
819
+ mlp_ratio=vision_cfg.mlp_ratio,
820
+ qkv_bias=vision_cfg.qkv_bias,
821
+ drop_path_rate=vision_cfg.drop_path_rate,
822
+ norm_layer=norm_layer_factory,
823
+ xattn=vision_cfg.xattn,
824
+ rope=vision_cfg.rope,
825
+ postnorm=vision_cfg.postnorm,
826
+ pt_hw_seq_len=vision_cfg.pt_hw_seq_len, # 224/14
827
+ intp_freq=vision_cfg.intp_freq,
828
+ naiveswiglu=vision_cfg.naiveswiglu,
829
+ subln=vision_cfg.subln,
830
+ )
831
+
832
+ state_dict = load_clip_visual_state_dict(vision_tower_path)
833
+ incompatible_keys = visual.load_state_dict(state_dict, strict=False)
834
+ rank0_print("EVA-CLIP incompatible_keys:", incompatible_keys)
835
+
836
+ return visual
837
+
838
+
839
+ class EVAEncoderWrapper(nn.Module):
840
+ def __init__(self, vision_tower_pretrained, config):
841
+ super(EVAEncoderWrapper, self).__init__()
842
+ self.config = config
843
+ self.config["vision_tower_path"] = vision_tower_pretrained
844
+ self.model = _build_vision_tower(**self.config)
845
+
846
+ def forward(self, image, **kwargs):
847
+ encode = self.model(image, return_all_features=True)[:, 1:, :] # remove the CLS token
848
+ return encode
849
+
850
+ @property
851
+ def dtype(self):
852
+ return list(self.parameters())[-1].dtype
853
+
854
+ @property
855
+ def device(self):
856
+ return list(self.parameters())[-1].device
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/factory.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ import os
4
+ import pathlib
5
+ import re
6
+ from copy import deepcopy
7
+ from pathlib import Path
8
+ from typing import Optional, Tuple, Union, Dict, Any
9
+ import torch
10
+
11
+ _MODEL_CONFIG_PATHS = [Path(__file__).parent / f"model_configs/"]
12
+ _MODEL_CONFIGS = {} # directory (model_name: config) of model architecture configs
13
+
14
+
15
+ def _natural_key(string_):
16
+ return [int(s) if s.isdigit() else s for s in re.split(r"(\d+)", string_.lower())]
17
+
18
+
19
+ def _rescan_model_configs():
20
+ global _MODEL_CONFIGS
21
+
22
+ config_ext = (".json",)
23
+ config_files = []
24
+ for config_path in _MODEL_CONFIG_PATHS:
25
+ if config_path.is_file() and config_path.suffix in config_ext:
26
+ config_files.append(config_path)
27
+ elif config_path.is_dir():
28
+ for ext in config_ext:
29
+ config_files.extend(config_path.glob(f"*{ext}"))
30
+
31
+ for cf in config_files:
32
+ with open(cf, "r", encoding="utf8") as f:
33
+ model_cfg = json.load(f)
34
+ if all(a in model_cfg for a in ("embed_dim", "vision_cfg", "text_cfg")):
35
+ _MODEL_CONFIGS[cf.stem] = model_cfg
36
+
37
+ _MODEL_CONFIGS = dict(sorted(_MODEL_CONFIGS.items(), key=lambda x: _natural_key(x[0])))
38
+
39
+
40
+ _rescan_model_configs() # initial populate of model config registry
41
+
42
+
43
+ def list_models():
44
+ """enumerate available model architectures based on config files"""
45
+ return list(_MODEL_CONFIGS.keys())
46
+
47
+
48
+ def add_model_config(path):
49
+ """add model config path or file and update registry"""
50
+ if not isinstance(path, Path):
51
+ path = Path(path)
52
+ _MODEL_CONFIG_PATHS.append(path)
53
+ _rescan_model_configs()
54
+
55
+
56
+ def get_model_config(model_name):
57
+ if model_name in _MODEL_CONFIGS:
58
+ return deepcopy(_MODEL_CONFIGS[model_name])
59
+ else:
60
+ return None
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA-CLIP-18B.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1536,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 48,
6
+ "width": 5120,
7
+ "head_width": 128,
8
+ "mlp_ratio": 5,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-18b-14-x",
11
+ "drop_path_rate": 0,
12
+ "qkv_bias": false,
13
+ "xattn": true,
14
+ "postnorm": true,
15
+ "fusedLN": false,
16
+ "use_rms_norm": true
17
+ },
18
+ "text_cfg": {
19
+ "context_length": 77,
20
+ "vocab_size": 49408,
21
+ "width": 1280,
22
+ "heads": 20,
23
+ "layers": 32,
24
+ "xattn": false,
25
+ "fusedLN": false
26
+ }
27
+ }
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA-CLIP-8B-plus.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1280,
3
+ "vision_cfg": {
4
+ "image_size": 448,
5
+ "layers": 32,
6
+ "width": 4096,
7
+ "head_width": 128,
8
+ "mlp_ratio": 5,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-8b-14-plus-x",
11
+ "drop_path_rate": 0,
12
+ "qkv_bias": false,
13
+ "xattn": true,
14
+ "postnorm": false,
15
+ "fusedLN": false,
16
+ "use_rms_norm": true
17
+ },
18
+ "text_cfg": {
19
+ "context_length": 77,
20
+ "vocab_size": 49408,
21
+ "width": 1280,
22
+ "heads": 20,
23
+ "layers": 32,
24
+ "xattn": false,
25
+ "fusedLN": false
26
+ }
27
+ }
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA-CLIP-8B.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1280,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 32,
6
+ "width": 4096,
7
+ "head_width": 128,
8
+ "mlp_ratio": 5,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-8b-14-x",
11
+ "drop_path_rate": 0,
12
+ "qkv_bias": false,
13
+ "xattn": true,
14
+ "postnorm": false,
15
+ "fusedLN": false,
16
+ "use_rms_norm": true
17
+ },
18
+ "text_cfg": {
19
+ "context_length": 77,
20
+ "vocab_size": 49408,
21
+ "width": 1280,
22
+ "heads": 20,
23
+ "layers": 32,
24
+ "xattn": false,
25
+ "fusedLN": false
26
+ }
27
+ }
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA01-CLIP-B-16.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 512,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 12,
6
+ "width": 768,
7
+ "patch_size": 16,
8
+ "eva_model_name": "eva-clip-b-16",
9
+ "ls_init_value": 0.1,
10
+ "drop_path_rate": 0.0
11
+ },
12
+ "text_cfg": {
13
+ "context_length": 77,
14
+ "vocab_size": 49408,
15
+ "width": 512,
16
+ "heads": 8,
17
+ "layers": 12
18
+ }
19
+ }
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA01-CLIP-g-14-plus.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1024,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 40,
6
+ "width": 1408,
7
+ "head_width": 88,
8
+ "mlp_ratio": 4.3637,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-g-14-x",
11
+ "drop_path_rate": 0,
12
+ "xattn": true,
13
+ "fusedLN": true
14
+ },
15
+ "text_cfg": {
16
+ "context_length": 77,
17
+ "vocab_size": 49408,
18
+ "width": 1024,
19
+ "heads": 16,
20
+ "layers": 24,
21
+ "xattn": false,
22
+ "fusedLN": true
23
+ }
24
+ }
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA01-CLIP-g-14.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1024,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 40,
6
+ "width": 1408,
7
+ "head_width": 88,
8
+ "mlp_ratio": 4.3637,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-g-14-x",
11
+ "drop_path_rate": 0.4,
12
+ "xattn": true,
13
+ "fusedLN": true
14
+ },
15
+ "text_cfg": {
16
+ "context_length": 77,
17
+ "vocab_size": 49408,
18
+ "width": 768,
19
+ "heads": 12,
20
+ "layers": 12,
21
+ "xattn": false,
22
+ "fusedLN": true
23
+ }
24
+ }
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-B-16.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 512,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 12,
6
+ "width": 768,
7
+ "head_width": 64,
8
+ "patch_size": 16,
9
+ "mlp_ratio": 2.6667,
10
+ "eva_model_name": "eva-clip-b-16-X",
11
+ "drop_path_rate": 0.0,
12
+ "xattn": true,
13
+ "fusedLN": true,
14
+ "rope": true,
15
+ "pt_hw_seq_len": 16,
16
+ "intp_freq": true,
17
+ "naiveswiglu": true,
18
+ "subln": true
19
+ },
20
+ "text_cfg": {
21
+ "context_length": 77,
22
+ "vocab_size": 49408,
23
+ "width": 512,
24
+ "heads": 8,
25
+ "layers": 12,
26
+ "xattn": true,
27
+ "fusedLN": true
28
+ }
29
+ }
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-L-14-336.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 768,
3
+ "vision_cfg": {
4
+ "image_size": 336,
5
+ "layers": 24,
6
+ "width": 1024,
7
+ "drop_path_rate": 0,
8
+ "head_width": 64,
9
+ "mlp_ratio": 2.6667,
10
+ "patch_size": 14,
11
+ "eva_model_name": "eva-clip-l-14-336",
12
+ "xattn": true,
13
+ "fusedLN": true,
14
+ "rope": true,
15
+ "pt_hw_seq_len": 16,
16
+ "intp_freq": true,
17
+ "naiveswiglu": true,
18
+ "subln": true
19
+ },
20
+ "text_cfg": {
21
+ "context_length": 77,
22
+ "vocab_size": 49408,
23
+ "width": 768,
24
+ "heads": 12,
25
+ "layers": 12,
26
+ "xattn": false,
27
+ "fusedLN": true
28
+ }
29
+ }
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-L-14.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 768,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 24,
6
+ "width": 1024,
7
+ "drop_path_rate": 0,
8
+ "head_width": 64,
9
+ "mlp_ratio": 2.6667,
10
+ "patch_size": 14,
11
+ "eva_model_name": "eva-clip-l-14",
12
+ "xattn": true,
13
+ "fusedLN": true,
14
+ "rope": true,
15
+ "pt_hw_seq_len": 16,
16
+ "intp_freq": true,
17
+ "naiveswiglu": true,
18
+ "subln": true
19
+ },
20
+ "text_cfg": {
21
+ "context_length": 77,
22
+ "vocab_size": 49408,
23
+ "width": 768,
24
+ "heads": 12,
25
+ "layers": 12,
26
+ "xattn": false,
27
+ "fusedLN": true
28
+ }
29
+ }
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-bigE-14-plus.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1024,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 64,
6
+ "width": 1792,
7
+ "head_width": 112,
8
+ "mlp_ratio": 8.571428571428571,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-4b-14-x",
11
+ "drop_path_rate": 0,
12
+ "xattn": true,
13
+ "postnorm": true,
14
+ "fusedLN": true
15
+ },
16
+ "text_cfg": {
17
+ "context_length": 77,
18
+ "vocab_size": 49408,
19
+ "width": 1280,
20
+ "heads": 20,
21
+ "layers": 32,
22
+ "xattn": false,
23
+ "fusedLN": true
24
+ }
25
+ }
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-bigE-14.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1024,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 64,
6
+ "width": 1792,
7
+ "head_width": 112,
8
+ "mlp_ratio": 8.571428571428571,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-4b-14-x",
11
+ "drop_path_rate": 0,
12
+ "xattn": true,
13
+ "postnorm": true,
14
+ "fusedLN": true
15
+ },
16
+ "text_cfg": {
17
+ "context_length": 77,
18
+ "vocab_size": 49408,
19
+ "width": 1024,
20
+ "heads": 16,
21
+ "layers": 24,
22
+ "xattn": false,
23
+ "fusedLN": true
24
+ }
25
+ }
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/Internal-EVA02-CLIP-10B-14-448.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1024,
3
+ "vision_cfg": {
4
+ "image_size": 448,
5
+ "layers": 77,
6
+ "width": 2304,
7
+ "head_width": 144,
8
+ "mlp_ratio": 10.9722,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-10b-14-x",
11
+ "drop_path_rate": 0,
12
+ "xattn": true,
13
+ "postnorm": false,
14
+ "fusedLN": true
15
+ },
16
+ "text_cfg": {
17
+ "context_length": 77,
18
+ "vocab_size": 49408,
19
+ "width": 1280,
20
+ "heads": 20,
21
+ "layers": 32,
22
+ "xattn": false,
23
+ "fusedLN": true
24
+ }
25
+ }
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/Internal-EVA02-CLIP-10B-14.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1024,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 77,
6
+ "width": 2304,
7
+ "head_width": 144,
8
+ "mlp_ratio": 10.9722,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-10b-14-x",
11
+ "drop_path_rate": 0,
12
+ "xattn": true,
13
+ "postnorm": false,
14
+ "fusedLN": true
15
+ },
16
+ "text_cfg": {
17
+ "context_length": 77,
18
+ "vocab_size": 49408,
19
+ "width": 1280,
20
+ "heads": 20,
21
+ "layers": 32,
22
+ "xattn": false,
23
+ "fusedLN": true
24
+ }
25
+ }
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/hf_vision.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from transformers import AutoModel, AutoImageProcessor, AutoConfig, CLIPImageProcessor
5
+ from llava.utils import rank0_print
6
+
7
+
8
+ class HFVisionTower(nn.Module):
9
+ def __init__(self, vision_tower, args, delay_load=False):
10
+ super().__init__()
11
+
12
+ self.is_loaded = False
13
+
14
+ self.vision_tower_name = vision_tower.replace("hf:", "", 1)
15
+ self.select_layer = args.mm_vision_select_layer
16
+ self.select_feature = getattr(args, "mm_vision_select_feature", "patch")
17
+
18
+ if not delay_load:
19
+ self.load_model()
20
+ else:
21
+ self.cfg_only = AutoConfig.from_pretrained(self.vision_tower_name)
22
+
23
+ def load_model(self):
24
+ try:
25
+ self.image_processor = AutoImageProcessor.from_pretrained(self.vision_tower_name)
26
+ except Exception as e:
27
+ if "448" in self.vision_tower_name:
28
+ image_size = 448
29
+ # use image processor with conig
30
+ self.image_processor = CLIPImageProcessor(size={"shortest_edge": image_size}, do_center_crop=True, crop_size=image_size)
31
+ else:
32
+ self.image_processor = CLIPImageProcessor.from_pretrained("openai/clip-vit-large-patch14")
33
+ rank0_print(f"Loaded image processor: {self.image_processor}")
34
+ self.vision_tower = AutoModel.from_pretrained(self.vision_tower_name, torch_dtype=torch.bfloat16, trust_remote_code=True).to("cuda")
35
+ self.device = self.vision_tower.device
36
+ self.dtype = self.vision_tower.dtype
37
+ self.config = self.vision_tower.config
38
+
39
+ if hasattr(self.vision_tower, "vision_model"):
40
+ self.vision_tower = self.vision_tower.vision_model
41
+ self.vision_tower.requires_grad_(False)
42
+ # self.vision_tower.eval()
43
+ self.is_loaded = True
44
+
45
+ def feature_select(self, image_forward_outs):
46
+ select_feature_type = self.select_feature
47
+
48
+ if self.select_feature in ["slicefour_patch", "slicefour_cls_patch"]:
49
+ select_every_k_layer = len(image_forward_outs.hidden_states) // 4
50
+ image_features = torch.cat([image_forward_outs.hidden_states[i] for i in range(select_every_k_layer + self.select_layer, len(image_forward_outs.hidden_states), select_every_k_layer)], dim=-1)
51
+ select_feature_type = select_feature_type.replace("slicefour_", "")
52
+ else:
53
+ image_features = image_forward_outs.hidden_states[self.select_layer]
54
+
55
+ if select_feature_type == "patch":
56
+ image_features = image_features[:, 1:]
57
+ elif select_feature_type == "cls_patch":
58
+ image_features = image_features
59
+ else:
60
+ raise ValueError(f"Unexpected select feature: {select_feature_type}")
61
+ return image_features
62
+
63
+ def forward(self, images):
64
+ if type(images) is list:
65
+ image_features = []
66
+ for image in images:
67
+ image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
68
+ image_feature = self.feature_select(image_forward_out).to(image.dtype)
69
+ image_features.append(image_feature)
70
+ else:
71
+ image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
72
+ image_features = self.feature_select(image_forward_outs).to(images.dtype)
73
+
74
+ return image_features
75
+
76
+ @property
77
+ def dummy_feature(self):
78
+ return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
79
+
80
+ # @property
81
+ # def dtype(self):
82
+ # return self.vision_tower.dtype
83
+
84
+ # @property
85
+ # def device(self):
86
+ # return self.vision_tower.device
87
+
88
+ @property
89
+ def hidden_size(self):
90
+ try:
91
+ _hidden_size = self.config.hidden_size
92
+ except:
93
+ _hidden_size = self.config.vision_config.hidden_size
94
+ if "slicefour" in self.select_feature:
95
+ _hidden_size *= 4
96
+ return _hidden_size
97
+
98
+ @property
99
+ def num_patches(self):
100
+ _num_patches = (self.config.image_size // self.config.patch_size) ** 2
101
+ if "cls_patch" in self.select_feature:
102
+ _num_patches += 1
103
+ return _num_patches
104
+
105
+ @property
106
+ def num_patches_per_side(self):
107
+ return self.config.image_size // self.config.patch_size
108
+
109
+ @property
110
+ def image_size(self):
111
+ return self.config.image_size
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/imagebind.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from transformers import CLIPImageProcessor
5
+
6
+ try:
7
+ from imagebind.models import imagebind_model
8
+ from imagebind.models.imagebind_model import ModalityType
9
+ from imagebind.data import load_and_transform_audio_data
10
+ except ImportError:
11
+ pass
12
+
13
+
14
+ class ImageBindWrapper(nn.Module):
15
+ def __init__(self, vision_tower, select_layer, select_feature="patch", delay_load=False):
16
+ super().__init__()
17
+
18
+ self.is_loaded = False
19
+
20
+ self.vision_tower_name = vision_tower
21
+ self.select_layer = select_layer
22
+ self.select_feature = select_feature
23
+
24
+ if not delay_load:
25
+ self.load_model()
26
+
27
+ def load_model(self):
28
+ self.image_processor = CLIPImageProcessor.from_pretrained("openai/clip-vit-large-patch14")
29
+ self.vision_tower = imagebind_model.imagebind_huge(pretrained=True)
30
+ for p in self.vision_tower.parameters():
31
+ p.requires_grad = False
32
+ self.vision_tower.eval()
33
+ self.is_loaded = True
34
+
35
+ def train(self, mode=True):
36
+ self.training = mode
37
+
38
+ if self.is_loaded:
39
+ self.vision_tower.eval()
40
+
41
+ @torch.no_grad()
42
+ def forward(self, x):
43
+ if type(x) == dict:
44
+ if x["audios"] is not None:
45
+ inputs = {ModalityType.AUDIO: load_and_transform_audio_data(x["audios"], device=self.device).half()}
46
+ embeddings = self.vision_tower(inputs)
47
+ audio_embedding = embeddings[ModalityType.AUDIO]
48
+ return audio_embedding.unsqueeze(1)
49
+ else:
50
+ inputs = {ModalityType.VISION: x.to(dtype=self.dtype)}
51
+ embeddings = self.vision_tower(inputs)
52
+ vision_embedding = embeddings[ModalityType.VISION]
53
+ if vision_embedding.ndim == 2:
54
+ return vision_embedding.unsqueeze(1)
55
+ if vision_embedding.shape[1] == 257:
56
+ return vision_embedding[:, 1:]
57
+ raise ValueError(f"Unexpected shape: {vision_embedding.shape}")
58
+
59
+ @property
60
+ def dummy_feature(self):
61
+ return torch.zeros(1, 1024, device=self.device, dtype=self.dtype)
62
+
63
+ @property
64
+ def dtype(self):
65
+ return self.vision_tower.modality_preprocessors.vision.cls_token.dtype
66
+
67
+ @property
68
+ def device(self):
69
+ return self.vision_tower.modality_preprocessors.vision.cls_token.device
70
+
71
+ @property
72
+ def hidden_size(self):
73
+ return 1024
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/open_clip_encoder.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from transformers import CLIPImageProcessor
4
+ from llava.utils import rank0_print
5
+
6
+ try:
7
+ import open_clip
8
+ import torchvision
9
+ from open_clip.transformer import _expand_token
10
+ except ImportError:
11
+ print("OpenCLIP not installed")
12
+ open_clip = None
13
+
14
+ HIDDEN_SIZE_DICT = {
15
+ "ViT-H-14-378-quickgelu": 1280,
16
+ }
17
+
18
+
19
+ class OpenCLIPVisionTower(nn.Module):
20
+ def __init__(self, vision_tower, args, delay_load=False):
21
+ super().__init__()
22
+
23
+ self.is_loaded = False
24
+ self.model_name = vision_tower.replace("open_clip_hub:", "")
25
+ self.pretrained = args.vision_tower_pretrained
26
+ self.select_layer = args.mm_vision_select_layer
27
+ self.select_feature = getattr(args, "mm_vision_select_feature", "patch")
28
+
29
+ if not delay_load:
30
+ rank0_print(f"Loading vision tower: {vision_tower}")
31
+ self.load_model()
32
+ elif getattr(args, "unfreeze_mm_vision_tower", False):
33
+ # TODO: better detector is needed.
34
+ rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `unfreeze_mm_vision_tower`: True.")
35
+ self.load_model()
36
+ elif hasattr(args, "mm_tunable_parts") and "mm_vision_tower" in args.mm_tunable_parts:
37
+ rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `mm_tunable_parts` contains `mm_vision_tower`.")
38
+ self.load_model()
39
+
40
+ def load_model(self, device_map="auto"):
41
+ rank0_print(f"Loading OpenCLIP model: {self.model_name}")
42
+ rank0_print(f"Pretrained: {self.pretrained}")
43
+ vision_tower, _, image_processor = open_clip.create_model_and_transforms(model_name=self.model_name, pretrained=self.pretrained, precision="fp32", device="cuda")
44
+
45
+ resize_transform = [t for t in image_processor.transforms if isinstance(t, torchvision.transforms.Resize)][0]
46
+ normalize_transform = [t for t in image_processor.transforms if isinstance(t, torchvision.transforms.Normalize)][0]
47
+ self.resize_transform_size = resize_transform.size # 224 or 384
48
+ self.patch_size = vision_tower.visual.conv1.kernel_size[0] # 14 or 16
49
+
50
+ self.image_processor = CLIPImageProcessor.from_pretrained(
51
+ "openai/clip-vit-large-patch14",
52
+ crop_size=resize_transform.size,
53
+ size={"shortest_edge": resize_transform.size},
54
+ image_mean=list(normalize_transform.mean),
55
+ image_std=list(normalize_transform.std),
56
+ )
57
+ rank0_print(f"Loaded image processor: {self.image_processor}")
58
+ self.vision_tower = vision_tower.visual
59
+ self.vision_tower.requires_grad_(False)
60
+
61
+ self.is_loaded = True
62
+
63
+ def feature_select(self, image_forward_outs):
64
+ image_features = image_forward_outs[self.select_layer]
65
+ if self.select_feature == "patch":
66
+ image_features = image_features[:, 1:]
67
+ elif self.select_feature == "cls_patch":
68
+ image_features = image_features
69
+ elif self.select_feature == "conv_flatten":
70
+ image_features = image_features.flatten(2).transpose(1, 2)
71
+ else:
72
+ raise ValueError(f"Unexpected select feature: {self.select_feature}")
73
+ return image_features
74
+
75
+ def forward_visual(self, x, output_hidden_states=False):
76
+ if hasattr(self.vision_tower, "trunk") and hasattr(self.vision_tower.trunk, "_intermediate_layers"):
77
+ return self.vision_tower.trunk._intermediate_layers(x, abs(self.select_layer))
78
+ else:
79
+
80
+ def forward_openclip(self, x: torch.Tensor):
81
+ features = []
82
+ x = self.conv1(x) # shape = [*, width, grid, grid]
83
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
84
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
85
+
86
+ # class embeddings and positional embeddings
87
+ x = torch.cat(
88
+ [_expand_token(self.class_embedding, x.shape[0]).to(x.dtype), x],
89
+ dim=1,
90
+ )
91
+ # shape = [*, grid ** 2 + 1, width]
92
+ x = x + self.positional_embedding.to(x.dtype)
93
+
94
+ x = self.patch_dropout(x)
95
+ x = self.ln_pre(x)
96
+
97
+ x = x.permute(1, 0, 2) # NLD -> LND
98
+ for r in self.transformer.resblocks:
99
+ x = r(x, attn_mask=None)
100
+ features.append(x)
101
+ return features
102
+
103
+ return forward_openclip(self.vision_tower, x)
104
+
105
+ def forward(self, images):
106
+ if type(images) is list:
107
+ image_features = []
108
+ for image in images:
109
+ image_forward_out = self.forward_visual(image.to(self.dtype).unsqueeze(0), output_hidden_states=True)
110
+ image_feature = self.feature_select(image_forward_out).to(image.dtype)
111
+ image_features.append(image_feature)
112
+ else:
113
+ image_forward_outs = self.forward_visual(images.to(self.dtype), output_hidden_states=True)
114
+ image_features = self.feature_select(image_forward_outs).to(images.dtype)
115
+
116
+ return image_features
117
+
118
+ @property
119
+ def dummy_feature(self):
120
+ return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
121
+
122
+ @property
123
+ def dtype(self):
124
+ if hasattr(self.vision_tower, "conv1"):
125
+ return self.vision_tower.conv1.weight.dtype
126
+ if hasattr(self.vision_tower, "trunk"):
127
+ return self.vision_tower.trunk.patch_embed.proj.weight.dtype
128
+ raise NotImplementedError
129
+
130
+ @property
131
+ def device(self):
132
+ if hasattr(self.vision_tower, "conv1"):
133
+ return self.vision_tower.conv1.weight.device
134
+ if hasattr(self.vision_tower, "trunk"):
135
+ return self.vision_tower.trunk.patch_embed.proj.weight.device
136
+ raise NotImplementedError
137
+
138
+ @property
139
+ def config(self):
140
+ return None
141
+
142
+ @property
143
+ def hidden_size(self):
144
+ if self.model_name in HIDDEN_SIZE_DICT:
145
+ return HIDDEN_SIZE_DICT[self.model_name]
146
+ else:
147
+ raise NotImplementedError
148
+
149
+ @property
150
+ def num_patches(self):
151
+ image_size = self.resize_transform_size if isinstance(self.resize_transform_size, int) else self.resize_transform_size[0]
152
+ _num_patches = (image_size // self.patch_size) ** 2
153
+ if "cls_patch" in self.select_feature:
154
+ _num_patches += 1
155
+ return _num_patches
156
+
157
+ @property
158
+ def image_size(self):
159
+ return self.resize_transform_size
160
+
161
+ @property
162
+ def num_patches_per_side(self):
163
+ return self.resize_transform_size // self.patch_size
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_encoder/siglip_encoder.py ADDED
@@ -0,0 +1,620 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ # Adapted from https://huggingface.co/MILVLG/imp-v1-3b/blob/main/vision_encoder.py
3
+ """
4
+
5
+ from typing import Optional, Tuple, Union, Dict
6
+ from dataclasses import dataclass
7
+ from functools import partial, reduce
8
+ from PIL import Image
9
+ import torch
10
+ import torch.utils.checkpoint
11
+ from torch import nn
12
+ import os
13
+ from transformers.image_processing_utils import BatchFeature, get_size_dict
14
+ from transformers.image_transforms import (
15
+ convert_to_rgb,
16
+ normalize,
17
+ rescale,
18
+ resize,
19
+ to_channel_dimension_format,
20
+ )
21
+ from transformers.image_utils import (
22
+ ChannelDimension,
23
+ PILImageResampling,
24
+ to_numpy_array,
25
+ )
26
+ from transformers.activations import ACT2FN
27
+ from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
28
+ from transformers.modeling_utils import PreTrainedModel
29
+ from transformers import PretrainedConfig
30
+ from transformers.utils import ModelOutput
31
+ from llava.utils import rank0_print
32
+
33
+
34
+ class SigLipImageProcessor:
35
+ def __init__(self, image_mean=(0.5, 0.5, 0.5), image_std=(0.5, 0.5, 0.5), size=(384, 384), crop_size: Dict[str, int] = None, resample=PILImageResampling.BICUBIC, rescale_factor=1 / 255, data_format=ChannelDimension.FIRST):
36
+ crop_size = crop_size if crop_size is not None else {"height": 384, "width": 384}
37
+ crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size")
38
+
39
+ self.image_mean = image_mean
40
+ self.image_std = image_std
41
+ self.size = size
42
+ self.resample = resample
43
+ self.rescale_factor = rescale_factor
44
+ self.data_format = data_format
45
+ self.crop_size = crop_size
46
+
47
+ def preprocess(self, images, return_tensors):
48
+ if isinstance(images, Image.Image):
49
+ images = [images]
50
+ else:
51
+ # to adapt video data
52
+ images = [to_numpy_array(image) for image in images]
53
+ assert isinstance(images, list)
54
+
55
+ transforms = [
56
+ convert_to_rgb,
57
+ to_numpy_array,
58
+ partial(resize, size=self.size, resample=self.resample, data_format=self.data_format),
59
+ partial(rescale, scale=self.rescale_factor, data_format=self.data_format),
60
+ partial(normalize, mean=self.image_mean, std=self.image_std, data_format=self.data_format),
61
+ partial(to_channel_dimension_format, channel_dim=self.data_format, input_channel_dim=self.data_format),
62
+ ]
63
+
64
+ images = reduce(lambda x, f: [*map(f, x)], transforms, images)
65
+ data = {"pixel_values": images}
66
+
67
+ return BatchFeature(data=data, tensor_type=return_tensors)
68
+
69
+
70
+ class SigLipVisionConfig(PretrainedConfig):
71
+ model_type = "siglip_vision_model"
72
+
73
+ def __init__(
74
+ self,
75
+ hidden_size=1152,
76
+ image_mean=(0.5, 0.5, 0.5),
77
+ intermediate_size=4304,
78
+ num_hidden_layers=27,
79
+ num_attention_heads=16,
80
+ num_channels=3,
81
+ image_size=384,
82
+ patch_size=14,
83
+ hidden_act="gelu_pytorch_tanh",
84
+ layer_norm_eps=1e-6,
85
+ attention_dropout=0.0,
86
+ **kwargs,
87
+ ):
88
+ super().__init__(**kwargs)
89
+
90
+ self.hidden_size = hidden_size
91
+ self.intermediate_size = intermediate_size
92
+ self.num_hidden_layers = num_hidden_layers
93
+ self.num_attention_heads = num_attention_heads
94
+ self.num_channels = num_channels
95
+ self.patch_size = patch_size
96
+ self.image_size = image_size
97
+ self.attention_dropout = attention_dropout
98
+ self.layer_norm_eps = layer_norm_eps
99
+ self.hidden_act = hidden_act
100
+ self.image_mean = image_mean
101
+
102
+ @classmethod
103
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
104
+ cls._set_token_in_kwargs(kwargs)
105
+
106
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
107
+
108
+ # get the vision config dict if we are loading from SigLipConfig
109
+ if config_dict.get("model_type") == "siglip":
110
+ config_dict = config_dict["vision_config"]
111
+
112
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
113
+ print(f"You are using a model of type {config_dict['model_type']} to instantiate a model of type " f"{cls.model_type}. This is not supported for all configurations of models and can yield errors.")
114
+
115
+ return cls.from_dict(config_dict, **kwargs)
116
+
117
+
118
+ @dataclass
119
+ # Copied from transformers.models.clip.modeling_clip.CLIPVisionModelOutput with CLIP->SigLip
120
+ class SigLipVisionModelOutput(ModelOutput):
121
+ """
122
+ Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
123
+
124
+ Args:
125
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
126
+ The image embeddings obtained by applying the projection layer to the pooler_output.
127
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
128
+ Sequence of hidden-states at the output of the last layer of the model.
129
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
130
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
131
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
132
+
133
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
134
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
135
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
136
+ sequence_length)`.
137
+
138
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
139
+ heads.
140
+ """
141
+
142
+ image_embeds: Optional[torch.FloatTensor] = None
143
+ last_hidden_state: torch.FloatTensor = None
144
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
145
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
146
+
147
+
148
+ class SigLipVisionEmbeddings(nn.Module):
149
+ def __init__(self, config: SigLipVisionConfig):
150
+ super().__init__()
151
+ self.config = config
152
+ self.embed_dim = config.hidden_size
153
+ self.image_size = config.image_size
154
+ self.patch_size = config.patch_size
155
+
156
+ self.patch_embedding = nn.Conv2d(
157
+ in_channels=config.num_channels,
158
+ out_channels=self.embed_dim,
159
+ kernel_size=self.patch_size,
160
+ stride=self.patch_size,
161
+ padding="valid",
162
+ )
163
+
164
+ self.num_patches = (self.image_size // self.patch_size) ** 2
165
+ self.num_positions = self.num_patches
166
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
167
+ self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
168
+
169
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
170
+ patch_embeds = self.patch_embedding(pixel_values) # shape = [*, width, grid, grid]
171
+ embeddings = patch_embeds.flatten(2).transpose(1, 2)
172
+
173
+ embeddings = embeddings + self.position_embedding(self.position_ids)
174
+ return embeddings
175
+
176
+
177
+ class SigLipAttention(nn.Module):
178
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
179
+
180
+ # Copied from transformers.models.clip.modeling_clip.CLIPAttention.__init__
181
+ def __init__(self, config):
182
+ super().__init__()
183
+ self.config = config
184
+ self.embed_dim = config.hidden_size
185
+ self.num_heads = config.num_attention_heads
186
+ self.head_dim = self.embed_dim // self.num_heads
187
+ if self.head_dim * self.num_heads != self.embed_dim:
188
+ raise ValueError(f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:" f" {self.num_heads}).")
189
+ self.scale = self.head_dim**-0.5
190
+ self.dropout = config.attention_dropout
191
+
192
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
193
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
194
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
195
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
196
+
197
+ def forward(
198
+ self,
199
+ hidden_states: torch.Tensor,
200
+ attention_mask: Optional[torch.Tensor] = None,
201
+ output_attentions: Optional[bool] = False,
202
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
203
+ """Input shape: Batch x Time x Channel"""
204
+
205
+ batch_size, q_len, _ = hidden_states.size()
206
+
207
+ query_states = self.q_proj(hidden_states)
208
+ key_states = self.k_proj(hidden_states)
209
+ value_states = self.v_proj(hidden_states)
210
+
211
+ query_states = query_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
212
+ key_states = key_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
213
+ value_states = value_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
214
+
215
+ k_v_seq_len = key_states.shape[-2]
216
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scale
217
+
218
+ if attn_weights.size() != (batch_size, self.num_heads, q_len, k_v_seq_len):
219
+ raise ValueError(f"Attention weights should be of size {(batch_size, self.num_heads, q_len, k_v_seq_len)}, but is" f" {attn_weights.size()}")
220
+
221
+ if attention_mask is not None:
222
+ if attention_mask.size() != (batch_size, 1, q_len, k_v_seq_len):
223
+ raise ValueError(f"Attention mask should be of size {(batch_size, 1, q_len, k_v_seq_len)}, but is {attention_mask.size()}")
224
+ attn_weights = attn_weights + attention_mask
225
+
226
+ # upcast attention to fp32
227
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
228
+ attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
229
+ attn_output = torch.matmul(attn_weights, value_states)
230
+
231
+ if attn_output.size() != (batch_size, self.num_heads, q_len, self.head_dim):
232
+ raise ValueError(f"`attn_output` should be of size {(batch_size, self.num_heads, q_len, self.head_dim)}, but is" f" {attn_output.size()}")
233
+
234
+ attn_output = attn_output.transpose(1, 2).contiguous()
235
+ attn_output = attn_output.reshape(batch_size, q_len, self.embed_dim)
236
+
237
+ attn_output = self.out_proj(attn_output)
238
+
239
+ return attn_output, attn_weights
240
+
241
+
242
+ # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->SigLip
243
+ class SigLipMLP(nn.Module):
244
+ def __init__(self, config):
245
+ super().__init__()
246
+ self.config = config
247
+ self.activation_fn = ACT2FN[config.hidden_act]
248
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
249
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
250
+
251
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
252
+ hidden_states = self.fc1(hidden_states)
253
+ hidden_states = self.activation_fn(hidden_states)
254
+ hidden_states = self.fc2(hidden_states)
255
+ return hidden_states
256
+
257
+
258
+ # Copied from transformers.models.clip.modeling_clip.CLIPEncoderLayer with CLIP->SigLip
259
+ class SigLipEncoderLayer(nn.Module):
260
+ def __init__(self, config: SigLipVisionConfig):
261
+ super().__init__()
262
+ self.embed_dim = config.hidden_size
263
+ self.self_attn = SigLipAttention(config)
264
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
265
+ self.mlp = SigLipMLP(config)
266
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
267
+
268
+ # Ignore copy
269
+ def forward(
270
+ self,
271
+ hidden_states: torch.Tensor,
272
+ attention_mask: torch.Tensor,
273
+ output_attentions: Optional[bool] = False,
274
+ ) -> Tuple[torch.FloatTensor]:
275
+ """
276
+ Args:
277
+ hidden_states (`torch.FloatTensor`):
278
+ Input to the layer of shape `(batch, seq_len, embed_dim)`.
279
+ attention_mask (`torch.FloatTensor`):
280
+ Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values.
281
+ output_attentions (`bool`, *optional*, defaults to `False`):
282
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
283
+ returned tensors for more detail.
284
+ """
285
+ residual = hidden_states
286
+
287
+ hidden_states = self.layer_norm1(hidden_states)
288
+ hidden_states, attn_weights = self.self_attn(
289
+ hidden_states=hidden_states,
290
+ attention_mask=attention_mask,
291
+ output_attentions=output_attentions,
292
+ )
293
+ hidden_states = residual + hidden_states
294
+
295
+ residual = hidden_states
296
+ hidden_states = self.layer_norm2(hidden_states)
297
+ hidden_states = self.mlp(hidden_states)
298
+ hidden_states = residual + hidden_states
299
+
300
+ outputs = (hidden_states,)
301
+
302
+ if output_attentions:
303
+ outputs += (attn_weights,)
304
+
305
+ return outputs
306
+
307
+
308
+ class SigLipPreTrainedModel(PreTrainedModel):
309
+ """
310
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
311
+ models.
312
+ """
313
+
314
+ config_class = SigLipVisionConfig
315
+ base_model_prefix = "siglip"
316
+ supports_gradient_checkpointing = True
317
+
318
+ def _init_weights(self, module):
319
+ """Initialize the weights"""
320
+ pass
321
+
322
+
323
+ # Copied from transformers.models.clip.modeling_clip.CLIPEncoder with CLIP->SigLip
324
+ class SigLipEncoder(nn.Module):
325
+ """
326
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
327
+ [`SigLipEncoderLayer`].
328
+
329
+ Args:
330
+ config: SigLipVisionConfig
331
+ """
332
+
333
+ def __init__(self, config: SigLipVisionConfig):
334
+ super().__init__()
335
+ self.config = config
336
+ self.layers = nn.ModuleList([SigLipEncoderLayer(config) for _ in range(config.num_hidden_layers)])
337
+ self.gradient_checkpointing = False
338
+
339
+ # Ignore copy
340
+ def forward(
341
+ self,
342
+ inputs_embeds,
343
+ attention_mask: Optional[torch.Tensor] = None,
344
+ output_attentions: Optional[bool] = None,
345
+ output_hidden_states: Optional[bool] = None,
346
+ return_dict: Optional[bool] = None,
347
+ ) -> Union[Tuple, BaseModelOutput]:
348
+ r"""
349
+ Args:
350
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
351
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
352
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
353
+ than the model's internal embedding lookup matrix.
354
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
355
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
356
+
357
+ - 1 for tokens that are **not masked**,
358
+ - 0 for tokens that are **masked**.
359
+
360
+ [What are attention masks?](../glossary#attention-mask)
361
+ output_attentions (`bool`, *optional*):
362
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
363
+ returned tensors for more detail.
364
+ output_hidden_states (`bool`, *optional*):
365
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
366
+ for more detail.
367
+ return_dict (`bool`, *optional*):
368
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
369
+ """
370
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
371
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
372
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
373
+
374
+ encoder_states = () if output_hidden_states else None
375
+ all_attentions = () if output_attentions else None
376
+
377
+ hidden_states = inputs_embeds
378
+ for encoder_layer in self.layers:
379
+ if output_hidden_states:
380
+ encoder_states = encoder_states + (hidden_states,)
381
+ if self.gradient_checkpointing and self.training:
382
+ layer_outputs = self._gradient_checkpointing_func(
383
+ encoder_layer.__call__,
384
+ hidden_states,
385
+ attention_mask,
386
+ output_attentions,
387
+ )
388
+ else:
389
+ layer_outputs = encoder_layer(
390
+ hidden_states,
391
+ attention_mask,
392
+ output_attentions=output_attentions,
393
+ )
394
+
395
+ hidden_states = layer_outputs[0]
396
+
397
+ if output_attentions:
398
+ all_attentions = all_attentions + (layer_outputs[1],)
399
+
400
+ if output_hidden_states:
401
+ encoder_states = encoder_states + (hidden_states,)
402
+
403
+ if not return_dict:
404
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
405
+ return BaseModelOutput(last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions)
406
+
407
+
408
+ class SigLipVisionTransformer(nn.Module):
409
+ def __init__(self, config: SigLipVisionConfig):
410
+ super().__init__()
411
+ self.config = config
412
+ embed_dim = config.hidden_size
413
+
414
+ self.embeddings = SigLipVisionEmbeddings(config)
415
+ self.encoder = SigLipEncoder(config)
416
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
417
+ self.head = SigLipMultiheadAttentionPoolingHead(config)
418
+
419
+ def forward(
420
+ self,
421
+ pixel_values,
422
+ output_attentions: Optional[bool] = None,
423
+ output_hidden_states: Optional[bool] = None,
424
+ return_dict: Optional[bool] = None,
425
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
426
+ r"""
427
+ Returns:
428
+
429
+ """
430
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
431
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
432
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
433
+
434
+ hidden_states = self.embeddings(pixel_values)
435
+
436
+ encoder_outputs = self.encoder(
437
+ inputs_embeds=hidden_states,
438
+ output_attentions=output_attentions,
439
+ output_hidden_states=output_hidden_states,
440
+ return_dict=return_dict,
441
+ )
442
+
443
+ last_hidden_state = encoder_outputs[0]
444
+ last_hidden_state = self.post_layernorm(last_hidden_state)
445
+
446
+ pooled_output = self.head(last_hidden_state)
447
+
448
+ if not return_dict:
449
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
450
+
451
+ return BaseModelOutputWithPooling(
452
+ last_hidden_state=last_hidden_state,
453
+ pooler_output=pooled_output,
454
+ hidden_states=encoder_outputs.hidden_states,
455
+ attentions=encoder_outputs.attentions,
456
+ )
457
+
458
+
459
+ class SigLipMultiheadAttentionPoolingHead(nn.Module):
460
+ """Multihead Attention Pooling."""
461
+
462
+ def __init__(self, config: SigLipVisionConfig):
463
+ super().__init__()
464
+
465
+ self.probe = nn.Parameter(torch.randn(1, 1, config.hidden_size))
466
+ self.attention = torch.nn.MultiheadAttention(config.hidden_size, config.num_attention_heads, batch_first=True)
467
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
468
+ self.mlp = SigLipMLP(config)
469
+
470
+ def forward(self, hidden_state):
471
+ batch_size = hidden_state.shape[0]
472
+ probe = self.probe.repeat(batch_size, 1, 1)
473
+
474
+ hidden_state = self.attention(probe, hidden_state, hidden_state)[0]
475
+
476
+ residual = hidden_state
477
+ hidden_state = self.layernorm(hidden_state)
478
+ hidden_state = residual + self.mlp(hidden_state)
479
+
480
+ return hidden_state[:, 0]
481
+
482
+
483
+ class SigLipVisionModel(SigLipPreTrainedModel):
484
+ config_class = SigLipVisionConfig
485
+ main_input_name = "pixel_values"
486
+ _no_split_modules = ["SigLipEncoderLayer"]
487
+
488
+ def __init__(self, config: SigLipVisionConfig):
489
+ super().__init__(config)
490
+
491
+ self.vision_model = SigLipVisionTransformer(config)
492
+
493
+ # Initialize weights and apply final processing
494
+ self.post_init()
495
+
496
+ def get_input_embeddings(self) -> nn.Module:
497
+ return self.vision_model.embeddings.patch_embedding
498
+
499
+ def forward(
500
+ self,
501
+ pixel_values,
502
+ output_attentions: Optional[bool] = None,
503
+ output_hidden_states: Optional[bool] = None,
504
+ return_dict: Optional[bool] = None,
505
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
506
+ r"""
507
+ Returns:
508
+
509
+ Examples:
510
+
511
+ ```python
512
+ >>> from PIL import Image
513
+ >>> import requests
514
+ >>> from transformers import AutoProcessor, SigLipVisionModel
515
+
516
+ >>> model = SigLipVisionModel.from_pretrained("google/siglip-base-patch16-224")
517
+ >>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224")
518
+
519
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
520
+ >>> image = Image.open(requests.get(url, stream=True).raw)
521
+
522
+ >>> inputs = processor(images=image, return_tensors="pt")
523
+
524
+ >>> outputs = model(**inputs)
525
+ >>> last_hidden_state = outputs.last_hidden_state
526
+ >>> pooled_output = outputs.pooler_output # pooled features
527
+ ```"""
528
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
529
+
530
+ return self.vision_model(
531
+ pixel_values=pixel_values,
532
+ output_attentions=output_attentions,
533
+ output_hidden_states=output_hidden_states,
534
+ return_dict=return_dict,
535
+ )
536
+
537
+
538
+ class SigLipVisionTower(nn.Module):
539
+ def __init__(self, vision_tower, vision_tower_cfg, delay_load=False):
540
+ super().__init__()
541
+
542
+ self.is_loaded = False
543
+
544
+ self.config = SigLipVisionConfig()
545
+
546
+ self.vision_tower_name = vision_tower
547
+
548
+ self.image_processor = SigLipImageProcessor()
549
+
550
+ if not delay_load:
551
+ rank0_print(f"Loading vision tower: {vision_tower}")
552
+ self.load_model()
553
+ elif getattr(vision_tower_cfg, "unfreeze_mm_vision_tower", False):
554
+ # TODO: better detector is needed.
555
+ rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `unfreeze_mm_vision_tower`: True.")
556
+ self.load_model()
557
+ elif hasattr(vision_tower_cfg, "mm_tunable_parts") and "mm_vision_tower" in vision_tower_cfg.mm_tunable_parts:
558
+ rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `mm_tunable_parts` contains `mm_vision_tower`.")
559
+ self.load_model()
560
+ else:
561
+ self.cfg_only = self.config
562
+
563
+ def load_model(self, device_map=None):
564
+ if self.is_loaded:
565
+ rank0_print("{} is already loaded, `load_model` called again, skipping.".format(self.vision_tower_name))
566
+ return
567
+
568
+ self.vision_tower = SigLipVisionModel.from_pretrained(self.vision_tower_name, device_map=device_map)
569
+
570
+ del self.vision_tower.vision_model.encoder.layers[-1:]
571
+ self.vision_tower.vision_model.head = nn.Identity()
572
+ self.vision_tower.requires_grad_(False)
573
+
574
+ self.is_loaded = True
575
+
576
+ def forward(self, images):
577
+ if type(images) is list:
578
+ image_features = []
579
+ for image in images:
580
+ image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
581
+ image_feature = image_forward_out.hidden_states[-1].to(image.dtype)
582
+ assert image_features.shape[-2] == 729
583
+ image_features.append(image_feature)
584
+ else:
585
+ image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
586
+ image_features = image_forward_outs.hidden_states[-1].to(images.dtype)
587
+ assert image_features.shape[-2] == 729
588
+
589
+ return image_features
590
+
591
+ @property
592
+ def dummy_feature(self):
593
+ return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
594
+
595
+ @property
596
+ def dtype(self):
597
+ for p in self.vision_tower.parameters():
598
+ return p.dtype
599
+
600
+ @property
601
+ def device(self):
602
+ for p in self.vision_tower.parameters():
603
+ return p.device
604
+
605
+ @property
606
+ def hidden_size(self):
607
+ return self.config.hidden_size
608
+
609
+ @property
610
+ def num_patches(self):
611
+ return (self.config.image_size // self.config.patch_size) ** 2
612
+
613
+ @property
614
+ def num_patches_per_side(self):
615
+ return self.config.image_size // self.config.patch_size
616
+ # return self.model_config["vision_cfg"]["image_size"] // self.model_config["vision_cfg"]["patch_size"]
617
+
618
+ @property
619
+ def image_size(self):
620
+ return self.config.image_size
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_projector/builder.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import re
4
+
5
+ from .pooler_projector import PoolerProjector
6
+
7
+
8
+ class IdentityMap(nn.Module):
9
+ def __init__(self):
10
+ super().__init__()
11
+
12
+ def forward(self, x, *args, **kwargs):
13
+ return x
14
+
15
+ @property
16
+ def config(self):
17
+ return {"mm_projector_type": "identity"}
18
+
19
+
20
+ class SimpleResBlock(nn.Module):
21
+ def __init__(self, channels):
22
+ super().__init__()
23
+ self.pre_norm = nn.LayerNorm(channels)
24
+
25
+ self.proj = nn.Sequential(nn.Linear(channels, channels), nn.GELU(), nn.Linear(channels, channels))
26
+
27
+ def forward(self, x):
28
+ x = self.pre_norm(x)
29
+ return x + self.proj(x)
30
+
31
+
32
+ def build_vision_projector(config, delay_load=False, **kwargs):
33
+ projector_type = getattr(config, "mm_projector_type", "linear")
34
+
35
+ if projector_type == "linear":
36
+ return nn.Linear(config.mm_hidden_size, config.hidden_size)
37
+
38
+ if projector_type == "pooler":
39
+ return PoolerProjector(config, kwargs["vision_cfg"])
40
+
41
+ mlp_gelu_match = re.match(r"^mlp(\d+)x_gelu$", projector_type)
42
+ if mlp_gelu_match:
43
+ mlp_depth = int(mlp_gelu_match.group(1))
44
+ modules = [nn.Linear(config.mm_hidden_size, config.hidden_size)]
45
+ for _ in range(1, mlp_depth):
46
+ modules.append(nn.GELU())
47
+ modules.append(nn.Linear(config.hidden_size, config.hidden_size))
48
+ return nn.Sequential(*modules)
49
+
50
+ mlp_gelu_resnet_match = re.match(r"^mlp(\d+)x_res(\d+)x_gelu$", projector_type)
51
+ if mlp_gelu_resnet_match:
52
+ mlp_depth = int(mlp_gelu_resnet_match.group(1))
53
+ res_depth = int(mlp_gelu_resnet_match.group(2))
54
+ modules = [nn.Linear(config.mm_hidden_size, config.hidden_size)]
55
+ for _ in range(1, mlp_depth):
56
+ modules.append(nn.GELU())
57
+ modules.append(nn.Linear(config.hidden_size, config.hidden_size))
58
+ for _ in range(res_depth):
59
+ modules.append(SimpleResBlock(config.hidden_size))
60
+ return nn.Sequential(*modules)
61
+
62
+ if projector_type == "identity":
63
+ return IdentityMap()
64
+
65
+ raise ValueError(f"Unknown projector type: {projector_type}")
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_projector/pooler_projector.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ import math
5
+
6
+ from transformers.models.clip.modeling_clip import CLIPVisionModel
7
+
8
+
9
+ class PoolerProjector(nn.Module):
10
+ def __init__(self, config, vision_cfg):
11
+ super().__init__()
12
+ self._config = config
13
+ self.hw = vision_cfg.image_size // vision_cfg.patch_size
14
+
15
+ self.conv_pool = nn.Conv2d(config.mm_hidden_size, config.hidden_size, kernel_size=2, stride=2)
16
+
17
+ self.proj = nn.Sequential(
18
+ nn.GELU(),
19
+ nn.Linear(config.hidden_size, config.hidden_size),
20
+ )
21
+
22
+ def forward(self, x, *args, **kwargs):
23
+ height = width = self.hw
24
+ assert height * width == x.shape[1]
25
+ x = x.view(x.shape[0], height, width, -1).permute(0, 3, 1, 2)
26
+ x = self.conv_pool(x)
27
+ x = x.flatten(2).transpose(1, 2)
28
+ x = self.proj(x)
29
+ return x
30
+
31
+ @property
32
+ def config(self):
33
+ return {"mm_projector_type": "pooler"}
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_resampler/builder.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ from .masked_drop import MaskedDrop
4
+ from .spatial_pool import SpatialPool
5
+ from .perceiver import PerceiverResampler
6
+ from .qformer import Qformer
7
+
8
+
9
+ class IdentityMap(torch.nn.Module):
10
+ def __init__(self):
11
+ super().__init__()
12
+
13
+ def forward(self, x, *args, **kwargs):
14
+ return x
15
+
16
+ @property
17
+ def config(self):
18
+ return {"mm_resampler_type": None}
19
+
20
+
21
+ def build_vision_resampler(model_args, delay_load=False, **kwargs):
22
+ resampler_type = getattr(model_args, "mm_resampler_type", None)
23
+ if resampler_type == "masked_drop":
24
+ return MaskedDrop(model_args)
25
+ elif resampler_type == "spatial_pool":
26
+ return SpatialPool(model_args, **kwargs)
27
+ elif resampler_type == "perceiver":
28
+ return PerceiverResampler(model_args, **kwargs)
29
+ elif resampler_type == "qformer":
30
+ return Qformer(model_args, **kwargs)
31
+ elif resampler_type is None:
32
+ return IdentityMap()
33
+
34
+ raise ValueError(f"Unknown resampler type: {resampler_type}")
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_resampler/masked_drop.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ import random
5
+
6
+
7
+ class MaskedDrop(nn.Module):
8
+ def __init__(self, model_args):
9
+ super().__init__()
10
+
11
+ self.mode = model_args.mm_mask_drop_mode
12
+ self.skip_percentage = model_args.mm_mask_drop_skip_percentage
13
+ self.ratio = model_args.mm_mask_drop_ratio
14
+ self.ratio_upper = model_args.mm_mask_drop_ratio_upper
15
+ self.ratio_lower = model_args.mm_mask_drop_ratio_lower
16
+
17
+ def forward(self, image_features, *args, **kwargs):
18
+
19
+ if not self.training:
20
+ return image_features
21
+
22
+ if self.skip_percentage > random.random():
23
+ return image_features
24
+
25
+ masked_features = []
26
+
27
+ for image_feature in image_features:
28
+ num_tokens = image_feature.shape[0]
29
+ if self.mode == "fixed":
30
+ num_keep = int(num_tokens * self.ratio)
31
+ masked_features.append(self.random_masking(image_feature.unsqueeze(0), num_keep)[0][0])
32
+ elif self.mode == "range":
33
+ num_keep = int(num_tokens * random.uniform(self.ratio_lower, self.ratio_upper))
34
+ masked_features.append(self.random_masking(image_feature.unsqueeze(0), num_keep)[0])
35
+ elif self.mode == "cls_only":
36
+ masked_features.append(image_feature[0:1])
37
+ else:
38
+ raise ValueError(f"Unexpected masked drop mode: {self.mode}")
39
+
40
+ if self.mode not in ["range"] and (type(image_features) is not list or self.mode in ["cls_only"]):
41
+ masked_features = torch.stack(masked_features, dim=0)
42
+
43
+ return masked_features
44
+
45
+ @property
46
+ def config(self):
47
+ return {
48
+ "mm_resampler_type": "masked_drop",
49
+ "mm_mask_drop_mode": self.mode,
50
+ "mm_mask_drop_skip_percentage": self.skip_percentage,
51
+ "mm_mask_drop_ratio": self.ratio,
52
+ "mm_mask_drop_ratio_upper": self.ratio_upper,
53
+ "mm_mask_drop_ratio_lower": self.ratio_lower,
54
+ }
55
+
56
+ def random_masking(self, x, len_keep):
57
+ """
58
+ Perform per-sample random masking by per-sample shuffling.
59
+ Per-sample shuffling is done by argsort random noise.
60
+ x: [N, L, D], sequence
61
+ """
62
+ N, L, D = x.shape # batch, length, dim
63
+
64
+ noise = torch.rand(N, L, device=x.device) # noise in [0, 1]
65
+
66
+ # sort noise for each sample
67
+ ids_shuffle = torch.argsort(noise, dim=1) # ascend: small is keep, large is remove
68
+ ids_restore = torch.argsort(ids_shuffle, dim=1)
69
+
70
+ # keep the first subset
71
+ ids_keep = ids_shuffle[:, :len_keep]
72
+ x_masked = torch.gather(x, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, D))
73
+
74
+ # generate the binary mask: 0 is keep, 1 is remove
75
+ mask = torch.ones([N, L], device=x.device)
76
+ mask[:, :len_keep] = 0
77
+ # unshuffle to get the binary mask
78
+ mask = torch.gather(mask, dim=1, index=ids_restore)
79
+
80
+ return x_masked, mask, ids_restore
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_resampler/perceiver.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Taken from https://github.com/lucidrains/flamingo-pytorch
3
+ """
4
+
5
+ import torch
6
+ from einops import rearrange, repeat
7
+
8
+ try:
9
+ from einops_exts import rearrange_many
10
+ except:
11
+ pass
12
+
13
+ from torch import einsum, nn
14
+
15
+
16
+ def exists(val):
17
+ return val is not None
18
+
19
+
20
+ def FeedForward(dim, mult=4):
21
+ inner_dim = int(dim * mult)
22
+ return nn.Sequential(
23
+ nn.LayerNorm(dim),
24
+ nn.Linear(dim, inner_dim, bias=False),
25
+ nn.GELU(),
26
+ nn.Linear(inner_dim, dim, bias=False),
27
+ )
28
+
29
+
30
+ class PerceiverAttention(nn.Module):
31
+ def __init__(self, *, dim, dim_head=64, heads=8):
32
+ super().__init__()
33
+ self.scale = dim_head**-0.5
34
+ self.heads = heads
35
+ inner_dim = dim_head * heads
36
+
37
+ self.norm_media = nn.LayerNorm(dim)
38
+ self.norm_latents = nn.LayerNorm(dim)
39
+
40
+ self.to_q = nn.Linear(dim, inner_dim, bias=False)
41
+ self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False)
42
+ self.to_out = nn.Linear(inner_dim, dim, bias=False)
43
+
44
+ def forward(self, x, latents):
45
+ """
46
+ Args:
47
+ x (torch.Tensor): image features
48
+ shape (b, T, n1, D)
49
+ latent (torch.Tensor): latent features
50
+ shape (b, T, n2, D)
51
+ """
52
+ x = self.norm_media(x)
53
+ latents = self.norm_latents(latents)
54
+
55
+ h = self.heads
56
+
57
+ q = self.to_q(latents)
58
+ kv_input = torch.cat((x, latents), dim=-2)
59
+ k, v = self.to_kv(kv_input).chunk(2, dim=-1)
60
+ q, k, v = rearrange_many((q, k, v), "b t n (h d) -> b h t n d", h=h)
61
+ q = q * self.scale
62
+
63
+ # attention
64
+ sim = einsum("... i d, ... j d -> ... i j", q, k)
65
+ sim = sim - sim.amax(dim=-1, keepdim=True).detach()
66
+ attn = sim.softmax(dim=-1)
67
+
68
+ out = einsum("... i j, ... j d -> ... i d", attn, v)
69
+ out = rearrange(out, "b h t n d -> b t n (h d)", h=h)
70
+ return self.to_out(out)
71
+
72
+
73
+ class PerceiverResamplerModule(nn.Module):
74
+ def __init__(
75
+ self,
76
+ *,
77
+ dim,
78
+ depth=6,
79
+ dim_head=64,
80
+ heads=8,
81
+ num_latents=64,
82
+ max_num_media=None,
83
+ max_num_frames=None,
84
+ ff_mult=4,
85
+ ):
86
+ super().__init__()
87
+ self.latents = nn.Parameter(torch.randn(num_latents, dim))
88
+ self.frame_embs = nn.Parameter(torch.randn(max_num_frames, dim)) if exists(max_num_frames) else None
89
+ self.media_time_embs = nn.Parameter(torch.randn(max_num_media, 1, dim)) if exists(max_num_media) else None
90
+
91
+ self.layers = nn.ModuleList([])
92
+ for _ in range(depth):
93
+ self.layers.append(
94
+ nn.ModuleList(
95
+ [
96
+ PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads),
97
+ FeedForward(dim=dim, mult=ff_mult) if ff_mult > 0 else nn.Identity(),
98
+ ]
99
+ )
100
+ )
101
+
102
+ self.norm = nn.LayerNorm(dim)
103
+
104
+ def forward(self, x):
105
+ """
106
+ Args:
107
+ x (torch.Tensor): image features
108
+ shape (b, T, F, v, D)
109
+ Returns:
110
+ shape (b, T, n, D) where n is self.num_latents
111
+ """
112
+ b, T, F, v = x.shape[:4]
113
+
114
+ # frame and media time embeddings
115
+ if exists(self.frame_embs):
116
+ frame_embs = repeat(self.frame_embs[:F], "F d -> b T F v d", b=b, T=T, v=v)
117
+ x = x + frame_embs
118
+ x = rearrange(x, "b T F v d -> b T (F v) d") # flatten the frame and spatial dimensions
119
+ if exists(self.media_time_embs):
120
+ x = x + self.media_time_embs[:T]
121
+
122
+ # blocks
123
+ latents = repeat(self.latents, "n d -> b T n d", b=b, T=T)
124
+ for attn, ff in self.layers:
125
+ latents = attn(x, latents) + latents
126
+ latents = ff(latents) + latents
127
+ return self.norm(latents)
128
+
129
+
130
+ class PerceiverResampler(nn.Module):
131
+ def __init__(self, model_args, vision_tower):
132
+ super().__init__()
133
+
134
+ self.depth = model_args.mm_perceiver_depth
135
+ self.num_latents = model_args.mm_perceiver_latents
136
+ self.ff_mult = model_args.mm_perceiver_ff_mult
137
+ self.pretrained = model_args.mm_perceiver_pretrained
138
+
139
+ self.perceiver = PerceiverResamplerModule(dim=vision_tower.hidden_size, depth=self.depth, num_latents=self.num_latents, ff_mult=self.ff_mult)
140
+
141
+ if self.pretrained is not None:
142
+ self.load_state_dict(torch.load(self.pretrained))
143
+
144
+ def forward(self, image_features, *args, **kwargs):
145
+ return self.perceiver(image_features[:, None, None]).squeeze(1)
146
+
147
+ @property
148
+ def config(self):
149
+ return {
150
+ "mm_resampler_type": "perceiver",
151
+ "mm_perceiver_depth": self.depth,
152
+ "mm_perceiver_latents": self.num_latents,
153
+ "mm_perceiver_ff_mult": self.ff_mult,
154
+ "mm_perceiver_pretrained": self.pretrained,
155
+ }
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_resampler/qformer.py ADDED
@@ -0,0 +1,1160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ * Copyright (c) 2023, salesforce.com, inc.
3
+ * All rights reserved.
4
+ * SPDX-License-Identifier: BSD-3-Clause
5
+ * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
6
+ * By Junnan Li
7
+ * Based on huggingface code base
8
+ * https://github.com/huggingface/transformers/blob/v4.15.0/src/transformers/models/bert
9
+ """
10
+
11
+ import math
12
+ import os
13
+ import warnings
14
+ from dataclasses import dataclass
15
+ from typing import Optional, Tuple, Dict, Any
16
+
17
+ import torch
18
+ from torch import Tensor, device, dtype, nn
19
+ import torch.utils.checkpoint
20
+ from torch import nn
21
+ from torch.nn import CrossEntropyLoss
22
+ import torch.nn.functional as F
23
+
24
+ from transformers.activations import ACT2FN
25
+ from transformers.file_utils import (
26
+ ModelOutput,
27
+ )
28
+ from transformers.modeling_outputs import (
29
+ BaseModelOutputWithPastAndCrossAttentions,
30
+ BaseModelOutputWithPoolingAndCrossAttentions,
31
+ CausalLMOutputWithCrossAttentions,
32
+ MaskedLMOutput,
33
+ MultipleChoiceModelOutput,
34
+ NextSentencePredictorOutput,
35
+ QuestionAnsweringModelOutput,
36
+ SequenceClassifierOutput,
37
+ TokenClassifierOutput,
38
+ )
39
+ from transformers.modeling_utils import (
40
+ PreTrainedModel,
41
+ apply_chunking_to_forward,
42
+ find_pruneable_heads_and_indices,
43
+ prune_linear_layer,
44
+ )
45
+ from transformers.utils import logging
46
+ from transformers.models.bert.configuration_bert import BertConfig
47
+
48
+ logger = logging.get_logger(__name__)
49
+
50
+
51
+ def disabled_train(self, mode=True):
52
+ """Overwrite model.train with this function to make sure train/eval mode
53
+ does not change anymore."""
54
+ return self
55
+
56
+
57
+ class BertEmbeddings(nn.Module):
58
+ """Construct the embeddings from word and position embeddings."""
59
+
60
+ def __init__(self, config):
61
+ super().__init__()
62
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
63
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
64
+
65
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
66
+ # any TensorFlow checkpoint file
67
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
68
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
69
+
70
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
71
+ self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))
72
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
73
+
74
+ self.config = config
75
+
76
+ def forward(
77
+ self,
78
+ input_ids=None,
79
+ position_ids=None,
80
+ query_embeds=None,
81
+ past_key_values_length=0,
82
+ ):
83
+ if input_ids is not None:
84
+ seq_length = input_ids.size()[1]
85
+ else:
86
+ seq_length = 0
87
+
88
+ if position_ids is None:
89
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length].clone()
90
+
91
+ if input_ids is not None:
92
+ embeddings = self.word_embeddings(input_ids)
93
+ if self.position_embedding_type == "absolute":
94
+ position_embeddings = self.position_embeddings(position_ids)
95
+ embeddings = embeddings + position_embeddings
96
+
97
+ if query_embeds is not None:
98
+ embeddings = torch.cat((query_embeds, embeddings), dim=1)
99
+ else:
100
+ embeddings = query_embeds
101
+
102
+ embeddings = self.LayerNorm(embeddings)
103
+ embeddings = self.dropout(embeddings)
104
+ return embeddings
105
+
106
+
107
+ class BertSelfAttention(nn.Module):
108
+ def __init__(self, config, is_cross_attention):
109
+ super().__init__()
110
+ self.config = config
111
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
112
+ raise ValueError("The hidden size (%d) is not a multiple of the number of attention " "heads (%d)" % (config.hidden_size, config.num_attention_heads))
113
+
114
+ self.num_attention_heads = config.num_attention_heads
115
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
116
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
117
+
118
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
119
+ if is_cross_attention:
120
+ self.key = nn.Linear(config.encoder_width, self.all_head_size)
121
+ self.value = nn.Linear(config.encoder_width, self.all_head_size)
122
+ else:
123
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
124
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
125
+
126
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
127
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
128
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
129
+ self.max_position_embeddings = config.max_position_embeddings
130
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
131
+ self.save_attention = False
132
+
133
+ def save_attn_gradients(self, attn_gradients):
134
+ self.attn_gradients = attn_gradients
135
+
136
+ def get_attn_gradients(self):
137
+ return self.attn_gradients
138
+
139
+ def save_attention_map(self, attention_map):
140
+ self.attention_map = attention_map
141
+
142
+ def get_attention_map(self):
143
+ return self.attention_map
144
+
145
+ def transpose_for_scores(self, x):
146
+ new_x_shape = x.size()[:-1] + (
147
+ self.num_attention_heads,
148
+ self.attention_head_size,
149
+ )
150
+ x = x.view(*new_x_shape)
151
+ return x.permute(0, 2, 1, 3)
152
+
153
+ def forward(
154
+ self,
155
+ hidden_states,
156
+ attention_mask=None,
157
+ head_mask=None,
158
+ encoder_hidden_states=None,
159
+ encoder_attention_mask=None,
160
+ past_key_value=None,
161
+ output_attentions=False,
162
+ ):
163
+
164
+ # If this is instantiated as a cross-attention module, the keys
165
+ # and values come from an encoder; the attention mask needs to be
166
+ # such that the encoder's padding tokens are not attended to.
167
+ is_cross_attention = encoder_hidden_states is not None
168
+
169
+ if is_cross_attention:
170
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
171
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
172
+ attention_mask = encoder_attention_mask
173
+ elif past_key_value is not None:
174
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
175
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
176
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
177
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
178
+ else:
179
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
180
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
181
+
182
+ mixed_query_layer = self.query(hidden_states)
183
+
184
+ query_layer = self.transpose_for_scores(mixed_query_layer)
185
+
186
+ past_key_value = (key_layer, value_layer)
187
+
188
+ # Take the dot product between "query" and "key" to get the raw attention scores.
189
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
190
+
191
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
192
+ seq_length = hidden_states.size()[1]
193
+ position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
194
+ position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
195
+ distance = position_ids_l - position_ids_r
196
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
197
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
198
+
199
+ if self.position_embedding_type == "relative_key":
200
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
201
+ attention_scores = attention_scores + relative_position_scores
202
+ elif self.position_embedding_type == "relative_key_query":
203
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
204
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
205
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
206
+
207
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
208
+ if attention_mask is not None:
209
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
210
+ attention_scores = attention_scores + attention_mask
211
+
212
+ # Normalize the attention scores to probabilities.
213
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
214
+
215
+ if is_cross_attention and self.save_attention:
216
+ self.save_attention_map(attention_probs)
217
+ attention_probs.register_hook(self.save_attn_gradients)
218
+
219
+ # This is actually dropping out entire tokens to attend to, which might
220
+ # seem a bit unusual, but is taken from the original Transformer paper.
221
+ attention_probs_dropped = self.dropout(attention_probs)
222
+
223
+ # Mask heads if we want to
224
+ if head_mask is not None:
225
+ attention_probs_dropped = attention_probs_dropped * head_mask
226
+
227
+ context_layer = torch.matmul(attention_probs_dropped, value_layer)
228
+
229
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
230
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
231
+ context_layer = context_layer.view(*new_context_layer_shape)
232
+
233
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
234
+
235
+ outputs = outputs + (past_key_value,)
236
+ return outputs
237
+
238
+
239
+ class BertSelfOutput(nn.Module):
240
+ def __init__(self, config):
241
+ super().__init__()
242
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
243
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
244
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
245
+
246
+ def forward(self, hidden_states, input_tensor):
247
+ hidden_states = self.dense(hidden_states)
248
+ hidden_states = self.dropout(hidden_states)
249
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
250
+ return hidden_states
251
+
252
+
253
+ class BertAttention(nn.Module):
254
+ def __init__(self, config, is_cross_attention=False):
255
+ super().__init__()
256
+ self.self = BertSelfAttention(config, is_cross_attention)
257
+ self.output = BertSelfOutput(config)
258
+ self.pruned_heads = set()
259
+
260
+ def prune_heads(self, heads):
261
+ if len(heads) == 0:
262
+ return
263
+ heads, index = find_pruneable_heads_and_indices(
264
+ heads,
265
+ self.self.num_attention_heads,
266
+ self.self.attention_head_size,
267
+ self.pruned_heads,
268
+ )
269
+
270
+ # Prune linear layers
271
+ self.self.query = prune_linear_layer(self.self.query, index)
272
+ self.self.key = prune_linear_layer(self.self.key, index)
273
+ self.self.value = prune_linear_layer(self.self.value, index)
274
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
275
+
276
+ # Update hyper params and store pruned heads
277
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
278
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
279
+ self.pruned_heads = self.pruned_heads.union(heads)
280
+
281
+ def forward(
282
+ self,
283
+ hidden_states,
284
+ attention_mask=None,
285
+ head_mask=None,
286
+ encoder_hidden_states=None,
287
+ encoder_attention_mask=None,
288
+ past_key_value=None,
289
+ output_attentions=False,
290
+ ):
291
+ self_outputs = self.self(
292
+ hidden_states,
293
+ attention_mask,
294
+ head_mask,
295
+ encoder_hidden_states,
296
+ encoder_attention_mask,
297
+ past_key_value,
298
+ output_attentions,
299
+ )
300
+ attention_output = self.output(self_outputs[0], hidden_states)
301
+
302
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
303
+ return outputs
304
+
305
+
306
+ class BertIntermediate(nn.Module):
307
+ def __init__(self, config):
308
+ super().__init__()
309
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
310
+ if isinstance(config.hidden_act, str):
311
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
312
+ else:
313
+ self.intermediate_act_fn = config.hidden_act
314
+
315
+ def forward(self, hidden_states):
316
+ hidden_states = self.dense(hidden_states)
317
+ hidden_states = self.intermediate_act_fn(hidden_states)
318
+ return hidden_states
319
+
320
+
321
+ class BertOutput(nn.Module):
322
+ def __init__(self, config):
323
+ super().__init__()
324
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
325
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
326
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
327
+
328
+ def forward(self, hidden_states, input_tensor):
329
+ hidden_states = self.dense(hidden_states)
330
+ hidden_states = self.dropout(hidden_states)
331
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
332
+ return hidden_states
333
+
334
+
335
+ class BertLayer(nn.Module):
336
+ def __init__(self, config, layer_num):
337
+ super().__init__()
338
+ self.config = config
339
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
340
+ self.seq_len_dim = 1
341
+ self.attention = BertAttention(config)
342
+ self.layer_num = layer_num
343
+ if self.config.add_cross_attention and layer_num % self.config.cross_attention_freq == 0:
344
+ self.crossattention = BertAttention(config, is_cross_attention=self.config.add_cross_attention)
345
+ self.has_cross_attention = True
346
+ else:
347
+ self.has_cross_attention = False
348
+ self.intermediate = BertIntermediate(config)
349
+ self.output = BertOutput(config)
350
+
351
+ self.intermediate_query = BertIntermediate(config)
352
+ self.output_query = BertOutput(config)
353
+
354
+ def forward(
355
+ self,
356
+ hidden_states,
357
+ attention_mask=None,
358
+ head_mask=None,
359
+ encoder_hidden_states=None,
360
+ encoder_attention_mask=None,
361
+ past_key_value=None,
362
+ output_attentions=False,
363
+ query_length=0,
364
+ ):
365
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
366
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
367
+ self_attention_outputs = self.attention(
368
+ hidden_states,
369
+ attention_mask,
370
+ head_mask,
371
+ output_attentions=output_attentions,
372
+ past_key_value=self_attn_past_key_value,
373
+ )
374
+ attention_output = self_attention_outputs[0]
375
+ outputs = self_attention_outputs[1:-1]
376
+
377
+ present_key_value = self_attention_outputs[-1]
378
+
379
+ if query_length > 0:
380
+ query_attention_output = attention_output[:, :query_length, :]
381
+
382
+ if self.has_cross_attention:
383
+ assert encoder_hidden_states is not None, "encoder_hidden_states must be given for cross-attention layers"
384
+ cross_attention_outputs = self.crossattention(
385
+ query_attention_output,
386
+ attention_mask,
387
+ head_mask,
388
+ encoder_hidden_states,
389
+ encoder_attention_mask,
390
+ output_attentions=output_attentions,
391
+ )
392
+ query_attention_output = cross_attention_outputs[0]
393
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
394
+
395
+ layer_output = apply_chunking_to_forward(
396
+ self.feed_forward_chunk_query,
397
+ self.chunk_size_feed_forward,
398
+ self.seq_len_dim,
399
+ query_attention_output,
400
+ )
401
+ if attention_output.shape[1] > query_length:
402
+ layer_output_text = apply_chunking_to_forward(
403
+ self.feed_forward_chunk,
404
+ self.chunk_size_feed_forward,
405
+ self.seq_len_dim,
406
+ attention_output[:, query_length:, :],
407
+ )
408
+ layer_output = torch.cat([layer_output, layer_output_text], dim=1)
409
+ else:
410
+ layer_output = apply_chunking_to_forward(
411
+ self.feed_forward_chunk,
412
+ self.chunk_size_feed_forward,
413
+ self.seq_len_dim,
414
+ attention_output,
415
+ )
416
+ outputs = (layer_output,) + outputs
417
+
418
+ outputs = outputs + (present_key_value,)
419
+
420
+ return outputs
421
+
422
+ def feed_forward_chunk(self, attention_output):
423
+ intermediate_output = self.intermediate(attention_output)
424
+ layer_output = self.output(intermediate_output, attention_output)
425
+ return layer_output
426
+
427
+ def feed_forward_chunk_query(self, attention_output):
428
+ intermediate_output = self.intermediate_query(attention_output)
429
+ layer_output = self.output_query(intermediate_output, attention_output)
430
+ return layer_output
431
+
432
+
433
+ class BertEncoder(nn.Module):
434
+ def __init__(self, config):
435
+ super().__init__()
436
+ self.config = config
437
+ self.layer = nn.ModuleList([BertLayer(config, i) for i in range(config.num_hidden_layers)])
438
+
439
+ def forward(
440
+ self,
441
+ hidden_states,
442
+ attention_mask=None,
443
+ head_mask=None,
444
+ encoder_hidden_states=None,
445
+ encoder_attention_mask=None,
446
+ past_key_values=None,
447
+ use_cache=None,
448
+ output_attentions=False,
449
+ output_hidden_states=False,
450
+ return_dict=True,
451
+ query_length=0,
452
+ ):
453
+ all_hidden_states = () if output_hidden_states else None
454
+ all_self_attentions = () if output_attentions else None
455
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
456
+
457
+ next_decoder_cache = () if use_cache else None
458
+
459
+ for i in range(self.config.num_hidden_layers):
460
+ layer_module = self.layer[i]
461
+ if output_hidden_states:
462
+ all_hidden_states = all_hidden_states + (hidden_states,)
463
+
464
+ layer_head_mask = head_mask[i] if head_mask is not None else None
465
+ past_key_value = past_key_values[i] if past_key_values is not None else None
466
+
467
+ if getattr(self.config, "gradient_checkpointing", False) and self.training:
468
+
469
+ if use_cache:
470
+ logger.warn("`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...")
471
+ use_cache = False
472
+
473
+ def create_custom_forward(module):
474
+ def custom_forward(*inputs):
475
+ return module(*inputs, past_key_value, output_attentions, query_length)
476
+
477
+ return custom_forward
478
+
479
+ layer_outputs = torch.utils.checkpoint.checkpoint(
480
+ create_custom_forward(layer_module),
481
+ hidden_states,
482
+ attention_mask,
483
+ layer_head_mask,
484
+ encoder_hidden_states,
485
+ encoder_attention_mask,
486
+ )
487
+ else:
488
+ layer_outputs = layer_module(
489
+ hidden_states,
490
+ attention_mask,
491
+ layer_head_mask,
492
+ encoder_hidden_states,
493
+ encoder_attention_mask,
494
+ past_key_value,
495
+ output_attentions,
496
+ query_length,
497
+ )
498
+
499
+ hidden_states = layer_outputs[0]
500
+ if use_cache:
501
+ next_decoder_cache += (layer_outputs[-1],)
502
+ if output_attentions:
503
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
504
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
505
+
506
+ if output_hidden_states:
507
+ all_hidden_states = all_hidden_states + (hidden_states,)
508
+
509
+ if not return_dict:
510
+ return tuple(
511
+ v
512
+ for v in [
513
+ hidden_states,
514
+ next_decoder_cache,
515
+ all_hidden_states,
516
+ all_self_attentions,
517
+ all_cross_attentions,
518
+ ]
519
+ if v is not None
520
+ )
521
+ return BaseModelOutputWithPastAndCrossAttentions(
522
+ last_hidden_state=hidden_states,
523
+ past_key_values=next_decoder_cache,
524
+ hidden_states=all_hidden_states,
525
+ attentions=all_self_attentions,
526
+ cross_attentions=all_cross_attentions,
527
+ )
528
+
529
+
530
+ class BertPooler(nn.Module):
531
+ def __init__(self, config):
532
+ super().__init__()
533
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
534
+ self.activation = nn.Tanh()
535
+
536
+ def forward(self, hidden_states):
537
+ # We "pool" the model by simply taking the hidden state corresponding
538
+ # to the first token.
539
+ first_token_tensor = hidden_states[:, 0]
540
+ pooled_output = self.dense(first_token_tensor)
541
+ pooled_output = self.activation(pooled_output)
542
+ return pooled_output
543
+
544
+
545
+ class BertPredictionHeadTransform(nn.Module):
546
+ def __init__(self, config):
547
+ super().__init__()
548
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
549
+ if isinstance(config.hidden_act, str):
550
+ self.transform_act_fn = ACT2FN[config.hidden_act]
551
+ else:
552
+ self.transform_act_fn = config.hidden_act
553
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
554
+
555
+ def forward(self, hidden_states):
556
+ hidden_states = self.dense(hidden_states)
557
+ hidden_states = self.transform_act_fn(hidden_states)
558
+ hidden_states = self.LayerNorm(hidden_states)
559
+ return hidden_states
560
+
561
+
562
+ class BertLMPredictionHead(nn.Module):
563
+ def __init__(self, config):
564
+ super().__init__()
565
+ self.transform = BertPredictionHeadTransform(config)
566
+
567
+ # The output weights are the same as the input embeddings, but there is
568
+ # an output-only bias for each token.
569
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
570
+
571
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
572
+
573
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
574
+ self.decoder.bias = self.bias
575
+
576
+ def forward(self, hidden_states):
577
+ hidden_states = self.transform(hidden_states)
578
+ hidden_states = self.decoder(hidden_states)
579
+ return hidden_states
580
+
581
+
582
+ class BertOnlyMLMHead(nn.Module):
583
+ def __init__(self, config):
584
+ super().__init__()
585
+ self.predictions = BertLMPredictionHead(config)
586
+
587
+ def forward(self, sequence_output):
588
+ prediction_scores = self.predictions(sequence_output)
589
+ return prediction_scores
590
+
591
+
592
+ class BertPreTrainedModel(PreTrainedModel):
593
+ """
594
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
595
+ models.
596
+ """
597
+
598
+ config_class = BertConfig
599
+ base_model_prefix = "bert"
600
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
601
+
602
+ def _init_weights(self, module):
603
+ """Initialize the weights"""
604
+ if isinstance(module, (nn.Linear, nn.Embedding)):
605
+ # Slightly different from the TF version which uses truncated_normal for initialization
606
+ # cf https://github.com/pytorch/pytorch/pull/5617
607
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
608
+ elif isinstance(module, nn.LayerNorm):
609
+ module.bias.data.zero_()
610
+ module.weight.data.fill_(1.0)
611
+ if isinstance(module, nn.Linear) and module.bias is not None:
612
+ module.bias.data.zero_()
613
+
614
+
615
+ class BertModel(BertPreTrainedModel):
616
+ """
617
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
618
+ cross-attention is added between the self-attention layers, following the architecture described in `Attention is
619
+ all you need <https://arxiv.org/abs/1706.03762>`__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
620
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
621
+ argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an
622
+ input to the forward pass.
623
+ """
624
+
625
+ def __init__(self, config, add_pooling_layer=False):
626
+ super().__init__(config)
627
+ self.config = config
628
+
629
+ self.embeddings = BertEmbeddings(config)
630
+
631
+ self.encoder = BertEncoder(config)
632
+
633
+ self.pooler = BertPooler(config) if add_pooling_layer else None
634
+
635
+ self.init_weights()
636
+
637
+ def get_input_embeddings(self):
638
+ return self.embeddings.word_embeddings
639
+
640
+ def set_input_embeddings(self, value):
641
+ self.embeddings.word_embeddings = value
642
+
643
+ def _prune_heads(self, heads_to_prune):
644
+ """
645
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
646
+ class PreTrainedModel
647
+ """
648
+ for layer, heads in heads_to_prune.items():
649
+ self.encoder.layer[layer].attention.prune_heads(heads)
650
+
651
+ def get_extended_attention_mask(
652
+ self,
653
+ attention_mask: Tensor,
654
+ input_shape: Tuple[int],
655
+ device: device,
656
+ is_decoder: bool,
657
+ has_query: bool = False,
658
+ ) -> Tensor:
659
+ """
660
+ Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
661
+
662
+ Arguments:
663
+ attention_mask (:obj:`torch.Tensor`):
664
+ Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
665
+ input_shape (:obj:`Tuple[int]`):
666
+ The shape of the input to the model.
667
+ device: (:obj:`torch.device`):
668
+ The device of the input to the model.
669
+
670
+ Returns:
671
+ :obj:`torch.Tensor` The extended attention mask, with a the same dtype as :obj:`attention_mask.dtype`.
672
+ """
673
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
674
+ # ourselves in which case we just need to make it broadcastable to all heads.
675
+ if attention_mask.dim() == 3:
676
+ extended_attention_mask = attention_mask[:, None, :, :]
677
+ elif attention_mask.dim() == 2:
678
+ # Provided a padding mask of dimensions [batch_size, seq_length]
679
+ # - if the model is a decoder, apply a causal mask in addition to the padding mask
680
+ # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]
681
+ if is_decoder:
682
+ batch_size, seq_length = input_shape
683
+
684
+ seq_ids = torch.arange(seq_length, device=device)
685
+ causal_mask = seq_ids[None, None, :].repeat(batch_size, seq_length, 1) <= seq_ids[None, :, None]
686
+
687
+ # add a prefix ones mask to the causal mask
688
+ # causal and attention masks must have same type with pytorch version < 1.3
689
+ causal_mask = causal_mask.to(attention_mask.dtype)
690
+
691
+ if causal_mask.shape[1] < attention_mask.shape[1]:
692
+ prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1]
693
+ if has_query: # UniLM style attention mask
694
+ causal_mask = torch.cat(
695
+ [
696
+ torch.zeros(
697
+ (batch_size, prefix_seq_len, seq_length),
698
+ device=device,
699
+ dtype=causal_mask.dtype,
700
+ ),
701
+ causal_mask,
702
+ ],
703
+ axis=1,
704
+ )
705
+ causal_mask = torch.cat(
706
+ [
707
+ torch.ones(
708
+ (batch_size, causal_mask.shape[1], prefix_seq_len),
709
+ device=device,
710
+ dtype=causal_mask.dtype,
711
+ ),
712
+ causal_mask,
713
+ ],
714
+ axis=-1,
715
+ )
716
+ extended_attention_mask = causal_mask[:, None, :, :] * attention_mask[:, None, None, :]
717
+ else:
718
+ extended_attention_mask = attention_mask[:, None, None, :]
719
+ else:
720
+ raise ValueError("Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format(input_shape, attention_mask.shape))
721
+
722
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
723
+ # masked positions, this operation will create a tensor which is 0.0 for
724
+ # positions we want to attend and -10000.0 for masked positions.
725
+ # Since we are adding it to the raw scores before the softmax, this is
726
+ # effectively the same as removing these entirely.
727
+ extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility
728
+ extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
729
+ return extended_attention_mask
730
+
731
+ def forward(
732
+ self,
733
+ input_ids=None,
734
+ attention_mask=None,
735
+ position_ids=None,
736
+ head_mask=None,
737
+ query_embeds=None,
738
+ encoder_hidden_states=None,
739
+ encoder_attention_mask=None,
740
+ past_key_values=None,
741
+ use_cache=None,
742
+ output_attentions=None,
743
+ output_hidden_states=None,
744
+ return_dict=None,
745
+ is_decoder=False,
746
+ ):
747
+ r"""
748
+ encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
749
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
750
+ the model is configured as a decoder.
751
+ encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
752
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
753
+ the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
754
+ - 1 for tokens that are **not masked**,
755
+ - 0 for tokens that are **masked**.
756
+ past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
757
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
758
+ If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
759
+ (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
760
+ instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
761
+ use_cache (:obj:`bool`, `optional`):
762
+ If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
763
+ decoding (see :obj:`past_key_values`).
764
+ """
765
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
766
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
767
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
768
+
769
+ # use_cache = use_cache if use_cache is not None else self.config.use_cache
770
+
771
+ if input_ids is None:
772
+ assert query_embeds is not None, "You have to specify query_embeds when input_ids is None"
773
+
774
+ # past_key_values_length
775
+ past_key_values_length = past_key_values[0][0].shape[2] - self.config.query_length if past_key_values is not None else 0
776
+
777
+ query_length = query_embeds.shape[1] if query_embeds is not None else 0
778
+
779
+ embedding_output = self.embeddings(
780
+ input_ids=input_ids,
781
+ position_ids=position_ids,
782
+ query_embeds=query_embeds,
783
+ past_key_values_length=past_key_values_length,
784
+ )
785
+
786
+ input_shape = embedding_output.size()[:-1]
787
+ batch_size, seq_length = input_shape
788
+ device = embedding_output.device
789
+
790
+ if attention_mask is None:
791
+ attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
792
+
793
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
794
+ # ourselves in which case we just need to make it broadcastable to all heads.
795
+ if is_decoder:
796
+ extended_attention_mask = self.get_extended_attention_mask(
797
+ attention_mask,
798
+ input_ids.shape,
799
+ device,
800
+ is_decoder,
801
+ has_query=(query_embeds is not None),
802
+ )
803
+ else:
804
+ extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape, device, is_decoder)
805
+
806
+ # If a 2D or 3D attention mask is provided for the cross-attention
807
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
808
+ if encoder_hidden_states is not None:
809
+ if type(encoder_hidden_states) == list:
810
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[0].size()
811
+ else:
812
+ (
813
+ encoder_batch_size,
814
+ encoder_sequence_length,
815
+ _,
816
+ ) = encoder_hidden_states.size()
817
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
818
+
819
+ if type(encoder_attention_mask) == list:
820
+ encoder_extended_attention_mask = [self.invert_attention_mask(mask) for mask in encoder_attention_mask]
821
+ elif encoder_attention_mask is None:
822
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
823
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
824
+ else:
825
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
826
+ else:
827
+ encoder_extended_attention_mask = None
828
+
829
+ # Prepare head mask if needed
830
+ # 1.0 in head_mask indicate we keep the head
831
+ # attention_probs has shape bsz x n_heads x N x N
832
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
833
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
834
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
835
+
836
+ encoder_outputs = self.encoder(
837
+ embedding_output,
838
+ attention_mask=extended_attention_mask,
839
+ head_mask=head_mask,
840
+ encoder_hidden_states=encoder_hidden_states,
841
+ encoder_attention_mask=encoder_extended_attention_mask,
842
+ past_key_values=past_key_values,
843
+ use_cache=use_cache,
844
+ output_attentions=output_attentions,
845
+ output_hidden_states=output_hidden_states,
846
+ return_dict=return_dict,
847
+ query_length=query_length,
848
+ )
849
+ sequence_output = encoder_outputs[0]
850
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
851
+
852
+ if not return_dict:
853
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
854
+
855
+ return BaseModelOutputWithPoolingAndCrossAttentions(
856
+ last_hidden_state=sequence_output,
857
+ pooler_output=pooled_output,
858
+ past_key_values=encoder_outputs.past_key_values,
859
+ hidden_states=encoder_outputs.hidden_states,
860
+ attentions=encoder_outputs.attentions,
861
+ cross_attentions=encoder_outputs.cross_attentions,
862
+ )
863
+
864
+
865
+ class BertLMHeadModel(BertPreTrainedModel):
866
+
867
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
868
+ _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
869
+
870
+ def __init__(self, config):
871
+ super().__init__(config)
872
+
873
+ self.bert = BertModel(config, add_pooling_layer=False)
874
+ self.cls = BertOnlyMLMHead(config)
875
+
876
+ self.init_weights()
877
+
878
+ def get_output_embeddings(self):
879
+ return self.cls.predictions.decoder
880
+
881
+ def set_output_embeddings(self, new_embeddings):
882
+ self.cls.predictions.decoder = new_embeddings
883
+
884
+ def forward(
885
+ self,
886
+ input_ids=None,
887
+ attention_mask=None,
888
+ position_ids=None,
889
+ head_mask=None,
890
+ query_embeds=None,
891
+ encoder_hidden_states=None,
892
+ encoder_attention_mask=None,
893
+ labels=None,
894
+ past_key_values=None,
895
+ use_cache=True,
896
+ output_attentions=None,
897
+ output_hidden_states=None,
898
+ return_dict=None,
899
+ return_logits=False,
900
+ is_decoder=True,
901
+ reduction="mean",
902
+ ):
903
+ r"""
904
+ encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
905
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
906
+ the model is configured as a decoder.
907
+ encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
908
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
909
+ the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
910
+ - 1 for tokens that are **not masked**,
911
+ - 0 for tokens that are **masked**.
912
+ labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
913
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
914
+ ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are
915
+ ignored (masked), the loss is only computed for the tokens with labels n ``[0, ..., config.vocab_size]``
916
+ past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
917
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
918
+ If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
919
+ (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
920
+ instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
921
+ use_cache (:obj:`bool`, `optional`):
922
+ If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
923
+ decoding (see :obj:`past_key_values`).
924
+ Returns:
925
+ Example::
926
+ >>> from transformers import BertTokenizer, BertLMHeadModel, BertConfig
927
+ >>> import torch
928
+ >>> tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
929
+ >>> config = BertConfig.from_pretrained("bert-base-cased")
930
+ >>> model = BertLMHeadModel.from_pretrained('bert-base-cased', config=config)
931
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
932
+ >>> outputs = model(**inputs)
933
+ >>> prediction_logits = outputs.logits
934
+ """
935
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
936
+ if labels is not None:
937
+ use_cache = False
938
+ if past_key_values is not None:
939
+ query_embeds = None
940
+
941
+ outputs = self.bert(
942
+ input_ids,
943
+ attention_mask=attention_mask,
944
+ position_ids=position_ids,
945
+ head_mask=head_mask,
946
+ query_embeds=query_embeds,
947
+ encoder_hidden_states=encoder_hidden_states,
948
+ encoder_attention_mask=encoder_attention_mask,
949
+ past_key_values=past_key_values,
950
+ use_cache=use_cache,
951
+ output_attentions=output_attentions,
952
+ output_hidden_states=output_hidden_states,
953
+ return_dict=return_dict,
954
+ is_decoder=is_decoder,
955
+ )
956
+
957
+ sequence_output = outputs[0]
958
+ if query_embeds is not None:
959
+ sequence_output = outputs[0][:, query_embeds.shape[1] :, :]
960
+
961
+ prediction_scores = self.cls(sequence_output)
962
+
963
+ if return_logits:
964
+ return prediction_scores[:, :-1, :].contiguous()
965
+
966
+ lm_loss = None
967
+ if labels is not None:
968
+ # we are doing next-token prediction; shift prediction scores and input ids by one
969
+ shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
970
+ labels = labels[:, 1:].contiguous()
971
+ loss_fct = CrossEntropyLoss(reduction=reduction, label_smoothing=0.1)
972
+ lm_loss = loss_fct(
973
+ shifted_prediction_scores.view(-1, self.config.vocab_size),
974
+ labels.view(-1),
975
+ )
976
+ if reduction == "none":
977
+ lm_loss = lm_loss.view(prediction_scores.size(0), -1).sum(1)
978
+
979
+ if not return_dict:
980
+ output = (prediction_scores,) + outputs[2:]
981
+ return ((lm_loss,) + output) if lm_loss is not None else output
982
+
983
+ return CausalLMOutputWithCrossAttentions(
984
+ loss=lm_loss,
985
+ logits=prediction_scores,
986
+ past_key_values=outputs.past_key_values,
987
+ hidden_states=outputs.hidden_states,
988
+ attentions=outputs.attentions,
989
+ cross_attentions=outputs.cross_attentions,
990
+ )
991
+
992
+ def prepare_inputs_for_generation(self, input_ids, query_embeds, past=None, attention_mask=None, **model_kwargs):
993
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
994
+ if attention_mask is None:
995
+ attention_mask = input_ids.new_ones(input_ids.shape)
996
+ query_mask = input_ids.new_ones(query_embeds.shape[:-1])
997
+ attention_mask = torch.cat([query_mask, attention_mask], dim=-1)
998
+
999
+ # cut decoder_input_ids if past is used
1000
+ if past is not None:
1001
+ input_ids = input_ids[:, -1:]
1002
+
1003
+ return {
1004
+ "input_ids": input_ids,
1005
+ "query_embeds": query_embeds,
1006
+ "attention_mask": attention_mask,
1007
+ "past_key_values": past,
1008
+ "encoder_hidden_states": model_kwargs.get("encoder_hidden_states", None),
1009
+ "encoder_attention_mask": model_kwargs.get("encoder_attention_mask", None),
1010
+ "is_decoder": True,
1011
+ }
1012
+
1013
+ def _reorder_cache(self, past, beam_idx):
1014
+ reordered_past = ()
1015
+ for layer_past in past:
1016
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
1017
+ return reordered_past
1018
+
1019
+
1020
+ class BertForMaskedLM(BertPreTrainedModel):
1021
+
1022
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
1023
+ _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
1024
+
1025
+ def __init__(self, config):
1026
+ super().__init__(config)
1027
+
1028
+ self.bert = BertModel(config, add_pooling_layer=False)
1029
+ self.cls = BertOnlyMLMHead(config)
1030
+
1031
+ self.init_weights()
1032
+
1033
+ def get_output_embeddings(self):
1034
+ return self.cls.predictions.decoder
1035
+
1036
+ def set_output_embeddings(self, new_embeddings):
1037
+ self.cls.predictions.decoder = new_embeddings
1038
+
1039
+ def forward(
1040
+ self,
1041
+ input_ids=None,
1042
+ attention_mask=None,
1043
+ position_ids=None,
1044
+ head_mask=None,
1045
+ query_embeds=None,
1046
+ encoder_hidden_states=None,
1047
+ encoder_attention_mask=None,
1048
+ labels=None,
1049
+ output_attentions=None,
1050
+ output_hidden_states=None,
1051
+ return_dict=None,
1052
+ return_logits=False,
1053
+ is_decoder=False,
1054
+ ):
1055
+ r"""
1056
+ labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
1057
+ Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ...,
1058
+ config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored
1059
+ (masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]``
1060
+ """
1061
+
1062
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1063
+
1064
+ outputs = self.bert(
1065
+ input_ids,
1066
+ attention_mask=attention_mask,
1067
+ position_ids=position_ids,
1068
+ head_mask=head_mask,
1069
+ query_embeds=query_embeds,
1070
+ encoder_hidden_states=encoder_hidden_states,
1071
+ encoder_attention_mask=encoder_attention_mask,
1072
+ output_attentions=output_attentions,
1073
+ output_hidden_states=output_hidden_states,
1074
+ return_dict=return_dict,
1075
+ is_decoder=is_decoder,
1076
+ )
1077
+
1078
+ if query_embeds is not None:
1079
+ sequence_output = outputs[0][:, query_embeds.shape[1] :, :]
1080
+ prediction_scores = self.cls(sequence_output)
1081
+
1082
+ if return_logits:
1083
+ return prediction_scores
1084
+
1085
+ masked_lm_loss = None
1086
+ if labels is not None:
1087
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
1088
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1089
+
1090
+ if not return_dict:
1091
+ output = (prediction_scores,) + outputs[2:]
1092
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1093
+
1094
+ return MaskedLMOutput(
1095
+ loss=masked_lm_loss,
1096
+ logits=prediction_scores,
1097
+ hidden_states=outputs.hidden_states,
1098
+ attentions=outputs.attentions,
1099
+ )
1100
+
1101
+
1102
+ class Qformer(nn.Module):
1103
+ def __init__(self, model_args, vision_tower):
1104
+ super().__init__()
1105
+
1106
+ self.depth = model_args.mm_qformer_depth
1107
+ self.num_latents = model_args.mm_qformer_latents
1108
+ self.pretrained = model_args.mm_qformer_pretrained
1109
+
1110
+ self.Qformer, self.query_tokens, self.ln_vision = self.build_Qformer(vision_tower.hidden_size, self.depth, self.num_latents)
1111
+
1112
+ if self.pretrained is not None:
1113
+ pretrained_dict = torch.load(self.pretrained, map_location="cpu")["model"]
1114
+ pretrained_dict = {k: v for k, v in pretrained_dict.items() if not k.startswith("t5_proj")}
1115
+ self.load_state_dict(pretrained_dict)
1116
+
1117
+ def build_Qformer(self, vision_width, cross_attention_freq, num_query_token):
1118
+ encoder_config = BertConfig.from_pretrained("bert-base-uncased")
1119
+ encoder_config.encoder_width = vision_width
1120
+ # insert cross-attention layer every other block
1121
+ encoder_config.add_cross_attention = True
1122
+ encoder_config.cross_attention_freq = cross_attention_freq
1123
+ encoder_config.query_length = num_query_token
1124
+ Qformer = BertLMHeadModel(config=encoder_config)
1125
+ query_tokens = nn.Parameter(torch.zeros(1, num_query_token, encoder_config.hidden_size))
1126
+ query_tokens.data.normal_(mean=0.0, std=encoder_config.initializer_range)
1127
+ Qformer.cls = None
1128
+ Qformer.bert.embeddings.word_embeddings = None
1129
+ Qformer.bert.embeddings.position_embeddings = None
1130
+ for layer in Qformer.bert.encoder.layer:
1131
+ layer.output = None
1132
+ layer.intermediate = None
1133
+ return Qformer, query_tokens, nn.LayerNorm(vision_width)
1134
+
1135
+ def forward(self, image_features, *args, **kwargs):
1136
+ x = self.ln_vision(image_features)
1137
+ image_atts = torch.ones(x.size()[:-1], dtype=torch.long).to(x.device)
1138
+
1139
+ query_tokens = self.query_tokens.expand(x.shape[0], -1, -1)
1140
+ query_output = self.Qformer.bert(
1141
+ query_embeds=query_tokens,
1142
+ encoder_hidden_states=x,
1143
+ encoder_attention_mask=image_atts,
1144
+ return_dict=True,
1145
+ )
1146
+
1147
+ return query_output.last_hidden_state
1148
+
1149
+ @property
1150
+ def hidden_size(self):
1151
+ return 768
1152
+
1153
+ @property
1154
+ def config(self):
1155
+ return {
1156
+ "mm_resampler_type": "qformer",
1157
+ "mm_qformer_depth": self.depth,
1158
+ "mm_qformer_latents": self.num_latents,
1159
+ "mm_qformer_pretrained": self.pretrained,
1160
+ }
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/model/multimodal_resampler/spatial_pool.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import math
4
+
5
+
6
+ class SpatialPool(nn.Module):
7
+ def __init__(self, model_args, vision_tower):
8
+ super().__init__()
9
+
10
+ self.mode = model_args.mm_spatial_pool_mode
11
+ self.stride = model_args.mm_spatial_pool_stride
12
+ self.out_channels = getattr(model_args, "mm_spatial_pool_out_channels", vision_tower.hidden_size)
13
+
14
+ if self.mode == "average":
15
+ self.pool = nn.AvgPool2d(kernel_size=self.stride, stride=self.stride)
16
+ elif self.mode == "max":
17
+ self.pool = nn.MaxPool2d(kernel_size=self.stride, stride=self.stride)
18
+ elif self.mode == "conv":
19
+ self.pool = nn.Conv2d(in_channels=vision_tower.hidden_size, out_channels=self.out_channels, kernel_size=self.stride, stride=self.stride)
20
+ else:
21
+ raise ValueError(f"Unknown pooling mode: {self.pool}.")
22
+
23
+ def forward(self, image_features, images, *args, **kwargs):
24
+ ori_W = int(math.sqrt(image_features.shape[1] * images.shape[3] // images.shape[2]))
25
+ ori_H = int(ori_W * images.shape[2] // images.shape[3])
26
+
27
+ B, _, F = image_features.shape
28
+
29
+ image_features_spatial = image_features.view(B, ori_H, ori_H, F).permute(0, 3, 1, 2)
30
+ image_features_spatial_pool = self.pool(image_features_spatial)
31
+
32
+ return image_features_spatial_pool.flatten(2).transpose(1, 2).contiguous()
33
+
34
+ @property
35
+ def config(self):
36
+ return {
37
+ "mm_resampler_type": "spatial_pool",
38
+ "mm_spatial_pool_stride": self.stride,
39
+ "mm_spatial_pool_mode": self.mode,
40
+ "mm_spatial_pool_out_channels": self.out_channels,
41
+ }
42
+
43
+ @property
44
+ def hidden_size(self):
45
+ return self.out_channels
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/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)
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/serve/__init__.py ADDED
File without changes
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/serve/cli.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria
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)
33
+
34
+ if "llama-2" in model_name.lower():
35
+ conv_mode = "llava_llama_2"
36
+ elif "v1" in model_name.lower():
37
+ conv_mode = "llava_v1"
38
+ elif "mpt" in model_name.lower():
39
+ conv_mode = "mpt"
40
+ else:
41
+ conv_mode = "llava_v0"
42
+
43
+ if args.conv_mode is not None and conv_mode != args.conv_mode:
44
+ print("[WARNING] the auto inferred conversation mode is {}, while `--conv-mode` is {}, using {}".format(conv_mode, args.conv_mode, args.conv_mode))
45
+ else:
46
+ args.conv_mode = conv_mode
47
+
48
+ conv = conv_templates[args.conv_mode].copy()
49
+ if "mpt" in model_name.lower():
50
+ roles = ("user", "assistant")
51
+ else:
52
+ roles = conv.roles
53
+
54
+ image = load_image(args.image_file)
55
+ image_tensor = image_processor.preprocess(image, return_tensors="pt")["pixel_values"].half().cuda()
56
+
57
+ while True:
58
+ try:
59
+ inp = input(f"{roles[0]}: ")
60
+ except EOFError:
61
+ inp = ""
62
+ if not inp:
63
+ print("exit...")
64
+ break
65
+
66
+ print(f"{roles[1]}: ", end="")
67
+
68
+ if image is not None:
69
+ # first message
70
+ if model.config.mm_use_im_start_end:
71
+ inp = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + "\n" + inp
72
+ else:
73
+ inp = DEFAULT_IMAGE_TOKEN + "\n" + inp
74
+ conv.append_message(conv.roles[0], inp)
75
+ image = None
76
+ else:
77
+ # later messages
78
+ conv.append_message(conv.roles[0], inp)
79
+ conv.append_message(conv.roles[1], None)
80
+ prompt = conv.get_prompt()
81
+
82
+ input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).cuda()
83
+ stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
84
+ keywords = [stop_str]
85
+ stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
86
+ streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
87
+
88
+ with torch.inference_mode():
89
+ output_ids = model.generate(input_ids, images=image_tensor, do_sample=True, temperature=0.2, max_new_tokens=1024, streamer=streamer, use_cache=True, stopping_criteria=[stopping_criteria])
90
+
91
+ outputs = tokenizer.decode(output_ids[0, input_ids.shape[1] :]).strip()
92
+ conv.messages[-1][-1] = outputs
93
+
94
+ if args.debug:
95
+ print("\n", {"prompt": prompt, "outputs": outputs}, "\n")
96
+
97
+
98
+ if __name__ == "__main__":
99
+ parser = argparse.ArgumentParser()
100
+ parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
101
+ parser.add_argument("--model-base", type=str, default=None)
102
+ parser.add_argument("--image-file", type=str, required=True)
103
+ parser.add_argument("--num-gpus", type=int, default=1)
104
+ parser.add_argument("--conv-mode", type=str, default=None)
105
+ parser.add_argument("--temperature", type=float, default=0.2)
106
+ parser.add_argument("--max-new-tokens", type=int, default=512)
107
+ parser.add_argument("--load-8bit", action="store_true")
108
+ parser.add_argument("--load-4bit", action="store_true")
109
+ parser.add_argument("--debug", action="store_true")
110
+ args = parser.parse_args()
111
+ main(args)
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/serve/controller.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A controller manages distributed workers.
3
+ It sends worker addresses to clients.
4
+ """
5
+
6
+ import argparse
7
+ import asyncio
8
+ import dataclasses
9
+ from enum import Enum, auto
10
+ import json
11
+ import logging
12
+ import time
13
+ from typing import List, Union
14
+ import threading
15
+
16
+ from fastapi import FastAPI, Request
17
+ from fastapi.responses import StreamingResponse
18
+ import numpy as np
19
+ import requests
20
+ import uvicorn
21
+
22
+ from llava.constants import CONTROLLER_HEART_BEAT_EXPIRATION
23
+ from llava.utils import build_logger, server_error_msg
24
+
25
+
26
+ logger = build_logger("controller", "controller.log")
27
+
28
+
29
+ class DispatchMethod(Enum):
30
+ LOTTERY = auto()
31
+ SHORTEST_QUEUE = auto()
32
+
33
+ @classmethod
34
+ def from_str(cls, name):
35
+ if name == "lottery":
36
+ return cls.LOTTERY
37
+ elif name == "shortest_queue":
38
+ return cls.SHORTEST_QUEUE
39
+ else:
40
+ raise ValueError(f"Invalid dispatch method")
41
+
42
+
43
+ @dataclasses.dataclass
44
+ class WorkerInfo:
45
+ model_names: List[str]
46
+ speed: int
47
+ queue_length: int
48
+ check_heart_beat: bool
49
+ last_heart_beat: str
50
+
51
+
52
+ def heart_beat_controller(controller):
53
+ while True:
54
+ time.sleep(CONTROLLER_HEART_BEAT_EXPIRATION)
55
+ controller.remove_stable_workers_by_expiration()
56
+
57
+
58
+ class Controller:
59
+ def __init__(self, dispatch_method: str):
60
+ # Dict[str -> WorkerInfo]
61
+ self.worker_info = {}
62
+ self.dispatch_method = DispatchMethod.from_str(dispatch_method)
63
+
64
+ self.heart_beat_thread = threading.Thread(target=heart_beat_controller, args=(self,))
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, worker_status: dict):
70
+ if worker_name not in self.worker_info:
71
+ logger.info(f"Register a new worker: {worker_name}")
72
+ else:
73
+ logger.info(f"Register an existing worker: {worker_name}")
74
+
75
+ if not worker_status:
76
+ worker_status = self.get_worker_status(worker_name)
77
+ if not worker_status:
78
+ return False
79
+
80
+ self.worker_info[worker_name] = WorkerInfo(worker_status["model_names"], worker_status["speed"], worker_status["queue_length"], check_heart_beat, time.time())
81
+
82
+ logger.info(f"Register done: {worker_name}, {worker_status}")
83
+ return True
84
+
85
+ def get_worker_status(self, worker_name: str):
86
+ try:
87
+ r = requests.post(worker_name + "/worker_get_status", timeout=5)
88
+ except requests.exceptions.RequestException as e:
89
+ logger.error(f"Get status fails: {worker_name}, {e}")
90
+ return None
91
+
92
+ if r.status_code != 200:
93
+ logger.error(f"Get status fails: {worker_name}, {r}")
94
+ return None
95
+
96
+ return r.json()
97
+
98
+ def remove_worker(self, worker_name: str):
99
+ del self.worker_info[worker_name]
100
+
101
+ def refresh_all_workers(self):
102
+ old_info = dict(self.worker_info)
103
+ self.worker_info = {}
104
+
105
+ for w_name, w_info in old_info.items():
106
+ if not self.register_worker(w_name, w_info.check_heart_beat, None):
107
+ logger.info(f"Remove stale worker: {w_name}")
108
+
109
+ def list_models(self):
110
+ model_names = set()
111
+
112
+ for w_name, w_info in self.worker_info.items():
113
+ model_names.update(w_info.model_names)
114
+
115
+ return list(model_names)
116
+
117
+ def get_worker_address(self, model_name: str):
118
+ if self.dispatch_method == DispatchMethod.LOTTERY:
119
+ worker_names = []
120
+ worker_speeds = []
121
+ for w_name, w_info in self.worker_info.items():
122
+ if model_name in w_info.model_names:
123
+ worker_names.append(w_name)
124
+ worker_speeds.append(w_info.speed)
125
+ worker_speeds = np.array(worker_speeds, dtype=np.float32)
126
+ norm = np.sum(worker_speeds)
127
+ if norm < 1e-4:
128
+ return ""
129
+ worker_speeds = worker_speeds / norm
130
+ if True: # Directly return address
131
+ pt = np.random.choice(np.arange(len(worker_names)), p=worker_speeds)
132
+ worker_name = worker_names[pt]
133
+ return worker_name
134
+
135
+ # Check status before returning
136
+ while True:
137
+ pt = np.random.choice(np.arange(len(worker_names)), p=worker_speeds)
138
+ worker_name = worker_names[pt]
139
+
140
+ if self.get_worker_status(worker_name):
141
+ break
142
+ else:
143
+ self.remove_worker(worker_name)
144
+ worker_speeds[pt] = 0
145
+ norm = np.sum(worker_speeds)
146
+ if norm < 1e-4:
147
+ return ""
148
+ worker_speeds = worker_speeds / norm
149
+ continue
150
+ return worker_name
151
+ elif self.dispatch_method == DispatchMethod.SHORTEST_QUEUE:
152
+ worker_names = []
153
+ worker_qlen = []
154
+ for w_name, w_info in self.worker_info.items():
155
+ if model_name in w_info.model_names:
156
+ worker_names.append(w_name)
157
+ worker_qlen.append(w_info.queue_length / w_info.speed)
158
+ if len(worker_names) == 0:
159
+ return ""
160
+ min_index = np.argmin(worker_qlen)
161
+ w_name = worker_names[min_index]
162
+ self.worker_info[w_name].queue_length += 1
163
+ logger.info(f"names: {worker_names}, queue_lens: {worker_qlen}, ret: {w_name}")
164
+ return w_name
165
+ else:
166
+ raise ValueError(f"Invalid dispatch method: {self.dispatch_method}")
167
+
168
+ def receive_heart_beat(self, worker_name: str, queue_length: int):
169
+ if worker_name not in self.worker_info:
170
+ logger.info(f"Receive unknown heart beat. {worker_name}")
171
+ return False
172
+
173
+ self.worker_info[worker_name].queue_length = queue_length
174
+ self.worker_info[worker_name].last_heart_beat = time.time()
175
+ logger.info(f"Receive heart beat. {worker_name}")
176
+ return True
177
+
178
+ def remove_stable_workers_by_expiration(self):
179
+ expire = time.time() - CONTROLLER_HEART_BEAT_EXPIRATION
180
+ to_delete = []
181
+ for worker_name, w_info in self.worker_info.items():
182
+ if w_info.check_heart_beat and w_info.last_heart_beat < expire:
183
+ to_delete.append(worker_name)
184
+
185
+ for worker_name in to_delete:
186
+ self.remove_worker(worker_name)
187
+
188
+ def worker_api_generate_stream(self, params):
189
+ worker_addr = self.get_worker_address(params["model"])
190
+ if not worker_addr:
191
+ logger.info(f"no worker: {params['model']}")
192
+ ret = {
193
+ "text": server_error_msg,
194
+ "error_code": 2,
195
+ }
196
+ yield json.dumps(ret).encode() + b"\0"
197
+
198
+ try:
199
+ response = requests.post(worker_addr + "/worker_generate_stream", json=params, stream=True, timeout=5)
200
+ for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
201
+ if chunk:
202
+ yield chunk + b"\0"
203
+ except requests.exceptions.RequestException as e:
204
+ logger.info(f"worker timeout: {worker_addr}")
205
+ ret = {
206
+ "text": server_error_msg,
207
+ "error_code": 3,
208
+ }
209
+ yield json.dumps(ret).encode() + b"\0"
210
+
211
+ # Let the controller act as a worker to achieve hierarchical
212
+ # management. This can be used to connect isolated sub networks.
213
+ def worker_api_get_status(self):
214
+ model_names = set()
215
+ speed = 0
216
+ queue_length = 0
217
+
218
+ for w_name in self.worker_info:
219
+ worker_status = self.get_worker_status(w_name)
220
+ if worker_status is not None:
221
+ model_names.update(worker_status["model_names"])
222
+ speed += worker_status["speed"]
223
+ queue_length += worker_status["queue_length"]
224
+
225
+ return {
226
+ "model_names": list(model_names),
227
+ "speed": speed,
228
+ "queue_length": queue_length,
229
+ }
230
+
231
+
232
+ app = FastAPI()
233
+
234
+
235
+ @app.post("/register_worker")
236
+ async def register_worker(request: Request):
237
+ data = await request.json()
238
+ controller.register_worker(data["worker_name"], data["check_heart_beat"], data.get("worker_status", None))
239
+
240
+
241
+ @app.post("/refresh_all_workers")
242
+ async def refresh_all_workers():
243
+ models = controller.refresh_all_workers()
244
+
245
+
246
+ @app.post("/list_models")
247
+ async def list_models():
248
+ models = controller.list_models()
249
+ return {"models": models}
250
+
251
+
252
+ @app.post("/get_worker_address")
253
+ async def get_worker_address(request: Request):
254
+ data = await request.json()
255
+ addr = controller.get_worker_address(data["model"])
256
+ return {"address": addr}
257
+
258
+
259
+ @app.post("/receive_heart_beat")
260
+ async def receive_heart_beat(request: Request):
261
+ data = await request.json()
262
+ exist = controller.receive_heart_beat(data["worker_name"], data["queue_length"])
263
+ return {"exist": exist}
264
+
265
+
266
+ @app.post("/worker_generate_stream")
267
+ async def worker_api_generate_stream(request: Request):
268
+ params = await request.json()
269
+ generator = controller.worker_api_generate_stream(params)
270
+ return StreamingResponse(generator)
271
+
272
+
273
+ @app.post("/worker_get_status")
274
+ async def worker_api_get_status(request: Request):
275
+ return controller.worker_api_get_status()
276
+
277
+
278
+ if __name__ == "__main__":
279
+ parser = argparse.ArgumentParser()
280
+ parser.add_argument("--host", type=str, default="localhost")
281
+ parser.add_argument("--port", type=int, default=21001)
282
+ parser.add_argument("--dispatch-method", type=str, choices=["lottery", "shortest_queue"], default="shortest_queue")
283
+ args = parser.parse_args()
284
+ logger.info(f"args: {args}")
285
+
286
+ controller = Controller(args.dispatch_method)
287
+ uvicorn.run(app, host=args.host, port=args.port, log_level="info")
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/serve/examples/extreme_ironing.jpg ADDED

Git LFS Details

  • SHA256: a54caa21bc513ed25c8ca7f5747555c05dfd4e33f6a3cf5c08b3d9138a4da1d9
  • Pointer size: 130 Bytes
  • Size of remote file: 62.6 kB
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/serve/examples/waterview.jpg ADDED

Git LFS Details

  • SHA256: d092764cc9f21b9bc535ff5284b5add4d8256148bab1bc2f5b5ab3fd32759a36
  • Pointer size: 130 Bytes
  • Size of remote file: 95.5 kB
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/serve/gradio_multi_image.py ADDED
@@ -0,0 +1,448 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, SeparatorStyle
11
+ from llava.constants import LOGDIR
12
+ from llava.utils import build_logger, server_error_msg, violates_moderation, moderation_msg
13
+ import hashlib
14
+
15
+
16
+ logger = build_logger("gradio_web_server", "gradio_web_server.log")
17
+
18
+ headers = {"User-Agent": "LLaVA Client"}
19
+
20
+ no_change_btn = gr.Button.update()
21
+ enable_btn = gr.Button.update(interactive=True)
22
+ disable_btn = gr.Button.update(interactive=False)
23
+
24
+ priority = {
25
+ "vicuna-13b": "aaaaaaa",
26
+ "koala-13b": "aaaaaab",
27
+ }
28
+
29
+
30
+ def get_conv_log_filename():
31
+ t = datetime.datetime.now()
32
+ name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-conv.json")
33
+ return name
34
+
35
+
36
+ def get_model_list():
37
+ ret = requests.post(args.controller_url + "/refresh_all_workers")
38
+ assert ret.status_code == 200
39
+ ret = requests.post(args.controller_url + "/list_models")
40
+ models = ret.json()["models"]
41
+ models.sort(key=lambda x: priority.get(x, x))
42
+ logger.info(f"Models: {models}")
43
+ return models
44
+
45
+
46
+ get_window_url_params = """
47
+ function() {
48
+ const params = new URLSearchParams(window.location.search);
49
+ url_params = Object.fromEntries(params);
50
+ console.log(url_params);
51
+ return url_params;
52
+ }
53
+ """
54
+
55
+
56
+ def load_demo(url_params, request: gr.Request):
57
+ logger.info(f"load_demo. ip: {request.client.host}. params: {url_params}")
58
+
59
+ dropdown_update = gr.Dropdown.update(visible=True)
60
+ if "model" in url_params:
61
+ model = url_params["model"]
62
+ if model in models:
63
+ dropdown_update = gr.Dropdown.update(value=model, visible=True)
64
+
65
+ state = default_conversation.copy()
66
+ return (state, dropdown_update, gr.Chatbot.update(visible=True), gr.Textbox.update(visible=True), gr.Button.update(visible=True), gr.Row.update(visible=True), gr.Accordion.update(visible=True))
67
+
68
+
69
+ def load_demo_refresh_model_list(request: gr.Request):
70
+ logger.info(f"load_demo. ip: {request.client.host}")
71
+ models = get_model_list()
72
+ state = default_conversation.copy()
73
+ return (
74
+ state,
75
+ gr.Dropdown.update(choices=models, value=models[0] if len(models) > 0 else ""),
76
+ gr.Chatbot.update(visible=True),
77
+ gr.Textbox.update(visible=True),
78
+ gr.Button.update(visible=True),
79
+ gr.Row.update(visible=True),
80
+ gr.Accordion.update(visible=True),
81
+ )
82
+
83
+
84
+ def vote_last_response(state, vote_type, model_selector, request: gr.Request):
85
+ with open(get_conv_log_filename(), "a") as fout:
86
+ data = {
87
+ "tstamp": round(time.time(), 4),
88
+ "type": vote_type,
89
+ "model": model_selector,
90
+ "state": state.dict(),
91
+ "ip": request.client.host,
92
+ }
93
+ fout.write(json.dumps(data) + "\n")
94
+
95
+
96
+ def upvote_last_response(state, model_selector, request: gr.Request):
97
+ logger.info(f"upvote. ip: {request.client.host}")
98
+ vote_last_response(state, "upvote", model_selector, request)
99
+ return ("",) + (disable_btn,) * 3
100
+
101
+
102
+ def downvote_last_response(state, model_selector, request: gr.Request):
103
+ logger.info(f"downvote. ip: {request.client.host}")
104
+ vote_last_response(state, "downvote", model_selector, request)
105
+ return ("",) + (disable_btn,) * 3
106
+
107
+
108
+ def flag_last_response(state, model_selector, request: gr.Request):
109
+ logger.info(f"flag. ip: {request.client.host}")
110
+ vote_last_response(state, "flag", model_selector, request)
111
+ return ("",) + (disable_btn,) * 3
112
+
113
+
114
+ def regenerate(state, image_process_mode, request: gr.Request):
115
+ logger.info(f"regenerate. ip: {request.client.host}")
116
+ state.messages[-1][-1] = None
117
+ prev_human_msg = state.messages[-2]
118
+ if type(prev_human_msg[1]) in (tuple, list):
119
+ prev_human_msg[1] = (*prev_human_msg[1][:2], image_process_mode)
120
+ state.skip_next = False
121
+ return (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn,) * 5
122
+
123
+
124
+ def clear_history(request: gr.Request):
125
+ logger.info(f"clear_history. ip: {request.client.host}")
126
+ state = default_conversation.copy()
127
+ return (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn,) * 5
128
+
129
+
130
+ def add_text(state, text, image, image2, image_process_mode, request: gr.Request):
131
+ logger.info(f"add_text. ip: {request.client.host}. len: {len(text)}")
132
+ if len(text) <= 0 and image is None:
133
+ state.skip_next = True
134
+ return (state, state.to_gradio_chatbot(), "", None) + (no_change_btn,) * 5
135
+ if args.moderate:
136
+ flagged = violates_moderation(text)
137
+ if flagged:
138
+ state.skip_next = True
139
+ return (state, state.to_gradio_chatbot(), moderation_msg, None) + (no_change_btn,) * 5
140
+
141
+ text = text[:3072] # Hard cut-off
142
+ images = [x for x in [image, image2] if x is not None]
143
+ num_images = len(images)
144
+ if num_images > 0:
145
+ text = text.replace("<image>", "").strip()
146
+ text = text[: 3072 - 512 * num_images]
147
+ text = "<image>\n" * num_images + text
148
+ text = (text, images, image_process_mode)
149
+ if len(state.get_images(return_pil=True)) > 0:
150
+ state = default_conversation.copy()
151
+ state.append_message(state.roles[0], text)
152
+ state.append_message(state.roles[1], None)
153
+ state.skip_next = False
154
+ return (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn,) * 5
155
+
156
+
157
+ def http_bot(state, model_selector, temperature, top_p, max_new_tokens, request: gr.Request):
158
+ logger.info(f"http_bot. ip: {request.client.host}")
159
+ start_tstamp = time.time()
160
+ model_name = model_selector
161
+
162
+ if state.skip_next:
163
+ # This generate call is skipped due to invalid inputs
164
+ yield (state, state.to_gradio_chatbot()) + (no_change_btn,) * 5
165
+ return
166
+
167
+ if len(state.messages) == state.offset + 2:
168
+ # First round of conversation
169
+ if "llava" in model_name.lower():
170
+ if "llama-2" in model_name.lower():
171
+ if "sharegpt" in model_name.lower():
172
+ if "mmtag" in model_name.lower():
173
+ template_name = "v1_mmtag"
174
+ elif "plain" in model_name.lower() and "finetune" not in model_name.lower():
175
+ template_name = "v1_mmtag"
176
+ else:
177
+ template_name = "llava_v1"
178
+ else:
179
+ if "mmtag" in model_name.lower():
180
+ template_name = "llava_llama_2_mmtag"
181
+ elif "simple" in model_name.lower():
182
+ template_name = "llava_llama_2_simple"
183
+ elif "plain" in model_name.lower() and "finetune" not in model_name.lower():
184
+ template_name = "llava_llama_2_mmtag"
185
+ elif "simple" in model_name.lower():
186
+ template_name = "llava_llama_2_simple"
187
+ else:
188
+ template_name = "llava_llama_2"
189
+ elif "v1" in model_name.lower():
190
+ if "mmtag" in model_name.lower():
191
+ template_name = "v1_mmtag"
192
+ elif "plain" in model_name.lower() and "finetune" not in model_name.lower():
193
+ template_name = "v1_mmtag"
194
+ else:
195
+ template_name = "llava_v1"
196
+ elif "mpt" in model_name.lower():
197
+ template_name = "mpt"
198
+ else:
199
+ if "mmtag" in model_name.lower():
200
+ template_name = "v0_mmtag"
201
+ elif "plain" in model_name.lower() and "finetune" not in model_name.lower():
202
+ template_name = "v0_mmtag"
203
+ else:
204
+ template_name = "llava_v0"
205
+ elif "mpt" in model_name.lower():
206
+ template_name = "mpt_text"
207
+ elif "llama-2" in model_name.lower():
208
+ if "sharegpt" in model_name.lower():
209
+ template_name = "vicuna_v1"
210
+ else:
211
+ template_name = "llama_2"
212
+ else:
213
+ template_name = "vicuna_v1"
214
+ new_state = conv_templates[template_name].copy()
215
+ new_state.append_message(new_state.roles[0], state.messages[-2][1])
216
+ new_state.append_message(new_state.roles[1], None)
217
+ state = new_state
218
+
219
+ # Query worker address
220
+ controller_url = args.controller_url
221
+ ret = requests.post(controller_url + "/get_worker_address", json={"model": model_name})
222
+ worker_addr = ret.json()["address"]
223
+ logger.info(f"model_name: {model_name}, worker_addr: {worker_addr}")
224
+
225
+ # No available worker
226
+ if worker_addr == "":
227
+ state.messages[-1][-1] = server_error_msg
228
+ yield (state, state.to_gradio_chatbot(), disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
229
+ return
230
+
231
+ # Construct prompt
232
+ prompt = state.get_prompt()
233
+
234
+ all_images = state.get_images(return_pil=True)
235
+ all_image_hash = [hashlib.md5(image.tobytes()).hexdigest() for image in all_images]
236
+ for image, hash in zip(all_images, all_image_hash):
237
+ t = datetime.datetime.now()
238
+ filename = os.path.join(LOGDIR, "serve_images", f"{t.year}-{t.month:02d}-{t.day:02d}", f"{hash}.jpg")
239
+ if not os.path.isfile(filename):
240
+ os.makedirs(os.path.dirname(filename), exist_ok=True)
241
+ image.save(filename)
242
+
243
+ # Make requests
244
+ pload = {
245
+ "model": model_name,
246
+ "prompt": prompt,
247
+ "temperature": float(temperature),
248
+ "top_p": float(top_p),
249
+ "max_new_tokens": min(int(max_new_tokens), 1536),
250
+ "stop": state.sep if state.sep_style in [SeparatorStyle.SINGLE, SeparatorStyle.MPT] else state.sep2,
251
+ "images": f"List of {len(state.get_images())} images: {all_image_hash}",
252
+ }
253
+ logger.info(f"==== request ====\n{pload}")
254
+
255
+ pload["images"] = state.get_images()
256
+
257
+ state.messages[-1][-1] = "▌"
258
+ yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
259
+
260
+ try:
261
+ # Stream output
262
+ response = requests.post(worker_addr + "/worker_generate_stream", headers=headers, json=pload, stream=True, timeout=10)
263
+ for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
264
+ if chunk:
265
+ data = json.loads(chunk.decode())
266
+ if data["error_code"] == 0:
267
+ output = data["text"][len(prompt) :].strip()
268
+ state.messages[-1][-1] = output + "▌"
269
+ yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
270
+ else:
271
+ output = data["text"] + f" (error_code: {data['error_code']})"
272
+ state.messages[-1][-1] = output
273
+ yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
274
+ return
275
+ time.sleep(0.03)
276
+ except requests.exceptions.RequestException as e:
277
+ state.messages[-1][-1] = server_error_msg
278
+ yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
279
+ return
280
+
281
+ state.messages[-1][-1] = state.messages[-1][-1][:-1]
282
+ yield (state, state.to_gradio_chatbot()) + (enable_btn,) * 5
283
+
284
+ finish_tstamp = time.time()
285
+ logger.info(f"{output}")
286
+
287
+ with open(get_conv_log_filename(), "a") as fout:
288
+ data = {
289
+ "tstamp": round(finish_tstamp, 4),
290
+ "type": "chat",
291
+ "model": model_name,
292
+ "start": round(start_tstamp, 4),
293
+ "finish": round(start_tstamp, 4),
294
+ "state": state.dict(),
295
+ "images": all_image_hash,
296
+ "ip": request.client.host,
297
+ }
298
+ fout.write(json.dumps(data) + "\n")
299
+
300
+
301
+ title_markdown = """
302
+ # 🌋 LLaVA: Large Language and Vision Assistant
303
+ [[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)]
304
+ """
305
+
306
+ tos_markdown = """
307
+ ### Terms of use
308
+ By using this service, users are required to agree to the following terms:
309
+ 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.
310
+ Please click the "Flag" button if you get any inappropriate answer! We will collect those to keep improving our moderator.
311
+ For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality.
312
+ """
313
+
314
+
315
+ learn_more_markdown = """
316
+ ### License
317
+ 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.
318
+ """
319
+
320
+ block_css = """
321
+
322
+ #buttons button {
323
+ min-width: min(120px,100%);
324
+ }
325
+
326
+ #chatbot img {
327
+ display: inline-block;
328
+ }
329
+
330
+ """
331
+
332
+
333
+ def build_demo(embed_mode):
334
+ textbox = gr.Textbox(show_label=False, placeholder="Enter text and press ENTER", container=False)
335
+ with gr.Blocks(title="LLaVA", theme=gr.themes.Default(), css=block_css) as demo:
336
+ state = gr.State()
337
+
338
+ if not embed_mode:
339
+ gr.Markdown(title_markdown)
340
+
341
+ with gr.Row():
342
+ with gr.Column(scale=3):
343
+ with gr.Row(elem_id="model_selector_row"):
344
+ model_selector = gr.Dropdown(choices=models, value=models[0] if len(models) > 0 else "", interactive=True, show_label=False, container=False)
345
+
346
+ with gr.Row(elem_id="images"):
347
+ imagebox = gr.Image(type="pil")
348
+ imagebox_2 = gr.Image(type="pil")
349
+ image_process_mode = gr.Radio(["Crop", "Resize", "Pad", "Default"], value="Default", label="Preprocess for non-square image", visible=False)
350
+
351
+ cur_dir = os.path.dirname(os.path.abspath(__file__))
352
+ gr.Examples(
353
+ examples=[
354
+ [f"{cur_dir}/examples/extreme_ironing.jpg", "What is unusual about this image?"],
355
+ [f"{cur_dir}/examples/waterview.jpg", "What are the things I should be cautious about when I visit here?"],
356
+ ],
357
+ inputs=[imagebox, textbox],
358
+ )
359
+
360
+ with gr.Accordion("Parameters", open=False, visible=False) as parameter_row:
361
+ temperature = gr.Slider(
362
+ minimum=0.0,
363
+ maximum=1.0,
364
+ value=0.2,
365
+ step=0.1,
366
+ interactive=True,
367
+ label="Temperature",
368
+ )
369
+ top_p = gr.Slider(
370
+ minimum=0.0,
371
+ maximum=1.0,
372
+ value=0.7,
373
+ step=0.1,
374
+ interactive=True,
375
+ label="Top P",
376
+ )
377
+ max_output_tokens = gr.Slider(
378
+ minimum=0,
379
+ maximum=1024,
380
+ value=512,
381
+ step=64,
382
+ interactive=True,
383
+ label="Max output tokens",
384
+ )
385
+
386
+ with gr.Column(scale=8):
387
+ chatbot = gr.Chatbot(elem_id="chatbot", label="LLaVA Chatbot", visible=False, height=550)
388
+ with gr.Row():
389
+ with gr.Column(scale=8):
390
+ textbox.render()
391
+ with gr.Column(scale=1, min_width=50):
392
+ submit_btn = gr.Button(value="Submit", visible=False)
393
+ with gr.Row(visible=False) as button_row:
394
+ upvote_btn = gr.Button(value="👍 Upvote", interactive=False)
395
+ downvote_btn = gr.Button(value="👎 Downvote", interactive=False)
396
+ flag_btn = gr.Button(value="⚠️ Flag", interactive=False)
397
+ # stop_btn = gr.Button(value="⏹️ Stop Generation", interactive=False)
398
+ regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=False)
399
+ clear_btn = gr.Button(value="🗑️ Clear", interactive=False)
400
+
401
+ if not embed_mode:
402
+ gr.Markdown(tos_markdown)
403
+ gr.Markdown(learn_more_markdown)
404
+ url_params = gr.JSON(visible=False)
405
+
406
+ # Register listeners
407
+ btn_list = [upvote_btn, downvote_btn, flag_btn, regenerate_btn, clear_btn]
408
+ upvote_btn.click(upvote_last_response, [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn])
409
+ downvote_btn.click(downvote_last_response, [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn])
410
+ flag_btn.click(flag_last_response, [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn])
411
+ regenerate_btn.click(regenerate, [state, image_process_mode], [state, chatbot, textbox, imagebox, imagebox_2] + btn_list).then(http_bot, [state, model_selector, temperature, top_p, max_output_tokens], [state, chatbot] + btn_list)
412
+ clear_btn.click(clear_history, None, [state, chatbot, textbox, imagebox, imagebox_2] + btn_list)
413
+
414
+ textbox.submit(add_text, [state, textbox, imagebox, imagebox_2, image_process_mode], [state, chatbot, textbox, imagebox, imagebox_2] + btn_list).then(
415
+ http_bot, [state, model_selector, temperature, top_p, max_output_tokens], [state, chatbot] + btn_list
416
+ )
417
+ submit_btn.click(add_text, [state, textbox, imagebox, imagebox_2, image_process_mode], [state, chatbot, textbox, imagebox, imagebox_2] + btn_list).then(
418
+ http_bot, [state, model_selector, temperature, top_p, max_output_tokens], [state, chatbot] + btn_list
419
+ )
420
+
421
+ if args.model_list_mode == "once":
422
+ demo.load(load_demo, [url_params], [state, model_selector, chatbot, textbox, submit_btn, button_row, parameter_row], _js=get_window_url_params)
423
+ elif args.model_list_mode == "reload":
424
+ demo.load(load_demo_refresh_model_list, None, [state, model_selector, chatbot, textbox, submit_btn, button_row, parameter_row])
425
+ else:
426
+ raise ValueError(f"Unknown model list mode: {args.model_list_mode}")
427
+
428
+ return demo
429
+
430
+
431
+ if __name__ == "__main__":
432
+ parser = argparse.ArgumentParser()
433
+ parser.add_argument("--host", type=str, default="0.0.0.0")
434
+ parser.add_argument("--port", type=int)
435
+ parser.add_argument("--controller-url", type=str, default="http://localhost:21001")
436
+ parser.add_argument("--concurrency-count", type=int, default=8)
437
+ parser.add_argument("--model-list-mode", type=str, default="once", choices=["once", "reload"])
438
+ parser.add_argument("--share", action="store_true")
439
+ parser.add_argument("--moderate", action="store_true")
440
+ parser.add_argument("--embed", action="store_true")
441
+ args = parser.parse_args()
442
+ logger.info(f"args: {args}")
443
+
444
+ models = get_model_list()
445
+
446
+ logger.info(args)
447
+ demo = build_demo(args.embed)
448
+ demo.queue(concurrency_count=args.concurrency_count, status_update_rate=10, api_open=False).launch(server_name=args.host, server_port=args.port, share=args.share)
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/serve/gradio_web_server.py ADDED
@@ -0,0 +1,442 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, SeparatorStyle
11
+ from llava.constants import LOGDIR
12
+ from llava.utils import build_logger, server_error_msg, violates_moderation, moderation_msg
13
+ import hashlib
14
+
15
+
16
+ logger = build_logger("gradio_web_server", "gradio_web_server.log")
17
+
18
+ headers = {"User-Agent": "LLaVA Client"}
19
+
20
+ no_change_btn = gr.Button.update()
21
+ enable_btn = gr.Button.update(interactive=True)
22
+ disable_btn = gr.Button.update(interactive=False)
23
+
24
+ priority = {
25
+ "vicuna-13b": "aaaaaaa",
26
+ "koala-13b": "aaaaaab",
27
+ }
28
+
29
+
30
+ def get_conv_log_filename():
31
+ t = datetime.datetime.now()
32
+ name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-conv.json")
33
+ return name
34
+
35
+
36
+ def get_model_list():
37
+ ret = requests.post(args.controller_url + "/refresh_all_workers")
38
+ assert ret.status_code == 200
39
+ ret = requests.post(args.controller_url + "/list_models")
40
+ models = ret.json()["models"]
41
+ models.sort(key=lambda x: priority.get(x, x))
42
+ logger.info(f"Models: {models}")
43
+ return models
44
+
45
+
46
+ get_window_url_params = """
47
+ function() {
48
+ const params = new URLSearchParams(window.location.search);
49
+ url_params = Object.fromEntries(params);
50
+ console.log(url_params);
51
+ return url_params;
52
+ }
53
+ """
54
+
55
+
56
+ def load_demo(url_params, request: gr.Request):
57
+ logger.info(f"load_demo. ip: {request.client.host}. params: {url_params}")
58
+
59
+ dropdown_update = gr.Dropdown.update(visible=True)
60
+ if "model" in url_params:
61
+ model = url_params["model"]
62
+ if model in models:
63
+ dropdown_update = gr.Dropdown.update(value=model, visible=True)
64
+
65
+ state = default_conversation.copy()
66
+ return state, dropdown_update
67
+
68
+
69
+ def load_demo_refresh_model_list(request: gr.Request):
70
+ logger.info(f"load_demo. ip: {request.client.host}")
71
+ models = get_model_list()
72
+ state = default_conversation.copy()
73
+ dropdown_update = gr.Dropdown.update(choices=models, value=models[0] if len(models) > 0 else "")
74
+ return state, dropdown_update
75
+
76
+
77
+ def vote_last_response(state, vote_type, model_selector, request: gr.Request):
78
+ with open(get_conv_log_filename(), "a") as fout:
79
+ data = {
80
+ "tstamp": round(time.time(), 4),
81
+ "type": vote_type,
82
+ "model": model_selector,
83
+ "state": state.dict(),
84
+ "ip": request.client.host,
85
+ }
86
+ fout.write(json.dumps(data) + "\n")
87
+
88
+
89
+ def upvote_last_response(state, model_selector, request: gr.Request):
90
+ logger.info(f"upvote. ip: {request.client.host}")
91
+ vote_last_response(state, "upvote", model_selector, request)
92
+ return ("",) + (disable_btn,) * 3
93
+
94
+
95
+ def downvote_last_response(state, model_selector, request: gr.Request):
96
+ logger.info(f"downvote. ip: {request.client.host}")
97
+ vote_last_response(state, "downvote", model_selector, request)
98
+ return ("",) + (disable_btn,) * 3
99
+
100
+
101
+ def flag_last_response(state, model_selector, request: gr.Request):
102
+ logger.info(f"flag. ip: {request.client.host}")
103
+ vote_last_response(state, "flag", model_selector, request)
104
+ return ("",) + (disable_btn,) * 3
105
+
106
+
107
+ def regenerate(state, image_process_mode, request: gr.Request):
108
+ logger.info(f"regenerate. ip: {request.client.host}")
109
+ state.messages[-1][-1] = None
110
+ prev_human_msg = state.messages[-2]
111
+ if type(prev_human_msg[1]) in (tuple, list):
112
+ prev_human_msg[1] = (*prev_human_msg[1][:2], image_process_mode)
113
+ state.skip_next = False
114
+ return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
115
+
116
+
117
+ def clear_history(request: gr.Request):
118
+ logger.info(f"clear_history. ip: {request.client.host}")
119
+ state = default_conversation.copy()
120
+ return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
121
+
122
+
123
+ def add_text(state, text, image, image_process_mode, request: gr.Request):
124
+ logger.info(f"add_text. ip: {request.client.host}. len: {len(text)}")
125
+ if len(text) <= 0 and image is None:
126
+ state.skip_next = True
127
+ return (state, state.to_gradio_chatbot(), "", None) + (no_change_btn,) * 5
128
+ if args.moderate:
129
+ flagged = violates_moderation(text)
130
+ if flagged:
131
+ state.skip_next = True
132
+ return (state, state.to_gradio_chatbot(), moderation_msg, None) + (no_change_btn,) * 5
133
+
134
+ text = text[:1536] # Hard cut-off
135
+ if image is not None:
136
+ text = text[:1200] # Hard cut-off for images
137
+ if "<image>" not in text:
138
+ # text = '<Image><image></Image>' + text
139
+ text = text + "\n<image>"
140
+ text = (text, image, image_process_mode)
141
+ if len(state.get_images(return_pil=True)) > 0:
142
+ state = default_conversation.copy()
143
+ state.append_message(state.roles[0], text)
144
+ state.append_message(state.roles[1], None)
145
+ state.skip_next = False
146
+ return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
147
+
148
+
149
+ def http_bot(state, model_selector, temperature, top_p, max_new_tokens, request: gr.Request, template_name=None):
150
+ logger.info(f"http_bot. ip: {request.client.host}")
151
+ start_tstamp = time.time()
152
+ model_name = model_selector
153
+
154
+ if state.skip_next:
155
+ # This generate call is skipped due to invalid inputs
156
+ yield (state, state.to_gradio_chatbot()) + (no_change_btn,) * 5
157
+ return
158
+
159
+ if len(state.messages) == state.offset + 2:
160
+ # First round of conversation
161
+ if "llava" in model_name.lower():
162
+ if "llama-2" in model_name.lower():
163
+ template_name = "llava_llama_2"
164
+ elif "mistral" in model_name.lower() or "mixtral" in model_name.lower():
165
+ if "orca" in model_name.lower():
166
+ template_name = "mistral_orca"
167
+ elif "hermes" in model_name.lower():
168
+ template_name = "mistral_direct"
169
+ else:
170
+ template_name = "mistral_instruct"
171
+ elif "zephyr" in model_name.lower():
172
+ template_name = "mistral_zephyr"
173
+ elif "hermes" in model_name.lower():
174
+ template_name = "mistral_direct"
175
+ elif "v1" in model_name.lower():
176
+ if "mmtag" in model_name.lower():
177
+ template_name = "llava_v1_mmtag"
178
+ elif "plain" in model_name.lower() and "finetune" not in model_name.lower():
179
+ template_name = "llava_v1_mmtag"
180
+ else:
181
+ template_name = "llava_v1"
182
+ elif "mpt" in model_name.lower():
183
+ template_name = "mpt"
184
+ else:
185
+ if "mmtag" in model_name.lower():
186
+ template_name = "v0_plain"
187
+ elif "plain" in model_name.lower() and "finetune" not in model_name.lower():
188
+ template_name = "v0_plain"
189
+ else:
190
+ template_name = "llava_v0"
191
+ elif "mistral" in model_name.lower() or "mixtral" in model_name.lower():
192
+ if "orca" in model_name.lower():
193
+ template_name = "mistral_orca"
194
+ elif "hermes" in model_name.lower():
195
+ template_name = "mistral_direct"
196
+ else:
197
+ template_name = "mistral_instruct"
198
+ elif "hermes" in model_name.lower():
199
+ template_name = "mistral_direct"
200
+ elif "zephyr" in model_name.lower():
201
+ template_name = "mistral_zephyr"
202
+ elif "mpt" in model_name:
203
+ template_name = "mpt_text"
204
+ elif "llama-2" in model_name:
205
+ template_name = "llama_2"
206
+ else:
207
+ template_name = "vicuna_v1"
208
+ new_state = conv_templates[template_name].copy()
209
+ new_state.append_message(new_state.roles[0], state.messages[-2][1])
210
+ new_state.append_message(new_state.roles[1], None)
211
+ state = new_state
212
+
213
+ # Query worker address
214
+ controller_url = args.controller_url
215
+ ret = requests.post(controller_url + "/get_worker_address", json={"model": model_name})
216
+ worker_addr = ret.json()["address"]
217
+ logger.info(f"model_name: {model_name}, worker_addr: {worker_addr}")
218
+
219
+ # No available worker
220
+ if worker_addr == "":
221
+ state.messages[-1][-1] = server_error_msg
222
+ yield (state, state.to_gradio_chatbot(), disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
223
+ return
224
+
225
+ # Construct prompt
226
+ prompt = state.get_prompt()
227
+
228
+ all_images = state.get_images(return_pil=True)
229
+ all_image_hash = [hashlib.md5(image.tobytes()).hexdigest() for image in all_images]
230
+ for image, hash in zip(all_images, all_image_hash):
231
+ t = datetime.datetime.now()
232
+ filename = os.path.join(LOGDIR, "serve_images", f"{t.year}-{t.month:02d}-{t.day:02d}", f"{hash}.jpg")
233
+ if not os.path.isfile(filename):
234
+ os.makedirs(os.path.dirname(filename), exist_ok=True)
235
+ image.save(filename)
236
+
237
+ # Make requests
238
+ pload = {
239
+ "model": model_name,
240
+ "prompt": prompt,
241
+ "temperature": float(temperature),
242
+ "top_p": float(top_p),
243
+ "max_new_tokens": min(int(max_new_tokens), 1536),
244
+ "stop": state.sep if state.sep_style in [SeparatorStyle.SINGLE, SeparatorStyle.MPT] else state.sep2,
245
+ "images": f"List of {len(state.get_images())} images: {all_image_hash}",
246
+ }
247
+ logger.info(f"==== request ====\n{pload}")
248
+
249
+ pload["images"] = state.get_images()
250
+
251
+ state.messages[-1][-1] = "▌"
252
+ yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
253
+
254
+ try:
255
+ # Stream output
256
+ response = requests.post(worker_addr + "/worker_generate_stream", headers=headers, json=pload, stream=True, timeout=100)
257
+ last_print_time = time.time()
258
+ for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
259
+ if chunk:
260
+ data = json.loads(chunk.decode())
261
+ if data["error_code"] == 0:
262
+ output = data["text"][len(prompt) :].strip()
263
+ state.messages[-1][-1] = output + "▌"
264
+ if time.time() - last_print_time > 0.05:
265
+ last_print_time = time.time()
266
+ yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
267
+ else:
268
+ output = data["text"] + f" (error_code: {data['error_code']})"
269
+ state.messages[-1][-1] = output
270
+ yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
271
+ return
272
+ time.sleep(0.03)
273
+ except requests.exceptions.RequestException as e:
274
+ state.messages[-1][-1] = server_error_msg
275
+ yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
276
+ return
277
+
278
+ state.messages[-1][-1] = state.messages[-1][-1][:-1]
279
+ yield (state, state.to_gradio_chatbot()) + (enable_btn,) * 5
280
+
281
+ finish_tstamp = time.time()
282
+ logger.info(f"{output}")
283
+
284
+ with open(get_conv_log_filename(), "a") as fout:
285
+ data = {
286
+ "tstamp": round(finish_tstamp, 4),
287
+ "type": "chat",
288
+ "model": model_name,
289
+ "start": round(start_tstamp, 4),
290
+ "finish": round(start_tstamp, 4),
291
+ "state": state.dict(),
292
+ "images": all_image_hash,
293
+ "ip": request.client.host,
294
+ }
295
+ fout.write(json.dumps(data) + "\n")
296
+
297
+
298
+ title_markdown = """
299
+ # 🌋 LLaVA: Large Language and Vision Assistant
300
+ [[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)]
301
+ """
302
+
303
+ tos_markdown = """
304
+ ### Terms of use
305
+ By using this service, users are required to agree to the following terms:
306
+ 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.
307
+ Please click the "Flag" button if you get any inappropriate answer! We will collect those to keep improving our moderator.
308
+ For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality.
309
+ """
310
+
311
+
312
+ learn_more_markdown = """
313
+ ### License
314
+ 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.
315
+ """
316
+
317
+ block_css = """
318
+
319
+ #buttons button {
320
+ min-width: min(120px,100%);
321
+ }
322
+
323
+ """
324
+
325
+
326
+ def build_demo(embed_mode):
327
+ textbox = gr.Textbox(show_label=False, placeholder="Enter text and press ENTER", container=False)
328
+ with gr.Blocks(title="LLaVA", theme=gr.themes.Default(), css=block_css) as demo:
329
+ state = gr.State()
330
+
331
+ if not embed_mode:
332
+ gr.Markdown(title_markdown)
333
+
334
+ with gr.Row():
335
+ with gr.Column(scale=3):
336
+ with gr.Row(elem_id="model_selector_row"):
337
+ model_selector = gr.Dropdown(choices=models, value=models[0] if len(models) > 0 else "", interactive=True, show_label=False, container=False)
338
+
339
+ imagebox = gr.Image(type="pil")
340
+ image_process_mode = gr.Radio(["Crop", "Resize", "Pad", "Default"], value="Default", label="Preprocess for non-square image", visible=False)
341
+
342
+ cur_dir = os.path.dirname(os.path.abspath(__file__))
343
+ gr.Examples(
344
+ examples=[
345
+ [f"{cur_dir}/examples/extreme_ironing.jpg", "What is unusual about this image?"],
346
+ [f"{cur_dir}/examples/waterview.jpg", "What are the things I should be cautious about when I visit here?"],
347
+ ],
348
+ inputs=[imagebox, textbox],
349
+ )
350
+
351
+ with gr.Accordion("Parameters", open=False) as parameter_row:
352
+ temperature = gr.Slider(
353
+ minimum=0.0,
354
+ maximum=1.0,
355
+ value=0.2,
356
+ step=0.1,
357
+ interactive=True,
358
+ label="Temperature",
359
+ )
360
+ top_p = gr.Slider(
361
+ minimum=0.0,
362
+ maximum=1.0,
363
+ value=0.7,
364
+ step=0.1,
365
+ interactive=True,
366
+ label="Top P",
367
+ )
368
+ max_output_tokens = gr.Slider(
369
+ minimum=0,
370
+ maximum=1024,
371
+ value=512,
372
+ step=64,
373
+ interactive=True,
374
+ label="Max output tokens",
375
+ )
376
+
377
+ with gr.Column(scale=8):
378
+ chatbot = gr.Chatbot(elem_id="chatbot", label="LLaVA Chatbot", height=550)
379
+ with gr.Row():
380
+ with gr.Column(scale=8):
381
+ textbox.render()
382
+ with gr.Column(scale=1, min_width=50):
383
+ submit_btn = gr.Button(value="Send", variant="primary")
384
+ with gr.Row(elem_id="buttons") as button_row:
385
+ upvote_btn = gr.Button(value="👍 Upvote", interactive=False)
386
+ downvote_btn = gr.Button(value="👎 Downvote", interactive=False)
387
+ flag_btn = gr.Button(value="⚠️ Flag", interactive=False)
388
+ # stop_btn = gr.Button(value="⏹️ Stop Generation", interactive=False)
389
+ regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=False)
390
+ clear_btn = gr.Button(value="🗑️ Clear", interactive=False)
391
+
392
+ if not embed_mode:
393
+ gr.Markdown(tos_markdown)
394
+ gr.Markdown(learn_more_markdown)
395
+ url_params = gr.JSON(visible=False)
396
+
397
+ # Register listeners
398
+ btn_list = [upvote_btn, downvote_btn, flag_btn, regenerate_btn, clear_btn]
399
+ upvote_btn.click(upvote_last_response, [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn], queue=False)
400
+ downvote_btn.click(downvote_last_response, [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn], queue=False)
401
+ flag_btn.click(flag_last_response, [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn], queue=False)
402
+
403
+ regenerate_btn.click(regenerate, [state, image_process_mode], [state, chatbot, textbox, imagebox] + btn_list, queue=False).then(http_bot, [state, model_selector, temperature, top_p, max_output_tokens], [state, chatbot] + btn_list)
404
+
405
+ clear_btn.click(clear_history, None, [state, chatbot, textbox, imagebox] + btn_list, queue=False)
406
+
407
+ textbox.submit(add_text, [state, textbox, imagebox, image_process_mode], [state, chatbot, textbox, imagebox] + btn_list, queue=False).then(
408
+ http_bot, [state, model_selector, temperature, top_p, max_output_tokens], [state, chatbot] + btn_list
409
+ )
410
+
411
+ submit_btn.click(add_text, [state, textbox, imagebox, image_process_mode], [state, chatbot, textbox, imagebox] + btn_list, queue=False).then(
412
+ http_bot, [state, model_selector, temperature, top_p, max_output_tokens], [state, chatbot] + btn_list
413
+ )
414
+
415
+ if args.model_list_mode == "once":
416
+ demo.load(load_demo, [url_params], [state, model_selector], _js=get_window_url_params, queue=False)
417
+ elif args.model_list_mode == "reload":
418
+ demo.load(load_demo_refresh_model_list, None, [state, model_selector], queue=False)
419
+ else:
420
+ raise ValueError(f"Unknown model list mode: {args.model_list_mode}")
421
+
422
+ return demo
423
+
424
+
425
+ if __name__ == "__main__":
426
+ parser = argparse.ArgumentParser()
427
+ parser.add_argument("--host", type=str, default="0.0.0.0")
428
+ parser.add_argument("--port", type=int)
429
+ parser.add_argument("--controller-url", type=str, default="http://localhost:21001")
430
+ parser.add_argument("--concurrency-count", type=int, default=10)
431
+ parser.add_argument("--model-list-mode", type=str, default="once", choices=["once", "reload"])
432
+ parser.add_argument("--share", action="store_true")
433
+ parser.add_argument("--moderate", action="store_true")
434
+ parser.add_argument("--embed", action="store_true")
435
+ args = parser.parse_args()
436
+ logger.info(f"args: {args}")
437
+
438
+ models = get_model_list()
439
+
440
+ logger.info(args)
441
+ demo = build_demo(args.embed)
442
+ demo.queue(concurrency_count=args.concurrency_count, api_open=False).launch(server_name=args.host, server_port=args.port, share=args.share)
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/serve/model_worker.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A model worker executes the model.
3
+ """
4
+
5
+ import argparse
6
+ import asyncio
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 torch
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, 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, KeywordsStoppingCriteria
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, worker_id, no_register, model_path, model_base, model_name, load_8bit, load_4bit):
46
+ self.controller_addr = controller_addr
47
+ self.worker_addr = worker_addr
48
+ self.worker_id = worker_id
49
+ if model_path.endswith("/"):
50
+ model_path = model_path[:-1]
51
+ if model_name is None:
52
+ model_paths = model_path.split("/")
53
+ if model_paths[-1].startswith("checkpoint-"):
54
+ self.model_name = model_paths[-2] + "_" + model_paths[-1]
55
+ else:
56
+ self.model_name = model_paths[-1]
57
+ else:
58
+ self.model_name = model_name
59
+
60
+ logger.info(f"Loading the model {self.model_name} on worker {worker_id} ...")
61
+ self.tokenizer, self.model, self.image_processor, self.context_len = load_pretrained_model(model_path, model_base, self.model_name, load_8bit, load_4bit)
62
+ self.is_multimodal = "llava" in self.model_name.lower()
63
+
64
+ if not no_register:
65
+ self.register_to_controller()
66
+ self.heart_beat_thread = threading.Thread(target=heart_beat_worker, args=(self,))
67
+ self.heart_beat_thread.start()
68
+
69
+ def register_to_controller(self):
70
+ logger.info("Register to controller")
71
+
72
+ url = self.controller_addr + "/register_worker"
73
+ data = {"worker_name": self.worker_addr, "check_heart_beat": True, "worker_status": self.get_status()}
74
+ r = requests.post(url, json=data)
75
+ assert r.status_code == 200
76
+
77
+ def send_heart_beat(self):
78
+ logger.info(f"Send heart beat. Models: {[self.model_name]}. " f"Semaphore: {pretty_print_semaphore(model_semaphore)}. " f"global_counter: {global_counter}")
79
+
80
+ url = self.controller_addr + "/receive_heart_beat"
81
+
82
+ while True:
83
+ try:
84
+ ret = requests.post(url, json={"worker_name": self.worker_addr, "queue_length": self.get_queue_length()}, timeout=5)
85
+ exist = ret.json()["exist"]
86
+ break
87
+ except requests.exceptions.RequestException as e:
88
+ logger.error(f"heart beat error: {e}")
89
+ time.sleep(5)
90
+
91
+ if not exist:
92
+ self.register_to_controller()
93
+
94
+ def get_queue_length(self):
95
+ if model_semaphore is None:
96
+ return 0
97
+ else:
98
+ return args.limit_model_concurrency - model_semaphore._value + (len(model_semaphore._waiters) if model_semaphore._waiters is not None else 0)
99
+
100
+ def get_status(self):
101
+ return {
102
+ "model_names": [self.model_name],
103
+ "speed": 1,
104
+ "queue_length": self.get_queue_length(),
105
+ }
106
+
107
+ @torch.inference_mode()
108
+ def generate_stream(self, params):
109
+ tokenizer, model, image_processor = self.tokenizer, self.model, self.image_processor
110
+
111
+ prompt = params["prompt"]
112
+ ori_prompt = prompt
113
+ images = params.get("images", None)
114
+ num_image_tokens = 0
115
+ if images is not None and len(images) > 0 and self.is_multimodal:
116
+ if len(images) > 0:
117
+ if len(images) != prompt.count(DEFAULT_IMAGE_TOKEN):
118
+ raise ValueError("Number of images does not match number of <image> tokens in prompt")
119
+
120
+ images = [load_image_from_base64(image) for image in images]
121
+ image_sizes = [image.size for image in images]
122
+ images = process_images(images, image_processor, model.config)
123
+
124
+ if type(images) is list:
125
+ images = [image.to(self.model.device, dtype=torch.float16) for image in images]
126
+ else:
127
+ images = images.to(self.model.device, dtype=torch.float16)
128
+
129
+ replace_token = DEFAULT_IMAGE_TOKEN
130
+ if getattr(self.model.config, "mm_use_im_start_end", False):
131
+ replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
132
+ prompt = prompt.replace(DEFAULT_IMAGE_TOKEN, replace_token)
133
+
134
+ num_image_tokens = prompt.count(replace_token) * model.get_vision_tower().num_patches
135
+ else:
136
+ images = None
137
+ image_sizes = None
138
+ image_args = {"images": images, "image_sizes": image_sizes}
139
+ else:
140
+ images = None
141
+ image_args = {}
142
+
143
+ temperature = float(params.get("temperature", 1.0))
144
+ top_p = float(params.get("top_p", 1.0))
145
+ max_context_length = getattr(model.config, "max_position_embeddings", 2048)
146
+ max_new_tokens = min(int(params.get("max_new_tokens", 256)), 1024)
147
+ stop_str = params.get("stop", None)
148
+ do_sample = True if temperature > 0.001 else False
149
+
150
+ input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).cuda()
151
+ keywords = [stop_str]
152
+ stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
153
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=15)
154
+
155
+ max_new_tokens = min(max_new_tokens, max_context_length - input_ids.shape[-1] - num_image_tokens)
156
+
157
+ if max_new_tokens < 1:
158
+ yield json.dumps({"text": ori_prompt + "Exceeds max token length. Please start a new conversation, thanks.", "error_code": 0}).encode() + b"\0"
159
+ return
160
+
161
+ thread = Thread(
162
+ target=model.generate,
163
+ kwargs=dict(
164
+ inputs=input_ids,
165
+ do_sample=do_sample,
166
+ temperature=temperature,
167
+ top_p=top_p,
168
+ max_new_tokens=max_new_tokens,
169
+ streamer=streamer,
170
+ # stopping_criteria=[stopping_criteria],
171
+ use_cache=True,
172
+ **image_args,
173
+ ),
174
+ )
175
+ thread.start()
176
+
177
+ start_time = time.time()
178
+ generated_text = ori_prompt
179
+ for new_text in streamer:
180
+ generated_text += new_text
181
+ if generated_text.endswith(stop_str):
182
+ generated_text = generated_text[: -len(stop_str)]
183
+ yield json.dumps({"text": generated_text, "error_code": 0}).encode() + b"\0"
184
+
185
+ end_time = time.time()
186
+
187
+ new_generated = generated_text[len(ori_prompt) :]
188
+ new_generated_tokens = tokenizer(new_generated).input_ids
189
+ token_per_second = len(new_generated_tokens) / (end_time - start_time)
190
+ print(f"token_per_second: {token_per_second}")
191
+
192
+ def generate_stream_gate(self, params):
193
+ try:
194
+ for x in self.generate_stream(params):
195
+ yield x
196
+ except ValueError as e:
197
+ print("Caught ValueError:", e)
198
+ ret = {
199
+ "text": server_error_msg,
200
+ "error_code": 1,
201
+ }
202
+ yield json.dumps(ret).encode() + b"\0"
203
+ except torch.cuda.CudaError as e:
204
+ print("Caught torch.cuda.CudaError:", e)
205
+ ret = {
206
+ "text": server_error_msg,
207
+ "error_code": 1,
208
+ }
209
+ yield json.dumps(ret).encode() + b"\0"
210
+ except Exception as e:
211
+ print("Caught Unknown Error", e)
212
+ ret = {
213
+ "text": server_error_msg,
214
+ "error_code": 1,
215
+ }
216
+ yield json.dumps(ret).encode() + b"\0"
217
+
218
+
219
+ app = FastAPI()
220
+
221
+
222
+ def release_model_semaphore(fn=None):
223
+ model_semaphore.release()
224
+ if fn is not None:
225
+ fn()
226
+
227
+
228
+ @app.post("/worker_generate_stream")
229
+ async def generate_stream(request: Request):
230
+ global model_semaphore, global_counter
231
+ global_counter += 1
232
+ params = await request.json()
233
+
234
+ if model_semaphore is None:
235
+ model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
236
+ await model_semaphore.acquire()
237
+ worker.send_heart_beat()
238
+ generator = worker.generate_stream_gate(params)
239
+ background_tasks = BackgroundTasks()
240
+ background_tasks.add_task(partial(release_model_semaphore, fn=worker.send_heart_beat))
241
+ return StreamingResponse(generator, background=background_tasks)
242
+
243
+
244
+ @app.post("/worker_get_status")
245
+ async def get_status(request: Request):
246
+ return worker.get_status()
247
+
248
+
249
+ if __name__ == "__main__":
250
+ parser = argparse.ArgumentParser()
251
+ parser.add_argument("--host", type=str, default="localhost")
252
+ parser.add_argument("--port", type=int, default=21002)
253
+ parser.add_argument("--worker-address", type=str, default="http://localhost:21002")
254
+ parser.add_argument("--controller-address", type=str, default="http://localhost:21001")
255
+ parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
256
+ parser.add_argument("--model-base", type=str, default=None)
257
+ parser.add_argument("--model-name", type=str)
258
+ 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.")
259
+ parser.add_argument("--limit-model-concurrency", type=int, default=5)
260
+ parser.add_argument("--stream-interval", type=int, default=1)
261
+ parser.add_argument("--no-register", action="store_true")
262
+ parser.add_argument("--load-8bit", action="store_true")
263
+ parser.add_argument("--load-4bit", action="store_true")
264
+ args = parser.parse_args()
265
+ logger.info(f"args: {args}")
266
+
267
+ if args.multi_modal:
268
+ logger.warning("Multimodal mode is automatically detected with model name, please make sure `llava` is included in the model path.")
269
+
270
+ worker = ModelWorker(args.controller_address, args.worker_address, worker_id, args.no_register, args.model_path, args.model_base, args.model_name, args.load_8bit, args.load_4bit)
271
+ uvicorn.run(app, host=args.host, port=args.port, log_level="info")
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/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
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/serve/sglang_worker.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A model worker executes the model.
3
+ """
4
+
5
+ import argparse
6
+ import asyncio
7
+ from concurrent.futures import ThreadPoolExecutor
8
+ import json
9
+ import time
10
+ import threading
11
+ import uuid
12
+
13
+ from fastapi import FastAPI, Request, BackgroundTasks
14
+ from fastapi.responses import StreamingResponse
15
+ import requests
16
+ import re
17
+ import uvicorn
18
+ from functools import partial
19
+
20
+ from llava.constants import WORKER_HEART_BEAT_INTERVAL
21
+ from llava.utils import build_logger, server_error_msg, pretty_print_semaphore
22
+ from llava.model.builder import load_pretrained_model
23
+ from llava.mm_utils import process_images, load_image_from_base64, tokenizer_image_token, expand2square
24
+ from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
25
+ from transformers import AutoTokenizer
26
+
27
+ import sglang as sgl
28
+ from sglang.test.test_utils import add_common_sglang_args_and_parse, select_sglang_backend
29
+ from sglang.backend.runtime_endpoint import RuntimeEndpoint
30
+ from sglang.utils import read_jsonl, dump_state_text
31
+ from sglang.lang.interpreter import ProgramState
32
+
33
+
34
+ GB = 1 << 30
35
+
36
+ worker_id = str(uuid.uuid4())[:6]
37
+ logger = build_logger("model_worker", f"model_worker_{worker_id}.log")
38
+ global_counter = 0
39
+
40
+ model_semaphore = None
41
+
42
+
43
+ def heart_beat_worker(controller):
44
+ while True:
45
+ time.sleep(WORKER_HEART_BEAT_INTERVAL)
46
+ controller.send_heart_beat()
47
+
48
+
49
+ @sgl.function
50
+ def pipeline(s, prompt, max_tokens):
51
+ for p in prompt:
52
+ if type(p) is str:
53
+ s += p
54
+ else:
55
+ s += sgl.image(p)
56
+ s += sgl.gen("response", max_tokens=max_tokens)
57
+
58
+
59
+ class ModelWorker:
60
+ def __init__(self, controller_addr, worker_addr, sgl_endpoint, worker_id, no_register, model_name):
61
+ self.controller_addr = controller_addr
62
+ self.worker_addr = worker_addr
63
+ self.worker_id = worker_id
64
+
65
+ # Select backend
66
+ backend = RuntimeEndpoint(sgl_endpoint)
67
+ sgl.set_default_backend(backend)
68
+ model_path = backend.model_info["model_path"]
69
+
70
+ if model_path.endswith("/"):
71
+ model_path = model_path[:-1]
72
+ if model_name is None:
73
+ model_paths = model_path.split("/")
74
+ if model_paths[-1].startswith("checkpoint-"):
75
+ self.model_name = model_paths[-2] + "_" + model_paths[-1]
76
+ else:
77
+ self.model_name = model_paths[-1]
78
+ else:
79
+ self.model_name = model_name
80
+
81
+ logger.info(f"Loading the SGLANG model {self.model_name} on worker {worker_id} ...")
82
+
83
+ if not no_register:
84
+ self.register_to_controller()
85
+ self.heart_beat_thread = threading.Thread(target=heart_beat_worker, args=(self,))
86
+ self.heart_beat_thread.start()
87
+
88
+ def register_to_controller(self):
89
+ logger.info("Register to controller")
90
+
91
+ url = self.controller_addr + "/register_worker"
92
+ data = {"worker_name": self.worker_addr, "check_heart_beat": True, "worker_status": self.get_status()}
93
+ r = requests.post(url, json=data)
94
+ assert r.status_code == 200
95
+
96
+ def send_heart_beat(self):
97
+ logger.info(f"Send heart beat. Models: {[self.model_name]}. " f"Semaphore: {pretty_print_semaphore(model_semaphore)}. " f"global_counter: {global_counter}")
98
+
99
+ url = self.controller_addr + "/receive_heart_beat"
100
+
101
+ while True:
102
+ try:
103
+ ret = requests.post(url, json={"worker_name": self.worker_addr, "queue_length": self.get_queue_length()}, timeout=5)
104
+ exist = ret.json()["exist"]
105
+ break
106
+ except requests.exceptions.RequestException as e:
107
+ logger.error(f"heart beat error: {e}")
108
+ time.sleep(5)
109
+
110
+ if not exist:
111
+ self.register_to_controller()
112
+
113
+ def get_queue_length(self):
114
+ if model_semaphore is None:
115
+ return 0
116
+ else:
117
+ return args.limit_model_concurrency - model_semaphore._value + (len(model_semaphore._waiters) if model_semaphore._waiters is not None else 0)
118
+
119
+ def get_status(self):
120
+ return {
121
+ "model_names": [self.model_name],
122
+ "speed": 1,
123
+ "queue_length": self.get_queue_length(),
124
+ }
125
+
126
+ async def generate_stream(self, params):
127
+ ori_prompt = prompt = params["prompt"]
128
+ images = params.get("images", None)
129
+ if images is not None and len(images) > 0:
130
+ if len(images) > 0:
131
+ if len(images) != prompt.count(DEFAULT_IMAGE_TOKEN):
132
+ raise ValueError("Number of images does not match number of <image> tokens in prompt")
133
+
134
+ images = [load_image_from_base64(image) for image in images]
135
+ # FIXME: hacky padding
136
+ images = [expand2square(image, tuple(int(x * 255) for x in [0.48145466, 0.4578275, 0.40821073])) for image in images]
137
+
138
+ # FIXME: for image-start/end token
139
+ # replace_token = DEFAULT_IMAGE_TOKEN
140
+ # if getattr(self.model.config, 'mm_use_im_start_end', False):
141
+ # replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
142
+ # prompt = prompt.replace(DEFAULT_IMAGE_TOKEN, replace_token)
143
+ prompt = prompt.replace(" " + DEFAULT_IMAGE_TOKEN + "\n", DEFAULT_IMAGE_TOKEN)
144
+ prompt_split = prompt.split(DEFAULT_IMAGE_TOKEN)
145
+ prompt = []
146
+ for i in range(len(prompt_split)):
147
+ prompt.append(prompt_split[i])
148
+ if i < len(images):
149
+ prompt.append(images[i])
150
+ else:
151
+ prompt = [prompt]
152
+
153
+ temperature = float(params.get("temperature", 1.0))
154
+ top_p = float(params.get("top_p", 1.0))
155
+ # max_context_length = getattr(model.config, 'max_position_embeddings', 2048)
156
+ max_new_tokens = min(int(params.get("max_new_tokens", 256)), 1024)
157
+ stop_str = params.get("stop", None)
158
+ stop_str = [stop_str] if stop_str is not None else None
159
+
160
+ if max_new_tokens < 1:
161
+ yield json.dumps({"text": ori_prompt + "Exceeds max token length. Please start a new conversation, thanks.", "error_code": 0}).encode() + b"\0"
162
+ return
163
+
164
+ # print(prompt)
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, default="http://localhost:21002")
227
+ parser.add_argument("--controller-address", type=str, default="http://localhost:21001")
228
+ parser.add_argument("--model-name", type=str)
229
+ parser.add_argument("--sgl-endpoint", type=str)
230
+ parser.add_argument("--limit-model-concurrency", type=int, default=5)
231
+ parser.add_argument("--stream-interval", type=int, default=1)
232
+ parser.add_argument("--no-register", action="store_true")
233
+ args = parser.parse_args()
234
+ logger.info(f"args: {args}")
235
+
236
+ worker = ModelWorker(args.controller_address, args.worker_address, args.sgl_endpoint, worker_id, args.no_register, args.model_name)
237
+ uvicorn.run(app, host=args.host, port=args.port, log_level="info")
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/serve/test_message.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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", json={"model": args.model_name})
21
+ worker_addr = ret.json()["address"]
22
+ print(f"worker_addr: {worker_addr}")
23
+
24
+ if worker_addr == "":
25
+ return
26
+
27
+ conv = default_conversation.copy()
28
+ conv.append_message(conv.roles[0], args.message)
29
+ prompt = conv.get_prompt()
30
+
31
+ headers = {"User-Agent": "LLaVA Client"}
32
+ pload = {
33
+ "model": args.model_name,
34
+ "prompt": prompt,
35
+ "max_new_tokens": args.max_new_tokens,
36
+ "temperature": 0.7,
37
+ "stop": conv.sep,
38
+ }
39
+ response = requests.post(worker_addr + "/worker_generate_stream", headers=headers, json=pload, stream=True)
40
+
41
+ print(prompt.replace(conv.sep, "\n"), end="")
42
+ for chunk in response.iter_lines(chunk_size=8192, decode_unicode=False, delimiter=b"\0"):
43
+ if chunk:
44
+ data = json.loads(chunk.decode("utf-8"))
45
+ output = data["text"].split(conv.sep)[-1]
46
+ print(output, end="\r")
47
+ print("")
48
+
49
+
50
+ if __name__ == "__main__":
51
+ parser = argparse.ArgumentParser()
52
+ parser.add_argument("--controller-address", type=str, default="http://localhost:21001")
53
+ parser.add_argument("--worker-address", type=str)
54
+ parser.add_argument("--model-name", type=str, default="facebook/opt-350m")
55
+ parser.add_argument("--max-new-tokens", type=int, default=32)
56
+ parser.add_argument("--message", type=str, default="Tell me a story with more than 1000 words.")
57
+ args = parser.parse_args()
58
+
59
+ main()
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/train/llama_flash_attn_monkey_patch.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Tuple
2
+ import warnings
3
+
4
+ import torch
5
+
6
+ import transformers
7
+ from transformers.models.llama.modeling_llama import apply_rotary_pos_emb, repeat_kv
8
+
9
+ try:
10
+ from flash_attn.flash_attn_interface import flash_attn_unpadded_qkvpacked_func
11
+ except ImportError:
12
+ from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func as flash_attn_unpadded_qkvpacked_func
13
+ from flash_attn.bert_padding import unpad_input, pad_input
14
+
15
+
16
+ def forward(
17
+ self,
18
+ hidden_states: torch.Tensor,
19
+ attention_mask: Optional[torch.Tensor] = None,
20
+ position_ids: Optional[torch.Tensor] = None,
21
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
22
+ output_attentions: bool = False,
23
+ use_cache: bool = False,
24
+ padding_mask: Optional[torch.Tensor] = None,
25
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
26
+ if output_attentions:
27
+ warnings.warn("Output attentions is not supported for patched `LlamaAttention`, returning `None` instead.")
28
+
29
+ bsz, q_len, _ = hidden_states.size()
30
+
31
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
32
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
33
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) # shape: (b, num_heads, s, head_dim)
34
+
35
+ kv_seq_len = key_states.shape[-2]
36
+ if past_key_value is not None:
37
+ kv_seq_len += past_key_value[0].shape[-2]
38
+
39
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
40
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
41
+
42
+ if past_key_value is not None:
43
+ # reuse k, v
44
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
45
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
46
+
47
+ past_key_value = (key_states, value_states) if use_cache else None
48
+
49
+ # repeat k/v heads if n_kv_heads < n_heads
50
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
51
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
52
+
53
+ # Transform the data into the format required by flash attention
54
+ qkv = torch.stack([query_states, key_states, value_states], dim=2)
55
+ qkv = qkv.transpose(1, 3) # shape: [b, s, 3, num_heads, head_dim]
56
+ key_padding_mask = attention_mask
57
+
58
+ if key_padding_mask is None:
59
+ qkv = qkv.reshape(-1, 3, self.num_heads, self.head_dim)
60
+ cu_q_lens = torch.arange(0, (bsz + 1) * q_len, step=q_len, dtype=torch.int32, device=qkv.device)
61
+ max_s = q_len
62
+ output = flash_attn_unpadded_qkvpacked_func(qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True)
63
+ output = output.view(bsz, q_len, -1)
64
+ else:
65
+ qkv = qkv.reshape(bsz, q_len, -1)
66
+ qkv, indices, cu_q_lens, max_s = unpad_input(qkv, key_padding_mask)
67
+ qkv = qkv.view(-1, 3, self.num_heads, self.head_dim)
68
+ output_unpad = flash_attn_unpadded_qkvpacked_func(qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True)
69
+ output_unpad = output_unpad.reshape(-1, self.num_heads * self.head_dim)
70
+ output = pad_input(output_unpad, indices, bsz, q_len)
71
+
72
+ return self.o_proj(output), None, past_key_value
73
+
74
+
75
+ # Disable the transformation of the attention mask in LlamaModel as the flash attention
76
+ # requires the attention mask to be the same as the key_padding_mask
77
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
78
+ # [bsz, seq_len]
79
+ return attention_mask
80
+
81
+
82
+ def replace_llama_attn_with_flash_attn():
83
+ cuda_major, cuda_minor = torch.cuda.get_device_capability()
84
+ if cuda_major < 8:
85
+ warnings.warn("Flash attention is only supported on A100 or H100 GPU during training due to head dim > 64 backward." "ref: https://github.com/HazyResearch/flash-attention/issues/190#issuecomment-1523359593")
86
+ transformers.models.llama.modeling_llama.LlamaModel._prepare_decoder_attention_mask = _prepare_decoder_attention_mask
87
+ transformers.models.llama.modeling_llama.LlamaAttention.forward = forward
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/train/llava_trainer.py ADDED
@@ -0,0 +1,527 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import torch.nn as nn
4
+ import datetime
5
+
6
+ from accelerate import Accelerator
7
+ from accelerate.utils import InitProcessGroupKwargs, GradientAccumulationPlugin
8
+ from torch.utils.data import Dataset, Sampler, DataLoader
9
+
10
+ from trl.trainer import DPOTrainer
11
+ from trl.trainer.utils import DPODataCollatorWithPadding
12
+
13
+ from transformers import Trainer
14
+ from transformers.trainer import is_sagemaker_mp_enabled, get_parameter_names, has_length, ALL_LAYERNORM_LAYERS, logger, is_accelerate_available, is_datasets_available, GradientAccumulationPlugin
15
+ from transformers.trainer_utils import seed_worker
16
+ from transformers.trainer_pt_utils import get_length_grouped_indices as get_length_grouped_indices_hf
17
+ from transformers.trainer_pt_utils import AcceleratorConfig
18
+ from typing import List, Optional
19
+ from datetime import timedelta
20
+
21
+ if is_accelerate_available():
22
+ from accelerate import Accelerator, skip_first_batches, InitProcessGroupKwargs
23
+
24
+ if is_datasets_available():
25
+ import datasets
26
+
27
+ from llava.utils import rank0_print
28
+
29
+
30
+ def maybe_zero_3(param, ignore_status=False, name=None):
31
+ from deepspeed import zero
32
+ from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
33
+
34
+ if hasattr(param, "ds_id"):
35
+ if param.ds_status == ZeroParamStatus.NOT_AVAILABLE:
36
+ if not ignore_status:
37
+ print(name, "no ignore status")
38
+ with zero.GatheredParameters([param]):
39
+ param = param.data.detach().cpu().clone()
40
+ else:
41
+ param = param.detach().cpu().clone()
42
+ return param
43
+
44
+
45
+ def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match):
46
+ to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)}
47
+ to_return = {k: maybe_zero_3(v, ignore_status=True, name=k).cpu() for k, v in to_return.items()}
48
+ return to_return
49
+
50
+
51
+ def split_to_even_chunks(indices, lengths, num_chunks):
52
+ """
53
+ Split a list of indices into `chunks` chunks of roughly equal lengths.
54
+ """
55
+
56
+ if len(indices) % num_chunks != 0:
57
+ return [indices[i::num_chunks] for i in range(num_chunks)]
58
+
59
+ num_indices_per_chunk = len(indices) // num_chunks
60
+
61
+ chunks = [[] for _ in range(num_chunks)]
62
+ chunks_lengths = [0 for _ in range(num_chunks)]
63
+ for index in indices:
64
+ shortest_chunk = chunks_lengths.index(min(chunks_lengths))
65
+ chunks[shortest_chunk].append(index)
66
+ chunks_lengths[shortest_chunk] += lengths[index]
67
+ if len(chunks[shortest_chunk]) == num_indices_per_chunk:
68
+ chunks_lengths[shortest_chunk] = float("inf")
69
+
70
+ return chunks
71
+
72
+
73
+ def get_variable_length_grouped_indices(lengths, batch_size, world_size, megabatch_mult=8, generator=None):
74
+ # We need to use torch for the random part as a distributed sampler will set the random seed for torch.
75
+ indices = torch.randperm(len(lengths), generator=generator)
76
+ sorted_indices = sorted(range(len(lengths)), key=lambda i: lengths[i], reverse=True)
77
+ megabatch_size = world_size * batch_size * megabatch_mult
78
+ megabatches = [sorted_indices[i : i + megabatch_size] for i in range(0, len(lengths), megabatch_size)]
79
+ megabatches = [sorted(megabatch, key=lambda i: indices[i], reverse=True) for megabatch in megabatches]
80
+ shuffled_indices = [i for megabatch in megabatches for i in megabatch]
81
+ world_batch_size = world_size * batch_size
82
+ batches = [shuffled_indices[i : i + world_batch_size] for i in range(0, len(lengths), world_batch_size)]
83
+ batch_indices = torch.randperm(len(batches), generator=generator)
84
+ batches = [batches[i] for i in batch_indices]
85
+
86
+ return [i for batch in batches for i in batch]
87
+
88
+
89
+ def get_modality_length_grouped_indices(lengths, batch_size, world_size, generator=None):
90
+ """
91
+ Return a list of indices so that each slice of `batch_size` consecutive indices correspond to elements of similar
92
+ lengths. To do this, the indices are:
93
+
94
+ - randomly permuted
95
+ - grouped in mega-batches of size `mega_batch_mult * batch_size`
96
+ - reorder by length in each mega-batch
97
+
98
+ The result is the concatenation of all mega-batches, with the batch of `batch_size` containing the element of
99
+ maximum length placed first, so that an OOM happens sooner rather than later.
100
+ """
101
+
102
+ # We need to use torch for the random part as a distributed sampler will set the random seed for torch.
103
+ assert all(l != 0 for l in lengths), "Should not have zero length."
104
+ if all(l > 0 for l in lengths) or all(l < 0 for l in lengths):
105
+ # all samples are in the same modality
106
+ return get_length_grouped_indices(lengths, batch_size, world_size, generator=generator)
107
+ mm_indices, mm_lengths = zip(*[(i, l) for i, l in enumerate(lengths) if l > 0])
108
+ lang_indices, lang_lengths = zip(*[(i, -l) for i, l in enumerate(lengths) if l < 0])
109
+
110
+ mm_shuffle = [mm_indices[i] for i in get_length_grouped_indices(mm_lengths, batch_size, world_size, generator=None)]
111
+ lang_shuffle = [lang_indices[i] for i in get_length_grouped_indices(lang_lengths, batch_size, world_size, generator=None)]
112
+ megabatch_size = world_size * batch_size
113
+ mm_megabatches = [mm_shuffle[i : i + megabatch_size] for i in range(0, len(mm_shuffle), megabatch_size)]
114
+ lang_megabatches = [lang_shuffle[i : i + megabatch_size] for i in range(0, len(lang_shuffle), megabatch_size)]
115
+
116
+ last_mm = mm_megabatches[-1]
117
+ last_lang = lang_megabatches[-1]
118
+ additional_batch = last_mm + last_lang
119
+ megabatches = mm_megabatches[:-1] + lang_megabatches[:-1]
120
+ megabatch_indices = torch.randperm(len(megabatches), generator=generator)
121
+ megabatches = [megabatches[i] for i in megabatch_indices]
122
+
123
+ if len(additional_batch) > 0:
124
+ megabatches.append(sorted(additional_batch))
125
+
126
+ return [i for megabatch in megabatches for i in megabatch]
127
+
128
+
129
+ def get_length_grouped_indices(lengths, batch_size, world_size, generator=None, merge=True):
130
+ """
131
+ Return a list of indices so that each slice of `batch_size` consecutive indices correspond to elements of similar
132
+ lengths. To do this, the indices are:
133
+
134
+ - randomly permuted
135
+ - grouped in mega-batches of size `mega_batch_mult * batch_size`
136
+ - reorder by length in each mega-batch
137
+
138
+ The result is the concatenation of all mega-batches, with the batch of `batch_size` containing the element of
139
+ maximum length placed first, so that an OOM happens sooner rather than later.
140
+ """
141
+
142
+ # We need to use torch for the random part as a distributed sampler will set the random seed for torch.
143
+ indices = torch.randperm(len(lengths), generator=generator)
144
+ megabatch_size = world_size * batch_size
145
+ megabatches = [indices[i : i + megabatch_size].tolist() for i in range(0, len(lengths), megabatch_size)]
146
+ megabatches = [sorted(megabatch, key=lambda i: lengths[i], reverse=True) for megabatch in megabatches]
147
+ megabatches = [split_to_even_chunks(megabatch, lengths, world_size) for megabatch in megabatches]
148
+
149
+ return [i for megabatch in megabatches for batch in megabatch for i in batch]
150
+
151
+
152
+ def get_length_grouped_indices_auto_single(lengths, batch_size, world_size, generator=None):
153
+ indices = get_length_grouped_indices_hf(lengths, batch_size * world_size, generator=generator)
154
+
155
+ megabatch_size = world_size * batch_size
156
+ megabatches = [indices[i : i + megabatch_size] for i in range(0, len(lengths), megabatch_size)]
157
+ megabatches = [sorted(megabatch, key=lambda i: lengths[i], reverse=True) for megabatch in megabatches]
158
+ megabatches = [split_to_even_chunks(megabatch, lengths, world_size) for megabatch in megabatches]
159
+
160
+ # We need to use torch for the random part as a distributed sampler will set the random seed for torch.
161
+ batch_indices = torch.randperm(len(megabatches), generator=generator)
162
+ megabatches = [megabatches[i] for i in batch_indices]
163
+
164
+ return [i for megabatch in megabatches for batch in megabatch for i in batch]
165
+
166
+
167
+ def get_modality_length_grouped_indices_auto(lengths, batch_size, world_size, generator=None):
168
+ # We need to use torch for the random part as a distributed sampler will set the random seed for torch.
169
+ assert all(l != 0 for l in lengths), "Should not have zero length."
170
+ if all(l > 0 for l in lengths) or all(l < 0 for l in lengths):
171
+ # all samples are in the same modality
172
+ return get_length_grouped_indices_auto_single(lengths, batch_size, world_size, generator=generator)
173
+ mm_indices, mm_lengths = zip(*[(i, l) for i, l in enumerate(lengths) if l > 0])
174
+ lang_indices, lang_lengths = zip(*[(i, -l) for i, l in enumerate(lengths) if l < 0])
175
+
176
+ mm_shuffle = [mm_indices[i] for i in get_length_grouped_indices_auto_single(mm_lengths, batch_size, world_size, generator=None)]
177
+ lang_shuffle = [lang_indices[i] for i in get_length_grouped_indices_auto_single(lang_lengths, batch_size, world_size, generator=None)]
178
+ megabatch_size = world_size * batch_size
179
+ mm_megabatches = [mm_shuffle[i : i + megabatch_size] for i in range(0, len(mm_shuffle), megabatch_size)]
180
+ lang_megabatches = [lang_shuffle[i : i + megabatch_size] for i in range(0, len(lang_shuffle), megabatch_size)]
181
+
182
+ last_mm = mm_megabatches[-1]
183
+ last_lang = lang_megabatches[-1]
184
+ additional_batch = last_mm + last_lang
185
+ megabatches = mm_megabatches[:-1] + lang_megabatches[:-1]
186
+ megabatch_indices = torch.randperm(len(megabatches), generator=generator)
187
+ megabatches = [megabatches[i] for i in megabatch_indices]
188
+
189
+ # FIXME: Hard code to avoid last batch mixed with different modalities
190
+ # if len(additional_batch) > 0:
191
+ # megabatches.append(sorted(additional_batch))
192
+
193
+ return [i for megabatch in megabatches for i in megabatch]
194
+
195
+
196
+ class LengthGroupedSampler(Sampler):
197
+ r"""
198
+ Sampler that samples indices in a way that groups together features of the dataset of roughly the same length while
199
+ keeping a bit of randomness.
200
+ """
201
+
202
+ def __init__(
203
+ self,
204
+ batch_size: int,
205
+ world_size: int,
206
+ lengths: Optional[List[int]] = None,
207
+ generator=None,
208
+ variable_length: bool = False,
209
+ group_by_modality: bool = False,
210
+ group_by_modality_auto: bool = False,
211
+ ):
212
+ if lengths is None:
213
+ raise ValueError("Lengths must be provided.")
214
+
215
+ self.batch_size = batch_size
216
+ self.world_size = world_size
217
+ self.lengths = lengths
218
+ self.generator = generator
219
+ self.variable_length = variable_length
220
+ self.group_by_modality = group_by_modality
221
+ self.group_by_modality_auto = group_by_modality_auto
222
+
223
+ def __len__(self):
224
+ return len(self.lengths)
225
+
226
+ def __iter__(self):
227
+ if self.variable_length:
228
+ assert not self.group_by_modality, "Variable length grouping is not supported with modality grouping."
229
+ indices = get_variable_length_grouped_indices(self.lengths, self.batch_size, self.world_size, generator=self.generator)
230
+ else:
231
+ if self.group_by_modality:
232
+ indices = get_modality_length_grouped_indices(self.lengths, self.batch_size, self.world_size, generator=self.generator)
233
+ elif self.group_by_modality_auto:
234
+ indices = get_modality_length_grouped_indices_auto(self.lengths, self.batch_size, self.world_size, generator=self.generator)
235
+ else:
236
+ indices = get_length_grouped_indices_auto_single(self.lengths, self.batch_size, self.world_size, generator=self.generator)
237
+ return iter(indices)
238
+
239
+
240
+ class LLaVATrainer(Trainer):
241
+
242
+ def create_accelerator_and_postprocess(self):
243
+ grad_acc_kwargs = {"num_steps": self.args.gradient_accumulation_steps}
244
+ grad_acc_kwargs["sync_with_dataloader"] = False
245
+ gradient_accumulation_plugin = GradientAccumulationPlugin(**grad_acc_kwargs)
246
+
247
+ accelerator_kwargs = InitProcessGroupKwargs(timeout=timedelta(weeks=52))
248
+ rank0_print("Setting NCCL timeout to INF to avoid running errors.")
249
+
250
+ # create accelerator object
251
+ self.accelerator = Accelerator(
252
+ dispatch_batches=self.args.dispatch_batches, split_batches=self.args.split_batches, deepspeed_plugin=self.args.deepspeed_plugin, gradient_accumulation_plugin=gradient_accumulation_plugin, kwargs_handlers=[accelerator_kwargs]
253
+ )
254
+ # some Trainer classes need to use `gather` instead of `gather_for_metrics`, thus we store a flag
255
+ self.gather_function = self.accelerator.gather_for_metrics
256
+
257
+ # deepspeed and accelerate flags covering both trainer args and accelerate launcher
258
+ self.is_deepspeed_enabled = getattr(self.accelerator.state, "deepspeed_plugin", None) is not None
259
+ self.is_fsdp_enabled = getattr(self.accelerator.state, "fsdp_plugin", None) is not None
260
+
261
+ # post accelerator creation setup
262
+ if self.is_fsdp_enabled:
263
+ fsdp_plugin = self.accelerator.state.fsdp_plugin
264
+ fsdp_plugin.limit_all_gathers = self.args.fsdp_config.get("limit_all_gathers", fsdp_plugin.limit_all_gathers)
265
+ if is_accelerate_available("0.23.0"):
266
+ fsdp_plugin.activation_checkpointing = self.args.fsdp_config.get("activation_checkpointing", fsdp_plugin.activation_checkpointing)
267
+ if fsdp_plugin.activation_checkpointing and self.args.gradient_checkpointing:
268
+ raise ValueError("The activation_checkpointing in FSDP config and the gradient_checkpointing in training arg " "can't be set to True simultaneously. Please use FSDP's activation_checkpointing logic " "when using FSDP.")
269
+
270
+ if self.is_deepspeed_enabled and getattr(self.args, "hf_deepspeed_config", None) is None:
271
+ self.propagate_args_to_deepspeed()
272
+
273
+ def _get_train_sampler(self) -> Optional[torch.utils.data.Sampler]:
274
+ if self.train_dataset is None or not has_length(self.train_dataset):
275
+ return None
276
+
277
+ if self.args.group_by_length:
278
+ lengths = self.train_dataset.lengths
279
+ return LengthGroupedSampler(
280
+ # self.args.train_batch_size * self.args.gradient_accumulation_steps, # TODO: seems that we should not have gradient_accumulation_steps
281
+ self.args.train_batch_size,
282
+ # world_size=self.args.world_size,
283
+ world_size=self.args.world_size * self.args.gradient_accumulation_steps, # TODO: seems that this may work?
284
+ lengths=lengths,
285
+ )
286
+ elif self.args.group_by_modality_length:
287
+ lengths = self.train_dataset.modality_lengths
288
+ return LengthGroupedSampler(
289
+ # self.args.train_batch_size * self.args.gradient_accumulation_steps, # TODO: seems that we should not have gradient_accumulation_steps
290
+ self.args.train_batch_size,
291
+ # world_size=self.args.world_size,
292
+ world_size=self.args.world_size * self.args.gradient_accumulation_steps, # TODO: seems that this may work?
293
+ lengths=lengths,
294
+ group_by_modality=True,
295
+ )
296
+ elif self.args.group_by_modality_length_auto:
297
+ lengths = self.train_dataset.modality_lengths
298
+ return LengthGroupedSampler(
299
+ # self.args.train_batch_size * self.args.gradient_accumulation_steps, # TODO: seems that we should not have gradient_accumulation_steps
300
+ self.args.train_batch_size,
301
+ # world_size=self.args.world_size,
302
+ world_size=self.args.world_size * self.args.gradient_accumulation_steps, # TODO: seems that this may work?
303
+ lengths=lengths,
304
+ group_by_modality_auto=True,
305
+ )
306
+ elif self.args.group_by_varlen:
307
+ lengths = self.train_dataset.lengths
308
+ return LengthGroupedSampler(
309
+ self.args.train_batch_size * self.args.gradient_accumulation_steps,
310
+ # self.args.train_batch_size, # TODO: seems that we should have gradient_accumulation_steps
311
+ # world_size=self.args.world_size,
312
+ world_size=self.args.world_size * self.args.gradient_accumulation_steps, # TODO: seems that this may work?
313
+ lengths=lengths,
314
+ variable_length=True,
315
+ )
316
+ else:
317
+ return super()._get_train_sampler()
318
+
319
+ def get_train_dataloader(self) -> DataLoader:
320
+ """
321
+ Returns the training [`~torch.utils.data.DataLoader`].
322
+
323
+ Will use no sampler if `train_dataset` does not implement `__len__`, a random sampler (adapted to distributed
324
+ training if necessary) otherwise.
325
+
326
+ Subclass and override this method if you want to inject some custom behavior.
327
+ """
328
+ if self.train_dataset is None:
329
+ raise ValueError("Trainer: training requires a train_dataset.")
330
+
331
+ train_dataset = self.train_dataset
332
+ data_collator = self.data_collator
333
+ if is_datasets_available() and isinstance(train_dataset, datasets.Dataset):
334
+ train_dataset = self._remove_unused_columns(train_dataset, description="training")
335
+ else:
336
+ data_collator = self._get_collator_with_removed_columns(data_collator, description="training")
337
+
338
+ dataloader_params = {
339
+ "batch_size": self._train_batch_size,
340
+ "collate_fn": data_collator,
341
+ "num_workers": self.args.dataloader_num_workers,
342
+ "pin_memory": self.args.dataloader_pin_memory,
343
+ "persistent_workers": self.args.dataloader_persistent_workers,
344
+ }
345
+
346
+ if not isinstance(train_dataset, torch.utils.data.IterableDataset):
347
+ dataloader_params["sampler"] = self._get_train_sampler()
348
+ dataloader_params["drop_last"] = self.args.dataloader_drop_last
349
+ dataloader_params["worker_init_fn"] = seed_worker
350
+ dataloader_params["prefetch_factor"] = self.args.dataloader_num_workers * 2 if self.args.dataloader_num_workers != 0 else None
351
+
352
+ dataloader = self.accelerator.prepare(DataLoader(train_dataset, **dataloader_params))
353
+
354
+ return dataloader
355
+
356
+ def create_optimizer(self):
357
+ """
358
+ Setup the optimizer.
359
+
360
+ We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the
361
+ Trainer's init through `optimizers`, or subclass and override this method in a subclass.
362
+ """
363
+ if is_sagemaker_mp_enabled():
364
+ return super().create_optimizer()
365
+
366
+ opt_model = self.model
367
+
368
+ if self.optimizer is None:
369
+ decay_parameters = get_parameter_names(opt_model, ALL_LAYERNORM_LAYERS)
370
+ decay_parameters = [name for name in decay_parameters if "bias" not in name]
371
+ lr_mapper = {}
372
+ if self.args.mm_projector_lr is not None:
373
+ lr_mapper["mm_projector"] = self.args.mm_projector_lr
374
+ if self.args.mm_vision_tower_lr is not None:
375
+ lr_mapper["vision_tower"] = self.args.mm_vision_tower_lr
376
+ if len(lr_mapper) > 0:
377
+ special_lr_parameters = [name for name, _ in opt_model.named_parameters() if any(module_keyword in name for module_keyword in lr_mapper)]
378
+ optimizer_grouped_parameters = [
379
+ {
380
+ "params": [p for n, p in opt_model.named_parameters() if (n in decay_parameters and n not in special_lr_parameters and p.requires_grad)],
381
+ "weight_decay": self.args.weight_decay,
382
+ },
383
+ {
384
+ "params": [p for n, p in opt_model.named_parameters() if (n not in decay_parameters and n not in special_lr_parameters and p.requires_grad)],
385
+ "weight_decay": 0.0,
386
+ },
387
+ ]
388
+ for module_keyword, lr in lr_mapper.items():
389
+ module_parameters = [name for name, _ in opt_model.named_parameters() if module_keyword in name]
390
+ optimizer_grouped_parameters.extend(
391
+ [
392
+ {
393
+ "params": [p for n, p in opt_model.named_parameters() if (n in decay_parameters and n in module_parameters and p.requires_grad)],
394
+ "weight_decay": self.args.weight_decay,
395
+ "lr": lr,
396
+ },
397
+ {
398
+ "params": [p for n, p in opt_model.named_parameters() if (n not in decay_parameters and n in module_parameters and p.requires_grad)],
399
+ "weight_decay": 0.0,
400
+ "lr": lr,
401
+ },
402
+ ]
403
+ )
404
+ else:
405
+ optimizer_grouped_parameters = [
406
+ {
407
+ "params": [p for n, p in opt_model.named_parameters() if (n in decay_parameters and p.requires_grad)],
408
+ "weight_decay": self.args.weight_decay,
409
+ },
410
+ {
411
+ "params": [p for n, p in opt_model.named_parameters() if (n not in decay_parameters and p.requires_grad)],
412
+ "weight_decay": 0.0,
413
+ },
414
+ ]
415
+
416
+ optimizer_cls, optimizer_kwargs = Trainer.get_optimizer_cls_and_kwargs(self.args)
417
+
418
+ self.optimizer = optimizer_cls(optimizer_grouped_parameters, **optimizer_kwargs)
419
+ if optimizer_cls.__name__ == "Adam8bit":
420
+ import bitsandbytes
421
+
422
+ manager = bitsandbytes.optim.GlobalOptimManager.get_instance()
423
+
424
+ skipped = 0
425
+ for module in opt_model.modules():
426
+ if isinstance(module, nn.Embedding):
427
+ skipped += sum({p.data_ptr(): p.numel() for p in module.parameters()}.values())
428
+ logger.info(f"skipped {module}: {skipped/2**20}M params")
429
+ manager.register_module_override(module, "weight", {"optim_bits": 32})
430
+ logger.debug(f"bitsandbytes: will optimize {module} in fp32")
431
+ logger.info(f"skipped: {skipped/2**20}M params")
432
+
433
+ return self.optimizer
434
+
435
+ def _save_checkpoint(self, model, trial, metrics=None):
436
+ if getattr(self.args, "tune_mm_mlp_adapter", False) or (
437
+ hasattr(self.args, "mm_tunable_parts") and (len(self.args.mm_tunable_parts.split(",")) == 1 and ("mm_mlp_adapter" in self.args.mm_tunable_parts or "mm_vision_resampler" in self.args.mm_tunable_parts))
438
+ ):
439
+ from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR
440
+
441
+ checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}"
442
+
443
+ run_dir = self._get_output_dir(trial=trial)
444
+ output_dir = os.path.join(run_dir, checkpoint_folder)
445
+
446
+ # Only save Adapter
447
+ keys_to_match = ["mm_projector", "vision_resampler"]
448
+ if getattr(self.args, "use_im_start_end", False):
449
+ keys_to_match.extend(["embed_tokens", "embed_in"])
450
+
451
+ weight_to_save = get_mm_adapter_state_maybe_zero_3(self.model.named_parameters(), keys_to_match)
452
+
453
+ if self.args.local_rank == 0 or self.args.local_rank == -1:
454
+ self.model.config.save_pretrained(output_dir)
455
+ torch.save(weight_to_save, os.path.join(output_dir, f"mm_projector.bin"))
456
+ else:
457
+ super(LLaVATrainer, self)._save_checkpoint(model, trial, metrics)
458
+
459
+ def _save(self, output_dir: Optional[str] = None, state_dict=None):
460
+ if getattr(self.args, "tune_mm_mlp_adapter", False):
461
+ pass
462
+ else:
463
+ super(LLaVATrainer, self)._save(output_dir, state_dict)
464
+
465
+
466
+ class LLaVADPOTrainer(DPOTrainer):
467
+ def _get_train_sampler(self) -> Optional[torch.utils.data.Sampler]:
468
+ if self.train_dataset is None or not has_length(self.train_dataset):
469
+ return None
470
+
471
+ if self.args.group_by_modality_length:
472
+ lengths = self.train_dataset.modality_lengths
473
+ return LengthGroupedSampler(
474
+ # self.args.train_batch_size * self.args.gradient_accumulation_steps, # TODO: seems that we should not have gradient_accumulation_steps
475
+ self.args.train_batch_size,
476
+ world_size=self.args.world_size,
477
+ lengths=lengths,
478
+ group_by_modality=True,
479
+ )
480
+ else:
481
+ return super()._get_train_sampler()
482
+
483
+ def _save_checkpoint(self, model, trial, metrics=None):
484
+ if getattr(self.args, "tune_mm_mlp_adapter", False) or (
485
+ hasattr(self.args, "mm_tunable_parts") and (len(self.args.mm_tunable_parts.split(",")) == 1 and ("mm_mlp_adapter" in self.args.mm_tunable_parts or "mm_vision_resampler" in self.args.mm_tunable_parts))
486
+ ):
487
+ from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR
488
+
489
+ checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}"
490
+
491
+ run_dir = self._get_output_dir(trial=trial)
492
+ output_dir = os.path.join(run_dir, checkpoint_folder)
493
+
494
+ # Only save Adapter
495
+ keys_to_match = ["mm_projector", "vision_resampler"]
496
+ if getattr(self.args, "use_im_start_end", False):
497
+ keys_to_match.extend(["embed_tokens", "embed_in"])
498
+
499
+ weight_to_save = get_mm_adapter_state_maybe_zero_3(self.model.named_parameters(), keys_to_match)
500
+
501
+ if self.args.local_rank == 0 or self.args.local_rank == -1:
502
+ self.model.config.save_pretrained(output_dir)
503
+ torch.save(weight_to_save, os.path.join(output_dir, f"mm_projector.bin"))
504
+ else:
505
+ # super(LLaVADPOTrainer, self)._save_checkpoint(model, trial, metrics)
506
+ # print(type(model))
507
+ # from transformers.modeling_utils import unwrap_model
508
+ # print(type(unwrap_model(model)))
509
+ # print(unwrap_model(model).config)
510
+ if self.args.lora_enable:
511
+ from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR
512
+
513
+ checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}"
514
+ run_dir = self._get_output_dir(trial=trial)
515
+ output_dir = os.path.join(run_dir, checkpoint_folder)
516
+ from transformers.modeling_utils import unwrap_model
517
+
518
+ unwrapped_model = unwrap_model(model)
519
+ self.save_my_lora_ckpt(output_dir, self.args, unwrapped_model)
520
+ else:
521
+ super(LLaVADPOTrainer, self)._save_checkpoint(model, trial, metrics)
522
+
523
+ def _save(self, output_dir: Optional[str] = None, state_dict=None):
524
+ if getattr(self.args, "tune_mm_mlp_adapter", False):
525
+ pass
526
+ else:
527
+ super(LLaVADPOTrainer, self)._save(output_dir, state_dict)
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/train/llava_trainer_eval.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import subprocess
3
+
4
+ from llava.train.llava_trainer import LLaVATrainer
5
+
6
+
7
+ class LLaVAEvalTrainer(LLaVATrainer):
8
+ def evaluate(self, evaluate_args):
9
+ cmd = f"accelerate launch --num_processes {evaluate_args.eval_num_processes} -m lmms_eval \
10
+ --model {evaluate_args.model} \
11
+ --model_args {evaluate_args.model_args} \
12
+ --tasks {evaluate_args.task_names} \
13
+ --batch_size {evaluate_args.batch_size} \
14
+ --log_samples_suffix {evaluate_args.log_samples_suffix} \
15
+ --output_path {evaluate_args.output_path}"
16
+ if evaluate_args.limit:
17
+ cmd += f" --limit {evaluate_args.limit}"
18
+ if evaluate_args.num_fewshot:
19
+ cmd += f" --num_fewshot {evaluate_args.num_fewshot}"
20
+ if evaluate_args.gen_kwargs != "":
21
+ cmd += f" --gen_kwargs {evaluate_args.gen_kwargs}"
22
+ if evaluate_args.log_samples:
23
+ cmd += f" --log_samples"
24
+ else:
25
+ assert False, "Please log samples so that the result can be parsed"
26
+ results = subprocess.run([cmd], shell=True, capture_output=True, text=True)
27
+ try:
28
+ result_file_index_start = results.stdout.index("Saved samples to ")
29
+ result_file_index_end = results.stdout.index(f".json")
30
+ result_file_index_start += len("Saved samples to ")
31
+ file = results.stdout[result_file_index_start:result_file_index_end]
32
+ except:
33
+ result_file_index_start = results.stderr.index("Saved samples to ")
34
+ result_file_index_end = results.stderr.index(f".json")
35
+ result_file_index_start += len("Saved samples to ")
36
+ file = results.stderr[result_file_index_start:result_file_index_end]
37
+ file = file.split("/")[:-1]
38
+ file = "/".join(file) + "/results.json"
39
+ with open(file, "r") as f:
40
+ lmms_eval_results = json.load(f)
41
+ result_dict = {}
42
+ tasks_list = evaluate_args.task_names.split(",")
43
+ for task in tasks_list:
44
+ task_results = lmms_eval_results["results"][task]
45
+ for k, v in task_results.items():
46
+ if k != "alias" and "stderr" not in k:
47
+ metric = k.split(",")[0]
48
+ result_dict[f"{task}_{metric}"] = v
49
+ return result_dict
50
+
51
+ """def evaluate(self, evaluate_args):
52
+ initialize_tasks()
53
+ tasks_list = evaluate_args.task_names.split(",")
54
+ result_dict = {}
55
+ results = evaluator.simple_evaluate(
56
+ model=evaluate_args.model,
57
+ model_args=evaluate_args.model_args,
58
+ tasks=tasks_list,
59
+ num_fewshot=evaluate_args.num_fewshot,
60
+ batch_size=evaluate_args.batch_size,
61
+ device=evaluate_args.device,
62
+ limit=evaluate_args.limit,
63
+ check_integrity=evaluate_args.check_integrity,
64
+ show_task_to_terminal=evaluate_args.show_task_to_terminal,
65
+ log_samples=evaluate_args.log_samples,
66
+ gen_kwargs=evaluate_args.gen_kwargs,
67
+ cli_args=evaluate_args,
68
+ )
69
+ for task in tasks_list:
70
+ task_results = results["results"][task]
71
+ for k,v in task_results.items():
72
+ if k != "alias" and "stderr" not in k:
73
+ metric = k.split(",")[0]
74
+ result_dict[f"{task}_{metric}"] = v
75
+
76
+ return result_dict"""
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/train/train.py ADDED
@@ -0,0 +1,1721 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright:
2
+ # Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright:
3
+ # Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import ast
18
+ import os
19
+ import copy
20
+ from dataclasses import dataclass, field
21
+ import json
22
+ import logging
23
+ import pathlib
24
+ from typing import Dict, Optional, Sequence, List
25
+ from PIL import Image, ImageFile
26
+ from packaging import version
27
+ import numpy as np
28
+
29
+ import time
30
+ import random
31
+ import yaml
32
+ import math
33
+ import re
34
+ import torch
35
+
36
+ import transformers
37
+ import tokenizers
38
+ import deepspeed
39
+
40
+ from transformers import AutoConfig
41
+ from torch.utils.data import Dataset
42
+ from llava.constants import IGNORE_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, IMAGE_TOKEN_INDEX
43
+ from llava.train.llava_trainer import LLaVATrainer
44
+
45
+ from llava import conversation as conversation_lib
46
+ from llava.model import *
47
+ from llava.mm_utils import process_highres_image, process_anyres_image, process_highres_image_crop_split, tokenizer_image_token
48
+ from llava.utils import rank0_print, process_video_with_pyav, process_video_with_decord
49
+
50
+ torch.multiprocessing.set_sharing_strategy("file_system")
51
+
52
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
53
+ local_rank = None
54
+
55
+ IS_TOKENIZER_GREATER_THAN_0_14 = version.parse(tokenizers.__version__) >= version.parse("0.14")
56
+
57
+
58
+ @dataclass
59
+ class ModelArguments:
60
+ model_name_or_path: Optional[str] = field(default="facebook/opt-125m")
61
+ model_class_name: Optional[str] = field(default=None, metadata={"help": "Used to init model class, format is XXXXForCausalLM. e.g. currently XXXX is chosen from LlavaLlama, LlavaMixtral, LlavaMistral, Llama"})
62
+
63
+ mm_tunable_parts: Optional[str] = field(
64
+ default=None, metadata={"help": 'Could be "mm_mlp_adapter", "mm_vision_resampler", "mm_vision_tower,mm_mlp_adapter,mm_language_model", "mm_vision_tower,mm_mlp_adapter,mm_language_model", "mm_mlp_adapter,mm_language_model"'}
65
+ )
66
+ # deciding which part of the multimodal model to tune, will overwrite other previous settings
67
+
68
+ version: Optional[str] = field(default="v0")
69
+ freeze_backbone: bool = field(default=False)
70
+ tune_mm_mlp_adapter: bool = field(default=False)
71
+ tune_mm_vision_resampler: bool = field(default=False)
72
+ vision_tower: Optional[str] = field(default=None)
73
+ vision_tower_pretrained: Optional[str] = field(default=None) # default to the last layer
74
+
75
+ unfreeze_mm_vision_tower: bool = field(default=False)
76
+ unfreeze_language_model: bool = field(default=False)
77
+ mm_vision_select_layer: Optional[int] = field(default=-1) # default to the last layer
78
+ pretrain_mm_mlp_adapter: Optional[str] = field(default=None)
79
+ mm_projector_type: Optional[str] = field(default="linear")
80
+ mm_use_im_start_end: bool = field(default=False)
81
+ mm_use_im_patch_token: bool = field(default=True)
82
+ mm_patch_merge_type: Optional[str] = field(default="flat")
83
+ mm_vision_select_feature: Optional[str] = field(default="patch")
84
+ mm_resampler_type: Optional[str] = field(default=None)
85
+ mm_mask_drop_mode: str = field(default="fixed")
86
+ mm_mask_drop_skip_percentage: float = field(default=0.0)
87
+ mm_mask_drop_ratio: float = field(default=0.25)
88
+ mm_mask_drop_ratio_upper: Optional[float] = field(default=None)
89
+ mm_mask_drop_ratio_lower: Optional[float] = field(default=None)
90
+ mm_spatial_pool_stride: Optional[int] = field(default=None)
91
+ mm_spatial_pool_mode: str = field(default="bilinear")
92
+ mm_spatial_pool_out_channels: Optional[int] = field(default=None)
93
+ mm_perceiver_depth: Optional[int] = field(default=3)
94
+ mm_perceiver_latents: Optional[int] = field(default=32)
95
+ mm_perceiver_ff_mult: Optional[float] = field(default=4)
96
+ mm_perceiver_pretrained: Optional[str] = field(default=None)
97
+ mm_qformer_depth: Optional[int] = field(default=3)
98
+ mm_qformer_latents: Optional[int] = field(default=32)
99
+ mm_qformer_pretrained: Optional[str] = field(default=None)
100
+
101
+ rope_scaling_factor: Optional[float] = field(default=None)
102
+ rope_scaling_type: Optional[str] = field(default=None)
103
+
104
+ s2: Optional[bool] = field(default=False)
105
+ s2_scales: Optional[str] = field(default="336,672,1008")
106
+
107
+ use_pos_skipping: Optional[bool] = field(default=False)
108
+ pos_skipping_range: Optional[int] = field(default=4096)
109
+
110
+
111
+ mm_newline_position: Optional[str] = field(default="grid")
112
+ delay_load: Optional[bool] = field(default=True)
113
+ add_faster_video: Optional[bool] = field(default=False)
114
+ faster_token_stride: Optional[int] = field(default=10)
115
+
116
+
117
+
118
+ @dataclass
119
+ class DataArguments:
120
+ data_path: str = field(default=None, metadata={"help": "Path to the training data, in llava's instruction.json format. Supporting multiple json files via /path/to/{a,b,c}.json"})
121
+ lazy_preprocess: bool = False
122
+ is_multimodal: bool = False
123
+ early_mix_text: bool = False
124
+ image_folder: Optional[str] = field(default=None)
125
+ image_aspect_ratio: str = "square"
126
+ image_grid_pinpoints: Optional[str] = field(default=None)
127
+ image_crop_resolution: Optional[int] = field(default=None)
128
+ image_split_resolution: Optional[int] = field(default=None)
129
+
130
+ video_folder: Optional[str] = field(default=None)
131
+ video_fps: Optional[int] = field(default=1)
132
+ frames_upbound: Optional[int] = field(default=0)
133
+ add_time_instruction: Optional[bool] = field(default=False)
134
+ force_sample: Optional[bool] = field(default=False)
135
+
136
+
137
+ @dataclass
138
+ class TrainingArguments(transformers.TrainingArguments):
139
+ cache_dir: Optional[str] = field(default=None)
140
+ optim: str = field(default="adamw_torch")
141
+ remove_unused_columns: bool = field(default=False)
142
+ freeze_mm_mlp_adapter: bool = field(default=False)
143
+ freeze_mm_vision_resampler: bool = field(default=False)
144
+ mpt_attn_impl: Optional[str] = field(default="triton")
145
+ model_max_length: int = field(
146
+ default=4096,
147
+ metadata={"help": "Maximum sequence length. Sequences will be right padded (and possibly truncated)."},
148
+ )
149
+ double_quant: bool = field(default=True, metadata={"help": "Compress the quantization statistics through double quantization."})
150
+ quant_type: str = field(default="nf4", metadata={"help": "Quantization data type to use. Should be one of `fp4` or `nf4`."})
151
+ bits: int = field(default=16, metadata={"help": "How many bits to use."})
152
+ lora_enable: bool = False
153
+ lora_r: int = 64
154
+ lora_alpha: int = 16
155
+ lora_dropout: float = 0.05
156
+ lora_weight_path: str = ""
157
+ lora_bias: str = "none"
158
+ mm_projector_lr: Optional[float] = None
159
+ mm_vision_tower_lr: Optional[float] = None
160
+ group_by_varlen: bool = field(default=False)
161
+ group_by_modality_length: bool = field(default=False)
162
+ group_by_modality_length_auto: bool = field(default=False)
163
+ auto_find_batch_size: bool = field(default=False)
164
+ gradient_checkpointing: bool = field(default=True)
165
+ verbose_logging: bool = field(default=False)
166
+ attn_implementation: str = field(default="flash_attention_2", metadata={"help": "Use transformers attention implementation."})
167
+
168
+
169
+ # @dataclass
170
+ # class EvaluationArguments:
171
+ # eval_num_processes: int = field(default=1)
172
+ # task_names: str = field(default=None)
173
+ # model: str = field(default="llava")
174
+ # model_args: Optional[str] = field(default=None)
175
+ # num_fewshot: Optional[int] = field(default=None)
176
+ # batch_size: int = field(default=1)
177
+ # device: Optional[str] = field(default=None)
178
+ # limit: Optional[int] = field(default=None)
179
+ # check_integrity: Optional[bool] = field(default=False)
180
+ # show_task_to_terminal: Optional[bool] = field(default=False)
181
+ # log_samples: Optional[bool] = field(default=True)
182
+ # gen_kwargs: Optional[str] = field(default="")
183
+ # log_samples_suffix: Optional[str] = field(default="")
184
+ # output_path: Optional[str] = field(default="./logs/")
185
+
186
+
187
+ def maybe_zero_3(param, ignore_status=False, name=None):
188
+ from deepspeed import zero
189
+ from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
190
+
191
+ if hasattr(param, "ds_id"):
192
+ if param.ds_status == ZeroParamStatus.NOT_AVAILABLE:
193
+ if not ignore_status:
194
+ logging.warning(f"{name}: param.ds_status != ZeroParamStatus.NOT_AVAILABLE: {param.ds_status}")
195
+ with zero.GatheredParameters([param]):
196
+ param = param.data.detach().cpu().clone()
197
+ else:
198
+ param = param.detach().cpu().clone()
199
+ return param
200
+
201
+
202
+ # Borrowed from peft.utils.get_peft_model_state_dict
203
+ def get_peft_state_maybe_zero_3(named_params, bias):
204
+ if bias == "none":
205
+ to_return = {k: t for k, t in named_params if "lora_" in k}
206
+ elif bias == "all":
207
+ to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k}
208
+ elif bias == "lora_only":
209
+ to_return = {}
210
+ maybe_lora_bias = {}
211
+ lora_bias_names = set()
212
+ for k, t in named_params:
213
+ if "lora_" in k:
214
+ to_return[k] = t
215
+ bias_name = k.split("lora_")[0] + "bias"
216
+ lora_bias_names.add(bias_name)
217
+ elif "bias" in k:
218
+ maybe_lora_bias[k] = t
219
+ for k, t in maybe_lora_bias:
220
+ if bias_name in lora_bias_names:
221
+ to_return[bias_name] = t
222
+ else:
223
+ raise NotImplementedError
224
+ to_return = {k: maybe_zero_3(v, ignore_status=True) for k, v in to_return.items()}
225
+ return to_return
226
+
227
+
228
+ def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True):
229
+ to_return = {k: t for k, t in named_params if "lora_" not in k}
230
+ if require_grad_only:
231
+ to_return = {k: t for k, t in to_return.items() if t.requires_grad}
232
+ to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()}
233
+ return to_return
234
+
235
+
236
+ def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match):
237
+ to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)}
238
+ to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()}
239
+ return to_return
240
+
241
+
242
+ def find_all_linear_names(model):
243
+ cls = torch.nn.Linear
244
+ lora_module_names = set()
245
+ multimodal_keywords = ["mm_projector", "vision_tower", "vision_resampler"]
246
+ for name, module in model.named_modules():
247
+ if any(mm_keyword in name for mm_keyword in multimodal_keywords):
248
+ continue
249
+ if isinstance(module, cls):
250
+ names = name.split(".")
251
+ lora_module_names.add(names[0] if len(names) == 1 else names[-1])
252
+
253
+ if "lm_head" in lora_module_names: # needed for 16-bit
254
+ lora_module_names.remove("lm_head")
255
+ return list(lora_module_names)
256
+
257
+
258
+ def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str):
259
+ """Collects the state dict and dump to disk."""
260
+ if hasattr(trainer.args, "tune_mm_mlp_adapter") and trainer.args.tune_mm_mlp_adapter:
261
+ check_only_save_mm_adapter_tunnable = True
262
+ # only has mm_mlp_adapter and mm_vision_resampler in the tuneable parts
263
+ elif hasattr(trainer.args, "mm_tunable_parts") and (len(trainer.args.mm_tunable_parts.split(",")) == 1 and ("mm_mlp_adapter" in trainer.args.mm_tunable_parts or "mm_vision_resampler" in trainer.args.mm_tunable_parts)):
264
+ check_only_save_mm_adapter_tunnable = True
265
+ else:
266
+ check_only_save_mm_adapter_tunnable = False
267
+
268
+ trainer.accelerator.wait_for_everyone()
269
+ torch.cuda.synchronize()
270
+ rank0_print(f"Only save projectors: {check_only_save_mm_adapter_tunnable}")
271
+ if check_only_save_mm_adapter_tunnable:
272
+ # Only save Adapter
273
+ keys_to_match = ["mm_projector", "vision_resampler"]
274
+ if getattr(trainer.args, "use_im_start_end", False):
275
+ keys_to_match.extend(["embed_tokens", "embed_in"])
276
+
277
+ weight_to_save = get_mm_adapter_state_maybe_zero_3(trainer.model.named_parameters(), keys_to_match)
278
+ trainer.model.config.save_pretrained(output_dir)
279
+
280
+ current_folder = output_dir.split("/")[-1]
281
+ parent_folder = os.path.dirname(output_dir)
282
+ if trainer.args.local_rank == 0 or trainer.args.local_rank == -1:
283
+ if current_folder.startswith("checkpoint-"):
284
+ mm_projector_folder = os.path.join(parent_folder, "mm_projector")
285
+ os.makedirs(mm_projector_folder, exist_ok=True)
286
+ torch.save(weight_to_save, os.path.join(mm_projector_folder, f"{current_folder}.bin"))
287
+ else:
288
+ torch.save(weight_to_save, os.path.join(output_dir, f"mm_projector.bin"))
289
+ return
290
+
291
+ if trainer.deepspeed:
292
+ trainer.save_model(output_dir)
293
+ return
294
+
295
+ state_dict = trainer.model.state_dict()
296
+ if trainer.args.should_save:
297
+ cpu_state_dict = {key: value.cpu() for key, value in state_dict.items()}
298
+ del state_dict
299
+ trainer._save(output_dir, state_dict=cpu_state_dict) # noqa
300
+
301
+
302
+ def smart_tokenizer_and_embedding_resize(
303
+ special_tokens_dict: Dict,
304
+ tokenizer: transformers.PreTrainedTokenizer,
305
+ model: transformers.PreTrainedModel,
306
+ ):
307
+ """Resize tokenizer and embedding.
308
+
309
+ Note: This is the unoptimized version that may make your embedding size not be divisible by 64.
310
+ """
311
+ num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict)
312
+ model.resize_token_embeddings(len(tokenizer))
313
+
314
+ if num_new_tokens > 0:
315
+ input_embeddings = model.get_input_embeddings().weight.data
316
+ output_embeddings = model.get_output_embeddings().weight.data
317
+
318
+ input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
319
+ output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
320
+
321
+ input_embeddings[-num_new_tokens:] = input_embeddings_avg
322
+ output_embeddings[-num_new_tokens:] = output_embeddings_avg
323
+
324
+
325
+ def _tokenize_fn(strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict:
326
+ """Tokenize a list of strings."""
327
+ tokenized_list = [
328
+ tokenizer(
329
+ text,
330
+ return_tensors="pt",
331
+ padding="longest",
332
+ max_length=tokenizer.model_max_length,
333
+ truncation=True,
334
+ )
335
+ for text in strings
336
+ ]
337
+ input_ids = labels = [tokenized.input_ids[0] for tokenized in tokenized_list]
338
+ input_ids_lens = labels_lens = [tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() for tokenized in tokenized_list]
339
+ return dict(
340
+ input_ids=input_ids,
341
+ labels=labels,
342
+ input_ids_lens=input_ids_lens,
343
+ labels_lens=labels_lens,
344
+ )
345
+
346
+
347
+ def _mask_targets(target, tokenized_lens, speakers):
348
+ # cur_idx = 0
349
+ cur_idx = tokenized_lens[0]
350
+ tokenized_lens = tokenized_lens[1:]
351
+ target[:cur_idx] = IGNORE_INDEX
352
+ for tokenized_len, speaker in zip(tokenized_lens, speakers):
353
+ if speaker == "human":
354
+ target[cur_idx + 2 : cur_idx + tokenized_len] = IGNORE_INDEX
355
+ cur_idx += tokenized_len
356
+
357
+
358
+ def _add_speaker_and_signal(header, source, get_conversation=True):
359
+ """Add speaker and start/end signal on each round."""
360
+ BEGIN_SIGNAL = "### "
361
+ END_SIGNAL = "\n"
362
+ conversation = header
363
+ for sentence in source:
364
+ from_str = sentence["from"]
365
+ if from_str.lower() == "human":
366
+ from_str = conversation_lib.default_conversation.roles[0]
367
+ elif from_str.lower() == "gpt":
368
+ from_str = conversation_lib.default_conversation.roles[1]
369
+ else:
370
+ from_str = "unknown"
371
+ sentence["value"] = BEGIN_SIGNAL + from_str + ": " + sentence["value"] + END_SIGNAL
372
+ if get_conversation:
373
+ conversation += sentence["value"]
374
+ conversation += BEGIN_SIGNAL
375
+ return conversation
376
+
377
+
378
+ def preprocess_multimodal(sources: Sequence[str], data_args: DataArguments) -> Dict:
379
+ is_multimodal = data_args.is_multimodal
380
+ if not is_multimodal:
381
+ return sources
382
+
383
+ for source in sources:
384
+ for sentence in source:
385
+ # TODO maybe this should be changed for interleaved data?
386
+ # if DEFAULT_IMAGE_TOKEN in sentence["value"] and not sentence["value"].startswith(DEFAULT_IMAGE_TOKEN):
387
+ # only check for num_im=1
388
+ num_im = len(re.findall(DEFAULT_IMAGE_TOKEN, sentence["value"]))
389
+ if num_im == 1 and DEFAULT_IMAGE_TOKEN in sentence["value"] and not sentence["value"].startswith(DEFAULT_IMAGE_TOKEN):
390
+ sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, "").strip()
391
+ sentence["value"] = DEFAULT_IMAGE_TOKEN + "\n" + sentence["value"]
392
+ sentence["value"] = sentence["value"].strip()
393
+ if "mmtag" in conversation_lib.default_conversation.version:
394
+ sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, "<Image>" + DEFAULT_IMAGE_TOKEN + "</Image>")
395
+ replace_token = DEFAULT_IMAGE_TOKEN
396
+ if data_args.mm_use_im_start_end:
397
+ replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
398
+ sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token)
399
+
400
+ # For videoInstruct-100k noisy_data. TODO: Ask Yuanhan to clean the data instead of leaving the noise code here.
401
+ sentence["value"] = sentence["value"].replace("QA_GT_caption_based_noisy", "")
402
+
403
+ return sources
404
+
405
+
406
+ def preprocess_llama_2(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict:
407
+ conv = conversation_lib.default_conversation.copy()
408
+ roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
409
+
410
+ # Apply prompt templates
411
+ conversations = []
412
+ for i, source in enumerate(sources):
413
+ if roles[source[0]["from"]] != conv.roles[0]:
414
+ # Skip the first one if it is not from human
415
+ source = source[1:]
416
+
417
+ conv.messages = []
418
+ for j, sentence in enumerate(source):
419
+ role = roles[sentence["from"]]
420
+ assert role == conv.roles[j % 2], f"{i}"
421
+ conv.append_message(role, sentence["value"])
422
+ conversations.append(conv.get_prompt())
423
+
424
+ # Tokenize conversations
425
+
426
+ if has_image:
427
+ input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0)
428
+ else:
429
+ input_ids = tokenizer(
430
+ conversations,
431
+ return_tensors="pt",
432
+ padding="longest",
433
+ max_length=tokenizer.model_max_length,
434
+ truncation=True,
435
+ ).input_ids
436
+
437
+ targets = input_ids.clone()
438
+
439
+ assert conv.sep_style == conversation_lib.SeparatorStyle.LLAMA_2
440
+
441
+ # Mask targets
442
+ sep = "[/INST] "
443
+ for conversation, target in zip(conversations, targets):
444
+ total_len = int(target.ne(tokenizer.pad_token_id).sum())
445
+
446
+ rounds = conversation.split(conv.sep2)
447
+ cur_len = 1
448
+ target[:cur_len] = IGNORE_INDEX
449
+ for i, rou in enumerate(rounds):
450
+ if rou == "":
451
+ break
452
+
453
+ parts = rou.split(sep)
454
+ if len(parts) != 2:
455
+ break
456
+ parts[0] += sep
457
+
458
+ if has_image:
459
+ round_len = len(tokenizer_image_token(rou, tokenizer))
460
+ instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2
461
+ else:
462
+ round_len = len(tokenizer(rou).input_ids)
463
+ instruction_len = len(tokenizer(parts[0]).input_ids) - 2
464
+
465
+ target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
466
+
467
+ cur_len += round_len
468
+ target[cur_len:] = IGNORE_INDEX
469
+
470
+ if cur_len < tokenizer.model_max_length:
471
+ if cur_len != total_len:
472
+ target[:] = IGNORE_INDEX
473
+ print(f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)")
474
+
475
+ return dict(
476
+ input_ids=input_ids,
477
+ labels=targets,
478
+ )
479
+
480
+
481
+ def preprocess_gemma(sources: List[List[Dict[str, str]]], tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict:
482
+ conv: conversation_lib.Conversation = conversation_lib.default_conversation.copy()
483
+ roles: Dict[str, str] = {"human": conv.roles[0], "gpt": conv.roles[1]}
484
+
485
+ # Apply prompt templates
486
+ conversations: List[str] = []
487
+ for i, source in enumerate(sources):
488
+ if roles[source[0]["from"]] != conv.roles[0]:
489
+ # Skip the first one if it is not from human
490
+ source: List[Dict[str, str]] = source[1:]
491
+
492
+ conv.messages = []
493
+ for j, sentence in enumerate(source):
494
+ role: str = roles[sentence["from"]]
495
+ assert role == conv.roles[j % 2], f"{i}"
496
+ conv.append_message(role, sentence["value"])
497
+ conversations.append(conv.get_prompt())
498
+
499
+ # Tokenize conversations
500
+ if has_image:
501
+ input_ids: torch.Tensor = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0)
502
+ else:
503
+ input_ids: torch.Tensor = tokenizer(
504
+ conversations,
505
+ return_tensors="pt",
506
+ padding="longest",
507
+ max_length=tokenizer.model_max_length,
508
+ truncation=True,
509
+ ).input_ids
510
+
511
+ targets: torch.Tensor = input_ids.clone()
512
+ assert conv.sep_style == conversation_lib.SeparatorStyle.GEMMA
513
+
514
+ # Mask target
515
+ sep: str = conv.sep + conv.roles[1]
516
+ for conversation, target in zip(conversations, targets):
517
+ total_len: int = int(target.ne(tokenizer.pad_token_id).sum())
518
+
519
+ rounds: List[str] = conversation.split(conv.sep)
520
+ re_rounds = []
521
+ for conv_idx in range(0, len(rounds), 2):
522
+ re_rounds.append(conv.sep.join(rounds[conv_idx : conv_idx + 2]))
523
+
524
+ cur_len = 1 # Ignore <bos>
525
+ target[:cur_len] = IGNORE_INDEX
526
+ for i, rou in enumerate(re_rounds):
527
+ if rou == "":
528
+ break
529
+
530
+ parts = rou.split(sep)
531
+ if len(parts) != 2:
532
+ break
533
+ parts[0] += sep # Re-append sep because split on this
534
+ # Now "".join(parts)==rou
535
+
536
+ if has_image:
537
+ round_len = len(tokenizer_image_token(rou, tokenizer)) - 1 # Ignore <bos>
538
+ instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 1 # Ignore <bos>
539
+ else:
540
+ round_len = len(tokenizer(rou).input_ids) - 1 # Ignore <bos>
541
+ instruction_len = len(tokenizer(parts[0]).input_ids) - 1 # Ignore <bos>
542
+
543
+ round_len += 2 # sep: <end_of_turn>\n takes 2 tokens
544
+ target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
545
+ cur_len += round_len
546
+
547
+ target[cur_len:] = IGNORE_INDEX
548
+
549
+ if cur_len < tokenizer.model_max_length:
550
+ if cur_len != total_len:
551
+ target[:] = IGNORE_INDEX
552
+ print(f"warning: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)")
553
+
554
+ return dict(
555
+ input_ids=input_ids,
556
+ labels=targets,
557
+ )
558
+
559
+
560
+ def preprocess_qwen(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False, max_len=2048, system_message: str = "You are a helpful assistant.") -> Dict:
561
+ # roles = {"human": "<|im_start|>user", "gpt": "<|im_start|>assistant"}
562
+ roles = {"human": "user", "gpt": "assistant"}
563
+
564
+ # Add image tokens to tokenizer as a special tokens
565
+ # Use a deepcopy of tokenizer so that we don't modify on the tokenizer
566
+ tokenizer = copy.deepcopy(tokenizer)
567
+ # When there is actually an image, we add the image tokens as a special token
568
+ if has_image:
569
+ tokenizer.add_tokens(["<image>"], special_tokens=True)
570
+
571
+ image_token_index = tokenizer.convert_tokens_to_ids("<image>")
572
+ im_start, im_end = tokenizer.additional_special_tokens_ids
573
+ # unmask_tokens = ["<|im_start|>", "<|im_start|>", "\n"]
574
+ unmask_tokens_idx = [198, im_start, im_end]
575
+ nl_tokens = tokenizer("\n").input_ids
576
+
577
+ # Reset Qwen chat templates so that it won't include system message every time we apply
578
+ chat_template = "{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}"
579
+ tokenizer.chat_template = chat_template
580
+
581
+ # _system = tokenizer("system").input_ids + nl_tokens
582
+ # _user = tokenizer("user").input_ids + nl_tokens
583
+ # _assistant = tokenizer("assistant").input_ids + nl_tokens
584
+
585
+ # Apply prompt templates
586
+ input_ids, targets = [], []
587
+ for i, source in enumerate(sources):
588
+ if roles[source[0]["from"]] != roles["human"]:
589
+ source = source[1:]
590
+
591
+ input_id, target = [], []
592
+
593
+ # New version, use apply chat template
594
+ # Build system message for each sentence
595
+ input_id += tokenizer.apply_chat_template([{"role" : "system", "content" : system_message}])
596
+ target += [IGNORE_INDEX] * len(input_id)
597
+
598
+ for conv in source:
599
+ # Make sure llava data can load
600
+ try:
601
+ role = conv["role"]
602
+ content = conv["content"]
603
+ except:
604
+ role = conv["from"]
605
+ content = conv["value"]
606
+
607
+ role = roles.get(role, role)
608
+
609
+ conv = [{"role" : role, "content" : content}]
610
+ encode_id = tokenizer.apply_chat_template(conv)
611
+ input_id += encode_id
612
+ if role in ["user", "system"]:
613
+ target += [IGNORE_INDEX] * len(encode_id)
614
+ else:
615
+ target += encode_id
616
+
617
+
618
+
619
+ assert len(input_id) == len(target), f"{len(input_id)} != {len(target)}"
620
+ for idx, encode_id in enumerate(input_id):
621
+ if encode_id in unmask_tokens_idx:
622
+ target[idx] = encode_id
623
+ if encode_id == image_token_index:
624
+ input_id[idx] = IMAGE_TOKEN_INDEX
625
+ input_ids.append(input_id)
626
+ targets.append(target)
627
+ input_ids = torch.tensor(input_ids, dtype=torch.long)
628
+ targets = torch.tensor(targets, dtype=torch.long)
629
+
630
+ return dict(
631
+ input_ids=input_ids, # tensor(bs x seq_len)
632
+ labels=targets, # tensor(bs x seq_len)
633
+ )
634
+
635
+
636
+ def preprocess_llama3(
637
+ sources,
638
+ tokenizer: transformers.PreTrainedTokenizer,
639
+ has_image: bool = False,
640
+ max_len=2048,
641
+ system_message: str = "You are a helpful language and vision assistant. You are able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language.",
642
+ ) -> Dict:
643
+ # roles = {"human": "<|start_header_id|>user<|end_header_id|>", "gpt": "<|start_header_id|>assistant<|end_header_id|>"}
644
+ roles = {"human": "user", "gpt": "assistant"}
645
+
646
+ # Add image tokens to tokenizer as a special tokens
647
+ # Use a deepcopy of tokenizer so that we don't modify on the tokenizer
648
+ tokenizer = copy.deepcopy(tokenizer)
649
+ # When there is actually an image, we add the image tokens as a special token
650
+ if has_image:
651
+ tokenizer.add_tokens(["<image>"], special_tokens=True)
652
+ image_token_index = tokenizer.convert_tokens_to_ids("<image>")
653
+ bos_token_id = tokenizer.convert_tokens_to_ids("<|begin_of_text|>")
654
+ start_header_id = tokenizer.convert_tokens_to_ids("<|start_header_id|>")
655
+ end_header_id = tokenizer.convert_tokens_to_ids("<|end_header_id|>")
656
+ eot_id = tokenizer.convert_tokens_to_ids("<|eot_id|>")
657
+
658
+ unmask_tokens = ["<|begin_of_text|>", "<|start_header_id|>", "<|end_header_id|>", "<|eot_id|>", "\n\n"]
659
+ unmask_tokens_idx = [tokenizer.convert_tokens_to_ids(tok) for tok in unmask_tokens]
660
+
661
+ # After update, calling tokenizer of llama3 will
662
+ # auto add bos id for the tokens. ヽ(`⌒´)ノ
663
+ def safe_tokenizer_llama3(text):
664
+ input_ids = tokenizer(text).input_ids
665
+ if input_ids[0] == bos_token_id:
666
+ input_ids = input_ids[1:]
667
+ return input_ids
668
+
669
+ nl_tokens = tokenizer.convert_tokens_to_ids("\n\n")
670
+ # Apply prompt templates
671
+ input_ids, targets = [], []
672
+ for i, source in enumerate(sources):
673
+ if roles[source[0]["from"]] != roles["human"]:
674
+ source = source[1:]
675
+
676
+ input_id, target = [], []
677
+
678
+ # New version, use apply chat template
679
+ # Build system message for each sentence
680
+ input_id += tokenizer.apply_chat_template([{"role" : "system", "content" : system_message}])
681
+ target += [IGNORE_INDEX] * len(input_id)
682
+
683
+ for conv in source:
684
+ # Make sure llava data can load
685
+ try:
686
+ role = conv["role"]
687
+ content = conv["content"]
688
+ except:
689
+ role = conv["from"]
690
+ content = conv["value"]
691
+
692
+ role = roles.get(role, role)
693
+
694
+ conv = [{"role" : role, "content" : content}]
695
+ # First is bos token we don't need here
696
+ encode_id = tokenizer.apply_chat_template(conv)[1:]
697
+ input_id += encode_id
698
+ if role in ["user", "system"]:
699
+ target += [IGNORE_INDEX] * len(encode_id)
700
+ else:
701
+ target += encode_id
702
+
703
+
704
+
705
+ assert len(input_id) == len(target), f"{len(input_id)} != {len(target)}"
706
+ for idx, encode_id in enumerate(input_id):
707
+ if encode_id in unmask_tokens_idx:
708
+ target[idx] = encode_id
709
+ if encode_id == image_token_index:
710
+ input_id[idx] = IMAGE_TOKEN_INDEX
711
+ input_ids.append(input_id)
712
+ targets.append(target)
713
+ input_ids = torch.tensor(input_ids, dtype=torch.long)
714
+ targets = torch.tensor(targets, dtype=torch.long)
715
+
716
+ return dict(
717
+ input_ids=input_ids, # tensor(bs x seq_len)
718
+ labels=targets, # tensor(bs x seq_len)
719
+ )
720
+
721
+
722
+ def preprocess_v1(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict:
723
+ conv = conversation_lib.default_conversation.copy()
724
+ roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
725
+
726
+ # Apply prompt templates
727
+ conversations = []
728
+ for i, source in enumerate(sources):
729
+ if roles[source[0]["from"]] != conv.roles[0]:
730
+ # Skip the first one if it is not from human
731
+ source = source[1:]
732
+
733
+ conv.messages = []
734
+ for j, sentence in enumerate(source):
735
+ role = roles[sentence["from"]]
736
+ assert role == conv.roles[j % 2], f"{i}"
737
+ conv.append_message(role, sentence["value"])
738
+ conversations.append(conv.get_prompt())
739
+
740
+ # Tokenize conversations
741
+
742
+ if has_image:
743
+ input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0)
744
+ else:
745
+ input_ids = tokenizer(
746
+ conversations,
747
+ return_tensors="pt",
748
+ padding="longest",
749
+ max_length=tokenizer.model_max_length,
750
+ truncation=True,
751
+ ).input_ids
752
+
753
+ targets = input_ids.clone()
754
+
755
+ assert conv.sep_style == conversation_lib.SeparatorStyle.TWO
756
+
757
+ # Mask targets
758
+ sep = conv.sep + conv.roles[1] + ": "
759
+ for conversation, target in zip(conversations, targets):
760
+ total_len = int(target.ne(tokenizer.pad_token_id).sum())
761
+
762
+ rounds = conversation.split(conv.sep2)
763
+ cur_len = 1
764
+ target[:cur_len] = IGNORE_INDEX
765
+ for i, rou in enumerate(rounds):
766
+ if rou == "":
767
+ break
768
+
769
+ parts = rou.split(sep)
770
+ if len(parts) != 2:
771
+ break
772
+ parts[0] += sep
773
+
774
+ if has_image:
775
+ round_len = len(tokenizer_image_token(rou, tokenizer))
776
+ instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2
777
+ else:
778
+ round_len = len(tokenizer(rou).input_ids)
779
+ instruction_len = len(tokenizer(parts[0]).input_ids) - 2
780
+
781
+ if i != 0 and not tokenizer.legacy and IS_TOKENIZER_GREATER_THAN_0_14:
782
+ round_len -= 1
783
+ instruction_len -= 1
784
+
785
+ target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
786
+
787
+ cur_len += round_len
788
+ target[cur_len:] = IGNORE_INDEX
789
+
790
+ if cur_len < tokenizer.model_max_length:
791
+ if cur_len != total_len:
792
+ target[:] = IGNORE_INDEX
793
+ print(f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)")
794
+
795
+ return dict(
796
+ input_ids=input_ids,
797
+ labels=targets,
798
+ )
799
+
800
+
801
+ def preprocess_mpt(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict:
802
+ conv = conversation_lib.default_conversation.copy()
803
+ roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
804
+
805
+ # Apply prompt templates
806
+ conversations = []
807
+ for i, source in enumerate(sources):
808
+ if roles[source[0]["from"]] != conv.roles[0]:
809
+ # Skip the first one if it is not from human
810
+ source = source[1:]
811
+
812
+ conv.messages = []
813
+ for j, sentence in enumerate(source):
814
+ role = roles[sentence["from"]]
815
+ assert role == conv.roles[j % 2], f"{i}"
816
+ conv.append_message(role, sentence["value"])
817
+ conversations.append(conv.get_prompt())
818
+
819
+ # Tokenize conversations
820
+
821
+ if has_image:
822
+ input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0)
823
+ else:
824
+ input_ids = tokenizer(
825
+ conversations,
826
+ return_tensors="pt",
827
+ padding="longest",
828
+ max_length=tokenizer.model_max_length,
829
+ truncation=True,
830
+ ).input_ids
831
+
832
+ targets = input_ids.clone()
833
+ assert conv.sep_style == conversation_lib.SeparatorStyle.MPT
834
+
835
+ # Mask targets
836
+ sep = conv.sep + conv.roles[1]
837
+ for conversation, target in zip(conversations, targets):
838
+ total_len = int(target.ne(tokenizer.pad_token_id).sum())
839
+
840
+ rounds = conversation.split(conv.sep)
841
+ re_rounds = [conv.sep.join(rounds[:3])] # system + user + gpt
842
+ for conv_idx in range(3, len(rounds), 2):
843
+ re_rounds.append(conv.sep.join(rounds[conv_idx : conv_idx + 2])) # user + gpt
844
+ cur_len = 1
845
+ target[:cur_len] = IGNORE_INDEX
846
+ for i, rou in enumerate(re_rounds):
847
+ if rou == "":
848
+ break
849
+
850
+ parts = rou.split(sep)
851
+ if len(parts) != 2:
852
+ break
853
+ parts[0] += sep
854
+
855
+ if has_image:
856
+ round_len = len(tokenizer_image_token(rou, tokenizer))
857
+ instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 1
858
+ else:
859
+ round_len = len(tokenizer(rou).input_ids)
860
+ instruction_len = len(tokenizer(parts[0]).input_ids) - 1
861
+
862
+ if i != 0 and getattr(tokenizer, "legacy", False) and IS_TOKENIZER_GREATER_THAN_0_14:
863
+ round_len += 1
864
+ instruction_len += 1
865
+
866
+ target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
867
+
868
+ cur_len += round_len
869
+ target[cur_len:] = IGNORE_INDEX
870
+
871
+ if cur_len < tokenizer.model_max_length:
872
+ if cur_len != total_len:
873
+ target[:] = IGNORE_INDEX
874
+ print(f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f"(#turns={len(re_rounds)} ignored)")
875
+
876
+ return dict(
877
+ input_ids=input_ids,
878
+ labels=targets,
879
+ )
880
+
881
+
882
+ def preprocess_plain(
883
+ sources: Sequence[str],
884
+ tokenizer: transformers.PreTrainedTokenizer,
885
+ ) -> Dict:
886
+ # add end signal and concatenate together
887
+ conversations = []
888
+ for source in sources:
889
+ assert len(source) == 2
890
+ assert DEFAULT_IMAGE_TOKEN in source[0]["value"]
891
+ source[0]["value"] = DEFAULT_IMAGE_TOKEN
892
+ conversation = source[0]["value"] + source[1]["value"] + conversation_lib.default_conversation.sep
893
+ conversations.append(conversation)
894
+ # tokenize conversations
895
+ input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations]
896
+ targets = copy.deepcopy(input_ids)
897
+ for target, source in zip(targets, sources):
898
+ tokenized_len = len(tokenizer_image_token(source[0]["value"], tokenizer))
899
+ target[:tokenized_len] = IGNORE_INDEX
900
+
901
+ return dict(input_ids=input_ids, labels=targets)
902
+
903
+
904
+ def preprocess(sources: Sequence[str], tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict:
905
+ """
906
+ Given a list of sources, each is a conversation list. This transform:
907
+ 1. Add signal '### ' at the beginning each sentence, with end signal '\n';
908
+ 2. Concatenate conversations together;
909
+ 3. Tokenize the concatenated conversation;
910
+ 4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX.
911
+ """
912
+ if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.PLAIN:
913
+ return preprocess_plain(sources, tokenizer)
914
+ if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.LLAMA_2:
915
+ return preprocess_llama_2(sources, tokenizer, has_image=has_image)
916
+ if conversation_lib.default_conversation.version.startswith("v1"):
917
+ return preprocess_v1(sources, tokenizer, has_image=has_image)
918
+ if conversation_lib.default_conversation.version == "mpt":
919
+ return preprocess_mpt(sources, tokenizer, has_image=has_image)
920
+ if conversation_lib.default_conversation.version == "qwen":
921
+ return preprocess_qwen(sources, tokenizer, has_image=has_image)
922
+ if conversation_lib.default_conversation.version == "gemma":
923
+ return preprocess_gemma(sources, tokenizer, has_image=has_image)
924
+ if conversation_lib.default_conversation.version == "llama_v3":
925
+ return preprocess_llama3(sources, tokenizer, has_image=has_image)
926
+ # add end signal and concatenate together
927
+ conversations = []
928
+ for source in sources:
929
+ header = f"{conversation_lib.default_conversation.system}\n\n"
930
+ conversation = _add_speaker_and_signal(header, source)
931
+ conversations.append(conversation)
932
+
933
+ # tokenize conversations
934
+ def get_tokenize_len(prompts):
935
+ return [len(tokenizer_image_token(prompt, tokenizer)) for prompt in prompts]
936
+
937
+ if has_image:
938
+ input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations]
939
+ else:
940
+ conversations_tokenized = _tokenize_fn(conversations, tokenizer)
941
+ input_ids = conversations_tokenized["input_ids"]
942
+
943
+ targets = copy.deepcopy(input_ids)
944
+ for target, source in zip(targets, sources):
945
+ if has_image:
946
+ tokenized_lens = get_tokenize_len([header] + [s["value"] for s in source])
947
+ else:
948
+ tokenized_lens = _tokenize_fn([header] + [s["value"] for s in source], tokenizer)["input_ids_lens"]
949
+ speakers = [sentence["from"] for sentence in source]
950
+ _mask_targets(target, tokenized_lens, speakers)
951
+
952
+ return dict(input_ids=input_ids, labels=targets)
953
+
954
+
955
+ class LazySupervisedDataset(Dataset):
956
+ def __init__(self, data_path: str, tokenizer: transformers.PreTrainedTokenizer, data_args: DataArguments):
957
+ super(LazySupervisedDataset, self).__init__()
958
+ self.tokenizer = tokenizer
959
+ self.list_data_dict = []
960
+
961
+ # Handle multiple JSON files specified in the data_path
962
+ if "{" in data_path and "}" in data_path:
963
+ base_path, file_pattern = re.match(r"^(.*)\{(.*)\}\.json$", data_path).groups()
964
+ file_names = file_pattern.split(",")
965
+ rank0_print(f"Loading {file_names} from {base_path}")
966
+ data_args.dataset_paths = []
967
+ for file_name in file_names:
968
+ data_args.dataset_paths.append(f"{base_path}{file_name}.json")
969
+ full_path = f"{base_path}{file_name}.json"
970
+ rank0_print(f"Loading {full_path}")
971
+ with open(full_path, "r") as file:
972
+ cur_data_dict = json.load(file)
973
+ rank0_print(f"Loaded {len(cur_data_dict)} samples from {full_path}")
974
+ self.list_data_dict.extend(cur_data_dict)
975
+ elif data_path.endswith(".yaml"):
976
+ with open(data_path, "r") as file:
977
+ yaml_data = yaml.safe_load(file)
978
+ datasets = yaml_data.get("datasets")
979
+ # file should be in the format of:
980
+ # datasets:
981
+ # - json_path: xxxx1.json
982
+ # sampling_strategy: first:1000
983
+ # - json_path: xxxx2.json
984
+ # sampling_strategy: end:3000
985
+ # - json_path: xxxx3.json
986
+ # sampling_strategy: random:999
987
+ data_args.dataset_paths = [dataset.get("json_path") for dataset in datasets]
988
+ for dataset in datasets:
989
+ json_path = dataset.get("json_path")
990
+ sampling_strategy = dataset.get("sampling_strategy", "all")
991
+ sampling_number = None
992
+
993
+ rank0_print(f"Loading {json_path} with {sampling_strategy} sampling strategy")
994
+
995
+ if json_path.endswith(".jsonl"):
996
+ cur_data_dict = []
997
+ with open(json_path, "r") as json_file:
998
+ for line in json_file:
999
+ cur_data_dict.append(json.loads(line.strip()))
1000
+ elif json_path.endswith(".json"):
1001
+ with open(json_path, "r") as json_file:
1002
+ cur_data_dict = json.load(json_file)
1003
+ else:
1004
+ raise ValueError(f"Unsupported file type: {json_path}")
1005
+
1006
+ if ":" in sampling_strategy:
1007
+ sampling_strategy, sampling_number = sampling_strategy.split(":")
1008
+ if "%" in sampling_number:
1009
+ sampling_number = math.ceil(int(sampling_number.split("%")[0]) * len(cur_data_dict) / 100)
1010
+ else:
1011
+ sampling_number = int(sampling_number)
1012
+
1013
+ # Apply the sampling strategy
1014
+ if sampling_strategy == "first" and sampling_number is not None:
1015
+ cur_data_dict = cur_data_dict[:sampling_number]
1016
+ elif sampling_strategy == "end" and sampling_number is not None:
1017
+ cur_data_dict = cur_data_dict[-sampling_number:]
1018
+ elif sampling_strategy == "random" and sampling_number is not None:
1019
+ random.shuffle(cur_data_dict)
1020
+ cur_data_dict = cur_data_dict[:sampling_number]
1021
+
1022
+ rank0_print(f"Loaded {len(cur_data_dict)} samples from {json_path}")
1023
+ self.list_data_dict.extend(cur_data_dict)
1024
+ else:
1025
+ data_args.dataset_paths = [data_path]
1026
+ rank0_print(f"Loading {data_path}")
1027
+ with open(data_path, "r") as file:
1028
+ cur_data_dict = json.load(file)
1029
+ rank0_print(f"Loaded {len(cur_data_dict)} samples from {data_path}")
1030
+ self.list_data_dict.extend(cur_data_dict)
1031
+
1032
+ rank0_print(f"Loaded {len(self.list_data_dict)} samples from {data_path}")
1033
+ rank0_print("Formatting inputs...Skip in lazy mode")
1034
+ self.tokenizer = tokenizer
1035
+ self.data_args = data_args
1036
+
1037
+ def __len__(self):
1038
+ return len(self.list_data_dict)
1039
+
1040
+ @property
1041
+ def lengths(self):
1042
+ length_list = []
1043
+ for sample in self.list_data_dict:
1044
+ img_tokens = 128 if "image" in sample else 0
1045
+ length_list.append(sum(len(conv["value"].split()) for conv in sample["conversations"]) + img_tokens)
1046
+ return length_list
1047
+
1048
+ @property
1049
+ def modality_lengths(self):
1050
+ length_list = []
1051
+ for sample in self.list_data_dict:
1052
+ cur_len = sum(len(conv["value"].split()) for conv in sample["conversations"])
1053
+ assert cur_len > 0, f"Conversation length is 0 for {sample}"
1054
+ if "image" in sample or "video" in sample or self.data_args.early_mix_text:
1055
+ length_list.append(cur_len)
1056
+ else:
1057
+ length_list.append(-cur_len)
1058
+ return length_list
1059
+
1060
+ def process_image(self, image_file, overwrite_image_aspect_ratio=None):
1061
+ image_folder = self.data_args.image_folder
1062
+ processor = self.data_args.image_processor
1063
+ # print(f"\n\nInspecting the image path, folder = {image_folder}, image={image_file}\n\n")
1064
+ try:
1065
+ image = Image.open(os.path.join(image_folder, image_file)).convert("RGB")
1066
+ except Exception as exn:
1067
+ print(f"Failed to open image {image_file}. Exception:", exn)
1068
+ raise exn
1069
+
1070
+ image_size = image.size
1071
+ image_aspect_ratio = self.data_args.image_aspect_ratio
1072
+ if overwrite_image_aspect_ratio is not None:
1073
+ image_aspect_ratio = overwrite_image_aspect_ratio
1074
+ if image_aspect_ratio == "highres":
1075
+ image = process_highres_image(image, self.data_args.image_processor, self.data_args.image_grid_pinpoints)
1076
+ elif image_aspect_ratio == "anyres" or "anyres_max" in image_aspect_ratio:
1077
+ image = process_anyres_image(image, self.data_args.image_processor, self.data_args.image_grid_pinpoints)
1078
+ elif image_aspect_ratio == "crop_split":
1079
+ image = process_highres_image_crop_split(image, self.data_args)
1080
+ elif image_aspect_ratio == "pad":
1081
+
1082
+ def expand2square(pil_img, background_color):
1083
+ width, height = pil_img.size
1084
+ if width == height:
1085
+ return pil_img
1086
+ elif width > height:
1087
+ result = Image.new(pil_img.mode, (width, width), background_color)
1088
+ result.paste(pil_img, (0, (width - height) // 2))
1089
+ return result
1090
+ else:
1091
+ result = Image.new(pil_img.mode, (height, height), background_color)
1092
+ result.paste(pil_img, ((height - width) // 2, 0))
1093
+ return result
1094
+
1095
+ image = expand2square(image, tuple(int(x * 255) for x in processor.image_mean))
1096
+ image = processor.preprocess(image, return_tensors="pt")["pixel_values"][0]
1097
+ else:
1098
+ image = processor.preprocess(image, return_tensors="pt")["pixel_values"][0]
1099
+ return image, image_size, "image"
1100
+
1101
+ def __getitem__(self, i) -> Dict[str, torch.Tensor]:
1102
+ # TODO: define number of retries somewhere else
1103
+ num_base_retries = 3
1104
+ num_final_retries = 300
1105
+
1106
+ # try the current sample first
1107
+ for attempt_idx in range(num_base_retries):
1108
+ try:
1109
+ sample = self._get_item(i)
1110
+ return sample
1111
+ except Exception as e:
1112
+ # sleep 1s in case it is a cloud disk issue
1113
+ print(f"[Try #{attempt_idx}] Failed to fetch sample {i}. Exception:", e)
1114
+ time.sleep(1)
1115
+
1116
+ # try other samples, in case it is file corruption issue
1117
+ for attempt_idx in range(num_base_retries):
1118
+ try:
1119
+ next_index = min(i + 1, len(self.list_data_dict) - 1)
1120
+ # sample_idx = random.choice(range(len(self)))
1121
+ sample = self._get_item(next_index)
1122
+ return sample
1123
+ except Exception as e:
1124
+ # no need to sleep
1125
+ print(f"[Try other #{attempt_idx}] Failed to fetch sample {next_index}. Exception:", e)
1126
+ pass
1127
+
1128
+ try:
1129
+ sample = self._get_item(i)
1130
+ return sample
1131
+ except Exception as e:
1132
+ raise e
1133
+
1134
+ def _get_item(self, i) -> Dict[str, torch.Tensor]:
1135
+ sources = self.list_data_dict[i]
1136
+ if isinstance(i, int):
1137
+ sources = [sources]
1138
+ assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME
1139
+
1140
+ if "image" in sources[0]:
1141
+ image_file = self.list_data_dict[i]["image"]
1142
+ if type(image_file) is list:
1143
+ image = [self.process_image(f) for f in image_file]
1144
+ # Handling multi images
1145
+ # overwrite to process with simple pad
1146
+ if len(image_file) > 1:
1147
+ image = [self.process_image(f, "pad") for f in image_file]
1148
+ image = [[im[0], im[1], "image"] for im in image]
1149
+ else:
1150
+ image = [self.process_image(image_file)]
1151
+ sources = preprocess_multimodal(copy.deepcopy([e["conversations"] for e in sources]), self.data_args)
1152
+
1153
+ elif "video" in sources[0]:
1154
+ video_file = self.list_data_dict[i]["video"]
1155
+ video_folder = self.data_args.video_folder
1156
+ video_file = os.path.join(video_folder, video_file)
1157
+ suffix = video_file.split(".")[-1]
1158
+ if not os.path.exists(video_file):
1159
+ print("File {} not exist!".format(video_file))
1160
+
1161
+ try:
1162
+ if "shareVideoGPTV" in video_file:
1163
+ frame_files = [os.path.join(video_file, f) for f in os.listdir(video_file) if os.path.isfile(os.path.join(video_file, f))]
1164
+ frame_files.sort() # Ensure the frames are sorted if they are named sequentially
1165
+
1166
+ # TODO: Hard CODE: Determine the indices for uniformly sampling 10 frames
1167
+ if self.data_args.force_sample:
1168
+ num_frames_to_sample = self.data_args.frames_upbound
1169
+ else:
1170
+ num_frames_to_sample = 10
1171
+
1172
+ avg_fps = 2
1173
+
1174
+ total_frames = len(frame_files)
1175
+ sampled_indices = np.linspace(0, total_frames - 1, num_frames_to_sample, dtype=int)
1176
+
1177
+
1178
+ frame_time = [i/2 for i in sampled_indices]
1179
+ frame_time = ",".join([f"{i:.2f}s" for i in frame_time])
1180
+
1181
+ video_time = total_frames / avg_fps
1182
+
1183
+ # Read and store the sampled frames
1184
+ video = []
1185
+ for idx in sampled_indices:
1186
+ frame_path = frame_files[idx]
1187
+ try:
1188
+ with Image.open(frame_path) as img:
1189
+ frame = img.convert("RGB")
1190
+ video.append(frame)
1191
+ except IOError:
1192
+ print(f"Failed to read frame at path: {frame_path}")
1193
+ else:
1194
+ video, video_time, frame_time, num_frames_to_sample = process_video_with_decord(video_file, self.data_args)
1195
+
1196
+ processor = self.data_args.image_processor
1197
+ image = processor.preprocess(video, return_tensors="pt")["pixel_values"]
1198
+ if self.data_args.add_time_instruction:
1199
+ time_instruciton = f"The video lasts for {video_time:.2f} seconds, and {num_frames_to_sample} frames are uniformly sampled from it. These frames are located at {frame_time}.Please answer the following questions related to this video."
1200
+ sources[0]["conversations"][0]["value"] = f'{DEFAULT_IMAGE_TOKEN}\n{time_instruciton}\n{sources[0]["conversations"][0]["value"].replace(DEFAULT_IMAGE_TOKEN, "")}'
1201
+ image = [(image, video[0].size, "video")]
1202
+ sources = preprocess_multimodal(copy.deepcopy([e["conversations"] for e in sources]), self.data_args)
1203
+ # print(sources)
1204
+ except Exception as e:
1205
+ print(f"Error: {e}")
1206
+ print(f"Failed to read video file: {video_file}")
1207
+ return self._get_item(i + 1)
1208
+ else:
1209
+ sources = copy.deepcopy([e["conversations"] for e in sources])
1210
+
1211
+ has_image = ("image" in self.list_data_dict[i]) or ("video" in self.list_data_dict[i])
1212
+ data_dict = preprocess(sources, self.tokenizer, has_image=has_image)
1213
+
1214
+ if "prompt" in data_dict:
1215
+ prompt = data_dict["prompt"]
1216
+ else:
1217
+ prompt = None
1218
+
1219
+ if isinstance(i, int):
1220
+ data_dict = dict(input_ids=data_dict["input_ids"][0], labels=data_dict["labels"][0])
1221
+
1222
+ # image exist in the data
1223
+ if "image" in self.list_data_dict[i]:
1224
+ data_dict["image"] = image
1225
+ elif "video" in self.list_data_dict[i]:
1226
+ data_dict["image"] = image
1227
+ elif self.data_args.is_multimodal:
1228
+ # image does not exist in the data, but the model is multimodal
1229
+ crop_size = self.data_args.image_processor.crop_size
1230
+ data_dict["image"] = [
1231
+ (torch.zeros(1, 3, crop_size["height"], crop_size["width"]), (crop_size["width"], crop_size["height"]), "text"),
1232
+ ]
1233
+ # prompt exist in the data
1234
+ if prompt is not None:
1235
+ data_dict["prompt"] = prompt
1236
+
1237
+ data_dict["id"] = self.list_data_dict[i].get("id", i)
1238
+
1239
+ return data_dict
1240
+
1241
+
1242
+ @dataclass
1243
+ class DataCollatorForSupervisedDataset(object):
1244
+ """Collate examples for supervised fine-tuning."""
1245
+
1246
+ tokenizer: transformers.PreTrainedTokenizer
1247
+
1248
+ def pad_sequence(self, input_ids, batch_first, padding_value):
1249
+ if self.tokenizer.padding_side == "left":
1250
+ input_ids = [torch.flip(_input_ids, [0]) for _input_ids in input_ids]
1251
+ input_ids = torch.nn.utils.rnn.pad_sequence(input_ids, batch_first=batch_first, padding_value=padding_value)
1252
+ if self.tokenizer.padding_side == "left":
1253
+ input_ids = torch.flip(input_ids, [1])
1254
+ return input_ids
1255
+
1256
+ def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]:
1257
+ input_ids, labels = tuple([instance[key] for instance in instances] for key in ("input_ids", "labels"))
1258
+ # input_ids, labels, ids = tuple([instance[key] for instance in instances] for key in ("input_ids", "labels", "id"))
1259
+ input_ids = [_input_ids[: self.tokenizer.model_max_length] for _input_ids in input_ids]
1260
+ labels = [_labels[: self.tokenizer.model_max_length] for _labels in labels]
1261
+ if self.tokenizer.pad_token_id is None:
1262
+ # self.tokenizer.pad_token_id = self.tokenizer.eos_token_id # FIXME: this could only be triggered for llama3 model.
1263
+ self.tokenizer.pad_token_id = 0 # This gets the best result. Don't know why.
1264
+ input_ids = self.pad_sequence(input_ids, batch_first=True, padding_value=self.tokenizer.pad_token_id)
1265
+ labels = self.pad_sequence(labels, batch_first=True, padding_value=IGNORE_INDEX)
1266
+ batch = dict(input_ids=input_ids, labels=labels.long() if labels.dtype == torch.int32 else labels, attention_mask=input_ids.ne(self.tokenizer.pad_token_id))
1267
+ # batch = dict(input_ids=input_ids, labels=labels, attention_mask=input_ids.ne(self.tokenizer.pad_token_id), ids=ids)
1268
+
1269
+ if "image" in instances[0]:
1270
+ images = [instance["image"] for instance in instances]
1271
+
1272
+ batch["image_sizes"] = [im[1] for im_list in images for im in im_list]
1273
+ batch["modalities"] = [im[2] for im_list in images for im in im_list]
1274
+ images = [im[0] for im_list in images for im in im_list]
1275
+
1276
+ # if all(x is not None and x.shape == images[0].shape for x in images):
1277
+ # Image: (N, P, C, H, W)
1278
+ # Video: (N, F, C, H, W)
1279
+ # batch["images"] = torch.stack(images)
1280
+ # else:
1281
+ batch["images"] = images
1282
+
1283
+ if "prompt" in instances[0]:
1284
+ batch["prompts"] = [instance["prompt"] for instance in instances]
1285
+
1286
+ return batch
1287
+
1288
+
1289
+ def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer, data_args) -> Dict:
1290
+ """Make dataset and collator for supervised fine-tuning."""
1291
+ train_dataset = LazySupervisedDataset(tokenizer=tokenizer, data_path=data_args.data_path, data_args=data_args)
1292
+ data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer)
1293
+ return dict(train_dataset=train_dataset, eval_dataset=None, data_collator=data_collator)
1294
+
1295
+
1296
+ def get_model(model_args, training_args, bnb_model_from_pretrained_args):
1297
+ assert training_args.attn_implementation
1298
+ if training_args.attn_implementation == "sdpa" and torch.__version__ < "2.1.2":
1299
+ raise ValueError("The 'sdpa' attention implementation requires torch version 2.1.2 or higher.")
1300
+
1301
+ customized_kwargs = dict()
1302
+ customized_kwargs.update(bnb_model_from_pretrained_args)
1303
+ cfg_pretrained = None
1304
+
1305
+ overwrite_config = {}
1306
+ if any(
1307
+ [
1308
+ model_args.rope_scaling_factor is not None,
1309
+ model_args.rope_scaling_type is not None,
1310
+ model_args.mm_spatial_pool_stride is not None,
1311
+ model_args.mm_spatial_pool_out_channels is not None,
1312
+ model_args.mm_spatial_pool_mode is not None,
1313
+ model_args.mm_resampler_type is not None,
1314
+ ]
1315
+ ):
1316
+ cfg_pretrained = AutoConfig.from_pretrained(model_args.model_name_or_path)
1317
+
1318
+ if model_args.use_pos_skipping is not None and model_args.pos_skipping_range is not None:
1319
+ overwrite_config["use_pos_skipping"] = model_args.use_pos_skipping
1320
+ overwrite_config["pos_skipping_range"] = model_args.pos_skipping_range
1321
+
1322
+ if model_args.rope_scaling_factor is not None and model_args.rope_scaling_type is not None:
1323
+ overwrite_config["rope_scaling"] = {
1324
+ "factor": model_args.rope_scaling_factor,
1325
+ "type": model_args.rope_scaling_type,
1326
+ }
1327
+ if training_args.model_max_length is None:
1328
+ training_args.model_max_length = cfg_pretrained.max_position_embeddings * model_args.rope_scaling_factor
1329
+ overwrite_config["max_sequence_length"] = training_args.model_max_length
1330
+ assert training_args.model_max_length == int(cfg_pretrained.max_position_embeddings * model_args.rope_scaling_factor), print(
1331
+ f"model_max_length: {training_args.model_max_length}, max_position_embeddings: {cfg_pretrained.max_position_embeddings}, rope_scaling_factor: {model_args.rope_scaling_factor}"
1332
+ )
1333
+ # overwrite_config["max_sequence_length"] = model_args.max_sequence_length
1334
+ # overwrite_config["tokenizer_model_max_length"] = model_args.tokenizer_model_max_length
1335
+
1336
+ if model_args.mm_spatial_pool_stride is not None and model_args.mm_spatial_pool_out_channels is not None and model_args.mm_spatial_pool_mode is not None and model_args.mm_resampler_type is not None:
1337
+ overwrite_config["mm_resampler_type"] = model_args.mm_resampler_type
1338
+ overwrite_config["mm_spatial_pool_stride"] = model_args.mm_spatial_pool_stride
1339
+ overwrite_config["mm_spatial_pool_out_channels"] = model_args.mm_spatial_pool_out_channels
1340
+ overwrite_config["mm_spatial_pool_mode"] = model_args.mm_spatial_pool_mode
1341
+
1342
+ if model_args.mm_spatial_pool_mode is not None:
1343
+ overwrite_config["mm_spatial_pool_mode"] = model_args.mm_spatial_pool_mode
1344
+
1345
+ if overwrite_config:
1346
+ assert cfg_pretrained is not None, "cfg_pretrained is None"
1347
+
1348
+ rank0_print(f"Overwriting config with {overwrite_config}")
1349
+ for k, v in overwrite_config.items():
1350
+ setattr(cfg_pretrained, k, v)
1351
+
1352
+ customized_kwargs["config"] = cfg_pretrained
1353
+
1354
+ if model_args.model_class_name is not None:
1355
+ actual_model_class_name = f"{model_args.model_class_name}ForCausalLM"
1356
+ model_class = getattr(transformers, actual_model_class_name)
1357
+ rank0_print(f"Using model class {model_class} from {model_args.model_class_name}")
1358
+ model = model_class.from_pretrained(
1359
+ model_args.model_name_or_path,
1360
+ cache_dir=training_args.cache_dir,
1361
+ attn_implementation=training_args.attn_implementation,
1362
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1363
+ low_cpu_mem_usage=False,
1364
+ **customized_kwargs,
1365
+ )
1366
+ elif model_args.vision_tower is not None:
1367
+ if "mixtral" in model_args.model_name_or_path.lower():
1368
+ model = LlavaMixtralForCausalLM.from_pretrained(
1369
+ model_args.model_name_or_path,
1370
+ cache_dir=training_args.cache_dir,
1371
+ attn_implementation=training_args.attn_implementation,
1372
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1373
+ low_cpu_mem_usage=False,
1374
+ **customized_kwargs,
1375
+ )
1376
+ from transformers.models.mixtral.modeling_mixtral import MixtralSparseMoeBlock
1377
+
1378
+ deepspeed.utils.set_z3_leaf_modules(model, [MixtralSparseMoeBlock])
1379
+ elif "mistral" in model_args.model_name_or_path.lower() or "zephyr" in model_args.model_name_or_path.lower():
1380
+ model = LlavaMistralForCausalLM.from_pretrained(
1381
+ model_args.model_name_or_path,
1382
+ cache_dir=training_args.cache_dir,
1383
+ attn_implementation=training_args.attn_implementation,
1384
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1385
+ low_cpu_mem_usage=False,
1386
+ **customized_kwargs,
1387
+ )
1388
+ elif (
1389
+ "wizardlm-2" in model_args.model_name_or_path.lower()
1390
+ or "vicuna" in model_args.model_name_or_path.lower()
1391
+ or "llama" in model_args.model_name_or_path.lower()
1392
+ or "yi" in model_args.model_name_or_path.lower()
1393
+ or "nous-hermes" in model_args.model_name_or_path.lower()
1394
+ and "wizard-2" in model_args.model_name_or_path.lower()
1395
+ ):
1396
+ model = LlavaLlamaForCausalLM.from_pretrained(
1397
+ model_args.model_name_or_path,
1398
+ cache_dir=training_args.cache_dir,
1399
+ attn_implementation=training_args.attn_implementation,
1400
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1401
+ low_cpu_mem_usage=False,
1402
+ **customized_kwargs,
1403
+ )
1404
+ elif "qwen" in model_args.model_name_or_path.lower():
1405
+ if "moe" in model_args.model_name_or_path.lower() or "A14B" in model_args.model_name_or_path:
1406
+ model = LlavaQwenMoeForCausalLM.from_pretrained(
1407
+ model_args.model_name_or_path,
1408
+ cache_dir=training_args.cache_dir,
1409
+ attn_implementation=training_args.attn_implementation,
1410
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1411
+ low_cpu_mem_usage=False,
1412
+ **customized_kwargs,
1413
+ )
1414
+ from transformers.models.qwen2_moe.modeling_qwen2_moe import Qwen2MoeSparseMoeBlock
1415
+
1416
+ deepspeed.utils.set_z3_leaf_modules(model, [Qwen2MoeSparseMoeBlock])
1417
+ else:
1418
+ model = LlavaQwenForCausalLM.from_pretrained(
1419
+ model_args.model_name_or_path,
1420
+ cache_dir=training_args.cache_dir,
1421
+ attn_implementation=training_args.attn_implementation,
1422
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1423
+ low_cpu_mem_usage=False,
1424
+ **customized_kwargs,
1425
+ )
1426
+ elif "gemma" in model_args.model_name_or_path.lower():
1427
+ model = LlavaGemmaForCausalLM.from_pretrained(
1428
+ model_args.model_name_or_path,
1429
+ cache_dir=training_args.cache_dir,
1430
+ attn_implementation=training_args.attn_implementation,
1431
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1432
+ low_cpu_mem_usage=False,
1433
+ **customized_kwargs,
1434
+ )
1435
+ else:
1436
+ raise ValueError(f"Unknown model class {model_args}")
1437
+ else:
1438
+ model = transformers.LlamaForCausalLM.from_pretrained(
1439
+ model_args.model_name_or_path,
1440
+ cache_dir=training_args.cache_dir,
1441
+ attn_implementation=training_args.attn_implementation,
1442
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1443
+ low_cpu_mem_usage=False,
1444
+ **customized_kwargs,
1445
+ )
1446
+ return model
1447
+
1448
+
1449
+ def train(attn_implementation=None):
1450
+ global local_rank
1451
+
1452
+ parser = transformers.HfArgumentParser((ModelArguments, DataArguments, TrainingArguments))
1453
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
1454
+
1455
+ if training_args.verbose_logging:
1456
+ rank0_print(f"Inspecting experiment hyperparameters:\n")
1457
+ rank0_print(f"model_args = {vars(model_args)}\n\n")
1458
+ rank0_print(f"data_args = {vars(data_args)}\n\n")
1459
+ rank0_print(f"training_args = {vars(training_args)}\n\n")
1460
+ # rank0_print(f"evaluation_args = {vars(evaluation_args)}\n\n")
1461
+
1462
+ local_rank = training_args.local_rank
1463
+ compute_dtype = torch.float16 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)
1464
+
1465
+ bnb_model_from_pretrained_args = {}
1466
+ if training_args.bits in [4, 8]:
1467
+ from transformers import BitsAndBytesConfig
1468
+
1469
+ bnb_model_from_pretrained_args.update(
1470
+ dict(
1471
+ device_map={"": training_args.device},
1472
+ load_in_4bit=training_args.bits == 4,
1473
+ load_in_8bit=training_args.bits == 8,
1474
+ quantization_config=BitsAndBytesConfig(
1475
+ load_in_4bit=training_args.bits == 4,
1476
+ load_in_8bit=training_args.bits == 8,
1477
+ llm_int8_threshold=6.0,
1478
+ llm_int8_has_fp16_weight=False,
1479
+ bnb_4bit_compute_dtype=compute_dtype,
1480
+ bnb_4bit_use_double_quant=training_args.double_quant,
1481
+ bnb_4bit_quant_type=training_args.quant_type, # {'fp4', 'nf4'}
1482
+ ),
1483
+ )
1484
+ )
1485
+
1486
+ model = get_model(model_args, training_args, bnb_model_from_pretrained_args)
1487
+ model.config.use_cache = False
1488
+ if model_args.rope_scaling_factor is not None and model_args.rope_scaling_type is not None:
1489
+ model.config.rope_scaling = {
1490
+ "factor": model_args.rope_scaling_factor,
1491
+ "type": model_args.rope_scaling_type,
1492
+ }
1493
+
1494
+ if model_args.freeze_backbone:
1495
+ model.model.requires_grad_(False)
1496
+
1497
+ if training_args.bits in [4, 8]:
1498
+ from peft import prepare_model_for_kbit_training
1499
+
1500
+ model.config.torch_dtype = torch.float32 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)
1501
+ model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=training_args.gradient_checkpointing)
1502
+
1503
+ if training_args.gradient_checkpointing:
1504
+ if hasattr(model, "enable_input_require_grads"):
1505
+ model.enable_input_require_grads()
1506
+ else:
1507
+
1508
+ def make_inputs_require_grad(module, input, output):
1509
+ output.requires_grad_(True)
1510
+
1511
+ model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
1512
+
1513
+ if training_args.lora_enable:
1514
+ from peft import LoraConfig, get_peft_model
1515
+
1516
+ lora_config = LoraConfig(
1517
+ r=training_args.lora_r,
1518
+ lora_alpha=training_args.lora_alpha,
1519
+ target_modules=find_all_linear_names(model),
1520
+ lora_dropout=training_args.lora_dropout,
1521
+ bias=training_args.lora_bias,
1522
+ task_type="CAUSAL_LM",
1523
+ )
1524
+ if training_args.bits == 16:
1525
+ if training_args.bf16:
1526
+ model.to(torch.bfloat16)
1527
+ if training_args.fp16:
1528
+ model.to(torch.float16)
1529
+ rank0_print("Adding LoRA adapters...")
1530
+ model = get_peft_model(model, lora_config)
1531
+
1532
+ if "mistral" in model_args.model_name_or_path.lower() or "mixtral" in model_args.model_name_or_path.lower() or "zephyr" in model_args.model_name_or_path.lower():
1533
+ tokenizer = transformers.AutoTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=training_args.cache_dir, model_max_length=training_args.model_max_length, padding_side="left")
1534
+ elif "qwen" in model_args.model_name_or_path.lower():
1535
+ tokenizer = transformers.AutoTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=training_args.cache_dir, model_max_length=training_args.model_max_length, padding_side="right")
1536
+ elif (
1537
+ "wizardlm-2" in model_args.model_name_or_path.lower()
1538
+ or "vicuna" in model_args.model_name_or_path.lower()
1539
+ or "llama" in model_args.model_name_or_path.lower()
1540
+ or "yi" in model_args.model_name_or_path.lower()
1541
+ or "nous-hermes" in model_args.model_name_or_path.lower()
1542
+ and "wizard-2" in model_args.model_name_or_path.lower()
1543
+ ):
1544
+ tokenizer = transformers.AutoTokenizer.from_pretrained(
1545
+ model_args.model_name_or_path,
1546
+ cache_dir=training_args.cache_dir,
1547
+ model_max_length=training_args.model_max_length,
1548
+ padding_side="right",
1549
+ use_fast=False,
1550
+ )
1551
+
1552
+ rank0_print(f"Prompt version: {model_args.version}")
1553
+ if model_args.version == "v0":
1554
+ if tokenizer.pad_token is None:
1555
+ smart_tokenizer_and_embedding_resize(
1556
+ special_tokens_dict=dict(pad_token="[PAD]"),
1557
+ tokenizer=tokenizer,
1558
+ model=model,
1559
+ )
1560
+ elif model_args.version == "v0.5":
1561
+ tokenizer.pad_token = tokenizer.unk_token
1562
+ else:
1563
+ if tokenizer.unk_token is not None:
1564
+ tokenizer.pad_token = tokenizer.unk_token
1565
+ if model_args.version in conversation_lib.conv_templates:
1566
+ conversation_lib.default_conversation = conversation_lib.conv_templates[model_args.version]
1567
+ else:
1568
+ conversation_lib.default_conversation = conversation_lib.conv_templates["vicuna_v1"]
1569
+
1570
+ if model_args.vision_tower is not None:
1571
+ model.get_model().initialize_vision_modules(model_args=model_args, fsdp=training_args.fsdp)
1572
+
1573
+ vision_tower = model.get_vision_tower()
1574
+ vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device)
1575
+
1576
+ data_args.image_processor = vision_tower.image_processor
1577
+ data_args.is_multimodal = True
1578
+
1579
+ model.config.image_aspect_ratio = data_args.image_aspect_ratio
1580
+ if data_args.image_grid_pinpoints is not None:
1581
+ if isinstance(data_args.image_grid_pinpoints, str) and "x" in data_args.image_grid_pinpoints:
1582
+ try:
1583
+ patch_size = data_args.image_processor.size[0]
1584
+ except Exception as e:
1585
+ patch_size = data_args.image_processor.size["shortest_edge"]
1586
+
1587
+ assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
1588
+ # Use regex to extract the range from the input string
1589
+ matches = re.findall(r"\((\d+)x(\d+)\)", data_args.image_grid_pinpoints)
1590
+ range_start = tuple(map(int, matches[0]))
1591
+ range_end = tuple(map(int, matches[-1]))
1592
+ # Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
1593
+ grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
1594
+ # Multiply all elements by patch_size
1595
+ data_args.image_grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
1596
+ elif isinstance(data_args.image_grid_pinpoints, str):
1597
+ data_args.image_grid_pinpoints = ast.literal_eval(data_args.image_grid_pinpoints)
1598
+
1599
+ model.config.image_grid_pinpoints = data_args.image_grid_pinpoints
1600
+ model.config.image_crop_resolution = data_args.image_crop_resolution
1601
+ model.config.image_split_resolution = data_args.image_split_resolution
1602
+ model.config.tokenizer_padding_side = tokenizer.padding_side
1603
+ model.config.tokenizer_model_max_length = tokenizer.model_max_length
1604
+ model.config.mm_newline_position = model_args.mm_newline_position
1605
+ model.config.add_faster_video = model_args.add_faster_video
1606
+ model.config.faster_token_stride = model_args.faster_token_stride
1607
+ model.config.add_time_instruction = data_args.add_time_instruction
1608
+ model.config.force_sample = data_args.force_sample
1609
+ model.config.mm_spatial_pool_stride = model_args.mm_spatial_pool_stride
1610
+
1611
+ ### Deciding train which part of the model
1612
+ if model_args.mm_tunable_parts is None: # traditional way of deciding which part to train
1613
+ model.config.tune_mm_mlp_adapter = training_args.tune_mm_mlp_adapter = model_args.tune_mm_mlp_adapter
1614
+ model.config.tune_mm_vision_resampler = training_args.tune_mm_vision_resampler = model_args.tune_mm_vision_resampler
1615
+ if model_args.tune_mm_mlp_adapter or model_args.tune_mm_vision_resampler:
1616
+ model.requires_grad_(False)
1617
+ if model_args.tune_mm_mlp_adapter:
1618
+ for p in model.get_model().mm_projector.parameters():
1619
+ p.requires_grad = True
1620
+ if model_args.tune_mm_vision_resampler:
1621
+ for p in model.get_model().vision_resampler.parameters():
1622
+ p.requires_grad = True
1623
+
1624
+ model.config.freeze_mm_mlp_adapter = training_args.freeze_mm_mlp_adapter
1625
+ if training_args.freeze_mm_mlp_adapter:
1626
+ for p in model.get_model().mm_projector.parameters():
1627
+ p.requires_grad = False
1628
+
1629
+ model.config.freeze_mm_vision_resampler = training_args.freeze_mm_vision_resampler
1630
+ if training_args.freeze_mm_vision_resampler:
1631
+ for p in model.get_model().vision_resampler.parameters():
1632
+ p.requires_grad = False
1633
+
1634
+ model.config.unfreeze_mm_vision_tower = model_args.unfreeze_mm_vision_tower
1635
+ if model_args.unfreeze_mm_vision_tower:
1636
+ vision_tower.requires_grad_(True)
1637
+ else:
1638
+ vision_tower.requires_grad_(False)
1639
+
1640
+ else:
1641
+ rank0_print(f"Using mm_tunable_parts: {model_args.mm_tunable_parts}")
1642
+ model.config.mm_tunable_parts = training_args.mm_tunable_parts = model_args.mm_tunable_parts
1643
+ # Set the entire model to not require gradients by default
1644
+ model.requires_grad_(False)
1645
+ vision_tower.requires_grad_(False)
1646
+ model.get_model().mm_projector.requires_grad_(False)
1647
+ model.get_model().vision_resampler.requires_grad_(False)
1648
+ # Parse the mm_tunable_parts to decide which parts to unfreeze
1649
+ tunable_parts = model_args.mm_tunable_parts.split(",")
1650
+ if "mm_mlp_adapter" in tunable_parts:
1651
+ for p in model.get_model().mm_projector.parameters():
1652
+ p.requires_grad = True
1653
+ if "mm_vision_resampler" in tunable_parts:
1654
+ for p in model.get_model().vision_resampler.parameters():
1655
+ p.requires_grad = True
1656
+ if "mm_vision_tower" in tunable_parts:
1657
+ for name, param in model.named_parameters():
1658
+ if "vision_tower" in name:
1659
+ param.requires_grad_(True)
1660
+ if "mm_language_model" in tunable_parts:
1661
+ for name, param in model.named_parameters():
1662
+ if "vision_tower" not in name and "mm_projector" not in name and "vision_resampler" not in name:
1663
+ param.requires_grad_(True)
1664
+
1665
+ total_params = sum(p.ds_numel if hasattr(p, "ds_numel") else p.numel() for p in model.parameters())
1666
+ trainable_params = sum(p.ds_numel if hasattr(p, "ds_numel") else p.numel() for p in model.parameters() if p.requires_grad)
1667
+ rank0_print(f"Total parameters: ~{total_params/1e6:.2f} MB)")
1668
+ rank0_print(f"Trainable parameters: ~{trainable_params/1e6:.2f} MB)")
1669
+ if training_args.bits in [4, 8]:
1670
+ model.get_model().mm_projector.to(dtype=compute_dtype, device=training_args.device)
1671
+
1672
+ model.config.mm_use_im_start_end = data_args.mm_use_im_start_end = model_args.mm_use_im_start_end
1673
+ model.config.mm_projector_lr = training_args.mm_projector_lr
1674
+ model.config.mm_vision_tower_lr = training_args.mm_vision_tower_lr
1675
+ training_args.use_im_start_end = model_args.mm_use_im_start_end
1676
+ model.config.mm_use_im_patch_token = model_args.mm_use_im_patch_token
1677
+ model.initialize_vision_tokenizer(model_args, tokenizer=tokenizer)
1678
+
1679
+ if training_args.bits in [4, 8]:
1680
+ from peft.tuners.lora import LoraLayer
1681
+
1682
+ for name, module in model.named_modules():
1683
+ if isinstance(module, LoraLayer):
1684
+ if training_args.bf16:
1685
+ module = module.to(torch.bfloat16)
1686
+ if "norm" in name:
1687
+ module = module.to(torch.float32)
1688
+ if "lm_head" in name or "embed_tokens" in name:
1689
+ if hasattr(module, "weight"):
1690
+ if training_args.bf16 and module.weight.dtype == torch.float32:
1691
+ module = module.to(torch.bfloat16)
1692
+
1693
+ data_module = make_supervised_data_module(tokenizer=tokenizer, data_args=data_args)
1694
+ trainer = LLaVATrainer(model=model, tokenizer=tokenizer, args=training_args, **data_module)
1695
+
1696
+ if list(pathlib.Path(training_args.output_dir).glob("checkpoint-*")):
1697
+ trainer.train(resume_from_checkpoint=True)
1698
+ else:
1699
+ trainer.train()
1700
+ trainer.save_state()
1701
+
1702
+ model.config.use_cache = True
1703
+
1704
+ if training_args.lora_enable:
1705
+ state_dict = get_peft_state_maybe_zero_3(model.named_parameters(), training_args.lora_bias)
1706
+ non_lora_state_dict = get_peft_state_non_lora_maybe_zero_3(model.named_parameters())
1707
+ if training_args.local_rank == 0 or training_args.local_rank == -1:
1708
+ if hasattr(model, "config"):
1709
+ model.config.save_pretrained(training_args.output_dir)
1710
+ if hasattr(model, "generation_config"):
1711
+ model.generation_config.save_pretrained(training_args.output_dir)
1712
+ model.save_pretrained(training_args.output_dir, state_dict=state_dict)
1713
+ torch.save(non_lora_state_dict, os.path.join(training_args.output_dir, "non_lora_trainables.bin"))
1714
+ else:
1715
+ safe_save_model_for_hf_trainer(trainer=trainer, output_dir=training_args.output_dir)
1716
+
1717
+ rank0_print(f"Model saved to {training_args.output_dir}")
1718
+
1719
+
1720
+ if __name__ == "__main__":
1721
+ train()
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/train/train_dpo.py ADDED
@@ -0,0 +1,1782 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright:
2
+ # Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright:
3
+ # Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import os
18
+ import copy
19
+ import deepspeed
20
+ from dataclasses import dataclass, field
21
+ import json
22
+ import logging
23
+ import pathlib
24
+ from typing import Dict, Optional, Sequence, List
25
+ import ast
26
+
27
+ import yaml
28
+ import time
29
+ import random
30
+ import yaml
31
+ import math
32
+ import re
33
+ import torch
34
+
35
+ import transformers
36
+ import tokenizers
37
+
38
+ from llava.constants import IGNORE_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, IMAGE_TOKEN_INDEX
39
+ from torch.utils.data import Dataset
40
+ from llava.train.llava_trainer import LLaVADPOTrainer
41
+ from data_processing.utils import load_jsonl, load_json
42
+ from llava import conversation as conversation_lib
43
+ from llava.model import *
44
+ from llava.model.language_model.llava_qwen import LlavaQwenConfig
45
+ from llava.model.language_model.llava_llama import LlavaConfig
46
+ from llava.model.language_model.llava_mistral import LlavaMistralConfig
47
+ from llava.mm_utils import process_highres_image, process_anyres_image, process_highres_image_crop_split, tokenizer_image_token
48
+ from llava.utils import rank0_print
49
+ from transformers import AutoConfig
50
+ import pickle
51
+
52
+ from trl.trainer.utils import DPODataCollatorWithPadding
53
+ from PIL import Image, ImageFile
54
+ from decord import VideoReader, cpu
55
+
56
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
57
+ from packaging import version
58
+ from typing import Any
59
+
60
+ local_rank = None
61
+ import numpy as np
62
+
63
+ IS_TOKENIZER_GREATER_THAN_0_14 = version.parse(tokenizers.__version__) >= version.parse("0.14")
64
+
65
+
66
+ @dataclass
67
+ class ModelArguments:
68
+ model_name_or_path: Optional[str] = field(default="facebook/opt-125m")
69
+ model_class_name: Optional[str] = field(default=None, metadata={"help": "Used to init model class, format is XXXXForCausalLM. e.g. currently XXXX is chosen from LlavaLlama, LlavaMixtral, LlavaMistral, Llama"})
70
+
71
+ mm_tunable_parts: Optional[str] = field(
72
+ default=None, metadata={"help": 'Could be "mm_mlp_adapter", "mm_vision_resampler", "mm_vision_tower,mm_mlp_adapter,mm_language_model", "mm_vision_tower,mm_mlp_adapter,mm_language_model", "mm_mlp_adapter,mm_language_model"'}
73
+ )
74
+ # deciding which part of the multimodal model to tune, will overwrite other previous settings
75
+
76
+ version: Optional[str] = field(default="v0")
77
+ freeze_backbone: bool = field(default=False)
78
+ tune_mm_mlp_adapter: bool = field(default=False)
79
+ tune_mm_vision_resampler: bool = field(default=False)
80
+ vision_tower: Optional[str] = field(default=None)
81
+ vision_tower_pretrained: Optional[str] = field(default=None) # default to the last layer
82
+
83
+ unfreeze_mm_vision_tower: bool = field(default=False)
84
+ unfreeze_language_model: bool = field(default=False)
85
+ mm_vision_select_layer: Optional[int] = field(default=-1) # default to the last layer
86
+ pretrain_mm_mlp_adapter: Optional[str] = field(default=None)
87
+ mm_projector_type: Optional[str] = field(default="linear")
88
+ mm_use_im_start_end: bool = field(default=False)
89
+ mm_use_im_patch_token: bool = field(default=True)
90
+ mm_patch_merge_type: Optional[str] = field(default="flat")
91
+ mm_vision_select_feature: Optional[str] = field(default="patch")
92
+ mm_resampler_type: Optional[str] = field(default=None)
93
+ mm_mask_drop_mode: str = field(default="fixed")
94
+ mm_mask_drop_skip_percentage: float = field(default=0.0)
95
+ mm_mask_drop_ratio: float = field(default=0.25)
96
+ mm_mask_drop_ratio_upper: Optional[float] = field(default=None)
97
+ mm_mask_drop_ratio_lower: Optional[float] = field(default=None)
98
+ mm_spatial_pool_stride: Optional[int] = field(default=None)
99
+ mm_spatial_pool_mode: str = field(default="average")
100
+ mm_spatial_pool_out_channels: Optional[int] = field(default=None)
101
+ mm_perceiver_depth: Optional[int] = field(default=3)
102
+ mm_perceiver_latents: Optional[int] = field(default=32)
103
+ mm_perceiver_ff_mult: Optional[float] = field(default=4)
104
+ mm_perceiver_pretrained: Optional[str] = field(default=None)
105
+ mm_qformer_depth: Optional[int] = field(default=3)
106
+ mm_qformer_latents: Optional[int] = field(default=32)
107
+ mm_qformer_pretrained: Optional[str] = field(default=None)
108
+
109
+ rope_scaling_factor: Optional[float] = field(default=None)
110
+ rope_scaling_type: Optional[str] = field(default=None)
111
+
112
+ s2: Optional[bool] = field(default=False)
113
+ s2_scales: Optional[str] = field(default="336,672,1008")
114
+
115
+
116
+ @dataclass
117
+ class DataArguments:
118
+ data_path: str = field(default=None, metadata={"help": "Path to the training data, in llava's instruction.json format. Supporting multiple json files via /path/to/{a,b,c}.json"})
119
+ lazy_preprocess: bool = False
120
+ is_multimodal: bool = False
121
+ image_folder: Optional[str] = field(default=None)
122
+ video_folder: Optional[str] = field(default=None)
123
+ video_fps: Optional[int] = field(default=1)
124
+ image_aspect_ratio: str = "square"
125
+ image_grid_pinpoints: Optional[str] = field(default=None)
126
+ image_crop_resolution: int = 384
127
+ image_split_resolution: int = 384
128
+ input_prompt: Optional[str] = field(default=None)
129
+ refine_prompt: Optional[bool] = field(default=False)
130
+ frames_upbound: Optional[int] = field(default=0)
131
+ num_sample: Optional[int] = field(default=None)
132
+
133
+
134
+ @dataclass
135
+ class TrainingArguments(transformers.TrainingArguments):
136
+ cache_dir: Optional[str] = field(default=None)
137
+ optim: str = field(default="adamw_torch")
138
+ remove_unused_columns: bool = field(default=False)
139
+ freeze_mm_mlp_adapter: bool = field(default=False)
140
+ freeze_mm_vision_resampler: bool = field(default=False)
141
+ mpt_attn_impl: Optional[str] = field(default="triton")
142
+ model_max_length: int = field(
143
+ default=4096,
144
+ metadata={"help": "Maximum sequence length. Sequences will be right padded (and possibly truncated)."},
145
+ )
146
+ double_quant: bool = field(default=True, metadata={"help": "Compress the quantization statistics through double quantization."})
147
+ quant_type: str = field(default="nf4", metadata={"help": "Quantization data type to use. Should be one of `fp4` or `nf4`."})
148
+ bits: int = field(default=16, metadata={"help": "How many bits to use."})
149
+ lora_enable: bool = False
150
+ lora_r: int = 64
151
+ lora_alpha: int = 16
152
+ lora_dropout: float = 0.05
153
+ lora_weight_path: str = ""
154
+ lora_bias: str = "none"
155
+ mm_projector_lr: Optional[float] = None
156
+ mm_vision_tower_lr: Optional[float] = None
157
+ group_by_varlen: bool = field(default=False)
158
+ group_by_modality_length: bool = field(default=False)
159
+ group_by_modality_length_auto: bool = field(default=False)
160
+ auto_find_batch_size: bool = field(default=False)
161
+ gradient_checkpointing: bool = field(default=True)
162
+ verbose_logging: bool = field(default=False)
163
+ attn_implementation: str = field(default="flash_attention_2", metadata={"help": "Use transformers attention implementation."})
164
+ dpo_alpha: float = field(default=1.0)
165
+ beta: float = field(default=0.1)
166
+ gamma: float = field(default=1.0)
167
+ generate_during_eval: bool = field(default=False)
168
+ precompute_ref_log_probs: bool = field(default=False)
169
+
170
+
171
+ def maybe_zero_3(param, ignore_status=False, name=None):
172
+ from deepspeed import zero
173
+ from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
174
+
175
+ if hasattr(param, "ds_id"):
176
+ if param.ds_status == ZeroParamStatus.NOT_AVAILABLE:
177
+ if not ignore_status:
178
+ logging.warning(f"{name}: param.ds_status != ZeroParamStatus.NOT_AVAILABLE: {param.ds_status}")
179
+ with zero.GatheredParameters([param]):
180
+ param = param.data.detach().cpu().clone()
181
+ else:
182
+ param = param.detach().cpu().clone()
183
+ return param
184
+
185
+
186
+ # Borrowed from peft.utils.get_peft_model_state_dict
187
+ def get_peft_state_maybe_zero_3(named_params, bias):
188
+ if bias == "none":
189
+ to_return = {k: t for k, t in named_params if "lora_" in k}
190
+ elif bias == "all":
191
+ to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k}
192
+ elif bias == "lora_only":
193
+ to_return = {}
194
+ maybe_lora_bias = {}
195
+ lora_bias_names = set()
196
+ for k, t in named_params:
197
+ if "lora_" in k:
198
+ to_return[k] = t
199
+ bias_name = k.split("lora_")[0] + "bias"
200
+ lora_bias_names.add(bias_name)
201
+ elif "bias" in k:
202
+ maybe_lora_bias[k] = t
203
+ for k, t in maybe_lora_bias:
204
+ if bias_name in lora_bias_names:
205
+ to_return[bias_name] = t
206
+ else:
207
+ raise NotImplementedError
208
+ to_return = {k: maybe_zero_3(v, ignore_status=True) for k, v in to_return.items()}
209
+ return to_return
210
+
211
+
212
+ def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True):
213
+ to_return = {k: t for k, t in named_params if "lora_" not in k}
214
+ if require_grad_only:
215
+ to_return = {k: t for k, t in to_return.items() if t.requires_grad}
216
+ to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()}
217
+ return to_return
218
+
219
+
220
+ def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match):
221
+ to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)}
222
+ to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()}
223
+ return to_return
224
+
225
+
226
+ def find_all_linear_names(model):
227
+ cls = torch.nn.Linear
228
+ lora_module_names = set()
229
+ multimodal_keywords = ["mm_projector", "vision_tower", "vision_resampler"]
230
+ for name, module in model.named_modules():
231
+ if any(mm_keyword in name for mm_keyword in multimodal_keywords):
232
+ continue
233
+ if isinstance(module, cls):
234
+ names = name.split(".")
235
+ lora_module_names.add(names[0] if len(names) == 1 else names[-1])
236
+
237
+ if "lm_head" in lora_module_names: # needed for 16-bit
238
+ lora_module_names.remove("lm_head")
239
+ return list(lora_module_names)
240
+
241
+
242
+ def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str):
243
+ """Collects the state dict and dump to disk."""
244
+ if hasattr(trainer.args, "tune_mm_mlp_adapter") and trainer.args.tune_mm_mlp_adapter:
245
+ check_only_save_mm_adapter_tunnable = True
246
+ # only has mm_mlp_adapter and mm_vision_resampler in the tuneable parts
247
+ elif hasattr(trainer.args, "mm_tunable_parts") and (len(trainer.args.mm_tunable_parts.split(",")) == 1 and ("mm_mlp_adapter" in trainer.args.mm_tunable_parts or "mm_vision_resampler" in trainer.args.mm_tunable_parts)):
248
+ check_only_save_mm_adapter_tunnable = True
249
+ else:
250
+ check_only_save_mm_adapter_tunnable = False
251
+
252
+ trainer.accelerator.wait_for_everyone()
253
+ torch.cuda.synchronize()
254
+ rank0_print(f"Only save projectors: {check_only_save_mm_adapter_tunnable}")
255
+ if check_only_save_mm_adapter_tunnable:
256
+ # Only save Adapter
257
+ keys_to_match = ["mm_projector", "vision_resampler"]
258
+ if getattr(trainer.args, "use_im_start_end", False):
259
+ keys_to_match.extend(["embed_tokens", "embed_in"])
260
+
261
+ weight_to_save = get_mm_adapter_state_maybe_zero_3(trainer.model.named_parameters(), keys_to_match)
262
+ trainer.model.config.save_pretrained(output_dir)
263
+
264
+ current_folder = output_dir.split("/")[-1]
265
+ parent_folder = os.path.dirname(output_dir)
266
+ if trainer.args.local_rank == 0 or trainer.args.local_rank == -1:
267
+ if current_folder.startswith("checkpoint-"):
268
+ mm_projector_folder = os.path.join(parent_folder, "mm_projector")
269
+ os.makedirs(mm_projector_folder, exist_ok=True)
270
+ torch.save(weight_to_save, os.path.join(mm_projector_folder, f"{current_folder}.bin"))
271
+ else:
272
+ torch.save(weight_to_save, os.path.join(output_dir, f"mm_projector.bin"))
273
+ return
274
+
275
+ if trainer.deepspeed:
276
+ trainer.save_model(output_dir)
277
+ return
278
+
279
+ state_dict = trainer.model.state_dict()
280
+ if trainer.args.should_save:
281
+ cpu_state_dict = {key: value.cpu() for key, value in state_dict.items()}
282
+ del state_dict
283
+ trainer._save(output_dir, state_dict=cpu_state_dict) # noqa
284
+
285
+
286
+ def smart_tokenizer_and_embedding_resize(
287
+ special_tokens_dict: Dict,
288
+ tokenizer: transformers.PreTrainedTokenizer,
289
+ model: transformers.PreTrainedModel,
290
+ ):
291
+ """Resize tokenizer and embedding.
292
+
293
+ Note: This is the unoptimized version that may make your embedding size not be divisible by 64.
294
+ """
295
+ num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict)
296
+ model.resize_token_embeddings(len(tokenizer))
297
+
298
+ if num_new_tokens > 0:
299
+ input_embeddings = model.get_input_embeddings().weight.data
300
+ output_embeddings = model.get_output_embeddings().weight.data
301
+
302
+ input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
303
+ output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
304
+
305
+ input_embeddings[-num_new_tokens:] = input_embeddings_avg
306
+ output_embeddings[-num_new_tokens:] = output_embeddings_avg
307
+
308
+
309
+ def _tokenize_fn(strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict:
310
+ """Tokenize a list of strings."""
311
+ tokenized_list = [
312
+ tokenizer(
313
+ text,
314
+ return_tensors="pt",
315
+ padding="longest",
316
+ max_length=tokenizer.model_max_length,
317
+ truncation=True,
318
+ )
319
+ for text in strings
320
+ ]
321
+ input_ids = labels = [tokenized.input_ids[0] for tokenized in tokenized_list]
322
+ input_ids_lens = labels_lens = [tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() for tokenized in tokenized_list]
323
+ return dict(
324
+ input_ids=input_ids,
325
+ labels=labels,
326
+ input_ids_lens=input_ids_lens,
327
+ labels_lens=labels_lens,
328
+ )
329
+
330
+
331
+ def _mask_targets(target, tokenized_lens, speakers):
332
+ # cur_idx = 0
333
+ cur_idx = tokenized_lens[0]
334
+ tokenized_lens = tokenized_lens[1:]
335
+ target[:cur_idx] = IGNORE_INDEX
336
+ for tokenized_len, speaker in zip(tokenized_lens, speakers):
337
+ if speaker == "human":
338
+ target[cur_idx + 2 : cur_idx + tokenized_len] = IGNORE_INDEX
339
+ cur_idx += tokenized_len
340
+
341
+
342
+ def _add_speaker_and_signal(header, source, get_conversation=True):
343
+ """Add speaker and start/end signal on each round."""
344
+ BEGIN_SIGNAL = "### "
345
+ END_SIGNAL = "\n"
346
+ conversation = header
347
+ for sentence in source:
348
+ from_str = sentence["from"]
349
+ if from_str.lower() == "human":
350
+ from_str = conversation_lib.default_conversation.roles[0]
351
+ elif from_str.lower() == "gpt":
352
+ from_str = conversation_lib.default_conversation.roles[1]
353
+ else:
354
+ from_str = "unknown"
355
+ sentence["value"] = BEGIN_SIGNAL + from_str + ": " + sentence["value"] + END_SIGNAL
356
+ if get_conversation:
357
+ conversation += sentence["value"]
358
+ conversation += BEGIN_SIGNAL
359
+ return conversation
360
+
361
+
362
+ def preprocess_multimodal(sources: Sequence[str], data_args: DataArguments) -> Dict:
363
+ is_multimodal = data_args.is_multimodal
364
+ if not is_multimodal:
365
+ return sources
366
+
367
+ for source in sources:
368
+ for sentence in source:
369
+ if DEFAULT_IMAGE_TOKEN in sentence["value"] and not sentence["value"].startswith(DEFAULT_IMAGE_TOKEN):
370
+ sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, "").strip()
371
+ sentence["value"] = DEFAULT_IMAGE_TOKEN + "\n" + sentence["value"]
372
+ sentence["value"] = sentence["value"].strip()
373
+ if "mmtag" in conversation_lib.default_conversation.version:
374
+ sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, "<Image>" + DEFAULT_IMAGE_TOKEN + "</Image>")
375
+ replace_token = DEFAULT_IMAGE_TOKEN
376
+ if data_args.mm_use_im_start_end:
377
+ replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
378
+ sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token)
379
+
380
+ return sources
381
+
382
+
383
+ def preprocess_multimodal_movie(sources: Sequence[str], data_args: DataArguments, video_inputs: str) -> Dict:
384
+ is_multimodal = data_args.is_multimodal
385
+ if not is_multimodal:
386
+ return sources
387
+
388
+ for source in sources:
389
+ for sentence in source:
390
+ if DEFAULT_IMAGE_TOKEN in sentence["value"]:
391
+ prompt = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, "").strip()
392
+ replace_token = video_inputs
393
+ if data_args.mm_use_im_start_end:
394
+ replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
395
+ sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token)
396
+
397
+ return sources, prompt
398
+
399
+
400
+ def preprocess_llama_2(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict:
401
+ conv = conversation_lib.default_conversation.copy()
402
+ roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
403
+
404
+ # Apply prompt templates
405
+ conversations = []
406
+ for i, source in enumerate(sources):
407
+ if roles[source[0]["from"]] != conv.roles[0]:
408
+ # Skip the first one if it is not from human
409
+ source = source[1:]
410
+
411
+ conv.messages = []
412
+ for j, sentence in enumerate(source):
413
+ role = roles[sentence["from"]]
414
+ assert role == conv.roles[j % 2], f"{i}"
415
+ conv.append_message(role, sentence["value"])
416
+ conversations.append(conv.get_prompt())
417
+
418
+ # Tokenize conversations
419
+
420
+ if has_image:
421
+ input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0)
422
+ else:
423
+ input_ids = tokenizer(
424
+ conversations,
425
+ return_tensors="pt",
426
+ padding="longest",
427
+ max_length=tokenizer.model_max_length,
428
+ truncation=True,
429
+ ).input_ids
430
+
431
+ targets = input_ids.clone()
432
+
433
+ assert conv.sep_style == conversation_lib.SeparatorStyle.LLAMA_2
434
+
435
+ # Mask targets
436
+ sep = "[/INST] "
437
+ for conversation, target in zip(conversations, targets):
438
+ total_len = int(target.ne(tokenizer.pad_token_id).sum())
439
+
440
+ rounds = conversation.split(conv.sep2)
441
+ cur_len = 1
442
+ target[:cur_len] = IGNORE_INDEX
443
+ for i, rou in enumerate(rounds):
444
+ if rou == "":
445
+ break
446
+
447
+ parts = rou.split(sep)
448
+ if len(parts) != 2:
449
+ break
450
+ parts[0] += sep
451
+
452
+ if has_image:
453
+ round_len = len(tokenizer_image_token(rou, tokenizer))
454
+ instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2
455
+ else:
456
+ round_len = len(tokenizer(rou).input_ids)
457
+ instruction_len = len(tokenizer(parts[0]).input_ids) - 2
458
+
459
+ target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
460
+
461
+ cur_len += round_len
462
+ target[cur_len:] = IGNORE_INDEX
463
+
464
+ if cur_len < tokenizer.model_max_length:
465
+ if cur_len != total_len:
466
+ target[:] = IGNORE_INDEX
467
+ rank0_print(f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)")
468
+
469
+ return dict(
470
+ input_ids=input_ids,
471
+ labels=targets,
472
+ )
473
+
474
+
475
+ def make_conv(prompt, answer):
476
+ return [
477
+ {
478
+ "from": "human",
479
+ "value": prompt,
480
+ },
481
+ {
482
+ "from": "gpt",
483
+ "value": answer,
484
+ },
485
+ ]
486
+
487
+
488
+ def preprocess_gemma(sources: List[List[Dict[str, str]]], tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict:
489
+ conv: conversation_lib.Conversation = conversation_lib.default_conversation.copy()
490
+ roles: Dict[str, str] = {"human": conv.roles[0], "gpt": conv.roles[1]}
491
+
492
+ # Apply prompt templates
493
+ conversations: List[str] = []
494
+ for i, source in enumerate(sources):
495
+ if roles[source[0]["from"]] != conv.roles[0]:
496
+ # Skip the first one if it is not from human
497
+ source: List[Dict[str, str]] = source[1:]
498
+
499
+ conv.messages = []
500
+ for j, sentence in enumerate(source):
501
+ role: str = roles[sentence["from"]]
502
+ assert role == conv.roles[j % 2], f"{i}"
503
+ conv.append_message(role, sentence["value"])
504
+ conversations.append(conv.get_prompt())
505
+
506
+ # Tokenize conversations
507
+ if has_image:
508
+ input_ids: torch.Tensor = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0)
509
+ else:
510
+ input_ids: torch.Tensor = tokenizer(
511
+ conversations,
512
+ return_tensors="pt",
513
+ padding="longest",
514
+ max_length=tokenizer.model_max_length,
515
+ truncation=True,
516
+ ).input_ids
517
+
518
+ targets: torch.Tensor = input_ids.clone()
519
+ assert conv.sep_style == conversation_lib.SeparatorStyle.GEMMA
520
+
521
+ # Mask target
522
+ sep: str = conv.sep + conv.roles[1]
523
+ for conversation, target in zip(conversations, targets):
524
+ total_len: int = int(target.ne(tokenizer.pad_token_id).sum())
525
+
526
+ rounds: List[str] = conversation.split(conv.sep)
527
+ re_rounds = []
528
+ for conv_idx in range(0, len(rounds), 2):
529
+ re_rounds.append(conv.sep.join(rounds[conv_idx : conv_idx + 2]))
530
+
531
+ cur_len = 1 # Ignore <bos>
532
+ target[:cur_len] = IGNORE_INDEX
533
+ for i, rou in enumerate(re_rounds):
534
+ if rou == "":
535
+ break
536
+
537
+ parts = rou.split(sep)
538
+ if len(parts) != 2:
539
+ break
540
+ parts[0] += sep # Re-append sep because split on this
541
+ # Now "".join(parts)==rou
542
+
543
+ if has_image:
544
+ round_len = len(tokenizer_image_token(rou, tokenizer)) - 1 # Ignore <bos>
545
+ instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 1 # Ignore <bos>
546
+ else:
547
+ round_len = len(tokenizer(rou).input_ids) - 1 # Ignore <bos>
548
+ instruction_len = len(tokenizer(parts[0]).input_ids) - 1 # Ignore <bos>
549
+
550
+ round_len += 2 # sep: <end_of_turn>\n takes 2 tokens
551
+ target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
552
+ cur_len += round_len
553
+
554
+ target[cur_len:] = IGNORE_INDEX
555
+
556
+ if cur_len < tokenizer.model_max_length:
557
+ if cur_len != total_len:
558
+ target[:] = IGNORE_INDEX
559
+ rank0_print(f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)")
560
+
561
+ return dict(
562
+ input_ids=input_ids,
563
+ labels=targets,
564
+ )
565
+
566
+
567
+ def preprocess_qwen(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False, max_len=2048, system_message: str = "You are a helpful assistant.") -> Dict:
568
+ roles = {"human": "<|im_start|>user", "gpt": "<|im_start|>assistant"}
569
+
570
+ im_start, im_end = tokenizer.additional_special_tokens_ids
571
+ nl_tokens = tokenizer("\n").input_ids
572
+ _system = tokenizer("system").input_ids + nl_tokens
573
+ _user = tokenizer("user").input_ids + nl_tokens
574
+ _assistant = tokenizer("assistant").input_ids + nl_tokens
575
+
576
+ # Apply prompt templates
577
+ input_ids, targets = [], []
578
+ for i, source in enumerate(sources):
579
+ if roles[source[0]["from"]] != roles["human"]:
580
+ source = source[1:]
581
+
582
+ input_id, target = [], []
583
+ system = [im_start] + _system + tokenizer(system_message).input_ids + [im_end] + nl_tokens
584
+ input_id += system
585
+ target += [im_start] + [IGNORE_INDEX] * (len(system) - 3) + [im_end] + nl_tokens
586
+ assert len(input_id) == len(target)
587
+ for j, sentence in enumerate(source):
588
+ role = roles[sentence["from"]]
589
+ if has_image and "<image>" in sentence["value"]:
590
+ assert sentence["value"].startswith("<image>"), print(sentence["value"])
591
+
592
+ _input_id = tokenizer(role).input_ids + nl_tokens + [IMAGE_TOKEN_INDEX] + nl_tokens + tokenizer(sentence["value"][len("<image>") :]).input_ids + [im_end] + nl_tokens
593
+ else:
594
+ _input_id = tokenizer(role).input_ids + nl_tokens + tokenizer(sentence["value"]).input_ids + [im_end] + nl_tokens
595
+ input_id += _input_id
596
+ if role == "<|im_start|>user":
597
+ _target = [im_start] + [IGNORE_INDEX] * (len(_input_id) - 3) + [im_end] + nl_tokens
598
+ elif role == "<|im_start|>assistant":
599
+ _target = [im_start] + [IGNORE_INDEX] * len(tokenizer(role).input_ids) + _input_id[len(tokenizer(role).input_ids) + 1 : -2] + [im_end] + nl_tokens
600
+ else:
601
+ raise NotImplementedError
602
+ target += _target
603
+ assert len(input_id) == len(target)
604
+ # input_id += [tokenizer.pad_token_id] * (max_len - len(input_id))
605
+ # target += [IGNORE_INDEX] * (max_len - len(target))
606
+ input_ids.append(input_id)
607
+ targets.append(target)
608
+ input_ids = torch.tensor(input_ids, dtype=torch.long)
609
+ targets = torch.tensor(targets, dtype=torch.long)
610
+
611
+ return dict(
612
+ input_ids=input_ids, # tensor(bs x seq_len)
613
+ labels=targets, # tensor(bs x seq_len)
614
+ # attention_mask=input_ids.ne(tokenizer.pad_token_id), # tensor(bs x seq_len)
615
+ )
616
+
617
+
618
+ def preprocess_llama3(
619
+ sources,
620
+ tokenizer: transformers.PreTrainedTokenizer,
621
+ has_image: bool = False,
622
+ max_len=2048,
623
+ system_message: str = "You are a helpful language and vision assistant. You are able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language.",
624
+ ) -> Dict:
625
+ roles = {"human": "<|start_header_id|>user<|end_header_id|>", "gpt": "<|start_header_id|>assistant<|end_header_id|>"}
626
+
627
+ eot_id = tokenizer.convert_tokens_to_ids("<|eot_id|>")
628
+ nl_tokens = tokenizer("\n").input_ids
629
+
630
+ # Apply prompt templates
631
+ input_ids, targets = [], []
632
+ for i, source in enumerate(sources):
633
+ if roles[source[0]["from"]] != roles["human"]:
634
+ source = source[1:]
635
+
636
+ input_id, target = [], []
637
+ system = tokenizer("<|begin_of_text|>").input_ids + tokenizer("<|start_header_id|>system<|end_header_id|>").input_ids + nl_tokens * 2 + tokenizer(system_message).input_ids + [eot_id]
638
+ input_id += system
639
+ target += [IGNORE_INDEX] * len(system)
640
+ for j, sentence in enumerate(source):
641
+ role = roles[sentence["from"]]
642
+ if has_image and "<image>" in sentence["value"]:
643
+ assert sentence["value"].startswith("<image>"), print(sentence["value"])
644
+ _input_id = tokenizer(role).input_ids + nl_tokens * 2 + [IMAGE_TOKEN_INDEX] + tokenizer(sentence["value"][len("<image>") :]).input_ids + [eot_id]
645
+ else:
646
+ _input_id = tokenizer(role).input_ids + nl_tokens * 2 + tokenizer(sentence["value"]).input_ids + [eot_id]
647
+ input_id += _input_id
648
+ if role == "<|start_header_id|>user<|end_header_id|>":
649
+ _target = [IGNORE_INDEX] * len(_input_id)
650
+ elif role == "<|start_header_id|>assistant<|end_header_id|>":
651
+ _target = [IGNORE_INDEX] * (len(tokenizer(role).input_ids) + 2) + _input_id[len(tokenizer(role).input_ids) + 2 : -1] + [eot_id]
652
+ else:
653
+ raise NotImplementedError
654
+ target += _target
655
+ assert len(input_id) == len(target), f"{len(input_id)} != {len(target)}"
656
+ input_ids.append(input_id)
657
+ targets.append(target)
658
+ input_ids = torch.tensor(input_ids, dtype=torch.long)
659
+ targets = torch.tensor(targets, dtype=torch.long)
660
+
661
+ return dict(
662
+ input_ids=input_ids, # tensor(bs x seq_len)
663
+ labels=targets, # tensor(bs x seq_len)
664
+ )
665
+
666
+
667
+ def preprocess_v1(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict:
668
+ conv = conversation_lib.default_conversation.copy()
669
+ roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
670
+
671
+ # Apply prompt templates
672
+ conversations = []
673
+ for i, source in enumerate(sources):
674
+ if roles[source[0]["from"]] != conv.roles[0]:
675
+ # Skip the first one if it is not from human
676
+ source = source[1:]
677
+
678
+ conv.messages = []
679
+ for j, sentence in enumerate(source):
680
+ role = roles[sentence["from"]]
681
+ assert role == conv.roles[j % 2], f"{i}"
682
+ conv.append_message(role, sentence["value"])
683
+ conversations.append(conv.get_prompt())
684
+
685
+ # Tokenize conversations
686
+
687
+ if has_image:
688
+ input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0)
689
+ else:
690
+ input_ids = tokenizer(
691
+ conversations,
692
+ return_tensors="pt",
693
+ padding="longest",
694
+ max_length=tokenizer.model_max_length,
695
+ truncation=True,
696
+ ).input_ids
697
+
698
+ targets = input_ids.clone()
699
+
700
+ assert conv.sep_style == conversation_lib.SeparatorStyle.TWO
701
+
702
+ # Mask targets
703
+ sep = conv.sep + conv.roles[1] + ": "
704
+ for conversation, target in zip(conversations, targets):
705
+ total_len = int(target.ne(tokenizer.pad_token_id).sum())
706
+
707
+ rounds = conversation.split(conv.sep2)
708
+ cur_len = 1
709
+ target[:cur_len] = IGNORE_INDEX
710
+ for i, rou in enumerate(rounds):
711
+ if rou == "":
712
+ break
713
+
714
+ parts = rou.split(sep)
715
+ if len(parts) != 2:
716
+ break
717
+ parts[0] += sep
718
+
719
+ if has_image:
720
+ round_len = len(tokenizer_image_token(rou, tokenizer))
721
+ instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2
722
+ else:
723
+ round_len = len(tokenizer(rou).input_ids)
724
+ instruction_len = len(tokenizer(parts[0]).input_ids) - 2
725
+
726
+ if i != 0 and not tokenizer.legacy and IS_TOKENIZER_GREATER_THAN_0_14:
727
+ round_len -= 1
728
+ instruction_len -= 1
729
+
730
+ target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
731
+
732
+ cur_len += round_len
733
+ target[cur_len:] = IGNORE_INDEX
734
+
735
+ if cur_len < tokenizer.model_max_length:
736
+ if cur_len != total_len:
737
+ target[:] = IGNORE_INDEX
738
+ print(f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)")
739
+
740
+ return dict(
741
+ input_ids=input_ids,
742
+ labels=targets,
743
+ )
744
+
745
+
746
+ def preprocess_mpt(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict:
747
+ conv = conversation_lib.default_conversation.copy()
748
+ roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
749
+
750
+ # Apply prompt templates
751
+ conversations = []
752
+ for i, source in enumerate(sources):
753
+ if roles[source[0]["from"]] != conv.roles[0]:
754
+ # Skip the first one if it is not from human
755
+ source = source[1:]
756
+
757
+ conv.messages = []
758
+ for j, sentence in enumerate(source):
759
+ role = roles[sentence["from"]]
760
+ assert role == conv.roles[j % 2], f"{i}"
761
+ conv.append_message(role, sentence["value"])
762
+ conversations.append(conv.get_prompt())
763
+
764
+ # Tokenize conversations
765
+
766
+ if has_image:
767
+ input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0)
768
+ else:
769
+ input_ids = tokenizer(
770
+ conversations,
771
+ return_tensors="pt",
772
+ padding="longest",
773
+ max_length=tokenizer.model_max_length,
774
+ truncation=True,
775
+ ).input_ids
776
+
777
+ targets = input_ids.clone()
778
+ assert conv.sep_style == conversation_lib.SeparatorStyle.MPT
779
+
780
+ # Mask targets
781
+ sep = conv.sep + conv.roles[1]
782
+ for conversation, target in zip(conversations, targets):
783
+ total_len = int(target.ne(tokenizer.pad_token_id).sum())
784
+
785
+ rounds = conversation.split(conv.sep)
786
+ re_rounds = [conv.sep.join(rounds[:3])] # system + user + gpt
787
+ for conv_idx in range(3, len(rounds), 2):
788
+ re_rounds.append(conv.sep.join(rounds[conv_idx : conv_idx + 2])) # user + gpt
789
+ cur_len = 1
790
+ target[:cur_len] = IGNORE_INDEX
791
+ for i, rou in enumerate(re_rounds):
792
+ if rou == "":
793
+ break
794
+
795
+ parts = rou.split(sep)
796
+ if len(parts) != 2:
797
+ break
798
+ parts[0] += sep
799
+
800
+ if has_image:
801
+ round_len = len(tokenizer_image_token(rou, tokenizer))
802
+ instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 1
803
+ else:
804
+ round_len = len(tokenizer(rou).input_ids)
805
+ instruction_len = len(tokenizer(parts[0]).input_ids) - 1
806
+
807
+ if i != 0 and getattr(tokenizer, "legacy", False) and IS_TOKENIZER_GREATER_THAN_0_14:
808
+ round_len += 1
809
+ instruction_len += 1
810
+
811
+ target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
812
+
813
+ cur_len += round_len
814
+ target[cur_len:] = IGNORE_INDEX
815
+
816
+ if cur_len < tokenizer.model_max_length:
817
+ if cur_len != total_len:
818
+ target[:] = IGNORE_INDEX
819
+ print(f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f"(#turns={len(re_rounds)} ignored)")
820
+
821
+ return dict(
822
+ input_ids=input_ids,
823
+ labels=targets,
824
+ )
825
+
826
+
827
+ def preprocess_plain(
828
+ sources: Sequence[str],
829
+ tokenizer: transformers.PreTrainedTokenizer,
830
+ ) -> Dict:
831
+ # add end signal and concatenate together
832
+ conversations = []
833
+ for source in sources:
834
+ assert len(source) == 2
835
+ assert DEFAULT_IMAGE_TOKEN in source[0]["value"]
836
+ source[0]["value"] = DEFAULT_IMAGE_TOKEN
837
+ conversation = source[0]["value"] + source[1]["value"] + conversation_lib.default_conversation.sep
838
+ conversations.append(conversation)
839
+ # tokenize conversations
840
+ input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations]
841
+ targets = copy.deepcopy(input_ids)
842
+ for target, source in zip(targets, sources):
843
+ tokenized_len = len(tokenizer_image_token(source[0]["value"], tokenizer))
844
+ target[:tokenized_len] = IGNORE_INDEX
845
+
846
+ return dict(input_ids=input_ids, labels=targets)
847
+
848
+
849
+ def preprocess(sources: Sequence[str], tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict:
850
+ """
851
+ Given a list of sources, each is a conversation list. This transform:
852
+ 1. Add signal '### ' at the beginning each sentence, with end signal '\n';
853
+ 2. Concatenate conversations together;
854
+ 3. Tokenize the concatenated conversation;
855
+ 4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX.
856
+ """
857
+ if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.PLAIN:
858
+ return preprocess_plain(sources, tokenizer)
859
+ if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.LLAMA_2:
860
+ return preprocess_llama_2(sources, tokenizer, has_image=has_image)
861
+ if conversation_lib.default_conversation.version.startswith("v1"):
862
+ return preprocess_v1(sources, tokenizer, has_image=has_image)
863
+ if conversation_lib.default_conversation.version == "mpt":
864
+ return preprocess_mpt(sources, tokenizer, has_image=has_image)
865
+ if conversation_lib.default_conversation.version == "qwen":
866
+ return preprocess_qwen(sources, tokenizer, has_image=has_image)
867
+ if conversation_lib.default_conversation.version == "gemma":
868
+ return preprocess_gemma(sources, tokenizer, has_image=has_image)
869
+ if conversation_lib.default_conversation.version == "llama_v3":
870
+ return preprocess_llama3(sources, tokenizer, has_image=has_image)
871
+ # add end signal and concatenate together
872
+ conversations = []
873
+ for source in sources:
874
+ header = f"{conversation_lib.default_conversation.system}\n\n"
875
+ conversation = _add_speaker_and_signal(header, source)
876
+ conversations.append(conversation)
877
+
878
+ # tokenize conversations
879
+ def get_tokenize_len(prompts):
880
+ return [len(tokenizer_image_token(prompt, tokenizer)) for prompt in prompts]
881
+
882
+ if has_image:
883
+ input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations]
884
+ else:
885
+ conversations_tokenized = _tokenize_fn(conversations, tokenizer)
886
+ input_ids = conversations_tokenized["input_ids"]
887
+
888
+ targets = copy.deepcopy(input_ids)
889
+ for target, source in zip(targets, sources):
890
+ if has_image:
891
+ tokenized_lens = get_tokenize_len([header] + [s["value"] for s in source])
892
+ else:
893
+ tokenized_lens = _tokenize_fn([header] + [s["value"] for s in source], tokenizer)["input_ids_lens"]
894
+ speakers = [sentence["from"] for sentence in source]
895
+ _mask_targets(target, tokenized_lens, speakers)
896
+
897
+ return dict(input_ids=input_ids, labels=targets)
898
+
899
+
900
+ def load_data(data_path):
901
+ if "jsonl" in data_path:
902
+ data_list = load_jsonl(data_path)
903
+ else:
904
+ data_list = load_json(data_path)
905
+ return data_list
906
+
907
+
908
+ class DPODataset(Dataset):
909
+ """Dataset for DPODataset fine-tuning."""
910
+
911
+ def __init__(self, data_path: str, tokenizer: transformers.PreTrainedTokenizer, data_args: DataArguments):
912
+ super(DPODataset, self).__init__()
913
+ # Handle multiple JSON files specified in the data_path
914
+ self.list_data_dict = []
915
+
916
+ if "{" in data_path and "}" in data_path:
917
+ base_path, file_pattern = re.match(r"^(.*)\{(.*)\}\.json$", data_path).groups()
918
+ file_names = file_pattern.split(",")
919
+ rank0_print(f"Loading {file_names} from {base_path}")
920
+ data_args.dataset_paths = []
921
+ for file_name in file_names:
922
+ data_args.dataset_paths.append(f"{base_path}{file_name}.json")
923
+ full_path = f"{base_path}{file_name}.json"
924
+ rank0_print(f"Loading {full_path}")
925
+ cur_data_dict = load_data(full_path)
926
+ rank0_print(f"Loaded {len(cur_data_dict)} samples from {full_path}")
927
+ self.list_data_dict.extend(cur_data_dict)
928
+ elif data_path.endswith(".yaml"):
929
+ with open(data_path, "r") as file:
930
+ yaml_data = yaml.safe_load(file)
931
+ datasets = yaml_data.get("datasets")
932
+ # file should be in the format of:
933
+ # datasets:
934
+ # - json_path: xxxx1.json
935
+ # sampling_strategy: first:1000
936
+ # - json_path: xxxx2.json
937
+ # sampling_strategy: end:3000
938
+ # - json_path: xxxx3.json
939
+ # sampling_strategy: random:999
940
+ data_args.dataset_paths = [dataset.get("json_path") for dataset in datasets]
941
+ for dataset in datasets:
942
+ json_path = dataset.get("json_path")
943
+ sampling_strategy = dataset.get("sampling_strategy", "all")
944
+ sampling_number = None
945
+
946
+ rank0_print(f"Loading {json_path} with {sampling_strategy} sampling strategy")
947
+ cur_data_dict = load_data(json_path)
948
+
949
+ if ":" in sampling_strategy:
950
+ sampling_strategy, sampling_number = sampling_strategy.split(":")
951
+ if "%" in sampling_number:
952
+ sampling_number = math.ceil(int(sampling_number.split("%")[0]) * len(cur_data_dict) / 100)
953
+ else:
954
+ sampling_number = int(sampling_number)
955
+
956
+ # Apply the sampling strategy
957
+ if sampling_strategy == "first" and sampling_number is not None:
958
+ cur_data_dict = cur_data_dict[:sampling_number]
959
+ elif sampling_strategy == "end" and sampling_number is not None:
960
+ cur_data_dict = cur_data_dict[-sampling_number:]
961
+ elif sampling_strategy == "random" and sampling_number is not None:
962
+ random.shuffle(cur_data_dict)
963
+ cur_data_dict = cur_data_dict[:sampling_number]
964
+
965
+ rank0_print(f"Loaded {len(cur_data_dict)} samples from {json_path}")
966
+ self.list_data_dict.extend(cur_data_dict)
967
+ else:
968
+ data_args.dataset_paths = [data_path]
969
+ rank0_print(f"Loading {data_path}")
970
+ cur_data_dict = load_data(data_path)
971
+ rank0_print(f"Loaded {len(cur_data_dict)} samples from {data_path}")
972
+ self.list_data_dict.extend(cur_data_dict)
973
+
974
+ rank0_print("Formatting inputs...Skip in lazy mode")
975
+ self.tokenizer = tokenizer
976
+ self.data_args = data_args
977
+
978
+ def __len__(self):
979
+ return len(self.list_data_dict)
980
+
981
+ @property
982
+ def lengths(self):
983
+ length_list = []
984
+ for sample in self.list_data_dict:
985
+ # Calculate the length of the prompt, answer, chosen, and rejected text
986
+ cur_len = len(sample["prompt"].split()) + len(sample["answer"].split()) + len(sample["chosen"].split()) + len(sample["rejected"].split())
987
+ # Add additional tokens if an image is present
988
+ img_tokens = 128 if "image" in sample else 0
989
+ length_list.append(cur_len + img_tokens)
990
+ return length_list
991
+
992
+ @property
993
+ def modality_lengths(self):
994
+ length_list = []
995
+ for sample in self.list_data_dict:
996
+ # Calculate the length of the prompt, answer, chosen, and rejected text
997
+ cur_len = len(sample["prompt"].split()) + len(sample["answer"].split()) + len(sample["chosen"].split()) + len(sample["rejected"].split())
998
+ # If the sample includes a video, the length is positive; otherwise, it is negative
999
+ cur_len = cur_len if ("video" in sample or "image" in sample) else -cur_len
1000
+ length_list.append(cur_len)
1001
+ return length_list
1002
+
1003
+ def process_image(self, image_file):
1004
+ image_folder = self.data_args.image_folder
1005
+ processor = self.data_args.image_processor
1006
+ # print(f"\n\nInspecting the image path, folder = {image_folder}, image={image_file}\n\n")
1007
+ try:
1008
+ image = Image.open(os.path.join(image_folder, image_file)).convert("RGB")
1009
+ except Exception as exn:
1010
+ print(f"Failed to open image {image_file}. Exception:", exn)
1011
+ raise exn
1012
+
1013
+ image_size = image.size
1014
+ if self.data_args.image_aspect_ratio == "highres":
1015
+ image = process_highres_image(image, self.data_args.image_processor, self.data_args.image_grid_pinpoints)
1016
+ elif self.data_args.image_aspect_ratio == "anyres" or "anyres" in self.data_args.image_aspect_ratio:
1017
+ image = process_anyres_image(image, self.data_args.image_processor, self.data_args.image_grid_pinpoints)
1018
+ elif self.data_args.image_aspect_ratio == "crop_split":
1019
+ image = process_highres_image_crop_split(image, self.data_args)
1020
+ elif self.data_args.image_aspect_ratio == "pad":
1021
+
1022
+ def expand2square(pil_img, background_color):
1023
+ width, height = pil_img.size
1024
+ if width == height:
1025
+ return pil_img
1026
+ elif width > height:
1027
+ result = Image.new(pil_img.mode, (width, width), background_color)
1028
+ result.paste(pil_img, (0, (width - height) // 2))
1029
+ return result
1030
+ else:
1031
+ result = Image.new(pil_img.mode, (height, height), background_color)
1032
+ result.paste(pil_img, ((height - width) // 2, 0))
1033
+ return result
1034
+
1035
+ image = expand2square(image, tuple(int(x * 255) for x in processor.image_mean))
1036
+ image = processor.preprocess(image, return_tensors="pt")["pixel_values"][0]
1037
+ else:
1038
+ image = processor.preprocess(image, return_tensors="pt")["pixel_values"][0]
1039
+ return image, image_size, "image"
1040
+
1041
+ def __getitem__(self, i) -> Dict[str, torch.Tensor]:
1042
+ # TODO: define number of retries somewhere else
1043
+ num_base_retries = 3
1044
+ num_final_retries = 300
1045
+
1046
+ # try the current sample first
1047
+ for attempt_idx in range(num_base_retries):
1048
+ try:
1049
+ sample = self._get_item(i)
1050
+ return sample
1051
+ except Exception as e:
1052
+ # sleep 1s in case it is a cloud disk issue
1053
+ print(f"[Try #{attempt_idx}] Failed to fetch sample {i}. Exception:", e)
1054
+ time.sleep(1)
1055
+
1056
+ # try other samples, in case it is file corruption issue
1057
+ for attempt_idx in range(num_base_retries):
1058
+ try:
1059
+ next_index = min(i + 1, len(self.list_data_dict) - 1)
1060
+ # sample_idx = random.choice(range(len(self)))
1061
+ sample = self._get_item(next_index)
1062
+ return sample
1063
+ except Exception as e:
1064
+ # no need to sleep
1065
+ print(f"[Try other #{attempt_idx}] Failed to fetch sample {next_index}. Exception:", e)
1066
+ pass
1067
+
1068
+ # still fail, most likely to be path issue or cloud disk issue, retry the same sample for longer
1069
+ # for attempt_idx in range(num_final_retries):
1070
+ # try:
1071
+ # sample = self._get_item(i)
1072
+ # return sample
1073
+ # except Exception as e:
1074
+ # # sleep 1s in case it is a cloud disk issue
1075
+ # print(f"[Final try #{attempt_idx}] Failed to fetch sample {i}. Exception:", e)
1076
+ # time.sleep(1)
1077
+
1078
+ # Finally raise exception on failing.
1079
+ assert False, "Failed to fetch sample."
1080
+
1081
+ def _get_item(self, i) -> Dict[str, torch.Tensor]:
1082
+ sources = self.list_data_dict[i]
1083
+ if isinstance(i, int):
1084
+ sources = [sources]
1085
+ assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME
1086
+
1087
+ suffix = None
1088
+ if "image" in sources[0]:
1089
+ image_file = self.list_data_dict[i]["image"]
1090
+ if type(image_file) is list:
1091
+ image = [self.process_image(f) for f in image_file]
1092
+ else:
1093
+ image = [self.process_image(image_file)]
1094
+ # sources = preprocess_multimodal(copy.deepcopy([e["conversations"] for e in sources]), self.data_args)
1095
+
1096
+ elif "video" in sources[0]: # FIXME: This logic should be largely improved by Yuanhan. It's too messy now.
1097
+ video_file = self.list_data_dict[i]["video"]
1098
+ video_folder = self.data_args.video_folder
1099
+ video_file = os.path.join(video_folder, video_file)
1100
+ suffix = video_file.split(".")[-1]
1101
+ if not os.path.exists(video_file):
1102
+ print("File {} not exist!".format(video_file))
1103
+
1104
+ if suffix == "pkl":
1105
+ video_info = pickle.load(open(video_file, "rb"))
1106
+ image = torch.from_numpy(video_info["feats"][:, 1:])
1107
+ input_prompt = video_info["inputs"].replace("...", "")
1108
+ # replace the default image token with multiple tokens
1109
+ input_prompt = input_prompt.replace(DEFAULT_IMAGE_TOKEN, DEFAULT_IMAGE_TOKEN * self.data_args.video_token)
1110
+ sources, query_prompt = preprocess_multimodal_movie(copy.deepcopy([e["conversations"] for e in sources]), self.data_args, input_prompt)
1111
+ else: # using videoreader
1112
+ if "shareVideoGPTV" not in video_file and "liangke" not in video_file:
1113
+ vr = VideoReader(video_file, ctx=cpu(0))
1114
+ total_frame_num = len(vr)
1115
+ avg_fps = round(vr.get_avg_fps() / self.data_args.video_fps)
1116
+ frame_idx = [i for i in range(0, total_frame_num, avg_fps)]
1117
+ if self.data_args.frames_upbound > 0:
1118
+ if len(frame_idx) > self.data_args.frames_upbound:
1119
+ uniform_sampled_frames = np.linspace(0, total_frame_num - 1, self.data_args.frames_upbound, dtype=int)
1120
+ frame_idx = uniform_sampled_frames.tolist()
1121
+ video = vr.get_batch(frame_idx).asnumpy()
1122
+ video = np.array(video)
1123
+ else:
1124
+ if "liangke" in video_file:
1125
+ video_file = self.list_data_dict[i]["video"]
1126
+ frame_files = [os.path.join(video_file, f) for f in os.listdir(video_file) if os.path.isfile(os.path.join(video_file, f))]
1127
+ frame_files.sort() # Ensure the frames are sorted if they are named sequentially
1128
+
1129
+ # TODO: Hard CODE: Determine the indices for uniformly sampling 10 frames
1130
+ num_frames_to_sample = 10
1131
+
1132
+ total_frames = len(frame_files)
1133
+
1134
+ sampled_indices = np.linspace(0, total_frames - 1, num_frames_to_sample, dtype=int)
1135
+
1136
+ # Read and store the sampled frames
1137
+ video = []
1138
+ for idx in sampled_indices:
1139
+ frame_path = frame_files[idx]
1140
+ try:
1141
+ with Image.open(frame_path) as img:
1142
+ frame = img.convert("RGB")
1143
+ video.append(frame)
1144
+ except IOError:
1145
+ print(f"Failed to read frame at path: {frame_path}")
1146
+
1147
+ processor = self.data_args.image_processor
1148
+ image = processor.preprocess(video, return_tensors="pt")["pixel_values"]
1149
+ image = [(image, video[0].size, "video")]
1150
+ # sources = preprocess_multimodal(copy.deepcopy([e["conversations"] for e in sources]), self.data_args)
1151
+
1152
+ else:
1153
+ sources = copy.deepcopy([e["conversations"] for e in sources])
1154
+
1155
+ has_image = ("image" in self.list_data_dict[i]) or ("video" in self.list_data_dict[i])
1156
+ # data_dict = preprocess(sources, self.tokenizer, has_image=has_image)
1157
+ data_dict = copy.deepcopy(self.list_data_dict[i]) # inplace modification following
1158
+
1159
+ if "prompt" in data_dict:
1160
+ prompt = data_dict["prompt"]
1161
+ prompt = prompt.replace("<image>", "").strip()
1162
+ prompt = "<image>\n" + prompt
1163
+ data_dict["prompt"] = prompt
1164
+ else:
1165
+ prompt = None
1166
+
1167
+ if suffix == "pkl":
1168
+ prompt = [query_prompt]
1169
+
1170
+ # image exist in the data
1171
+ if "image" in self.list_data_dict[i]:
1172
+ data_dict["image"] = image
1173
+ elif "video" in self.list_data_dict[i]:
1174
+ data_dict["image"] = image
1175
+ elif self.data_args.is_multimodal:
1176
+ # image does not exist in the data, but the model is multimodal
1177
+ crop_size = self.data_args.image_processor.crop_size
1178
+ data_dict["image"] = [
1179
+ (torch.zeros(1, 3, crop_size["height"], crop_size["width"]), (crop_size["width"], crop_size["height"]), "text"),
1180
+ ]
1181
+ # prompt exist in the data
1182
+ data_dict["has_image"] = has_image
1183
+ return data_dict
1184
+
1185
+
1186
+ @dataclass
1187
+ class DPODataCollator(DPODataCollatorWithPadding):
1188
+ """Collate examples for DPO fine-tuning."""
1189
+
1190
+ # tokenizer: transformers.PreTrainedTokenizer
1191
+
1192
+ def collate(self, batch):
1193
+ # first, pad everything to the same length
1194
+ # input_ids, labels = tuple([instance[key] for instance in instances]
1195
+ # for key in ("input_ids", "labels"))
1196
+ # input_ids = torch.nn.utils.rnn.pad_sequence(
1197
+ # input_ids,
1198
+ # batch_first=True,
1199
+ # padding_value=self.tokenizer.pad_token_id)
1200
+ # labels = torch.nn.utils.rnn.pad_sequence(labels,
1201
+ # batch_first=True,
1202
+ # padding_value=IGNORE_INDEX)
1203
+ # input_ids = input_ids[:, :self.tokenizer.model_max_length]
1204
+ # labels = labels[:, :self.tokenizer.model_max_length]
1205
+ # batch = dict(
1206
+ # input_ids=input_ids,
1207
+ # labels=labels,
1208
+ # attention_mask=input_ids.ne(self.tokenizer.pad_token_id),
1209
+ # )
1210
+ padded_batch = {}
1211
+ for k in batch[0].keys():
1212
+ if k.endswith("_input_ids") or k.endswith("_attention_mask") or k.endswith("_labels"):
1213
+ # if "prompt" in k:
1214
+ # to_pad = [torch.LongTensor(ex[k][::-1]) for ex in batch]
1215
+ # else:
1216
+ to_pad = [torch.LongTensor(ex[k]) for ex in batch]
1217
+ if k.endswith("_input_ids"):
1218
+ padding_value = self.tokenizer.pad_token_id
1219
+ elif k.endswith("_labels"):
1220
+ padding_value = self.label_pad_token_id
1221
+ else:
1222
+ continue
1223
+ # elif k.endswith("_attention_mask"):
1224
+ # padding_value = self.padding_value
1225
+ # else:
1226
+ # raise ValueError(f"Unexpected key in batch '{k}'")
1227
+
1228
+ padded_batch[k] = torch.nn.utils.rnn.pad_sequence(to_pad, batch_first=True, padding_value=padding_value)
1229
+ # for the prompt, flip back so padding is on left side
1230
+ # if "prompt" in k:
1231
+ # padded_batch[k] = padded_batch[k].flip(dims=[1])
1232
+ else:
1233
+ padded_batch[k] = [ex[k] for ex in batch]
1234
+ for k in ["chosen_input_ids", "rejected_input_ids"]:
1235
+ attn_k = k.replace("input_ids", "attention_mask")
1236
+ padded_batch[attn_k] = padded_batch[k].ne(self.tokenizer.pad_token_id)
1237
+ return padded_batch
1238
+
1239
+ def tokenize_batch_element(self, prompt: str, chosen: str, rejected: str, has_image: bool = True) -> Dict:
1240
+ """Tokenize a single batch element.
1241
+
1242
+ At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation
1243
+ in case the prompt + chosen or prompt + rejected responses is/are too long. First
1244
+ we truncate the prompt; if we're still too long, we truncate the chosen/rejected.
1245
+
1246
+ We also create the labels for the chosen/rejected responses, which are of length equal to
1247
+ the sum of the length of the prompt and the chosen/rejected response, with
1248
+ label_pad_token_id for the prompt tokens.
1249
+ """
1250
+ # import pdb; pdb.set_trace()
1251
+ batch = {}
1252
+
1253
+ chosen_sources = make_conv(prompt, chosen)
1254
+ rejected_sources = make_conv(prompt, rejected)
1255
+ chosen_data_dict = preprocess([chosen_sources], self.tokenizer, has_image=has_image)
1256
+ # chosen_data_dict['attention_mask'] = chosen_data_dict["input_ids"].ne(self.tokenizer.pad_token_id)
1257
+
1258
+ rejected_data_dict = preprocess([rejected_sources], self.tokenizer, has_image=has_image)
1259
+ # rejected_data_dict['attention_mask'] = rejected_data_dict["input_ids"].ne(self.tokenizer.pad_token_id)
1260
+
1261
+ chosen_data_dict = {k: v[0] for k, v in chosen_data_dict.items()}
1262
+ rejected_data_dict = {k: v[0] for k, v in rejected_data_dict.items()}
1263
+
1264
+ for k, toks in {
1265
+ "chosen": chosen_data_dict,
1266
+ "rejected": rejected_data_dict,
1267
+ }.items():
1268
+ for type_key, tokens in toks.items():
1269
+ if type_key == "token_type_ids":
1270
+ continue
1271
+ batch[f"{k}_{type_key}"] = tokens
1272
+ return batch
1273
+
1274
+ def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]:
1275
+
1276
+ tokenized_batch = []
1277
+ Xs, keys = [], []
1278
+ for feature in features:
1279
+ prompt = feature["prompt"]
1280
+ chosen = feature["chosen"]
1281
+ rejected = feature["rejected"]
1282
+ has_image = feature["has_image"]
1283
+ # Xs.append(feature[has_X])
1284
+ # keys.append(has_X)
1285
+
1286
+ batch_element = self.tokenize_batch_element(prompt, chosen, rejected, has_image=has_image)
1287
+ tokenized_batch.append(batch_element)
1288
+
1289
+ # return collated batch
1290
+ padded_batch = self.collate(tokenized_batch)
1291
+ # import pdb;pdb.set_trace()
1292
+ if "image" in features[0]:
1293
+ # instances[1]['image'][0][0].shape
1294
+ # torch.Size([5, 3, 224, 224])
1295
+ images = [instance["image"] for instance in features]
1296
+
1297
+ padded_batch["image_sizes"] = [im[1] for im_list in images for im in im_list]
1298
+ padded_batch["modalities"] = [im[2] for im_list in images for im in im_list]
1299
+ images = [im[0] for im_list in images for im in im_list]
1300
+ # import pdb;pdb.set_trace()
1301
+
1302
+ padded_batch["images"] = images
1303
+ # padded_batch["images"] =[padded_batch["modalities"], images]
1304
+
1305
+ return padded_batch
1306
+
1307
+
1308
+ def make_dpo_data_module(tokenizer: transformers.PreTrainedTokenizer, data_args) -> Dict:
1309
+ """Make dataset and collator for supervised fine-tuning."""
1310
+ train_dataset = DPODataset(tokenizer=tokenizer, data_path=data_args.data_path, data_args=data_args)
1311
+ return train_dataset
1312
+
1313
+
1314
+ def get_model(model_args, training_args, bnb_model_from_pretrained_args):
1315
+ assert training_args.attn_implementation
1316
+ if training_args.attn_implementation == "sdpa" and torch.__version__ < "2.1.2":
1317
+ raise ValueError("The 'sdpa' attention implementation requires torch version 2.1.2 or higher.")
1318
+
1319
+ ######################### Overwrite config #########################
1320
+ customized_kwargs = dict()
1321
+ customized_kwargs.update(bnb_model_from_pretrained_args)
1322
+ overwrite_config = {}
1323
+ cfg_pretrained = None
1324
+ if "qwen" in model_args.model_name_or_path.lower():
1325
+ cfg_pretrained = LlavaQwenConfig.from_pretrained(model_args.model_name_or_path)
1326
+ elif "mistral" in model_args.model_name_or_path.lower() or "zephyr" in model_args.model_name_or_path.lower():
1327
+ cfg_pretrained = LlavaMistralConfig.from_pretrained(model_args.model_name_or_path)
1328
+ elif (
1329
+ "wizardlm-2" in model_args.model_name_or_path.lower()
1330
+ or "vicuna" in model_args.model_name_or_path.lower()
1331
+ or "llama" in model_args.model_name_or_path.lower()
1332
+ or "yi" in model_args.model_name_or_path.lower()
1333
+ or "nous-hermes" in model_args.model_name_or_path.lower()
1334
+ and "wizard-2" in model_args.model_name_or_path.lower()
1335
+ ):
1336
+ cfg_pretrained = LlavaConfig.from_pretrained(model_args.model_name_or_path)
1337
+ else:
1338
+ cfg_pretrained = AutoConfig.from_pretrained(model_args.model_name_or_path)
1339
+
1340
+ if model_args.rope_scaling_factor is not None and model_args.rope_scaling_type is not None and cfg_pretrained is not None:
1341
+ overwrite_config["rope_scaling"] = {
1342
+ "factor": model_args.rope_scaling_factor,
1343
+ "type": model_args.rope_scaling_type,
1344
+ }
1345
+ if training_args.model_max_length is None:
1346
+ training_args.model_max_length = cfg_pretrained.max_position_embeddings * model_args.rope_scaling_factor
1347
+ overwrite_config["max_sequence_length"] = training_args.model_max_length
1348
+ assert training_args.model_max_length == int(cfg_pretrained.max_position_embeddings * model_args.rope_scaling_factor), print(
1349
+ f"model_max_length: {training_args.model_max_length}, max_position_embeddings: {cfg_pretrained.max_position_embeddings}, rope_scaling_factor: {model_args.rope_scaling_factor}"
1350
+ )
1351
+ # overwrite_config["max_sequence_length"] = model_args.max_sequence_length
1352
+ # overwrite_config["tokenizer_model_max_length"] = model_args.tokenizer_model_max_length
1353
+
1354
+ if model_args.mm_spatial_pool_stride is not None and model_args.mm_spatial_pool_out_channels is not None and model_args.mm_spatial_pool_mode is not None and model_args.mm_resampler_type is not None and cfg_pretrained is not None:
1355
+ overwrite_config["mm_resampler_type"] = model_args.mm_resampler_type
1356
+ overwrite_config["mm_spatial_pool_stride"] = model_args.mm_spatial_pool_stride
1357
+ overwrite_config["mm_spatial_pool_out_channels"] = model_args.mm_spatial_pool_out_channels
1358
+ overwrite_config["mm_spatial_pool_mode"] = model_args.mm_spatial_pool_mode
1359
+
1360
+ if overwrite_config:
1361
+ rank0_print(f"Overwriting config with {overwrite_config}")
1362
+ for k, v in overwrite_config.items():
1363
+ setattr(cfg_pretrained, k, v)
1364
+
1365
+ customized_kwargs["config"] = cfg_pretrained
1366
+
1367
+ ######################### Finish Overwrite ###########################
1368
+
1369
+ ref_model = None
1370
+ if model_args.model_class_name is not None:
1371
+ actual_model_class_name = f"{model_args.model_class_name}ForCausalLM"
1372
+ model_class = getattr(transformers, actual_model_class_name)
1373
+ rank0_print(f"Using model class {model_class} from {model_args.model_class_name}")
1374
+ model = model_class.from_pretrained(
1375
+ model_args.model_name_or_path,
1376
+ cache_dir=training_args.cache_dir,
1377
+ attn_implementation=training_args.attn_implementation,
1378
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1379
+ low_cpu_mem_usage=False,
1380
+ **customized_kwargs,
1381
+ )
1382
+ elif model_args.vision_tower is not None:
1383
+ if "mixtral" in model_args.model_name_or_path.lower():
1384
+ model = LlavaMixtralForCausalLM.from_pretrained(
1385
+ model_args.model_name_or_path,
1386
+ cache_dir=training_args.cache_dir,
1387
+ attn_implementation=training_args.attn_implementation,
1388
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1389
+ low_cpu_mem_usage=False,
1390
+ **customized_kwargs,
1391
+ )
1392
+ from transformers.models.mixtral.modeling_mixtral import MixtralSparseMoeBlock
1393
+
1394
+ deepspeed.utils.set_z3_leaf_modules(model, [MixtralSparseMoeBlock])
1395
+ elif "mistral" in model_args.model_name_or_path.lower() or "zephyr" in model_args.model_name_or_path.lower():
1396
+ model = LlavaMistralForCausalLM.from_pretrained(
1397
+ model_args.model_name_or_path,
1398
+ cache_dir=training_args.cache_dir,
1399
+ attn_implementation=training_args.attn_implementation,
1400
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1401
+ low_cpu_mem_usage=False,
1402
+ **customized_kwargs,
1403
+ )
1404
+ elif (
1405
+ "wizardlm-2" in model_args.model_name_or_path.lower()
1406
+ or "vicuna" in model_args.model_name_or_path.lower()
1407
+ or "llama" in model_args.model_name_or_path.lower()
1408
+ or "yi" in model_args.model_name_or_path.lower()
1409
+ or "nous-hermes" in model_args.model_name_or_path.lower()
1410
+ and "wizard-2" in model_args.model_name_or_path.lower()
1411
+ ):
1412
+ model = LlavaLlamaForCausalLM.from_pretrained(
1413
+ model_args.model_name_or_path,
1414
+ cache_dir=training_args.cache_dir,
1415
+ attn_implementation=training_args.attn_implementation,
1416
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1417
+ low_cpu_mem_usage=False,
1418
+ **customized_kwargs,
1419
+ )
1420
+
1421
+ if "zero3" in training_args.deepspeed:
1422
+ rank0_print("#### Initialize reference model #####")
1423
+ ref_model = LlavaLlamaForCausalLM.from_pretrained(
1424
+ model_args.model_name_or_path,
1425
+ cache_dir=training_args.cache_dir,
1426
+ attn_implementation=training_args.attn_implementation,
1427
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1428
+ low_cpu_mem_usage=False,
1429
+ **customized_kwargs,
1430
+ )
1431
+
1432
+ elif "qwen" in model_args.model_name_or_path.lower() or "quyen" in model_args.model_name_or_path.lower():
1433
+ if "moe" in model_args.model_name_or_path.lower():
1434
+ model = LlavaQwenMoeForCausalLM.from_pretrained(
1435
+ model_args.model_name_or_path,
1436
+ cache_dir=training_args.cache_dir,
1437
+ attn_implementation=training_args.attn_implementation,
1438
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1439
+ low_cpu_mem_usage=False,
1440
+ **customized_kwargs,
1441
+ )
1442
+ from transformers.models.qwen2_moe.modeling_qwen2_moe import Qwen2MoeSparseMoeBlock
1443
+
1444
+ deepspeed.utils.set_z3_leaf_modules(model, [Qwen2MoeSparseMoeBlock])
1445
+ else:
1446
+ model = LlavaQwenForCausalLM.from_pretrained(
1447
+ model_args.model_name_or_path,
1448
+ cache_dir=training_args.cache_dir,
1449
+ attn_implementation=training_args.attn_implementation,
1450
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1451
+ low_cpu_mem_usage=False,
1452
+ **customized_kwargs,
1453
+ )
1454
+
1455
+ if "zero3" in training_args.deepspeed:
1456
+ rank0_print("#### Initialize reference model #####")
1457
+ ref_model = LlavaQwenForCausalLM.from_pretrained(
1458
+ model_args.model_name_or_path,
1459
+ cache_dir=training_args.cache_dir,
1460
+ attn_implementation=training_args.attn_implementation,
1461
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1462
+ low_cpu_mem_usage=False,
1463
+ **customized_kwargs,
1464
+ )
1465
+
1466
+ elif "gemma" in model_args.model_name_or_path.lower():
1467
+ model = LlavaGemmaForCausalLM.from_pretrained(
1468
+ model_args.model_name_or_path,
1469
+ cache_dir=training_args.cache_dir,
1470
+ attn_implementation=training_args.attn_implementation,
1471
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
1472
+ low_cpu_mem_usage=False,
1473
+ **customized_kwargs,
1474
+ )
1475
+ else:
1476
+ raise ValueError(f"Unknown model class {model_args}")
1477
+ else:
1478
+ model = transformers.LlamaForCausalLM.from_pretrained(
1479
+ model_args.model_name_or_path, cache_dir=training_args.cache_dir, attn_implementation=training_args.attn_implementation, torch_dtype=(torch.bfloat16 if training_args.bf16 else None), **customized_kwargs
1480
+ )
1481
+ return model, ref_model
1482
+
1483
+
1484
+ def train(attn_implementation=None):
1485
+ global local_rank
1486
+
1487
+ parser = transformers.HfArgumentParser((ModelArguments, DataArguments, TrainingArguments))
1488
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
1489
+
1490
+ if training_args.verbose_logging:
1491
+ rank0_print(f"Inspecting experiment hyperparameters:\n")
1492
+ rank0_print(f"model_args = {vars(model_args)}\n\n")
1493
+ rank0_print(f"data_args = {vars(data_args)}\n\n")
1494
+ rank0_print(f"training_args = {vars(training_args)}\n\n")
1495
+ # rank0_print(f"evaluation_args = {vars(evaluation_args)}\n\n")
1496
+
1497
+ local_rank = training_args.local_rank
1498
+ compute_dtype = torch.float16 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)
1499
+
1500
+ bnb_model_from_pretrained_args = {}
1501
+ if training_args.bits in [4, 8]:
1502
+ from transformers import BitsAndBytesConfig
1503
+
1504
+ bnb_model_from_pretrained_args.update(
1505
+ dict(
1506
+ device_map={"": training_args.device},
1507
+ load_in_4bit=training_args.bits == 4,
1508
+ load_in_8bit=training_args.bits == 8,
1509
+ quantization_config=BitsAndBytesConfig(
1510
+ load_in_4bit=training_args.bits == 4,
1511
+ load_in_8bit=training_args.bits == 8,
1512
+ llm_int8_threshold=6.0,
1513
+ llm_int8_has_fp16_weight=False,
1514
+ bnb_4bit_compute_dtype=compute_dtype,
1515
+ bnb_4bit_use_double_quant=training_args.double_quant,
1516
+ bnb_4bit_quant_type=training_args.quant_type, # {'fp4', 'nf4'}
1517
+ ),
1518
+ )
1519
+ )
1520
+
1521
+ model, ref_model = get_model(model_args, training_args, bnb_model_from_pretrained_args)
1522
+ model.config.use_cache = False
1523
+
1524
+ if model_args.freeze_backbone:
1525
+ model.model.requires_grad_(False)
1526
+
1527
+ if training_args.bits in [4, 8]:
1528
+ from peft import prepare_model_for_kbit_training
1529
+
1530
+ model.config.torch_dtype = torch.float32 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)
1531
+ model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=training_args.gradient_checkpointing)
1532
+
1533
+ if training_args.gradient_checkpointing:
1534
+ if hasattr(model, "enable_input_require_grads"):
1535
+ model.enable_input_require_grads()
1536
+ if ref_model is not None:
1537
+ ref_model.enable_input_require_grads()
1538
+ else:
1539
+
1540
+ def make_inputs_require_grad(module, input, output):
1541
+ output.requires_grad_(True)
1542
+
1543
+ model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
1544
+
1545
+ if ref_model is not None:
1546
+ ref_model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
1547
+
1548
+ if training_args.lora_enable:
1549
+ from peft import LoraConfig, get_peft_model
1550
+
1551
+ lora_config = LoraConfig(
1552
+ r=training_args.lora_r,
1553
+ lora_alpha=training_args.lora_alpha,
1554
+ target_modules=find_all_linear_names(model),
1555
+ lora_dropout=training_args.lora_dropout,
1556
+ bias=training_args.lora_bias,
1557
+ task_type="CAUSAL_LM",
1558
+ )
1559
+ if training_args.bits == 16:
1560
+ if training_args.bf16:
1561
+ model.to(torch.bfloat16)
1562
+ if training_args.fp16:
1563
+ model.to(torch.float16)
1564
+ rank0_print("Adding LoRA adapters...")
1565
+ model = get_peft_model(model, lora_config)
1566
+
1567
+ if "mpt" in model_args.model_name_or_path:
1568
+ tokenizer = transformers.AutoTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=training_args.cache_dir, model_max_length=training_args.model_max_length, padding_side="right")
1569
+ elif "mistral" in model_args.model_name_or_path.lower() or "mixtral" in model_args.model_name_or_path.lower() or "zephyr" in model_args.model_name_or_path.lower():
1570
+ tokenizer = transformers.AutoTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=training_args.cache_dir, model_max_length=training_args.model_max_length, padding_side="left")
1571
+ elif "qwen" in model_args.model_name_or_path.lower():
1572
+ tokenizer = transformers.AutoTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=training_args.cache_dir, model_max_length=training_args.model_max_length, padding_side="right")
1573
+ else: # for all other models
1574
+ tokenizer = transformers.AutoTokenizer.from_pretrained(
1575
+ model_args.model_name_or_path,
1576
+ cache_dir=training_args.cache_dir,
1577
+ model_max_length=training_args.model_max_length,
1578
+ padding_side="right",
1579
+ use_fast=False,
1580
+ )
1581
+
1582
+ rank0_print(f"Prompt version: {model_args.version}")
1583
+ if model_args.version == "v0":
1584
+ if tokenizer.pad_token is None:
1585
+ smart_tokenizer_and_embedding_resize(
1586
+ special_tokens_dict=dict(pad_token="[PAD]"),
1587
+ tokenizer=tokenizer,
1588
+ model=model,
1589
+ )
1590
+ elif model_args.version == "v0.5":
1591
+ tokenizer.pad_token = tokenizer.unk_token
1592
+ else:
1593
+ if tokenizer.unk_token is not None:
1594
+ tokenizer.pad_token = tokenizer.unk_token
1595
+ if model_args.version in conversation_lib.conv_templates:
1596
+ conversation_lib.default_conversation = conversation_lib.conv_templates[model_args.version]
1597
+ else:
1598
+ conversation_lib.default_conversation = conversation_lib.conv_templates["vicuna_v1"]
1599
+
1600
+ if model_args.vision_tower is not None:
1601
+ model.get_model().initialize_vision_modules(model_args=model_args, fsdp=training_args.fsdp)
1602
+
1603
+ vision_tower = model.get_vision_tower()
1604
+ vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device)
1605
+
1606
+ data_args.image_processor = vision_tower.image_processor
1607
+ data_args.is_multimodal = True
1608
+
1609
+ model.config.image_aspect_ratio = data_args.image_aspect_ratio
1610
+ if data_args.image_grid_pinpoints is not None:
1611
+ # for input like "(1x1)...(3x3)", convert to [(1, 1), (2, 1), (3, 1), (1, 2), (2, 2), (3, 2), (1, 3), (2, 3), (3, 3)]
1612
+ if "x" in data_args.image_grid_pinpoints and "..." in data_args.image_grid_pinpoints:
1613
+ vis_encoder_size = data_args.image_processor.size[0]
1614
+ matches = re.findall(r"\((\d+)x(\d+)\)", data_args.image_grid_pinpoints)
1615
+ range_start = tuple(map(int, matches[0]))
1616
+ range_end = tuple(map(int, matches[-1]))
1617
+ grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
1618
+ grid_pinpoints = [[dim * vis_encoder_size for dim in pair] for pair in grid_pinpoints]
1619
+ data_args.image_grid_pinpoints = grid_pinpoints
1620
+ elif "x" in data_args.image_grid_pinpoints:
1621
+ vis_encoder_size = data_args.image_processor.size[0]
1622
+ assert vis_encoder_size in [224, 336, 384, 448, 512], "vis_encoder_size should be in [224, 336, 384, 448, 512]"
1623
+ grid_pinpoints = data_args.image_grid_pinpoints.replace(" ", "").replace("x", ",")[1:-1].split("),(")
1624
+ data_args.image_grid_pinpoints = [[int(x) * vis_encoder_size for x in item.split(",")] for item in grid_pinpoints]
1625
+ else:
1626
+ data_args.image_grid_pinpoints = ast.literal_eval(data_args.image_grid_pinpoints) # for backward compatibility
1627
+ model.config.image_grid_pinpoints = data_args.image_grid_pinpoints
1628
+ model.config.image_crop_resolution = data_args.image_crop_resolution
1629
+ model.config.image_split_resolution = data_args.image_split_resolution
1630
+ model.config.tokenizer_padding_side = tokenizer.padding_side
1631
+ model.config.tokenizer_model_max_length = tokenizer.model_max_length
1632
+
1633
+ ### Deciding train which part of the model
1634
+ if model_args.mm_tunable_parts is None: # traditional way of deciding which part to train
1635
+ model.config.tune_mm_mlp_adapter = training_args.tune_mm_mlp_adapter = model_args.tune_mm_mlp_adapter
1636
+ model.config.tune_mm_vision_resampler = training_args.tune_mm_vision_resampler = model_args.tune_mm_vision_resampler
1637
+ if model_args.tune_mm_mlp_adapter or model_args.tune_mm_vision_resampler:
1638
+ model.requires_grad_(False)
1639
+ if model_args.tune_mm_mlp_adapter:
1640
+ for p in model.get_model().mm_projector.parameters():
1641
+ p.requires_grad = True
1642
+ if model_args.tune_mm_vision_resampler:
1643
+ for p in model.get_model().vision_resampler.parameters():
1644
+ p.requires_grad = True
1645
+
1646
+ model.config.freeze_mm_mlp_adapter = training_args.freeze_mm_mlp_adapter
1647
+ if training_args.freeze_mm_mlp_adapter:
1648
+ for p in model.get_model().mm_projector.parameters():
1649
+ p.requires_grad = False
1650
+
1651
+ model.config.freeze_mm_vision_resampler = training_args.freeze_mm_vision_resampler
1652
+ if training_args.freeze_mm_vision_resampler:
1653
+ for p in model.get_model().vision_resampler.parameters():
1654
+ p.requires_grad = False
1655
+
1656
+ model.config.unfreeze_mm_vision_tower = model_args.unfreeze_mm_vision_tower
1657
+ if model_args.unfreeze_mm_vision_tower:
1658
+ vision_tower.requires_grad_(True)
1659
+ else:
1660
+ vision_tower.requires_grad_(False)
1661
+
1662
+ else:
1663
+ rank0_print(f"Using mm_tunable_parts: {model_args.mm_tunable_parts}")
1664
+ model.config.mm_tunable_parts = training_args.mm_tunable_parts = model_args.mm_tunable_parts
1665
+ # Set the entire model to not require gradients by default
1666
+ model.requires_grad_(False)
1667
+ vision_tower.requires_grad_(False)
1668
+ model.get_model().mm_projector.requires_grad_(False)
1669
+ model.get_model().vision_resampler.requires_grad_(False)
1670
+ # Parse the mm_tunable_parts to decide which parts to unfreeze
1671
+ tunable_parts = model_args.mm_tunable_parts.split(",")
1672
+ if "mm_mlp_adapter" in tunable_parts:
1673
+ for p in model.get_model().mm_projector.parameters():
1674
+ p.requires_grad = True
1675
+ if "mm_vision_resampler" in tunable_parts:
1676
+ for p in model.get_model().vision_resampler.parameters():
1677
+ p.requires_grad = True
1678
+ if "mm_vision_tower" in tunable_parts:
1679
+ for name, param in model.named_parameters():
1680
+ if "vision_tower" in name:
1681
+ param.requires_grad_(True)
1682
+ if "mm_language_model" in tunable_parts:
1683
+ for name, param in model.named_parameters():
1684
+ if "vision_tower" not in name and "mm_projector" not in name and "vision_resampler" not in name:
1685
+ param.requires_grad_(True)
1686
+
1687
+ total_params = sum(p.ds_numel if hasattr(p, "ds_numel") else p.numel() for p in model.parameters())
1688
+ trainable_params = sum(p.ds_numel if hasattr(p, "ds_numel") else p.numel() for p in model.parameters() if p.requires_grad)
1689
+ rank0_print(f"Total parameters: ~{total_params/1e6:.2f} MB)")
1690
+ rank0_print(f"Trainable parameters: ~{trainable_params/1e6:.2f} MB)")
1691
+ if training_args.bits in [4, 8]:
1692
+ model.get_model().mm_projector.to(dtype=compute_dtype, device=training_args.device)
1693
+
1694
+ model.config.mm_use_im_start_end = data_args.mm_use_im_start_end = model_args.mm_use_im_start_end
1695
+ model.config.mm_projector_lr = training_args.mm_projector_lr
1696
+ model.config.mm_vision_tower_lr = training_args.mm_vision_tower_lr
1697
+ training_args.use_im_start_end = model_args.mm_use_im_start_end
1698
+ model.config.mm_use_im_patch_token = model_args.mm_use_im_patch_token
1699
+ model.initialize_vision_tokenizer(model_args, tokenizer=tokenizer)
1700
+
1701
+ if ref_model is not None:
1702
+ ref_model.get_model().initialize_vision_modules(model_args=model_args, fsdp=training_args.fsdp)
1703
+ ref_vision_tower = ref_model.get_vision_tower()
1704
+ ref_vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device)
1705
+ ref_model.config.image_aspect_ratio = data_args.image_aspect_ratio
1706
+ ref_model.config.image_grid_pinpoints = data_args.image_grid_pinpoints
1707
+ ref_model.config.image_crop_resolution = data_args.image_crop_resolution
1708
+ ref_model.config.image_split_resolution = data_args.image_split_resolution
1709
+ ref_model.config.tokenizer_padding_side = tokenizer.padding_side
1710
+ ref_model.config.tokenizer_model_max_length = tokenizer.model_max_length
1711
+ ref_model.config.mm_use_im_start_end = data_args.mm_use_im_start_end
1712
+ ref_model.config.mm_use_im_patch_token = model_args.mm_use_im_patch_token
1713
+ ref_model.initialize_vision_tokenizer(model_args, tokenizer=tokenizer)
1714
+ parameter_names = [n for n, _ in ref_model.named_parameters()]
1715
+ for param_name in parameter_names:
1716
+ param = ref_model.get_parameter(param_name)
1717
+ param.requires_grad = False
1718
+ ref_model.eval()
1719
+
1720
+ if training_args.bits in [4, 8]:
1721
+ from peft.tuners.lora import LoraLayer
1722
+
1723
+ for name, module in model.named_modules():
1724
+ if isinstance(module, LoraLayer):
1725
+ if training_args.bf16:
1726
+ module = module.to(torch.bfloat16)
1727
+ if "norm" in name:
1728
+ module = module.to(torch.float32)
1729
+ if "lm_head" in name or "embed_tokens" in name:
1730
+ if hasattr(module, "weight"):
1731
+ if training_args.bf16 and module.weight.dtype == torch.float32:
1732
+ module = module.to(torch.bfloat16)
1733
+
1734
+ train_dataset = make_dpo_data_module(tokenizer=tokenizer, data_args=data_args)
1735
+ data_collator = DPODataCollator(
1736
+ tokenizer,
1737
+ label_pad_token_id=IGNORE_INDEX,
1738
+ pad_token_id=tokenizer.pad_token_id,
1739
+ )
1740
+
1741
+ trainer = LLaVADPOTrainer(
1742
+ model,
1743
+ ref_model,
1744
+ args=training_args,
1745
+ dpo_alpha=training_args.dpo_alpha,
1746
+ beta=training_args.beta,
1747
+ gamma=training_args.gamma,
1748
+ train_dataset=train_dataset,
1749
+ eval_dataset=None,
1750
+ data_collator=data_collator,
1751
+ tokenizer=tokenizer,
1752
+ max_length=training_args.model_max_length,
1753
+ generate_during_eval=False, # training_args.generate_during_eval,
1754
+ precompute_ref_log_probs=training_args.precompute_ref_log_probs,
1755
+ )
1756
+
1757
+ if list(pathlib.Path(training_args.output_dir).glob("checkpoint-*")):
1758
+ trainer.train(resume_from_checkpoint=True)
1759
+ else:
1760
+ trainer.train()
1761
+ trainer.save_state()
1762
+
1763
+ model.config.use_cache = True
1764
+
1765
+ if training_args.lora_enable:
1766
+ state_dict = get_peft_state_maybe_zero_3(model.named_parameters(), training_args.lora_bias)
1767
+ non_lora_state_dict = get_peft_state_non_lora_maybe_zero_3(model.named_parameters())
1768
+ if training_args.local_rank == 0 or training_args.local_rank == -1:
1769
+ if hasattr(model, "config"):
1770
+ model.config.save_pretrained(training_args.output_dir)
1771
+ if hasattr(model, "generation_config"):
1772
+ model.generation_config.save_pretrained(training_args.output_dir)
1773
+ model.save_pretrained(training_args.output_dir, state_dict=state_dict)
1774
+ torch.save(non_lora_state_dict, os.path.join(training_args.output_dir, "non_lora_trainables.bin"))
1775
+ else:
1776
+ safe_save_model_for_hf_trainer(trainer=trainer, output_dir=training_args.output_dir)
1777
+
1778
+ rank0_print(f"Model saved to {training_args.output_dir}")
1779
+
1780
+
1781
+ if __name__ == "__main__":
1782
+ train()
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/train/train_mem.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from llava.train.train import train
2
+
3
+ if __name__ == "__main__":
4
+ train()
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/llava/utils.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import logging
3
+ import logging.handlers
4
+ import os
5
+ import sys
6
+ import numpy as np
7
+
8
+ import requests
9
+
10
+ from llava.constants import LOGDIR
11
+
12
+ server_error_msg = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**"
13
+ moderation_msg = "I am sorry. Your input may violate our content moderation guidelines. Please avoid using harmful or offensive content."
14
+
15
+ handler = None
16
+
17
+ import torch.distributed as dist
18
+
19
+ try:
20
+ import av
21
+ from decord import VideoReader, cpu
22
+ except ImportError:
23
+ print("Please install pyav to use video processing functions.")
24
+
25
+ def process_video_with_decord(video_file, data_args):
26
+ vr = VideoReader(video_file, ctx=cpu(0), num_threads=1)
27
+ total_frame_num = len(vr)
28
+ video_time = total_frame_num / vr.get_avg_fps()
29
+ avg_fps = round(vr.get_avg_fps() / data_args.video_fps)
30
+ frame_idx = [i for i in range(0, total_frame_num, avg_fps)]
31
+ frame_time = [i/avg_fps for i in frame_idx]
32
+
33
+
34
+ if data_args.frames_upbound > 0:
35
+ if len(frame_idx) > data_args.frames_upbound or data_args.force_sample:
36
+ uniform_sampled_frames = np.linspace(0, total_frame_num - 1, data_args.frames_upbound, dtype=int)
37
+ frame_idx = uniform_sampled_frames.tolist()
38
+ frame_time = [i/vr.get_avg_fps() for i in frame_idx]
39
+
40
+ video = vr.get_batch(frame_idx).asnumpy()
41
+ frame_time = ",".join([f"{i:.2f}s" for i in frame_time])
42
+
43
+ num_frames_to_sample = num_frames = len(frame_idx)
44
+ # https://github.com/dmlc/decord/issues/208
45
+ vr.seek(0)
46
+ return video, video_time, frame_time, num_frames_to_sample
47
+
48
+ def process_video_with_pyav(video_file, data_args):
49
+ container = av.open(video_file)
50
+ # !!! This is the only difference. Using auto threading
51
+ container.streams.video[0].thread_type = "AUTO"
52
+
53
+ video_frames = []
54
+ for packet in container.demux():
55
+ if packet.stream.type == 'video':
56
+ for frame in packet.decode():
57
+ video_frames.append(frame)
58
+ total_frame_num = len(video_frames)
59
+ video_time = video_frames[-1].time
60
+ avg_fps = round(total_frame_num / video_time / data_args.video_fps)
61
+ frame_idx = [i for i in range(0, total_frame_num, avg_fps)]
62
+
63
+ if data_args.frames_upbound > 0:
64
+ if len(frame_idx) > data_args.frames_upbound:
65
+ uniform_sampled_frames = np.linspace(0, total_frame_num - 1, data_args.frames_upbound, dtype=int)
66
+ frame_idx = uniform_sampled_frames.tolist()
67
+
68
+
69
+ frames = [video_frames[i] for i in frame_idx]
70
+ return np.stack([x.to_ndarray(format="rgb24") for x in frames])
71
+
72
+
73
+ def rank0_print(*args):
74
+ if dist.is_initialized():
75
+ if dist.get_rank() == 0:
76
+ print(f"Rank {dist.get_rank()}: ", *args)
77
+ else:
78
+ print(*args)
79
+
80
+
81
+ def rank_print(*args):
82
+ if dist.is_initialized():
83
+ print(f"Rank {dist.get_rank()}: ", *args)
84
+ else:
85
+ print(*args)
86
+
87
+ def build_logger(logger_name, logger_filename):
88
+ global handler
89
+
90
+ formatter = logging.Formatter(
91
+ fmt="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
92
+ datefmt="%Y-%m-%d %H:%M:%S",
93
+ )
94
+
95
+ # Set the format of root handlers
96
+ if not logging.getLogger().handlers:
97
+ logging.basicConfig(level=logging.INFO)
98
+ logging.getLogger().handlers[0].setFormatter(formatter)
99
+
100
+ # Redirect stdout and stderr to loggers
101
+ stdout_logger = logging.getLogger("stdout")
102
+ stdout_logger.setLevel(logging.INFO)
103
+ sl = StreamToLogger(stdout_logger, logging.INFO)
104
+ sys.stdout = sl
105
+
106
+ stderr_logger = logging.getLogger("stderr")
107
+ stderr_logger.setLevel(logging.ERROR)
108
+ sl = StreamToLogger(stderr_logger, logging.ERROR)
109
+ sys.stderr = sl
110
+
111
+ # Get logger
112
+ logger = logging.getLogger(logger_name)
113
+ logger.setLevel(logging.INFO)
114
+
115
+ # Add a file handler for all loggers
116
+ if handler is None:
117
+ os.makedirs(LOGDIR, exist_ok=True)
118
+ filename = os.path.join(LOGDIR, logger_filename)
119
+ handler = logging.handlers.TimedRotatingFileHandler(filename, when="D", utc=True)
120
+ handler.setFormatter(formatter)
121
+
122
+ for name, item in logging.root.manager.loggerDict.items():
123
+ if isinstance(item, logging.Logger):
124
+ item.addHandler(handler)
125
+
126
+ return logger
127
+
128
+
129
+ class StreamToLogger(object):
130
+ """
131
+ Fake file-like stream object that redirects writes to a logger instance.
132
+ """
133
+
134
+ def __init__(self, logger, log_level=logging.INFO):
135
+ self.terminal = sys.stdout
136
+ self.logger = logger
137
+ self.log_level = log_level
138
+ self.linebuf = ""
139
+
140
+ def __getattr__(self, attr):
141
+ return getattr(self.terminal, attr)
142
+
143
+ def write(self, buf):
144
+ temp_linebuf = self.linebuf + buf
145
+ self.linebuf = ""
146
+ for line in temp_linebuf.splitlines(True):
147
+ # From the io.TextIOWrapper docs:
148
+ # On output, if newline is None, any '\n' characters written
149
+ # are translated to the system default line separator.
150
+ # By default sys.stdout.write() expects '\n' newlines and then
151
+ # translates them so this is still cross platform.
152
+ if line[-1] == "\n":
153
+ self.logger.log(self.log_level, line.rstrip())
154
+ else:
155
+ self.linebuf += line
156
+
157
+ def flush(self):
158
+ if self.linebuf != "":
159
+ self.logger.log(self.log_level, self.linebuf.rstrip())
160
+ self.linebuf = ""
161
+
162
+
163
+ def disable_torch_init():
164
+ """
165
+ Disable the redundant torch default initialization to accelerate model creation.
166
+ """
167
+ import torch
168
+
169
+ setattr(torch.nn.Linear, "reset_parameters", lambda self: None)
170
+ setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None)
171
+
172
+
173
+ def violates_moderation(text):
174
+ """
175
+ Check whether the text violates OpenAI moderation API.
176
+ """
177
+ url = "https://api.openai.com/v1/moderations"
178
+ headers = {"Content-Type": "application/json", "Authorization": "Bearer " + os.environ["OPENAI_API_KEY"]}
179
+ text = text.replace("\n", "")
180
+ data = "{" + '"input": ' + f'"{text}"' + "}"
181
+ data = data.encode("utf-8")
182
+ try:
183
+ ret = requests.post(url, headers=headers, data=data, timeout=5)
184
+ flagged = ret.json()["results"][0]["flagged"]
185
+ except requests.exceptions.RequestException as e:
186
+ print(f"######################### Moderation Error: {e} #########################")
187
+ flagged = False
188
+ except KeyError as e:
189
+ print(f"######################### Moderation Error: {e} #########################")
190
+ flagged = False
191
+
192
+ return flagged
193
+
194
+
195
+ def pretty_print_semaphore(semaphore):
196
+ if semaphore is None:
197
+ return "None"
198
+ return f"Semaphore(value={semaphore._value}, locked={semaphore.locked()})"
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/playground/2d_hist.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from PIL import Image
4
+ from tqdm import tqdm
5
+ import matplotlib.pyplot as plt
6
+ import numpy as np
7
+ from multiprocessing import Pool
8
+ import functools
9
+ import argparse
10
+
11
+
12
+ def load_data(json_path):
13
+ with open(json_path, "r") as f:
14
+ return json.load(f)
15
+
16
+
17
+ def filter_data(data):
18
+ filtered_data = [item for item in data if "image" in item]
19
+ return filtered_data
20
+
21
+
22
+ def calculate_image_dimension(image_path, images_folder):
23
+ full_path = os.path.join(images_folder, image_path)
24
+ try:
25
+ with Image.open(full_path) as img:
26
+ width, height = img.size
27
+ return width, height
28
+ except Exception as e:
29
+ print(f"Error opening {full_path}: {e}")
30
+ return None, None
31
+
32
+
33
+ def calculate_image_dimensions_multiprocess(filtered_data, images_folder, num_processes=256):
34
+ image_paths = []
35
+ for item in filtered_data:
36
+ if isinstance(item["image"], list):
37
+ image_paths.extend(item["image"])
38
+ else:
39
+ image_paths.append(item["image"])
40
+
41
+ with Pool(num_processes) as p:
42
+ dimensions = list(
43
+ tqdm(
44
+ p.imap(functools.partial(calculate_image_dimension, images_folder=images_folder), image_paths),
45
+ total=len(image_paths),
46
+ desc="Calculating image dimensions",
47
+ )
48
+ )
49
+ widths, heights = zip(*[dim for dim in dimensions if dim[0] is not None])
50
+ return list(widths), list(heights)
51
+
52
+
53
+ def tokenize(text):
54
+ return text.split()
55
+
56
+
57
+ def calculate_tokenized_lengths(data):
58
+ lengths = []
59
+ for item in tqdm(data, desc="Tokenizing conversations"):
60
+ for conversation in item["conversations"]:
61
+ tokenized_value = tokenize(conversation["value"])
62
+ lengths.append(len(tokenized_value))
63
+ return lengths
64
+
65
+
66
+ def main():
67
+ parser = argparse.ArgumentParser(description="Process data for LLaVA_Next project.")
68
+ parser.add_argument(
69
+ "--json_path",
70
+ type=str,
71
+ help="Path to the JSON file containing data.",
72
+ default="/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/llava_ofa_DEMON-FULL.json",
73
+ )
74
+ parser.add_argument(
75
+ "--images_folder",
76
+ type=str,
77
+ default="/mnt/bn/vl-research/data/llava_data",
78
+ help="Path to the folder containing images.",
79
+ )
80
+ args = parser.parse_args()
81
+
82
+ llava_instruct_name = os.path.basename(args.json_path).replace(".json", "")
83
+ images_folder = args.images_folder
84
+
85
+ data = load_data(args.json_path)
86
+ filtered_data = filter_data(data)
87
+
88
+ print(f"Total data items: {len(data)}, Filtered data items: {len(filtered_data)}")
89
+ widths, heights = calculate_image_dimensions_multiprocess(filtered_data, images_folder)
90
+ max_width, max_height = max(widths), max(heights)
91
+ print(f"Max width: {max_width}, Max height: {max_height}")
92
+
93
+ tokenized_lengths = calculate_tokenized_lengths(filtered_data)
94
+
95
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 12))
96
+
97
+ # Plot 2D histogram
98
+ widths_bins = [min(widths), max(widths) + 1] if min(widths) == max(widths) else np.arange(min(widths), max(widths) + 100, 100)
99
+ heights_bins = [min(heights), max(heights) + 1] if min(heights) == max(heights) else np.arange(min(heights), max(heights) + 100, 100)
100
+
101
+ h, xedges, yedges, image = ax1.hist2d(widths, heights, bins=[widths_bins, heights_bins], cmap=plt.cm.jet, density=True)
102
+ fig.colorbar(image, ax=ax1)
103
+ ax1.set_xlabel("Width")
104
+ ax1.set_ylabel("Height")
105
+ ax1.set_title(
106
+ f"dist_{llava_instruct_name}_2d_w_h\nMax width: {max(widths)}, Max height: {max(heights)}",
107
+ fontsize=10,
108
+ )
109
+
110
+ # Plot histogram
111
+ hist, bin_edges = np.histogram(tokenized_lengths, bins=np.arange(0, max(tokenized_lengths) + 10, 10))
112
+ bins = np.arange(0, max(tokenized_lengths) + 10, 10)
113
+ ax2.bar(bin_edges[:-1], hist, width=7, edgecolor="black", log=True)
114
+
115
+ # Display every nth label on the x-axis
116
+ n = 8 # Adjust this value to control the number of labels displayed
117
+ ticks = bins[::n]
118
+ tick_labels = [int(tick) for tick in ticks]
119
+ ax2.set_xticks(ticks)
120
+ ax2.set_xticklabels(tick_labels, rotation=90, fontsize=8)
121
+
122
+ ax2.set_xlim(min(bin_edges), max(bin_edges))
123
+ ax2.set_xlabel("Tokenized Length")
124
+ ax2.set_ylabel("Count (log scale)")
125
+ ax2.set_title(f"dist_{llava_instruct_name}_tokenized_length", fontsize=8)
126
+
127
+ plt.tight_layout()
128
+ plt.savefig(f"./dist_{llava_instruct_name}_combined.png")
129
+
130
+
131
+ if __name__ == "__main__":
132
+ main()
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/playground/data_checker.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from tqdm import tqdm
4
+ from multiprocessing import Pool, cpu_count
5
+ import yaml
6
+
7
+
8
+ class DataProcessor:
9
+ def __init__(self, file_path, image_root, video_root):
10
+ self.file_path = file_path
11
+ self.image_root = image_root
12
+ self.data = None
13
+ self.video_root = video_root
14
+ self.load_data()
15
+
16
+ def load_data(self):
17
+ if self.file_path.endswith(".json"):
18
+ with open(self.file_path, "r") as f:
19
+ self.data = json.load(f)
20
+ elif self.file_path.endswith(".yaml"):
21
+ with open(self.file_path, "r") as f:
22
+ self.data = yaml.safe_load(f)
23
+ elif self.file_path.endswith(".jsonl"):
24
+ with open(self.file_path, "r") as f:
25
+ self.data = [json.loads(line) for line in f.readlines()]
26
+ else:
27
+ raise ValueError("Unsupported file format")
28
+
29
+ def load_json_data(self, json_path):
30
+ if json_path.endswith(".jsonl"):
31
+ cur_data_dict = []
32
+ with open(json_path, "r") as json_file:
33
+ for line in json_file:
34
+ cur_data_dict.append(json.loads(line.strip()))
35
+ return cur_data_dict
36
+ elif json_path.endswith(".json"):
37
+ with open(json_path, "r") as f:
38
+ return json.load(f)
39
+ else:
40
+ raise ValueError("Unsupported file format")
41
+
42
+ def check_image_existence(self, data):
43
+ if "image" in data:
44
+ if type(data["image"]) == list:
45
+ images = data["image"]
46
+ else:
47
+ images = [data["image"]]
48
+
49
+ for image in images:
50
+ full_image_path = os.path.join(self.image_root, image)
51
+ if not os.path.exists(full_image_path):
52
+ print(f"WARNING!!! {full_image_path} not exists !!!")
53
+
54
+ if "video" in data:
55
+ full_video_path = os.path.join(self.video_root, data["video"])
56
+ if not os.path.exists(full_video_path):
57
+ print(f"WARNING!!! {full_video_path} not exists !!!")
58
+
59
+ # if data["conversations"][0]["value"].count("<image>") > 1:
60
+ # print(f"WARNING!!! {data['conversations'][0]['value']} has more than one <image> !!!")
61
+
62
+ def check_item_structure(self, item):
63
+ if not all(key in item for key in ["conversations"]):
64
+ print(f"WARNING!!! Item {item.get('id', 'unknown')} is missing required fields!")
65
+ return False
66
+
67
+ conversations = item["conversations"]
68
+ if not isinstance(conversations, list) or len(conversations) < 2 or len(conversations) % 2 != 0:
69
+ print(f"WARNING!!! Item {item['id']} has invalid conversations structure!")
70
+ return False
71
+
72
+ for i, conv in enumerate(conversations):
73
+ if not all(key in conv for key in ["from", "value"]):
74
+ print(f"WARNING!!! Item {item['id']} has invalid conversation format!")
75
+ return False
76
+
77
+ expected_from = "human" if i % 2 == 0 else "gpt"
78
+ if conv["from"] != expected_from:
79
+ print(f"WARNING!!! Item {item['id']} has incorrect conversation order!")
80
+ return False
81
+
82
+ return True
83
+
84
+ def check_image_and_structure(self, item):
85
+ if not self.check_item_structure(item):
86
+ return
87
+
88
+ # self.check_image_existence(item)
89
+
90
+ def process_images(self):
91
+ if isinstance(self.data, list):
92
+ args = [d for d in self.data]
93
+ with Pool(processes=cpu_count()) as pool:
94
+ list(tqdm(pool.imap(self.check_image_and_structure, args), total=len(self.data)))
95
+ elif isinstance(self.data, dict):
96
+ for d in self.data["datasets"]:
97
+ dd_json_path = d["json_path"]
98
+ data = self.load_json_data(dd_json_path)
99
+ args = [d for d in data]
100
+ with Pool(processes=cpu_count()) as pool:
101
+ list(tqdm(pool.imap(self.check_image_and_structure, args), total=len(data), desc=f"Processing {dd_json_path}"))
102
+
103
+ def count_items(self):
104
+ if isinstance(self.data, list): # Assuming JSON data loaded directly
105
+ return len(self.data)
106
+ elif isinstance(self.data, dict): # Assuming YAML data loaded
107
+ total_items_count = 0
108
+ for d in self.data["datasets"]:
109
+ dd_json_path = d["json_path"]
110
+ data = self.load_json_data(dd_json_path)
111
+ current_items_count = len(data)
112
+
113
+ sampling_strategy = d["sampling_strategy"]
114
+ try:
115
+ if sampling_strategy != "all":
116
+ percentage = float(sampling_strategy.split(":")[-1].replace("%", "")) / 100.0
117
+ else:
118
+ percentage = 1.0
119
+ except Exception as e:
120
+ print(f"Error: {e}")
121
+ percentage = 1.0
122
+
123
+ sampling_count = int(current_items_count * percentage)
124
+ total_items_count += sampling_count
125
+ print(f"{dd_json_path}: {sampling_count}")
126
+ return total_items_count
127
+
128
+ def stat_data(self):
129
+ if isinstance(self.data, dict):
130
+ cur_lens_list = []
131
+ single_image_count = 0
132
+ multiple_image_count = 0
133
+ video_count = 0
134
+ total_count = 0
135
+ text_count = 0
136
+ max_tokens_item = None
137
+ max_tokens = 0
138
+
139
+ for d in self.data["datasets"]:
140
+ dd_json_path = d["json_path"]
141
+ data = self.load_json_data(dd_json_path)
142
+ sampling_strategy = d["sampling_strategy"]
143
+
144
+ try:
145
+ if sampling_strategy != "all":
146
+ percentage = float(sampling_strategy.split(":")[-1].replace("%", "")) / 100.0
147
+ else:
148
+ percentage = 1.0
149
+ except Exception as e:
150
+ print(f"Error parsing sampling strategy: {e}")
151
+ percentage = 1.0
152
+
153
+ sampled_count = int(len(data) * percentage)
154
+ print(f"{dd_json_path}: {sampled_count} (sampled from {len(data)})")
155
+
156
+ for item in data[:sampled_count]:
157
+ conversations = item["conversations"]
158
+ cur_len = sum([len(conv["value"].split()) for conv in conversations])
159
+ cur_lens_list.append(cur_len)
160
+
161
+ if cur_len > max_tokens:
162
+ max_tokens = cur_len
163
+ max_tokens_item = item
164
+
165
+ total_count += 1
166
+ if "image" in item:
167
+ if isinstance(item["image"], list):
168
+ if len(item["image"]) > 1:
169
+ multiple_image_count += 1
170
+ else:
171
+ single_image_count += 1
172
+ else:
173
+ single_image_count += 1
174
+ elif "video" in item:
175
+ video_count += 1
176
+ else:
177
+ text_count += 1
178
+
179
+ print(f"Max length: {max(cur_lens_list)}, Min length: {min(cur_lens_list)}, Average length: {sum(cur_lens_list) / len(cur_lens_list)}")
180
+ print(f"Total items: {total_count}")
181
+ print(f"Text items: {text_count} ({text_count/total_count*100:.2f}%)")
182
+ print(f"Single image items: {single_image_count} ({single_image_count/total_count*100:.2f}%)")
183
+ print(f"Multiple image items: {multiple_image_count} ({multiple_image_count/total_count*100:.2f}%)")
184
+ print(f"Video items: {video_count} ({video_count/total_count*100:.2f}%)")
185
+
186
+ print("\nItem with the largest number of tokens:")
187
+ print(f"Token count: {max_tokens}")
188
+ print("Item content:")
189
+ print(json.dumps(max_tokens_item, indent=2))
190
+
191
+ def filter_data(self):
192
+ if isinstance(self.data, dict):
193
+ for d in self.data["datasets"]:
194
+ dd_json_path = d["json_path"]
195
+ print(f"Processing {dd_json_path}")
196
+ data = self.load_json_data(dd_json_path)
197
+
198
+ filtered_data = []
199
+ mismatch_data = []
200
+ mismatch_flag = False
201
+ for item in data:
202
+ try:
203
+ if "image" in item:
204
+ num_image = len(item["image"]) if isinstance(item["image"], list) else 1
205
+ else:
206
+ num_image = 0
207
+
208
+ if "video" in item:
209
+ num_video = len(item["video"]) if isinstance(item["video"], list) else 1
210
+ else:
211
+ num_video = 0
212
+
213
+ num_visuals = num_image + num_video
214
+ conv_text = ""
215
+ for conv in item["conversations"]:
216
+ conv_text += conv["value"]
217
+
218
+ num_img_token_appearance = conv_text.count("<image>")
219
+ if len(conv_text) == 0:
220
+ print(f"Conversation text is empty for {item}")
221
+
222
+ if num_img_token_appearance == num_visuals or num_img_token_appearance < num_visuals and len(conv_text) > 0:
223
+ filtered_data.append(item)
224
+ elif num_img_token_appearance > num_visuals:
225
+ item["num_img_token_appearance"] = num_img_token_appearance
226
+ item["num_visuals"] = num_visuals
227
+ mismatch_data.append(item)
228
+
229
+ if not mismatch_flag:
230
+ print(f"Data mismatch for {item}")
231
+
232
+ mismatch_flag = True
233
+ except Exception as e:
234
+ print(f"Error: {e}")
235
+ print()
236
+
237
+ if mismatch_flag:
238
+ print(f"Data mismatch for {dd_json_path}")
239
+
240
+ if len(filtered_data) < len(data):
241
+ saving_dd_json_path = dd_json_path.replace(".jsonl", f"fltd_{len(filtered_data)}.json").replace(".json", f"fltd_{len(filtered_data)}.json")
242
+ with open(saving_dd_json_path, "w") as f:
243
+ json.dump(filtered_data, f, indent=2)
244
+ print(f"Filtered data count: {len(filtered_data)}")
245
+ else:
246
+ pass
247
+
248
+ def stat_and_filter_data(self, threshold):
249
+ if isinstance(self.data, dict):
250
+ cur_lens_list = []
251
+ single_image_count = 0
252
+ multiple_image_count = 0
253
+ video_count = 0
254
+ total_count = 0
255
+ text_count = 0
256
+
257
+ for d in self.data["datasets"]:
258
+ dd_json_path = d["json_path"]
259
+ data = self.load_json_data(dd_json_path)
260
+ sampling_strategy = d["sampling_strategy"]
261
+ filtered_data = []
262
+
263
+ try:
264
+ if sampling_strategy != "all":
265
+ percentage = float(sampling_strategy.split(":")[-1].replace("%", "")) / 100.0
266
+ else:
267
+ percentage = 1.0
268
+ except Exception as e:
269
+ print(f"Error parsing sampling strategy: {e}")
270
+ percentage = 1.0
271
+
272
+ sampled_count = int(len(data) * percentage)
273
+ print(f"{dd_json_path}: {sampled_count} (sampled from {len(data)})")
274
+
275
+ save_flag = False
276
+ for item in data:
277
+ total_count += 1
278
+ conversations = item["conversations"]
279
+ filtered_conversations = []
280
+ current_token_count = 0
281
+
282
+ for i in range(0, len(conversations), 2):
283
+ if i + 1 < len(conversations):
284
+ human_conv = conversations[i]
285
+ gpt_conv = conversations[i + 1]
286
+ pair_tokens = len(human_conv["value"].split()) + len(gpt_conv["value"].split())
287
+
288
+ if current_token_count + pair_tokens <= threshold:
289
+ filtered_conversations.extend([human_conv, gpt_conv])
290
+ current_token_count += pair_tokens
291
+ else:
292
+ save_flag = True
293
+ break
294
+
295
+ if filtered_conversations:
296
+ item["conversations"] = filtered_conversations
297
+ cur_len = sum([len(conv["value"].split()) for conv in filtered_conversations])
298
+ cur_lens_list.append(cur_len)
299
+ filtered_data.append(item)
300
+
301
+ if "image" in item:
302
+ if isinstance(item["image"], list):
303
+ if len(item["image"]) > 1:
304
+ multiple_image_count += 1
305
+ else:
306
+ single_image_count += 1
307
+ else:
308
+ single_image_count += 1
309
+ elif "video" in item:
310
+ video_count += 1
311
+ else:
312
+ text_count += 1
313
+
314
+ # Save filtered data for each dataset
315
+ if filtered_data and save_flag:
316
+ if dd_json_path.endswith(".jsonl"):
317
+ output_file = dd_json_path.replace(".jsonl", f"_filtered_{threshold}tokens_{len(filtered_data)}.jsonl")
318
+ with open(output_file, "w") as f:
319
+ for item in filtered_data:
320
+ f.write(json.dumps(item) + "\n")
321
+ else:
322
+ output_file = dd_json_path.replace(".json", f"_filtered_{threshold}tokens_{len(filtered_data)}.json")
323
+ with open(output_file, "w") as f:
324
+ json.dump(filtered_data, f, indent=2)
325
+ print(f"Filtered data for {dd_json_path} saved to: {output_file}")
326
+
327
+ print(f"Max length: {max(cur_lens_list)}, Min length: {min(cur_lens_list)}, Average length: {sum(cur_lens_list) / len(cur_lens_list)}")
328
+ print(f"Total items: {total_count}")
329
+ print(f"Text items: {text_count} ({text_count/total_count*100:.2f}%)")
330
+ print(f"Single image items: {single_image_count} ({single_image_count/total_count*100:.2f}%)")
331
+ print(f"Multiple image items: {multiple_image_count} ({multiple_image_count/total_count*100:.2f}%)")
332
+ print(f"Video items: {video_count} ({video_count/total_count*100:.2f}%)")
333
+
334
+
335
+ def main(file_path, image_root, operation, video_root, threshold=None):
336
+ processor = DataProcessor(file_path, image_root, video_root)
337
+ if operation == "check":
338
+ processor.process_images()
339
+ elif operation == "count":
340
+ total_items = processor.count_items()
341
+ print(f"Total items: {total_items}")
342
+ elif operation == "filter":
343
+ processor.filter_data()
344
+ elif operation == "stat":
345
+ processor.stat_data()
346
+ elif operation == "stat_and_filter":
347
+ if threshold is None:
348
+ raise ValueError("Threshold must be provided for stat_and_filter operation")
349
+ processor.stat_and_filter_data(threshold)
350
+ else:
351
+ raise ValueError("Unsupported operation")
352
+
353
+
354
+ if __name__ == "__main__":
355
+ import argparse
356
+
357
+ parser = argparse.ArgumentParser()
358
+ parser.add_argument("--file_path", type=str, default="/mnt/bn/vl-research/workspace/boli01/projects/LLaVA_Next/scripts/i18n/scale_llms/next_continual.yaml")
359
+ parser.add_argument("--image_root", type=str, default="/mnt/bn/vl-research/data/llava_data")
360
+ parser.add_argument("--video_root", type=str, default="/mnt/bn/vl-research/data/llava_video")
361
+ parser.add_argument("--operation", type=str, default="filter")
362
+ parser.add_argument("--threshold", type=int, default=None, help="Threshold for stat_and_filter operation")
363
+ args = parser.parse_args()
364
+ main(args.file_path, args.image_root, args.operation, args.video_root, args.threshold)
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/playground/demo/video_demo.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_anyres_image,tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria
9
+
10
+ import json
11
+ import os
12
+ import math
13
+ from tqdm import tqdm
14
+ from decord import VideoReader, cpu
15
+
16
+ from transformers import AutoConfig
17
+
18
+ import cv2
19
+ import base64
20
+ import openai
21
+
22
+ from PIL import Image
23
+
24
+
25
+
26
+ import numpy as np
27
+
28
+ def split_list(lst, n):
29
+ """Split a list into n (roughly) equal-sized chunks"""
30
+ chunk_size = math.ceil(len(lst) / n) # integer division
31
+ return [lst[i : i + chunk_size] for i in range(0, len(lst), chunk_size)]
32
+
33
+
34
+ def get_chunk(lst, n, k):
35
+ chunks = split_list(lst, n)
36
+ return chunks[k]
37
+
38
+
39
+ def parse_args():
40
+ """
41
+ Parse command-line arguments.
42
+ """
43
+ parser = argparse.ArgumentParser()
44
+
45
+ # Define the command-line arguments
46
+ parser.add_argument("--video_path", help="Path to the video files.", required=True)
47
+ parser.add_argument("--output_dir", help="Directory to save the model results JSON.", required=True)
48
+ parser.add_argument("--output_name", help="Name of the file for storing results JSON.", required=True)
49
+ parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
50
+ parser.add_argument("--model-base", type=str, default=None)
51
+ parser.add_argument("--conv-mode", type=str, default=None)
52
+ parser.add_argument("--chunk-idx", type=int, default=0)
53
+ parser.add_argument("--mm_resampler_type", type=str, default="spatial_pool")
54
+ parser.add_argument("--mm_spatial_pool_stride", type=int, default=4)
55
+ parser.add_argument("--mm_spatial_pool_out_channels", type=int, default=1024)
56
+ parser.add_argument("--mm_spatial_pool_mode", type=str, default="average")
57
+ parser.add_argument("--image_aspect_ratio", type=str, default="anyres")
58
+ parser.add_argument("--image_grid_pinpoints", type=str, default="[(224, 448), (224, 672), (224, 896), (448, 448), (448, 224), (672, 224), (896, 224)]")
59
+ parser.add_argument("--mm_patch_merge_type", type=str, default="spatial_unpad")
60
+ parser.add_argument("--overwrite", type=lambda x: (str(x).lower() == 'true'), default=True)
61
+ parser.add_argument("--for_get_frames_num", type=int, default=4)
62
+ parser.add_argument("--load_8bit", type=lambda x: (str(x).lower() == 'true'), default=False)
63
+ parser.add_argument("--prompt", type=str, default=None)
64
+ parser.add_argument("--api_key", type=str, help="OpenAI API key")
65
+ parser.add_argument("--mm_newline_position", type=str, default="no_token")
66
+ parser.add_argument("--force_sample", type=lambda x: (str(x).lower() == 'true'), default=False)
67
+ parser.add_argument("--add_time_instruction", type=str, default=False)
68
+ return parser.parse_args()
69
+
70
+ def load_video(video_path,args):
71
+ if args.for_get_frames_num == 0:
72
+ return np.zeros((1, 336, 336, 3))
73
+ vr = VideoReader(video_path, ctx=cpu(0),num_threads=1)
74
+ total_frame_num = len(vr)
75
+ video_time = total_frame_num / vr.get_avg_fps()
76
+ fps = round(vr.get_avg_fps())
77
+ frame_idx = [i for i in range(0, len(vr), fps)]
78
+ frame_time = [i/fps for i in frame_idx]
79
+ if len(frame_idx) > args.for_get_frames_num or args.force_sample:
80
+ sample_fps = args.for_get_frames_num
81
+ uniform_sampled_frames = np.linspace(0, total_frame_num - 1, sample_fps, dtype=int)
82
+ frame_idx = uniform_sampled_frames.tolist()
83
+ frame_time = [i/vr.get_avg_fps() for i in frame_idx]
84
+ frame_time = ",".join([f"{i:.2f}s" for i in frame_time])
85
+ spare_frames = vr.get_batch(frame_idx).asnumpy()
86
+ # import pdb;pdb.set_trace()
87
+
88
+ return spare_frames,frame_time,video_time
89
+
90
+
91
+
92
+
93
+ def load_video_base64(path):
94
+ video = cv2.VideoCapture(path)
95
+
96
+ base64Frames = []
97
+ while video.isOpened():
98
+ success, frame = video.read()
99
+ if not success:
100
+ break
101
+ _, buffer = cv2.imencode(".jpg", frame)
102
+ base64Frames.append(base64.b64encode(buffer).decode("utf-8"))
103
+
104
+ video.release()
105
+ # print(len(base64Frames), "frames read.")
106
+ return base64Frames
107
+
108
+
109
+ def run_inference(args):
110
+ """
111
+ Run inference on ActivityNet QA DataSet using the Video-ChatGPT model.
112
+
113
+ Args:
114
+ args: Command-line arguments.
115
+ """
116
+ # Initialize the model
117
+ if "gpt4v" != args.model_path:
118
+ model_name = get_model_name_from_path(args.model_path)
119
+ # Set model configuration parameters if they exist
120
+ if args.overwrite == True:
121
+ overwrite_config = {}
122
+ overwrite_config["mm_spatial_pool_mode"] = args.mm_spatial_pool_mode
123
+ overwrite_config["mm_spatial_pool_stride"] = args.mm_spatial_pool_stride
124
+ overwrite_config["mm_newline_position"] = args.mm_newline_position
125
+
126
+ cfg_pretrained = AutoConfig.from_pretrained(args.model_path)
127
+
128
+ # import pdb;pdb.set_trace()
129
+ if "qwen" not in args.model_path.lower():
130
+ if "224" in cfg_pretrained.mm_vision_tower:
131
+ # suppose the length of text tokens is around 1000, from bo's report
132
+ least_token_number = args.for_get_frames_num*(16//args.mm_spatial_pool_stride)**2 + 1000
133
+ else:
134
+ least_token_number = args.for_get_frames_num*(24//args.mm_spatial_pool_stride)**2 + 1000
135
+
136
+ scaling_factor = math.ceil(least_token_number/4096)
137
+ if scaling_factor >= 2:
138
+ if "vicuna" in cfg_pretrained._name_or_path.lower():
139
+ print(float(scaling_factor))
140
+ overwrite_config["rope_scaling"] = {"factor": float(scaling_factor), "type": "linear"}
141
+ overwrite_config["max_sequence_length"] = 4096 * scaling_factor
142
+ overwrite_config["tokenizer_model_max_length"] = 4096 * scaling_factor
143
+
144
+ tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, load_8bit=args.load_8bit, overwrite_config=overwrite_config)
145
+ else:
146
+ tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name)
147
+ else:
148
+ pass
149
+
150
+ # import pdb;pdb.set_trace()
151
+ if getattr(model.config, "force_sample", None) is not None:
152
+ args.force_sample = model.config.force_sample
153
+ else:
154
+ args.force_sample = False
155
+
156
+ # import pdb;pdb.set_trace()
157
+
158
+ if getattr(model.config, "add_time_instruction", None) is not None:
159
+ args.add_time_instruction = model.config.add_time_instruction
160
+ else:
161
+ args.add_time_instruction = False
162
+
163
+ # Create the output directory if it doesn't exist
164
+ if not os.path.exists(args.output_dir):
165
+ os.makedirs(args.output_dir)
166
+
167
+ output_name = args.output_name
168
+ answers_file = os.path.join(args.output_dir, f"{output_name}.json")
169
+ ans_file = open(answers_file, "w")
170
+
171
+ video_path = args.video_path
172
+
173
+ all_video_pathes = []
174
+
175
+ # Check if the video_path is a directory or a file
176
+ if os.path.isdir(video_path):
177
+ # If it's a directory, loop over all files in the directory
178
+ for filename in os.listdir(video_path):
179
+ # Load the video file
180
+ cur_video_path = os.path.join(video_path, f"{filename}")
181
+ all_video_pathes.append(os.path.join(video_path, cur_video_path))
182
+ else:
183
+ # If it's a file, just process the video
184
+ all_video_pathes.append(video_path)
185
+
186
+ # import pdb;pdb.set_trace()
187
+ for video_path in all_video_pathes:
188
+
189
+ sample_set = {}
190
+ question = args.prompt
191
+ sample_set["Q"] = question
192
+ sample_set["video_name"] = video_path
193
+
194
+
195
+ # Check if the video exists
196
+ if os.path.exists(video_path):
197
+ if "gpt4v" != args.model_path:
198
+ video,frame_time,video_time = load_video(video_path, args)
199
+ video = image_processor.preprocess(video, return_tensors="pt")["pixel_values"].half().cuda()
200
+ video = [video]
201
+ else:
202
+ spare_frames,frame_time,video_time = load_video_base64(video_path)
203
+ interval = int(len(video) / args.for_get_frames_num)
204
+
205
+ # try:
206
+ # Run inference on the video and add the output to the list
207
+ if "gpt4v" != args.model_path:
208
+ qs = question
209
+ if args.add_time_instruction:
210
+ time_instruciton = f"The video lasts for {video_time:.2f} seconds, and {len(video[0])} frames are uniformly sampled from it. These frames are located at {frame_time}.Please answer the following questions related to this video."
211
+ qs = f'{time_instruciton}\n{qs}'
212
+ if model.config.mm_use_im_start_end:
213
+ qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + "\n" + qs
214
+ else:
215
+ qs = DEFAULT_IMAGE_TOKEN + "\n" + qs
216
+
217
+ conv = conv_templates[args.conv_mode].copy()
218
+ conv.append_message(conv.roles[0], qs)
219
+ conv.append_message(conv.roles[1], None)
220
+ prompt = conv.get_prompt()
221
+
222
+ input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).cuda()
223
+ if tokenizer.pad_token_id is None:
224
+ if "qwen" in tokenizer.name_or_path.lower():
225
+ print("Setting pad token to bos token for qwen model.")
226
+ tokenizer.pad_token_id = 151643
227
+
228
+ attention_masks = input_ids.ne(tokenizer.pad_token_id).long().cuda()
229
+
230
+ stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
231
+ keywords = [stop_str]
232
+ stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
233
+
234
+ cur_prompt = question
235
+ else:
236
+ prompt = question
237
+
238
+ system_error = ""
239
+
240
+ if "gpt4v" != args.model_path:
241
+
242
+
243
+ with torch.inference_mode():
244
+ # model.update_prompt([[cur_prompt]])
245
+ # import pdb;pdb.set_trace()
246
+ # output_ids = model.generate(inputs=input_ids, images=video, attention_mask=attention_masks, modalities="video", do_sample=True, temperature=0.2, max_new_tokens=1024, use_cache=True, stopping_criteria=[stopping_criteria])
247
+ if "mistral" not in cfg_pretrained._name_or_path.lower():
248
+ output_ids = model.generate(inputs=input_ids, images=video, attention_mask=attention_masks, modalities="video", do_sample=False, temperature=0.0, max_new_tokens=1024, top_p=0.1,num_beams=1,use_cache=True, stopping_criteria=[stopping_criteria])
249
+ # output_ids = model.generate(inputs=input_ids, images=video, attention_mask=attention_masks, modalities="video", do_sample=True, temperature=0.2, max_new_tokens=1024, use_cache=True, stopping_criteria=[stopping_criteria])
250
+ else:
251
+ output_ids = model.generate(inputs=input_ids, images=video, attention_mask=attention_masks, modalities="video", do_sample=False, temperature=0.0, max_new_tokens=1024, top_p=0.1, num_beams=1, use_cache=True)
252
+ # output_ids = model.generate(inputs=input_ids, images=video, attention_mask=attention_masks, modalities="video", do_sample=True, temperature=0.2, max_new_tokens=1024, use_cache=True)
253
+ else:
254
+ openai.api_key = args.api_key # Your API key here
255
+
256
+ max_num_retries = 0
257
+ retry = 5
258
+ PROMPT_MESSAGES = [
259
+ {
260
+ "role": "user",
261
+ "content": [
262
+ f"These are frames from a video that I want to upload. Answer me one question of this video: {prompt}",
263
+ *map(lambda x: {"image": x, "resize": 336}, video[0::interval]),
264
+ ],
265
+ },
266
+ ]
267
+ params = {
268
+ "model": "gpt-4-vision-preview", #gpt-4-1106-vision-preview
269
+ "messages": PROMPT_MESSAGES,
270
+ "max_tokens": 1024,
271
+ }
272
+ sucess_flag=False
273
+ while max_num_retries < retry:
274
+ try:
275
+ result = openai.ChatCompletion.create(**params)
276
+ outputs = result.choices[0].message.content
277
+ sucess_flag = True
278
+ break
279
+ except Exception as inst :
280
+ if 'error' in dir(inst):
281
+ # import pdb;pdb.set_trace()
282
+ if inst.error.code == 'rate_limit_exceeded':
283
+ if "TPM" in inst.error.message:
284
+ time.sleep(30)
285
+ continue
286
+ else:
287
+ import pdb;pdb.set_trace()
288
+ elif inst.error.code == 'insufficient_quota':
289
+ print(f'insufficient_quota key')
290
+ exit()
291
+ elif inst.error.code == 'content_policy_violation':
292
+ print(f'content_policy_violation')
293
+ system_error = "content_policy_violation"
294
+
295
+ break
296
+ print('Find error message in response: ',str(inst.error.message), 'error code: ', str(inst.error.code))
297
+
298
+ continue
299
+ if not sucess_flag:
300
+ print(f'Calling OpenAI failed after retrying for {max_num_retries} times. Check the logs for details.')
301
+ exit()
302
+
303
+ if "gpt4v" != args.model_path:
304
+ outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
305
+ else:
306
+ print(len(video[0::interval]))
307
+
308
+ print(f"Question: {prompt}\n")
309
+ print(f"Response: {outputs}\n")
310
+
311
+ if "gpt4v" == args.model_path:
312
+ if system_error == 'content_policy_violation':
313
+ continue
314
+ elif system_error == "":
315
+ continue
316
+ else:
317
+ import pdb;pdb.set_trace()
318
+
319
+ # import pdb;pdb.set_trace()
320
+ if "mistral" not in cfg_pretrained._name_or_path.lower():
321
+ if outputs.endswith(stop_str):
322
+ outputs = outputs[: -len(stop_str)]
323
+
324
+ outputs = outputs.strip()
325
+
326
+ sample_set["pred"] = outputs
327
+ ans_file.write(json.dumps(sample_set, ensure_ascii=False) + "\n")
328
+ ans_file.flush()
329
+
330
+ ans_file.close()
331
+
332
+
333
+ if __name__ == "__main__":
334
+ args = parse_args()
335
+ run_inference(args)
video_gen_14d/third_party/VBench/VBench-2.0/vbench2/third_party/LLaVA_NeXT/playground/equal_splitter.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from math import ceil
3
+
4
+
5
+ def split_json_file(input_file, n_splits):
6
+ # Read the JSON file
7
+ with open(input_file, "r") as file:
8
+ data = json.load(file)
9
+
10
+ # Calculate the size of each split
11
+ total_items = len(data)
12
+ items_per_split = ceil(total_items / n_splits)
13
+
14
+ # Split the data and save into separate files
15
+ for i in range(n_splits):
16
+ start_index = i * items_per_split
17
+ end_index = min((i + 1) * items_per_split, total_items)
18
+ split_data = data[start_index:end_index]
19
+
20
+ # Write the split data to a new JSON file
21
+ with open(f"{input_file.split('.')[0]}_split_{i}.json", "w") as split_file:
22
+ json.dump(split_data, split_file, indent=4)
23
+
24
+
25
+ def main():
26
+ import argparse
27
+
28
+ parser = argparse.ArgumentParser(description="Split a JSON file into multiple parts.")
29
+ parser.add_argument("--input_file", type=str, help="The JSON file to split")
30
+ parser.add_argument("--n_splits", type=int, help="The number of splits")
31
+
32
+ args = parser.parse_args()
33
+
34
+ split_json_file(args.input_file, args.n_splits)
35
+
36
+
37
+ if __name__ == "__main__":
38
+ main()