Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- VISTA/llava/eval/table/results/test_sqa_llava_lcs_558k_sqa_12e_vicuna_v1_3_13b.json +0 -0
- VISTA/llava/model/language_model/__pycache__/llava_mpt.cpython-310.pyc +0 -0
- VISTA/llava/model/language_model/mpt/flash_attn_triton.py +484 -0
- VISTA/llava/model/language_model/mpt/norm.py +56 -0
- VISTA/llava/model/language_model/mpt/param_init_fns.py +181 -0
- VISTA/llava/model/multimodal_encoder/__pycache__/clip_encoder.cpython-310.pyc +0 -0
- VISTA/llava/model/multimodal_encoder/clip_encoder.py +135 -0
- VISTA/llava/model/multimodal_encoder/eva_clip/__pycache__/configuration_evaclip.cpython-310.pyc +0 -0
- VISTA/llava/model/multimodal_encoder/eva_clip/__pycache__/modeling_evaclip.cpython-310.pyc +0 -0
- VISTA/llava/model/multimodal_encoder/eva_clip/configuration_evaclip.py +425 -0
- VISTA/llava/model/multimodal_encoder/eva_clip/modeling_evaclip.py +1428 -0
- VISTA/llava/model/multimodal_encoder/intern_vit_6b/__pycache__/configuration_intern_vit.cpython-310.pyc +0 -0
- VISTA/llava/model/multimodal_encoder/intern_vit_6b/__pycache__/flash_attention.cpython-310.pyc +0 -0
- VISTA/llava/model/multimodal_encoder/intern_vit_6b/__pycache__/modeling_intern_vit.cpython-310.pyc +0 -0
- VISTA/llava/model/multimodal_encoder/intern_vit_6b/configuration_intern_vit.py +117 -0
- VISTA/llava/model/multimodal_encoder/intern_vit_6b/flash_attention.py +75 -0
- VISTA/llava/model/multimodal_encoder/intern_vit_6b/modeling_intern_vit.py +354 -0
- VISTA/llava/model/multimodal_encoder/internvl_14b/__init__.py +87 -0
- VISTA/llava/model/multimodal_encoder/internvl_14b/__pycache__/__init__.cpython-310.pyc +0 -0
- VISTA/llava/model/multimodal_encoder/internvl_14b/__pycache__/configuration_intern_vit.cpython-310.pyc +0 -0
- VISTA/llava/model/multimodal_encoder/internvl_14b/__pycache__/configuration_internvl.cpython-310.pyc +0 -0
- VISTA/llava/model/multimodal_encoder/internvl_14b/__pycache__/flash_attention.cpython-310.pyc +0 -0
- VISTA/llava/model/multimodal_encoder/internvl_14b/__pycache__/modeling_intern_vit.cpython-310.pyc +0 -0
- VISTA/llava/model/multimodal_encoder/internvl_14b/__pycache__/modeling_internvl.cpython-310.pyc +0 -0
- VISTA/llava/model/multimodal_encoder/internvl_14b/__pycache__/modeling_qllama.cpython-310.pyc +0 -0
- VISTA/llava/model/multimodal_encoder/internvl_14b/configuration_intern_vit.py +117 -0
- VISTA/llava/model/multimodal_encoder/internvl_14b/configuration_internvl.py +108 -0
- VISTA/llava/model/multimodal_encoder/internvl_14b/flash_attention.py +76 -0
- VISTA/llava/model/multimodal_encoder/internvl_14b/modeling_intern_vit.py +354 -0
- VISTA/llava/model/multimodal_encoder/internvl_14b/modeling_internvl.py +543 -0
- VISTA/llava/model/multimodal_encoder/internvl_14b/modeling_qllama.py +1073 -0
- VISTA/llava/model/multimodal_projector/__pycache__/builder.cpython-310.pyc +0 -0
- VISTA/llava/model/multimodal_projector/builder.py +84 -0
- VISTA/llava/serve/__init__.py +0 -0
- VISTA/llava/serve/cli.py +125 -0
- VISTA/llava/serve/controller.py +298 -0
- VISTA/llava/serve/examples/extreme_ironing.jpg +0 -0
- VISTA/llava/serve/examples/img1.jpg +0 -0
- VISTA/llava/serve/examples/img4.jpg +0 -0
- VISTA/llava/serve/examples/img5.jpg +0 -0
- VISTA/llava/serve/examples/img6.jpg +0 -0
- VISTA/llava/serve/examples/waterview.jpg +0 -0
- VISTA/llava/serve/gradio_web_server.py +455 -0
- VISTA/llava/serve/model_worker.py +285 -0
- VISTA/llava/serve/register_worker.py +26 -0
- VISTA/llava/serve/test_message.py +62 -0
- VISTA/llava/train/dist_utils.py +101 -0
- VISTA/llava/train/llama_flash_attn_monkey_patch.py +115 -0
- VISTA/llava/train/llava_trainer.py +180 -0
- VISTA/llava/train/train.py +993 -0
VISTA/llava/eval/table/results/test_sqa_llava_lcs_558k_sqa_12e_vicuna_v1_3_13b.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
VISTA/llava/model/language_model/__pycache__/llava_mpt.cpython-310.pyc
ADDED
|
Binary file (3.19 kB). View file
|
|
|
VISTA/llava/model/language_model/mpt/flash_attn_triton.py
ADDED
|
@@ -0,0 +1,484 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Copied from https://github.com/HazyResearch/flash-attention/blob/eff9fe6b8076df59d64d7a3f464696738a3c7c24/flash_attn/flash_attn_triton.py
|
| 3 |
+
update imports to use 'triton_pre_mlir'
|
| 4 |
+
|
| 5 |
+
*Experimental* implementation of FlashAttention in Triton.
|
| 6 |
+
Tested with triton==2.0.0.dev20221202.
|
| 7 |
+
Triton 2.0 has a new backend (MLIR) but seems like it doesn't yet work for head dimensions
|
| 8 |
+
other than 64:
|
| 9 |
+
https://github.com/openai/triton/blob/d376020f90002757eea3ea9475d4f7cfc2ec5ead/python/triton/ops/flash_attention.py#L207
|
| 10 |
+
We'll update this implementation with the new Triton backend once this is fixed.
|
| 11 |
+
|
| 12 |
+
We use the FlashAttention implementation from Phil Tillet a starting point.
|
| 13 |
+
https://github.com/openai/triton/blob/master/python/tutorials/06-fused-attention.py
|
| 14 |
+
|
| 15 |
+
Changes:
|
| 16 |
+
- Implement both causal and non-causal attention.
|
| 17 |
+
- Implement both self-attention and cross-attention.
|
| 18 |
+
- Support arbitrary seqlens (not just multiples of 128), for both forward and backward.
|
| 19 |
+
- Support all head dimensions up to 128 (not just 16, 32, 64, 128), for both forward and backward.
|
| 20 |
+
- Support attention bias.
|
| 21 |
+
- Speed up the forward pass a bit, and only store the LSE instead of m and l.
|
| 22 |
+
- Make the backward for d=128 much faster by reducing register spilling.
|
| 23 |
+
- Optionally parallelize the backward pass across seqlen_k, to deal with the case of
|
| 24 |
+
small batch size * nheads.
|
| 25 |
+
|
| 26 |
+
Caution:
|
| 27 |
+
- This is an *experimental* implementation. The forward pass should be quite robust but
|
| 28 |
+
I'm not 100% sure that the backward pass doesn't have race conditions (due to the Triton compiler).
|
| 29 |
+
- This implementation has only been tested on A100.
|
| 30 |
+
- If you plan to use headdim other than 64 and 128, you should test for race conditions
|
| 31 |
+
(due to the Triton compiler), as done in tests/test_flash_attn.py
|
| 32 |
+
"test_flash_attn_triton_race_condition". I've tested and fixed many race conditions
|
| 33 |
+
for different head dimensions (40, 48, 64, 128, 80, 88, 96), but I'm still not 100% confident
|
| 34 |
+
that there are none left for other head dimensions.
|
| 35 |
+
|
| 36 |
+
Differences between this Triton version and the CUDA version:
|
| 37 |
+
- Triton version doesn't support dropout.
|
| 38 |
+
- Triton forward is generally faster than CUDA forward, while Triton backward is
|
| 39 |
+
generally slower than CUDA backward. Overall Triton forward + backward is slightly slower
|
| 40 |
+
than CUDA forward + backward.
|
| 41 |
+
- Triton version doesn't support different sequence lengths in a batch (i.e., RaggedTensor/NestedTensor).
|
| 42 |
+
- Triton version supports attention bias, while CUDA version doesn't.
|
| 43 |
+
"""
|
| 44 |
+
import math
|
| 45 |
+
import torch
|
| 46 |
+
import triton_pre_mlir as triton
|
| 47 |
+
import triton_pre_mlir.language as tl
|
| 48 |
+
|
| 49 |
+
@triton.heuristics({'EVEN_M': lambda args: args['seqlen_q'] % args['BLOCK_M'] == 0, 'EVEN_N': lambda args: args['seqlen_k'] % args['BLOCK_N'] == 0, 'EVEN_HEADDIM': lambda args: args['headdim'] == args['BLOCK_HEADDIM']})
|
| 50 |
+
@triton.jit
|
| 51 |
+
def _fwd_kernel(Q, K, V, Bias, Out, Lse, TMP, softmax_scale, stride_qb, stride_qh, stride_qm, stride_kb, stride_kh, stride_kn, stride_vb, stride_vh, stride_vn, stride_bb, stride_bh, stride_bm, stride_ob, stride_oh, stride_om, nheads, seqlen_q, seqlen_k, seqlen_q_rounded, headdim, CACHE_KEY_SEQLEN_Q, CACHE_KEY_SEQLEN_K, BIAS_TYPE: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_HEADDIM: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr):
|
| 52 |
+
start_m = tl.program_id(0)
|
| 53 |
+
off_hb = tl.program_id(1)
|
| 54 |
+
off_b = off_hb // nheads
|
| 55 |
+
off_h = off_hb % nheads
|
| 56 |
+
offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
| 57 |
+
offs_n = tl.arange(0, BLOCK_N)
|
| 58 |
+
offs_d = tl.arange(0, BLOCK_HEADDIM)
|
| 59 |
+
q_ptrs = Q + off_b * stride_qb + off_h * stride_qh + (offs_m[:, None] * stride_qm + offs_d[None, :])
|
| 60 |
+
k_ptrs = K + off_b * stride_kb + off_h * stride_kh + (offs_n[:, None] * stride_kn + offs_d[None, :])
|
| 61 |
+
v_ptrs = V + off_b * stride_vb + off_h * stride_vh + (offs_n[:, None] * stride_vn + offs_d[None, :])
|
| 62 |
+
if BIAS_TYPE == 'vector':
|
| 63 |
+
b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + offs_n
|
| 64 |
+
elif BIAS_TYPE == 'matrix':
|
| 65 |
+
b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + (offs_m[:, None] * stride_bm + offs_n[None, :])
|
| 66 |
+
t_ptrs = TMP + off_hb * seqlen_q_rounded + offs_m
|
| 67 |
+
lse_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float('inf')
|
| 68 |
+
m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float('inf')
|
| 69 |
+
acc_o = tl.zeros([BLOCK_M, BLOCK_HEADDIM], dtype=tl.float32)
|
| 70 |
+
if EVEN_M & EVEN_N:
|
| 71 |
+
if EVEN_HEADDIM:
|
| 72 |
+
q = tl.load(q_ptrs)
|
| 73 |
+
else:
|
| 74 |
+
q = tl.load(q_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
|
| 75 |
+
elif EVEN_HEADDIM:
|
| 76 |
+
q = tl.load(q_ptrs, mask=offs_m[:, None] < seqlen_q, other=0.0)
|
| 77 |
+
else:
|
| 78 |
+
q = tl.load(q_ptrs, mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0)
|
| 79 |
+
end_n = seqlen_k if not IS_CAUSAL else tl.minimum((start_m + 1) * BLOCK_M, seqlen_k)
|
| 80 |
+
for start_n in range(0, end_n, BLOCK_N):
|
| 81 |
+
start_n = tl.multiple_of(start_n, BLOCK_N)
|
| 82 |
+
if EVEN_N & EVEN_M:
|
| 83 |
+
if EVEN_HEADDIM:
|
| 84 |
+
k = tl.load(k_ptrs + start_n * stride_kn)
|
| 85 |
+
else:
|
| 86 |
+
k = tl.load(k_ptrs + start_n * stride_kn, mask=offs_d[None, :] < headdim, other=0.0)
|
| 87 |
+
elif EVEN_HEADDIM:
|
| 88 |
+
k = tl.load(k_ptrs + start_n * stride_kn, mask=(start_n + offs_n)[:, None] < seqlen_k, other=0.0)
|
| 89 |
+
else:
|
| 90 |
+
k = tl.load(k_ptrs + start_n * stride_kn, mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0)
|
| 91 |
+
qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)
|
| 92 |
+
qk += tl.dot(q, k, trans_b=True)
|
| 93 |
+
if not EVEN_N:
|
| 94 |
+
qk += tl.where((start_n + offs_n)[None, :] < seqlen_k, 0, float('-inf'))
|
| 95 |
+
if IS_CAUSAL:
|
| 96 |
+
qk += tl.where(offs_m[:, None] >= (start_n + offs_n)[None, :], 0, float('-inf'))
|
| 97 |
+
if BIAS_TYPE != 'none':
|
| 98 |
+
if BIAS_TYPE == 'vector':
|
| 99 |
+
if EVEN_N:
|
| 100 |
+
bias = tl.load(b_ptrs + start_n).to(tl.float32)
|
| 101 |
+
else:
|
| 102 |
+
bias = tl.load(b_ptrs + start_n, mask=start_n + offs_n < seqlen_k, other=0.0).to(tl.float32)
|
| 103 |
+
bias = bias[None, :]
|
| 104 |
+
elif BIAS_TYPE == 'matrix':
|
| 105 |
+
if EVEN_M & EVEN_N:
|
| 106 |
+
bias = tl.load(b_ptrs + start_n).to(tl.float32)
|
| 107 |
+
else:
|
| 108 |
+
bias = tl.load(b_ptrs + start_n, mask=(offs_m[:, None] < seqlen_q) & ((start_n + offs_n)[None, :] < seqlen_k), other=0.0).to(tl.float32)
|
| 109 |
+
qk = qk * softmax_scale + bias
|
| 110 |
+
m_ij = tl.maximum(tl.max(qk, 1), lse_i)
|
| 111 |
+
p = tl.exp(qk - m_ij[:, None])
|
| 112 |
+
else:
|
| 113 |
+
m_ij = tl.maximum(tl.max(qk, 1) * softmax_scale, lse_i)
|
| 114 |
+
p = tl.exp(qk * softmax_scale - m_ij[:, None])
|
| 115 |
+
l_ij = tl.sum(p, 1)
|
| 116 |
+
acc_o_scale = tl.exp(m_i - m_ij)
|
| 117 |
+
tl.store(t_ptrs, acc_o_scale)
|
| 118 |
+
acc_o_scale = tl.load(t_ptrs)
|
| 119 |
+
acc_o = acc_o * acc_o_scale[:, None]
|
| 120 |
+
if EVEN_N & EVEN_M:
|
| 121 |
+
if EVEN_HEADDIM:
|
| 122 |
+
v = tl.load(v_ptrs + start_n * stride_vn)
|
| 123 |
+
else:
|
| 124 |
+
v = tl.load(v_ptrs + start_n * stride_vn, mask=offs_d[None, :] < headdim, other=0.0)
|
| 125 |
+
elif EVEN_HEADDIM:
|
| 126 |
+
v = tl.load(v_ptrs + start_n * stride_vn, mask=(start_n + offs_n)[:, None] < seqlen_k, other=0.0)
|
| 127 |
+
else:
|
| 128 |
+
v = tl.load(v_ptrs + start_n * stride_vn, mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0)
|
| 129 |
+
p = p.to(v.dtype)
|
| 130 |
+
acc_o += tl.dot(p, v)
|
| 131 |
+
m_i = m_ij
|
| 132 |
+
l_i_new = tl.exp(lse_i - m_ij) + l_ij
|
| 133 |
+
lse_i = m_ij + tl.log(l_i_new)
|
| 134 |
+
o_scale = tl.exp(m_i - lse_i)
|
| 135 |
+
tl.store(t_ptrs, o_scale)
|
| 136 |
+
o_scale = tl.load(t_ptrs)
|
| 137 |
+
acc_o = acc_o * o_scale[:, None]
|
| 138 |
+
start_m = tl.program_id(0)
|
| 139 |
+
offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
| 140 |
+
lse_ptrs = Lse + off_hb * seqlen_q_rounded + offs_m
|
| 141 |
+
tl.store(lse_ptrs, lse_i)
|
| 142 |
+
offs_d = tl.arange(0, BLOCK_HEADDIM)
|
| 143 |
+
out_ptrs = Out + off_b * stride_ob + off_h * stride_oh + (offs_m[:, None] * stride_om + offs_d[None, :])
|
| 144 |
+
if EVEN_M:
|
| 145 |
+
if EVEN_HEADDIM:
|
| 146 |
+
tl.store(out_ptrs, acc_o)
|
| 147 |
+
else:
|
| 148 |
+
tl.store(out_ptrs, acc_o, mask=offs_d[None, :] < headdim)
|
| 149 |
+
elif EVEN_HEADDIM:
|
| 150 |
+
tl.store(out_ptrs, acc_o, mask=offs_m[:, None] < seqlen_q)
|
| 151 |
+
else:
|
| 152 |
+
tl.store(out_ptrs, acc_o, mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim))
|
| 153 |
+
|
| 154 |
+
@triton.jit
|
| 155 |
+
def _bwd_preprocess_do_o_dot(Out, DO, Delta, stride_ob, stride_oh, stride_om, stride_dob, stride_doh, stride_dom, nheads, seqlen_q, seqlen_q_rounded, headdim, BLOCK_M: tl.constexpr, BLOCK_HEADDIM: tl.constexpr):
|
| 156 |
+
start_m = tl.program_id(0)
|
| 157 |
+
off_hb = tl.program_id(1)
|
| 158 |
+
off_b = off_hb // nheads
|
| 159 |
+
off_h = off_hb % nheads
|
| 160 |
+
offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
| 161 |
+
offs_d = tl.arange(0, BLOCK_HEADDIM)
|
| 162 |
+
o = tl.load(Out + off_b * stride_ob + off_h * stride_oh + offs_m[:, None] * stride_om + offs_d[None, :], mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0).to(tl.float32)
|
| 163 |
+
do = tl.load(DO + off_b * stride_dob + off_h * stride_doh + offs_m[:, None] * stride_dom + offs_d[None, :], mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0).to(tl.float32)
|
| 164 |
+
delta = tl.sum(o * do, axis=1)
|
| 165 |
+
tl.store(Delta + off_hb * seqlen_q_rounded + offs_m, delta)
|
| 166 |
+
|
| 167 |
+
@triton.jit
|
| 168 |
+
def _bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr):
|
| 169 |
+
if EVEN_N & EVEN_M:
|
| 170 |
+
if EVEN_HEADDIM:
|
| 171 |
+
tl.store(dv_ptrs, dv)
|
| 172 |
+
tl.store(dk_ptrs, dk)
|
| 173 |
+
else:
|
| 174 |
+
tl.store(dv_ptrs, dv, mask=offs_d[None, :] < headdim)
|
| 175 |
+
tl.store(dk_ptrs, dk, mask=offs_d[None, :] < headdim)
|
| 176 |
+
elif EVEN_HEADDIM:
|
| 177 |
+
tl.store(dv_ptrs, dv, mask=offs_n[:, None] < seqlen_k)
|
| 178 |
+
tl.store(dk_ptrs, dk, mask=offs_n[:, None] < seqlen_k)
|
| 179 |
+
else:
|
| 180 |
+
tl.store(dv_ptrs, dv, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim))
|
| 181 |
+
tl.store(dk_ptrs, dk, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim))
|
| 182 |
+
|
| 183 |
+
@triton.jit
|
| 184 |
+
def _bwd_kernel_one_col_block(start_n, Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qm, stride_kn, stride_vn, stride_bm, stride_dom, stride_dqm, stride_dkn, stride_dvn, seqlen_q, seqlen_k, headdim, ATOMIC_ADD: tl.constexpr, BIAS_TYPE: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_HEADDIM: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr):
|
| 185 |
+
begin_m = 0 if not IS_CAUSAL else start_n * BLOCK_N // BLOCK_M * BLOCK_M
|
| 186 |
+
offs_qm = begin_m + tl.arange(0, BLOCK_M)
|
| 187 |
+
offs_n = start_n * BLOCK_N + tl.arange(0, BLOCK_N)
|
| 188 |
+
offs_m = tl.arange(0, BLOCK_M)
|
| 189 |
+
offs_d = tl.arange(0, BLOCK_HEADDIM)
|
| 190 |
+
q_ptrs = Q + (offs_qm[:, None] * stride_qm + offs_d[None, :])
|
| 191 |
+
k_ptrs = K + (offs_n[:, None] * stride_kn + offs_d[None, :])
|
| 192 |
+
v_ptrs = V + (offs_n[:, None] * stride_vn + offs_d[None, :])
|
| 193 |
+
do_ptrs = DO + (offs_qm[:, None] * stride_dom + offs_d[None, :])
|
| 194 |
+
dq_ptrs = DQ + (offs_qm[:, None] * stride_dqm + offs_d[None, :])
|
| 195 |
+
if BIAS_TYPE == 'vector':
|
| 196 |
+
b_ptrs = Bias + offs_n
|
| 197 |
+
elif BIAS_TYPE == 'matrix':
|
| 198 |
+
b_ptrs = Bias + (offs_qm[:, None] * stride_bm + offs_n[None, :])
|
| 199 |
+
dv = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
|
| 200 |
+
dk = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
|
| 201 |
+
if begin_m >= seqlen_q:
|
| 202 |
+
dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :])
|
| 203 |
+
dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :])
|
| 204 |
+
_bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM)
|
| 205 |
+
return
|
| 206 |
+
if EVEN_N & EVEN_M:
|
| 207 |
+
if EVEN_HEADDIM:
|
| 208 |
+
k = tl.load(k_ptrs)
|
| 209 |
+
v = tl.load(v_ptrs)
|
| 210 |
+
else:
|
| 211 |
+
k = tl.load(k_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
|
| 212 |
+
v = tl.load(v_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
|
| 213 |
+
elif EVEN_HEADDIM:
|
| 214 |
+
k = tl.load(k_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
|
| 215 |
+
v = tl.load(v_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
|
| 216 |
+
else:
|
| 217 |
+
k = tl.load(k_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0)
|
| 218 |
+
v = tl.load(v_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0)
|
| 219 |
+
num_block_m = tl.cdiv(seqlen_q, BLOCK_M)
|
| 220 |
+
for start_m in range(begin_m, num_block_m * BLOCK_M, BLOCK_M):
|
| 221 |
+
start_m = tl.multiple_of(start_m, BLOCK_M)
|
| 222 |
+
offs_m_curr = start_m + offs_m
|
| 223 |
+
if EVEN_M & EVEN_HEADDIM:
|
| 224 |
+
q = tl.load(q_ptrs)
|
| 225 |
+
elif EVEN_HEADDIM:
|
| 226 |
+
q = tl.load(q_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0)
|
| 227 |
+
else:
|
| 228 |
+
q = tl.load(q_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0)
|
| 229 |
+
qk = tl.dot(q, k, trans_b=True)
|
| 230 |
+
if not EVEN_N:
|
| 231 |
+
qk = tl.where(offs_n[None, :] < seqlen_k, qk, float('-inf'))
|
| 232 |
+
if IS_CAUSAL:
|
| 233 |
+
qk = tl.where(offs_m_curr[:, None] >= offs_n[None, :], qk, float('-inf'))
|
| 234 |
+
if BIAS_TYPE != 'none':
|
| 235 |
+
tl.debug_barrier()
|
| 236 |
+
if BIAS_TYPE == 'vector':
|
| 237 |
+
if EVEN_N:
|
| 238 |
+
bias = tl.load(b_ptrs).to(tl.float32)
|
| 239 |
+
else:
|
| 240 |
+
bias = tl.load(b_ptrs, mask=offs_n < seqlen_k, other=0.0).to(tl.float32)
|
| 241 |
+
bias = bias[None, :]
|
| 242 |
+
elif BIAS_TYPE == 'matrix':
|
| 243 |
+
if EVEN_M & EVEN_N:
|
| 244 |
+
bias = tl.load(b_ptrs).to(tl.float32)
|
| 245 |
+
else:
|
| 246 |
+
bias = tl.load(b_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_n[None, :] < seqlen_k), other=0.0).to(tl.float32)
|
| 247 |
+
qk = qk * softmax_scale + bias
|
| 248 |
+
if not EVEN_M & EVEN_HEADDIM:
|
| 249 |
+
tl.debug_barrier()
|
| 250 |
+
lse_i = tl.load(LSE + offs_m_curr)
|
| 251 |
+
if BIAS_TYPE == 'none':
|
| 252 |
+
p = tl.exp(qk * softmax_scale - lse_i[:, None])
|
| 253 |
+
else:
|
| 254 |
+
p = tl.exp(qk - lse_i[:, None])
|
| 255 |
+
if EVEN_M & EVEN_HEADDIM:
|
| 256 |
+
do = tl.load(do_ptrs)
|
| 257 |
+
else:
|
| 258 |
+
do = tl.load(do_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0)
|
| 259 |
+
dv += tl.dot(p.to(do.dtype), do, trans_a=True)
|
| 260 |
+
if not EVEN_M & EVEN_HEADDIM:
|
| 261 |
+
tl.debug_barrier()
|
| 262 |
+
dp = tl.dot(do, v, trans_b=True)
|
| 263 |
+
if not EVEN_HEADDIM:
|
| 264 |
+
tl.debug_barrier()
|
| 265 |
+
Di = tl.load(D + offs_m_curr)
|
| 266 |
+
ds = (p * (dp - Di[:, None]) * softmax_scale).to(q.dtype)
|
| 267 |
+
dk += tl.dot(ds, q, trans_a=True)
|
| 268 |
+
if not EVEN_M & EVEN_HEADDIM:
|
| 269 |
+
tl.debug_barrier()
|
| 270 |
+
if not ATOMIC_ADD:
|
| 271 |
+
if EVEN_M & EVEN_HEADDIM:
|
| 272 |
+
dq = tl.load(dq_ptrs, eviction_policy='evict_last')
|
| 273 |
+
dq += tl.dot(ds, k)
|
| 274 |
+
tl.store(dq_ptrs, dq, eviction_policy='evict_last')
|
| 275 |
+
elif EVEN_HEADDIM:
|
| 276 |
+
dq = tl.load(dq_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0, eviction_policy='evict_last')
|
| 277 |
+
dq += tl.dot(ds, k)
|
| 278 |
+
tl.store(dq_ptrs, dq, mask=offs_m_curr[:, None] < seqlen_q, eviction_policy='evict_last')
|
| 279 |
+
else:
|
| 280 |
+
dq = tl.load(dq_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0, eviction_policy='evict_last')
|
| 281 |
+
dq += tl.dot(ds, k)
|
| 282 |
+
tl.store(dq_ptrs, dq, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), eviction_policy='evict_last')
|
| 283 |
+
else:
|
| 284 |
+
dq = tl.dot(ds, k)
|
| 285 |
+
if EVEN_M & EVEN_HEADDIM:
|
| 286 |
+
tl.atomic_add(dq_ptrs, dq)
|
| 287 |
+
elif EVEN_HEADDIM:
|
| 288 |
+
tl.atomic_add(dq_ptrs, dq, mask=offs_m_curr[:, None] < seqlen_q)
|
| 289 |
+
else:
|
| 290 |
+
tl.atomic_add(dq_ptrs, dq, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim))
|
| 291 |
+
dq_ptrs += BLOCK_M * stride_dqm
|
| 292 |
+
q_ptrs += BLOCK_M * stride_qm
|
| 293 |
+
do_ptrs += BLOCK_M * stride_dom
|
| 294 |
+
if BIAS_TYPE == 'matrix':
|
| 295 |
+
b_ptrs += BLOCK_M * stride_bm
|
| 296 |
+
dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :])
|
| 297 |
+
dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :])
|
| 298 |
+
_bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM)
|
| 299 |
+
|
| 300 |
+
def init_to_zero(name):
|
| 301 |
+
return lambda nargs: nargs[name].zero_()
|
| 302 |
+
|
| 303 |
+
@triton.autotune(configs=[triton.Config({'BLOCK_M': 128, 'BLOCK_N': 128, 'SEQUENCE_PARALLEL': False}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')), triton.Config({'BLOCK_M': 128, 'BLOCK_N': 128, 'SEQUENCE_PARALLEL': True}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ'))], key=['CACHE_KEY_SEQLEN_Q', 'CACHE_KEY_SEQLEN_K', 'BIAS_TYPE', 'IS_CAUSAL', 'BLOCK_HEADDIM'])
|
| 304 |
+
@triton.heuristics({'EVEN_M': lambda args: args['seqlen_q'] % args['BLOCK_M'] == 0, 'EVEN_N': lambda args: args['seqlen_k'] % args['BLOCK_N'] == 0, 'EVEN_HEADDIM': lambda args: args['headdim'] == args['BLOCK_HEADDIM']})
|
| 305 |
+
@triton.jit
|
| 306 |
+
def _bwd_kernel(Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qb, stride_qh, stride_qm, stride_kb, stride_kh, stride_kn, stride_vb, stride_vh, stride_vn, stride_bb, stride_bh, stride_bm, stride_dob, stride_doh, stride_dom, stride_dqb, stride_dqh, stride_dqm, stride_dkb, stride_dkh, stride_dkn, stride_dvb, stride_dvh, stride_dvn, nheads, seqlen_q, seqlen_k, seqlen_q_rounded, headdim, CACHE_KEY_SEQLEN_Q, CACHE_KEY_SEQLEN_K, BIAS_TYPE: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_HEADDIM: tl.constexpr, SEQUENCE_PARALLEL: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr):
|
| 307 |
+
off_hb = tl.program_id(1)
|
| 308 |
+
off_b = off_hb // nheads
|
| 309 |
+
off_h = off_hb % nheads
|
| 310 |
+
Q += off_b * stride_qb + off_h * stride_qh
|
| 311 |
+
K += off_b * stride_kb + off_h * stride_kh
|
| 312 |
+
V += off_b * stride_vb + off_h * stride_vh
|
| 313 |
+
DO += off_b * stride_dob + off_h * stride_doh
|
| 314 |
+
DQ += off_b * stride_dqb + off_h * stride_dqh
|
| 315 |
+
DK += off_b * stride_dkb + off_h * stride_dkh
|
| 316 |
+
DV += off_b * stride_dvb + off_h * stride_dvh
|
| 317 |
+
if BIAS_TYPE != 'none':
|
| 318 |
+
Bias += off_b * stride_bb + off_h * stride_bh
|
| 319 |
+
D += off_hb * seqlen_q_rounded
|
| 320 |
+
LSE += off_hb * seqlen_q_rounded
|
| 321 |
+
if not SEQUENCE_PARALLEL:
|
| 322 |
+
num_block_n = tl.cdiv(seqlen_k, BLOCK_N)
|
| 323 |
+
for start_n in range(0, num_block_n):
|
| 324 |
+
_bwd_kernel_one_col_block(start_n, Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qm, stride_kn, stride_vn, stride_bm, stride_dom, stride_dqm, stride_dkn, stride_dvn, seqlen_q, seqlen_k, headdim, ATOMIC_ADD=False, BIAS_TYPE=BIAS_TYPE, IS_CAUSAL=IS_CAUSAL, BLOCK_HEADDIM=BLOCK_HEADDIM, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM, BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N)
|
| 325 |
+
else:
|
| 326 |
+
start_n = tl.program_id(0)
|
| 327 |
+
_bwd_kernel_one_col_block(start_n, Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qm, stride_kn, stride_vn, stride_bm, stride_dom, stride_dqm, stride_dkn, stride_dvn, seqlen_q, seqlen_k, headdim, ATOMIC_ADD=True, BIAS_TYPE=BIAS_TYPE, IS_CAUSAL=IS_CAUSAL, BLOCK_HEADDIM=BLOCK_HEADDIM, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM, BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N)
|
| 328 |
+
|
| 329 |
+
def _flash_attn_forward(q, k, v, bias=None, causal=False, softmax_scale=None):
|
| 330 |
+
(batch, seqlen_q, nheads, d) = q.shape
|
| 331 |
+
(_, seqlen_k, _, _) = k.shape
|
| 332 |
+
assert k.shape == (batch, seqlen_k, nheads, d)
|
| 333 |
+
assert v.shape == (batch, seqlen_k, nheads, d)
|
| 334 |
+
assert d <= 128, 'FlashAttention only support head dimensions up to 128'
|
| 335 |
+
assert q.dtype == k.dtype == v.dtype, 'All tensors must have the same type'
|
| 336 |
+
assert q.dtype in [torch.float16, torch.bfloat16], 'Only support fp16 and bf16'
|
| 337 |
+
assert q.is_cuda and k.is_cuda and v.is_cuda
|
| 338 |
+
softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
|
| 339 |
+
has_bias = bias is not None
|
| 340 |
+
bias_type = 'none'
|
| 341 |
+
if has_bias:
|
| 342 |
+
assert bias.dtype in [q.dtype, torch.float]
|
| 343 |
+
assert bias.is_cuda
|
| 344 |
+
assert bias.dim() == 4
|
| 345 |
+
if bias.stride(-1) != 1:
|
| 346 |
+
bias = bias.contiguous()
|
| 347 |
+
if bias.shape[2:] == (1, seqlen_k):
|
| 348 |
+
bias_type = 'vector'
|
| 349 |
+
elif bias.shape[2:] == (seqlen_q, seqlen_k):
|
| 350 |
+
bias_type = 'matrix'
|
| 351 |
+
else:
|
| 352 |
+
raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k) or (seqlen_q, seqlen_k)')
|
| 353 |
+
bias = bias.expand(batch, nheads, seqlen_q, seqlen_k)
|
| 354 |
+
bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0)
|
| 355 |
+
seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
|
| 356 |
+
lse = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32)
|
| 357 |
+
tmp = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32)
|
| 358 |
+
o = torch.empty_like(q)
|
| 359 |
+
BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
|
| 360 |
+
BLOCK = 128
|
| 361 |
+
num_warps = 4 if d <= 64 else 8
|
| 362 |
+
grid = lambda META: (triton.cdiv(seqlen_q, META['BLOCK_M']), batch * nheads)
|
| 363 |
+
_fwd_kernel[grid](q, k, v, bias, o, lse, tmp, softmax_scale, q.stride(0), q.stride(2), q.stride(1), k.stride(0), k.stride(2), k.stride(1), v.stride(0), v.stride(2), v.stride(1), *bias_strides, o.stride(0), o.stride(2), o.stride(1), nheads, seqlen_q, seqlen_k, seqlen_q_rounded, d, seqlen_q // 32, seqlen_k // 32, bias_type, causal, BLOCK_HEADDIM, BLOCK_M=BLOCK, BLOCK_N=BLOCK, num_warps=num_warps, num_stages=1)
|
| 364 |
+
return (o, lse, softmax_scale)
|
| 365 |
+
|
| 366 |
+
def _flash_attn_backward(do, q, k, v, o, lse, dq, dk, dv, bias=None, causal=False, softmax_scale=None):
|
| 367 |
+
if do.stride(-1) != 1:
|
| 368 |
+
do = do.contiguous()
|
| 369 |
+
(batch, seqlen_q, nheads, d) = q.shape
|
| 370 |
+
(_, seqlen_k, _, _) = k.shape
|
| 371 |
+
assert d <= 128
|
| 372 |
+
seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
|
| 373 |
+
assert lse.shape == (batch, nheads, seqlen_q_rounded)
|
| 374 |
+
assert q.stride(-1) == k.stride(-1) == v.stride(-1) == o.stride(-1) == 1
|
| 375 |
+
assert dq.stride(-1) == dk.stride(-1) == dv.stride(-1) == 1
|
| 376 |
+
softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
|
| 377 |
+
dq_accum = torch.empty_like(q, dtype=torch.float32)
|
| 378 |
+
delta = torch.empty_like(lse)
|
| 379 |
+
BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
|
| 380 |
+
grid = lambda META: (triton.cdiv(seqlen_q, META['BLOCK_M']), batch * nheads)
|
| 381 |
+
_bwd_preprocess_do_o_dot[grid](o, do, delta, o.stride(0), o.stride(2), o.stride(1), do.stride(0), do.stride(2), do.stride(1), nheads, seqlen_q, seqlen_q_rounded, d, BLOCK_M=128, BLOCK_HEADDIM=BLOCK_HEADDIM)
|
| 382 |
+
has_bias = bias is not None
|
| 383 |
+
bias_type = 'none'
|
| 384 |
+
if has_bias:
|
| 385 |
+
assert bias.dtype in [q.dtype, torch.float]
|
| 386 |
+
assert bias.is_cuda
|
| 387 |
+
assert bias.dim() == 4
|
| 388 |
+
assert bias.stride(-1) == 1
|
| 389 |
+
if bias.shape[2:] == (1, seqlen_k):
|
| 390 |
+
bias_type = 'vector'
|
| 391 |
+
elif bias.shape[2:] == (seqlen_q, seqlen_k):
|
| 392 |
+
bias_type = 'matrix'
|
| 393 |
+
else:
|
| 394 |
+
raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k) or (seqlen_q, seqlen_k)')
|
| 395 |
+
bias = bias.expand(batch, nheads, seqlen_q, seqlen_k)
|
| 396 |
+
bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0)
|
| 397 |
+
grid = lambda META: (triton.cdiv(seqlen_k, META['BLOCK_N']) if META['SEQUENCE_PARALLEL'] else 1, batch * nheads)
|
| 398 |
+
_bwd_kernel[grid](q, k, v, bias, do, dq_accum, dk, dv, lse, delta, softmax_scale, q.stride(0), q.stride(2), q.stride(1), k.stride(0), k.stride(2), k.stride(1), v.stride(0), v.stride(2), v.stride(1), *bias_strides, do.stride(0), do.stride(2), do.stride(1), dq_accum.stride(0), dq_accum.stride(2), dq_accum.stride(1), dk.stride(0), dk.stride(2), dk.stride(1), dv.stride(0), dv.stride(2), dv.stride(1), nheads, seqlen_q, seqlen_k, seqlen_q_rounded, d, seqlen_q // 32, seqlen_k // 32, bias_type, causal, BLOCK_HEADDIM)
|
| 399 |
+
dq.copy_(dq_accum)
|
| 400 |
+
|
| 401 |
+
class FlashAttnQKVPackedFunc(torch.autograd.Function):
|
| 402 |
+
|
| 403 |
+
@staticmethod
|
| 404 |
+
def forward(ctx, qkv, bias=None, causal=False, softmax_scale=None):
|
| 405 |
+
"""
|
| 406 |
+
qkv: (batch, seqlen, 3, nheads, headdim)
|
| 407 |
+
bias: optional, shape broadcastible to (batch, nheads, seqlen, seqlen).
|
| 408 |
+
For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen).
|
| 409 |
+
ALiBi mask for non-causal would have shape (1, nheads, seqlen, seqlen)
|
| 410 |
+
"""
|
| 411 |
+
if qkv.stride(-1) != 1:
|
| 412 |
+
qkv = qkv.contiguous()
|
| 413 |
+
(o, lse, ctx.softmax_scale) = _flash_attn_forward(qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2], bias=bias, causal=causal, softmax_scale=softmax_scale)
|
| 414 |
+
ctx.save_for_backward(qkv, o, lse, bias)
|
| 415 |
+
ctx.causal = causal
|
| 416 |
+
return o
|
| 417 |
+
|
| 418 |
+
@staticmethod
|
| 419 |
+
def backward(ctx, do):
|
| 420 |
+
(qkv, o, lse, bias) = ctx.saved_tensors
|
| 421 |
+
assert not ctx.needs_input_grad[1], 'FlashAttention does not support bias gradient yet'
|
| 422 |
+
with torch.inference_mode():
|
| 423 |
+
dqkv = torch.empty_like(qkv)
|
| 424 |
+
_flash_attn_backward(do, qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2], o, lse, dqkv[:, :, 0], dqkv[:, :, 1], dqkv[:, :, 2], bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale)
|
| 425 |
+
return (dqkv, None, None, None)
|
| 426 |
+
flash_attn_qkvpacked_func = FlashAttnQKVPackedFunc.apply
|
| 427 |
+
|
| 428 |
+
class FlashAttnKVPackedFunc(torch.autograd.Function):
|
| 429 |
+
|
| 430 |
+
@staticmethod
|
| 431 |
+
def forward(ctx, q, kv, bias=None, causal=False, softmax_scale=None):
|
| 432 |
+
"""
|
| 433 |
+
q: (batch, seqlen_q, nheads, headdim)
|
| 434 |
+
kv: (batch, seqlen_k, 2, nheads, headdim)
|
| 435 |
+
bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
|
| 436 |
+
For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
|
| 437 |
+
ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k)
|
| 438 |
+
"""
|
| 439 |
+
(q, kv) = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, kv]]
|
| 440 |
+
(o, lse, ctx.softmax_scale) = _flash_attn_forward(q, kv[:, :, 0], kv[:, :, 1], bias=bias, causal=causal, softmax_scale=softmax_scale)
|
| 441 |
+
ctx.save_for_backward(q, kv, o, lse, bias)
|
| 442 |
+
ctx.causal = causal
|
| 443 |
+
return o
|
| 444 |
+
|
| 445 |
+
@staticmethod
|
| 446 |
+
def backward(ctx, do):
|
| 447 |
+
(q, kv, o, lse, bias) = ctx.saved_tensors
|
| 448 |
+
if len(ctx.needs_input_grad) >= 3:
|
| 449 |
+
assert not ctx.needs_input_grad[2], 'FlashAttention does not support bias gradient yet'
|
| 450 |
+
with torch.inference_mode():
|
| 451 |
+
dq = torch.empty_like(q)
|
| 452 |
+
dkv = torch.empty_like(kv)
|
| 453 |
+
_flash_attn_backward(do, q, kv[:, :, 0], kv[:, :, 1], o, lse, dq, dkv[:, :, 0], dkv[:, :, 1], bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale)
|
| 454 |
+
return (dq, dkv, None, None, None)
|
| 455 |
+
flash_attn_kvpacked_func = FlashAttnKVPackedFunc.apply
|
| 456 |
+
|
| 457 |
+
class FlashAttnFunc(torch.autograd.Function):
|
| 458 |
+
|
| 459 |
+
@staticmethod
|
| 460 |
+
def forward(ctx, q, k, v, bias=None, causal=False, softmax_scale=None):
|
| 461 |
+
"""
|
| 462 |
+
q: (batch_size, seqlen_q, nheads, headdim)
|
| 463 |
+
k, v: (batch_size, seqlen_k, nheads, headdim)
|
| 464 |
+
bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
|
| 465 |
+
For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
|
| 466 |
+
ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k)
|
| 467 |
+
"""
|
| 468 |
+
(q, k, v) = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, k, v]]
|
| 469 |
+
(o, lse, ctx.softmax_scale) = _flash_attn_forward(q, k, v, bias=bias, causal=causal, softmax_scale=softmax_scale)
|
| 470 |
+
ctx.save_for_backward(q, k, v, o, lse, bias)
|
| 471 |
+
ctx.causal = causal
|
| 472 |
+
return o
|
| 473 |
+
|
| 474 |
+
@staticmethod
|
| 475 |
+
def backward(ctx, do):
|
| 476 |
+
(q, k, v, o, lse, bias) = ctx.saved_tensors
|
| 477 |
+
assert not ctx.needs_input_grad[3], 'FlashAttention does not support bias gradient yet'
|
| 478 |
+
with torch.inference_mode():
|
| 479 |
+
dq = torch.empty_like(q)
|
| 480 |
+
dk = torch.empty_like(k)
|
| 481 |
+
dv = torch.empty_like(v)
|
| 482 |
+
_flash_attn_backward(do, q, k, v, o, lse, dq, dk, dv, bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale)
|
| 483 |
+
return (dq, dk, dv, None, None, None)
|
| 484 |
+
flash_attn_func = FlashAttnFunc.apply
|
VISTA/llava/model/language_model/mpt/norm.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
def _cast_if_autocast_enabled(tensor):
|
| 4 |
+
if torch.is_autocast_enabled():
|
| 5 |
+
if tensor.device.type == 'cuda':
|
| 6 |
+
dtype = torch.get_autocast_gpu_dtype()
|
| 7 |
+
elif tensor.device.type == 'cpu':
|
| 8 |
+
dtype = torch.get_autocast_cpu_dtype()
|
| 9 |
+
else:
|
| 10 |
+
raise NotImplementedError()
|
| 11 |
+
return tensor.to(dtype=dtype)
|
| 12 |
+
return tensor
|
| 13 |
+
|
| 14 |
+
class LPLayerNorm(torch.nn.LayerNorm):
|
| 15 |
+
|
| 16 |
+
def __init__(self, normalized_shape, eps=1e-05, elementwise_affine=True, device=None, dtype=None):
|
| 17 |
+
super().__init__(normalized_shape=normalized_shape, eps=eps, elementwise_affine=elementwise_affine, device=device, dtype=dtype)
|
| 18 |
+
|
| 19 |
+
def forward(self, x):
|
| 20 |
+
module_device = x.device
|
| 21 |
+
downcast_x = _cast_if_autocast_enabled(x)
|
| 22 |
+
downcast_weight = _cast_if_autocast_enabled(self.weight) if self.weight is not None else self.weight
|
| 23 |
+
downcast_bias = _cast_if_autocast_enabled(self.bias) if self.bias is not None else self.bias
|
| 24 |
+
with torch.autocast(enabled=False, device_type=module_device.type):
|
| 25 |
+
return torch.nn.functional.layer_norm(downcast_x, self.normalized_shape, downcast_weight, downcast_bias, self.eps)
|
| 26 |
+
|
| 27 |
+
def rms_norm(x, weight=None, eps=1e-05):
|
| 28 |
+
output = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps)
|
| 29 |
+
if weight is not None:
|
| 30 |
+
return output * weight
|
| 31 |
+
return output
|
| 32 |
+
|
| 33 |
+
class RMSNorm(torch.nn.Module):
|
| 34 |
+
|
| 35 |
+
def __init__(self, normalized_shape, eps=1e-05, weight=True, dtype=None, device=None):
|
| 36 |
+
super().__init__()
|
| 37 |
+
self.eps = eps
|
| 38 |
+
if weight:
|
| 39 |
+
self.weight = torch.nn.Parameter(torch.ones(normalized_shape, dtype=dtype, device=device))
|
| 40 |
+
else:
|
| 41 |
+
self.register_parameter('weight', None)
|
| 42 |
+
|
| 43 |
+
def forward(self, x):
|
| 44 |
+
return rms_norm(x.float(), self.weight, self.eps).to(dtype=x.dtype)
|
| 45 |
+
|
| 46 |
+
class LPRMSNorm(RMSNorm):
|
| 47 |
+
|
| 48 |
+
def __init__(self, normalized_shape, eps=1e-05, weight=True, dtype=None, device=None):
|
| 49 |
+
super().__init__(normalized_shape=normalized_shape, eps=eps, weight=weight, dtype=dtype, device=device)
|
| 50 |
+
|
| 51 |
+
def forward(self, x):
|
| 52 |
+
downcast_x = _cast_if_autocast_enabled(x)
|
| 53 |
+
downcast_weight = _cast_if_autocast_enabled(self.weight) if self.weight is not None else self.weight
|
| 54 |
+
with torch.autocast(enabled=False, device_type=x.device.type):
|
| 55 |
+
return rms_norm(downcast_x, downcast_weight, self.eps).to(dtype=x.dtype)
|
| 56 |
+
NORM_CLASS_REGISTRY = {'layernorm': torch.nn.LayerNorm, 'low_precision_layernorm': LPLayerNorm, 'rmsnorm': RMSNorm, 'low_precision_rmsnorm': LPRMSNorm}
|
VISTA/llava/model/language_model/mpt/param_init_fns.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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uple, Union
|
| 6 |
+
import torch
|
| 7 |
+
from torch import nn
|
| 8 |
+
from .norm import NORM_CLASS_REGISTRY
|
| 9 |
+
|
| 10 |
+
def torch_default_param_init_fn_(module: nn.Module, verbose: int=0, **kwargs):
|
| 11 |
+
del kwargs
|
| 12 |
+
if verbose > 1:
|
| 13 |
+
warnings.warn(f"Initializing network using module's reset_parameters attribute")
|
| 14 |
+
if hasattr(module, 'reset_parameters'):
|
| 15 |
+
module.reset_parameters()
|
| 16 |
+
|
| 17 |
+
def fused_init_helper_(module: nn.Module, init_fn_):
|
| 18 |
+
_fused = getattr(module, '_fused', None)
|
| 19 |
+
if _fused is None:
|
| 20 |
+
raise RuntimeError(f'Internal logic error')
|
| 21 |
+
(dim, splits) = _fused
|
| 22 |
+
splits = (0, *splits, module.weight.size(dim))
|
| 23 |
+
for (s, e) in zip(splits[:-1], splits[1:]):
|
| 24 |
+
slice_indices = [slice(None)] * module.weight.ndim
|
| 25 |
+
slice_indices[dim] = slice(s, e)
|
| 26 |
+
init_fn_(module.weight[slice_indices])
|
| 27 |
+
|
| 28 |
+
def generic_param_init_fn_(module: nn.Module, init_fn_, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
|
| 29 |
+
del kwargs
|
| 30 |
+
if verbose > 1:
|
| 31 |
+
warnings.warn(f'If model has bias parameters they are initialized to 0.')
|
| 32 |
+
init_div_is_residual = init_div_is_residual
|
| 33 |
+
if init_div_is_residual is False:
|
| 34 |
+
div_is_residual = 1.0
|
| 35 |
+
elif init_div_is_residual is True:
|
| 36 |
+
div_is_residual = math.sqrt(2 * n_layers)
|
| 37 |
+
elif isinstance(init_div_is_residual, float) or isinstance(init_div_is_residual, int):
|
| 38 |
+
div_is_residual = init_div_is_residual
|
| 39 |
+
elif isinstance(init_div_is_residual, str) and init_div_is_residual.isnumeric():
|
| 40 |
+
div_is_residual = float(init_div_is_residual)
|
| 41 |
+
else:
|
| 42 |
+
div_is_residual = 1.0
|
| 43 |
+
raise ValueError(f'Expected init_div_is_residual to be boolean or numeric, got {init_div_is_residual}')
|
| 44 |
+
if init_div_is_residual is not False:
|
| 45 |
+
if verbose > 1:
|
| 46 |
+
warnings.warn(f'Initializing _is_residual layers then dividing them by {div_is_residual:.3f}. ' + f'Set `init_div_is_residual: false` in init config to disable this.')
|
| 47 |
+
if isinstance(module, nn.Linear):
|
| 48 |
+
if hasattr(module, '_fused'):
|
| 49 |
+
fused_init_helper_(module, init_fn_)
|
| 50 |
+
else:
|
| 51 |
+
init_fn_(module.weight)
|
| 52 |
+
if module.bias is not None:
|
| 53 |
+
torch.nn.init.zeros_(module.bias)
|
| 54 |
+
if init_div_is_residual is not False and getattr(module, '_is_residual', False):
|
| 55 |
+
with torch.no_grad():
|
| 56 |
+
module.weight.div_(div_is_residual)
|
| 57 |
+
elif isinstance(module, nn.Embedding):
|
| 58 |
+
if emb_init_std is not None:
|
| 59 |
+
std = emb_init_std
|
| 60 |
+
if std == 0:
|
| 61 |
+
warnings.warn(f'Embedding layer initialized to 0.')
|
| 62 |
+
emb_init_fn_ = partial(torch.nn.init.normal_, mean=0.0, std=std)
|
| 63 |
+
if verbose > 1:
|
| 64 |
+
warnings.warn(f'Embedding layer initialized using normal distribution with mean=0 and std={std!r}.')
|
| 65 |
+
elif emb_init_uniform_lim is not None:
|
| 66 |
+
lim = emb_init_uniform_lim
|
| 67 |
+
if isinstance(lim, Sequence):
|
| 68 |
+
if len(lim) > 2:
|
| 69 |
+
raise ValueError(f'Uniform init requires a min and a max limit. User input: {lim}.')
|
| 70 |
+
if lim[0] == lim[1]:
|
| 71 |
+
warnings.warn(f'Embedding layer initialized to {lim[0]}.')
|
| 72 |
+
else:
|
| 73 |
+
if lim == 0:
|
| 74 |
+
warnings.warn(f'Embedding layer initialized to 0.')
|
| 75 |
+
lim = [-lim, lim]
|
| 76 |
+
(a, b) = lim
|
| 77 |
+
emb_init_fn_ = partial(torch.nn.init.uniform_, a=a, b=b)
|
| 78 |
+
if verbose > 1:
|
| 79 |
+
warnings.warn(f'Embedding layer initialized using uniform distribution in range {lim}.')
|
| 80 |
+
else:
|
| 81 |
+
emb_init_fn_ = init_fn_
|
| 82 |
+
emb_init_fn_(module.weight)
|
| 83 |
+
elif isinstance(module, tuple(set(NORM_CLASS_REGISTRY.values()))):
|
| 84 |
+
if verbose > 1:
|
| 85 |
+
warnings.warn(f'Norm weights are set to 1. If norm layer has a bias it is initialized to 0.')
|
| 86 |
+
if hasattr(module, 'weight') and module.weight is not None:
|
| 87 |
+
torch.nn.init.ones_(module.weight)
|
| 88 |
+
if hasattr(module, 'bias') and module.bias is not None:
|
| 89 |
+
torch.nn.init.zeros_(module.bias)
|
| 90 |
+
elif isinstance(module, nn.MultiheadAttention):
|
| 91 |
+
if module._qkv_same_embed_dim:
|
| 92 |
+
assert module.in_proj_weight is not None
|
| 93 |
+
assert module.q_proj_weight is None and module.k_proj_weight is None and (module.v_proj_weight is None)
|
| 94 |
+
assert d_model is not None
|
| 95 |
+
_d = d_model
|
| 96 |
+
splits = (0, _d, 2 * _d, 3 * _d)
|
| 97 |
+
for (s, e) in zip(splits[:-1], splits[1:]):
|
| 98 |
+
init_fn_(module.in_proj_weight[s:e])
|
| 99 |
+
else:
|
| 100 |
+
assert module.q_proj_weight is not None and module.k_proj_weight is not None and (module.v_proj_weight is not None)
|
| 101 |
+
assert module.in_proj_weight is None
|
| 102 |
+
init_fn_(module.q_proj_weight)
|
| 103 |
+
init_fn_(module.k_proj_weight)
|
| 104 |
+
init_fn_(module.v_proj_weight)
|
| 105 |
+
if module.in_proj_bias is not None:
|
| 106 |
+
torch.nn.init.zeros_(module.in_proj_bias)
|
| 107 |
+
if module.bias_k is not None:
|
| 108 |
+
torch.nn.init.zeros_(module.bias_k)
|
| 109 |
+
if module.bias_v is not None:
|
| 110 |
+
torch.nn.init.zeros_(module.bias_v)
|
| 111 |
+
init_fn_(module.out_proj.weight)
|
| 112 |
+
if init_div_is_residual is not False and getattr(module.out_proj, '_is_residual', False):
|
| 113 |
+
with torch.no_grad():
|
| 114 |
+
module.out_proj.weight.div_(div_is_residual)
|
| 115 |
+
if module.out_proj.bias is not None:
|
| 116 |
+
torch.nn.init.zeros_(module.out_proj.bias)
|
| 117 |
+
else:
|
| 118 |
+
for _ in module.parameters(recurse=False):
|
| 119 |
+
raise NotImplementedError(f'{module.__class__.__name__} parameters are not initialized by param_init_fn.')
|
| 120 |
+
|
| 121 |
+
def _normal_init_(std, mean=0.0):
|
| 122 |
+
return partial(torch.nn.init.normal_, mean=mean, std=std)
|
| 123 |
+
|
| 124 |
+
def _normal_param_init_fn_(module: nn.Module, std: float, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
|
| 125 |
+
del kwargs
|
| 126 |
+
init_fn_ = _normal_init_(std=std)
|
| 127 |
+
if verbose > 1:
|
| 128 |
+
warnings.warn(f'Using torch.nn.init.normal_ init fn mean=0.0, std={std}')
|
| 129 |
+
generic_param_init_fn_(module=module, init_fn_=init_fn_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
|
| 130 |
+
|
| 131 |
+
def baseline_param_init_fn_(module: nn.Module, init_std: float, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
|
| 132 |
+
del kwargs
|
| 133 |
+
if init_std is None:
|
| 134 |
+
raise ValueError("You must set model.init_config['init_std'] to a float value to use the default initialization scheme.")
|
| 135 |
+
_normal_param_init_fn_(module=module, std=init_std, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
|
| 136 |
+
|
| 137 |
+
def small_param_init_fn_(module: nn.Module, n_layers: int, d_model: int, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
|
| 138 |
+
del kwargs
|
| 139 |
+
std = math.sqrt(2 / (5 * d_model))
|
| 140 |
+
_normal_param_init_fn_(module=module, std=std, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
|
| 141 |
+
|
| 142 |
+
def neox_param_init_fn_(module: nn.Module, n_layers: int, d_model: int, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
|
| 143 |
+
"""From section 2.3.1 of GPT-NeoX-20B:
|
| 144 |
+
|
| 145 |
+
An Open-Source AutoregressiveLanguage Model — Black et. al. (2022)
|
| 146 |
+
see https://github.com/EleutherAI/gpt-neox/blob/9610391ab319403cef079b438edd016a2443af54/megatron/model/init_functions.py#L151
|
| 147 |
+
and https://github.com/EleutherAI/gpt-neox/blob/main/megatron/model/transformer.py
|
| 148 |
+
"""
|
| 149 |
+
del kwargs
|
| 150 |
+
residual_div = n_layers / math.sqrt(10)
|
| 151 |
+
if verbose > 1:
|
| 152 |
+
warnings.warn(f'setting init_div_is_residual to {residual_div}')
|
| 153 |
+
small_param_init_fn_(module=module, d_model=d_model, n_layers=n_layers, init_div_is_residual=residual_div, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
|
| 154 |
+
|
| 155 |
+
def kaiming_uniform_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, fan_mode: str='fan_in', init_nonlinearity: str='leaky_relu', verbose: int=0, **kwargs):
|
| 156 |
+
del kwargs
|
| 157 |
+
if verbose > 1:
|
| 158 |
+
warnings.warn(f'Using nn.init.kaiming_uniform_ init fn with parameters: ' + f'a={init_gain}, mode={fan_mode}, nonlinearity={init_nonlinearity}')
|
| 159 |
+
kaiming_uniform_ = partial(nn.init.kaiming_uniform_, a=init_gain, mode=fan_mode, nonlinearity=init_nonlinearity)
|
| 160 |
+
generic_param_init_fn_(module=module, init_fn_=kaiming_uniform_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
|
| 161 |
+
|
| 162 |
+
def kaiming_normal_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, fan_mode: str='fan_in', init_nonlinearity: str='leaky_relu', verbose: int=0, **kwargs):
|
| 163 |
+
del kwargs
|
| 164 |
+
if verbose > 1:
|
| 165 |
+
warnings.warn(f'Using nn.init.kaiming_normal_ init fn with parameters: ' + f'a={init_gain}, mode={fan_mode}, nonlinearity={init_nonlinearity}')
|
| 166 |
+
kaiming_normal_ = partial(torch.nn.init.kaiming_normal_, a=init_gain, mode=fan_mode, nonlinearity=init_nonlinearity)
|
| 167 |
+
generic_param_init_fn_(module=module, init_fn_=kaiming_normal_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
|
| 168 |
+
|
| 169 |
+
def xavier_uniform_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, verbose: int=0, **kwargs):
|
| 170 |
+
del kwargs
|
| 171 |
+
xavier_uniform_ = partial(torch.nn.init.xavier_uniform_, gain=init_gain)
|
| 172 |
+
if verbose > 1:
|
| 173 |
+
warnings.warn(f'Using torch.nn.init.xavier_uniform_ init fn with parameters: ' + f'gain={init_gain}')
|
| 174 |
+
generic_param_init_fn_(module=module, init_fn_=xavier_uniform_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
|
| 175 |
+
|
| 176 |
+
def xavier_normal_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, verbose: int=0, **kwargs):
|
| 177 |
+
xavier_normal_ = partial(torch.nn.init.xavier_normal_, gain=init_gain)
|
| 178 |
+
if verbose > 1:
|
| 179 |
+
warnings.warn(f'Using torch.nn.init.xavier_normal_ init fn with parameters: ' + f'gain={init_gain}')
|
| 180 |
+
generic_param_init_fn_(module=module, init_fn_=xavier_normal_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
|
| 181 |
+
MODEL_INIT_REGISTRY = {'default_': torch_default_param_init_fn_, 'baseline_': baseline_param_init_fn_, 'kaiming_uniform_': kaiming_uniform_param_init_fn_, 'kaiming_normal_': kaiming_normal_param_init_fn_, 'neox_init_': neox_param_init_fn_, 'small_init_': small_param_init_fn_, 'xavier_uniform_': xavier_uniform_param_init_fn_, 'xavier_normal_': xavier_normal_param_init_fn_}
|
VISTA/llava/model/multimodal_encoder/__pycache__/clip_encoder.cpython-310.pyc
ADDED
|
Binary file (4.97 kB). View file
|
|
|
VISTA/llava/model/multimodal_encoder/clip_encoder.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
|
| 6 |
+
from transformers import CLIPVisionModel, CLIPImageProcessor, CLIPVisionConfig
|
| 7 |
+
from .eva_clip.configuration_evaclip import EvaCLIPVisionConfig
|
| 8 |
+
from .eva_clip.modeling_evaclip import EvaCLIPVisionModel
|
| 9 |
+
from .intern_vit_6b.configuration_intern_vit import InternVisionConfig
|
| 10 |
+
from .intern_vit_6b.modeling_intern_vit import InternVisionModel
|
| 11 |
+
from .internvl_14b.configuration_internvl import InternVLConfig
|
| 12 |
+
from .internvl_14b.modeling_internvl import InternVLModel
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def is_intern_vit_6b_model(vision_tower_name):
|
| 16 |
+
model_names = ["intern_vit_6b", "internvit_6b", "InternViT-6B", "internvit6b"]
|
| 17 |
+
return any(name in vision_tower_name for name in model_names)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def is_internvl_14b_model(vision_tower_name):
|
| 21 |
+
model_names = ["internvl_14b", "intern_vl_14b", "InternVL-14B", "internvl14b"]
|
| 22 |
+
return any(name in vision_tower_name for name in model_names)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class CLIPVisionTower(nn.Module):
|
| 26 |
+
def __init__(self, vision_tower, args, delay_load=False):
|
| 27 |
+
super().__init__()
|
| 28 |
+
|
| 29 |
+
self.is_loaded = False
|
| 30 |
+
|
| 31 |
+
self.vision_tower_name = vision_tower
|
| 32 |
+
self.select_layer = args.mm_vision_select_layer
|
| 33 |
+
self.select_feature = getattr(args, 'mm_vision_select_feature', 'patch')
|
| 34 |
+
|
| 35 |
+
if not delay_load:
|
| 36 |
+
self.load_model()
|
| 37 |
+
else:
|
| 38 |
+
if "EVA" in self.vision_tower_name or "eva" in self.vision_tower_name:
|
| 39 |
+
self.cfg_only = EvaCLIPVisionConfig.from_pretrained(self.vision_tower_name)
|
| 40 |
+
elif is_intern_vit_6b_model(self.vision_tower_name):
|
| 41 |
+
self.cfg_only = InternVisionConfig.from_pretrained(self.vision_tower_name)
|
| 42 |
+
elif is_internvl_14b_model(self.vision_tower_name):
|
| 43 |
+
self.cfg_only = InternVLConfig.from_pretrained(self.vision_tower_name)
|
| 44 |
+
else:
|
| 45 |
+
self.cfg_only = CLIPVisionConfig.from_pretrained(self.vision_tower_name)
|
| 46 |
+
|
| 47 |
+
def load_model(self):
|
| 48 |
+
if "EVA" in self.vision_tower_name or "eva" in self.vision_tower_name:
|
| 49 |
+
self.image_processor = CLIPImageProcessor.from_pretrained(self.vision_tower_name)
|
| 50 |
+
self.vision_tower = EvaCLIPVisionModel.from_pretrained(self.vision_tower_name)
|
| 51 |
+
elif is_intern_vit_6b_model(self.vision_tower_name):
|
| 52 |
+
crop_size = 448 if "448" in self.vision_tower_name else 336
|
| 53 |
+
self.image_processor = CLIPImageProcessor(
|
| 54 |
+
crop_size=crop_size, do_center_crop=True, do_normalize=True, do_resize=True,
|
| 55 |
+
image_mean=[0.485, 0.456, 0.406], image_std=[0.229, 0.224, 0.225], size=crop_size
|
| 56 |
+
)
|
| 57 |
+
# self.vision_tower = InternVisionModel.from_pretrained(self.vision_tower_name)
|
| 58 |
+
self.vision_tower = InternVisionModel.from_pretrained("/root/autodl-tmp/InternViT-6B-224px")
|
| 59 |
+
elif is_internvl_14b_model(self.vision_tower_name):
|
| 60 |
+
self.image_processor = CLIPImageProcessor(
|
| 61 |
+
crop_size=336, do_center_crop=True, do_normalize=True, do_resize=True,
|
| 62 |
+
image_mean=[0.485, 0.456, 0.406], image_std=[0.229, 0.224, 0.225], size=336
|
| 63 |
+
)
|
| 64 |
+
self.vision_tower = InternVLModel.from_pretrained(self.vision_tower_name)
|
| 65 |
+
self.vision_tower.eval()
|
| 66 |
+
else:
|
| 67 |
+
self.image_processor = CLIPImageProcessor.from_pretrained(self.vision_tower_name)
|
| 68 |
+
self.vision_tower = CLIPVisionModel.from_pretrained(self.vision_tower_name)
|
| 69 |
+
self.vision_tower.requires_grad_(False)
|
| 70 |
+
|
| 71 |
+
self.is_loaded = True
|
| 72 |
+
|
| 73 |
+
def feature_select(self, image_forward_outs):
|
| 74 |
+
image_features = image_forward_outs.hidden_states[self.select_layer]
|
| 75 |
+
if self.select_feature == 'patch':
|
| 76 |
+
image_features = image_features[:, 1:]
|
| 77 |
+
elif self.select_feature == 'cls_patch':
|
| 78 |
+
image_features = image_features
|
| 79 |
+
else:
|
| 80 |
+
raise ValueError(f'Unexpected select feature: {self.select_feature}')
|
| 81 |
+
return image_features
|
| 82 |
+
|
| 83 |
+
@torch.no_grad()
|
| 84 |
+
def forward(self, images):
|
| 85 |
+
if type(images) is list:
|
| 86 |
+
image_features = []
|
| 87 |
+
for image in images:
|
| 88 |
+
if is_internvl_14b_model(self.vision_tower_name):
|
| 89 |
+
image_forward_out, query_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
|
| 90 |
+
image_feature = self.feature_select(image_forward_out).to(image.dtype)
|
| 91 |
+
image_features.append([image_feature, query_out])
|
| 92 |
+
else:
|
| 93 |
+
image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
|
| 94 |
+
image_feature = self.feature_select(image_forward_out).to(image.dtype)
|
| 95 |
+
image_features.append(image_feature)
|
| 96 |
+
else:
|
| 97 |
+
if is_internvl_14b_model(self.vision_tower_name):
|
| 98 |
+
image_forward_outs, query_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
|
| 99 |
+
image_features = self.feature_select(image_forward_outs).to(images.dtype)
|
| 100 |
+
image_features = [image_features, query_outs]
|
| 101 |
+
else:
|
| 102 |
+
image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
|
| 103 |
+
image_features = self.feature_select(image_forward_outs).to(images.dtype)
|
| 104 |
+
|
| 105 |
+
return image_features
|
| 106 |
+
|
| 107 |
+
@property
|
| 108 |
+
def dummy_feature(self):
|
| 109 |
+
return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
|
| 110 |
+
|
| 111 |
+
@property
|
| 112 |
+
def dtype(self):
|
| 113 |
+
return self.vision_tower.dtype
|
| 114 |
+
|
| 115 |
+
@property
|
| 116 |
+
def device(self):
|
| 117 |
+
return self.vision_tower.device
|
| 118 |
+
|
| 119 |
+
@property
|
| 120 |
+
def config(self):
|
| 121 |
+
if self.is_loaded:
|
| 122 |
+
return self.vision_tower.config
|
| 123 |
+
else:
|
| 124 |
+
return self.cfg_only
|
| 125 |
+
|
| 126 |
+
@property
|
| 127 |
+
def hidden_size(self):
|
| 128 |
+
return self.config.hidden_size
|
| 129 |
+
|
| 130 |
+
@property
|
| 131 |
+
def num_patches(self):
|
| 132 |
+
if is_internvl_14b_model(self.vision_tower_name):
|
| 133 |
+
return (self.config.image_size // self.config.patch_size) ** 2 + 96
|
| 134 |
+
else:
|
| 135 |
+
return (self.config.image_size // self.config.patch_size) ** 2
|
VISTA/llava/model/multimodal_encoder/eva_clip/__pycache__/configuration_evaclip.cpython-310.pyc
ADDED
|
Binary file (14.7 kB). View file
|
|
|
VISTA/llava/model/multimodal_encoder/eva_clip/__pycache__/modeling_evaclip.cpython-310.pyc
ADDED
|
Binary file (43.2 kB). View file
|
|
|
VISTA/llava/model/multimodal_encoder/eva_clip/configuration_evaclip.py
ADDED
|
@@ -0,0 +1,425 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" EvaCLIP model configuration"""
|
| 16 |
+
# Code mainly copied here: https://github.com/huggingface/transformers/blob/main/src/transformers/models/clip/configuration_clip.py
|
| 17 |
+
# and adjusted for evaclip
|
| 18 |
+
|
| 19 |
+
import copy
|
| 20 |
+
import os
|
| 21 |
+
from collections import OrderedDict
|
| 22 |
+
from typing import TYPE_CHECKING, Any, Mapping, Optional, Union
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
if TYPE_CHECKING:
|
| 26 |
+
from transformers.processing_utils import ProcessorMixin
|
| 27 |
+
from transformers.utils import TensorType
|
| 28 |
+
|
| 29 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 30 |
+
from transformers.utils import logging
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class EvaCLIPTextConfig(PretrainedConfig):
|
| 37 |
+
r"""
|
| 38 |
+
This is the configuration class to store the configuration of a [`CLIPTextModel`]. It is used to instantiate a CLIP
|
| 39 |
+
text encoder according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 40 |
+
with the defaults will yield a similar configuration to that of the text encoder of the CLIP
|
| 41 |
+
[openai/clip-vit-base-patch32](https://huggingface.co/openai/clip-vit-base-patch32) architecture.
|
| 42 |
+
|
| 43 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 44 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
vocab_size (`int`, *optional*, defaults to 49408):
|
| 48 |
+
Vocabulary size of the CLIP text model. Defines the number of different tokens that can be represented by
|
| 49 |
+
the `inputs_ids` passed when calling [`CLIPModel`].
|
| 50 |
+
hidden_size (`int`, *optional*, defaults to 512):
|
| 51 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 52 |
+
intermediate_size (`int`, *optional*, defaults to 2048):
|
| 53 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 54 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 55 |
+
Number of hidden layers in the Transformer encoder.
|
| 56 |
+
num_attention_heads (`int`, *optional*, defaults to 8):
|
| 57 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 58 |
+
max_position_embeddings (`int`, *optional*, defaults to 77):
|
| 59 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 60 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 61 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
|
| 62 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 63 |
+
`"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
|
| 64 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-5):
|
| 65 |
+
The epsilon used by the layer normalization layers.
|
| 66 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 67 |
+
The dropout ratio for the attention probabilities.
|
| 68 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 69 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 70 |
+
initializer_factor (`float`, *optional*, defaults to 1):
|
| 71 |
+
A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
|
| 72 |
+
testing).
|
| 73 |
+
|
| 74 |
+
Example:
|
| 75 |
+
|
| 76 |
+
```python
|
| 77 |
+
>>> from transformers import CLIPTextConfig, CLIPTextModel
|
| 78 |
+
|
| 79 |
+
>>> # Initializing a CLIPTextConfig with openai/clip-vit-base-patch32 style configuration
|
| 80 |
+
>>> configuration = CLIPTextConfig()
|
| 81 |
+
|
| 82 |
+
>>> # Initializing a CLIPTextModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
|
| 83 |
+
>>> model = CLIPTextModel(configuration)
|
| 84 |
+
|
| 85 |
+
>>> # Accessing the model configuration
|
| 86 |
+
>>> configuration = model.config
|
| 87 |
+
```"""
|
| 88 |
+
model_type = "clip_text_model"
|
| 89 |
+
|
| 90 |
+
def __init__(
|
| 91 |
+
self,
|
| 92 |
+
vocab_size=49408,
|
| 93 |
+
hidden_size=512,
|
| 94 |
+
intermediate_size=2048,
|
| 95 |
+
projection_dim=512,
|
| 96 |
+
num_hidden_layers=12,
|
| 97 |
+
num_attention_heads=8,
|
| 98 |
+
max_position_embeddings=77,
|
| 99 |
+
hidden_act="gelu",
|
| 100 |
+
layer_norm_eps=1e-5,
|
| 101 |
+
attention_dropout=0.0,
|
| 102 |
+
initializer_range=0.02,
|
| 103 |
+
initializer_factor=1.0,
|
| 104 |
+
q_bias=True,
|
| 105 |
+
k_bias=True,
|
| 106 |
+
v_bias=True,
|
| 107 |
+
post_layernorm=False,
|
| 108 |
+
pad_token_id=1,
|
| 109 |
+
bos_token_id=0,
|
| 110 |
+
eos_token_id=2,
|
| 111 |
+
**kwargs,
|
| 112 |
+
):
|
| 113 |
+
super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
| 114 |
+
|
| 115 |
+
self.vocab_size = vocab_size
|
| 116 |
+
self.hidden_size = hidden_size
|
| 117 |
+
self.intermediate_size = intermediate_size
|
| 118 |
+
self.projection_dim = projection_dim
|
| 119 |
+
self.num_hidden_layers = num_hidden_layers
|
| 120 |
+
self.num_attention_heads = num_attention_heads
|
| 121 |
+
self.max_position_embeddings = max_position_embeddings
|
| 122 |
+
self.layer_norm_eps = layer_norm_eps
|
| 123 |
+
self.hidden_act = hidden_act
|
| 124 |
+
self.initializer_range = initializer_range
|
| 125 |
+
self.initializer_factor = initializer_factor
|
| 126 |
+
self.q_bias=q_bias
|
| 127 |
+
self.k_bias=k_bias
|
| 128 |
+
self.v_bias=v_bias
|
| 129 |
+
self.post_layernorm = post_layernorm
|
| 130 |
+
self.attention_dropout = attention_dropout
|
| 131 |
+
|
| 132 |
+
@classmethod
|
| 133 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
|
| 134 |
+
cls._set_token_in_kwargs(kwargs)
|
| 135 |
+
|
| 136 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
| 137 |
+
|
| 138 |
+
# get the text config dict if we are loading from CLIPConfig
|
| 139 |
+
if config_dict.get("model_type") == "clip":
|
| 140 |
+
config_dict = config_dict["text_config"]
|
| 141 |
+
|
| 142 |
+
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
|
| 143 |
+
logger.warning(
|
| 144 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
| 145 |
+
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
return cls.from_dict(config_dict, **kwargs)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class EvaCLIPVisionConfig(PretrainedConfig):
|
| 152 |
+
r"""
|
| 153 |
+
This is the configuration class to store the configuration of a [`CLIPVisionModel`]. It is used to instantiate a
|
| 154 |
+
CLIP vision encoder according to the specified arguments, defining the model architecture. Instantiating a
|
| 155 |
+
configuration with the defaults will yield a similar configuration to that of the vision encoder of the CLIP
|
| 156 |
+
[openai/clip-vit-base-patch32](https://huggingface.co/openai/clip-vit-base-patch32) architecture.
|
| 157 |
+
|
| 158 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 159 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 160 |
+
|
| 161 |
+
Args:
|
| 162 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 163 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 164 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 165 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 166 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 167 |
+
Number of hidden layers in the Transformer encoder.
|
| 168 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 169 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 170 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 171 |
+
The size (resolution) of each image.
|
| 172 |
+
patch_size (`int`, *optional*, defaults to 32):
|
| 173 |
+
The size (resolution) of each patch.
|
| 174 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
|
| 175 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 176 |
+
`"relu"`, `"selu"` and `"gelu_new"` ``"quick_gelu"` are supported.
|
| 177 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-5):
|
| 178 |
+
The epsilon used by the layer normalization layers.
|
| 179 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 180 |
+
The dropout ratio for the attention probabilities.
|
| 181 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 182 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 183 |
+
initializer_factor (`float`, *optional*, defaults to 1):
|
| 184 |
+
A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
|
| 185 |
+
testing).
|
| 186 |
+
|
| 187 |
+
Example:
|
| 188 |
+
|
| 189 |
+
```python
|
| 190 |
+
>>> from transformers import CLIPVisionConfig, CLIPVisionModel
|
| 191 |
+
|
| 192 |
+
>>> # Initializing a CLIPVisionConfig with openai/clip-vit-base-patch32 style configuration
|
| 193 |
+
>>> configuration = CLIPVisionConfig()
|
| 194 |
+
|
| 195 |
+
>>> # Initializing a CLIPVisionModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
|
| 196 |
+
>>> model = CLIPVisionModel(configuration)
|
| 197 |
+
|
| 198 |
+
>>> # Accessing the model configuration
|
| 199 |
+
>>> configuration = model.config
|
| 200 |
+
```"""
|
| 201 |
+
|
| 202 |
+
model_type = "clip_vision_model"
|
| 203 |
+
|
| 204 |
+
def __init__(
|
| 205 |
+
self,
|
| 206 |
+
hidden_size=768,
|
| 207 |
+
intermediate_size=3072,
|
| 208 |
+
projection_dim=512,
|
| 209 |
+
num_hidden_layers=12,
|
| 210 |
+
num_attention_heads=12,
|
| 211 |
+
num_channels=3,
|
| 212 |
+
image_size=224,
|
| 213 |
+
patch_size=32,
|
| 214 |
+
hidden_act="gelu",
|
| 215 |
+
layer_norm_eps=1e-5,
|
| 216 |
+
attention_dropout=0.0,
|
| 217 |
+
initializer_range=0.02,
|
| 218 |
+
initializer_factor=1.0,
|
| 219 |
+
q_bias=True,
|
| 220 |
+
k_bias=True,
|
| 221 |
+
v_bias=True,
|
| 222 |
+
post_layernorm=False,
|
| 223 |
+
**kwargs,
|
| 224 |
+
):
|
| 225 |
+
super().__init__(**kwargs)
|
| 226 |
+
|
| 227 |
+
self.hidden_size = hidden_size
|
| 228 |
+
self.intermediate_size = intermediate_size
|
| 229 |
+
self.projection_dim = projection_dim
|
| 230 |
+
self.num_hidden_layers = num_hidden_layers
|
| 231 |
+
self.num_attention_heads = num_attention_heads
|
| 232 |
+
self.num_channels = num_channels
|
| 233 |
+
self.patch_size = patch_size
|
| 234 |
+
self.image_size = image_size
|
| 235 |
+
self.initializer_range = initializer_range
|
| 236 |
+
self.initializer_factor = initializer_factor
|
| 237 |
+
self.q_bias=q_bias
|
| 238 |
+
self.k_bias=k_bias
|
| 239 |
+
self.v_bias=v_bias
|
| 240 |
+
self.post_layernorm = post_layernorm
|
| 241 |
+
self.attention_dropout = attention_dropout
|
| 242 |
+
self.layer_norm_eps = layer_norm_eps
|
| 243 |
+
self.hidden_act = hidden_act
|
| 244 |
+
|
| 245 |
+
@classmethod
|
| 246 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
|
| 247 |
+
cls._set_token_in_kwargs(kwargs)
|
| 248 |
+
|
| 249 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
| 250 |
+
|
| 251 |
+
# get the vision config dict if we are loading from CLIPConfig
|
| 252 |
+
if config_dict.get("model_type") == "clip":
|
| 253 |
+
config_dict = config_dict["vision_config"]
|
| 254 |
+
|
| 255 |
+
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
|
| 256 |
+
logger.warning(
|
| 257 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
| 258 |
+
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
return cls.from_dict(config_dict, **kwargs)
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
class EvaCLIPConfig(PretrainedConfig):
|
| 265 |
+
r"""
|
| 266 |
+
[`CLIPConfig`] is the configuration class to store the configuration of a [`CLIPModel`]. It is used to instantiate
|
| 267 |
+
a CLIP model according to the specified arguments, defining the text model and vision model configs. Instantiating
|
| 268 |
+
a configuration with the defaults will yield a similar configuration to that of the CLIP
|
| 269 |
+
[openai/clip-vit-base-patch32](https://huggingface.co/openai/clip-vit-base-patch32) architecture.
|
| 270 |
+
|
| 271 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 272 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 273 |
+
|
| 274 |
+
Args:
|
| 275 |
+
text_config (`dict`, *optional*):
|
| 276 |
+
Dictionary of configuration options used to initialize [`CLIPTextConfig`].
|
| 277 |
+
vision_config (`dict`, *optional*):
|
| 278 |
+
Dictionary of configuration options used to initialize [`CLIPVisionConfig`].
|
| 279 |
+
projection_dim (`int`, *optional*, defaults to 512):
|
| 280 |
+
Dimentionality of text and vision projection layers.
|
| 281 |
+
logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
|
| 282 |
+
The inital value of the *logit_scale* paramter. Default is used as per the original CLIP implementation.
|
| 283 |
+
kwargs (*optional*):
|
| 284 |
+
Dictionary of keyword arguments.
|
| 285 |
+
|
| 286 |
+
Example:
|
| 287 |
+
|
| 288 |
+
```python
|
| 289 |
+
>>> from transformers import CLIPConfig, CLIPModel
|
| 290 |
+
|
| 291 |
+
>>> # Initializing a CLIPConfig with openai/clip-vit-base-patch32 style configuration
|
| 292 |
+
>>> configuration = CLIPConfig()
|
| 293 |
+
|
| 294 |
+
>>> # Initializing a CLIPModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
|
| 295 |
+
>>> model = CLIPModel(configuration)
|
| 296 |
+
|
| 297 |
+
>>> # Accessing the model configuration
|
| 298 |
+
>>> configuration = model.config
|
| 299 |
+
|
| 300 |
+
>>> # We can also initialize a CLIPConfig from a CLIPTextConfig and a CLIPVisionConfig
|
| 301 |
+
>>> from transformers import CLIPTextConfig, CLIPVisionConfig
|
| 302 |
+
|
| 303 |
+
>>> # Initializing a CLIPText and CLIPVision configuration
|
| 304 |
+
>>> config_text = CLIPTextConfig()
|
| 305 |
+
>>> config_vision = CLIPVisionConfig()
|
| 306 |
+
|
| 307 |
+
>>> config = CLIPConfig.from_text_vision_configs(config_text, config_vision)
|
| 308 |
+
```"""
|
| 309 |
+
|
| 310 |
+
model_type = "clip"
|
| 311 |
+
is_composition = True
|
| 312 |
+
|
| 313 |
+
def __init__(
|
| 314 |
+
self, text_config=None, vision_config=None, projection_dim=512, logit_scale_init_value=2.6592, **kwargs
|
| 315 |
+
):
|
| 316 |
+
# If `_config_dict` exist, we use them for the backward compatibility.
|
| 317 |
+
# We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
|
| 318 |
+
# of confusion!).
|
| 319 |
+
text_config_dict = kwargs.pop("text_config_dict", None)
|
| 320 |
+
vision_config_dict = kwargs.pop("vision_config_dict", None)
|
| 321 |
+
|
| 322 |
+
super().__init__(**kwargs)
|
| 323 |
+
|
| 324 |
+
# Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
|
| 325 |
+
# `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
|
| 326 |
+
# cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
|
| 327 |
+
if text_config_dict is not None:
|
| 328 |
+
if text_config is None:
|
| 329 |
+
text_config = {}
|
| 330 |
+
|
| 331 |
+
# This is the complete result when using `text_config_dict`.
|
| 332 |
+
_text_config_dict = EvaCLIPTextConfig(**text_config_dict).to_dict()
|
| 333 |
+
|
| 334 |
+
# Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
|
| 335 |
+
for key, value in _text_config_dict.items():
|
| 336 |
+
if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
|
| 337 |
+
# If specified in `text_config_dict`
|
| 338 |
+
if key in text_config_dict:
|
| 339 |
+
message = (
|
| 340 |
+
f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
|
| 341 |
+
f'The value `text_config_dict["{key}"]` will be used instead.'
|
| 342 |
+
)
|
| 343 |
+
# If inferred from default argument values (just to be super careful)
|
| 344 |
+
else:
|
| 345 |
+
message = (
|
| 346 |
+
f"`text_config_dict` is provided which will be used to initialize `CLIPTextConfig`. The "
|
| 347 |
+
f'value `text_config["{key}"]` will be overriden.'
|
| 348 |
+
)
|
| 349 |
+
logger.warning(message)
|
| 350 |
+
|
| 351 |
+
# Update all values in `text_config` with the ones in `_text_config_dict`.
|
| 352 |
+
text_config.update(_text_config_dict)
|
| 353 |
+
|
| 354 |
+
if vision_config_dict is not None:
|
| 355 |
+
if vision_config is None:
|
| 356 |
+
vision_config = {}
|
| 357 |
+
|
| 358 |
+
# This is the complete result when using `vision_config_dict`.
|
| 359 |
+
_vision_config_dict = EvaCLIPVisionConfig(**vision_config_dict).to_dict()
|
| 360 |
+
# convert keys to string instead of integer
|
| 361 |
+
if "id2label" in _vision_config_dict:
|
| 362 |
+
_vision_config_dict["id2label"] = {
|
| 363 |
+
str(key): value for key, value in _vision_config_dict["id2label"].items()
|
| 364 |
+
}
|
| 365 |
+
|
| 366 |
+
# Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
|
| 367 |
+
for key, value in _vision_config_dict.items():
|
| 368 |
+
if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
|
| 369 |
+
# If specified in `vision_config_dict`
|
| 370 |
+
if key in vision_config_dict:
|
| 371 |
+
message = (
|
| 372 |
+
f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
|
| 373 |
+
f'values. The value `vision_config_dict["{key}"]` will be used instead.'
|
| 374 |
+
)
|
| 375 |
+
# If inferred from default argument values (just to be super careful)
|
| 376 |
+
else:
|
| 377 |
+
message = (
|
| 378 |
+
f"`vision_config_dict` is provided which will be used to initialize `CLIPVisionConfig`. "
|
| 379 |
+
f'The value `vision_config["{key}"]` will be overriden.'
|
| 380 |
+
)
|
| 381 |
+
logger.warning(message)
|
| 382 |
+
|
| 383 |
+
# Update all values in `vision_config` with the ones in `_vision_config_dict`.
|
| 384 |
+
vision_config.update(_vision_config_dict)
|
| 385 |
+
|
| 386 |
+
if text_config is None:
|
| 387 |
+
text_config = {}
|
| 388 |
+
logger.info("`text_config` is `None`. Initializing the `CLIPTextConfig` with default values.")
|
| 389 |
+
|
| 390 |
+
if vision_config is None:
|
| 391 |
+
vision_config = {}
|
| 392 |
+
logger.info("`vision_config` is `None`. initializing the `CLIPVisionConfig` with default values.")
|
| 393 |
+
|
| 394 |
+
self.text_config = EvaCLIPTextConfig(**text_config)
|
| 395 |
+
self.vision_config = EvaCLIPVisionConfig(**vision_config)
|
| 396 |
+
|
| 397 |
+
self.projection_dim = projection_dim
|
| 398 |
+
self.logit_scale_init_value = logit_scale_init_value
|
| 399 |
+
self.initializer_factor = 1.0
|
| 400 |
+
|
| 401 |
+
@classmethod
|
| 402 |
+
def from_text_vision_configs(cls, text_config: EvaCLIPTextConfig, vision_config: EvaCLIPVisionConfig, **kwargs):
|
| 403 |
+
r"""
|
| 404 |
+
Instantiate a [`CLIPConfig`] (or a derived class) from clip text model configuration and clip vision model
|
| 405 |
+
configuration.
|
| 406 |
+
|
| 407 |
+
Returns:
|
| 408 |
+
[`CLIPConfig`]: An instance of a configuration object
|
| 409 |
+
"""
|
| 410 |
+
|
| 411 |
+
return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)
|
| 412 |
+
|
| 413 |
+
def to_dict(self):
|
| 414 |
+
"""
|
| 415 |
+
Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
|
| 416 |
+
|
| 417 |
+
Returns:
|
| 418 |
+
`Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
|
| 419 |
+
"""
|
| 420 |
+
output = copy.deepcopy(self.__dict__)
|
| 421 |
+
output["text_config"] = self.text_config.to_dict()
|
| 422 |
+
output["vision_config"] = self.vision_config.to_dict()
|
| 423 |
+
output["model_type"] = self.__class__.model_type
|
| 424 |
+
return output
|
| 425 |
+
|
VISTA/llava/model/multimodal_encoder/eva_clip/modeling_evaclip.py
ADDED
|
@@ -0,0 +1,1428 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The OpenAI Team Authors and The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" PyTorch EvaCLIP model."""
|
| 16 |
+
# Code mainly taken from https://github.com/huggingface/transformers/blob/main/src/transformers/models/clip/modeling_clip.py#L943
|
| 17 |
+
# and adjusteed for EvaClip
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
from dataclasses import dataclass
|
| 21 |
+
from typing import Any, Optional, Tuple, Union
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
import torch.utils.checkpoint
|
| 25 |
+
from torch import nn
|
| 26 |
+
|
| 27 |
+
from transformers.activations import ACT2FN
|
| 28 |
+
from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
|
| 29 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 30 |
+
from transformers.utils import (
|
| 31 |
+
ModelOutput,
|
| 32 |
+
add_start_docstrings,
|
| 33 |
+
add_start_docstrings_to_model_forward,
|
| 34 |
+
logging,
|
| 35 |
+
replace_return_docstrings,
|
| 36 |
+
)
|
| 37 |
+
from .configuration_evaclip import EvaCLIPConfig, EvaCLIPTextConfig, EvaCLIPVisionConfig
|
| 38 |
+
|
| 39 |
+
logger = logging.get_logger(__name__)
|
| 40 |
+
|
| 41 |
+
_CHECKPOINT_FOR_DOC = "QuanSun/EVA02_CLIP_E_psz14_plus_s9B"
|
| 42 |
+
|
| 43 |
+
Eva_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
| 44 |
+
"EVA02_CLIP_E_psz14_plus_s9B",
|
| 45 |
+
]
|
| 46 |
+
|
| 47 |
+
# Copied from transformers.models.bart.modeling_bart._expand_mask
|
| 48 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
| 49 |
+
"""
|
| 50 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
| 51 |
+
"""
|
| 52 |
+
bsz, src_len = mask.size()
|
| 53 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
| 54 |
+
|
| 55 |
+
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
| 56 |
+
|
| 57 |
+
inverted_mask = 1.0 - expanded_mask
|
| 58 |
+
|
| 59 |
+
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# contrastive loss function, adapted from
|
| 63 |
+
# https://sachinruk.github.io/blog/pytorch/pytorch%20lightning/loss%20function/gpu/2021/03/07/CLIP.html
|
| 64 |
+
def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
|
| 65 |
+
return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device))
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def clip_loss(similarity: torch.Tensor) -> torch.Tensor:
|
| 69 |
+
caption_loss = contrastive_loss(similarity)
|
| 70 |
+
image_loss = contrastive_loss(similarity.t())
|
| 71 |
+
return (caption_loss + image_loss) / 2.0
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
@dataclass
|
| 75 |
+
class EvaCLIPVisionModelOutput(ModelOutput):
|
| 76 |
+
"""
|
| 77 |
+
Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
|
| 78 |
+
|
| 79 |
+
Args:
|
| 80 |
+
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
|
| 81 |
+
The image embeddings obtained by applying the projection layer to the pooler_output.
|
| 82 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 83 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 84 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 85 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 86 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 87 |
+
|
| 88 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 89 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 90 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 91 |
+
sequence_length)`.
|
| 92 |
+
|
| 93 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 94 |
+
heads.
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
image_embeds: Optional[torch.FloatTensor] = None
|
| 98 |
+
last_hidden_state: torch.FloatTensor = None
|
| 99 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 100 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@dataclass
|
| 104 |
+
class EvaCLIPTextModelOutput(ModelOutput):
|
| 105 |
+
"""
|
| 106 |
+
Base class for text model's outputs that also contains a pooling of the last hidden states.
|
| 107 |
+
|
| 108 |
+
Args:
|
| 109 |
+
text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
|
| 110 |
+
The text embeddings obtained by applying the projection layer to the pooler_output.
|
| 111 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 112 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 113 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 114 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 115 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 116 |
+
|
| 117 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 118 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 119 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 120 |
+
sequence_length)`.
|
| 121 |
+
|
| 122 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 123 |
+
heads.
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
text_embeds: Optional[torch.FloatTensor] = None
|
| 127 |
+
last_hidden_state: torch.FloatTensor = None
|
| 128 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 129 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
@dataclass
|
| 133 |
+
class EvaCLIPOutput(ModelOutput):
|
| 134 |
+
"""
|
| 135 |
+
Args:
|
| 136 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
|
| 137 |
+
Contrastive loss for image-text similarity.
|
| 138 |
+
logits_per_image:(`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
|
| 139 |
+
The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
|
| 140 |
+
similarity scores.
|
| 141 |
+
logits_per_text:(`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
|
| 142 |
+
The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
|
| 143 |
+
similarity scores.
|
| 144 |
+
text_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
| 145 |
+
The text embeddings obtained by applying the projection layer to the pooled output of [`EvaCLIPTextModel`].
|
| 146 |
+
image_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
| 147 |
+
The image embeddings obtained by applying the projection layer to the pooled output of [`EvaCLIPVisionModel`].
|
| 148 |
+
text_model_output(`BaseModelOutputWithPooling`):
|
| 149 |
+
The output of the [`EvaCLIPTextModel`].
|
| 150 |
+
vision_model_output(`BaseModelOutputWithPooling`):
|
| 151 |
+
The output of the [`EvaCLIPVisionModel`].
|
| 152 |
+
"""
|
| 153 |
+
|
| 154 |
+
loss: Optional[torch.FloatTensor] = None
|
| 155 |
+
logits_per_image: torch.FloatTensor = None
|
| 156 |
+
logits_per_text: torch.FloatTensor = None
|
| 157 |
+
text_embeds: torch.FloatTensor = None
|
| 158 |
+
image_embeds: torch.FloatTensor = None
|
| 159 |
+
text_model_output: BaseModelOutputWithPooling = None
|
| 160 |
+
vision_model_output: BaseModelOutputWithPooling = None
|
| 161 |
+
|
| 162 |
+
def to_tuple(self) -> Tuple[Any]:
|
| 163 |
+
return tuple(
|
| 164 |
+
self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
|
| 165 |
+
for k in self.keys()
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class EvaCLIPVisionEmbeddings(nn.Module):
|
| 170 |
+
def __init__(self, config: EvaCLIPVisionConfig):
|
| 171 |
+
super().__init__()
|
| 172 |
+
self.config = config
|
| 173 |
+
self.embed_dim = config.hidden_size
|
| 174 |
+
self.image_size = config.image_size
|
| 175 |
+
self.patch_size = config.patch_size
|
| 176 |
+
|
| 177 |
+
self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
|
| 178 |
+
|
| 179 |
+
self.patch_embedding = nn.Conv2d(
|
| 180 |
+
in_channels=config.num_channels,
|
| 181 |
+
out_channels=self.embed_dim,
|
| 182 |
+
kernel_size=self.patch_size,
|
| 183 |
+
stride=self.patch_size,
|
| 184 |
+
bias=True,
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
self.num_patches = (self.image_size // self.patch_size) ** 2
|
| 188 |
+
self.num_positions = self.num_patches + 1
|
| 189 |
+
self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
|
| 190 |
+
self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent = False)
|
| 191 |
+
|
| 192 |
+
def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
|
| 193 |
+
batch_size = pixel_values.shape[0]
|
| 194 |
+
patch_embeds = self.patch_embedding(pixel_values) # shape = [*, width, grid, grid]
|
| 195 |
+
patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
|
| 196 |
+
|
| 197 |
+
class_embeds = self.class_embedding.expand(batch_size, 1, -1)
|
| 198 |
+
embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
|
| 199 |
+
embeddings = embeddings + self.position_embedding(self.position_ids)
|
| 200 |
+
return embeddings
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class EvaCLIPTextEmbeddings(nn.Module):
|
| 204 |
+
def __init__(self, config: EvaCLIPTextConfig):
|
| 205 |
+
super().__init__()
|
| 206 |
+
embed_dim = config.hidden_size
|
| 207 |
+
|
| 208 |
+
self.token_embedding = nn.Embedding(config.vocab_size, embed_dim)
|
| 209 |
+
self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
|
| 210 |
+
|
| 211 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 212 |
+
self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False)
|
| 213 |
+
|
| 214 |
+
def forward(
|
| 215 |
+
self,
|
| 216 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 217 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 218 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 219 |
+
) -> torch.Tensor:
|
| 220 |
+
seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
|
| 221 |
+
|
| 222 |
+
if position_ids is None:
|
| 223 |
+
position_ids = self.position_ids[:, :seq_length]
|
| 224 |
+
|
| 225 |
+
if inputs_embeds is None:
|
| 226 |
+
inputs_embeds = self.token_embedding(input_ids)
|
| 227 |
+
|
| 228 |
+
position_embeddings = self.position_embedding(position_ids)
|
| 229 |
+
embeddings = inputs_embeds + position_embeddings
|
| 230 |
+
|
| 231 |
+
return embeddings
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
class EvaCLIPAttention(nn.Module):
|
| 235 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 236 |
+
|
| 237 |
+
def __init__(self, config):
|
| 238 |
+
super().__init__()
|
| 239 |
+
self.config = config
|
| 240 |
+
self.embed_dim = config.hidden_size
|
| 241 |
+
self.num_heads = config.num_attention_heads
|
| 242 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 243 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
| 244 |
+
raise ValueError(
|
| 245 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
| 246 |
+
f" {self.num_heads})."
|
| 247 |
+
)
|
| 248 |
+
self.scale = self.head_dim**-0.5
|
| 249 |
+
self.dropout = config.attention_dropout
|
| 250 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.k_bias)
|
| 251 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.v_bias)
|
| 252 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.q_bias)
|
| 253 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=True)
|
| 254 |
+
|
| 255 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
| 256 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 257 |
+
|
| 258 |
+
def forward(
|
| 259 |
+
self,
|
| 260 |
+
hidden_states: torch.Tensor,
|
| 261 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 262 |
+
causal_attention_mask: Optional[torch.Tensor] = None,
|
| 263 |
+
output_attentions: Optional[bool] = False,
|
| 264 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 265 |
+
"""Input shape: Batch x Time x Channel"""
|
| 266 |
+
|
| 267 |
+
bsz, tgt_len, embed_dim = hidden_states.size()
|
| 268 |
+
|
| 269 |
+
# get query proj
|
| 270 |
+
query_states = self.q_proj(hidden_states) * self.scale
|
| 271 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 272 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 273 |
+
|
| 274 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
| 275 |
+
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
|
| 276 |
+
key_states = key_states.view(*proj_shape)
|
| 277 |
+
value_states = value_states.view(*proj_shape)
|
| 278 |
+
|
| 279 |
+
src_len = key_states.size(1)
|
| 280 |
+
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
|
| 281 |
+
|
| 282 |
+
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
|
| 283 |
+
raise ValueError(
|
| 284 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
| 285 |
+
f" {attn_weights.size()}"
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
# apply the causal_attention_mask first
|
| 289 |
+
if causal_attention_mask is not None:
|
| 290 |
+
if causal_attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
| 291 |
+
raise ValueError(
|
| 292 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
|
| 293 |
+
f" {causal_attention_mask.size()}"
|
| 294 |
+
)
|
| 295 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + causal_attention_mask
|
| 296 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 297 |
+
|
| 298 |
+
if attention_mask is not None:
|
| 299 |
+
if attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
| 300 |
+
raise ValueError(
|
| 301 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
|
| 302 |
+
)
|
| 303 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
|
| 304 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 305 |
+
|
| 306 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 307 |
+
|
| 308 |
+
if output_attentions:
|
| 309 |
+
# this operation is a bit akward, but it's required to
|
| 310 |
+
# make sure that attn_weights keeps its gradient.
|
| 311 |
+
# In order to do so, attn_weights have to reshaped
|
| 312 |
+
# twice and have to be reused in the following
|
| 313 |
+
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 314 |
+
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
|
| 315 |
+
else:
|
| 316 |
+
attn_weights_reshaped = None
|
| 317 |
+
|
| 318 |
+
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
| 319 |
+
|
| 320 |
+
attn_output = torch.bmm(attn_probs, value_states)
|
| 321 |
+
|
| 322 |
+
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
|
| 323 |
+
raise ValueError(
|
| 324 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
|
| 325 |
+
f" {attn_output.size()}"
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
|
| 329 |
+
attn_output = attn_output.transpose(1, 2)
|
| 330 |
+
attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
|
| 331 |
+
|
| 332 |
+
attn_output = self.out_proj(attn_output)
|
| 333 |
+
|
| 334 |
+
return attn_output, attn_weights_reshaped
|
| 335 |
+
|
| 336 |
+
class EvaCLIPTextAttention(nn.Module):
|
| 337 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 338 |
+
|
| 339 |
+
def __init__(self, config):
|
| 340 |
+
super().__init__()
|
| 341 |
+
self.config = config
|
| 342 |
+
self.embed_dim = config.hidden_size
|
| 343 |
+
self.num_heads = config.num_attention_heads
|
| 344 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 345 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
| 346 |
+
raise ValueError(
|
| 347 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
| 348 |
+
f" {self.num_heads})."
|
| 349 |
+
)
|
| 350 |
+
self.scale = self.head_dim**-0.5
|
| 351 |
+
self.dropout = config.attention_dropout
|
| 352 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.k_bias)
|
| 353 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.v_bias)
|
| 354 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.q_bias)
|
| 355 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=True)
|
| 356 |
+
|
| 357 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
| 358 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 359 |
+
|
| 360 |
+
def forward(
|
| 361 |
+
self,
|
| 362 |
+
hidden_states: torch.Tensor,
|
| 363 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 364 |
+
causal_attention_mask: Optional[torch.Tensor] = None,
|
| 365 |
+
output_attentions: Optional[bool] = False,
|
| 366 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 367 |
+
"""Input shape: Batch x Time x Channel"""
|
| 368 |
+
|
| 369 |
+
bsz, tgt_len, embed_dim = hidden_states.size()
|
| 370 |
+
|
| 371 |
+
# get query proj
|
| 372 |
+
query_states = self.q_proj(hidden_states) * self.scale
|
| 373 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 374 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 375 |
+
|
| 376 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
| 377 |
+
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
|
| 378 |
+
key_states = key_states.view(*proj_shape)
|
| 379 |
+
value_states = value_states.view(*proj_shape)
|
| 380 |
+
|
| 381 |
+
src_len = key_states.size(1)
|
| 382 |
+
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
|
| 383 |
+
|
| 384 |
+
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
|
| 385 |
+
raise ValueError(
|
| 386 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
| 387 |
+
f" {attn_weights.size()}"
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
# apply the causal_attention_mask first
|
| 391 |
+
if causal_attention_mask is not None:
|
| 392 |
+
if causal_attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
| 393 |
+
raise ValueError(
|
| 394 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
|
| 395 |
+
f" {causal_attention_mask.size()}"
|
| 396 |
+
)
|
| 397 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + causal_attention_mask
|
| 398 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 399 |
+
|
| 400 |
+
if attention_mask is not None:
|
| 401 |
+
if attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
| 402 |
+
raise ValueError(
|
| 403 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
|
| 404 |
+
)
|
| 405 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
|
| 406 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 407 |
+
|
| 408 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 409 |
+
|
| 410 |
+
if output_attentions:
|
| 411 |
+
# this operation is a bit akward, but it's required to
|
| 412 |
+
# make sure that attn_weights keeps its gradient.
|
| 413 |
+
# In order to do so, attn_weights have to reshaped
|
| 414 |
+
# twice and have to be reused in the following
|
| 415 |
+
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 416 |
+
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
|
| 417 |
+
else:
|
| 418 |
+
attn_weights_reshaped = None
|
| 419 |
+
|
| 420 |
+
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
| 421 |
+
|
| 422 |
+
attn_output = torch.bmm(attn_probs, value_states)
|
| 423 |
+
|
| 424 |
+
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
|
| 425 |
+
raise ValueError(
|
| 426 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
|
| 427 |
+
f" {attn_output.size()}"
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
|
| 431 |
+
attn_output = attn_output.transpose(1, 2)
|
| 432 |
+
attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
|
| 433 |
+
|
| 434 |
+
attn_output = self.out_proj(attn_output)
|
| 435 |
+
|
| 436 |
+
return attn_output, attn_weights_reshaped
|
| 437 |
+
|
| 438 |
+
class EvaCLIPMLP(nn.Module):
|
| 439 |
+
def __init__(self, config):
|
| 440 |
+
super().__init__()
|
| 441 |
+
self.config = config
|
| 442 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
| 443 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 444 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 445 |
+
|
| 446 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 447 |
+
hidden_states = self.fc1(hidden_states)
|
| 448 |
+
hidden_states = self.activation_fn(hidden_states)
|
| 449 |
+
hidden_states = self.fc2(hidden_states)
|
| 450 |
+
return hidden_states
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
class EvaCLIPEncoderLayer(nn.Module):
|
| 454 |
+
def __init__(self, config: EvaCLIPConfig):
|
| 455 |
+
super().__init__()
|
| 456 |
+
self.config = config
|
| 457 |
+
self.embed_dim = config.hidden_size
|
| 458 |
+
self.post_layernorm = config.post_layernorm if config.post_layernorm is not None else False
|
| 459 |
+
self.self_attn = EvaCLIPAttention(config)
|
| 460 |
+
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 461 |
+
self.mlp = EvaCLIPMLP(config)
|
| 462 |
+
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 463 |
+
|
| 464 |
+
def forward(
|
| 465 |
+
self,
|
| 466 |
+
hidden_states: torch.Tensor,
|
| 467 |
+
attention_mask: torch.Tensor,
|
| 468 |
+
causal_attention_mask: torch.Tensor,
|
| 469 |
+
output_attentions: Optional[bool] = False,
|
| 470 |
+
) -> Tuple[torch.FloatTensor]:
|
| 471 |
+
"""
|
| 472 |
+
Args:
|
| 473 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 474 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 475 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 476 |
+
`(config.encoder_attention_heads,)`.
|
| 477 |
+
output_attentions (`bool`, *optional*):
|
| 478 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 479 |
+
returned tensors for more detail.
|
| 480 |
+
"""
|
| 481 |
+
residual = hidden_states
|
| 482 |
+
|
| 483 |
+
if not self.post_layernorm:
|
| 484 |
+
hidden_states = self.layer_norm1(hidden_states)
|
| 485 |
+
hidden_states, attn_weights = self.self_attn(
|
| 486 |
+
hidden_states=hidden_states,
|
| 487 |
+
attention_mask=attention_mask,
|
| 488 |
+
causal_attention_mask=causal_attention_mask,
|
| 489 |
+
output_attentions=output_attentions,
|
| 490 |
+
)
|
| 491 |
+
if self.post_layernorm:
|
| 492 |
+
hidden_states = self.layer_norm1(hidden_states)
|
| 493 |
+
hidden_states = residual + hidden_states
|
| 494 |
+
residual = hidden_states
|
| 495 |
+
if not self.post_layernorm:
|
| 496 |
+
hidden_states = self.layer_norm2(hidden_states)
|
| 497 |
+
hidden_states = self.mlp(hidden_states)
|
| 498 |
+
if self.post_layernorm:
|
| 499 |
+
hidden_states = self.layer_norm2(hidden_states)
|
| 500 |
+
hidden_states = residual + hidden_states
|
| 501 |
+
|
| 502 |
+
outputs = (hidden_states,)
|
| 503 |
+
|
| 504 |
+
if output_attentions:
|
| 505 |
+
outputs += (attn_weights,)
|
| 506 |
+
|
| 507 |
+
return outputs
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
class EvaCLIPPreTrainedModel(PreTrainedModel):
|
| 511 |
+
"""
|
| 512 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 513 |
+
models.
|
| 514 |
+
"""
|
| 515 |
+
|
| 516 |
+
config_class = EvaCLIPConfig
|
| 517 |
+
base_model_prefix = "clip"
|
| 518 |
+
supports_gradient_checkpointing = True
|
| 519 |
+
_keys_to_ignore_on_load_missing = [r"position_ids"]
|
| 520 |
+
|
| 521 |
+
def _init_weights(self, module):
|
| 522 |
+
"""Initialize the weights"""
|
| 523 |
+
factor = self.config.initializer_factor
|
| 524 |
+
if isinstance(module, EvaCLIPTextEmbeddings):
|
| 525 |
+
module.token_embedding.weight.data.normal_(mean=0.0, std=factor * 0.02)
|
| 526 |
+
module.position_embedding.weight.data.normal_(mean=0.0, std=factor * 0.02)
|
| 527 |
+
elif isinstance(module, EvaCLIPVisionEmbeddings):
|
| 528 |
+
factor = self.config.initializer_factor
|
| 529 |
+
nn.init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
|
| 530 |
+
nn.init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
|
| 531 |
+
nn.init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
|
| 532 |
+
elif isinstance(module, EvaCLIPAttention):
|
| 533 |
+
factor = self.config.initializer_factor
|
| 534 |
+
in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
| 535 |
+
out_proj_std = (module.embed_dim**-0.5) * factor
|
| 536 |
+
nn.init.normal_(module.q_proj.weight, std=in_proj_std)
|
| 537 |
+
nn.init.normal_(module.k_proj.weight, std=in_proj_std)
|
| 538 |
+
nn.init.normal_(module.v_proj.weight, std=in_proj_std)
|
| 539 |
+
nn.init.normal_(module.out_proj.weight, std=out_proj_std)
|
| 540 |
+
elif isinstance(module, EvaCLIPMLP):
|
| 541 |
+
factor = self.config.initializer_factor
|
| 542 |
+
in_proj_std = (
|
| 543 |
+
(module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
| 544 |
+
)
|
| 545 |
+
fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
|
| 546 |
+
nn.init.normal_(module.fc1.weight, std=fc_std)
|
| 547 |
+
nn.init.normal_(module.fc2.weight, std=in_proj_std)
|
| 548 |
+
elif isinstance(module, EvaCLIPModel):
|
| 549 |
+
nn.init.normal_(
|
| 550 |
+
module.text_projection.weight,
|
| 551 |
+
std=module.text_embed_dim**-0.5 * self.config.initializer_factor,
|
| 552 |
+
)
|
| 553 |
+
nn.init.normal_(
|
| 554 |
+
module.visual_projection.weight,
|
| 555 |
+
std=module.vision_embed_dim**-0.5 * self.config.initializer_factor,
|
| 556 |
+
)
|
| 557 |
+
elif isinstance(module, EvaCLIPVisionModelWithProjection):
|
| 558 |
+
nn.init.normal_(
|
| 559 |
+
module.visual_projection.weight,
|
| 560 |
+
std=self.config.hidden_size**-0.5 * self.config.initializer_factor,
|
| 561 |
+
)
|
| 562 |
+
elif isinstance(module, EvaCLIPTextModelWithProjection):
|
| 563 |
+
nn.init.normal_(
|
| 564 |
+
module.text_projection.weight,
|
| 565 |
+
std=self.config.hidden_size**-0.5 * self.config.initializer_factor,
|
| 566 |
+
)
|
| 567 |
+
|
| 568 |
+
if isinstance(module, nn.LayerNorm):
|
| 569 |
+
module.bias.data.zero_()
|
| 570 |
+
module.weight.data.fill_(1.0)
|
| 571 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
| 572 |
+
module.bias.data.zero_()
|
| 573 |
+
|
| 574 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
| 575 |
+
if isinstance(module, EvaCLIPEncoder):
|
| 576 |
+
module.gradient_checkpointing = value
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
EvaCLIP_START_DOCSTRING = r"""
|
| 580 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 581 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 582 |
+
etc.)
|
| 583 |
+
|
| 584 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 585 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 586 |
+
and behavior.
|
| 587 |
+
|
| 588 |
+
Parameters:
|
| 589 |
+
config ([`CLIPConfig`]): Model configuration class with all the parameters of the model.
|
| 590 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 591 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 592 |
+
"""
|
| 593 |
+
|
| 594 |
+
EvaCLIP_TEXT_INPUTS_DOCSTRING = r"""
|
| 595 |
+
Args:
|
| 596 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 597 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 598 |
+
it.
|
| 599 |
+
|
| 600 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 601 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 602 |
+
|
| 603 |
+
[What are input IDs?](../glossary#input-ids)
|
| 604 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 605 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 606 |
+
|
| 607 |
+
- 1 for tokens that are **not masked**,
|
| 608 |
+
- 0 for tokens that are **masked**.
|
| 609 |
+
|
| 610 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 611 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 612 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 613 |
+
config.max_position_embeddings - 1]`.
|
| 614 |
+
|
| 615 |
+
[What are position IDs?](../glossary#position-ids)
|
| 616 |
+
output_attentions (`bool`, *optional*):
|
| 617 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 618 |
+
tensors for more detail.
|
| 619 |
+
output_hidden_states (`bool`, *optional*):
|
| 620 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 621 |
+
more detail.
|
| 622 |
+
return_dict (`bool`, *optional*):
|
| 623 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 624 |
+
"""
|
| 625 |
+
|
| 626 |
+
EvaCLIP_VISION_INPUTS_DOCSTRING = r"""
|
| 627 |
+
Args:
|
| 628 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 629 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
| 630 |
+
[`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
|
| 631 |
+
output_attentions (`bool`, *optional*):
|
| 632 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 633 |
+
tensors for more detail.
|
| 634 |
+
output_hidden_states (`bool`, *optional*):
|
| 635 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 636 |
+
more detail.
|
| 637 |
+
return_dict (`bool`, *optional*):
|
| 638 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 639 |
+
"""
|
| 640 |
+
|
| 641 |
+
EvaCLIP_INPUTS_DOCSTRING = r"""
|
| 642 |
+
Args:
|
| 643 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 644 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 645 |
+
it.
|
| 646 |
+
|
| 647 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 648 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 649 |
+
|
| 650 |
+
[What are input IDs?](../glossary#input-ids)
|
| 651 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 652 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 653 |
+
|
| 654 |
+
- 1 for tokens that are **not masked**,
|
| 655 |
+
- 0 for tokens that are **masked**.
|
| 656 |
+
|
| 657 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 658 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 659 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 660 |
+
config.max_position_embeddings - 1]`.
|
| 661 |
+
|
| 662 |
+
[What are position IDs?](../glossary#position-ids)
|
| 663 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 664 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
| 665 |
+
[`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
|
| 666 |
+
return_loss (`bool`, *optional*):
|
| 667 |
+
Whether or not to return the contrastive loss.
|
| 668 |
+
output_attentions (`bool`, *optional*):
|
| 669 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 670 |
+
tensors for more detail.
|
| 671 |
+
output_hidden_states (`bool`, *optional*):
|
| 672 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 673 |
+
more detail.
|
| 674 |
+
return_dict (`bool`, *optional*):
|
| 675 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 676 |
+
"""
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
class EvaCLIPEncoder(nn.Module):
|
| 680 |
+
"""
|
| 681 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
| 682 |
+
[`CLIPEncoderLayer`].
|
| 683 |
+
|
| 684 |
+
Args:
|
| 685 |
+
config: CLIPConfig
|
| 686 |
+
"""
|
| 687 |
+
|
| 688 |
+
def __init__(self, config: EvaCLIPConfig):
|
| 689 |
+
super().__init__()
|
| 690 |
+
self.config = config
|
| 691 |
+
self.layers = nn.ModuleList([EvaCLIPEncoderLayer(config) for _ in range(config.num_hidden_layers)])
|
| 692 |
+
self.gradient_checkpointing = False
|
| 693 |
+
|
| 694 |
+
def forward(
|
| 695 |
+
self,
|
| 696 |
+
inputs_embeds,
|
| 697 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 698 |
+
causal_attention_mask: Optional[torch.Tensor] = None,
|
| 699 |
+
output_attentions: Optional[bool] = None,
|
| 700 |
+
output_hidden_states: Optional[bool] = None,
|
| 701 |
+
return_dict: Optional[bool] = None,
|
| 702 |
+
) -> Union[Tuple, BaseModelOutput]:
|
| 703 |
+
r"""
|
| 704 |
+
Args:
|
| 705 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 706 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 707 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 708 |
+
than the model's internal embedding lookup matrix.
|
| 709 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 710 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 711 |
+
|
| 712 |
+
- 1 for tokens that are **not masked**,
|
| 713 |
+
- 0 for tokens that are **masked**.
|
| 714 |
+
|
| 715 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 716 |
+
causal_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 717 |
+
Causal mask for the text model. Mask values selected in `[0, 1]`:
|
| 718 |
+
|
| 719 |
+
- 1 for tokens that are **not masked**,
|
| 720 |
+
- 0 for tokens that are **masked**.
|
| 721 |
+
|
| 722 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 723 |
+
output_attentions (`bool`, *optional*):
|
| 724 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 725 |
+
returned tensors for more detail.
|
| 726 |
+
output_hidden_states (`bool`, *optional*):
|
| 727 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 728 |
+
for more detail.
|
| 729 |
+
return_dict (`bool`, *optional*):
|
| 730 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 731 |
+
"""
|
| 732 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 733 |
+
output_hidden_states = (
|
| 734 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 735 |
+
)
|
| 736 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 737 |
+
|
| 738 |
+
encoder_states = () if output_hidden_states else None
|
| 739 |
+
all_attentions = () if output_attentions else None
|
| 740 |
+
|
| 741 |
+
hidden_states = inputs_embeds
|
| 742 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 743 |
+
if output_hidden_states:
|
| 744 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 745 |
+
if self.gradient_checkpointing and self.training:
|
| 746 |
+
|
| 747 |
+
def create_custom_forward(module):
|
| 748 |
+
def custom_forward(*inputs):
|
| 749 |
+
return module(*inputs, output_attentions)
|
| 750 |
+
|
| 751 |
+
return custom_forward
|
| 752 |
+
|
| 753 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
| 754 |
+
create_custom_forward(encoder_layer),
|
| 755 |
+
hidden_states,
|
| 756 |
+
attention_mask,
|
| 757 |
+
causal_attention_mask,
|
| 758 |
+
)
|
| 759 |
+
else:
|
| 760 |
+
layer_outputs = encoder_layer(
|
| 761 |
+
hidden_states,
|
| 762 |
+
attention_mask,
|
| 763 |
+
causal_attention_mask,
|
| 764 |
+
output_attentions=output_attentions,
|
| 765 |
+
)
|
| 766 |
+
|
| 767 |
+
hidden_states = layer_outputs[0]
|
| 768 |
+
|
| 769 |
+
if output_attentions:
|
| 770 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 771 |
+
|
| 772 |
+
if output_hidden_states:
|
| 773 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 774 |
+
|
| 775 |
+
if not return_dict:
|
| 776 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 777 |
+
return BaseModelOutput(
|
| 778 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
| 779 |
+
)
|
| 780 |
+
|
| 781 |
+
|
| 782 |
+
class EvaCLIPTextTransformer(nn.Module):
|
| 783 |
+
def __init__(self, config: EvaCLIPTextConfig):
|
| 784 |
+
super().__init__()
|
| 785 |
+
self.config = config
|
| 786 |
+
embed_dim = config.hidden_size
|
| 787 |
+
self.embeddings = EvaCLIPTextEmbeddings(config)
|
| 788 |
+
self.encoder = EvaCLIPEncoder(config)
|
| 789 |
+
self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 790 |
+
|
| 791 |
+
@add_start_docstrings_to_model_forward(EvaCLIP_TEXT_INPUTS_DOCSTRING)
|
| 792 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=EvaCLIPTextConfig)
|
| 793 |
+
def forward(
|
| 794 |
+
self,
|
| 795 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 796 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 797 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 798 |
+
output_attentions: Optional[bool] = None,
|
| 799 |
+
output_hidden_states: Optional[bool] = None,
|
| 800 |
+
return_dict: Optional[bool] = None,
|
| 801 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 802 |
+
r"""
|
| 803 |
+
Returns:
|
| 804 |
+
|
| 805 |
+
"""
|
| 806 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 807 |
+
output_hidden_states = (
|
| 808 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 809 |
+
)
|
| 810 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 811 |
+
|
| 812 |
+
if input_ids is None:
|
| 813 |
+
raise ValueError("You have to specify input_ids")
|
| 814 |
+
|
| 815 |
+
input_shape = input_ids.size()
|
| 816 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 817 |
+
|
| 818 |
+
hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids)
|
| 819 |
+
|
| 820 |
+
bsz, seq_len = input_shape
|
| 821 |
+
# CLIP's text model uses causal mask, prepare it here.
|
| 822 |
+
# https://github.com/openai/CLIP/blob/cfcffb90e69f37bf2ff1e988237a0fbe41f33c04/clip/model.py#L324
|
| 823 |
+
causal_attention_mask = self._build_causal_attention_mask(bsz, seq_len, hidden_states.dtype).to(
|
| 824 |
+
hidden_states.device
|
| 825 |
+
)
|
| 826 |
+
# expand attention_mask
|
| 827 |
+
if attention_mask is not None:
|
| 828 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 829 |
+
attention_mask = _expand_mask(attention_mask, hidden_states.dtype)
|
| 830 |
+
|
| 831 |
+
encoder_outputs = self.encoder(
|
| 832 |
+
inputs_embeds=hidden_states,
|
| 833 |
+
attention_mask=attention_mask,
|
| 834 |
+
causal_attention_mask=causal_attention_mask,
|
| 835 |
+
output_attentions=output_attentions,
|
| 836 |
+
output_hidden_states=output_hidden_states,
|
| 837 |
+
return_dict=return_dict,
|
| 838 |
+
)
|
| 839 |
+
|
| 840 |
+
last_hidden_state = encoder_outputs[0]
|
| 841 |
+
last_hidden_state = self.final_layer_norm(last_hidden_state)
|
| 842 |
+
|
| 843 |
+
# text_embeds.shape = [batch_size, sequence_length, transformer.width]
|
| 844 |
+
# take features from the eot embedding (eot_token is the highest number in each sequence)
|
| 845 |
+
# casting to torch.int for onnx compatibility: argmax doesn't support int64 inputs with opset 14
|
| 846 |
+
pooled_output = last_hidden_state[
|
| 847 |
+
torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device),
|
| 848 |
+
input_ids.to(dtype=torch.int, device=last_hidden_state.device).argmax(dim=-1),
|
| 849 |
+
]
|
| 850 |
+
|
| 851 |
+
if not return_dict:
|
| 852 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
| 853 |
+
|
| 854 |
+
return BaseModelOutputWithPooling(
|
| 855 |
+
last_hidden_state=last_hidden_state,
|
| 856 |
+
pooler_output=pooled_output,
|
| 857 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 858 |
+
attentions=encoder_outputs.attentions,
|
| 859 |
+
)
|
| 860 |
+
|
| 861 |
+
def _build_causal_attention_mask(self, bsz, seq_len, dtype):
|
| 862 |
+
# lazily create causal attention mask, with full attention between the vision tokens
|
| 863 |
+
# pytorch uses additive attention mask; fill with -inf
|
| 864 |
+
mask = torch.empty(bsz, seq_len, seq_len, dtype=dtype)
|
| 865 |
+
mask.fill_(torch.tensor(torch.finfo(dtype).min))
|
| 866 |
+
mask.triu_(1) # zero out the lower diagonal
|
| 867 |
+
mask = mask.unsqueeze(1) # expand mask
|
| 868 |
+
return mask
|
| 869 |
+
|
| 870 |
+
|
| 871 |
+
@add_start_docstrings(
|
| 872 |
+
"""The text model from EvaCLIP without any head or projection on top.""",
|
| 873 |
+
EvaCLIP_START_DOCSTRING,
|
| 874 |
+
)
|
| 875 |
+
class EvaCLIPTextModel(EvaCLIPPreTrainedModel):
|
| 876 |
+
config_class = EvaCLIPTextConfig
|
| 877 |
+
|
| 878 |
+
_no_split_modules = ["EvaCLIPEncoderLayer"]
|
| 879 |
+
|
| 880 |
+
def __init__(self, config: EvaCLIPTextConfig):
|
| 881 |
+
super().__init__(config)
|
| 882 |
+
self.text_model = EvaCLIPTextTransformer(config)
|
| 883 |
+
# Initialize weights and apply final processing
|
| 884 |
+
self.post_init()
|
| 885 |
+
|
| 886 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 887 |
+
return self.text_model.embeddings.token_embedding
|
| 888 |
+
|
| 889 |
+
def set_input_embeddings(self, value):
|
| 890 |
+
self.text_model.embeddings.token_embedding = value
|
| 891 |
+
|
| 892 |
+
@add_start_docstrings_to_model_forward(EvaCLIP_TEXT_INPUTS_DOCSTRING)
|
| 893 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=EvaCLIPTextConfig)
|
| 894 |
+
def forward(
|
| 895 |
+
self,
|
| 896 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 897 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 898 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 899 |
+
output_attentions: Optional[bool] = None,
|
| 900 |
+
output_hidden_states: Optional[bool] = None,
|
| 901 |
+
return_dict: Optional[bool] = None,
|
| 902 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 903 |
+
r"""
|
| 904 |
+
Returns:
|
| 905 |
+
|
| 906 |
+
Examples:
|
| 907 |
+
|
| 908 |
+
```python
|
| 909 |
+
>>> from transformers import AutoTokenizer, CLIPTextModel
|
| 910 |
+
|
| 911 |
+
>>> model = CLIPTextModel.from_pretrained("openai/clip-vit-base-patch32")
|
| 912 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
|
| 913 |
+
|
| 914 |
+
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
|
| 915 |
+
|
| 916 |
+
>>> outputs = model(**inputs)
|
| 917 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
| 918 |
+
>>> pooled_output = outputs.pooler_output # pooled (EOS token) states
|
| 919 |
+
```"""
|
| 920 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 921 |
+
|
| 922 |
+
return self.text_model(
|
| 923 |
+
input_ids=input_ids,
|
| 924 |
+
attention_mask=attention_mask,
|
| 925 |
+
position_ids=position_ids,
|
| 926 |
+
output_attentions=output_attentions,
|
| 927 |
+
output_hidden_states=output_hidden_states,
|
| 928 |
+
return_dict=return_dict,
|
| 929 |
+
)
|
| 930 |
+
|
| 931 |
+
|
| 932 |
+
class EvaCLIPVisionTransformer(nn.Module):
|
| 933 |
+
def __init__(self, config: EvaCLIPVisionConfig):
|
| 934 |
+
super().__init__()
|
| 935 |
+
self.config = config
|
| 936 |
+
embed_dim = config.hidden_size
|
| 937 |
+
|
| 938 |
+
self.embeddings = EvaCLIPVisionEmbeddings(config)
|
| 939 |
+
self.encoder = EvaCLIPEncoder(config)
|
| 940 |
+
self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 941 |
+
|
| 942 |
+
@add_start_docstrings_to_model_forward(EvaCLIP_VISION_INPUTS_DOCSTRING)
|
| 943 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=EvaCLIPVisionConfig)
|
| 944 |
+
def forward(
|
| 945 |
+
self,
|
| 946 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 947 |
+
output_attentions: Optional[bool] = None,
|
| 948 |
+
output_hidden_states: Optional[bool] = None,
|
| 949 |
+
return_dict: Optional[bool] = None,
|
| 950 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 951 |
+
r"""
|
| 952 |
+
Returns:
|
| 953 |
+
|
| 954 |
+
"""
|
| 955 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 956 |
+
output_hidden_states = (
|
| 957 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 958 |
+
)
|
| 959 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 960 |
+
|
| 961 |
+
if pixel_values is None:
|
| 962 |
+
raise ValueError("You have to specify pixel_values")
|
| 963 |
+
|
| 964 |
+
hidden_states = self.embeddings(pixel_values)
|
| 965 |
+
|
| 966 |
+
encoder_outputs = self.encoder(
|
| 967 |
+
inputs_embeds=hidden_states,
|
| 968 |
+
output_attentions=output_attentions,
|
| 969 |
+
output_hidden_states=output_hidden_states,
|
| 970 |
+
return_dict=return_dict,
|
| 971 |
+
)
|
| 972 |
+
|
| 973 |
+
last_hidden_state = encoder_outputs[0]
|
| 974 |
+
pooled_output = last_hidden_state[:, 0, :]
|
| 975 |
+
pooled_output = self.post_layernorm(pooled_output)
|
| 976 |
+
|
| 977 |
+
if not return_dict:
|
| 978 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
| 979 |
+
|
| 980 |
+
return BaseModelOutputWithPooling(
|
| 981 |
+
last_hidden_state=last_hidden_state,
|
| 982 |
+
pooler_output=pooled_output,
|
| 983 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 984 |
+
attentions=encoder_outputs.attentions,
|
| 985 |
+
)
|
| 986 |
+
|
| 987 |
+
|
| 988 |
+
@add_start_docstrings(
|
| 989 |
+
"""The vision model from EvaCLIP without any head or projection on top.""",
|
| 990 |
+
EvaCLIP_START_DOCSTRING,
|
| 991 |
+
)
|
| 992 |
+
class EvaCLIPVisionModel(EvaCLIPPreTrainedModel):
|
| 993 |
+
config_class = EvaCLIPVisionConfig
|
| 994 |
+
main_input_name = "pixel_values"
|
| 995 |
+
|
| 996 |
+
def __init__(self, config: EvaCLIPVisionConfig):
|
| 997 |
+
super().__init__(config)
|
| 998 |
+
self.vision_model = EvaCLIPVisionTransformer(config)
|
| 999 |
+
# Initialize weights and apply final processing
|
| 1000 |
+
self.post_init()
|
| 1001 |
+
|
| 1002 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 1003 |
+
return self.vision_model.embeddings.patch_embedding
|
| 1004 |
+
|
| 1005 |
+
@add_start_docstrings_to_model_forward(EvaCLIP_VISION_INPUTS_DOCSTRING)
|
| 1006 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=EvaCLIPVisionConfig)
|
| 1007 |
+
def forward(
|
| 1008 |
+
self,
|
| 1009 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1010 |
+
output_attentions: Optional[bool] = None,
|
| 1011 |
+
output_hidden_states: Optional[bool] = None,
|
| 1012 |
+
return_dict: Optional[bool] = None,
|
| 1013 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 1014 |
+
r"""
|
| 1015 |
+
Returns:
|
| 1016 |
+
|
| 1017 |
+
Examples:
|
| 1018 |
+
|
| 1019 |
+
```python
|
| 1020 |
+
>>> from PIL import Image
|
| 1021 |
+
>>> import requests
|
| 1022 |
+
>>> from transformers import AutoProcessor, CLIPVisionModel
|
| 1023 |
+
|
| 1024 |
+
>>> model = CLIPVisionModel.from_pretrained("openai/clip-vit-base-patch32")
|
| 1025 |
+
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
| 1026 |
+
|
| 1027 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1028 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1029 |
+
|
| 1030 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 1031 |
+
|
| 1032 |
+
>>> outputs = model(**inputs)
|
| 1033 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
| 1034 |
+
>>> pooled_output = outputs.pooler_output # pooled CLS states
|
| 1035 |
+
```"""
|
| 1036 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1037 |
+
|
| 1038 |
+
return self.vision_model(
|
| 1039 |
+
pixel_values=pixel_values,
|
| 1040 |
+
output_attentions=output_attentions,
|
| 1041 |
+
output_hidden_states=output_hidden_states,
|
| 1042 |
+
return_dict=return_dict,
|
| 1043 |
+
)
|
| 1044 |
+
|
| 1045 |
+
|
| 1046 |
+
@add_start_docstrings(EvaCLIP_START_DOCSTRING)
|
| 1047 |
+
class EvaCLIPModel(EvaCLIPPreTrainedModel):
|
| 1048 |
+
config_class = EvaCLIPConfig
|
| 1049 |
+
|
| 1050 |
+
def __init__(self, config: EvaCLIPConfig):
|
| 1051 |
+
super().__init__(config)
|
| 1052 |
+
|
| 1053 |
+
if not (type(config.text_config).__name__ == "EvaCLIPTextConfig"):
|
| 1054 |
+
raise ValueError(
|
| 1055 |
+
"config.text_config is expected to be of type EvaCLIPTextConfig but is of type"
|
| 1056 |
+
f" {type(config.text_config)}."
|
| 1057 |
+
)
|
| 1058 |
+
|
| 1059 |
+
if not (type(config.vision_config).__name__ == "EvaCLIPVisionConfig"):
|
| 1060 |
+
raise ValueError(
|
| 1061 |
+
"config.vision_config is expected to be of type EvaCLIPVisionConfig but is of type"
|
| 1062 |
+
f" {type(config.vision_config)}."
|
| 1063 |
+
)
|
| 1064 |
+
|
| 1065 |
+
text_config = config.text_config
|
| 1066 |
+
vision_config = config.vision_config
|
| 1067 |
+
|
| 1068 |
+
self.projection_dim = config.projection_dim
|
| 1069 |
+
self.text_embed_dim = text_config.hidden_size
|
| 1070 |
+
self.vision_embed_dim = vision_config.hidden_size
|
| 1071 |
+
|
| 1072 |
+
self.text_model = EvaCLIPTextTransformer(text_config)
|
| 1073 |
+
self.vision_model = EvaCLIPVisionTransformer(vision_config)
|
| 1074 |
+
|
| 1075 |
+
self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=True)
|
| 1076 |
+
self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False)
|
| 1077 |
+
self.logit_scale = nn.Parameter(torch.ones([]) * self.config.logit_scale_init_value)
|
| 1078 |
+
|
| 1079 |
+
# Initialize weights and apply final processing
|
| 1080 |
+
self.post_init()
|
| 1081 |
+
|
| 1082 |
+
@add_start_docstrings_to_model_forward(EvaCLIP_TEXT_INPUTS_DOCSTRING)
|
| 1083 |
+
def get_text_features(
|
| 1084 |
+
self,
|
| 1085 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1086 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1087 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1088 |
+
output_attentions: Optional[bool] = None,
|
| 1089 |
+
output_hidden_states: Optional[bool] = None,
|
| 1090 |
+
return_dict: Optional[bool] = None,
|
| 1091 |
+
) -> torch.FloatTensor:
|
| 1092 |
+
r"""
|
| 1093 |
+
Returns:
|
| 1094 |
+
text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
|
| 1095 |
+
applying the projection layer to the pooled output of [`CLIPTextModel`].
|
| 1096 |
+
|
| 1097 |
+
Examples:
|
| 1098 |
+
|
| 1099 |
+
```python
|
| 1100 |
+
>>> from transformers import AutoTokenizer, CLIPModel
|
| 1101 |
+
|
| 1102 |
+
>>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
| 1103 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
|
| 1104 |
+
|
| 1105 |
+
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
|
| 1106 |
+
>>> text_features = model.get_text_features(**inputs)
|
| 1107 |
+
```"""
|
| 1108 |
+
# Use CLIP model's config for some fields (if specified) instead of those of vision & text components.
|
| 1109 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1110 |
+
output_hidden_states = (
|
| 1111 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1112 |
+
)
|
| 1113 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1114 |
+
|
| 1115 |
+
text_outputs = self.text_model(
|
| 1116 |
+
input_ids=input_ids,
|
| 1117 |
+
attention_mask=attention_mask,
|
| 1118 |
+
position_ids=position_ids,
|
| 1119 |
+
output_attentions=output_attentions,
|
| 1120 |
+
output_hidden_states=output_hidden_states,
|
| 1121 |
+
return_dict=return_dict,
|
| 1122 |
+
)
|
| 1123 |
+
|
| 1124 |
+
pooled_output = text_outputs[1]
|
| 1125 |
+
text_features = self.text_projection(pooled_output)
|
| 1126 |
+
|
| 1127 |
+
return text_features
|
| 1128 |
+
|
| 1129 |
+
@add_start_docstrings_to_model_forward(EvaCLIP_VISION_INPUTS_DOCSTRING)
|
| 1130 |
+
def get_image_features(
|
| 1131 |
+
self,
|
| 1132 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1133 |
+
output_attentions: Optional[bool] = None,
|
| 1134 |
+
output_hidden_states: Optional[bool] = None,
|
| 1135 |
+
return_dict: Optional[bool] = None,
|
| 1136 |
+
) -> torch.FloatTensor:
|
| 1137 |
+
r"""
|
| 1138 |
+
Returns:
|
| 1139 |
+
image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
|
| 1140 |
+
applying the projection layer to the pooled output of [`EvaCLIPVisionModel`].
|
| 1141 |
+
|
| 1142 |
+
Examples:
|
| 1143 |
+
|
| 1144 |
+
```python
|
| 1145 |
+
>>> from PIL import Image
|
| 1146 |
+
>>> import requests
|
| 1147 |
+
>>> from transformers import AutoProcessor, CLIPModel
|
| 1148 |
+
|
| 1149 |
+
>>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
| 1150 |
+
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
| 1151 |
+
|
| 1152 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1153 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1154 |
+
|
| 1155 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 1156 |
+
|
| 1157 |
+
>>> image_features = model.get_image_features(**inputs)
|
| 1158 |
+
```"""
|
| 1159 |
+
# Use EvaCLIP model's config for some fields (if specified) instead of those of vision & text components.
|
| 1160 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1161 |
+
output_hidden_states = (
|
| 1162 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1163 |
+
)
|
| 1164 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1165 |
+
|
| 1166 |
+
vision_outputs = self.vision_model(
|
| 1167 |
+
pixel_values=pixel_values,
|
| 1168 |
+
output_attentions=output_attentions,
|
| 1169 |
+
output_hidden_states=output_hidden_states,
|
| 1170 |
+
return_dict=return_dict,
|
| 1171 |
+
)
|
| 1172 |
+
|
| 1173 |
+
pooled_output = vision_outputs[1] # pooled_output
|
| 1174 |
+
image_features = self.visual_projection(pooled_output)
|
| 1175 |
+
|
| 1176 |
+
return image_features
|
| 1177 |
+
|
| 1178 |
+
@add_start_docstrings_to_model_forward(EvaCLIP_INPUTS_DOCSTRING)
|
| 1179 |
+
@replace_return_docstrings(output_type=EvaCLIPOutput, config_class=EvaCLIPConfig)
|
| 1180 |
+
def forward(
|
| 1181 |
+
self,
|
| 1182 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1183 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1184 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1185 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1186 |
+
return_loss: Optional[bool] = None,
|
| 1187 |
+
output_attentions: Optional[bool] = None,
|
| 1188 |
+
output_hidden_states: Optional[bool] = None,
|
| 1189 |
+
return_dict: Optional[bool] = None,
|
| 1190 |
+
) -> Union[Tuple, EvaCLIPOutput]:
|
| 1191 |
+
r"""
|
| 1192 |
+
Returns:
|
| 1193 |
+
|
| 1194 |
+
Examples:
|
| 1195 |
+
|
| 1196 |
+
```python
|
| 1197 |
+
>>> from PIL import Image
|
| 1198 |
+
>>> import requests
|
| 1199 |
+
>>> from transformers import AutoProcessor, CLIPModel
|
| 1200 |
+
|
| 1201 |
+
>>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
| 1202 |
+
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
| 1203 |
+
|
| 1204 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1205 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1206 |
+
|
| 1207 |
+
>>> inputs = processor(
|
| 1208 |
+
... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True
|
| 1209 |
+
... )
|
| 1210 |
+
|
| 1211 |
+
>>> outputs = model(**inputs)
|
| 1212 |
+
>>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
|
| 1213 |
+
>>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
|
| 1214 |
+
```"""
|
| 1215 |
+
# Use CLIP model's config for some fields (if specified) instead of those of vision & text components.
|
| 1216 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1217 |
+
output_hidden_states = (
|
| 1218 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1219 |
+
)
|
| 1220 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1221 |
+
|
| 1222 |
+
vision_outputs = self.vision_model(
|
| 1223 |
+
pixel_values=pixel_values,
|
| 1224 |
+
output_attentions=output_attentions,
|
| 1225 |
+
output_hidden_states=output_hidden_states,
|
| 1226 |
+
return_dict=return_dict,
|
| 1227 |
+
)
|
| 1228 |
+
|
| 1229 |
+
text_outputs = self.text_model(
|
| 1230 |
+
input_ids=input_ids,
|
| 1231 |
+
attention_mask=attention_mask,
|
| 1232 |
+
position_ids=position_ids,
|
| 1233 |
+
output_attentions=output_attentions,
|
| 1234 |
+
output_hidden_states=output_hidden_states,
|
| 1235 |
+
return_dict=return_dict,
|
| 1236 |
+
)
|
| 1237 |
+
|
| 1238 |
+
image_embeds = vision_outputs[1]
|
| 1239 |
+
image_embeds = self.visual_projection(image_embeds)
|
| 1240 |
+
|
| 1241 |
+
text_embeds = text_outputs[1]
|
| 1242 |
+
text_embeds = self.text_projection(text_embeds)
|
| 1243 |
+
|
| 1244 |
+
# normalized features
|
| 1245 |
+
image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
|
| 1246 |
+
text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
|
| 1247 |
+
|
| 1248 |
+
# cosine similarity as logits
|
| 1249 |
+
logit_scale = self.logit_scale.exp()
|
| 1250 |
+
logits_per_text = torch.matmul(text_embeds, image_embeds.t()) * logit_scale
|
| 1251 |
+
logits_per_image = logits_per_text.t()
|
| 1252 |
+
|
| 1253 |
+
loss = None
|
| 1254 |
+
if return_loss:
|
| 1255 |
+
loss = clip_loss(logits_per_text)
|
| 1256 |
+
|
| 1257 |
+
if not return_dict:
|
| 1258 |
+
output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
|
| 1259 |
+
return ((loss,) + output) if loss is not None else output
|
| 1260 |
+
|
| 1261 |
+
return EvaCLIPOutput(
|
| 1262 |
+
loss=loss,
|
| 1263 |
+
logits_per_image=logits_per_image,
|
| 1264 |
+
logits_per_text=logits_per_text,
|
| 1265 |
+
text_embeds=text_embeds,
|
| 1266 |
+
image_embeds=image_embeds,
|
| 1267 |
+
text_model_output=text_outputs,
|
| 1268 |
+
vision_model_output=vision_outputs,
|
| 1269 |
+
)
|
| 1270 |
+
|
| 1271 |
+
|
| 1272 |
+
@add_start_docstrings(
|
| 1273 |
+
"""
|
| 1274 |
+
EvaCLIP Text Model with a projection layer on top (a linear layer on top of the pooled output).
|
| 1275 |
+
""",
|
| 1276 |
+
EvaCLIP_START_DOCSTRING,
|
| 1277 |
+
)
|
| 1278 |
+
class EvaCLIPTextModelWithProjection(EvaCLIPPreTrainedModel):
|
| 1279 |
+
config_class = EvaCLIPTextConfig
|
| 1280 |
+
|
| 1281 |
+
_no_split_modules = ["EvaCLIPEncoderLayer"]
|
| 1282 |
+
|
| 1283 |
+
def __init__(self, config: EvaCLIPTextConfig):
|
| 1284 |
+
super().__init__(config)
|
| 1285 |
+
|
| 1286 |
+
self.text_model = EvaCLIPTextTransformer(config)
|
| 1287 |
+
|
| 1288 |
+
self.text_projection = nn.Linear(config.hidden_size, config.projection_dim, bias=False)
|
| 1289 |
+
|
| 1290 |
+
# Initialize weights and apply final processing
|
| 1291 |
+
self.posxt_init()
|
| 1292 |
+
|
| 1293 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 1294 |
+
return self.text_model.embeddings.token_embedding
|
| 1295 |
+
|
| 1296 |
+
def set_input_embeddings(self, value):
|
| 1297 |
+
self.text_model.embeddings.token_embedding = value
|
| 1298 |
+
|
| 1299 |
+
@add_start_docstrings_to_model_forward(EvaCLIP_TEXT_INPUTS_DOCSTRING)
|
| 1300 |
+
@replace_return_docstrings(output_type=EvaCLIPTextModelOutput, config_class=EvaCLIPTextConfig)
|
| 1301 |
+
def forward(
|
| 1302 |
+
self,
|
| 1303 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1304 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1305 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1306 |
+
output_attentions: Optional[bool] = None,
|
| 1307 |
+
output_hidden_states: Optional[bool] = None,
|
| 1308 |
+
return_dict: Optional[bool] = None,
|
| 1309 |
+
) -> Union[Tuple, EvaCLIPTextModelOutput]:
|
| 1310 |
+
r"""
|
| 1311 |
+
Returns:
|
| 1312 |
+
|
| 1313 |
+
Examples:
|
| 1314 |
+
|
| 1315 |
+
```python
|
| 1316 |
+
>>> from transformers import AutoTokenizer, CLIPTextModelWithProjection
|
| 1317 |
+
|
| 1318 |
+
>>> model = CLIPTextModelWithProjection.from_pretrained("openai/clip-vit-base-patch32")
|
| 1319 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
|
| 1320 |
+
|
| 1321 |
+
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
|
| 1322 |
+
|
| 1323 |
+
>>> outputs = model(**inputs)
|
| 1324 |
+
>>> text_embeds = outputs.text_embeds
|
| 1325 |
+
```"""
|
| 1326 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1327 |
+
|
| 1328 |
+
text_outputs = self.text_model(
|
| 1329 |
+
input_ids=input_ids,
|
| 1330 |
+
attention_mask=attention_mask,
|
| 1331 |
+
position_ids=position_ids,
|
| 1332 |
+
output_attentions=output_attentions,
|
| 1333 |
+
output_hidden_states=output_hidden_states,
|
| 1334 |
+
return_dict=return_dict,
|
| 1335 |
+
)
|
| 1336 |
+
|
| 1337 |
+
pooled_output = text_outputs[1]
|
| 1338 |
+
|
| 1339 |
+
text_embeds = self.text_projection(pooled_output)
|
| 1340 |
+
|
| 1341 |
+
if not return_dict:
|
| 1342 |
+
outputs = (text_embeds, text_outputs[0]) + text_outputs[2:]
|
| 1343 |
+
return tuple(output for output in outputs if output is not None)
|
| 1344 |
+
|
| 1345 |
+
return EvaCLIPTextModelOutput(
|
| 1346 |
+
text_embeds=text_embeds,
|
| 1347 |
+
last_hidden_state=text_outputs.last_hidden_state,
|
| 1348 |
+
hidden_states=text_outputs.hidden_states,
|
| 1349 |
+
attentions=text_outputs.attentions,
|
| 1350 |
+
)
|
| 1351 |
+
|
| 1352 |
+
|
| 1353 |
+
@add_start_docstrings(
|
| 1354 |
+
"""
|
| 1355 |
+
EvaCLIP Vision Model with a projection layer on top (a linear layer on top of the pooled output).
|
| 1356 |
+
""",
|
| 1357 |
+
EvaCLIP_START_DOCSTRING,
|
| 1358 |
+
)
|
| 1359 |
+
class EvaCLIPVisionModelWithProjection(EvaCLIPPreTrainedModel):
|
| 1360 |
+
config_class = EvaCLIPVisionConfig
|
| 1361 |
+
main_input_name = "pixel_values"
|
| 1362 |
+
|
| 1363 |
+
def __init__(self, config: EvaCLIPVisionConfig):
|
| 1364 |
+
super().__init__(config)
|
| 1365 |
+
|
| 1366 |
+
self.vision_model = EvaCLIPVisionTransformer(config)
|
| 1367 |
+
|
| 1368 |
+
self.visual_projection = nn.Linear(config.hidden_size, config.projection_dim, bias=False)
|
| 1369 |
+
|
| 1370 |
+
# Initialize weights and apply final processing
|
| 1371 |
+
self.post_init()
|
| 1372 |
+
|
| 1373 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 1374 |
+
return self.vision_model.embeddings.patch_embedding
|
| 1375 |
+
|
| 1376 |
+
@add_start_docstrings_to_model_forward(EvaCLIP_VISION_INPUTS_DOCSTRING)
|
| 1377 |
+
@replace_return_docstrings(output_type=EvaCLIPVisionModelOutput, config_class=EvaCLIPVisionConfig)
|
| 1378 |
+
def forward(
|
| 1379 |
+
self,
|
| 1380 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1381 |
+
output_attentions: Optional[bool] = None,
|
| 1382 |
+
output_hidden_states: Optional[bool] = None,
|
| 1383 |
+
return_dict: Optional[bool] = None,
|
| 1384 |
+
) -> Union[Tuple, EvaCLIPVisionModelOutput]:
|
| 1385 |
+
r"""
|
| 1386 |
+
Returns:
|
| 1387 |
+
|
| 1388 |
+
Examples:
|
| 1389 |
+
|
| 1390 |
+
```python
|
| 1391 |
+
>>> from PIL import Image
|
| 1392 |
+
>>> import requests
|
| 1393 |
+
>>> from transformers import AutoProcessor, CLIPVisionModelWithProjection
|
| 1394 |
+
|
| 1395 |
+
>>> model = CLIPVisionModelWithProjection.from_pretrained("openai/clip-vit-base-patch32")
|
| 1396 |
+
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
| 1397 |
+
|
| 1398 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1399 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1400 |
+
|
| 1401 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 1402 |
+
|
| 1403 |
+
>>> outputs = model(**inputs)
|
| 1404 |
+
>>> image_embeds = outputs.image_embeds
|
| 1405 |
+
```"""
|
| 1406 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1407 |
+
|
| 1408 |
+
vision_outputs = self.vision_model(
|
| 1409 |
+
pixel_values=pixel_values,
|
| 1410 |
+
output_attentions=output_attentions,
|
| 1411 |
+
output_hidden_states=output_hidden_states,
|
| 1412 |
+
return_dict=return_dict,
|
| 1413 |
+
)
|
| 1414 |
+
|
| 1415 |
+
pooled_output = vision_outputs[1] # pooled_output
|
| 1416 |
+
|
| 1417 |
+
image_embeds = self.visual_projection(pooled_output)
|
| 1418 |
+
|
| 1419 |
+
if not return_dict:
|
| 1420 |
+
outputs = (image_embeds, vision_outputs[0]) + vision_outputs[2:]
|
| 1421 |
+
return tuple(output for output in outputs if output is not None)
|
| 1422 |
+
|
| 1423 |
+
return EvaCLIPVisionModelOutput(
|
| 1424 |
+
image_embeds=image_embeds,
|
| 1425 |
+
last_hidden_state=vision_outputs.last_hidden_state,
|
| 1426 |
+
hidden_states=vision_outputs.hidden_states,
|
| 1427 |
+
attentions=vision_outputs.attentions,
|
| 1428 |
+
)
|
VISTA/llava/model/multimodal_encoder/intern_vit_6b/__pycache__/configuration_intern_vit.cpython-310.pyc
ADDED
|
Binary file (5.01 kB). View file
|
|
|
VISTA/llava/model/multimodal_encoder/intern_vit_6b/__pycache__/flash_attention.cpython-310.pyc
ADDED
|
Binary file (2.73 kB). View file
|
|
|
VISTA/llava/model/multimodal_encoder/intern_vit_6b/__pycache__/modeling_intern_vit.cpython-310.pyc
ADDED
|
Binary file (12.8 kB). View file
|
|
|
VISTA/llava/model/multimodal_encoder/intern_vit_6b/configuration_intern_vit.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------
|
| 2 |
+
# InternVL
|
| 3 |
+
# Copyright (c) 2023 OpenGVLab
|
| 4 |
+
# Licensed under The MIT License [see LICENSE for details]
|
| 5 |
+
# --------------------------------------------------------
|
| 6 |
+
import os
|
| 7 |
+
from typing import Union
|
| 8 |
+
|
| 9 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 10 |
+
from transformers.utils import logging
|
| 11 |
+
|
| 12 |
+
logger = logging.get_logger(__name__)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class InternVisionConfig(PretrainedConfig):
|
| 16 |
+
r"""
|
| 17 |
+
This is the configuration class to store the configuration of a [`InternVisionModel`]. It is used to
|
| 18 |
+
instantiate a vision encoder according to the specified arguments, defining the model architecture.
|
| 19 |
+
|
| 20 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 21 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 22 |
+
|
| 23 |
+
Args:
|
| 24 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 25 |
+
Number of color channels in the input images (e.g., 3 for RGB).
|
| 26 |
+
patch_size (`int`, *optional*, defaults to 14):
|
| 27 |
+
The size (resolution) of each patch.
|
| 28 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 29 |
+
The size (resolution) of each image.
|
| 30 |
+
qkv_bias (`bool`, *optional*, defaults to `False`):
|
| 31 |
+
Whether to add a bias to the queries and values in the self-attention layers.
|
| 32 |
+
hidden_size (`int`, *optional*, defaults to 3200):
|
| 33 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 34 |
+
num_attention_heads (`int`, *optional*, defaults to 25):
|
| 35 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 36 |
+
intermediate_size (`int`, *optional*, defaults to 12800):
|
| 37 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 38 |
+
qk_normalization (`bool`, *optional*, defaults to `True`):
|
| 39 |
+
Whether to normalize the queries and keys in the self-attention layers.
|
| 40 |
+
num_hidden_layers (`int`, *optional*, defaults to 48):
|
| 41 |
+
Number of hidden layers in the Transformer encoder.
|
| 42 |
+
use_flash_attn (`bool`, *optional*, defaults to `True`):
|
| 43 |
+
Whether to use flash attention mechanism.
|
| 44 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 45 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 46 |
+
`"relu"`, `"selu"` and `"gelu_new"` ``"gelu"` are supported.
|
| 47 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-6):
|
| 48 |
+
The epsilon used by the layer normalization layers.
|
| 49 |
+
dropout (`float`, *optional*, defaults to 0.0):
|
| 50 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 51 |
+
drop_path_rate (`float`, *optional*, defaults to 0.0):
|
| 52 |
+
Dropout rate for stochastic depth.
|
| 53 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 54 |
+
The dropout ratio for the attention probabilities.
|
| 55 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 56 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 57 |
+
initializer_factor (`float`, *optional*, defaults to 0.1):
|
| 58 |
+
A factor for layer scale.
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
model_type = 'intern_vit_6b'
|
| 62 |
+
|
| 63 |
+
def __init__(
|
| 64 |
+
self,
|
| 65 |
+
num_channels=3,
|
| 66 |
+
patch_size=14,
|
| 67 |
+
image_size=224,
|
| 68 |
+
qkv_bias=False,
|
| 69 |
+
hidden_size=3200,
|
| 70 |
+
num_attention_heads=25,
|
| 71 |
+
intermediate_size=12800,
|
| 72 |
+
qk_normalization=True,
|
| 73 |
+
num_hidden_layers=48,
|
| 74 |
+
use_flash_attn=True,
|
| 75 |
+
hidden_act='gelu',
|
| 76 |
+
layer_norm_eps=1e-6,
|
| 77 |
+
dropout=0.0,
|
| 78 |
+
drop_path_rate=0.0,
|
| 79 |
+
attention_dropout=0.0,
|
| 80 |
+
initializer_range=0.02,
|
| 81 |
+
initializer_factor=0.1,
|
| 82 |
+
**kwargs,
|
| 83 |
+
):
|
| 84 |
+
super().__init__(**kwargs)
|
| 85 |
+
|
| 86 |
+
self.hidden_size = hidden_size
|
| 87 |
+
self.intermediate_size = intermediate_size
|
| 88 |
+
self.dropout = dropout
|
| 89 |
+
self.drop_path_rate = drop_path_rate
|
| 90 |
+
self.num_hidden_layers = num_hidden_layers
|
| 91 |
+
self.num_attention_heads = num_attention_heads
|
| 92 |
+
self.num_channels = num_channels
|
| 93 |
+
self.patch_size = patch_size
|
| 94 |
+
self.image_size = image_size
|
| 95 |
+
self.initializer_range = initializer_range
|
| 96 |
+
self.initializer_factor = initializer_factor
|
| 97 |
+
self.attention_dropout = attention_dropout
|
| 98 |
+
self.layer_norm_eps = layer_norm_eps
|
| 99 |
+
self.hidden_act = hidden_act
|
| 100 |
+
self.qkv_bias = qkv_bias
|
| 101 |
+
self.qk_normalization = qk_normalization
|
| 102 |
+
self.use_flash_attn = use_flash_attn
|
| 103 |
+
|
| 104 |
+
@classmethod
|
| 105 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> 'PretrainedConfig':
|
| 106 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
| 107 |
+
|
| 108 |
+
if 'vision_config' in config_dict:
|
| 109 |
+
config_dict = config_dict['vision_config']
|
| 110 |
+
|
| 111 |
+
if 'model_type' in config_dict and hasattr(cls, 'model_type') and config_dict['model_type'] != cls.model_type:
|
| 112 |
+
logger.warning(
|
| 113 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
| 114 |
+
f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
return cls.from_dict(config_dict, **kwargs)
|
VISTA/llava/model/multimodal_encoder/intern_vit_6b/flash_attention.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from einops import rearrange
|
| 4 |
+
|
| 5 |
+
try: # v1
|
| 6 |
+
from flash_attn.flash_attn_interface import \
|
| 7 |
+
flash_attn_unpadded_qkvpacked_func
|
| 8 |
+
except: # v2
|
| 9 |
+
from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func as flash_attn_unpadded_qkvpacked_func
|
| 10 |
+
|
| 11 |
+
from flash_attn.bert_padding import pad_input, unpad_input
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class FlashAttention(nn.Module):
|
| 15 |
+
"""Implement the scaled dot product attention with softmax.
|
| 16 |
+
Arguments
|
| 17 |
+
---------
|
| 18 |
+
softmax_scale: The temperature to use for the softmax attention.
|
| 19 |
+
(default: 1/sqrt(d_keys) where d_keys is computed at
|
| 20 |
+
runtime)
|
| 21 |
+
attention_dropout: The dropout rate to apply to the attention
|
| 22 |
+
(default: 0.0)
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
def __init__(self, softmax_scale=None, attention_dropout=0.0, device=None, dtype=None):
|
| 26 |
+
super().__init__()
|
| 27 |
+
self.softmax_scale = softmax_scale
|
| 28 |
+
self.dropout_p = attention_dropout
|
| 29 |
+
|
| 30 |
+
def forward(self, qkv, key_padding_mask=None, causal=False, cu_seqlens=None,
|
| 31 |
+
max_s=None, need_weights=False):
|
| 32 |
+
"""Implements the multihead softmax attention.
|
| 33 |
+
Arguments
|
| 34 |
+
---------
|
| 35 |
+
qkv: The tensor containing the query, key, and value. (B, S, 3, H, D) if key_padding_mask is None
|
| 36 |
+
if unpadded: (nnz, 3, h, d)
|
| 37 |
+
key_padding_mask: a bool tensor of shape (B, S)
|
| 38 |
+
"""
|
| 39 |
+
assert not need_weights
|
| 40 |
+
assert qkv.dtype in [torch.float16, torch.bfloat16]
|
| 41 |
+
assert qkv.is_cuda
|
| 42 |
+
|
| 43 |
+
if cu_seqlens is None:
|
| 44 |
+
batch_size = qkv.shape[0]
|
| 45 |
+
seqlen = qkv.shape[1]
|
| 46 |
+
if key_padding_mask is None:
|
| 47 |
+
qkv = rearrange(qkv, 'b s ... -> (b s) ...')
|
| 48 |
+
max_s = seqlen
|
| 49 |
+
cu_seqlens = torch.arange(0, (batch_size + 1) * seqlen, step=seqlen, dtype=torch.int32,
|
| 50 |
+
device=qkv.device)
|
| 51 |
+
output = flash_attn_unpadded_qkvpacked_func(
|
| 52 |
+
qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
|
| 53 |
+
softmax_scale=self.softmax_scale, causal=causal
|
| 54 |
+
)
|
| 55 |
+
output = rearrange(output, '(b s) ... -> b s ...', b=batch_size)
|
| 56 |
+
else:
|
| 57 |
+
nheads = qkv.shape[-2]
|
| 58 |
+
x = rearrange(qkv, 'b s three h d -> b s (three h d)')
|
| 59 |
+
x_unpad, indices, cu_seqlens, max_s = unpad_input(x, key_padding_mask)
|
| 60 |
+
x_unpad = rearrange(x_unpad, 'nnz (three h d) -> nnz three h d', three=3, h=nheads)
|
| 61 |
+
output_unpad = flash_attn_unpadded_qkvpacked_func(
|
| 62 |
+
x_unpad, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
|
| 63 |
+
softmax_scale=self.softmax_scale, causal=causal
|
| 64 |
+
)
|
| 65 |
+
output = rearrange(pad_input(rearrange(output_unpad, 'nnz h d -> nnz (h d)'),
|
| 66 |
+
indices, batch_size, seqlen),
|
| 67 |
+
'b s (h d) -> b s h d', h=nheads)
|
| 68 |
+
else:
|
| 69 |
+
assert max_s is not None
|
| 70 |
+
output = flash_attn_unpadded_qkvpacked_func(
|
| 71 |
+
qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
|
| 72 |
+
softmax_scale=self.softmax_scale, causal=causal
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
return output, None
|
VISTA/llava/model/multimodal_encoder/intern_vit_6b/modeling_intern_vit.py
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------
|
| 2 |
+
# InternVL
|
| 3 |
+
# Copyright (c) 2023 OpenGVLab
|
| 4 |
+
# Licensed under The MIT License [see LICENSE for details]
|
| 5 |
+
# --------------------------------------------------------
|
| 6 |
+
from typing import Optional, Tuple, Union
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
import torch.utils.checkpoint
|
| 11 |
+
from einops import rearrange
|
| 12 |
+
from timm.models.layers import DropPath
|
| 13 |
+
from torch import nn
|
| 14 |
+
from transformers.activations import ACT2FN
|
| 15 |
+
from transformers.modeling_outputs import (BaseModelOutput,
|
| 16 |
+
BaseModelOutputWithPooling)
|
| 17 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 18 |
+
from transformers.utils import logging
|
| 19 |
+
|
| 20 |
+
from .configuration_intern_vit import InternVisionConfig
|
| 21 |
+
|
| 22 |
+
try:
|
| 23 |
+
from .flash_attention import FlashAttention
|
| 24 |
+
has_flash_attn = True
|
| 25 |
+
except:
|
| 26 |
+
print('FlashAttention is not installed.')
|
| 27 |
+
has_flash_attn = False
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class InternRMSNorm(nn.Module):
|
| 34 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 35 |
+
super().__init__()
|
| 36 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 37 |
+
self.variance_epsilon = eps
|
| 38 |
+
|
| 39 |
+
def forward(self, hidden_states):
|
| 40 |
+
input_dtype = hidden_states.dtype
|
| 41 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 42 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 43 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 44 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
try:
|
| 48 |
+
from apex.normalization import FusedRMSNorm
|
| 49 |
+
|
| 50 |
+
InternRMSNorm = FusedRMSNorm # noqa
|
| 51 |
+
|
| 52 |
+
logger.info('Discovered apex.normalization.FusedRMSNorm - will use it instead of InternRMSNorm')
|
| 53 |
+
except ImportError:
|
| 54 |
+
# using the normal InternRMSNorm
|
| 55 |
+
pass
|
| 56 |
+
except Exception:
|
| 57 |
+
logger.warning('discovered apex but it failed to load, falling back to InternRMSNorm')
|
| 58 |
+
pass
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class InternVisionEmbeddings(nn.Module):
|
| 62 |
+
def __init__(self, config: InternVisionConfig):
|
| 63 |
+
super().__init__()
|
| 64 |
+
self.config = config
|
| 65 |
+
self.embed_dim = config.hidden_size
|
| 66 |
+
self.image_size = config.image_size
|
| 67 |
+
self.patch_size = config.patch_size
|
| 68 |
+
|
| 69 |
+
self.class_embedding = nn.Parameter(
|
| 70 |
+
torch.randn(1, 1, self.embed_dim),
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
self.patch_embedding = nn.Conv2d(
|
| 74 |
+
in_channels=3, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
self.num_patches = (self.image_size // self.patch_size) ** 2
|
| 78 |
+
self.num_positions = self.num_patches + 1
|
| 79 |
+
|
| 80 |
+
self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))
|
| 81 |
+
|
| 82 |
+
def _get_pos_embed(self, pos_embed, H, W):
|
| 83 |
+
target_dtype = pos_embed.dtype
|
| 84 |
+
pos_embed = pos_embed.float().reshape(
|
| 85 |
+
1, self.image_size // self.patch_size, self.image_size // self.patch_size, -1).permute(0, 3, 1, 2)
|
| 86 |
+
pos_embed = F.interpolate(pos_embed, size=(H, W), mode='bicubic', align_corners=False).\
|
| 87 |
+
reshape(1, -1, H * W).permute(0, 2, 1).to(target_dtype)
|
| 88 |
+
return pos_embed
|
| 89 |
+
|
| 90 |
+
def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
|
| 91 |
+
target_dtype = self.patch_embedding.weight.dtype
|
| 92 |
+
patch_embeds = self.patch_embedding(pixel_values) # shape = [*, channel, width, height]
|
| 93 |
+
batch_size, _, height, width = patch_embeds.shape
|
| 94 |
+
patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
|
| 95 |
+
class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype)
|
| 96 |
+
embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
|
| 97 |
+
position_embedding = torch.cat([
|
| 98 |
+
self.position_embedding[:, :1, :],
|
| 99 |
+
self._get_pos_embed(self.position_embedding[:, 1:, :], height, width)
|
| 100 |
+
], dim=1)
|
| 101 |
+
embeddings = embeddings + position_embedding.to(target_dtype)
|
| 102 |
+
return embeddings
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class InternAttention(nn.Module):
|
| 106 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 107 |
+
|
| 108 |
+
def __init__(self, config: InternVisionConfig):
|
| 109 |
+
super().__init__()
|
| 110 |
+
self.config = config
|
| 111 |
+
self.embed_dim = config.hidden_size
|
| 112 |
+
self.num_heads = config.num_attention_heads
|
| 113 |
+
self.use_flash_attn = config.use_flash_attn and has_flash_attn
|
| 114 |
+
if config.use_flash_attn and not has_flash_attn:
|
| 115 |
+
print('Warning: Flash Attention is not available, use_flash_attn is set to False.')
|
| 116 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 117 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
| 118 |
+
raise ValueError(
|
| 119 |
+
f'embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:'
|
| 120 |
+
f' {self.num_heads}).'
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
self.scale = self.head_dim ** -0.5
|
| 124 |
+
self.qkv = nn.Linear(self.embed_dim, 3 * self.embed_dim, bias=config.qkv_bias)
|
| 125 |
+
self.attn_drop = nn.Dropout(config.attention_dropout)
|
| 126 |
+
self.proj_drop = nn.Dropout(config.dropout)
|
| 127 |
+
|
| 128 |
+
self.qk_normalization = config.qk_normalization
|
| 129 |
+
|
| 130 |
+
if self.qk_normalization:
|
| 131 |
+
self.q_norm = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 132 |
+
self.k_norm = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 133 |
+
|
| 134 |
+
if self.use_flash_attn:
|
| 135 |
+
self.inner_attn = FlashAttention(attention_dropout=config.attention_dropout)
|
| 136 |
+
self.proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 137 |
+
|
| 138 |
+
def _naive_attn(self, x):
|
| 139 |
+
B, N, C = x.shape
|
| 140 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
|
| 141 |
+
q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple)
|
| 142 |
+
|
| 143 |
+
if self.qk_normalization:
|
| 144 |
+
B_, H_, N_, D_ = q.shape
|
| 145 |
+
q = self.q_norm(q.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
|
| 146 |
+
k = self.k_norm(k.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
|
| 147 |
+
|
| 148 |
+
attn = ((q * self.scale) @ k.transpose(-2, -1))
|
| 149 |
+
attn = attn.softmax(dim=-1)
|
| 150 |
+
attn = self.attn_drop(attn)
|
| 151 |
+
|
| 152 |
+
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
|
| 153 |
+
x = self.proj(x)
|
| 154 |
+
x = self.proj_drop(x)
|
| 155 |
+
return x
|
| 156 |
+
|
| 157 |
+
def _flash_attn(self, x, key_padding_mask=None, need_weights=False):
|
| 158 |
+
qkv = self.qkv(x)
|
| 159 |
+
qkv = rearrange(qkv, 'b s (three h d) -> b s three h d', three=3, h=self.num_heads)
|
| 160 |
+
|
| 161 |
+
if self.qk_normalization:
|
| 162 |
+
q, k, v = qkv.unbind(2)
|
| 163 |
+
q = self.q_norm(q.flatten(-2, -1)).view(q.shape)
|
| 164 |
+
k = self.k_norm(k.flatten(-2, -1)).view(k.shape)
|
| 165 |
+
qkv = torch.stack([q, k, v], dim=2)
|
| 166 |
+
|
| 167 |
+
context, _ = self.inner_attn(
|
| 168 |
+
qkv, key_padding_mask=key_padding_mask, need_weights=need_weights, causal=False
|
| 169 |
+
)
|
| 170 |
+
outs = self.proj(rearrange(context, 'b s h d -> b s (h d)'))
|
| 171 |
+
outs = self.proj_drop(outs)
|
| 172 |
+
return outs
|
| 173 |
+
|
| 174 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 175 |
+
x = self._naive_attn(hidden_states) if not self.use_flash_attn else self._flash_attn(hidden_states)
|
| 176 |
+
return x
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class InternMLP(nn.Module):
|
| 180 |
+
def __init__(self, config: InternVisionConfig):
|
| 181 |
+
super().__init__()
|
| 182 |
+
self.config = config
|
| 183 |
+
self.act = ACT2FN[config.hidden_act]
|
| 184 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 185 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 186 |
+
|
| 187 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 188 |
+
hidden_states = self.fc1(hidden_states)
|
| 189 |
+
hidden_states = self.act(hidden_states)
|
| 190 |
+
hidden_states = self.fc2(hidden_states)
|
| 191 |
+
return hidden_states
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
class InternVisionEncoderLayer(nn.Module):
|
| 195 |
+
def __init__(self, config: InternVisionConfig, drop_path_rate: float):
|
| 196 |
+
super().__init__()
|
| 197 |
+
self.embed_dim = config.hidden_size
|
| 198 |
+
self.intermediate_size = config.intermediate_size
|
| 199 |
+
|
| 200 |
+
self.attn = InternAttention(config)
|
| 201 |
+
self.mlp = InternMLP(config)
|
| 202 |
+
self.norm1 = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 203 |
+
self.norm2 = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 204 |
+
|
| 205 |
+
self.ls1 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
|
| 206 |
+
self.ls2 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
|
| 207 |
+
self.drop_path1 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
|
| 208 |
+
self.drop_path2 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
|
| 209 |
+
|
| 210 |
+
def forward(
|
| 211 |
+
self,
|
| 212 |
+
hidden_states: torch.Tensor,
|
| 213 |
+
) -> Tuple[torch.FloatTensor, Optional[torch.FloatTensor], Optional[Tuple[torch.FloatTensor]]]:
|
| 214 |
+
"""
|
| 215 |
+
Args:
|
| 216 |
+
hidden_states (`Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 217 |
+
"""
|
| 218 |
+
hidden_states = hidden_states + self.drop_path1(self.attn(self.norm1(hidden_states)) * self.ls1)
|
| 219 |
+
|
| 220 |
+
hidden_states = hidden_states + self.drop_path2(self.mlp(self.norm2(hidden_states)) * self.ls2)
|
| 221 |
+
|
| 222 |
+
return hidden_states
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
class InternVisionEncoder(nn.Module):
|
| 226 |
+
"""
|
| 227 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
| 228 |
+
[`InternEncoderLayer`].
|
| 229 |
+
|
| 230 |
+
Args:
|
| 231 |
+
config (`InternConfig`):
|
| 232 |
+
The corresponding vision configuration for the `InternEncoder`.
|
| 233 |
+
"""
|
| 234 |
+
|
| 235 |
+
def __init__(self, config: InternVisionConfig):
|
| 236 |
+
super().__init__()
|
| 237 |
+
self.config = config
|
| 238 |
+
# stochastic depth decay rule
|
| 239 |
+
dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, config.num_hidden_layers)]
|
| 240 |
+
self.layers = nn.ModuleList([
|
| 241 |
+
InternVisionEncoderLayer(config, dpr[idx]) for idx in range(config.num_hidden_layers)])
|
| 242 |
+
self.gradient_checkpointing = True
|
| 243 |
+
|
| 244 |
+
def forward(
|
| 245 |
+
self,
|
| 246 |
+
inputs_embeds,
|
| 247 |
+
output_hidden_states: Optional[bool] = None,
|
| 248 |
+
return_dict: Optional[bool] = None,
|
| 249 |
+
) -> Union[Tuple, BaseModelOutput]:
|
| 250 |
+
r"""
|
| 251 |
+
Args:
|
| 252 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 253 |
+
Embedded representation of the inputs. Should be float, not int tokens.
|
| 254 |
+
output_hidden_states (`bool`, *optional*):
|
| 255 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 256 |
+
for more detail.
|
| 257 |
+
return_dict (`bool`, *optional*):
|
| 258 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 259 |
+
"""
|
| 260 |
+
output_hidden_states = (
|
| 261 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 262 |
+
)
|
| 263 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 264 |
+
|
| 265 |
+
encoder_states = () if output_hidden_states else None
|
| 266 |
+
hidden_states = inputs_embeds
|
| 267 |
+
|
| 268 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 269 |
+
if output_hidden_states:
|
| 270 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 271 |
+
if self.gradient_checkpointing and self.training:
|
| 272 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
| 273 |
+
encoder_layer,
|
| 274 |
+
hidden_states)
|
| 275 |
+
else:
|
| 276 |
+
layer_outputs = encoder_layer(
|
| 277 |
+
hidden_states,
|
| 278 |
+
)
|
| 279 |
+
hidden_states = layer_outputs
|
| 280 |
+
|
| 281 |
+
if output_hidden_states:
|
| 282 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 283 |
+
|
| 284 |
+
if not return_dict:
|
| 285 |
+
return tuple(v for v in [hidden_states, encoder_states] if v is not None)
|
| 286 |
+
return BaseModelOutput(
|
| 287 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
class InternVisionModel(PreTrainedModel):
|
| 292 |
+
main_input_name = 'pixel_values'
|
| 293 |
+
config_class = InternVisionConfig
|
| 294 |
+
|
| 295 |
+
def __init__(self, config: InternVisionConfig):
|
| 296 |
+
super().__init__(config)
|
| 297 |
+
self.config = config
|
| 298 |
+
|
| 299 |
+
self.embeddings = InternVisionEmbeddings(config)
|
| 300 |
+
self.encoder = InternVisionEncoder(config)
|
| 301 |
+
|
| 302 |
+
def resize_pos_embeddings(self, old_size, new_size, patch_size):
|
| 303 |
+
pos_emb = self.embeddings.position_embedding
|
| 304 |
+
_, num_positions, embed_dim = pos_emb.shape
|
| 305 |
+
cls_emb = pos_emb[:, :1, :]
|
| 306 |
+
pos_emb = pos_emb[:, 1:, :].reshape(1, old_size // patch_size, old_size // patch_size, -1).permute(0, 3, 1, 2)
|
| 307 |
+
pos_emb = F.interpolate(pos_emb.float(), size=new_size // patch_size, mode='bicubic', align_corners=False)
|
| 308 |
+
pos_emb = pos_emb.to(cls_emb.dtype).reshape(1, embed_dim, -1).permute(0, 2, 1)
|
| 309 |
+
pos_emb = torch.cat([cls_emb, pos_emb], dim=1)
|
| 310 |
+
self.embeddings.position_embedding = nn.Parameter(pos_emb)
|
| 311 |
+
logger.info('Resized position embeddings from {} to {}'.format(old_size, new_size))
|
| 312 |
+
|
| 313 |
+
def get_input_embeddings(self):
|
| 314 |
+
return self.embeddings
|
| 315 |
+
|
| 316 |
+
def forward(
|
| 317 |
+
self,
|
| 318 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 319 |
+
output_hidden_states: Optional[bool] = None,
|
| 320 |
+
return_dict: Optional[bool] = None,
|
| 321 |
+
pixel_embeds: Optional[torch.FloatTensor] = None,
|
| 322 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 323 |
+
output_hidden_states = (
|
| 324 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 325 |
+
)
|
| 326 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 327 |
+
|
| 328 |
+
if pixel_values is None and pixel_embeds is None:
|
| 329 |
+
raise ValueError('You have to specify pixel_values or pixel_embeds')
|
| 330 |
+
|
| 331 |
+
if pixel_embeds is not None:
|
| 332 |
+
hidden_states = pixel_embeds
|
| 333 |
+
else:
|
| 334 |
+
if len(pixel_values.shape) == 4:
|
| 335 |
+
hidden_states = self.embeddings(pixel_values)
|
| 336 |
+
else:
|
| 337 |
+
raise ValueError(f'wrong pixel_values size: {pixel_values.shape}')
|
| 338 |
+
encoder_outputs = self.encoder(
|
| 339 |
+
inputs_embeds=hidden_states,
|
| 340 |
+
output_hidden_states=output_hidden_states,
|
| 341 |
+
return_dict=return_dict,
|
| 342 |
+
)
|
| 343 |
+
last_hidden_state = encoder_outputs.last_hidden_state
|
| 344 |
+
pooled_output = last_hidden_state[:, 0, :]
|
| 345 |
+
|
| 346 |
+
if not return_dict:
|
| 347 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
| 348 |
+
|
| 349 |
+
return BaseModelOutputWithPooling(
|
| 350 |
+
last_hidden_state=last_hidden_state,
|
| 351 |
+
pooler_output=pooled_output,
|
| 352 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 353 |
+
attentions=encoder_outputs.attentions,
|
| 354 |
+
)
|
VISTA/llava/model/multimodal_encoder/internvl_14b/__init__.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------
|
| 2 |
+
# InternVL
|
| 3 |
+
# Copyright (c) 2023 OpenGVLab
|
| 4 |
+
# Licensed under The MIT License [see LICENSE for details]
|
| 5 |
+
# --------------------------------------------------------
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
import torchvision.transforms as T
|
| 10 |
+
from torchvision.transforms import InterpolationMode
|
| 11 |
+
from transformers import LlamaTokenizer
|
| 12 |
+
|
| 13 |
+
from .configuration_intern_vit import InternVisionConfig
|
| 14 |
+
from .configuration_internvl import InternVLConfig
|
| 15 |
+
from .modeling_intern_vit import InternVisionModel
|
| 16 |
+
from .modeling_internvl import InternVL_C, InternVL_G, InternVLModel
|
| 17 |
+
|
| 18 |
+
__all__ = ['InternVisionConfig', 'InternVisionModel', 'InternVLConfig',
|
| 19 |
+
'InternVLModel', 'InternVL_C', 'InternVL_G']
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# Prefix the text "summarize:"
|
| 23 |
+
class InternVLTokenizer(nn.Module):
|
| 24 |
+
def __init__(self, model_path):
|
| 25 |
+
super(InternVLTokenizer, self).__init__()
|
| 26 |
+
self.tokenizer = LlamaTokenizer.from_pretrained(model_path)
|
| 27 |
+
self.tokenizer.pad_token = ' ' # allow padding
|
| 28 |
+
self.tokenizer.add_eos_token = True
|
| 29 |
+
|
| 30 |
+
def forward(self, text, prefix='summarize:'):
|
| 31 |
+
if type(text) == str:
|
| 32 |
+
text = prefix + text
|
| 33 |
+
elif type(text) == list:
|
| 34 |
+
text = [prefix + item for item in text]
|
| 35 |
+
text = self.tokenizer(text, return_tensors='pt', max_length=80, truncation=True, padding='max_length').input_ids
|
| 36 |
+
return text
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def build_transform(task, image_size=224, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]):
|
| 40 |
+
if task == 'retrieval':
|
| 41 |
+
transform = T.Compose([
|
| 42 |
+
T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
|
| 43 |
+
T.Resize((image_size, image_size), interpolation=InterpolationMode.BICUBIC),
|
| 44 |
+
T.ToTensor(),
|
| 45 |
+
T.Normalize(mean=mean, std=std)])
|
| 46 |
+
else:
|
| 47 |
+
transform = T.Compose([
|
| 48 |
+
T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
|
| 49 |
+
T.Resize(image_size, interpolation=InterpolationMode.BICUBIC),
|
| 50 |
+
T.CenterCrop(image_size),
|
| 51 |
+
T.ToTensor(),
|
| 52 |
+
T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])
|
| 53 |
+
return transform
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def load_internvl_c_huggingface(ckpt_path, device, task):
|
| 57 |
+
model = InternVL_C.from_pretrained(ckpt_path, torch_dtype=torch.float16).to(device)
|
| 58 |
+
if model.config.use_backbone_lora:
|
| 59 |
+
model.vision_model.merge_and_unload()
|
| 60 |
+
model.vision_model = model.vision_model.model
|
| 61 |
+
if model.config.use_qllama_lora:
|
| 62 |
+
model.qllama.merge_and_unload()
|
| 63 |
+
model.qllama = model.qllama.model
|
| 64 |
+
if model.config.force_image_size is not None:
|
| 65 |
+
image_size = model.config.force_image_size
|
| 66 |
+
else:
|
| 67 |
+
image_size = model.config.vision_config.image_size
|
| 68 |
+
transform = build_transform(task, image_size)
|
| 69 |
+
tokenizer = InternVLTokenizer(ckpt_path)
|
| 70 |
+
return model, transform, tokenizer
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def load_internvl_g_huggingface(ckpt_path, device, task):
|
| 74 |
+
model = InternVL_G.from_pretrained(ckpt_path, torch_dtype=torch.float16).to(device)
|
| 75 |
+
if model.config.use_backbone_lora:
|
| 76 |
+
model.vision_model.merge_and_unload()
|
| 77 |
+
model.vision_model = model.vision_model.model
|
| 78 |
+
if model.config.use_qllama_lora:
|
| 79 |
+
model.qllama.merge_and_unload()
|
| 80 |
+
model.qllama = model.qllama.model
|
| 81 |
+
if model.config.force_image_size is not None:
|
| 82 |
+
image_size = model.config.force_image_size
|
| 83 |
+
else:
|
| 84 |
+
image_size = model.config.vision_config.image_size
|
| 85 |
+
transform = build_transform(task, image_size)
|
| 86 |
+
tokenizer = InternVLTokenizer(ckpt_path)
|
| 87 |
+
return model, transform, tokenizer
|
VISTA/llava/model/multimodal_encoder/internvl_14b/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (3.15 kB). View file
|
|
|
VISTA/llava/model/multimodal_encoder/internvl_14b/__pycache__/configuration_intern_vit.cpython-310.pyc
ADDED
|
Binary file (5.01 kB). View file
|
|
|
VISTA/llava/model/multimodal_encoder/internvl_14b/__pycache__/configuration_internvl.cpython-310.pyc
ADDED
|
Binary file (4.36 kB). View file
|
|
|
VISTA/llava/model/multimodal_encoder/internvl_14b/__pycache__/flash_attention.cpython-310.pyc
ADDED
|
Binary file (2.73 kB). View file
|
|
|
VISTA/llava/model/multimodal_encoder/internvl_14b/__pycache__/modeling_intern_vit.cpython-310.pyc
ADDED
|
Binary file (12.8 kB). View file
|
|
|
VISTA/llava/model/multimodal_encoder/internvl_14b/__pycache__/modeling_internvl.cpython-310.pyc
ADDED
|
Binary file (13.7 kB). View file
|
|
|
VISTA/llava/model/multimodal_encoder/internvl_14b/__pycache__/modeling_qllama.cpython-310.pyc
ADDED
|
Binary file (31.5 kB). View file
|
|
|
VISTA/llava/model/multimodal_encoder/internvl_14b/configuration_intern_vit.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------
|
| 2 |
+
# InternVL
|
| 3 |
+
# Copyright (c) 2023 OpenGVLab
|
| 4 |
+
# Licensed under The MIT License [see LICENSE for details]
|
| 5 |
+
# --------------------------------------------------------
|
| 6 |
+
import os
|
| 7 |
+
from typing import Union
|
| 8 |
+
|
| 9 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 10 |
+
from transformers.utils import logging
|
| 11 |
+
|
| 12 |
+
logger = logging.get_logger(__name__)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class InternVisionConfig(PretrainedConfig):
|
| 16 |
+
r"""
|
| 17 |
+
This is the configuration class to store the configuration of a [`InternVisionModel`]. It is used to
|
| 18 |
+
instantiate a vision encoder according to the specified arguments, defining the model architecture.
|
| 19 |
+
|
| 20 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 21 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 22 |
+
|
| 23 |
+
Args:
|
| 24 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 25 |
+
Number of color channels in the input images (e.g., 3 for RGB).
|
| 26 |
+
patch_size (`int`, *optional*, defaults to 14):
|
| 27 |
+
The size (resolution) of each patch.
|
| 28 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 29 |
+
The size (resolution) of each image.
|
| 30 |
+
qkv_bias (`bool`, *optional*, defaults to `False`):
|
| 31 |
+
Whether to add a bias to the queries and values in the self-attention layers.
|
| 32 |
+
hidden_size (`int`, *optional*, defaults to 3200):
|
| 33 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 34 |
+
num_attention_heads (`int`, *optional*, defaults to 25):
|
| 35 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 36 |
+
intermediate_size (`int`, *optional*, defaults to 12800):
|
| 37 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 38 |
+
qk_normalization (`bool`, *optional*, defaults to `True`):
|
| 39 |
+
Whether to normalize the queries and keys in the self-attention layers.
|
| 40 |
+
num_hidden_layers (`int`, *optional*, defaults to 48):
|
| 41 |
+
Number of hidden layers in the Transformer encoder.
|
| 42 |
+
use_flash_attn (`bool`, *optional*, defaults to `True`):
|
| 43 |
+
Whether to use flash attention mechanism.
|
| 44 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 45 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 46 |
+
`"relu"`, `"selu"` and `"gelu_new"` ``"gelu"` are supported.
|
| 47 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-6):
|
| 48 |
+
The epsilon used by the layer normalization layers.
|
| 49 |
+
dropout (`float`, *optional*, defaults to 0.0):
|
| 50 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 51 |
+
drop_path_rate (`float`, *optional*, defaults to 0.0):
|
| 52 |
+
Dropout rate for stochastic depth.
|
| 53 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 54 |
+
The dropout ratio for the attention probabilities.
|
| 55 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 56 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 57 |
+
initializer_factor (`float`, *optional*, defaults to 0.1):
|
| 58 |
+
A factor for layer scale.
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
model_type = 'intern_vit_6b'
|
| 62 |
+
|
| 63 |
+
def __init__(
|
| 64 |
+
self,
|
| 65 |
+
num_channels=3,
|
| 66 |
+
patch_size=14,
|
| 67 |
+
image_size=224,
|
| 68 |
+
qkv_bias=False,
|
| 69 |
+
hidden_size=3200,
|
| 70 |
+
num_attention_heads=25,
|
| 71 |
+
intermediate_size=12800,
|
| 72 |
+
qk_normalization=True,
|
| 73 |
+
num_hidden_layers=48,
|
| 74 |
+
use_flash_attn=True,
|
| 75 |
+
hidden_act='gelu',
|
| 76 |
+
layer_norm_eps=1e-6,
|
| 77 |
+
dropout=0.0,
|
| 78 |
+
drop_path_rate=0.0,
|
| 79 |
+
attention_dropout=0.0,
|
| 80 |
+
initializer_range=0.02,
|
| 81 |
+
initializer_factor=0.1,
|
| 82 |
+
**kwargs,
|
| 83 |
+
):
|
| 84 |
+
super().__init__(**kwargs)
|
| 85 |
+
|
| 86 |
+
self.hidden_size = hidden_size
|
| 87 |
+
self.intermediate_size = intermediate_size
|
| 88 |
+
self.dropout = dropout
|
| 89 |
+
self.drop_path_rate = drop_path_rate
|
| 90 |
+
self.num_hidden_layers = num_hidden_layers
|
| 91 |
+
self.num_attention_heads = num_attention_heads
|
| 92 |
+
self.num_channels = num_channels
|
| 93 |
+
self.patch_size = patch_size
|
| 94 |
+
self.image_size = image_size
|
| 95 |
+
self.initializer_range = initializer_range
|
| 96 |
+
self.initializer_factor = initializer_factor
|
| 97 |
+
self.attention_dropout = attention_dropout
|
| 98 |
+
self.layer_norm_eps = layer_norm_eps
|
| 99 |
+
self.hidden_act = hidden_act
|
| 100 |
+
self.qkv_bias = qkv_bias
|
| 101 |
+
self.qk_normalization = qk_normalization
|
| 102 |
+
self.use_flash_attn = use_flash_attn
|
| 103 |
+
|
| 104 |
+
@classmethod
|
| 105 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> 'PretrainedConfig':
|
| 106 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
| 107 |
+
|
| 108 |
+
if 'vision_config' in config_dict:
|
| 109 |
+
config_dict = config_dict['vision_config']
|
| 110 |
+
|
| 111 |
+
if 'model_type' in config_dict and hasattr(cls, 'model_type') and config_dict['model_type'] != cls.model_type:
|
| 112 |
+
logger.warning(
|
| 113 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
| 114 |
+
f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
return cls.from_dict(config_dict, **kwargs)
|
VISTA/llava/model/multimodal_encoder/internvl_14b/configuration_internvl.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------
|
| 2 |
+
# InternVL
|
| 3 |
+
# Copyright (c) 2023 OpenGVLab
|
| 4 |
+
# Licensed under The MIT License [see LICENSE for details]
|
| 5 |
+
# --------------------------------------------------------
|
| 6 |
+
import copy
|
| 7 |
+
|
| 8 |
+
from transformers import LlamaConfig
|
| 9 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 10 |
+
from transformers.utils import logging
|
| 11 |
+
|
| 12 |
+
from .configuration_intern_vit import InternVisionConfig
|
| 13 |
+
|
| 14 |
+
logger = logging.get_logger(__name__)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class InternVLConfig(PretrainedConfig):
|
| 18 |
+
r"""
|
| 19 |
+
[`InternVLConfig`] is the configuration class to store the configuration of a
|
| 20 |
+
[`InternVLModel`]. It is used to instantiate a InternVLModel according to the specified
|
| 21 |
+
arguments, defining the InternViT-6B and QLLaMA configs. Instantiating a configuration with
|
| 22 |
+
the defaults will yield a similar configuration to that of the InternVL architecture.
|
| 23 |
+
|
| 24 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 25 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
vision_config (`dict`, *optional*):
|
| 29 |
+
Dictionary of configuration options used to initialize [`InternVisionConfig`].
|
| 30 |
+
qllama_config (`dict`, *optional*):
|
| 31 |
+
Dictionary of configuration options used to initialize [`LLaMAConfig`].
|
| 32 |
+
clip_embed_dim (`int`, *optional*, defaults to 768):
|
| 33 |
+
Size of the embeddings from the CLIP model.
|
| 34 |
+
attn_pool_num_heads (`int`, *optional*, defaults to 16):
|
| 35 |
+
Number of attention heads used in the attention pooling layers.
|
| 36 |
+
num_query_token (`int`, *optional*, defaults to 96):
|
| 37 |
+
Number of query tokens used in the transformer.
|
| 38 |
+
label_smoothing (`float`, *optional*, defaults to 0.0):
|
| 39 |
+
The amount of label smoothing to apply.
|
| 40 |
+
cross_attention_frequency (`int`, *optional*, defaults to 2):
|
| 41 |
+
The frequency of cross-attention layers in the model.
|
| 42 |
+
use_backbone_lora (`int`, *optional*, defaults to 0):
|
| 43 |
+
If non-zero, indicates the use of LoRA in the backbone of the model.
|
| 44 |
+
use_qllama_lora (`int`, *optional*, defaults to 0):
|
| 45 |
+
If non-zero, indicates the use of LoRA in the QLLaMA of the model.
|
| 46 |
+
force_image_size (`int` or `None`, *optional*):
|
| 47 |
+
If not None, forces the model to use this specific image size.
|
| 48 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 49 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 50 |
+
kwargs (*optional*):
|
| 51 |
+
Dictionary of additional keyword arguments.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
model_type = 'internvl'
|
| 55 |
+
is_composition = True
|
| 56 |
+
|
| 57 |
+
def __init__(
|
| 58 |
+
self,
|
| 59 |
+
vision_config=None,
|
| 60 |
+
qllama_config=None,
|
| 61 |
+
clip_embed_dim=768,
|
| 62 |
+
attn_pool_num_heads=16,
|
| 63 |
+
num_query_token=96,
|
| 64 |
+
label_smoothing=0.0,
|
| 65 |
+
cross_attention_frequency=2,
|
| 66 |
+
use_backbone_lora=0,
|
| 67 |
+
use_qllama_lora=0,
|
| 68 |
+
force_image_size=None,
|
| 69 |
+
initializer_range=0.02,
|
| 70 |
+
**kwargs):
|
| 71 |
+
super().__init__(**kwargs)
|
| 72 |
+
|
| 73 |
+
if vision_config is None:
|
| 74 |
+
vision_config = {}
|
| 75 |
+
logger.info('vision_config is None. initializing the InternVisionConfig with default values.')
|
| 76 |
+
|
| 77 |
+
if qllama_config is None:
|
| 78 |
+
qllama_config = {}
|
| 79 |
+
logger.info(
|
| 80 |
+
'qllama_config is None. Initializing the InternTextConfig config with default values (`LlamaConfig`).')
|
| 81 |
+
|
| 82 |
+
self.vision_config = InternVisionConfig(**vision_config)
|
| 83 |
+
self.qllama_config = LlamaConfig(**qllama_config)
|
| 84 |
+
self.qllama_config.num_query_token = num_query_token
|
| 85 |
+
self.qllama_config.cross_attention_frequency = cross_attention_frequency
|
| 86 |
+
self.hidden_size = self.qllama_config.hidden_size
|
| 87 |
+
|
| 88 |
+
self.clip_embed_dim = clip_embed_dim
|
| 89 |
+
self.attn_pool_num_heads = attn_pool_num_heads
|
| 90 |
+
self.num_query_token = num_query_token
|
| 91 |
+
self.label_smoothing = label_smoothing
|
| 92 |
+
self.use_backbone_lora = use_backbone_lora
|
| 93 |
+
self.use_qllama_lora = use_qllama_lora
|
| 94 |
+
self.force_image_size = force_image_size
|
| 95 |
+
self.initializer_range = initializer_range
|
| 96 |
+
|
| 97 |
+
def to_dict(self):
|
| 98 |
+
"""
|
| 99 |
+
Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
|
| 100 |
+
|
| 101 |
+
Returns:
|
| 102 |
+
`Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
|
| 103 |
+
"""
|
| 104 |
+
output = copy.deepcopy(self.__dict__)
|
| 105 |
+
output['vision_config'] = self.vision_config.to_dict()
|
| 106 |
+
output['qllama_config'] = self.qllama_config.to_dict()
|
| 107 |
+
output['model_type'] = self.__class__.model_type
|
| 108 |
+
return output
|
VISTA/llava/model/multimodal_encoder/internvl_14b/flash_attention.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# https://github.com/Dao-AILab/flash-attention/blob/v0.2.8/flash_attn/flash_attention.py
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from einops import rearrange
|
| 5 |
+
|
| 6 |
+
try: # v1
|
| 7 |
+
from flash_attn.flash_attn_interface import \
|
| 8 |
+
flash_attn_unpadded_qkvpacked_func
|
| 9 |
+
except: # v2
|
| 10 |
+
from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func as flash_attn_unpadded_qkvpacked_func
|
| 11 |
+
|
| 12 |
+
from flash_attn.bert_padding import pad_input, unpad_input
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class FlashAttention(nn.Module):
|
| 16 |
+
"""Implement the scaled dot product attention with softmax.
|
| 17 |
+
Arguments
|
| 18 |
+
---------
|
| 19 |
+
softmax_scale: The temperature to use for the softmax attention.
|
| 20 |
+
(default: 1/sqrt(d_keys) where d_keys is computed at
|
| 21 |
+
runtime)
|
| 22 |
+
attention_dropout: The dropout rate to apply to the attention
|
| 23 |
+
(default: 0.0)
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def __init__(self, softmax_scale=None, attention_dropout=0.0, device=None, dtype=None):
|
| 27 |
+
super().__init__()
|
| 28 |
+
self.softmax_scale = softmax_scale
|
| 29 |
+
self.dropout_p = attention_dropout
|
| 30 |
+
|
| 31 |
+
def forward(self, qkv, key_padding_mask=None, causal=False, cu_seqlens=None,
|
| 32 |
+
max_s=None, need_weights=False):
|
| 33 |
+
"""Implements the multihead softmax attention.
|
| 34 |
+
Arguments
|
| 35 |
+
---------
|
| 36 |
+
qkv: The tensor containing the query, key, and value. (B, S, 3, H, D) if key_padding_mask is None
|
| 37 |
+
if unpadded: (nnz, 3, h, d)
|
| 38 |
+
key_padding_mask: a bool tensor of shape (B, S)
|
| 39 |
+
"""
|
| 40 |
+
assert not need_weights
|
| 41 |
+
assert qkv.dtype in [torch.float16, torch.bfloat16]
|
| 42 |
+
assert qkv.is_cuda
|
| 43 |
+
|
| 44 |
+
if cu_seqlens is None:
|
| 45 |
+
batch_size = qkv.shape[0]
|
| 46 |
+
seqlen = qkv.shape[1]
|
| 47 |
+
if key_padding_mask is None:
|
| 48 |
+
qkv = rearrange(qkv, 'b s ... -> (b s) ...')
|
| 49 |
+
max_s = seqlen
|
| 50 |
+
cu_seqlens = torch.arange(0, (batch_size + 1) * seqlen, step=seqlen, dtype=torch.int32,
|
| 51 |
+
device=qkv.device)
|
| 52 |
+
output = flash_attn_unpadded_qkvpacked_func(
|
| 53 |
+
qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
|
| 54 |
+
softmax_scale=self.softmax_scale, causal=causal
|
| 55 |
+
)
|
| 56 |
+
output = rearrange(output, '(b s) ... -> b s ...', b=batch_size)
|
| 57 |
+
else:
|
| 58 |
+
nheads = qkv.shape[-2]
|
| 59 |
+
x = rearrange(qkv, 'b s three h d -> b s (three h d)')
|
| 60 |
+
x_unpad, indices, cu_seqlens, max_s = unpad_input(x, key_padding_mask)
|
| 61 |
+
x_unpad = rearrange(x_unpad, 'nnz (three h d) -> nnz three h d', three=3, h=nheads)
|
| 62 |
+
output_unpad = flash_attn_unpadded_qkvpacked_func(
|
| 63 |
+
x_unpad, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
|
| 64 |
+
softmax_scale=self.softmax_scale, causal=causal
|
| 65 |
+
)
|
| 66 |
+
output = rearrange(pad_input(rearrange(output_unpad, 'nnz h d -> nnz (h d)'),
|
| 67 |
+
indices, batch_size, seqlen),
|
| 68 |
+
'b s (h d) -> b s h d', h=nheads)
|
| 69 |
+
else:
|
| 70 |
+
assert max_s is not None
|
| 71 |
+
output = flash_attn_unpadded_qkvpacked_func(
|
| 72 |
+
qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
|
| 73 |
+
softmax_scale=self.softmax_scale, causal=causal
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
return output, None
|
VISTA/llava/model/multimodal_encoder/internvl_14b/modeling_intern_vit.py
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------
|
| 2 |
+
# InternVL
|
| 3 |
+
# Copyright (c) 2023 OpenGVLab
|
| 4 |
+
# Licensed under The MIT License [see LICENSE for details]
|
| 5 |
+
# --------------------------------------------------------
|
| 6 |
+
from typing import Optional, Tuple, Union
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
import torch.utils.checkpoint
|
| 11 |
+
from einops import rearrange
|
| 12 |
+
from timm.models.layers import DropPath
|
| 13 |
+
from torch import nn
|
| 14 |
+
from transformers.activations import ACT2FN
|
| 15 |
+
from transformers.modeling_outputs import (BaseModelOutput,
|
| 16 |
+
BaseModelOutputWithPooling)
|
| 17 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 18 |
+
from transformers.utils import logging
|
| 19 |
+
|
| 20 |
+
from .configuration_intern_vit import InternVisionConfig
|
| 21 |
+
|
| 22 |
+
try:
|
| 23 |
+
from .flash_attention import FlashAttention
|
| 24 |
+
has_flash_attn = True
|
| 25 |
+
except:
|
| 26 |
+
print('FlashAttention is not installed.')
|
| 27 |
+
has_flash_attn = False
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class InternRMSNorm(nn.Module):
|
| 34 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 35 |
+
super().__init__()
|
| 36 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 37 |
+
self.variance_epsilon = eps
|
| 38 |
+
|
| 39 |
+
def forward(self, hidden_states):
|
| 40 |
+
input_dtype = hidden_states.dtype
|
| 41 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 42 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 43 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 44 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
try:
|
| 48 |
+
from apex.normalization import FusedRMSNorm
|
| 49 |
+
|
| 50 |
+
InternRMSNorm = FusedRMSNorm # noqa
|
| 51 |
+
|
| 52 |
+
logger.info('Discovered apex.normalization.FusedRMSNorm - will use it instead of InternRMSNorm')
|
| 53 |
+
except ImportError:
|
| 54 |
+
# using the normal InternRMSNorm
|
| 55 |
+
pass
|
| 56 |
+
except Exception:
|
| 57 |
+
logger.warning('discovered apex but it failed to load, falling back to InternRMSNorm')
|
| 58 |
+
pass
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class InternVisionEmbeddings(nn.Module):
|
| 62 |
+
def __init__(self, config: InternVisionConfig):
|
| 63 |
+
super().__init__()
|
| 64 |
+
self.config = config
|
| 65 |
+
self.embed_dim = config.hidden_size
|
| 66 |
+
self.image_size = config.image_size
|
| 67 |
+
self.patch_size = config.patch_size
|
| 68 |
+
|
| 69 |
+
self.class_embedding = nn.Parameter(
|
| 70 |
+
torch.randn(1, 1, self.embed_dim),
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
self.patch_embedding = nn.Conv2d(
|
| 74 |
+
in_channels=3, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
self.num_patches = (self.image_size // self.patch_size) ** 2
|
| 78 |
+
self.num_positions = self.num_patches + 1
|
| 79 |
+
|
| 80 |
+
self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))
|
| 81 |
+
|
| 82 |
+
def _get_pos_embed(self, pos_embed, H, W):
|
| 83 |
+
target_dtype = pos_embed.dtype
|
| 84 |
+
pos_embed = pos_embed.float().reshape(
|
| 85 |
+
1, self.image_size // self.patch_size, self.image_size // self.patch_size, -1).permute(0, 3, 1, 2)
|
| 86 |
+
pos_embed = F.interpolate(pos_embed, size=(H, W), mode='bicubic', align_corners=False).\
|
| 87 |
+
reshape(1, -1, H * W).permute(0, 2, 1).to(target_dtype)
|
| 88 |
+
return pos_embed
|
| 89 |
+
|
| 90 |
+
def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
|
| 91 |
+
target_dtype = self.patch_embedding.weight.dtype
|
| 92 |
+
patch_embeds = self.patch_embedding(pixel_values) # shape = [*, channel, width, height]
|
| 93 |
+
batch_size, _, height, width = patch_embeds.shape
|
| 94 |
+
patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
|
| 95 |
+
class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype)
|
| 96 |
+
embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
|
| 97 |
+
position_embedding = torch.cat([
|
| 98 |
+
self.position_embedding[:, :1, :],
|
| 99 |
+
self._get_pos_embed(self.position_embedding[:, 1:, :], height, width)
|
| 100 |
+
], dim=1)
|
| 101 |
+
embeddings = embeddings + position_embedding.to(target_dtype)
|
| 102 |
+
return embeddings
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class InternAttention(nn.Module):
|
| 106 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 107 |
+
|
| 108 |
+
def __init__(self, config: InternVisionConfig):
|
| 109 |
+
super().__init__()
|
| 110 |
+
self.config = config
|
| 111 |
+
self.embed_dim = config.hidden_size
|
| 112 |
+
self.num_heads = config.num_attention_heads
|
| 113 |
+
self.use_flash_attn = config.use_flash_attn and has_flash_attn
|
| 114 |
+
if config.use_flash_attn and not has_flash_attn:
|
| 115 |
+
print('Warning: Flash Attention is not available, use_flash_attn is set to False.')
|
| 116 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 117 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
| 118 |
+
raise ValueError(
|
| 119 |
+
f'embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:'
|
| 120 |
+
f' {self.num_heads}).'
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
self.scale = self.head_dim ** -0.5
|
| 124 |
+
self.qkv = nn.Linear(self.embed_dim, 3 * self.embed_dim, bias=config.qkv_bias)
|
| 125 |
+
self.attn_drop = nn.Dropout(config.attention_dropout)
|
| 126 |
+
self.proj_drop = nn.Dropout(config.dropout)
|
| 127 |
+
|
| 128 |
+
self.qk_normalization = config.qk_normalization
|
| 129 |
+
|
| 130 |
+
if self.qk_normalization:
|
| 131 |
+
self.q_norm = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 132 |
+
self.k_norm = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 133 |
+
|
| 134 |
+
if self.use_flash_attn:
|
| 135 |
+
self.inner_attn = FlashAttention(attention_dropout=config.attention_dropout)
|
| 136 |
+
self.proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 137 |
+
|
| 138 |
+
def _naive_attn(self, x):
|
| 139 |
+
B, N, C = x.shape
|
| 140 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
|
| 141 |
+
q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple)
|
| 142 |
+
|
| 143 |
+
if self.qk_normalization:
|
| 144 |
+
B_, H_, N_, D_ = q.shape
|
| 145 |
+
q = self.q_norm(q.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
|
| 146 |
+
k = self.k_norm(k.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
|
| 147 |
+
|
| 148 |
+
attn = ((q * self.scale) @ k.transpose(-2, -1))
|
| 149 |
+
attn = attn.softmax(dim=-1)
|
| 150 |
+
attn = self.attn_drop(attn)
|
| 151 |
+
|
| 152 |
+
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
|
| 153 |
+
x = self.proj(x)
|
| 154 |
+
x = self.proj_drop(x)
|
| 155 |
+
return x
|
| 156 |
+
|
| 157 |
+
def _flash_attn(self, x, key_padding_mask=None, need_weights=False):
|
| 158 |
+
qkv = self.qkv(x)
|
| 159 |
+
qkv = rearrange(qkv, 'b s (three h d) -> b s three h d', three=3, h=self.num_heads)
|
| 160 |
+
|
| 161 |
+
if self.qk_normalization:
|
| 162 |
+
q, k, v = qkv.unbind(2)
|
| 163 |
+
q = self.q_norm(q.flatten(-2, -1)).view(q.shape)
|
| 164 |
+
k = self.k_norm(k.flatten(-2, -1)).view(k.shape)
|
| 165 |
+
qkv = torch.stack([q, k, v], dim=2)
|
| 166 |
+
|
| 167 |
+
context, _ = self.inner_attn(
|
| 168 |
+
qkv, key_padding_mask=key_padding_mask, need_weights=need_weights, causal=False
|
| 169 |
+
)
|
| 170 |
+
outs = self.proj(rearrange(context, 'b s h d -> b s (h d)'))
|
| 171 |
+
outs = self.proj_drop(outs)
|
| 172 |
+
return outs
|
| 173 |
+
|
| 174 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 175 |
+
x = self._naive_attn(hidden_states) if not self.use_flash_attn else self._flash_attn(hidden_states)
|
| 176 |
+
return x
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class InternMLP(nn.Module):
|
| 180 |
+
def __init__(self, config: InternVisionConfig):
|
| 181 |
+
super().__init__()
|
| 182 |
+
self.config = config
|
| 183 |
+
self.act = ACT2FN[config.hidden_act]
|
| 184 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 185 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 186 |
+
|
| 187 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 188 |
+
hidden_states = self.fc1(hidden_states)
|
| 189 |
+
hidden_states = self.act(hidden_states)
|
| 190 |
+
hidden_states = self.fc2(hidden_states)
|
| 191 |
+
return hidden_states
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
class InternVisionEncoderLayer(nn.Module):
|
| 195 |
+
def __init__(self, config: InternVisionConfig, drop_path_rate: float):
|
| 196 |
+
super().__init__()
|
| 197 |
+
self.embed_dim = config.hidden_size
|
| 198 |
+
self.intermediate_size = config.intermediate_size
|
| 199 |
+
|
| 200 |
+
self.attn = InternAttention(config)
|
| 201 |
+
self.mlp = InternMLP(config)
|
| 202 |
+
self.norm1 = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 203 |
+
self.norm2 = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 204 |
+
|
| 205 |
+
self.ls1 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
|
| 206 |
+
self.ls2 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
|
| 207 |
+
self.drop_path1 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
|
| 208 |
+
self.drop_path2 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
|
| 209 |
+
|
| 210 |
+
def forward(
|
| 211 |
+
self,
|
| 212 |
+
hidden_states: torch.Tensor,
|
| 213 |
+
) -> Tuple[torch.FloatTensor, Optional[torch.FloatTensor], Optional[Tuple[torch.FloatTensor]]]:
|
| 214 |
+
"""
|
| 215 |
+
Args:
|
| 216 |
+
hidden_states (`Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 217 |
+
"""
|
| 218 |
+
hidden_states = hidden_states + self.drop_path1(self.attn(self.norm1(hidden_states)) * self.ls1)
|
| 219 |
+
|
| 220 |
+
hidden_states = hidden_states + self.drop_path2(self.mlp(self.norm2(hidden_states)) * self.ls2)
|
| 221 |
+
|
| 222 |
+
return hidden_states
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
class InternVisionEncoder(nn.Module):
|
| 226 |
+
"""
|
| 227 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
| 228 |
+
[`InternEncoderLayer`].
|
| 229 |
+
|
| 230 |
+
Args:
|
| 231 |
+
config (`InternConfig`):
|
| 232 |
+
The corresponding vision configuration for the `InternEncoder`.
|
| 233 |
+
"""
|
| 234 |
+
|
| 235 |
+
def __init__(self, config: InternVisionConfig):
|
| 236 |
+
super().__init__()
|
| 237 |
+
self.config = config
|
| 238 |
+
# stochastic depth decay rule
|
| 239 |
+
dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, config.num_hidden_layers)]
|
| 240 |
+
self.layers = nn.ModuleList([
|
| 241 |
+
InternVisionEncoderLayer(config, dpr[idx]) for idx in range(config.num_hidden_layers)])
|
| 242 |
+
self.gradient_checkpointing = True
|
| 243 |
+
|
| 244 |
+
def forward(
|
| 245 |
+
self,
|
| 246 |
+
inputs_embeds,
|
| 247 |
+
output_hidden_states: Optional[bool] = None,
|
| 248 |
+
return_dict: Optional[bool] = None,
|
| 249 |
+
) -> Union[Tuple, BaseModelOutput]:
|
| 250 |
+
r"""
|
| 251 |
+
Args:
|
| 252 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 253 |
+
Embedded representation of the inputs. Should be float, not int tokens.
|
| 254 |
+
output_hidden_states (`bool`, *optional*):
|
| 255 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 256 |
+
for more detail.
|
| 257 |
+
return_dict (`bool`, *optional*):
|
| 258 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 259 |
+
"""
|
| 260 |
+
output_hidden_states = (
|
| 261 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 262 |
+
)
|
| 263 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 264 |
+
|
| 265 |
+
encoder_states = () if output_hidden_states else None
|
| 266 |
+
hidden_states = inputs_embeds
|
| 267 |
+
|
| 268 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 269 |
+
if output_hidden_states:
|
| 270 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 271 |
+
if self.gradient_checkpointing and self.training:
|
| 272 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
| 273 |
+
encoder_layer,
|
| 274 |
+
hidden_states)
|
| 275 |
+
else:
|
| 276 |
+
layer_outputs = encoder_layer(
|
| 277 |
+
hidden_states,
|
| 278 |
+
)
|
| 279 |
+
hidden_states = layer_outputs
|
| 280 |
+
|
| 281 |
+
if output_hidden_states:
|
| 282 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 283 |
+
|
| 284 |
+
if not return_dict:
|
| 285 |
+
return tuple(v for v in [hidden_states, encoder_states] if v is not None)
|
| 286 |
+
return BaseModelOutput(
|
| 287 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
class InternVisionModel(PreTrainedModel):
|
| 292 |
+
main_input_name = 'pixel_values'
|
| 293 |
+
config_class = InternVisionConfig
|
| 294 |
+
|
| 295 |
+
def __init__(self, config: InternVisionConfig):
|
| 296 |
+
super().__init__(config)
|
| 297 |
+
self.config = config
|
| 298 |
+
|
| 299 |
+
self.embeddings = InternVisionEmbeddings(config)
|
| 300 |
+
self.encoder = InternVisionEncoder(config)
|
| 301 |
+
|
| 302 |
+
def resize_pos_embeddings(self, old_size, new_size, patch_size):
|
| 303 |
+
pos_emb = self.embeddings.position_embedding
|
| 304 |
+
_, num_positions, embed_dim = pos_emb.shape
|
| 305 |
+
cls_emb = pos_emb[:, :1, :]
|
| 306 |
+
pos_emb = pos_emb[:, 1:, :].reshape(1, old_size // patch_size, old_size // patch_size, -1).permute(0, 3, 1, 2)
|
| 307 |
+
pos_emb = F.interpolate(pos_emb.float(), size=new_size // patch_size, mode='bicubic', align_corners=False)
|
| 308 |
+
pos_emb = pos_emb.to(cls_emb.dtype).reshape(1, embed_dim, -1).permute(0, 2, 1)
|
| 309 |
+
pos_emb = torch.cat([cls_emb, pos_emb], dim=1)
|
| 310 |
+
self.embeddings.position_embedding = nn.Parameter(pos_emb)
|
| 311 |
+
logger.info('Resized position embeddings from {} to {}'.format(old_size, new_size))
|
| 312 |
+
|
| 313 |
+
def get_input_embeddings(self):
|
| 314 |
+
return self.embeddings
|
| 315 |
+
|
| 316 |
+
def forward(
|
| 317 |
+
self,
|
| 318 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 319 |
+
output_hidden_states: Optional[bool] = None,
|
| 320 |
+
return_dict: Optional[bool] = None,
|
| 321 |
+
pixel_embeds: Optional[torch.FloatTensor] = None,
|
| 322 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 323 |
+
output_hidden_states = (
|
| 324 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 325 |
+
)
|
| 326 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 327 |
+
|
| 328 |
+
if pixel_values is None and pixel_embeds is None:
|
| 329 |
+
raise ValueError('You have to specify pixel_values or pixel_embeds')
|
| 330 |
+
|
| 331 |
+
if pixel_embeds is not None:
|
| 332 |
+
hidden_states = pixel_embeds
|
| 333 |
+
else:
|
| 334 |
+
if len(pixel_values.shape) == 4:
|
| 335 |
+
hidden_states = self.embeddings(pixel_values)
|
| 336 |
+
else:
|
| 337 |
+
raise ValueError(f'wrong pixel_values size: {pixel_values.shape}')
|
| 338 |
+
encoder_outputs = self.encoder(
|
| 339 |
+
inputs_embeds=hidden_states,
|
| 340 |
+
output_hidden_states=output_hidden_states,
|
| 341 |
+
return_dict=return_dict,
|
| 342 |
+
)
|
| 343 |
+
last_hidden_state = encoder_outputs.last_hidden_state
|
| 344 |
+
pooled_output = last_hidden_state[:, 0, :]
|
| 345 |
+
|
| 346 |
+
if not return_dict:
|
| 347 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
| 348 |
+
|
| 349 |
+
return BaseModelOutputWithPooling(
|
| 350 |
+
last_hidden_state=last_hidden_state,
|
| 351 |
+
pooler_output=pooled_output,
|
| 352 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 353 |
+
attentions=encoder_outputs.attentions,
|
| 354 |
+
)
|
VISTA/llava/model/multimodal_encoder/internvl_14b/modeling_internvl.py
ADDED
|
@@ -0,0 +1,543 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------
|
| 2 |
+
# InternVL
|
| 3 |
+
# Copyright (c) 2023 OpenGVLab
|
| 4 |
+
# Licensed under The MIT License [see LICENSE for details]
|
| 5 |
+
# --------------------------------------------------------
|
| 6 |
+
from functools import partial
|
| 7 |
+
from typing import Optional
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
import torch.utils.checkpoint
|
| 13 |
+
from peft import LoraConfig, get_peft_model
|
| 14 |
+
from timm.models.layers import DropPath
|
| 15 |
+
from torch import nn
|
| 16 |
+
from transformers import GenerationConfig
|
| 17 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 18 |
+
from transformers.utils import logging
|
| 19 |
+
|
| 20 |
+
from .configuration_internvl import InternVLConfig
|
| 21 |
+
from .modeling_intern_vit import (InternVisionEmbeddings, InternVisionEncoder,
|
| 22 |
+
InternVisionModel)
|
| 23 |
+
from .modeling_qllama import LlamaForCausalLM, _expand_mask, _make_causal_mask
|
| 24 |
+
|
| 25 |
+
try:
|
| 26 |
+
from .flash_attention import FlashAttention # v1/v2
|
| 27 |
+
except:
|
| 28 |
+
print('FlashAttention is not installed.')
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class InternVLPreTrainedModel(PreTrainedModel):
|
| 34 |
+
"""
|
| 35 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 36 |
+
models.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
config_class = InternVLConfig
|
| 40 |
+
base_model_prefix = 'internvl'
|
| 41 |
+
supports_gradient_checkpointing = True
|
| 42 |
+
_keys_to_ignore_on_load_missing = [
|
| 43 |
+
r'position_ids',
|
| 44 |
+
]
|
| 45 |
+
_no_split_modules = ['InternAttention', 'LlamaDecoderLayer', 'LlamaForCausalLM']
|
| 46 |
+
_skip_keys_device_placement = 'past_key_values'
|
| 47 |
+
_keep_in_fp32_modules = ['wo']
|
| 48 |
+
|
| 49 |
+
def _init_weights(self, module):
|
| 50 |
+
"""Initialize the weights"""
|
| 51 |
+
factor = self.config.initializer_range
|
| 52 |
+
if isinstance(module, nn.Conv2d) or isinstance(module, nn.Embedding) or isinstance(module, nn.Linear):
|
| 53 |
+
module.weight.data.normal_(mean=0.0, std=factor)
|
| 54 |
+
if hasattr(module, 'bias') and module.bias is not None:
|
| 55 |
+
module.bias.data.zero_()
|
| 56 |
+
if isinstance(module, InternVisionEmbeddings):
|
| 57 |
+
if hasattr(self.config, 'vision_config'):
|
| 58 |
+
factor = self.config.vision_config.initializer_range
|
| 59 |
+
nn.init.trunc_normal_(module.position_embedding, mean=0.0, std=factor)
|
| 60 |
+
nn.init.trunc_normal_(module.class_embedding, mean=0.0, std=factor)
|
| 61 |
+
elif isinstance(module, nn.LayerNorm):
|
| 62 |
+
module.bias.data.zero_()
|
| 63 |
+
module.weight.data.fill_(1.0)
|
| 64 |
+
elif isinstance(module, nn.Linear) and module.bias is not None:
|
| 65 |
+
module.bias.data.zero_()
|
| 66 |
+
|
| 67 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
| 68 |
+
if isinstance(module, InternVisionModel):
|
| 69 |
+
module.gradient_checkpointing = value
|
| 70 |
+
if isinstance(module, InternVisionEncoder):
|
| 71 |
+
module.gradient_checkpointing = value
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class CrossAttention(nn.Module):
|
| 75 |
+
def __init__(
|
| 76 |
+
self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.,
|
| 77 |
+
proj_drop=0., attn_head_dim=None, out_dim=None):
|
| 78 |
+
super().__init__()
|
| 79 |
+
if out_dim is None:
|
| 80 |
+
out_dim = dim
|
| 81 |
+
self.num_heads = num_heads
|
| 82 |
+
head_dim = dim // num_heads
|
| 83 |
+
if attn_head_dim is not None:
|
| 84 |
+
head_dim = attn_head_dim
|
| 85 |
+
all_head_dim = head_dim * self.num_heads
|
| 86 |
+
self.scale = qk_scale or head_dim ** -0.5
|
| 87 |
+
assert all_head_dim == dim
|
| 88 |
+
|
| 89 |
+
self.q = nn.Linear(dim, all_head_dim, bias=False)
|
| 90 |
+
self.k = nn.Linear(dim, all_head_dim, bias=False)
|
| 91 |
+
self.v = nn.Linear(dim, all_head_dim, bias=False)
|
| 92 |
+
|
| 93 |
+
if qkv_bias:
|
| 94 |
+
self.q_bias = nn.Parameter(torch.zeros(all_head_dim))
|
| 95 |
+
self.k_bias = nn.Parameter(torch.zeros(all_head_dim))
|
| 96 |
+
self.v_bias = nn.Parameter(torch.zeros(all_head_dim))
|
| 97 |
+
else:
|
| 98 |
+
self.q_bias = None
|
| 99 |
+
self.k_bias = None
|
| 100 |
+
self.v_bias = None
|
| 101 |
+
|
| 102 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
| 103 |
+
self.proj = nn.Linear(all_head_dim, out_dim)
|
| 104 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
| 105 |
+
|
| 106 |
+
def forward(self, x, k=None, v=None):
|
| 107 |
+
B, N, C = x.shape
|
| 108 |
+
N_k = k.shape[1]
|
| 109 |
+
N_v = v.shape[1]
|
| 110 |
+
|
| 111 |
+
q_bias, k_bias, v_bias = None, None, None
|
| 112 |
+
if self.q_bias is not None:
|
| 113 |
+
q_bias = self.q_bias
|
| 114 |
+
k_bias = self.k_bias
|
| 115 |
+
v_bias = self.v_bias
|
| 116 |
+
|
| 117 |
+
q = F.linear(input=x, weight=self.q.weight, bias=q_bias)
|
| 118 |
+
q = q.reshape(B, N, 1, self.num_heads, -1).permute(2, 0, 3, 1, 4).squeeze(0) # (B, N_head, N_q, dim)
|
| 119 |
+
|
| 120 |
+
k = F.linear(input=k, weight=self.k.weight, bias=k_bias)
|
| 121 |
+
k = k.reshape(B, N_k, 1, self.num_heads, -1).permute(2, 0, 3, 1, 4).squeeze(0)
|
| 122 |
+
|
| 123 |
+
v = F.linear(input=v, weight=self.v.weight, bias=v_bias)
|
| 124 |
+
v = v.reshape(B, N_v, 1, self.num_heads, -1).permute(2, 0, 3, 1, 4).squeeze(0)
|
| 125 |
+
|
| 126 |
+
q = q * self.scale
|
| 127 |
+
attn = (q @ k.transpose(-2, -1)) # (B, N_head, N_q, N_k)
|
| 128 |
+
|
| 129 |
+
attn = attn.softmax(dim=-1)
|
| 130 |
+
attn = self.attn_drop(attn)
|
| 131 |
+
|
| 132 |
+
x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
|
| 133 |
+
x = self.proj(x)
|
| 134 |
+
x = self.proj_drop(x)
|
| 135 |
+
|
| 136 |
+
return x
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class AttentiveBlock(nn.Module):
|
| 140 |
+
|
| 141 |
+
def __init__(self, dim, num_heads, qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
|
| 142 |
+
drop_path=0., norm_layer=nn.LayerNorm, attn_head_dim=None, out_dim=None):
|
| 143 |
+
super().__init__()
|
| 144 |
+
|
| 145 |
+
self.norm1_q = norm_layer(dim)
|
| 146 |
+
self.norm1_k = norm_layer(dim)
|
| 147 |
+
self.norm1_v = norm_layer(dim)
|
| 148 |
+
self.cross_attn = CrossAttention(
|
| 149 |
+
dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop,
|
| 150 |
+
proj_drop=drop, attn_head_dim=attn_head_dim, out_dim=out_dim)
|
| 151 |
+
|
| 152 |
+
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
| 153 |
+
|
| 154 |
+
def forward(self, x_q, x_kv, pos_q, pos_k, bool_masked_pos, rel_pos_bias=None):
|
| 155 |
+
x_q = self.norm1_q(x_q + pos_q)
|
| 156 |
+
x_k = self.norm1_k(x_kv + pos_k)
|
| 157 |
+
x_v = self.norm1_v(x_kv)
|
| 158 |
+
x = self.cross_attn(x_q, k=x_k, v=x_v)
|
| 159 |
+
|
| 160 |
+
return x
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class AttentionPoolingBlock(AttentiveBlock):
|
| 164 |
+
|
| 165 |
+
def forward(self, x):
|
| 166 |
+
x_q = x.mean(1, keepdim=True)
|
| 167 |
+
x_kv, pos_q, pos_k = x, 0, 0
|
| 168 |
+
x = super().forward(x_q, x_kv, pos_q, pos_k, bool_masked_pos=None, rel_pos_bias=None)
|
| 169 |
+
x = x.squeeze(1)
|
| 170 |
+
return x
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class InternVLModel(InternVLPreTrainedModel):
|
| 174 |
+
config_class = InternVLConfig
|
| 175 |
+
main_input_name = 'pixel_values'
|
| 176 |
+
|
| 177 |
+
def __init__(self, config: InternVLConfig):
|
| 178 |
+
super().__init__(config)
|
| 179 |
+
|
| 180 |
+
text_hidden_size = config.qllama_config.hidden_size
|
| 181 |
+
vision_hidden_size = config.vision_config.hidden_size
|
| 182 |
+
clip_embed_dim = config.clip_embed_dim
|
| 183 |
+
attn_pool_num_heads = config.attn_pool_num_heads
|
| 184 |
+
config.qllama_config.num_query_token = config.num_query_token
|
| 185 |
+
self.num_query_token = config.num_query_token
|
| 186 |
+
self.label_smoothing = config.label_smoothing
|
| 187 |
+
|
| 188 |
+
self.vision_model = InternVisionModel(config.vision_config) # frozen
|
| 189 |
+
self.qllama = LlamaForCausalLM(config.qllama_config) # frozen
|
| 190 |
+
self.query_tokens = nn.Parameter( # trainable
|
| 191 |
+
torch.zeros(1, config.num_query_token, text_hidden_size)
|
| 192 |
+
)
|
| 193 |
+
# self.text_projection = nn.Parameter(torch.empty(text_hidden_size, clip_embed_dim)) # frozen
|
| 194 |
+
# self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) # trainable
|
| 195 |
+
# self.clip_projector = AttentionPoolingBlock( # frozen
|
| 196 |
+
# dim=vision_hidden_size, num_heads=attn_pool_num_heads, qkv_bias=True, qk_scale=None,
|
| 197 |
+
# drop=0., attn_drop=0., norm_layer=partial(nn.LayerNorm, eps=1e-5), out_dim=clip_embed_dim)
|
| 198 |
+
# self.clip_projector2 = AttentionPoolingBlock( # trainable
|
| 199 |
+
# dim=text_hidden_size, num_heads=attn_pool_num_heads, qkv_bias=True, qk_scale=None,
|
| 200 |
+
# drop=0., attn_drop=0., norm_layer=partial(nn.LayerNorm, eps=1e-5), out_dim=clip_embed_dim)
|
| 201 |
+
# self.itm_head = nn.Linear(text_hidden_size, 2) # trainable
|
| 202 |
+
self.gradient_checkpointing = True
|
| 203 |
+
|
| 204 |
+
# Initialize weights and apply final processing
|
| 205 |
+
# self.post_init()
|
| 206 |
+
|
| 207 |
+
if config.use_backbone_lora:
|
| 208 |
+
self.wrap_backbone_lora(r=config.use_backbone_lora)
|
| 209 |
+
if config.use_qllama_lora:
|
| 210 |
+
self.wrap_qllama_lora(r=config.use_qllama_lora)
|
| 211 |
+
if config.force_image_size:
|
| 212 |
+
self.vision_model.resize_pos_embeddings(
|
| 213 |
+
old_size=config.vision_config.image_size,
|
| 214 |
+
new_size=config.force_image_size,
|
| 215 |
+
patch_size=config.vision_config.patch_size
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
def wrap_backbone_lora(self, r=128, lora_alpha=256, lora_dropout=0.05):
|
| 219 |
+
lora_config = LoraConfig(
|
| 220 |
+
r=r,
|
| 221 |
+
target_modules=['attn.qkv', 'attn.proj', 'mlp.fc1', 'mlp.fc2'],
|
| 222 |
+
lora_alpha=lora_alpha,
|
| 223 |
+
lora_dropout=lora_dropout,
|
| 224 |
+
)
|
| 225 |
+
self.vision_model = get_peft_model(self.vision_model, lora_config)
|
| 226 |
+
self.vision_model.print_trainable_parameters()
|
| 227 |
+
|
| 228 |
+
def wrap_qllama_lora(self, r=128, lora_alpha=256, lora_dropout=0.05):
|
| 229 |
+
lora_config = LoraConfig(
|
| 230 |
+
r=r,
|
| 231 |
+
target_modules=['self_attn.q_proj', 'self_attn.k_proj', 'self_attn.v_proj', 'self_attn.o_proj',
|
| 232 |
+
'mlp.gate_proj', 'mlp.down_proj', 'mlp.up_proj'],
|
| 233 |
+
lora_alpha=lora_alpha,
|
| 234 |
+
lora_dropout=lora_dropout,
|
| 235 |
+
)
|
| 236 |
+
self.qllama = get_peft_model(self.qllama, lora_config)
|
| 237 |
+
self.qllama.print_trainable_parameters()
|
| 238 |
+
|
| 239 |
+
def get_input_embeddings(self):
|
| 240 |
+
return self.qllama.get_input_embeddings()
|
| 241 |
+
|
| 242 |
+
def set_input_embeddings(self, value):
|
| 243 |
+
self.qllama.set_input_embeddings(value)
|
| 244 |
+
|
| 245 |
+
def set_output_embeddings(self, new_embeddings):
|
| 246 |
+
self.qllama.set_output_embeddings(new_embeddings)
|
| 247 |
+
|
| 248 |
+
def get_output_embeddings(self) -> nn.Module:
|
| 249 |
+
return self.qllama.get_output_embeddings()
|
| 250 |
+
|
| 251 |
+
@torch.no_grad()
|
| 252 |
+
def generate(
|
| 253 |
+
self,
|
| 254 |
+
pixel_values: torch.FloatTensor,
|
| 255 |
+
input_ids: torch.FloatTensor,
|
| 256 |
+
attention_mask: torch.LongTensor,
|
| 257 |
+
generation_config: Optional[GenerationConfig] = None,
|
| 258 |
+
output_hidden_states: Optional[bool] = None,
|
| 259 |
+
return_dict: Optional[bool] = None,
|
| 260 |
+
**generate_kwargs,
|
| 261 |
+
) -> torch.LongTensor:
|
| 262 |
+
|
| 263 |
+
vision_outputs = self.vision_model(
|
| 264 |
+
pixel_values=pixel_values,
|
| 265 |
+
output_hidden_states=output_hidden_states,
|
| 266 |
+
return_dict=return_dict)
|
| 267 |
+
image_embeds = vision_outputs[0]
|
| 268 |
+
|
| 269 |
+
batch_size = image_embeds.shape[0]
|
| 270 |
+
input_embeds = self.get_input_embeddings()(input_ids)
|
| 271 |
+
query_tokens = self.query_tokens.repeat(batch_size, 1, 1)
|
| 272 |
+
input_embeds = torch.cat([query_tokens, input_embeds], dim=1)
|
| 273 |
+
image_attention_mask = torch.ones(query_tokens.size()[:-1], dtype=torch.long, device=image_embeds.device)
|
| 274 |
+
attention_mask = torch.cat([image_attention_mask, attention_mask], dim=1)
|
| 275 |
+
|
| 276 |
+
outputs = self.qllama.generate(
|
| 277 |
+
inputs_embeds=input_embeds,
|
| 278 |
+
attention_mask=attention_mask,
|
| 279 |
+
vision_hidden_states=image_embeds,
|
| 280 |
+
generation_config=generation_config,
|
| 281 |
+
use_zero_attention_mask=True,
|
| 282 |
+
**generate_kwargs,
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
return outputs
|
| 286 |
+
|
| 287 |
+
def get_text_features(
|
| 288 |
+
self,
|
| 289 |
+
input_ids: torch.Tensor,
|
| 290 |
+
attention_mask: torch.Tensor,
|
| 291 |
+
output_attentions: Optional[bool] = None,
|
| 292 |
+
output_hidden_states: Optional[bool] = None,
|
| 293 |
+
return_dict: Optional[bool] = None,
|
| 294 |
+
):
|
| 295 |
+
r"""
|
| 296 |
+
Returns:
|
| 297 |
+
text_outputs (`CausalLMOutputWithPast`, or `tuple(torch.FloatTensor)` if `return_dict=False`):
|
| 298 |
+
The language model outputs. If `return_dict=True`, the output is a [`CausalLMOutputWithPast`] that
|
| 299 |
+
contains the language model logits, the past key values and the hidden states if
|
| 300 |
+
`output_hidden_states=True`.
|
| 301 |
+
```"""
|
| 302 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 303 |
+
output_hidden_states = (
|
| 304 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 305 |
+
)
|
| 306 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 307 |
+
|
| 308 |
+
input_embeds = self.get_input_embeddings()(input_ids)
|
| 309 |
+
attention_mask = _expand_mask(attention_mask, input_embeds.dtype).to(
|
| 310 |
+
input_embeds.device) # [bsz, 1, tgt_seq_len, src_seq_len]
|
| 311 |
+
attention_mask += _make_causal_mask(
|
| 312 |
+
(attention_mask.shape[0], attention_mask.shape[2]),
|
| 313 |
+
input_embeds.dtype,
|
| 314 |
+
device=input_embeds.device
|
| 315 |
+
)
|
| 316 |
+
if type(self.qllama.model) == LlamaForCausalLM:
|
| 317 |
+
outputs = self.qllama.model.model.forward_train(
|
| 318 |
+
inputs_embeds=input_embeds,
|
| 319 |
+
vision_hidden_states=None,
|
| 320 |
+
attention_mask=attention_mask,
|
| 321 |
+
output_attentions=output_attentions,
|
| 322 |
+
output_hidden_states=output_hidden_states,
|
| 323 |
+
return_dict=return_dict,
|
| 324 |
+
).last_hidden_state
|
| 325 |
+
else:
|
| 326 |
+
outputs = self.qllama.model.forward_train(
|
| 327 |
+
inputs_embeds=input_embeds,
|
| 328 |
+
vision_hidden_states=None,
|
| 329 |
+
attention_mask=attention_mask,
|
| 330 |
+
output_attentions=output_attentions,
|
| 331 |
+
output_hidden_states=output_hidden_states,
|
| 332 |
+
return_dict=return_dict,
|
| 333 |
+
).last_hidden_state
|
| 334 |
+
return outputs
|
| 335 |
+
|
| 336 |
+
def get_image_features(
|
| 337 |
+
self,
|
| 338 |
+
pixel_values: torch.FloatTensor,
|
| 339 |
+
output_attentions: Optional[bool] = None,
|
| 340 |
+
output_hidden_states: Optional[bool] = None,
|
| 341 |
+
return_dict: Optional[bool] = None,
|
| 342 |
+
):
|
| 343 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 344 |
+
output_hidden_states = (
|
| 345 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 346 |
+
)
|
| 347 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 348 |
+
|
| 349 |
+
vision_outputs = self.vision_model(
|
| 350 |
+
pixel_values=pixel_values,
|
| 351 |
+
output_hidden_states=output_hidden_states,
|
| 352 |
+
return_dict=return_dict)
|
| 353 |
+
image_embeds = vision_outputs[0]
|
| 354 |
+
backbone_embeds = image_embeds
|
| 355 |
+
|
| 356 |
+
batch_size = image_embeds.shape[0]
|
| 357 |
+
input_embeds = self.query_tokens.repeat(batch_size, 1, 1)
|
| 358 |
+
|
| 359 |
+
attention_mask = torch.ones(input_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)
|
| 360 |
+
attention_mask = _expand_mask(attention_mask, input_embeds.dtype).to(
|
| 361 |
+
input_embeds.device) # [bsz, 1, tgt_seq_len, src_seq_len]
|
| 362 |
+
if type(self.qllama.model) == LlamaForCausalLM:
|
| 363 |
+
outputs = self.qllama.model.model.forward_train(
|
| 364 |
+
inputs_embeds=input_embeds,
|
| 365 |
+
vision_hidden_states=image_embeds,
|
| 366 |
+
attention_mask=attention_mask,
|
| 367 |
+
output_attentions=output_attentions,
|
| 368 |
+
output_hidden_states=output_hidden_states,
|
| 369 |
+
return_dict=return_dict,
|
| 370 |
+
).last_hidden_state
|
| 371 |
+
else:
|
| 372 |
+
outputs = self.qllama.model.forward_train(
|
| 373 |
+
inputs_embeds=input_embeds,
|
| 374 |
+
vision_hidden_states=image_embeds,
|
| 375 |
+
attention_mask=attention_mask,
|
| 376 |
+
output_attentions=output_attentions,
|
| 377 |
+
output_hidden_states=output_hidden_states,
|
| 378 |
+
return_dict=return_dict,
|
| 379 |
+
).last_hidden_state
|
| 380 |
+
return backbone_embeds, outputs
|
| 381 |
+
|
| 382 |
+
def encode_image(self, image, mode):
|
| 383 |
+
if mode == 'InternVL-C':
|
| 384 |
+
vision_outputs = self.vision_model(
|
| 385 |
+
pixel_values=image,
|
| 386 |
+
output_hidden_states=False,
|
| 387 |
+
return_dict=True)
|
| 388 |
+
image_embeds = vision_outputs[0]
|
| 389 |
+
image_embeds = self.clip_projector(image_embeds)
|
| 390 |
+
elif mode == 'InternVL-G':
|
| 391 |
+
backbone_embeds, image_embeds = self.get_image_features(
|
| 392 |
+
pixel_values=image,
|
| 393 |
+
output_hidden_states=False,
|
| 394 |
+
return_dict=True,
|
| 395 |
+
)
|
| 396 |
+
backbone_embeds = self.clip_projector(backbone_embeds)
|
| 397 |
+
image_embeds = self.clip_projector2(image_embeds)
|
| 398 |
+
# ensemble
|
| 399 |
+
backbone_embeds = backbone_embeds / backbone_embeds.norm(dim=1, keepdim=True)
|
| 400 |
+
image_embeds = image_embeds / image_embeds.norm(dim=1, keepdim=True)
|
| 401 |
+
image_embeds = image_embeds + backbone_embeds
|
| 402 |
+
else:
|
| 403 |
+
raise NotImplementedError
|
| 404 |
+
return image_embeds
|
| 405 |
+
|
| 406 |
+
def encode_text(self, text):
|
| 407 |
+
attention_mask = text > 0
|
| 408 |
+
text_embeds = self.get_text_features(
|
| 409 |
+
input_ids=text,
|
| 410 |
+
attention_mask=attention_mask,
|
| 411 |
+
output_attentions=False,
|
| 412 |
+
output_hidden_states=False,
|
| 413 |
+
return_dict=True,
|
| 414 |
+
)
|
| 415 |
+
text_embeds = text_embeds[torch.arange(text_embeds.shape[0]), attention_mask.sum(1) - 1]
|
| 416 |
+
text_embeds = text_embeds @ self.text_projection
|
| 417 |
+
return text_embeds
|
| 418 |
+
|
| 419 |
+
def forward(self, pixel_values: torch.FloatTensor,
|
| 420 |
+
output_hidden_states: Optional[bool] = None,
|
| 421 |
+
return_dict: Optional[bool] = None) -> torch.Tensor:
|
| 422 |
+
output_hidden_states = (
|
| 423 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 424 |
+
)
|
| 425 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 426 |
+
|
| 427 |
+
vision_outputs = self.vision_model(
|
| 428 |
+
pixel_values=pixel_values,
|
| 429 |
+
output_hidden_states=output_hidden_states,
|
| 430 |
+
return_dict=return_dict)
|
| 431 |
+
image_embeds = vision_outputs[0]
|
| 432 |
+
|
| 433 |
+
batch_size = image_embeds.shape[0]
|
| 434 |
+
input_embeds = self.query_tokens.repeat(batch_size, 1, 1)
|
| 435 |
+
|
| 436 |
+
attention_mask = torch.ones(input_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)
|
| 437 |
+
attention_mask = _expand_mask(attention_mask, input_embeds.dtype).to(
|
| 438 |
+
input_embeds.device) # [bsz, 1, tgt_seq_len, src_seq_len]
|
| 439 |
+
if type(self.qllama.model) == LlamaForCausalLM:
|
| 440 |
+
outputs = self.qllama.model.model.forward_train(
|
| 441 |
+
inputs_embeds=input_embeds,
|
| 442 |
+
vision_hidden_states=image_embeds,
|
| 443 |
+
attention_mask=attention_mask,
|
| 444 |
+
output_attentions=False,
|
| 445 |
+
output_hidden_states=False,
|
| 446 |
+
return_dict=return_dict,
|
| 447 |
+
).last_hidden_state
|
| 448 |
+
else:
|
| 449 |
+
outputs = self.qllama.model.forward_train(
|
| 450 |
+
inputs_embeds=input_embeds,
|
| 451 |
+
vision_hidden_states=image_embeds,
|
| 452 |
+
attention_mask=attention_mask,
|
| 453 |
+
output_attentions=False,
|
| 454 |
+
output_hidden_states=False,
|
| 455 |
+
return_dict=return_dict,
|
| 456 |
+
).last_hidden_state
|
| 457 |
+
|
| 458 |
+
return vision_outputs, outputs
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
class InternVL_C(InternVLModel):
|
| 462 |
+
|
| 463 |
+
def encode_image(self, image):
|
| 464 |
+
vision_outputs = self.vision_model(
|
| 465 |
+
pixel_values=image,
|
| 466 |
+
output_hidden_states=False,
|
| 467 |
+
return_dict=True)
|
| 468 |
+
image_embeds = vision_outputs[0]
|
| 469 |
+
image_embeds = self.clip_projector(image_embeds)
|
| 470 |
+
return image_embeds
|
| 471 |
+
|
| 472 |
+
def encode_text(self, text):
|
| 473 |
+
attention_mask = text > 0
|
| 474 |
+
text_embeds = self.get_text_features(
|
| 475 |
+
input_ids=text,
|
| 476 |
+
attention_mask=attention_mask,
|
| 477 |
+
output_attentions=False,
|
| 478 |
+
output_hidden_states=False,
|
| 479 |
+
return_dict=True,
|
| 480 |
+
)
|
| 481 |
+
text_embeds = text_embeds[torch.arange(text_embeds.shape[0]), attention_mask.sum(1) - 1]
|
| 482 |
+
text_embeds = text_embeds @ self.text_projection
|
| 483 |
+
return text_embeds
|
| 484 |
+
|
| 485 |
+
def forward(self, image, text):
|
| 486 |
+
image_features = self.encode_image(image)
|
| 487 |
+
text_features = self.encode_text(text)
|
| 488 |
+
|
| 489 |
+
# normalized features
|
| 490 |
+
image_features = image_features / image_features.norm(dim=1, keepdim=True)
|
| 491 |
+
text_features = text_features / text_features.norm(dim=1, keepdim=True)
|
| 492 |
+
|
| 493 |
+
# cosine similarity as logits
|
| 494 |
+
logit_scale = self.logit_scale.exp()
|
| 495 |
+
logits_per_image = logit_scale * image_features @ text_features.t()
|
| 496 |
+
logits_per_text = logits_per_image.t()
|
| 497 |
+
|
| 498 |
+
return logits_per_image, logits_per_text
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
class InternVL_G(InternVLModel):
|
| 502 |
+
|
| 503 |
+
def encode_image(self, image):
|
| 504 |
+
backbone_embeds, image_embeds = self.get_image_features(
|
| 505 |
+
pixel_values=image,
|
| 506 |
+
output_hidden_states=False,
|
| 507 |
+
return_dict=True,
|
| 508 |
+
)
|
| 509 |
+
backbone_embeds = self.clip_projector(backbone_embeds)
|
| 510 |
+
image_embeds = self.clip_projector2(image_embeds)
|
| 511 |
+
# ensemble
|
| 512 |
+
backbone_embeds = backbone_embeds / backbone_embeds.norm(dim=1, keepdim=True)
|
| 513 |
+
image_embeds = image_embeds / image_embeds.norm(dim=1, keepdim=True)
|
| 514 |
+
image_embeds = image_embeds + backbone_embeds
|
| 515 |
+
return image_embeds
|
| 516 |
+
|
| 517 |
+
def encode_text(self, text):
|
| 518 |
+
attention_mask = text > 0
|
| 519 |
+
text_embeds = self.get_text_features(
|
| 520 |
+
input_ids=text,
|
| 521 |
+
attention_mask=attention_mask,
|
| 522 |
+
output_attentions=False,
|
| 523 |
+
output_hidden_states=False,
|
| 524 |
+
return_dict=True,
|
| 525 |
+
)
|
| 526 |
+
text_embeds = text_embeds[torch.arange(text_embeds.shape[0]), attention_mask.sum(1) - 1]
|
| 527 |
+
text_embeds = text_embeds @ self.text_projection
|
| 528 |
+
return text_embeds
|
| 529 |
+
|
| 530 |
+
def forward(self, image, text):
|
| 531 |
+
image_features = self.encode_image(image)
|
| 532 |
+
text_features = self.encode_text(text)
|
| 533 |
+
|
| 534 |
+
# normalized features
|
| 535 |
+
image_features = image_features / image_features.norm(dim=1, keepdim=True)
|
| 536 |
+
text_features = text_features / text_features.norm(dim=1, keepdim=True)
|
| 537 |
+
|
| 538 |
+
# cosine similarity as logits
|
| 539 |
+
logit_scale = self.logit_scale.exp()
|
| 540 |
+
logits_per_image = logit_scale * image_features @ text_features.t()
|
| 541 |
+
logits_per_text = logits_per_image.t()
|
| 542 |
+
|
| 543 |
+
return logits_per_image, logits_per_text
|
VISTA/llava/model/multimodal_encoder/internvl_14b/modeling_qllama.py
ADDED
|
@@ -0,0 +1,1073 @@
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
| 4 |
+
# and OPT implementations in this library. It has been modified from its
|
| 5 |
+
# original forms to accommodate minor architectural differences compared
|
| 6 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
| 7 |
+
#
|
| 8 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 9 |
+
# you may not use this file except in compliance with the License.
|
| 10 |
+
# You may obtain a copy of the License at
|
| 11 |
+
#
|
| 12 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 13 |
+
#
|
| 14 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 15 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 16 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 17 |
+
# See the License for the specific language governing permissions and
|
| 18 |
+
# limitations under the License.
|
| 19 |
+
""" PyTorch QLLaMA model."""
|
| 20 |
+
import math
|
| 21 |
+
from typing import List, Optional, Tuple, Union
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
import torch.utils.checkpoint
|
| 25 |
+
from torch import nn
|
| 26 |
+
from torch.nn import CrossEntropyLoss
|
| 27 |
+
from transformers import LlamaConfig
|
| 28 |
+
from transformers.activations import ACT2FN
|
| 29 |
+
from transformers.modeling_outputs import (BaseModelOutputWithPast,
|
| 30 |
+
CausalLMOutputWithPast)
|
| 31 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 32 |
+
from transformers.utils import (add_start_docstrings,
|
| 33 |
+
add_start_docstrings_to_model_forward, logging,
|
| 34 |
+
replace_return_docstrings)
|
| 35 |
+
|
| 36 |
+
logger = logging.get_logger(__name__)
|
| 37 |
+
|
| 38 |
+
_CONFIG_FOR_DOC = 'LlamaConfig'
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
|
| 42 |
+
def _make_causal_mask(
|
| 43 |
+
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
|
| 44 |
+
):
|
| 45 |
+
"""
|
| 46 |
+
Make causal mask used for bi-directional self-attention.
|
| 47 |
+
"""
|
| 48 |
+
bsz, tgt_len = input_ids_shape
|
| 49 |
+
mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
|
| 50 |
+
mask_cond = torch.arange(mask.size(-1), device=device)
|
| 51 |
+
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
| 52 |
+
mask = mask.to(dtype)
|
| 53 |
+
|
| 54 |
+
if past_key_values_length > 0:
|
| 55 |
+
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
| 56 |
+
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# Copied from transformers.models.bart.modeling_bart._expand_mask
|
| 60 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
| 61 |
+
"""
|
| 62 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
| 63 |
+
"""
|
| 64 |
+
bsz, src_len = mask.size()
|
| 65 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
| 66 |
+
|
| 67 |
+
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
| 68 |
+
|
| 69 |
+
inverted_mask = 1.0 - expanded_mask
|
| 70 |
+
|
| 71 |
+
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class LlamaRMSNorm(nn.Module):
|
| 75 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 76 |
+
"""
|
| 77 |
+
LlamaRMSNorm is equivalent to T5LayerNorm
|
| 78 |
+
"""
|
| 79 |
+
super().__init__()
|
| 80 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 81 |
+
self.variance_epsilon = eps
|
| 82 |
+
|
| 83 |
+
def forward(self, hidden_states):
|
| 84 |
+
variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
|
| 85 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 86 |
+
|
| 87 |
+
# convert into half-precision if necessary
|
| 88 |
+
if self.weight.dtype in [torch.float16, torch.bfloat16]:
|
| 89 |
+
hidden_states = hidden_states.to(self.weight.dtype)
|
| 90 |
+
|
| 91 |
+
return self.weight * hidden_states
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
try:
|
| 95 |
+
from functools import partial
|
| 96 |
+
|
| 97 |
+
from apex.normalization import FusedRMSNorm
|
| 98 |
+
|
| 99 |
+
LlamaRMSNorm = partial(FusedRMSNorm, eps=1e-6) # noqa
|
| 100 |
+
print('Discovered apex.normalization.FusedRMSNorm - will use it instead of LlamaRMSNorm')
|
| 101 |
+
except ImportError:
|
| 102 |
+
# using the normal LlamaRMSNorm
|
| 103 |
+
pass
|
| 104 |
+
except Exception:
|
| 105 |
+
print('discovered apex but it failed to load, falling back to LlamaRMSNorm')
|
| 106 |
+
pass
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class LlamaRotaryEmbedding(torch.nn.Module):
|
| 110 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
| 111 |
+
super().__init__()
|
| 112 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
|
| 113 |
+
self.register_buffer('inv_freq', inv_freq)
|
| 114 |
+
|
| 115 |
+
# Build here to make `torch.jit.trace` work.
|
| 116 |
+
self.max_seq_len_cached = max_position_embeddings
|
| 117 |
+
t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
|
| 118 |
+
freqs = torch.einsum('i,j->ij', t, self.inv_freq)
|
| 119 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
| 120 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 121 |
+
self.register_buffer('cos_cached', emb.cos()[None, None, :, :], persistent=False)
|
| 122 |
+
self.register_buffer('sin_cached', emb.sin()[None, None, :, :], persistent=False)
|
| 123 |
+
|
| 124 |
+
def forward(self, x, seq_len=None):
|
| 125 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
| 126 |
+
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
|
| 127 |
+
if seq_len > self.max_seq_len_cached:
|
| 128 |
+
self.max_seq_len_cached = seq_len
|
| 129 |
+
t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
|
| 130 |
+
freqs = torch.einsum('i,j->ij', t, self.inv_freq)
|
| 131 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
| 132 |
+
emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
|
| 133 |
+
self.register_buffer('cos_cached', emb.cos()[None, None, :, :], persistent=False)
|
| 134 |
+
self.register_buffer('sin_cached', emb.sin()[None, None, :, :], persistent=False)
|
| 135 |
+
return (
|
| 136 |
+
self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
| 137 |
+
self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
class FixedLlamaRotaryEmbedding(torch.nn.Module):
|
| 142 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
| 143 |
+
super().__init__()
|
| 144 |
+
|
| 145 |
+
self.dim = dim
|
| 146 |
+
self.max_position_embeddings = max_position_embeddings
|
| 147 |
+
self.base = base
|
| 148 |
+
self.inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
|
| 149 |
+
|
| 150 |
+
# Build here to make `torch.jit.trace` work.
|
| 151 |
+
self._set_cos_sin_cache(
|
| 152 |
+
seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
| 156 |
+
self.max_seq_len_cached = seq_len
|
| 157 |
+
t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=torch.float32)
|
| 158 |
+
|
| 159 |
+
freqs = torch.outer(t, self.inv_freq)
|
| 160 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
| 161 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 162 |
+
self.register_buffer('cos_cached', emb.cos()[None, None, :, :], persistent=False)
|
| 163 |
+
self.register_buffer('sin_cached', emb.sin()[None, None, :, :], persistent=False)
|
| 164 |
+
|
| 165 |
+
def forward(self, x, seq_len=None):
|
| 166 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
| 167 |
+
if seq_len > self.max_seq_len_cached:
|
| 168 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
| 169 |
+
|
| 170 |
+
return (
|
| 171 |
+
self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
| 172 |
+
self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
LlamaRotaryEmbedding = FixedLlamaRotaryEmbedding
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def rotate_half(x):
|
| 180 |
+
"""Rotates half the hidden dims of the input."""
|
| 181 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 182 |
+
x2 = x[..., x.shape[-1] // 2:]
|
| 183 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
|
| 187 |
+
gather_indices = position_ids[:, None, :, None] # [bs, 1, seq_len, 1]
|
| 188 |
+
gather_indices = gather_indices.repeat(1, cos.shape[1], 1, cos.shape[3])
|
| 189 |
+
cos = torch.gather(cos.repeat(gather_indices.shape[0], 1, 1, 1), 2, gather_indices)
|
| 190 |
+
sin = torch.gather(sin.repeat(gather_indices.shape[0], 1, 1, 1), 2, gather_indices)
|
| 191 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 192 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 193 |
+
return q_embed, k_embed
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
class LlamaMLP(nn.Module):
|
| 197 |
+
def __init__(
|
| 198 |
+
self,
|
| 199 |
+
hidden_size: int,
|
| 200 |
+
intermediate_size: int,
|
| 201 |
+
hidden_act: str,
|
| 202 |
+
):
|
| 203 |
+
super().__init__()
|
| 204 |
+
self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
| 205 |
+
self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
|
| 206 |
+
self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
| 207 |
+
self.act_fn = ACT2FN[hidden_act]
|
| 208 |
+
|
| 209 |
+
def forward(self, x):
|
| 210 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
class LlamaAttention(nn.Module):
|
| 214 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 215 |
+
|
| 216 |
+
def __init__(self, config: LlamaConfig):
|
| 217 |
+
super().__init__()
|
| 218 |
+
self.config = config
|
| 219 |
+
self.hidden_size = config.hidden_size
|
| 220 |
+
self.num_heads = config.num_attention_heads
|
| 221 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 222 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 223 |
+
|
| 224 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
| 225 |
+
raise ValueError(
|
| 226 |
+
f'hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}'
|
| 227 |
+
f' and `num_heads`: {self.num_heads}).'
|
| 228 |
+
)
|
| 229 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
| 230 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
| 231 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
| 232 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
| 233 |
+
self.rotary_emb = LlamaRotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
|
| 234 |
+
|
| 235 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
| 236 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 237 |
+
|
| 238 |
+
def forward(
|
| 239 |
+
self,
|
| 240 |
+
hidden_states: torch.Tensor,
|
| 241 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 242 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 243 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 244 |
+
output_attentions: bool = False,
|
| 245 |
+
use_cache: bool = False,
|
| 246 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 247 |
+
bsz, q_len, _ = hidden_states.size()
|
| 248 |
+
|
| 249 |
+
query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 250 |
+
key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 251 |
+
value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 252 |
+
|
| 253 |
+
kv_seq_len = key_states.shape[-2]
|
| 254 |
+
if past_key_value is not None:
|
| 255 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
| 256 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
| 257 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
| 258 |
+
# [bsz, nh, t, hd]
|
| 259 |
+
|
| 260 |
+
if past_key_value is not None:
|
| 261 |
+
# reuse k, v, self_attention
|
| 262 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
| 263 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
| 264 |
+
|
| 265 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
| 266 |
+
|
| 267 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
| 268 |
+
|
| 269 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
| 270 |
+
raise ValueError(
|
| 271 |
+
f'Attention weights should be of size {(bsz * self.num_heads, q_len, kv_seq_len)}, but is'
|
| 272 |
+
f' {attn_weights.size()}'
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
if attention_mask is not None:
|
| 276 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
| 277 |
+
raise ValueError(
|
| 278 |
+
f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}'
|
| 279 |
+
)
|
| 280 |
+
attn_weights = attn_weights + attention_mask
|
| 281 |
+
attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
|
| 282 |
+
|
| 283 |
+
# upcast attention to fp32
|
| 284 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
| 285 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 286 |
+
|
| 287 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
| 288 |
+
raise ValueError(
|
| 289 |
+
f'`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is'
|
| 290 |
+
f' {attn_output.size()}'
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
attn_output = attn_output.transpose(1, 2)
|
| 294 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
| 295 |
+
|
| 296 |
+
attn_output = self.o_proj(attn_output)
|
| 297 |
+
|
| 298 |
+
if not output_attentions:
|
| 299 |
+
attn_weights = None
|
| 300 |
+
|
| 301 |
+
return attn_output, attn_weights, past_key_value
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
class LlamaCrossAttention(nn.Module):
|
| 305 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 306 |
+
|
| 307 |
+
def __init__(self, config: LlamaConfig):
|
| 308 |
+
super().__init__()
|
| 309 |
+
self.config = config
|
| 310 |
+
self.hidden_size = config.hidden_size
|
| 311 |
+
self.num_heads = config.num_attention_heads
|
| 312 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 313 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 314 |
+
self.vision_hidden_size = 3200
|
| 315 |
+
|
| 316 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
| 317 |
+
raise ValueError(
|
| 318 |
+
f'hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}'
|
| 319 |
+
f' and `num_heads`: {self.num_heads}).'
|
| 320 |
+
)
|
| 321 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
| 322 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
| 323 |
+
self.norm1 = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 324 |
+
|
| 325 |
+
self.k_proj = nn.Linear(self.vision_hidden_size, self.num_heads * self.head_dim, bias=False)
|
| 326 |
+
self.v_proj = nn.Linear(self.vision_hidden_size, self.num_heads * self.head_dim, bias=False)
|
| 327 |
+
self.norm2 = LlamaRMSNorm(self.vision_hidden_size, eps=config.rms_norm_eps)
|
| 328 |
+
|
| 329 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
| 330 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 331 |
+
|
| 332 |
+
def forward(
|
| 333 |
+
self,
|
| 334 |
+
hidden_states: torch.Tensor,
|
| 335 |
+
vision_hidden_states: torch.Tensor,
|
| 336 |
+
repeat_time: int = 1,
|
| 337 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 338 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 339 |
+
output_attentions: bool = False,
|
| 340 |
+
use_cache: bool = False,
|
| 341 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 342 |
+
hidden_states = self.norm1(hidden_states)
|
| 343 |
+
|
| 344 |
+
bsz, q_len, _ = hidden_states.size()
|
| 345 |
+
|
| 346 |
+
query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 347 |
+
|
| 348 |
+
vision_hidden_states = self.norm2(vision_hidden_states)
|
| 349 |
+
|
| 350 |
+
bs_v, kv_len, _ = vision_hidden_states.size()
|
| 351 |
+
|
| 352 |
+
key_states = self.k_proj(vision_hidden_states).view(
|
| 353 |
+
bs_v, kv_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 354 |
+
value_states = self.v_proj(vision_hidden_states).view(
|
| 355 |
+
bs_v, kv_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 356 |
+
|
| 357 |
+
key_states = key_states.repeat(repeat_time, 1, 1, 1)
|
| 358 |
+
value_states = value_states.repeat(repeat_time, 1, 1, 1)
|
| 359 |
+
|
| 360 |
+
kv_seq_len = key_states.shape[-2]
|
| 361 |
+
if past_key_value is not None:
|
| 362 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
| 363 |
+
|
| 364 |
+
if past_key_value is not None:
|
| 365 |
+
# reuse k, v, self_attention
|
| 366 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
| 367 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
| 368 |
+
|
| 369 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
| 370 |
+
|
| 371 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
| 372 |
+
|
| 373 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
| 374 |
+
raise ValueError(
|
| 375 |
+
f'Attention weights should be of size {(bsz * self.num_heads, q_len, kv_seq_len)}, but is'
|
| 376 |
+
f' {attn_weights.size()}'
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
if attention_mask is not None:
|
| 380 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
| 381 |
+
raise ValueError(
|
| 382 |
+
f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}'
|
| 383 |
+
)
|
| 384 |
+
attn_weights = attn_weights + attention_mask
|
| 385 |
+
attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
|
| 386 |
+
|
| 387 |
+
# upcast attention to fp32
|
| 388 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
| 389 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 390 |
+
|
| 391 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
| 392 |
+
raise ValueError(
|
| 393 |
+
f'`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is'
|
| 394 |
+
f' {attn_output.size()}'
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
attn_output = attn_output.transpose(1, 2)
|
| 398 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
| 399 |
+
|
| 400 |
+
attn_output = self.o_proj(attn_output)
|
| 401 |
+
|
| 402 |
+
if not output_attentions:
|
| 403 |
+
attn_weights = None
|
| 404 |
+
|
| 405 |
+
return attn_output, attn_weights, past_key_value
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
class LlamaDecoderLayer(nn.Module):
|
| 409 |
+
def __init__(self, config: LlamaConfig, use_cross_attn: bool):
|
| 410 |
+
super().__init__()
|
| 411 |
+
self.hidden_size = config.hidden_size
|
| 412 |
+
self.self_attn = LlamaAttention(config=config)
|
| 413 |
+
self.cross_attn = LlamaCrossAttention(config=config) if use_cross_attn else None
|
| 414 |
+
self.mlp = LlamaMLP(
|
| 415 |
+
hidden_size=self.hidden_size,
|
| 416 |
+
intermediate_size=config.intermediate_size,
|
| 417 |
+
hidden_act=config.hidden_act,
|
| 418 |
+
)
|
| 419 |
+
self.num_query_token = 96
|
| 420 |
+
self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 421 |
+
self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 422 |
+
|
| 423 |
+
def forward(
|
| 424 |
+
self,
|
| 425 |
+
hidden_states: torch.Tensor,
|
| 426 |
+
vision_hidden_states: torch.Tensor,
|
| 427 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 428 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 429 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 430 |
+
output_attentions: Optional[bool] = False,
|
| 431 |
+
use_cache: Optional[bool] = False,
|
| 432 |
+
repeat_time: int = 1,
|
| 433 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 434 |
+
"""
|
| 435 |
+
Args:
|
| 436 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 437 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
| 438 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 439 |
+
output_attentions (`bool`, *optional*):
|
| 440 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 441 |
+
returned tensors for more detail.
|
| 442 |
+
use_cache (`bool`, *optional*):
|
| 443 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 444 |
+
(see `past_key_values`).
|
| 445 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
| 446 |
+
"""
|
| 447 |
+
|
| 448 |
+
residual = hidden_states
|
| 449 |
+
|
| 450 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 451 |
+
|
| 452 |
+
# Self Attention
|
| 453 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
| 454 |
+
hidden_states=hidden_states,
|
| 455 |
+
attention_mask=attention_mask,
|
| 456 |
+
position_ids=position_ids,
|
| 457 |
+
past_key_value=past_key_value,
|
| 458 |
+
output_attentions=output_attentions,
|
| 459 |
+
use_cache=use_cache,
|
| 460 |
+
)
|
| 461 |
+
hidden_states = residual + hidden_states
|
| 462 |
+
|
| 463 |
+
# when using generate function and cache mode, the size of hidden_states is 1,
|
| 464 |
+
# so we should not use cross attention
|
| 465 |
+
if self.cross_attn is not None and hidden_states.size(1) >= self.num_query_token \
|
| 466 |
+
and vision_hidden_states is not None:
|
| 467 |
+
query_feats = hidden_states[:, :self.num_query_token, :]
|
| 468 |
+
text_feats = hidden_states[:, self.num_query_token:, :]
|
| 469 |
+
residual = query_feats
|
| 470 |
+
query_feats, _, _ = self.cross_attn(
|
| 471 |
+
hidden_states=query_feats,
|
| 472 |
+
vision_hidden_states=vision_hidden_states,
|
| 473 |
+
attention_mask=None, # not use attention mask in cross attention
|
| 474 |
+
past_key_value=past_key_value,
|
| 475 |
+
output_attentions=output_attentions,
|
| 476 |
+
use_cache=use_cache,
|
| 477 |
+
repeat_time=repeat_time,
|
| 478 |
+
)
|
| 479 |
+
query_feats = residual + query_feats
|
| 480 |
+
hidden_states = torch.cat([query_feats, text_feats], dim=1)
|
| 481 |
+
|
| 482 |
+
# Fully Connected
|
| 483 |
+
residual = hidden_states
|
| 484 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 485 |
+
hidden_states = self.mlp(hidden_states)
|
| 486 |
+
hidden_states = residual + hidden_states
|
| 487 |
+
|
| 488 |
+
outputs = (hidden_states,)
|
| 489 |
+
|
| 490 |
+
if output_attentions:
|
| 491 |
+
outputs += (self_attn_weights,)
|
| 492 |
+
|
| 493 |
+
if use_cache:
|
| 494 |
+
outputs += (present_key_value,)
|
| 495 |
+
|
| 496 |
+
return outputs
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
LLAMA_START_DOCSTRING = r"""
|
| 500 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 501 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 502 |
+
etc.)
|
| 503 |
+
|
| 504 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 505 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 506 |
+
and behavior.
|
| 507 |
+
|
| 508 |
+
Parameters:
|
| 509 |
+
config ([`LlamaConfig`]):
|
| 510 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
| 511 |
+
load the weights associated with the model, only the configuration. Check out the
|
| 512 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 513 |
+
"""
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
@add_start_docstrings(
|
| 517 |
+
'The bare LLaMA Model outputting raw hidden-states without any specific head on top.',
|
| 518 |
+
LLAMA_START_DOCSTRING,
|
| 519 |
+
)
|
| 520 |
+
class LlamaPreTrainedModel(PreTrainedModel):
|
| 521 |
+
config_class = LlamaConfig
|
| 522 |
+
base_model_prefix = 'model'
|
| 523 |
+
supports_gradient_checkpointing = True
|
| 524 |
+
_no_split_modules = ['LlamaDecoderLayer']
|
| 525 |
+
_keys_to_ignore_on_load_unexpected = [r'decoder\.version']
|
| 526 |
+
|
| 527 |
+
def _init_weights(self, module):
|
| 528 |
+
std = self.config.initializer_range
|
| 529 |
+
if isinstance(module, nn.Linear):
|
| 530 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 531 |
+
if module.bias is not None:
|
| 532 |
+
module.bias.data.zero_()
|
| 533 |
+
elif isinstance(module, nn.Embedding):
|
| 534 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 535 |
+
if module.padding_idx is not None:
|
| 536 |
+
module.weight.data[module.padding_idx].zero_()
|
| 537 |
+
|
| 538 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
| 539 |
+
if isinstance(module, LlamaModel):
|
| 540 |
+
module.gradient_checkpointing = value
|
| 541 |
+
if isinstance(module, LlamaDecoderLayer):
|
| 542 |
+
module.gradient_checkpointing = value
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
LLAMA_INPUTS_DOCSTRING = r"""
|
| 546 |
+
Args:
|
| 547 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 548 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 549 |
+
it.
|
| 550 |
+
|
| 551 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 552 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 553 |
+
|
| 554 |
+
[What are input IDs?](../glossary#input-ids)
|
| 555 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 556 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 557 |
+
|
| 558 |
+
- 1 for tokens that are **not masked**,
|
| 559 |
+
- 0 for tokens that are **masked**.
|
| 560 |
+
|
| 561 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 562 |
+
|
| 563 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 564 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 565 |
+
|
| 566 |
+
If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
| 567 |
+
`past_key_values`).
|
| 568 |
+
|
| 569 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
| 570 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
| 571 |
+
information on the default strategy.
|
| 572 |
+
|
| 573 |
+
- 1 indicates the head is **not masked**,
|
| 574 |
+
- 0 indicates the head is **masked**.
|
| 575 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 576 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 577 |
+
config.n_positions - 1]`.
|
| 578 |
+
|
| 579 |
+
[What are position IDs?](../glossary#position-ids)
|
| 580 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 581 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
| 582 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
|
| 583 |
+
`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
|
| 584 |
+
|
| 585 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
| 586 |
+
blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 587 |
+
|
| 588 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 589 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 590 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 591 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 592 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 593 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 594 |
+
model's internal embedding lookup matrix.
|
| 595 |
+
use_cache (`bool`, *optional*):
|
| 596 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 597 |
+
`past_key_values`).
|
| 598 |
+
output_attentions (`bool`, *optional*):
|
| 599 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 600 |
+
tensors for more detail.
|
| 601 |
+
output_hidden_states (`bool`, *optional*):
|
| 602 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 603 |
+
more detail.
|
| 604 |
+
return_dict (`bool`, *optional*):
|
| 605 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 606 |
+
"""
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
@add_start_docstrings(
|
| 610 |
+
'The bare LLaMA Model outputting raw hidden-states without any specific head on top.',
|
| 611 |
+
LLAMA_START_DOCSTRING,
|
| 612 |
+
)
|
| 613 |
+
class LlamaModel(LlamaPreTrainedModel):
|
| 614 |
+
"""
|
| 615 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
|
| 616 |
+
|
| 617 |
+
Args:
|
| 618 |
+
config: LlamaConfig
|
| 619 |
+
"""
|
| 620 |
+
|
| 621 |
+
def __init__(self, config: LlamaConfig):
|
| 622 |
+
super().__init__(config)
|
| 623 |
+
self.padding_idx = config.pad_token_id
|
| 624 |
+
self.vocab_size = config.vocab_size
|
| 625 |
+
self.cross_attention_frequency = config.cross_attention_frequency
|
| 626 |
+
self.num_query_token = config.num_query_token
|
| 627 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 628 |
+
use_cross_attn = [idx % self.cross_attention_frequency == 0 for idx in range(config.num_hidden_layers)]
|
| 629 |
+
self.layers = nn.ModuleList(
|
| 630 |
+
[LlamaDecoderLayer(config, use_cross_attn[idx]) for idx in range(config.num_hidden_layers)])
|
| 631 |
+
self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 632 |
+
self.gradient_checkpointing = False
|
| 633 |
+
# Initialize weights and apply final processing
|
| 634 |
+
# self.post_init()
|
| 635 |
+
|
| 636 |
+
def get_input_embeddings(self):
|
| 637 |
+
return self.embed_tokens
|
| 638 |
+
|
| 639 |
+
def set_input_embeddings(self, value):
|
| 640 |
+
self.embed_tokens = value
|
| 641 |
+
|
| 642 |
+
# Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
|
| 643 |
+
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
|
| 644 |
+
# create causal mask
|
| 645 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 646 |
+
combined_attention_mask = None
|
| 647 |
+
if input_shape[-1] > 1:
|
| 648 |
+
combined_attention_mask = _make_causal_mask(
|
| 649 |
+
input_shape,
|
| 650 |
+
inputs_embeds.dtype,
|
| 651 |
+
device=inputs_embeds.device,
|
| 652 |
+
past_key_values_length=past_key_values_length,
|
| 653 |
+
)
|
| 654 |
+
|
| 655 |
+
if attention_mask is not None:
|
| 656 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 657 |
+
expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
|
| 658 |
+
inputs_embeds.device
|
| 659 |
+
)
|
| 660 |
+
combined_attention_mask = (
|
| 661 |
+
expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
|
| 662 |
+
)
|
| 663 |
+
|
| 664 |
+
return combined_attention_mask
|
| 665 |
+
|
| 666 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
| 667 |
+
def forward(
|
| 668 |
+
self,
|
| 669 |
+
input_ids: torch.LongTensor = None,
|
| 670 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 671 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 672 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 673 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 674 |
+
vision_hidden_states: Optional[torch.FloatTensor] = None,
|
| 675 |
+
repeat_time: Optional[int] = 1,
|
| 676 |
+
use_cache: Optional[bool] = None,
|
| 677 |
+
output_attentions: Optional[bool] = None,
|
| 678 |
+
output_hidden_states: Optional[bool] = None,
|
| 679 |
+
use_zero_attention_mask: Optional[bool] = None,
|
| 680 |
+
return_dict: Optional[bool] = None,
|
| 681 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
| 682 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 683 |
+
output_hidden_states = (
|
| 684 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 685 |
+
)
|
| 686 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 687 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 688 |
+
|
| 689 |
+
# retrieve input_ids and inputs_embeds
|
| 690 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 691 |
+
raise ValueError('You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time')
|
| 692 |
+
elif input_ids is not None:
|
| 693 |
+
batch_size, seq_length = input_ids.shape
|
| 694 |
+
elif inputs_embeds is not None:
|
| 695 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
| 696 |
+
else:
|
| 697 |
+
raise ValueError('You have to specify either decoder_input_ids or decoder_inputs_embeds')
|
| 698 |
+
seq_length_with_past = seq_length
|
| 699 |
+
past_key_values_length = 0
|
| 700 |
+
|
| 701 |
+
if past_key_values is not None:
|
| 702 |
+
past_key_values_length = past_key_values[0][0].shape[2]
|
| 703 |
+
seq_length_with_past = seq_length_with_past + past_key_values_length
|
| 704 |
+
|
| 705 |
+
if position_ids is None:
|
| 706 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 707 |
+
position_ids = torch.arange(
|
| 708 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
| 709 |
+
)
|
| 710 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
| 711 |
+
else:
|
| 712 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
| 713 |
+
|
| 714 |
+
if inputs_embeds is None:
|
| 715 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 716 |
+
# embed positions
|
| 717 |
+
if attention_mask is None:
|
| 718 |
+
attention_mask = torch.ones(
|
| 719 |
+
(batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
|
| 720 |
+
)
|
| 721 |
+
attention_mask = self._prepare_decoder_attention_mask(
|
| 722 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
| 723 |
+
)
|
| 724 |
+
if use_zero_attention_mask:
|
| 725 |
+
attention_mask[:, :, :self.num_query_token, :self.num_query_token] = 0
|
| 726 |
+
|
| 727 |
+
hidden_states = inputs_embeds
|
| 728 |
+
|
| 729 |
+
if self.gradient_checkpointing and self.training:
|
| 730 |
+
if use_cache:
|
| 731 |
+
logger.warning_once(
|
| 732 |
+
'`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...'
|
| 733 |
+
)
|
| 734 |
+
use_cache = False
|
| 735 |
+
|
| 736 |
+
# decoder layers
|
| 737 |
+
all_hidden_states = () if output_hidden_states else None
|
| 738 |
+
all_self_attns = () if output_attentions else None
|
| 739 |
+
next_decoder_cache = () if use_cache else None
|
| 740 |
+
|
| 741 |
+
for idx, decoder_layer in enumerate(self.layers):
|
| 742 |
+
if output_hidden_states:
|
| 743 |
+
all_hidden_states += (hidden_states,)
|
| 744 |
+
|
| 745 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
| 746 |
+
|
| 747 |
+
layer_outputs = decoder_layer(
|
| 748 |
+
hidden_states,
|
| 749 |
+
vision_hidden_states,
|
| 750 |
+
attention_mask=attention_mask,
|
| 751 |
+
position_ids=position_ids,
|
| 752 |
+
past_key_value=past_key_value,
|
| 753 |
+
output_attentions=output_attentions,
|
| 754 |
+
use_cache=use_cache,
|
| 755 |
+
repeat_time=repeat_time,
|
| 756 |
+
)
|
| 757 |
+
|
| 758 |
+
hidden_states = layer_outputs[0]
|
| 759 |
+
|
| 760 |
+
if use_cache:
|
| 761 |
+
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
|
| 762 |
+
|
| 763 |
+
if output_attentions:
|
| 764 |
+
all_self_attns += (layer_outputs[1],)
|
| 765 |
+
|
| 766 |
+
hidden_states = self.norm(hidden_states)
|
| 767 |
+
|
| 768 |
+
# add hidden states from the last decoder layer
|
| 769 |
+
if output_hidden_states:
|
| 770 |
+
all_hidden_states += (hidden_states,)
|
| 771 |
+
|
| 772 |
+
next_cache = next_decoder_cache if use_cache else None
|
| 773 |
+
if not return_dict:
|
| 774 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
| 775 |
+
return BaseModelOutputWithPast(
|
| 776 |
+
last_hidden_state=hidden_states,
|
| 777 |
+
past_key_values=next_cache,
|
| 778 |
+
hidden_states=all_hidden_states,
|
| 779 |
+
attentions=all_self_attns,
|
| 780 |
+
)
|
| 781 |
+
|
| 782 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
| 783 |
+
def forward_train(
|
| 784 |
+
self,
|
| 785 |
+
input_ids: torch.LongTensor = None,
|
| 786 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 787 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 788 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 789 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 790 |
+
vision_hidden_states: Optional[torch.FloatTensor] = None,
|
| 791 |
+
repeat_time: Optional[int] = 1,
|
| 792 |
+
use_cache: Optional[bool] = None,
|
| 793 |
+
output_attentions: Optional[bool] = None,
|
| 794 |
+
output_hidden_states: Optional[bool] = None,
|
| 795 |
+
return_dict: Optional[bool] = None,
|
| 796 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
| 797 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 798 |
+
output_hidden_states = (
|
| 799 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 800 |
+
)
|
| 801 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 802 |
+
|
| 803 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 804 |
+
|
| 805 |
+
# retrieve input_ids and inputs_embeds
|
| 806 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 807 |
+
raise ValueError('You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time')
|
| 808 |
+
elif input_ids is not None:
|
| 809 |
+
batch_size, seq_length = input_ids.shape
|
| 810 |
+
elif inputs_embeds is not None:
|
| 811 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
| 812 |
+
else:
|
| 813 |
+
raise ValueError('You have to specify either decoder_input_ids or decoder_inputs_embeds')
|
| 814 |
+
|
| 815 |
+
seq_length_with_past = seq_length
|
| 816 |
+
past_key_values_length = 0
|
| 817 |
+
|
| 818 |
+
if past_key_values is not None:
|
| 819 |
+
past_key_values_length = past_key_values[0][0].shape[2]
|
| 820 |
+
seq_length_with_past = seq_length_with_past + past_key_values_length
|
| 821 |
+
|
| 822 |
+
if position_ids is None:
|
| 823 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 824 |
+
position_ids = torch.arange(
|
| 825 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
| 826 |
+
)
|
| 827 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
| 828 |
+
else:
|
| 829 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
| 830 |
+
|
| 831 |
+
if inputs_embeds is None:
|
| 832 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 833 |
+
# embed positions
|
| 834 |
+
# if attention_mask is None:
|
| 835 |
+
# attention_mask = torch.ones(
|
| 836 |
+
# (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
|
| 837 |
+
# )
|
| 838 |
+
# attention_mask = self._prepare_decoder_attention_mask(
|
| 839 |
+
# attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
| 840 |
+
# )
|
| 841 |
+
hidden_states = inputs_embeds
|
| 842 |
+
|
| 843 |
+
if self.gradient_checkpointing and self.training:
|
| 844 |
+
if use_cache:
|
| 845 |
+
logger.warning_once(
|
| 846 |
+
'`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...'
|
| 847 |
+
)
|
| 848 |
+
use_cache = False
|
| 849 |
+
|
| 850 |
+
# decoder layers
|
| 851 |
+
all_hidden_states = () if output_hidden_states else None
|
| 852 |
+
all_self_attns = () if output_attentions else None
|
| 853 |
+
next_decoder_cache = () if use_cache else None
|
| 854 |
+
|
| 855 |
+
for idx, decoder_layer in enumerate(self.layers):
|
| 856 |
+
if output_hidden_states:
|
| 857 |
+
all_hidden_states += (hidden_states,)
|
| 858 |
+
|
| 859 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
| 860 |
+
|
| 861 |
+
if self.gradient_checkpointing and self.training:
|
| 862 |
+
|
| 863 |
+
def create_custom_forward(module):
|
| 864 |
+
def custom_forward(*inputs):
|
| 865 |
+
# None for past_key_value
|
| 866 |
+
return module(*inputs, output_attentions, None, repeat_time)
|
| 867 |
+
|
| 868 |
+
return custom_forward
|
| 869 |
+
|
| 870 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
| 871 |
+
create_custom_forward(decoder_layer),
|
| 872 |
+
hidden_states,
|
| 873 |
+
vision_hidden_states,
|
| 874 |
+
attention_mask,
|
| 875 |
+
position_ids,
|
| 876 |
+
None,
|
| 877 |
+
)
|
| 878 |
+
else:
|
| 879 |
+
layer_outputs = decoder_layer(
|
| 880 |
+
hidden_states,
|
| 881 |
+
vision_hidden_states,
|
| 882 |
+
attention_mask=attention_mask,
|
| 883 |
+
position_ids=position_ids,
|
| 884 |
+
past_key_value=past_key_value,
|
| 885 |
+
output_attentions=output_attentions,
|
| 886 |
+
use_cache=use_cache,
|
| 887 |
+
repeat_time=repeat_time,
|
| 888 |
+
)
|
| 889 |
+
|
| 890 |
+
hidden_states = layer_outputs[0]
|
| 891 |
+
|
| 892 |
+
if use_cache:
|
| 893 |
+
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
|
| 894 |
+
|
| 895 |
+
if output_attentions:
|
| 896 |
+
all_self_attns += (layer_outputs[1],)
|
| 897 |
+
|
| 898 |
+
hidden_states = self.norm(hidden_states)
|
| 899 |
+
|
| 900 |
+
# add hidden states from the last decoder layer
|
| 901 |
+
if output_hidden_states:
|
| 902 |
+
all_hidden_states += (hidden_states,)
|
| 903 |
+
|
| 904 |
+
next_cache = next_decoder_cache if use_cache else None
|
| 905 |
+
if not return_dict:
|
| 906 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
| 907 |
+
return BaseModelOutputWithPast(
|
| 908 |
+
last_hidden_state=hidden_states,
|
| 909 |
+
past_key_values=next_cache,
|
| 910 |
+
hidden_states=all_hidden_states,
|
| 911 |
+
attentions=all_self_attns,
|
| 912 |
+
)
|
| 913 |
+
|
| 914 |
+
|
| 915 |
+
class LlamaForCausalLM(LlamaPreTrainedModel):
|
| 916 |
+
def __init__(self, config):
|
| 917 |
+
super().__init__(config)
|
| 918 |
+
self.model = LlamaModel(config)
|
| 919 |
+
|
| 920 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 921 |
+
|
| 922 |
+
# Initialize weights and apply final processing
|
| 923 |
+
# self.post_init()
|
| 924 |
+
|
| 925 |
+
def get_input_embeddings(self):
|
| 926 |
+
return self.model.embed_tokens
|
| 927 |
+
|
| 928 |
+
def set_input_embeddings(self, value):
|
| 929 |
+
self.model.embed_tokens = value
|
| 930 |
+
|
| 931 |
+
def get_output_embeddings(self):
|
| 932 |
+
return self.lm_head
|
| 933 |
+
|
| 934 |
+
def set_output_embeddings(self, new_embeddings):
|
| 935 |
+
self.lm_head = new_embeddings
|
| 936 |
+
|
| 937 |
+
def set_decoder(self, decoder):
|
| 938 |
+
self.model = decoder
|
| 939 |
+
|
| 940 |
+
def get_decoder(self):
|
| 941 |
+
return self.model
|
| 942 |
+
|
| 943 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
| 944 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
| 945 |
+
def forward(
|
| 946 |
+
self,
|
| 947 |
+
input_ids: torch.LongTensor = None,
|
| 948 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 949 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 950 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 951 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 952 |
+
vision_hidden_states: Optional[torch.FloatTensor] = None,
|
| 953 |
+
labels: Optional[torch.LongTensor] = None,
|
| 954 |
+
use_cache: Optional[bool] = None,
|
| 955 |
+
output_attentions: Optional[bool] = None,
|
| 956 |
+
output_hidden_states: Optional[bool] = None,
|
| 957 |
+
use_zero_attention_mask: Optional[bool] = None,
|
| 958 |
+
return_dict: Optional[bool] = None,
|
| 959 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 960 |
+
r"""
|
| 961 |
+
Args:
|
| 962 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 963 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 964 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 965 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 966 |
+
|
| 967 |
+
Returns:
|
| 968 |
+
|
| 969 |
+
Example:
|
| 970 |
+
|
| 971 |
+
```python
|
| 972 |
+
>>> from transformers import AutoTokenizer, LlamaForCausalLM
|
| 973 |
+
|
| 974 |
+
>>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
|
| 975 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
|
| 976 |
+
|
| 977 |
+
>>> prompt = "Hey, are you consciours? Can you talk to me?"
|
| 978 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
| 979 |
+
|
| 980 |
+
>>> # Generate
|
| 981 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 982 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 983 |
+
"Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
|
| 984 |
+
```"""
|
| 985 |
+
|
| 986 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 987 |
+
output_hidden_states = (
|
| 988 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 989 |
+
)
|
| 990 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 991 |
+
|
| 992 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 993 |
+
outputs = self.model(
|
| 994 |
+
input_ids=input_ids,
|
| 995 |
+
attention_mask=attention_mask,
|
| 996 |
+
position_ids=position_ids,
|
| 997 |
+
past_key_values=past_key_values,
|
| 998 |
+
inputs_embeds=inputs_embeds,
|
| 999 |
+
vision_hidden_states=vision_hidden_states,
|
| 1000 |
+
use_cache=use_cache,
|
| 1001 |
+
output_attentions=output_attentions,
|
| 1002 |
+
output_hidden_states=output_hidden_states,
|
| 1003 |
+
return_dict=return_dict,
|
| 1004 |
+
use_zero_attention_mask=use_zero_attention_mask,
|
| 1005 |
+
)
|
| 1006 |
+
|
| 1007 |
+
hidden_states = outputs[0]
|
| 1008 |
+
logits = self.lm_head(hidden_states)
|
| 1009 |
+
|
| 1010 |
+
loss = None
|
| 1011 |
+
if labels is not None:
|
| 1012 |
+
# Shift so that tokens < n predict n
|
| 1013 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 1014 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 1015 |
+
# Flatten the tokens
|
| 1016 |
+
loss_fct = CrossEntropyLoss()
|
| 1017 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
| 1018 |
+
shift_labels = shift_labels.view(-1)
|
| 1019 |
+
# Enable model parallelism
|
| 1020 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
| 1021 |
+
loss = loss_fct(shift_logits, shift_labels)
|
| 1022 |
+
|
| 1023 |
+
if not return_dict:
|
| 1024 |
+
output = (logits,) + outputs[1:]
|
| 1025 |
+
return (loss,) + output if loss is not None else output
|
| 1026 |
+
|
| 1027 |
+
return CausalLMOutputWithPast(
|
| 1028 |
+
loss=loss,
|
| 1029 |
+
logits=logits,
|
| 1030 |
+
past_key_values=outputs.past_key_values,
|
| 1031 |
+
hidden_states=outputs.hidden_states,
|
| 1032 |
+
attentions=outputs.attentions,
|
| 1033 |
+
)
|
| 1034 |
+
|
| 1035 |
+
def prepare_inputs_for_generation(
|
| 1036 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None,
|
| 1037 |
+
vision_hidden_states=None, use_zero_attention_mask=None, **kwargs
|
| 1038 |
+
):
|
| 1039 |
+
if past_key_values:
|
| 1040 |
+
input_ids = input_ids[:, -1:]
|
| 1041 |
+
|
| 1042 |
+
position_ids = kwargs.get('position_ids', None)
|
| 1043 |
+
if attention_mask is not None and position_ids is None:
|
| 1044 |
+
# create position_ids on the fly for batch generation
|
| 1045 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
| 1046 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
| 1047 |
+
if past_key_values:
|
| 1048 |
+
position_ids = position_ids[:, -1].unsqueeze(-1)
|
| 1049 |
+
|
| 1050 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
| 1051 |
+
if inputs_embeds is not None and past_key_values is None:
|
| 1052 |
+
model_inputs = {'inputs_embeds': inputs_embeds}
|
| 1053 |
+
else:
|
| 1054 |
+
model_inputs = {'input_ids': input_ids}
|
| 1055 |
+
|
| 1056 |
+
model_inputs.update(
|
| 1057 |
+
{
|
| 1058 |
+
'position_ids': position_ids,
|
| 1059 |
+
'past_key_values': past_key_values,
|
| 1060 |
+
'use_cache': kwargs.get('use_cache'),
|
| 1061 |
+
'attention_mask': attention_mask,
|
| 1062 |
+
'vision_hidden_states': vision_hidden_states,
|
| 1063 |
+
'use_zero_attention_mask': use_zero_attention_mask,
|
| 1064 |
+
}
|
| 1065 |
+
)
|
| 1066 |
+
return model_inputs
|
| 1067 |
+
|
| 1068 |
+
@staticmethod
|
| 1069 |
+
def _reorder_cache(past_key_values, beam_idx):
|
| 1070 |
+
reordered_past = ()
|
| 1071 |
+
for layer_past in past_key_values:
|
| 1072 |
+
reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
|
| 1073 |
+
return reordered_past
|
VISTA/llava/model/multimodal_projector/__pycache__/builder.cpython-310.pyc
ADDED
|
Binary file (2.87 kB). View file
|
|
|
VISTA/llava/model/multimodal_projector/builder.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class IdentityMap(nn.Module):
|
| 7 |
+
def __init__(self):
|
| 8 |
+
super().__init__()
|
| 9 |
+
|
| 10 |
+
def forward(self, x, *args, **kwargs):
|
| 11 |
+
return x
|
| 12 |
+
|
| 13 |
+
@property
|
| 14 |
+
def config(self):
|
| 15 |
+
return {"mm_projector_type": 'identity'}
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class SimpleResBlock(nn.Module):
|
| 19 |
+
def __init__(self, channels):
|
| 20 |
+
super().__init__()
|
| 21 |
+
self.pre_norm = nn.LayerNorm(channels)
|
| 22 |
+
|
| 23 |
+
self.proj = nn.Sequential(
|
| 24 |
+
nn.Linear(channels, channels),
|
| 25 |
+
nn.GELU(),
|
| 26 |
+
nn.Linear(channels, channels)
|
| 27 |
+
)
|
| 28 |
+
def forward(self, x):
|
| 29 |
+
x = self.pre_norm(x)
|
| 30 |
+
return x + self.proj(x)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class TwoMLP(nn.Module):
|
| 34 |
+
def __init__(self, config):
|
| 35 |
+
super().__init__()
|
| 36 |
+
self.vit_hidden_size = 3200
|
| 37 |
+
self.mlp1 = nn.Sequential(
|
| 38 |
+
nn.Linear(self.vit_hidden_size, config.hidden_size),
|
| 39 |
+
nn.GELU(),
|
| 40 |
+
nn.Linear(config.hidden_size, config.hidden_size),
|
| 41 |
+
)
|
| 42 |
+
self.mlp2 = nn.Sequential(
|
| 43 |
+
nn.Linear(config.mm_hidden_size, config.hidden_size),
|
| 44 |
+
nn.GELU(),
|
| 45 |
+
nn.Linear(config.hidden_size, config.hidden_size),
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
def forward(self, inputs):
|
| 49 |
+
images, queries = inputs
|
| 50 |
+
images = self.mlp1(images)
|
| 51 |
+
queries = self.mlp2(queries)
|
| 52 |
+
out = torch.cat([queries, images], dim=1)
|
| 53 |
+
assert out.size(1) == 576 + 96, f"Expected 576+96, got {out.size(1)}"
|
| 54 |
+
|
| 55 |
+
return out
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def build_vision_projector(config, delay_load=False, **kwargs):
|
| 59 |
+
projector_type = getattr(config, 'mm_projector_type', 'linear')
|
| 60 |
+
|
| 61 |
+
if projector_type == 'linear':
|
| 62 |
+
return nn.Linear(config.mm_hidden_size, config.hidden_size)
|
| 63 |
+
|
| 64 |
+
mlp_gelu_match = re.match(r'^mlp(\d+)x_gelu*', projector_type)
|
| 65 |
+
use_ln = "ln" in projector_type
|
| 66 |
+
print("use LN for projection: ", use_ln)
|
| 67 |
+
if mlp_gelu_match:
|
| 68 |
+
mlp_depth = int(mlp_gelu_match.group(1))
|
| 69 |
+
modules = []
|
| 70 |
+
if use_ln:
|
| 71 |
+
modules.append(nn.LayerNorm(config.mm_hidden_size))
|
| 72 |
+
modules.append(nn.Linear(config.mm_hidden_size, config.hidden_size))
|
| 73 |
+
for _ in range(1, mlp_depth):
|
| 74 |
+
modules.append(nn.GELU())
|
| 75 |
+
modules.append(nn.Linear(config.hidden_size, config.hidden_size))
|
| 76 |
+
return nn.Sequential(*modules)
|
| 77 |
+
|
| 78 |
+
if projector_type == 'identity':
|
| 79 |
+
return IdentityMap()
|
| 80 |
+
|
| 81 |
+
if projector_type == 'two_mlp':
|
| 82 |
+
return TwoMLP(config)
|
| 83 |
+
|
| 84 |
+
raise ValueError(f'Unknown projector type: {projector_type}')
|
VISTA/llava/serve/__init__.py
ADDED
|
File without changes
|
VISTA/llava/serve/cli.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
| 5 |
+
from llava.conversation import conv_templates, SeparatorStyle
|
| 6 |
+
from llava.model.builder import load_pretrained_model
|
| 7 |
+
from llava.utils import disable_torch_init
|
| 8 |
+
from llava.mm_utils import process_images, tokenizer_image_token, get_model_name_from_path, 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, device=args.device)
|
| 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 |
+
# Similar operation in model_worker.py
|
| 56 |
+
image_tensor = process_images([image], image_processor, args)
|
| 57 |
+
if type(image_tensor) is list:
|
| 58 |
+
image_tensor = [image.to(model.device, dtype=torch.float16) for image in image_tensor]
|
| 59 |
+
else:
|
| 60 |
+
image_tensor = image_tensor.to(model.device, dtype=torch.float16)
|
| 61 |
+
|
| 62 |
+
while True:
|
| 63 |
+
try:
|
| 64 |
+
inp = input(f"{roles[0]}: ")
|
| 65 |
+
except EOFError:
|
| 66 |
+
inp = ""
|
| 67 |
+
if not inp:
|
| 68 |
+
print("exit...")
|
| 69 |
+
break
|
| 70 |
+
|
| 71 |
+
print(f"{roles[1]}: ", end="")
|
| 72 |
+
|
| 73 |
+
if image is not None:
|
| 74 |
+
# first message
|
| 75 |
+
if model.config.mm_use_im_start_end:
|
| 76 |
+
inp = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + inp
|
| 77 |
+
else:
|
| 78 |
+
inp = DEFAULT_IMAGE_TOKEN + '\n' + inp
|
| 79 |
+
conv.append_message(conv.roles[0], inp)
|
| 80 |
+
image = None
|
| 81 |
+
else:
|
| 82 |
+
# later messages
|
| 83 |
+
conv.append_message(conv.roles[0], inp)
|
| 84 |
+
conv.append_message(conv.roles[1], None)
|
| 85 |
+
prompt = conv.get_prompt()
|
| 86 |
+
|
| 87 |
+
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()
|
| 88 |
+
stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
|
| 89 |
+
keywords = [stop_str]
|
| 90 |
+
stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
|
| 91 |
+
streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
|
| 92 |
+
|
| 93 |
+
with torch.inference_mode():
|
| 94 |
+
output_ids = model.generate(
|
| 95 |
+
input_ids,
|
| 96 |
+
images=image_tensor,
|
| 97 |
+
do_sample=True,
|
| 98 |
+
temperature=args.temperature,
|
| 99 |
+
max_new_tokens=args.max_new_tokens,
|
| 100 |
+
streamer=streamer,
|
| 101 |
+
use_cache=True,
|
| 102 |
+
stopping_criteria=[stopping_criteria])
|
| 103 |
+
|
| 104 |
+
outputs = tokenizer.decode(output_ids[0, input_ids.shape[1]:]).strip()
|
| 105 |
+
conv.messages[-1][-1] = outputs
|
| 106 |
+
|
| 107 |
+
if args.debug:
|
| 108 |
+
print("\n", {"prompt": prompt, "outputs": outputs}, "\n")
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
if __name__ == "__main__":
|
| 112 |
+
parser = argparse.ArgumentParser()
|
| 113 |
+
parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
|
| 114 |
+
parser.add_argument("--model-base", type=str, default=None)
|
| 115 |
+
parser.add_argument("--image-file", type=str, required=True)
|
| 116 |
+
parser.add_argument("--device", type=str, default="cuda")
|
| 117 |
+
parser.add_argument("--conv-mode", type=str, default=None)
|
| 118 |
+
parser.add_argument("--temperature", type=float, default=0.2)
|
| 119 |
+
parser.add_argument("--max-new-tokens", type=int, default=512)
|
| 120 |
+
parser.add_argument("--load-8bit", action="store_true")
|
| 121 |
+
parser.add_argument("--load-4bit", action="store_true")
|
| 122 |
+
parser.add_argument("--debug", action="store_true")
|
| 123 |
+
parser.add_argument("--image-aspect-ratio", type=str, default='pad')
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A controller manages distributed workers.
|
| 3 |
+
It sends worker addresses to clients.
|
| 4 |
+
"""
|
| 5 |
+
import argparse
|
| 6 |
+
import asyncio
|
| 7 |
+
import dataclasses
|
| 8 |
+
from enum import Enum, auto
|
| 9 |
+
import json
|
| 10 |
+
import logging
|
| 11 |
+
import time
|
| 12 |
+
from typing import List, Union
|
| 13 |
+
import threading
|
| 14 |
+
|
| 15 |
+
from fastapi import FastAPI, Request
|
| 16 |
+
from fastapi.responses import StreamingResponse
|
| 17 |
+
import numpy as np
|
| 18 |
+
import requests
|
| 19 |
+
import uvicorn
|
| 20 |
+
|
| 21 |
+
from llava.constants import CONTROLLER_HEART_BEAT_EXPIRATION
|
| 22 |
+
from llava.utils import build_logger, server_error_msg
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = build_logger("controller", "controller.log")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class DispatchMethod(Enum):
|
| 29 |
+
LOTTERY = auto()
|
| 30 |
+
SHORTEST_QUEUE = auto()
|
| 31 |
+
|
| 32 |
+
@classmethod
|
| 33 |
+
def from_str(cls, name):
|
| 34 |
+
if name == "lottery":
|
| 35 |
+
return cls.LOTTERY
|
| 36 |
+
elif name == "shortest_queue":
|
| 37 |
+
return cls.SHORTEST_QUEUE
|
| 38 |
+
else:
|
| 39 |
+
raise ValueError(f"Invalid dispatch method")
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@dataclasses.dataclass
|
| 43 |
+
class WorkerInfo:
|
| 44 |
+
model_names: List[str]
|
| 45 |
+
speed: int
|
| 46 |
+
queue_length: int
|
| 47 |
+
check_heart_beat: bool
|
| 48 |
+
last_heart_beat: str
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def heart_beat_controller(controller):
|
| 52 |
+
while True:
|
| 53 |
+
time.sleep(CONTROLLER_HEART_BEAT_EXPIRATION)
|
| 54 |
+
controller.remove_stable_workers_by_expiration()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class Controller:
|
| 58 |
+
def __init__(self, dispatch_method: str):
|
| 59 |
+
# Dict[str -> WorkerInfo]
|
| 60 |
+
self.worker_info = {}
|
| 61 |
+
self.dispatch_method = DispatchMethod.from_str(dispatch_method)
|
| 62 |
+
|
| 63 |
+
self.heart_beat_thread = threading.Thread(
|
| 64 |
+
target=heart_beat_controller, args=(self,))
|
| 65 |
+
self.heart_beat_thread.start()
|
| 66 |
+
|
| 67 |
+
logger.info("Init controller")
|
| 68 |
+
|
| 69 |
+
def register_worker(self, worker_name: str, check_heart_beat: bool,
|
| 70 |
+
worker_status: dict):
|
| 71 |
+
if worker_name not in self.worker_info:
|
| 72 |
+
logger.info(f"Register a new worker: {worker_name}")
|
| 73 |
+
else:
|
| 74 |
+
logger.info(f"Register an existing worker: {worker_name}")
|
| 75 |
+
|
| 76 |
+
if not worker_status:
|
| 77 |
+
worker_status = self.get_worker_status(worker_name)
|
| 78 |
+
if not worker_status:
|
| 79 |
+
return False
|
| 80 |
+
|
| 81 |
+
self.worker_info[worker_name] = WorkerInfo(
|
| 82 |
+
worker_status["model_names"], worker_status["speed"], worker_status["queue_length"],
|
| 83 |
+
check_heart_beat, time.time())
|
| 84 |
+
|
| 85 |
+
logger.info(f"Register done: {worker_name}, {worker_status}")
|
| 86 |
+
return True
|
| 87 |
+
|
| 88 |
+
def get_worker_status(self, worker_name: str):
|
| 89 |
+
try:
|
| 90 |
+
r = requests.post(worker_name + "/worker_get_status", timeout=5)
|
| 91 |
+
except requests.exceptions.RequestException as e:
|
| 92 |
+
logger.error(f"Get status fails: {worker_name}, {e}")
|
| 93 |
+
return None
|
| 94 |
+
|
| 95 |
+
if r.status_code != 200:
|
| 96 |
+
logger.error(f"Get status fails: {worker_name}, {r}")
|
| 97 |
+
return None
|
| 98 |
+
|
| 99 |
+
return r.json()
|
| 100 |
+
|
| 101 |
+
def remove_worker(self, worker_name: str):
|
| 102 |
+
del self.worker_info[worker_name]
|
| 103 |
+
|
| 104 |
+
def refresh_all_workers(self):
|
| 105 |
+
old_info = dict(self.worker_info)
|
| 106 |
+
self.worker_info = {}
|
| 107 |
+
|
| 108 |
+
for w_name, w_info in old_info.items():
|
| 109 |
+
if not self.register_worker(w_name, w_info.check_heart_beat, None):
|
| 110 |
+
logger.info(f"Remove stale worker: {w_name}")
|
| 111 |
+
|
| 112 |
+
def list_models(self):
|
| 113 |
+
model_names = set()
|
| 114 |
+
|
| 115 |
+
for w_name, w_info in self.worker_info.items():
|
| 116 |
+
model_names.update(w_info.model_names)
|
| 117 |
+
|
| 118 |
+
return list(model_names)
|
| 119 |
+
|
| 120 |
+
def get_worker_address(self, model_name: str):
|
| 121 |
+
if self.dispatch_method == DispatchMethod.LOTTERY:
|
| 122 |
+
worker_names = []
|
| 123 |
+
worker_speeds = []
|
| 124 |
+
for w_name, w_info in self.worker_info.items():
|
| 125 |
+
if model_name in w_info.model_names:
|
| 126 |
+
worker_names.append(w_name)
|
| 127 |
+
worker_speeds.append(w_info.speed)
|
| 128 |
+
worker_speeds = np.array(worker_speeds, dtype=np.float32)
|
| 129 |
+
norm = np.sum(worker_speeds)
|
| 130 |
+
if norm < 1e-4:
|
| 131 |
+
return ""
|
| 132 |
+
worker_speeds = worker_speeds / norm
|
| 133 |
+
if True: # Directly return address
|
| 134 |
+
pt = np.random.choice(np.arange(len(worker_names)),
|
| 135 |
+
p=worker_speeds)
|
| 136 |
+
worker_name = worker_names[pt]
|
| 137 |
+
return worker_name
|
| 138 |
+
|
| 139 |
+
# Check status before returning
|
| 140 |
+
while True:
|
| 141 |
+
pt = np.random.choice(np.arange(len(worker_names)),
|
| 142 |
+
p=worker_speeds)
|
| 143 |
+
worker_name = worker_names[pt]
|
| 144 |
+
|
| 145 |
+
if self.get_worker_status(worker_name):
|
| 146 |
+
break
|
| 147 |
+
else:
|
| 148 |
+
self.remove_worker(worker_name)
|
| 149 |
+
worker_speeds[pt] = 0
|
| 150 |
+
norm = np.sum(worker_speeds)
|
| 151 |
+
if norm < 1e-4:
|
| 152 |
+
return ""
|
| 153 |
+
worker_speeds = worker_speeds / norm
|
| 154 |
+
continue
|
| 155 |
+
return worker_name
|
| 156 |
+
elif self.dispatch_method == DispatchMethod.SHORTEST_QUEUE:
|
| 157 |
+
worker_names = []
|
| 158 |
+
worker_qlen = []
|
| 159 |
+
for w_name, w_info in self.worker_info.items():
|
| 160 |
+
if model_name in w_info.model_names:
|
| 161 |
+
worker_names.append(w_name)
|
| 162 |
+
worker_qlen.append(w_info.queue_length / w_info.speed)
|
| 163 |
+
if len(worker_names) == 0:
|
| 164 |
+
return ""
|
| 165 |
+
min_index = np.argmin(worker_qlen)
|
| 166 |
+
w_name = worker_names[min_index]
|
| 167 |
+
self.worker_info[w_name].queue_length += 1
|
| 168 |
+
logger.info(f"names: {worker_names}, queue_lens: {worker_qlen}, ret: {w_name}")
|
| 169 |
+
return w_name
|
| 170 |
+
else:
|
| 171 |
+
raise ValueError(f"Invalid dispatch method: {self.dispatch_method}")
|
| 172 |
+
|
| 173 |
+
def receive_heart_beat(self, worker_name: str, queue_length: int):
|
| 174 |
+
if worker_name not in self.worker_info:
|
| 175 |
+
logger.info(f"Receive unknown heart beat. {worker_name}")
|
| 176 |
+
return False
|
| 177 |
+
|
| 178 |
+
self.worker_info[worker_name].queue_length = queue_length
|
| 179 |
+
self.worker_info[worker_name].last_heart_beat = time.time()
|
| 180 |
+
logger.info(f"Receive heart beat. {worker_name}")
|
| 181 |
+
return True
|
| 182 |
+
|
| 183 |
+
def remove_stable_workers_by_expiration(self):
|
| 184 |
+
expire = time.time() - CONTROLLER_HEART_BEAT_EXPIRATION
|
| 185 |
+
to_delete = []
|
| 186 |
+
for worker_name, w_info in self.worker_info.items():
|
| 187 |
+
if w_info.check_heart_beat and w_info.last_heart_beat < expire:
|
| 188 |
+
to_delete.append(worker_name)
|
| 189 |
+
|
| 190 |
+
for worker_name in to_delete:
|
| 191 |
+
self.remove_worker(worker_name)
|
| 192 |
+
|
| 193 |
+
def worker_api_generate_stream(self, params):
|
| 194 |
+
worker_addr = self.get_worker_address(params["model"])
|
| 195 |
+
if not worker_addr:
|
| 196 |
+
logger.info(f"no worker: {params['model']}")
|
| 197 |
+
ret = {
|
| 198 |
+
"text": server_error_msg,
|
| 199 |
+
"error_code": 2,
|
| 200 |
+
}
|
| 201 |
+
yield json.dumps(ret).encode() + b"\0"
|
| 202 |
+
|
| 203 |
+
try:
|
| 204 |
+
response = requests.post(worker_addr + "/worker_generate_stream",
|
| 205 |
+
json=params, stream=True, timeout=5)
|
| 206 |
+
for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
|
| 207 |
+
if chunk:
|
| 208 |
+
yield chunk + b"\0"
|
| 209 |
+
except requests.exceptions.RequestException as e:
|
| 210 |
+
logger.info(f"worker timeout: {worker_addr}")
|
| 211 |
+
ret = {
|
| 212 |
+
"text": server_error_msg,
|
| 213 |
+
"error_code": 3,
|
| 214 |
+
}
|
| 215 |
+
yield json.dumps(ret).encode() + b"\0"
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
# Let the controller act as a worker to achieve hierarchical
|
| 219 |
+
# management. This can be used to connect isolated sub networks.
|
| 220 |
+
def worker_api_get_status(self):
|
| 221 |
+
model_names = set()
|
| 222 |
+
speed = 0
|
| 223 |
+
queue_length = 0
|
| 224 |
+
|
| 225 |
+
for w_name in self.worker_info:
|
| 226 |
+
worker_status = self.get_worker_status(w_name)
|
| 227 |
+
if worker_status is not None:
|
| 228 |
+
model_names.update(worker_status["model_names"])
|
| 229 |
+
speed += worker_status["speed"]
|
| 230 |
+
queue_length += worker_status["queue_length"]
|
| 231 |
+
|
| 232 |
+
return {
|
| 233 |
+
"model_names": list(model_names),
|
| 234 |
+
"speed": speed,
|
| 235 |
+
"queue_length": queue_length,
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
app = FastAPI()
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
@app.post("/register_worker")
|
| 243 |
+
async def register_worker(request: Request):
|
| 244 |
+
data = await request.json()
|
| 245 |
+
controller.register_worker(
|
| 246 |
+
data["worker_name"], data["check_heart_beat"],
|
| 247 |
+
data.get("worker_status", None))
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
@app.post("/refresh_all_workers")
|
| 251 |
+
async def refresh_all_workers():
|
| 252 |
+
models = controller.refresh_all_workers()
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
@app.post("/list_models")
|
| 256 |
+
async def list_models():
|
| 257 |
+
models = controller.list_models()
|
| 258 |
+
return {"models": models}
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
@app.post("/get_worker_address")
|
| 262 |
+
async def get_worker_address(request: Request):
|
| 263 |
+
data = await request.json()
|
| 264 |
+
addr = controller.get_worker_address(data["model"])
|
| 265 |
+
return {"address": addr}
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
@app.post("/receive_heart_beat")
|
| 269 |
+
async def receive_heart_beat(request: Request):
|
| 270 |
+
data = await request.json()
|
| 271 |
+
exist = controller.receive_heart_beat(
|
| 272 |
+
data["worker_name"], data["queue_length"])
|
| 273 |
+
return {"exist": exist}
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
@app.post("/worker_generate_stream")
|
| 277 |
+
async def worker_api_generate_stream(request: Request):
|
| 278 |
+
params = await request.json()
|
| 279 |
+
generator = controller.worker_api_generate_stream(params)
|
| 280 |
+
return StreamingResponse(generator)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
@app.post("/worker_get_status")
|
| 284 |
+
async def worker_api_get_status(request: Request):
|
| 285 |
+
return controller.worker_api_get_status()
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
if __name__ == "__main__":
|
| 289 |
+
parser = argparse.ArgumentParser()
|
| 290 |
+
parser.add_argument("--host", type=str, default="localhost")
|
| 291 |
+
parser.add_argument("--port", type=int, default=21001)
|
| 292 |
+
parser.add_argument("--dispatch-method", type=str, choices=[
|
| 293 |
+
"lottery", "shortest_queue"], default="shortest_queue")
|
| 294 |
+
args = parser.parse_args()
|
| 295 |
+
logger.info(f"args: {args}")
|
| 296 |
+
|
| 297 |
+
controller = Controller(args.dispatch_method)
|
| 298 |
+
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
VISTA/llava/serve/examples/extreme_ironing.jpg
ADDED
|
VISTA/llava/serve/examples/img1.jpg
ADDED
|
VIST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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
import random
|
| 10 |
+
from llava.conversation import (default_conversation, conv_templates,
|
| 11 |
+
SeparatorStyle)
|
| 12 |
+
from llava.constants import LOGDIR
|
| 13 |
+
from llava.utils import (build_logger, server_error_msg,
|
| 14 |
+
violates_moderation, moderation_msg)
|
| 15 |
+
import hashlib
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
logger = build_logger("gradio_web_server", "gradio_web_server.log")
|
| 19 |
+
|
| 20 |
+
headers = {"User-Agent": "InternVL-Chat Client"}
|
| 21 |
+
|
| 22 |
+
no_change_btn = gr.Button.update()
|
| 23 |
+
enable_btn = gr.Button.update(interactive=True)
|
| 24 |
+
disable_btn = gr.Button.update(interactive=False)
|
| 25 |
+
|
| 26 |
+
priority = {
|
| 27 |
+
"vicuna-13b": "aaaaaaa",
|
| 28 |
+
"koala-13b": "aaaaaab",
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def get_conv_log_filename():
|
| 33 |
+
t = datetime.datetime.now()
|
| 34 |
+
name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-conv.json")
|
| 35 |
+
return name
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def sort_models(models):
|
| 39 |
+
def custom_sort_key(model_name):
|
| 40 |
+
# InternVL-Chat-V1-5 should be the first item
|
| 41 |
+
if model_name == "InternVL-Chat-V1-5":
|
| 42 |
+
return (1, model_name) # 1 indicates highest precedence
|
| 43 |
+
else:
|
| 44 |
+
return (0, model_name) # 0 indicates normal order
|
| 45 |
+
|
| 46 |
+
models.sort(key=custom_sort_key, reverse=True)
|
| 47 |
+
try: # We have five InternVL-Chat-V1-5 models, randomly choose one to be the first
|
| 48 |
+
first_three = models[:6]
|
| 49 |
+
random.shuffle(first_three)
|
| 50 |
+
models[:6] = first_three
|
| 51 |
+
except:
|
| 52 |
+
pass
|
| 53 |
+
return models
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def get_model_list():
|
| 57 |
+
ret = requests.post(args.controller_url + "/refresh_all_workers")
|
| 58 |
+
assert ret.status_code == 200
|
| 59 |
+
ret = requests.post(args.controller_url + "/list_models")
|
| 60 |
+
models = ret.json()["models"]
|
| 61 |
+
models = sort_models(models)
|
| 62 |
+
|
| 63 |
+
logger.info(f"Models: {models}")
|
| 64 |
+
return models
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
get_window_url_params = """
|
| 68 |
+
function() {
|
| 69 |
+
const params = new URLSearchParams(window.location.search);
|
| 70 |
+
url_params = Object.fromEntries(params);
|
| 71 |
+
console.log(url_params);
|
| 72 |
+
return url_params;
|
| 73 |
+
}
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def load_demo(url_params, request: gr.Request):
|
| 78 |
+
logger.info(f"load_demo. ip: {request.client.host}. params: {url_params}")
|
| 79 |
+
|
| 80 |
+
dropdown_update = gr.Dropdown.update(visible=True)
|
| 81 |
+
if "model" in url_params:
|
| 82 |
+
model = url_params["model"]
|
| 83 |
+
if model in models:
|
| 84 |
+
dropdown_update = gr.Dropdown.update(
|
| 85 |
+
value=model, visible=True)
|
| 86 |
+
|
| 87 |
+
state = default_conversation.copy()
|
| 88 |
+
return state, dropdown_update
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def load_demo_refresh_model_list(request: gr.Request):
|
| 92 |
+
logger.info(f"load_demo. ip: {request.client.host}")
|
| 93 |
+
models = get_model_list()
|
| 94 |
+
state = default_conversation.copy()
|
| 95 |
+
dropdown_update = gr.Dropdown.update(
|
| 96 |
+
choices=models,
|
| 97 |
+
value=models[0] if len(models) > 0 else ""
|
| 98 |
+
)
|
| 99 |
+
return state, dropdown_update
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def vote_last_response(state, vote_type, model_selector, request: gr.Request):
|
| 103 |
+
with open(get_conv_log_filename(), "a") as fout:
|
| 104 |
+
data = {
|
| 105 |
+
"tstamp": round(time.time(), 4),
|
| 106 |
+
"type": vote_type,
|
| 107 |
+
"model": model_selector,
|
| 108 |
+
"state": state.dict(),
|
| 109 |
+
"ip": request.client.host,
|
| 110 |
+
}
|
| 111 |
+
fout.write(json.dumps(data) + "\n")
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def upvote_last_response(state, model_selector, request: gr.Request):
|
| 115 |
+
logger.info(f"upvote. ip: {request.client.host}")
|
| 116 |
+
vote_last_response(state, "upvote", model_selector, request)
|
| 117 |
+
return ("",) + (disable_btn,) * 3
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def downvote_last_response(state, model_selector, request: gr.Request):
|
| 121 |
+
logger.info(f"downvote. ip: {request.client.host}")
|
| 122 |
+
vote_last_response(state, "downvote", model_selector, request)
|
| 123 |
+
return ("",) + (disable_btn,) * 3
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def flag_last_response(state, model_selector, request: gr.Request):
|
| 127 |
+
logger.info(f"flag. ip: {request.client.host}")
|
| 128 |
+
vote_last_response(state, "flag", model_selector, request)
|
| 129 |
+
return ("",) + (disable_btn,) * 3
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def regenerate(state, image_process_mode, request: gr.Request):
|
| 133 |
+
logger.info(f"regenerate. ip: {request.client.host}")
|
| 134 |
+
state.messages[-1][-1] = None
|
| 135 |
+
prev_human_msg = state.messages[-2]
|
| 136 |
+
if type(prev_human_msg[1]) in (tuple, list):
|
| 137 |
+
prev_human_msg[1] = (*prev_human_msg[1][:2], image_process_mode)
|
| 138 |
+
state.skip_next = False
|
| 139 |
+
return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def clear_history(request: gr.Request):
|
| 143 |
+
logger.info(f"clear_history. ip: {request.client.host}")
|
| 144 |
+
state = default_conversation.copy()
|
| 145 |
+
return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def add_text(state, text, image, image_process_mode, request: gr.Request):
|
| 149 |
+
logger.info(f"add_text. ip: {request.client.host}. len: {len(text)}")
|
| 150 |
+
if len(text) <= 0 and image is None:
|
| 151 |
+
state.skip_next = True
|
| 152 |
+
return (state, state.to_gradio_chatbot(), "", None) + (no_change_btn,) * 5
|
| 153 |
+
if args.moderate:
|
| 154 |
+
flagged = violates_moderation(text)
|
| 155 |
+
if flagged:
|
| 156 |
+
state.skip_next = True
|
| 157 |
+
return (state, state.to_gradio_chatbot(), moderation_msg, None) + (
|
| 158 |
+
no_change_btn,) * 5
|
| 159 |
+
|
| 160 |
+
if image is not None:
|
| 161 |
+
if '<image>' not in text:
|
| 162 |
+
text = '<image>\n' + text
|
| 163 |
+
text = (text, image, image_process_mode)
|
| 164 |
+
if len(state.get_images(return_pil=True)) > 0:
|
| 165 |
+
state = default_conversation.copy()
|
| 166 |
+
state.append_message(state.roles[0], text)
|
| 167 |
+
state.append_message(state.roles[1], None)
|
| 168 |
+
state.skip_next = False
|
| 169 |
+
return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def http_bot(state, model_selector, temperature, top_p, max_new_tokens, max_input_tiles, request: gr.Request):
|
| 173 |
+
logger.info(f"http_bot. ip: {request.client.host}")
|
| 174 |
+
start_tstamp = time.time()
|
| 175 |
+
model_name = model_selector
|
| 176 |
+
|
| 177 |
+
if hasattr(state, 'skip_next') and state.skip_next:
|
| 178 |
+
# This generate call is skipped due to invalid inputs
|
| 179 |
+
yield (state, state.to_gradio_chatbot()) + (no_change_btn,) * 5
|
| 180 |
+
return
|
| 181 |
+
|
| 182 |
+
if len(state.messages) == state.offset + 2:
|
| 183 |
+
# First round of conversation
|
| 184 |
+
if "llava" in model_name.lower():
|
| 185 |
+
if 'llama-2' in model_name.lower():
|
| 186 |
+
template_name = "llava_llama_2"
|
| 187 |
+
elif "v1" in model_name.lower():
|
| 188 |
+
if 'mmtag' in model_name.lower():
|
| 189 |
+
template_name = "v1_mmtag"
|
| 190 |
+
elif 'plain' in model_name.lower() and 'finetune' not in model_name.lower():
|
| 191 |
+
template_name = "v1_mmtag"
|
| 192 |
+
else:
|
| 193 |
+
template_name = "llava_v1"
|
| 194 |
+
elif "mpt" in model_name.lower():
|
| 195 |
+
template_name = "mpt"
|
| 196 |
+
else:
|
| 197 |
+
if 'mmtag' in model_name.lower():
|
| 198 |
+
template_name = "v0_mmtag"
|
| 199 |
+
elif 'plain' in model_name.lower() and 'finetune' not in model_name.lower():
|
| 200 |
+
template_name = "v0_mmtag"
|
| 201 |
+
else:
|
| 202 |
+
template_name = "llava_v0"
|
| 203 |
+
elif "intern" in model_name.lower():
|
| 204 |
+
if any(x in model_name.lower() for x in ["hermes2", "v1-2", "v1_2"]):
|
| 205 |
+
template_name = "Hermes-2"
|
| 206 |
+
elif any(x in model_name.lower() for x in ["internlm2", "v1-5", "v1_5"]):
|
| 207 |
+
template_name = "internlm2-chat"
|
| 208 |
+
elif any(x in model_name.lower() for x in ["chinese", "v1-1", "v1_1"]):
|
| 209 |
+
template_name = "internvl_zh"
|
| 210 |
+
else:
|
| 211 |
+
template_name = "llava_v1"
|
| 212 |
+
elif "mpt" in model_name:
|
| 213 |
+
template_name = "mpt_text"
|
| 214 |
+
elif "llama-2" in model_name:
|
| 215 |
+
template_name = "llama_2"
|
| 216 |
+
else:
|
| 217 |
+
template_name = "vicuna_v1"
|
| 218 |
+
logger.info(f"template: {template_name}")
|
| 219 |
+
new_state = conv_templates[template_name].copy()
|
| 220 |
+
new_state.append_message(new_state.roles[0], state.messages[-2][1])
|
| 221 |
+
new_state.append_message(new_state.roles[1], None)
|
| 222 |
+
state = new_state
|
| 223 |
+
|
| 224 |
+
# Query worker address
|
| 225 |
+
controller_url = args.controller_url
|
| 226 |
+
ret = requests.post(controller_url + "/get_worker_address",
|
| 227 |
+
json={"model": model_name})
|
| 228 |
+
worker_addr = ret.json()["address"]
|
| 229 |
+
logger.info(f"model_name: {model_name}, worker_addr: {worker_addr}")
|
| 230 |
+
|
| 231 |
+
# No available worker
|
| 232 |
+
if worker_addr == "":
|
| 233 |
+
state.messages[-1][-1] = server_error_msg
|
| 234 |
+
yield (state, state.to_gradio_chatbot(), disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
|
| 235 |
+
return
|
| 236 |
+
|
| 237 |
+
# Construct prompt
|
| 238 |
+
prompt = state.get_prompt()
|
| 239 |
+
|
| 240 |
+
all_images = state.get_images(return_pil=True)
|
| 241 |
+
all_image_hash = [hashlib.md5(image.tobytes()).hexdigest() for image in all_images]
|
| 242 |
+
for image, hash in zip(all_images, all_image_hash):
|
| 243 |
+
t = datetime.datetime.now()
|
| 244 |
+
filename = os.path.join(LOGDIR, "serve_images", f"{t.year}-{t.month:02d}-{t.day:02d}", f"{hash}.jpg")
|
| 245 |
+
if not os.path.isfile(filename):
|
| 246 |
+
os.makedirs(os.path.dirname(filename), exist_ok=True)
|
| 247 |
+
image.save(filename)
|
| 248 |
+
|
| 249 |
+
# Make requests
|
| 250 |
+
pload = {
|
| 251 |
+
"model": model_name,
|
| 252 |
+
"prompt": prompt,
|
| 253 |
+
"temperature": float(temperature),
|
| 254 |
+
"top_p": float(top_p),
|
| 255 |
+
"max_new_tokens": max_new_tokens,
|
| 256 |
+
"max_input_tiles": max_input_tiles,
|
| 257 |
+
"stop": state.sep if state.sep_style in [SeparatorStyle.SINGLE, SeparatorStyle.MPT] else state.sep2,
|
| 258 |
+
"images": f'List of {len(state.get_images())} images: {all_image_hash}',
|
| 259 |
+
"org_images": f'List of {len(state.get_images(return_org=True))} images: {all_image_hash}',
|
| 260 |
+
}
|
| 261 |
+
logger.info(f"==== request ====\n{pload}")
|
| 262 |
+
|
| 263 |
+
pload['images'] = state.get_images()
|
| 264 |
+
pload['org_images'] = state.get_images(return_org=True)
|
| 265 |
+
|
| 266 |
+
state.messages[-1][-1] = "▌"
|
| 267 |
+
yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
|
| 268 |
+
|
| 269 |
+
try:
|
| 270 |
+
# Stream output
|
| 271 |
+
response = requests.post(worker_addr + "/worker_generate_stream",
|
| 272 |
+
headers=headers, json=pload, stream=True, timeout=10)
|
| 273 |
+
for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
|
| 274 |
+
if chunk:
|
| 275 |
+
data = json.loads(chunk.decode())
|
| 276 |
+
if data["error_code"] == 0:
|
| 277 |
+
output = data["text"][len(prompt):].strip()
|
| 278 |
+
state.messages[-1][-1] = output + "▌"
|
| 279 |
+
yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
|
| 280 |
+
else:
|
| 281 |
+
output = data["text"] + f" (error_code: {data['error_code']})"
|
| 282 |
+
state.messages[-1][-1] = output
|
| 283 |
+
yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
|
| 284 |
+
return
|
| 285 |
+
time.sleep(0.03)
|
| 286 |
+
except requests.exceptions.RequestException as e:
|
| 287 |
+
state.messages[-1][-1] = server_error_msg
|
| 288 |
+
yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
|
| 289 |
+
return
|
| 290 |
+
|
| 291 |
+
state.messages[-1][-1] = state.messages[-1][-1][:-1]
|
| 292 |
+
yield (state, state.to_gradio_chatbot()) + (enable_btn,) * 5
|
| 293 |
+
|
| 294 |
+
finish_tstamp = time.time()
|
| 295 |
+
logger.info(f"{output}")
|
| 296 |
+
|
| 297 |
+
with open(get_conv_log_filename(), "a") as fout:
|
| 298 |
+
data = {
|
| 299 |
+
"tstamp": round(finish_tstamp, 4),
|
| 300 |
+
"type": "chat",
|
| 301 |
+
"model": model_name,
|
| 302 |
+
"start": round(start_tstamp, 4),
|
| 303 |
+
"finish": round(start_tstamp, 4),
|
| 304 |
+
"state": state.dict(),
|
| 305 |
+
"images": all_image_hash,
|
| 306 |
+
"ip": request.client.host,
|
| 307 |
+
}
|
| 308 |
+
fout.write(json.dumps(data) + "\n")
|
| 309 |
+
|
| 310 |
+
title_markdown = ("""
|
| 311 |
+
# InternVL Family: A Pioneering Open-Source Alternative to GPT-4V [CVPR 2024 Oral]
|
| 312 |
+
💻 [[Code](https://github.com/OpenGVLab/InternVL)] | 📚 [[Paper](https://arxiv.org/abs/2312.14238)] | 🌟 [[Quick Start](https://github.com/OpenGVLab/InternVL?tab=readme-ov-file#quick-start-with-huggingface)] | 🤗 [[Hugging Face](https://huggingface.co/OpenGVLab/InternVL-Chat-V1-5)]
|
| 313 |
+
""")
|
| 314 |
+
|
| 315 |
+
tos_markdown = ("""
|
| 316 |
+
### Terms of use
|
| 317 |
+
By using this service, users are required to agree to the following terms:
|
| 318 |
+
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.
|
| 319 |
+
Please click the "Flag" button if you get any inappropriate answer! We will collect those to keep improving our moderator.
|
| 320 |
+
For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality.
|
| 321 |
+
""")
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
learn_more_markdown = ("""
|
| 325 |
+
### License
|
| 326 |
+
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.
|
| 327 |
+
|
| 328 |
+
### Acknowledgement
|
| 329 |
+
This demo is modified from LLaVA's demo. Thanks for their awesome work!
|
| 330 |
+
""")
|
| 331 |
+
|
| 332 |
+
block_css = """
|
| 333 |
+
|
| 334 |
+
#buttons button {
|
| 335 |
+
min-width: min(120px,100%);
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
"""
|
| 339 |
+
|
| 340 |
+
def build_demo(embed_mode):
|
| 341 |
+
textbox = gr.Textbox(show_label=False, placeholder="Enter text and press ENTER", container=False)
|
| 342 |
+
with gr.Blocks(title="InternVL-Chat", theme=gr.themes.Default(), css=block_css) as demo:
|
| 343 |
+
state = gr.State()
|
| 344 |
+
|
| 345 |
+
if not embed_mode:
|
| 346 |
+
gr.Markdown(title_markdown)
|
| 347 |
+
|
| 348 |
+
with gr.Row():
|
| 349 |
+
with gr.Column(scale=3):
|
| 350 |
+
with gr.Row(elem_id="model_selector_row"):
|
| 351 |
+
model_selector = gr.Dropdown(
|
| 352 |
+
choices=models,
|
| 353 |
+
value=models[0] if len(models) > 0 else "",
|
| 354 |
+
interactive=True,
|
| 355 |
+
show_label=False,
|
| 356 |
+
container=False)
|
| 357 |
+
|
| 358 |
+
imagebox = gr.Image(type="pil")
|
| 359 |
+
image_process_mode = gr.Radio(
|
| 360 |
+
["Crop", "Resize", "Pad", "Default"],
|
| 361 |
+
value="Default",
|
| 362 |
+
label="Preprocess for non-square image", visible=False)
|
| 363 |
+
|
| 364 |
+
cur_dir = os.path.dirname(os.path.abspath(__file__))
|
| 365 |
+
gr.Examples(examples=[
|
| 366 |
+
[f"{cur_dir}/examples/img1.jpg", "What does this image mean"],
|
| 367 |
+
[f"{cur_dir}/examples/img3.jpg", "Describe this image in detail"],
|
| 368 |
+
[f"{cur_dir}/examples/img5.jpg", "Please read the text in this image and return the information in the JSON format"],
|
| 369 |
+
[f"{cur_dir}/examples/img6.jpg", "How many dogs are in the figure, and why?"],
|
| 370 |
+
], inputs=[imagebox, textbox])
|
| 371 |
+
|
| 372 |
+
with gr.Accordion("Parameters", open=False) as parameter_row:
|
| 373 |
+
temperature = gr.Slider(minimum=0.0, maximum=1.0, value=0.8, step=0.1, interactive=True, label="Temperature",)
|
| 374 |
+
top_p = gr.Slider(minimum=0.0, maximum=1.0, value=0.7, step=0.1, interactive=True, label="Top P",)
|
| 375 |
+
max_output_tokens = gr.Slider(minimum=0, maximum=4096, value=1024, step=64, interactive=True, label="Max output tokens",)
|
| 376 |
+
max_input_tiles = gr.Slider(minimum=1, maximum=32, value=12, step=1, interactive=True, label="Max input tiles (control the image size)",)
|
| 377 |
+
|
| 378 |
+
with gr.Column(scale=8):
|
| 379 |
+
chatbot = gr.Chatbot(elem_id="chatbot", label="InternVL-Chat", height=550)
|
| 380 |
+
with gr.Row():
|
| 381 |
+
with gr.Column(scale=8):
|
| 382 |
+
textbox.render()
|
| 383 |
+
with gr.Column(scale=1, min_width=50):
|
| 384 |
+
submit_btn = gr.Button(value="Send", variant="primary")
|
| 385 |
+
with gr.Row(elem_id="buttons") as button_row:
|
| 386 |
+
upvote_btn = gr.Button(value="👍 Upvote", interactive=False)
|
| 387 |
+
downvote_btn = gr.Button(value="👎 Downvote", interactive=False)
|
| 388 |
+
flag_btn = gr.Button(value="⚠️ Flag", interactive=False)
|
| 389 |
+
#stop_btn = gr.Button(value="⏹️ Stop Generation", interactive=False)
|
| 390 |
+
regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=False)
|
| 391 |
+
clear_btn = gr.Button(value="🗑️ Clear", interactive=False)
|
| 392 |
+
|
| 393 |
+
if not embed_mode:
|
| 394 |
+
gr.Markdown(tos_markdown)
|
| 395 |
+
gr.Markdown(learn_more_markdown)
|
| 396 |
+
url_params = gr.JSON(visible=False)
|
| 397 |
+
|
| 398 |
+
# Register listeners
|
| 399 |
+
btn_list = [upvote_btn, downvote_btn, flag_btn, regenerate_btn, clear_btn]
|
| 400 |
+
upvote_btn.click(upvote_last_response,
|
| 401 |
+
[state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn])
|
| 402 |
+
downvote_btn.click(downvote_last_response,
|
| 403 |
+
[state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn])
|
| 404 |
+
flag_btn.click(flag_last_response,
|
| 405 |
+
[state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn])
|
| 406 |
+
regenerate_btn.click(regenerate, [state, image_process_mode],
|
| 407 |
+
[state, chatbot, textbox, imagebox] + btn_list).then(
|
| 408 |
+
http_bot, [state, model_selector, temperature, top_p, max_output_tokens, max_input_tiles],
|
| 409 |
+
[state, chatbot] + btn_list)
|
| 410 |
+
clear_btn.click(clear_history, None, [state, chatbot, textbox, imagebox] + btn_list)
|
| 411 |
+
|
| 412 |
+
textbox.submit(add_text, [state, textbox, imagebox, image_process_mode], [state, chatbot, textbox, imagebox] + btn_list
|
| 413 |
+
).then(http_bot, [state, model_selector, temperature, top_p, max_output_tokens, max_input_tiles],
|
| 414 |
+
[state, chatbot] + btn_list)
|
| 415 |
+
submit_btn.click(add_text, [state, textbox, imagebox, image_process_mode], [state, chatbot, textbox, imagebox] + btn_list
|
| 416 |
+
).then(http_bot, [state, model_selector, temperature, top_p, max_output_tokens, max_input_tiles],
|
| 417 |
+
[state, chatbot] + btn_list)
|
| 418 |
+
|
| 419 |
+
if args.model_list_mode == "once":
|
| 420 |
+
demo.load(load_demo, [url_params], [state, model_selector],
|
| 421 |
+
_js=get_window_url_params)
|
| 422 |
+
elif args.model_list_mode == "reload":
|
| 423 |
+
demo.load(load_demo_refresh_model_list, None, [state, model_selector])
|
| 424 |
+
else:
|
| 425 |
+
raise ValueError(f"Unknown model list mode: {args.model_list_mode}")
|
| 426 |
+
|
| 427 |
+
return demo
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
if __name__ == "__main__":
|
| 431 |
+
parser = argparse.ArgumentParser()
|
| 432 |
+
parser.add_argument("--host", type=str, default="0.0.0.0")
|
| 433 |
+
parser.add_argument("--port", type=int)
|
| 434 |
+
parser.add_argument("--controller-url", type=str, default="http://localhost:21001")
|
| 435 |
+
parser.add_argument("--concurrency-count", type=int, default=10)
|
| 436 |
+
parser.add_argument("--model-list-mode", type=str, default="once",
|
| 437 |
+
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(
|
| 449 |
+
concurrency_count=args.concurrency_count,
|
| 450 |
+
api_open=False
|
| 451 |
+
).launch(
|
| 452 |
+
server_name=args.host,
|
| 453 |
+
server_port=args.port,
|
| 454 |
+
share=args.share
|
| 455 |
+
)
|
VISTA/llava/serve/model_worker.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 11 |
+
from fastapi import FastAPI, Request, BackgroundTasks
|
| 12 |
+
from fastapi.responses import StreamingResponse
|
| 13 |
+
import requests
|
| 14 |
+
import torch
|
| 15 |
+
import uvicorn
|
| 16 |
+
from functools import partial
|
| 17 |
+
|
| 18 |
+
from llava.constants import WORKER_HEART_BEAT_INTERVAL
|
| 19 |
+
from llava.utils import (build_logger, server_error_msg,
|
| 20 |
+
pretty_print_semaphore)
|
| 21 |
+
from llava.model.builder import load_pretrained_model
|
| 22 |
+
from llava.mm_utils import process_images, load_image_from_base64, tokenizer_image_token, 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,
|
| 46 |
+
worker_id, no_register,
|
| 47 |
+
model_path, model_base, model_name,
|
| 48 |
+
load_8bit, load_4bit, device):
|
| 49 |
+
self.controller_addr = controller_addr
|
| 50 |
+
self.worker_addr = worker_addr
|
| 51 |
+
self.worker_id = worker_id
|
| 52 |
+
if model_path.endswith("/"):
|
| 53 |
+
model_path = model_path[:-1]
|
| 54 |
+
if model_name is None:
|
| 55 |
+
model_paths = model_path.split("/")
|
| 56 |
+
if model_paths[-1].startswith('checkpoint-'):
|
| 57 |
+
self.model_name = model_paths[-2] + "_" + model_paths[-1]
|
| 58 |
+
else:
|
| 59 |
+
self.model_name = model_paths[-1]
|
| 60 |
+
else:
|
| 61 |
+
self.model_name = model_name
|
| 62 |
+
|
| 63 |
+
self.device = device
|
| 64 |
+
logger.info(f"Loading the model {self.model_name} on worker {worker_id} ...")
|
| 65 |
+
self.tokenizer, self.model, self.image_processor, self.context_len = load_pretrained_model(
|
| 66 |
+
model_path, model_base, self.model_name, load_8bit, load_4bit, device=self.device)
|
| 67 |
+
self.is_multimodal = 'llava' in self.model_name.lower() or 'intern' in self.model_name.lower()
|
| 68 |
+
|
| 69 |
+
if not no_register:
|
| 70 |
+
self.register_to_controller()
|
| 71 |
+
self.heart_beat_thread = threading.Thread(
|
| 72 |
+
target=heart_beat_worker, args=(self,))
|
| 73 |
+
self.heart_beat_thread.start()
|
| 74 |
+
|
| 75 |
+
def register_to_controller(self):
|
| 76 |
+
logger.info("Register to controller")
|
| 77 |
+
|
| 78 |
+
url = self.controller_addr + "/register_worker"
|
| 79 |
+
data = {
|
| 80 |
+
"worker_name": self.worker_addr,
|
| 81 |
+
"check_heart_beat": True,
|
| 82 |
+
"worker_status": self.get_status()
|
| 83 |
+
}
|
| 84 |
+
r = requests.post(url, json=data)
|
| 85 |
+
assert r.status_code == 200
|
| 86 |
+
|
| 87 |
+
def send_heart_beat(self):
|
| 88 |
+
logger.info(f"Send heart beat. Models: {[self.model_name]}. "
|
| 89 |
+
f"Semaphore: {pretty_print_semaphore(model_semaphore)}. "
|
| 90 |
+
f"global_counter: {global_counter}")
|
| 91 |
+
|
| 92 |
+
url = self.controller_addr + "/receive_heart_beat"
|
| 93 |
+
|
| 94 |
+
while True:
|
| 95 |
+
try:
|
| 96 |
+
ret = requests.post(url, json={
|
| 97 |
+
"worker_name": self.worker_addr,
|
| 98 |
+
"queue_length": self.get_queue_length()}, timeout=5)
|
| 99 |
+
exist = ret.json()["exist"]
|
| 100 |
+
break
|
| 101 |
+
except requests.exceptions.RequestException as e:
|
| 102 |
+
logger.error(f"heart beat error: {e}")
|
| 103 |
+
time.sleep(5)
|
| 104 |
+
|
| 105 |
+
if not exist:
|
| 106 |
+
self.register_to_controller()
|
| 107 |
+
|
| 108 |
+
def get_queue_length(self):
|
| 109 |
+
if model_semaphore is None:
|
| 110 |
+
return 0
|
| 111 |
+
else:
|
| 112 |
+
return args.limit_model_concurrency - model_semaphore._value + (len(
|
| 113 |
+
model_semaphore._waiters) if model_semaphore._waiters is not None else 0)
|
| 114 |
+
|
| 115 |
+
def get_status(self):
|
| 116 |
+
return {
|
| 117 |
+
"model_names": [self.model_name],
|
| 118 |
+
"speed": 1,
|
| 119 |
+
"queue_length": self.get_queue_length(),
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
@torch.inference_mode()
|
| 123 |
+
def generate_stream(self, params):
|
| 124 |
+
tokenizer, model, image_processor = self.tokenizer, self.model, self.image_processor
|
| 125 |
+
|
| 126 |
+
prompt = params["prompt"]
|
| 127 |
+
ori_prompt = prompt
|
| 128 |
+
images = params.get("images", None)
|
| 129 |
+
num_image_tokens = 0
|
| 130 |
+
if images is not None and len(images) > 0 and self.is_multimodal:
|
| 131 |
+
if len(images) > 0:
|
| 132 |
+
if len(images) != prompt.count(DEFAULT_IMAGE_TOKEN):
|
| 133 |
+
raise ValueError("Number of images does not match number of <image> tokens in prompt")
|
| 134 |
+
|
| 135 |
+
images = [load_image_from_base64(image) for image in images]
|
| 136 |
+
images = process_images(images, image_processor, model.config)
|
| 137 |
+
|
| 138 |
+
if type(images) is list:
|
| 139 |
+
images = [image.to(self.model.device, dtype=torch.float16) for image in images]
|
| 140 |
+
else:
|
| 141 |
+
images = images.to(self.model.device, dtype=torch.float16)
|
| 142 |
+
|
| 143 |
+
replace_token = DEFAULT_IMAGE_TOKEN
|
| 144 |
+
if getattr(self.model.config, 'mm_use_im_start_end', False):
|
| 145 |
+
replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
|
| 146 |
+
prompt = prompt.replace(DEFAULT_IMAGE_TOKEN, replace_token)
|
| 147 |
+
|
| 148 |
+
num_image_tokens = prompt.count(replace_token) * model.get_vision_tower().num_patches
|
| 149 |
+
else:
|
| 150 |
+
images = None
|
| 151 |
+
image_args = {"images": images}
|
| 152 |
+
else:
|
| 153 |
+
images = None
|
| 154 |
+
image_args = {}
|
| 155 |
+
|
| 156 |
+
temperature = float(params.get("temperature", 1.0))
|
| 157 |
+
top_p = float(params.get("top_p", 1.0))
|
| 158 |
+
max_context_length = getattr(model.config, 'max_position_embeddings', 2048)
|
| 159 |
+
max_new_tokens = min(int(params.get("max_new_tokens", 256)), 1024)
|
| 160 |
+
stop_str = params.get("stop", None)
|
| 161 |
+
do_sample = True if temperature > 0.001 else False
|
| 162 |
+
|
| 163 |
+
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(self.device)
|
| 164 |
+
keywords = [stop_str]
|
| 165 |
+
stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
|
| 166 |
+
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=15)
|
| 167 |
+
|
| 168 |
+
max_new_tokens = min(max_new_tokens, max_context_length - input_ids.shape[-1] - num_image_tokens)
|
| 169 |
+
|
| 170 |
+
if max_new_tokens < 1:
|
| 171 |
+
yield json.dumps({"text": ori_prompt + "Exceeds max token length. Please start a new conversation, thanks.", "error_code": 0}).encode() + b"\0"
|
| 172 |
+
return
|
| 173 |
+
|
| 174 |
+
thread = Thread(target=model.generate, kwargs=dict(
|
| 175 |
+
inputs=input_ids,
|
| 176 |
+
do_sample=do_sample,
|
| 177 |
+
temperature=temperature,
|
| 178 |
+
top_p=top_p,
|
| 179 |
+
max_new_tokens=max_new_tokens,
|
| 180 |
+
streamer=streamer,
|
| 181 |
+
stopping_criteria=[stopping_criteria],
|
| 182 |
+
use_cache=True,
|
| 183 |
+
**image_args
|
| 184 |
+
))
|
| 185 |
+
thread.start()
|
| 186 |
+
|
| 187 |
+
generated_text = ori_prompt
|
| 188 |
+
for new_text in streamer:
|
| 189 |
+
generated_text += new_text
|
| 190 |
+
if generated_text.endswith(stop_str):
|
| 191 |
+
generated_text = generated_text[:-len(stop_str)]
|
| 192 |
+
yield json.dumps({"text": generated_text, "error_code": 0}).encode() + b"\0"
|
| 193 |
+
|
| 194 |
+
def generate_stream_gate(self, params):
|
| 195 |
+
try:
|
| 196 |
+
for x in self.generate_stream(params):
|
| 197 |
+
yield x
|
| 198 |
+
except ValueError as e:
|
| 199 |
+
print("Caught ValueError:", e)
|
| 200 |
+
ret = {
|
| 201 |
+
"text": server_error_msg,
|
| 202 |
+
"error_code": 1,
|
| 203 |
+
}
|
| 204 |
+
yield json.dumps(ret).encode() + b"\0"
|
| 205 |
+
except torch.cuda.CudaError as e:
|
| 206 |
+
print("Caught torch.cuda.CudaError:", e)
|
| 207 |
+
ret = {
|
| 208 |
+
"text": server_error_msg,
|
| 209 |
+
"error_code": 1,
|
| 210 |
+
}
|
| 211 |
+
yield json.dumps(ret).encode() + b"\0"
|
| 212 |
+
except Exception as e:
|
| 213 |
+
print("Caught Unknown Error", e)
|
| 214 |
+
ret = {
|
| 215 |
+
"text": server_error_msg,
|
| 216 |
+
"error_code": 1,
|
| 217 |
+
}
|
| 218 |
+
yield json.dumps(ret).encode() + b"\0"
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
app = FastAPI()
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def release_model_semaphore(fn=None):
|
| 225 |
+
model_semaphore.release()
|
| 226 |
+
if fn is not None:
|
| 227 |
+
fn()
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
@app.post("/worker_generate_stream")
|
| 231 |
+
async def generate_stream(request: Request):
|
| 232 |
+
global model_semaphore, global_counter
|
| 233 |
+
global_counter += 1
|
| 234 |
+
params = await request.json()
|
| 235 |
+
|
| 236 |
+
if model_semaphore is None:
|
| 237 |
+
model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
|
| 238 |
+
await model_semaphore.acquire()
|
| 239 |
+
worker.send_heart_beat()
|
| 240 |
+
generator = worker.generate_stream_gate(params)
|
| 241 |
+
background_tasks = BackgroundTasks()
|
| 242 |
+
background_tasks.add_task(partial(release_model_semaphore, fn=worker.send_heart_beat))
|
| 243 |
+
return StreamingResponse(generator, background=background_tasks)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
@app.post("/worker_get_status")
|
| 247 |
+
async def get_status(request: Request):
|
| 248 |
+
return worker.get_status()
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
if __name__ == "__main__":
|
| 252 |
+
parser = argparse.ArgumentParser()
|
| 253 |
+
parser.add_argument("--host", type=str, default="localhost")
|
| 254 |
+
parser.add_argument("--port", type=int, default=21002)
|
| 255 |
+
parser.add_argument("--worker-address", type=str,
|
| 256 |
+
default="http://localhost:21002")
|
| 257 |
+
parser.add_argument("--controller-address", type=str,
|
| 258 |
+
default="http://localhost:21001")
|
| 259 |
+
parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
|
| 260 |
+
parser.add_argument("--model-base", type=str, default=None)
|
| 261 |
+
parser.add_argument("--model-name", type=str)
|
| 262 |
+
parser.add_argument("--device", type=str, default="cuda")
|
| 263 |
+
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.")
|
| 264 |
+
parser.add_argument("--limit-model-concurrency", type=int, default=5)
|
| 265 |
+
parser.add_argument("--stream-interval", type=int, default=1)
|
| 266 |
+
parser.add_argument("--no-register", action="store_true")
|
| 267 |
+
parser.add_argument("--load-8bit", action="store_true")
|
| 268 |
+
parser.add_argument("--load-4bit", action="store_true")
|
| 269 |
+
args = parser.parse_args()
|
| 270 |
+
logger.info(f"args: {args}")
|
| 271 |
+
|
| 272 |
+
if args.multi_modal:
|
| 273 |
+
logger.warning("Multimodal mode is automatically detected with model name, please make sure `llava` is included in the model path.")
|
| 274 |
+
|
| 275 |
+
worker = ModelWorker(args.controller_address,
|
| 276 |
+
args.worker_address,
|
| 277 |
+
worker_id,
|
| 278 |
+
args.no_register,
|
| 279 |
+
args.model_path,
|
| 280 |
+
args.model_base,
|
| 281 |
+
args.model_name,
|
| 282 |
+
args.load_8bit,
|
| 283 |
+
args.load_4bit,
|
| 284 |
+
args.device)
|
| 285 |
+
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
VISTA/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
|
VISTA/llava/serve/test_message.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import json
|
| 3 |
+
|
| 4 |
+
import requests
|
| 5 |
+
|
| 6 |
+
from llava.conversation import default_conversation
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def main():
|
| 10 |
+
if args.worker_address:
|
| 11 |
+
worker_addr = args.worker_address
|
| 12 |
+
else:
|
| 13 |
+
controller_addr = args.controller_address
|
| 14 |
+
ret = requests.post(controller_addr + "/refresh_all_workers")
|
| 15 |
+
ret = requests.post(controller_addr + "/list_models")
|
| 16 |
+
models = ret.json()["models"]
|
| 17 |
+
models.sort()
|
| 18 |
+
print(f"Models: {models}")
|
| 19 |
+
|
| 20 |
+
ret = requests.post(controller_addr + "/get_worker_address",
|
| 21 |
+
json={"model": args.model_name})
|
| 22 |
+
worker_addr = ret.json()["address"]
|
| 23 |
+
print(f"worker_addr: {worker_addr}")
|
| 24 |
+
|
| 25 |
+
if worker_addr == "":
|
| 26 |
+
return
|
| 27 |
+
|
| 28 |
+
conv = default_conversation.copy()
|
| 29 |
+
conv.append_message(conv.roles[0], args.message)
|
| 30 |
+
prompt = conv.get_prompt()
|
| 31 |
+
|
| 32 |
+
headers = {"User-Agent": "LLaVA Client"}
|
| 33 |
+
pload = {
|
| 34 |
+
"model": args.model_name,
|
| 35 |
+
"prompt": prompt,
|
| 36 |
+
"max_new_tokens": args.max_new_tokens,
|
| 37 |
+
"temperature": 0.7,
|
| 38 |
+
"stop": conv.sep,
|
| 39 |
+
}
|
| 40 |
+
response = requests.post(worker_addr + "/worker_generate_stream", headers=headers,
|
| 41 |
+
json=pload, stream=True)
|
| 42 |
+
|
| 43 |
+
print(prompt.replace(conv.sep, "\n"), end="")
|
| 44 |
+
for chunk in response.iter_lines(chunk_size=8192, decode_unicode=False, delimiter=b"\0"):
|
| 45 |
+
if chunk:
|
| 46 |
+
data = json.loads(chunk.decode("utf-8"))
|
| 47 |
+
output = data["text"].split(conv.sep)[-1]
|
| 48 |
+
print(output, end="\r")
|
| 49 |
+
print("")
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
if __name__ == "__main__":
|
| 53 |
+
parser = argparse.ArgumentParser()
|
| 54 |
+
parser.add_argument("--controller-address", type=str, default="http://localhost:21001")
|
| 55 |
+
parser.add_argument("--worker-address", type=str)
|
| 56 |
+
parser.add_argument("--model-name", type=str, default="facebook/opt-350m")
|
| 57 |
+
parser.add_argument("--max-new-tokens", type=int, default=32)
|
| 58 |
+
parser.add_argument("--message", type=str, default=
|
| 59 |
+
"Tell me a story with more than 1000 words.")
|
| 60 |
+
args = parser.parse_args()
|
| 61 |
+
|
| 62 |
+
main()
|
VISTA/llava/train/dist_utils.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import socket
|
| 3 |
+
import subprocess
|
| 4 |
+
from datetime import timedelta
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.multiprocessing as mp
|
| 8 |
+
from torch import distributed as dist
|
| 9 |
+
|
| 10 |
+
timeout = timedelta(minutes=60)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _find_free_port():
|
| 14 |
+
# Copied from https://github.com/facebookresearch/detectron2/blob/main/detectron2/engine/launch.py # noqa: E501
|
| 15 |
+
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
| 16 |
+
# Binding to port 0 will cause the OS to find an available port for us
|
| 17 |
+
sock.bind(('', 0))
|
| 18 |
+
port = sock.getsockname()[1]
|
| 19 |
+
sock.close()
|
| 20 |
+
# NOTE: there is still a chance the port could be taken by other processes.
|
| 21 |
+
return port
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _is_free_port(port):
|
| 25 |
+
ips = socket.gethostbyname_ex(socket.gethostname())[-1]
|
| 26 |
+
ips.append('localhost')
|
| 27 |
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
| 28 |
+
return all(s.connect_ex((ip, port)) != 0 for ip in ips)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def init_dist(launcher, backend='nccl', **kwargs):
|
| 32 |
+
if mp.get_start_method(allow_none=True) is None:
|
| 33 |
+
mp.set_start_method('spawn')
|
| 34 |
+
if launcher == 'pytorch':
|
| 35 |
+
_init_dist_pytorch(backend, **kwargs)
|
| 36 |
+
elif launcher == 'mpi':
|
| 37 |
+
_init_dist_mpi(backend, **kwargs)
|
| 38 |
+
elif launcher == 'slurm':
|
| 39 |
+
_init_dist_slurm(backend, **kwargs)
|
| 40 |
+
else:
|
| 41 |
+
raise ValueError(f'Invalid launcher type: {launcher}')
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _init_dist_pytorch(backend, **kwargs):
|
| 45 |
+
# TODO: use local_rank instead of rank % num_gpus
|
| 46 |
+
rank = int(os.environ['RANK'])
|
| 47 |
+
num_gpus = torch.cuda.device_count()
|
| 48 |
+
torch.cuda.set_device(rank % num_gpus)
|
| 49 |
+
dist.init_process_group(backend=backend, **kwargs)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _init_dist_mpi(backend, **kwargs):
|
| 53 |
+
local_rank = int(os.environ['OMPI_COMM_WORLD_LOCAL_RANK'])
|
| 54 |
+
torch.cuda.set_device(local_rank)
|
| 55 |
+
if 'MASTER_PORT' not in os.environ:
|
| 56 |
+
# 29500 is torch.distributed default port
|
| 57 |
+
os.environ['MASTER_PORT'] = '29500'
|
| 58 |
+
if 'MASTER_ADDR' not in os.environ:
|
| 59 |
+
raise KeyError('The environment variable MASTER_ADDR is not set')
|
| 60 |
+
os.environ['WORLD_SIZE'] = os.environ['OMPI_COMM_WORLD_SIZE']
|
| 61 |
+
os.environ['RANK'] = os.environ['OMPI_COMM_WORLD_RANK']
|
| 62 |
+
dist.init_process_group(backend=backend, **kwargs)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _init_dist_slurm(backend, port=None):
|
| 66 |
+
"""Initialize slurm distributed training environment.
|
| 67 |
+
|
| 68 |
+
If argument ``port`` is not specified, then the master port will be system
|
| 69 |
+
environment variable ``MASTER_PORT``. If ``MASTER_PORT`` is not in system
|
| 70 |
+
environment variable, then a default port ``29500`` will be used.
|
| 71 |
+
|
| 72 |
+
Args:
|
| 73 |
+
backend (str): Backend of torch.distributed.
|
| 74 |
+
port (int, optional): Master port. Defaults to None.
|
| 75 |
+
"""
|
| 76 |
+
proc_id = int(os.environ['SLURM_PROCID'])
|
| 77 |
+
ntasks = int(os.environ['SLURM_NTASKS'])
|
| 78 |
+
node_list = os.environ['SLURM_NODELIST']
|
| 79 |
+
num_gpus = torch.cuda.device_count()
|
| 80 |
+
torch.cuda.set_device(proc_id % num_gpus)
|
| 81 |
+
addr = subprocess.getoutput(
|
| 82 |
+
f'scontrol show hostname {node_list} | head -n1')
|
| 83 |
+
# specify master port
|
| 84 |
+
if port is not None:
|
| 85 |
+
os.environ['MASTER_PORT'] = str(port)
|
| 86 |
+
elif 'MASTER_PORT' in os.environ:
|
| 87 |
+
pass # use MASTER_PORT in the environment variable
|
| 88 |
+
else:
|
| 89 |
+
# if torch.distributed default port(29500) is available
|
| 90 |
+
# then use it, else find a free port
|
| 91 |
+
if _is_free_port(29500):
|
| 92 |
+
os.environ['MASTER_PORT'] = '29500'
|
| 93 |
+
else:
|
| 94 |
+
os.environ['MASTER_PORT'] = str(_find_free_port())
|
| 95 |
+
# use MASTER_ADDR in the environment variable if it already exists
|
| 96 |
+
if 'MASTER_ADDR' not in os.environ:
|
| 97 |
+
os.environ['MASTER_ADDR'] = addr
|
| 98 |
+
os.environ['WORLD_SIZE'] = str(ntasks)
|
| 99 |
+
os.environ['LOCAL_RANK'] = str(proc_id % num_gpus)
|
| 100 |
+
os.environ['RANK'] = str(proc_id)
|
| 101 |
+
dist.init_process_group(backend=backend, timeout=timeout)
|
VISTA/llava/train/llama_flash_attn_monkey_patch.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 25 |
+
if output_attentions:
|
| 26 |
+
warnings.warn(
|
| 27 |
+
"Output attentions is not supported for patched `LlamaAttention`, returning `None` instead."
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
bsz, q_len, _ = hidden_states.size()
|
| 31 |
+
|
| 32 |
+
query_states = (
|
| 33 |
+
self.q_proj(hidden_states)
|
| 34 |
+
.view(bsz, q_len, self.num_heads, self.head_dim)
|
| 35 |
+
.transpose(1, 2)
|
| 36 |
+
)
|
| 37 |
+
key_states = (
|
| 38 |
+
self.k_proj(hidden_states)
|
| 39 |
+
.view(bsz, q_len, self.num_key_value_heads, self.head_dim)
|
| 40 |
+
.transpose(1, 2)
|
| 41 |
+
)
|
| 42 |
+
value_states = (
|
| 43 |
+
self.v_proj(hidden_states)
|
| 44 |
+
.view(bsz, q_len, self.num_key_value_heads, self.head_dim)
|
| 45 |
+
.transpose(1, 2)
|
| 46 |
+
) # shape: (b, num_heads, s, head_dim)
|
| 47 |
+
|
| 48 |
+
kv_seq_len = key_states.shape[-2]
|
| 49 |
+
if past_key_value is not None:
|
| 50 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
| 51 |
+
|
| 52 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
| 53 |
+
query_states, key_states = apply_rotary_pos_emb(
|
| 54 |
+
query_states, key_states, cos, sin, position_ids
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
if past_key_value is not None:
|
| 58 |
+
# reuse k, v
|
| 59 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
| 60 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
| 61 |
+
|
| 62 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
| 63 |
+
|
| 64 |
+
# repeat k/v heads if n_kv_heads < n_heads
|
| 65 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 66 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 67 |
+
|
| 68 |
+
# Transform the data into the format required by flash attention
|
| 69 |
+
qkv = torch.stack([query_states, key_states, value_states], dim=2)
|
| 70 |
+
qkv = qkv.transpose(1, 3) # shape: [b, s, 3, num_heads, head_dim]
|
| 71 |
+
key_padding_mask = attention_mask
|
| 72 |
+
|
| 73 |
+
if key_padding_mask is None:
|
| 74 |
+
qkv = qkv.reshape(-1, 3, self.num_heads, self.head_dim)
|
| 75 |
+
cu_q_lens = torch.arange(
|
| 76 |
+
0, (bsz + 1) * q_len, step=q_len, dtype=torch.int32, device=qkv.device
|
| 77 |
+
)
|
| 78 |
+
max_s = q_len
|
| 79 |
+
output = flash_attn_unpadded_qkvpacked_func(
|
| 80 |
+
qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True
|
| 81 |
+
)
|
| 82 |
+
output = output.view(bsz, q_len, -1)
|
| 83 |
+
else:
|
| 84 |
+
qkv = qkv.reshape(bsz, q_len, -1)
|
| 85 |
+
qkv, indices, cu_q_lens, max_s = unpad_input(qkv, key_padding_mask)
|
| 86 |
+
qkv = qkv.view(-1, 3, self.num_heads, self.head_dim)
|
| 87 |
+
output_unpad = flash_attn_unpadded_qkvpacked_func(
|
| 88 |
+
qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True
|
| 89 |
+
)
|
| 90 |
+
output_unpad = output_unpad.reshape(-1, self.num_heads * self.head_dim)
|
| 91 |
+
output = pad_input(output_unpad, indices, bsz, q_len)
|
| 92 |
+
|
| 93 |
+
return self.o_proj(output), None, past_key_value
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
# Disable the transformation of the attention mask in LlamaModel as the flash attention
|
| 97 |
+
# requires the attention mask to be the same as the key_padding_mask
|
| 98 |
+
def _prepare_decoder_attention_mask(
|
| 99 |
+
self, attention_mask, input_shape, inputs_embeds, past_key_values_length
|
| 100 |
+
):
|
| 101 |
+
# [bsz, seq_len]
|
| 102 |
+
return attention_mask
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def replace_llama_attn_with_flash_attn():
|
| 106 |
+
cuda_major, cuda_minor = torch.cuda.get_device_capability()
|
| 107 |
+
if cuda_major < 8:
|
| 108 |
+
warnings.warn(
|
| 109 |
+
"Flash attention is only supported on A100 or H100 GPU during training due to head dim > 64 backward."
|
| 110 |
+
"ref: https://github.com/HazyResearch/flash-attention/issues/190#issuecomment-1523359593"
|
| 111 |
+
)
|
| 112 |
+
transformers.models.llama.modeling_llama.LlamaModel._prepare_decoder_attention_mask = (
|
| 113 |
+
_prepare_decoder_attention_mask
|
| 114 |
+
)
|
| 115 |
+
transformers.models.llama.modeling_llama.LlamaAttention.forward = forward
|
VISTA/llava/train/llava_trainer.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from torch.utils.data import Sampler
|
| 5 |
+
|
| 6 |
+
from transformers import Trainer
|
| 7 |
+
from transformers.trainer import (
|
| 8 |
+
has_length,
|
| 9 |
+
)
|
| 10 |
+
from typing import List, Optional
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def maybe_zero_3(param, ignore_status=False, name=None):
|
| 14 |
+
from deepspeed import zero
|
| 15 |
+
from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
|
| 16 |
+
if hasattr(param, "ds_id"):
|
| 17 |
+
if param.ds_status == ZeroParamStatus.NOT_AVAILABLE:
|
| 18 |
+
if not ignore_status:
|
| 19 |
+
print(name, 'no ignore status')
|
| 20 |
+
with zero.GatheredParameters([param]):
|
| 21 |
+
param = param.data.detach().cpu().clone()
|
| 22 |
+
else:
|
| 23 |
+
param = param.detach().cpu().clone()
|
| 24 |
+
return param
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match):
|
| 28 |
+
to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)}
|
| 29 |
+
to_return = {k: maybe_zero_3(v, ignore_status=True, name=k).cpu() for k, v in to_return.items()}
|
| 30 |
+
return to_return
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def split_to_even_chunks(indices, lengths, num_chunks):
|
| 34 |
+
"""
|
| 35 |
+
Split a list of indices into `chunks` chunks of roughly equal lengths.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
if len(indices) % num_chunks != 0:
|
| 39 |
+
return [indices[i::num_chunks] for i in range(num_chunks)]
|
| 40 |
+
|
| 41 |
+
num_indices_per_chunk = len(indices) // num_chunks
|
| 42 |
+
|
| 43 |
+
chunks = [[] for _ in range(num_chunks)]
|
| 44 |
+
chunks_lengths = [0 for _ in range(num_chunks)]
|
| 45 |
+
for index in indices:
|
| 46 |
+
shortest_chunk = chunks_lengths.index(min(chunks_lengths))
|
| 47 |
+
chunks[shortest_chunk].append(index)
|
| 48 |
+
chunks_lengths[shortest_chunk] += lengths[index]
|
| 49 |
+
if len(chunks[shortest_chunk]) == num_indices_per_chunk:
|
| 50 |
+
chunks_lengths[shortest_chunk] = float("inf")
|
| 51 |
+
|
| 52 |
+
return chunks
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def get_modality_length_grouped_indices(lengths, batch_size, world_size, generator=None):
|
| 56 |
+
# We need to use torch for the random part as a distributed sampler will set the random seed for torch.
|
| 57 |
+
assert all(l != 0 for l in lengths), "Should not have zero length."
|
| 58 |
+
mm_indices, mm_lengths = zip(*[(i, l) for i, l in enumerate(lengths) if l > 0])
|
| 59 |
+
lang_indices, lang_lengths = zip(*[(i, -l) for i, l in enumerate(lengths) if l < 0])
|
| 60 |
+
|
| 61 |
+
assert len(mm_indices) > 0, "Should have at least one multimodal sample."
|
| 62 |
+
assert len(lang_indices) > 0, "Should have at least one language sample."
|
| 63 |
+
|
| 64 |
+
mm_shuffle = [mm_indices[i] for i in get_length_grouped_indices(mm_lengths, batch_size, world_size, generator=None)]
|
| 65 |
+
lang_shuffle = [lang_indices[i] for i in get_length_grouped_indices(lang_lengths, batch_size, world_size, generator=None)]
|
| 66 |
+
megabatch_size = world_size * batch_size
|
| 67 |
+
mm_megabatches = [mm_shuffle[i : i + megabatch_size] for i in range(0, len(mm_shuffle), megabatch_size)]
|
| 68 |
+
lang_megabatches = [lang_shuffle[i : i + megabatch_size] for i in range(0, len(lang_shuffle), megabatch_size)]
|
| 69 |
+
|
| 70 |
+
last_mm = mm_megabatches[-1]
|
| 71 |
+
last_lang = lang_megabatches[-1]
|
| 72 |
+
additional_batch = last_mm + last_lang
|
| 73 |
+
megabatches = mm_megabatches[:-1] + lang_megabatches[:-1]
|
| 74 |
+
megabatch_indices = torch.randperm(len(megabatches), generator=generator)
|
| 75 |
+
megabatches = [megabatches[i] for i in megabatch_indices]
|
| 76 |
+
|
| 77 |
+
if len(additional_batch) >= megabatch_size:
|
| 78 |
+
megabatches = [additional_batch[:megabatch_size]] + megabatches
|
| 79 |
+
additional_batch = additional_batch[megabatch_size:]
|
| 80 |
+
|
| 81 |
+
if len(additional_batch) > 0:
|
| 82 |
+
megabatches.append(additional_batch)
|
| 83 |
+
|
| 84 |
+
return [i for megabatch in megabatches for i in megabatch]
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def get_length_grouped_indices(lengths, batch_size, world_size, generator=None, merge=True):
|
| 88 |
+
# We need to use torch for the random part as a distributed sampler will set the random seed for torch.
|
| 89 |
+
indices = torch.randperm(len(lengths), generator=generator)
|
| 90 |
+
megabatch_size = world_size * batch_size
|
| 91 |
+
megabatches = [indices[i : i + megabatch_size].tolist() for i in range(0, len(lengths), megabatch_size)]
|
| 92 |
+
megabatches = [sorted(megabatch, key=lambda i: lengths[i], reverse=True) for megabatch in megabatches]
|
| 93 |
+
megabatches = [split_to_even_chunks(megabatch, lengths, world_size) for megabatch in megabatches]
|
| 94 |
+
|
| 95 |
+
return [i for megabatch in megabatches for batch in megabatch for i in batch]
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class LengthGroupedSampler(Sampler):
|
| 99 |
+
r"""
|
| 100 |
+
Sampler that samples indices in a way that groups together features of the dataset of roughly the same length while
|
| 101 |
+
keeping a bit of randomness.
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
def __init__(
|
| 105 |
+
self,
|
| 106 |
+
batch_size: int,
|
| 107 |
+
world_size: int,
|
| 108 |
+
lengths: Optional[List[int]] = None,
|
| 109 |
+
generator=None,
|
| 110 |
+
group_by_modality: bool = False,
|
| 111 |
+
):
|
| 112 |
+
if lengths is None:
|
| 113 |
+
raise ValueError("Lengths must be provided.")
|
| 114 |
+
|
| 115 |
+
self.batch_size = batch_size
|
| 116 |
+
self.world_size = world_size
|
| 117 |
+
self.lengths = lengths
|
| 118 |
+
self.generator = generator
|
| 119 |
+
self.group_by_modality = group_by_modality
|
| 120 |
+
|
| 121 |
+
def __len__(self):
|
| 122 |
+
return len(self.lengths)
|
| 123 |
+
|
| 124 |
+
def __iter__(self):
|
| 125 |
+
if self.group_by_modality:
|
| 126 |
+
indices = get_modality_length_grouped_indices(self.lengths, self.batch_size, self.world_size, generator=self.generator)
|
| 127 |
+
else:
|
| 128 |
+
indices = get_length_grouped_indices(self.lengths, self.batch_size, self.world_size, generator=self.generator)
|
| 129 |
+
return iter(indices)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class LLaVATrainer(Trainer):
|
| 133 |
+
|
| 134 |
+
def _get_train_sampler(self) -> Optional[torch.utils.data.Sampler]:
|
| 135 |
+
if self.train_dataset is None or not has_length(self.train_dataset):
|
| 136 |
+
return None
|
| 137 |
+
|
| 138 |
+
if self.args.group_by_modality_length:
|
| 139 |
+
lengths = self.train_dataset.modality_lengths
|
| 140 |
+
return LengthGroupedSampler(
|
| 141 |
+
# self.args.train_batch_size * self.args.gradient_accumulation_steps, # TODO: seems that we should not have gradient_accumulation_steps
|
| 142 |
+
self.args.train_batch_size,
|
| 143 |
+
world_size=self.args.world_size,
|
| 144 |
+
lengths=lengths,
|
| 145 |
+
group_by_modality=True,
|
| 146 |
+
)
|
| 147 |
+
else:
|
| 148 |
+
return super()._get_train_sampler()
|
| 149 |
+
|
| 150 |
+
def _save_checkpoint(self, model, trial, metrics=None):
|
| 151 |
+
if getattr(self.args, 'tune_mm_mlp_adapter', False):
|
| 152 |
+
from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR
|
| 153 |
+
checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}"
|
| 154 |
+
|
| 155 |
+
run_dir = self._get_output_dir(trial=trial)
|
| 156 |
+
output_dir = os.path.join(run_dir, checkpoint_folder)
|
| 157 |
+
|
| 158 |
+
# Only save Adapter
|
| 159 |
+
keys_to_match = ['mm_projector', 'vision_resampler']
|
| 160 |
+
if getattr(self.args, "use_im_start_end", False):
|
| 161 |
+
keys_to_match.extend(['embed_tokens', 'embed_in'])
|
| 162 |
+
|
| 163 |
+
# also save pos embedding
|
| 164 |
+
if getattr(self.args, "tune_vit_pos_embedding", False):
|
| 165 |
+
keys_to_match.extend(['vision_tower.embeddings.position_embedding'])
|
| 166 |
+
|
| 167 |
+
weight_to_save = get_mm_adapter_state_maybe_zero_3(self.model.named_parameters(), keys_to_match)
|
| 168 |
+
print("weight to save:", weight_to_save.keys())
|
| 169 |
+
|
| 170 |
+
if self.args.local_rank == 0 or self.args.local_rank == -1:
|
| 171 |
+
self.model.config.save_pretrained(output_dir)
|
| 172 |
+
torch.save(weight_to_save, os.path.join(output_dir, f'mm_projector.bin'))
|
| 173 |
+
else:
|
| 174 |
+
super(LLaVATrainer, self)._save_checkpoint(model, trial, metrics)
|
| 175 |
+
|
| 176 |
+
def _save(self, output_dir: Optional[str] = None, state_dict=None):
|
| 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
| 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 |
+
from dataclasses import dataclass, field
|
| 20 |
+
import json
|
| 21 |
+
import logging
|
| 22 |
+
import pathlib
|
| 23 |
+
from typing import Dict, Optional, Sequence, List
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import random
|
| 27 |
+
|
| 28 |
+
import transformers
|
| 29 |
+
|
| 30 |
+
from llava.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
| 31 |
+
from torch.utils.data import Dataset
|
| 32 |
+
from llava.train.llava_trainer import LLaVATrainer
|
| 33 |
+
|
| 34 |
+
from llava import conversation as conversation_lib
|
| 35 |
+
from llava.model import *
|
| 36 |
+
from llava.mm_utils import tokenizer_image_token
|
| 37 |
+
|
| 38 |
+
from PIL import Image
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
local_rank = None
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def rank0_print(*args):
|
| 45 |
+
if local_rank == 0:
|
| 46 |
+
print(*args)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@dataclass
|
| 50 |
+
class ModelArguments:
|
| 51 |
+
model_name_or_path: Optional[str] = field(default="facebook/opt-125m")
|
| 52 |
+
version: Optional[str] = field(default="v0")
|
| 53 |
+
freeze_backbone: bool = field(default=False)
|
| 54 |
+
tune_mm_mlp_adapter: bool = field(default=False)
|
| 55 |
+
tune_vit_pos_embedding: bool = field(default=False)
|
| 56 |
+
vision_tower: Optional[str] = field(default=None)
|
| 57 |
+
mm_vision_select_layer: Optional[int] = field(default=-1) # default to the last layer
|
| 58 |
+
pretrain_mm_mlp_adapter: Optional[str] = field(default=None)
|
| 59 |
+
mm_projector_type: Optional[str] = field(default='linear')
|
| 60 |
+
mm_use_im_start_end: bool = field(default=False)
|
| 61 |
+
mm_use_im_patch_token: bool = field(default=True)
|
| 62 |
+
mm_vision_select_feature: Optional[str] = field(default="patch")
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@dataclass
|
| 66 |
+
class DataArguments:
|
| 67 |
+
data_path: str = field(default=None,
|
| 68 |
+
metadata={"help": "Path to the training data."})
|
| 69 |
+
lazy_preprocess: bool = False
|
| 70 |
+
is_multimodal: bool = False
|
| 71 |
+
image_folder: Optional[str] = field(default=None)
|
| 72 |
+
image_aspect_ratio: str = 'square'
|
| 73 |
+
image_grid_pinpoints: Optional[str] = field(default=None)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@dataclass
|
| 77 |
+
class TrainingArguments(transformers.TrainingArguments):
|
| 78 |
+
cache_dir: Optional[str] = field(default=None)
|
| 79 |
+
optim: str = field(default="adamw_torch")
|
| 80 |
+
remove_unused_columns: bool = field(default=False)
|
| 81 |
+
freeze_mm_mlp_adapter: bool = field(default=False)
|
| 82 |
+
freeze_llm: bool = field(default=False)
|
| 83 |
+
mpt_attn_impl: Optional[str] = field(default="triton")
|
| 84 |
+
model_max_length: int = field(
|
| 85 |
+
default=512,
|
| 86 |
+
metadata={
|
| 87 |
+
"help":
|
| 88 |
+
"Maximum sequence length. Sequences will be right padded (and possibly truncated)."
|
| 89 |
+
},
|
| 90 |
+
)
|
| 91 |
+
double_quant: bool = field(
|
| 92 |
+
default=True,
|
| 93 |
+
metadata={"help": "Compress the quantization statistics through double quantization."}
|
| 94 |
+
)
|
| 95 |
+
quant_type: str = field(
|
| 96 |
+
default="nf4",
|
| 97 |
+
metadata={"help": "Quantization data type to use. Should be one of `fp4` or `nf4`."}
|
| 98 |
+
)
|
| 99 |
+
bits: int = field(
|
| 100 |
+
default=16,
|
| 101 |
+
metadata={"help": "How many bits to use."}
|
| 102 |
+
)
|
| 103 |
+
lora_enable: bool = False
|
| 104 |
+
lora_r: int = 64
|
| 105 |
+
lora_alpha: int = 16
|
| 106 |
+
lora_dropout: float = 0.05
|
| 107 |
+
lora_weight_path: str = ""
|
| 108 |
+
lora_bias: str = "none"
|
| 109 |
+
group_by_modality_length: bool = field(default=False)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def maybe_zero_3(param, ignore_status=False, name=None):
|
| 113 |
+
from deepspeed import zero
|
| 114 |
+
from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
|
| 115 |
+
if hasattr(param, "ds_id"):
|
| 116 |
+
if param.ds_status == ZeroParamStatus.NOT_AVAILABLE:
|
| 117 |
+
if not ignore_status:
|
| 118 |
+
logging.warning(f"{name}: param.ds_status != ZeroParamStatus.NOT_AVAILABLE: {param.ds_status}")
|
| 119 |
+
with zero.GatheredParameters([param]):
|
| 120 |
+
param = param.data.detach().cpu().clone()
|
| 121 |
+
else:
|
| 122 |
+
param = param.detach().cpu().clone()
|
| 123 |
+
return param
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
# Borrowed from peft.utils.get_peft_model_state_dict
|
| 127 |
+
def get_peft_state_maybe_zero_3(named_params, bias):
|
| 128 |
+
if bias == "none":
|
| 129 |
+
to_return = {k: t for k, t in named_params if "lora_" in k}
|
| 130 |
+
elif bias == "all":
|
| 131 |
+
to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k}
|
| 132 |
+
elif bias == "lora_only":
|
| 133 |
+
to_return = {}
|
| 134 |
+
maybe_lora_bias = {}
|
| 135 |
+
lora_bias_names = set()
|
| 136 |
+
for k, t in named_params:
|
| 137 |
+
if "lora_" in k:
|
| 138 |
+
to_return[k] = t
|
| 139 |
+
bias_name = k.split("lora_")[0] + "bias"
|
| 140 |
+
lora_bias_names.add(bias_name)
|
| 141 |
+
elif "bias" in k:
|
| 142 |
+
maybe_lora_bias[k] = t
|
| 143 |
+
for k, t in maybe_lora_bias:
|
| 144 |
+
if bias_name in lora_bias_names:
|
| 145 |
+
to_return[bias_name] = t
|
| 146 |
+
else:
|
| 147 |
+
raise NotImplementedError
|
| 148 |
+
to_return = {k: maybe_zero_3(v, ignore_status=True) for k, v in to_return.items()}
|
| 149 |
+
return to_return
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True):
|
| 153 |
+
to_return = {k: t for k, t in named_params if "lora_" not in k}
|
| 154 |
+
if require_grad_only:
|
| 155 |
+
to_return = {k: t for k, t in to_return.items() if t.requires_grad}
|
| 156 |
+
to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()}
|
| 157 |
+
return to_return
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match):
|
| 161 |
+
to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)}
|
| 162 |
+
to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()}
|
| 163 |
+
return to_return
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def find_all_linear_names(model):
|
| 167 |
+
cls = torch.nn.Linear
|
| 168 |
+
lora_module_names = set()
|
| 169 |
+
for name, module in model.named_modules():
|
| 170 |
+
if isinstance(module, cls):
|
| 171 |
+
names = name.split('.')
|
| 172 |
+
lora_module_names.add(names[0] if len(names) == 1 else names[-1])
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
if 'lm_head' in lora_module_names: # needed for 16-bit
|
| 176 |
+
lora_module_names.remove('lm_head')
|
| 177 |
+
return list(lora_module_names)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def safe_save_model_for_hf_trainer(trainer: transformers.Trainer,
|
| 181 |
+
output_dir: str):
|
| 182 |
+
"""Collects the state dict and dump to disk."""
|
| 183 |
+
|
| 184 |
+
if getattr(trainer.args, "tune_mm_mlp_adapter", False):
|
| 185 |
+
# Only save Adapter
|
| 186 |
+
keys_to_match = ['mm_projector']
|
| 187 |
+
if getattr(trainer.args, "use_im_start_end", False):
|
| 188 |
+
keys_to_match.extend(['embed_tokens', 'embed_in'])
|
| 189 |
+
|
| 190 |
+
# also save pos embedding
|
| 191 |
+
if getattr(trainer.args, "tune_vit_pos_embedding", False):
|
| 192 |
+
keys_to_match.extend(['vision_tower.embeddings.position_embedding'])
|
| 193 |
+
|
| 194 |
+
weight_to_save = get_mm_adapter_state_maybe_zero_3(trainer.model.named_parameters(), keys_to_match)
|
| 195 |
+
print("weight to save:", weight_to_save.keys())
|
| 196 |
+
trainer.model.config.save_pretrained(output_dir)
|
| 197 |
+
|
| 198 |
+
current_folder = output_dir.split('/')[-1]
|
| 199 |
+
parent_folder = os.path.dirname(output_dir)
|
| 200 |
+
if trainer.args.local_rank == 0 or trainer.args.local_rank == -1:
|
| 201 |
+
if current_folder.startswith('checkpoint-'):
|
| 202 |
+
mm_projector_folder = os.path.join(parent_folder, "mm_projector")
|
| 203 |
+
os.makedirs(mm_projector_folder, exist_ok=True)
|
| 204 |
+
torch.save(weight_to_save, os.path.join(mm_projector_folder, f'{current_folder}.bin'))
|
| 205 |
+
else:
|
| 206 |
+
torch.save(weight_to_save, os.path.join(output_dir, f'mm_projector.bin'))
|
| 207 |
+
return
|
| 208 |
+
|
| 209 |
+
if trainer.deepspeed:
|
| 210 |
+
torch.cuda.synchronize()
|
| 211 |
+
trainer.save_model(output_dir)
|
| 212 |
+
return
|
| 213 |
+
|
| 214 |
+
state_dict = trainer.model.state_dict()
|
| 215 |
+
if trainer.args.should_save:
|
| 216 |
+
cpu_state_dict = {
|
| 217 |
+
key: value.cpu()
|
| 218 |
+
for key, value in state_dict.items()
|
| 219 |
+
}
|
| 220 |
+
del state_dict
|
| 221 |
+
trainer._save(output_dir, state_dict=cpu_state_dict) # noqa
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def smart_tokenizer_and_embedding_resize(
|
| 225 |
+
special_tokens_dict: Dict,
|
| 226 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
| 227 |
+
model: transformers.PreTrainedModel,
|
| 228 |
+
):
|
| 229 |
+
"""Resize tokenizer and embedding.
|
| 230 |
+
|
| 231 |
+
Note: This is the unoptimized version that may make your embedding size not be divisible by 64.
|
| 232 |
+
"""
|
| 233 |
+
num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict)
|
| 234 |
+
model.resize_token_embeddings(len(tokenizer))
|
| 235 |
+
|
| 236 |
+
if num_new_tokens > 0:
|
| 237 |
+
input_embeddings = model.get_input_embeddings().weight.data
|
| 238 |
+
output_embeddings = model.get_output_embeddings().weight.data
|
| 239 |
+
|
| 240 |
+
input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(
|
| 241 |
+
dim=0, keepdim=True)
|
| 242 |
+
output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(
|
| 243 |
+
dim=0, keepdim=True)
|
| 244 |
+
|
| 245 |
+
input_embeddings[-num_new_tokens:] = input_embeddings_avg
|
| 246 |
+
output_embeddings[-num_new_tokens:] = output_embeddings_avg
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def _tokenize_fn(strings: Sequence[str],
|
| 250 |
+
tokenizer: transformers.PreTrainedTokenizer) -> Dict:
|
| 251 |
+
"""Tokenize a list of strings."""
|
| 252 |
+
tokenized_list = [
|
| 253 |
+
tokenizer(
|
| 254 |
+
text,
|
| 255 |
+
return_tensors="pt",
|
| 256 |
+
padding="longest",
|
| 257 |
+
max_length=tokenizer.model_max_length,
|
| 258 |
+
truncation=True,
|
| 259 |
+
) for text in strings
|
| 260 |
+
]
|
| 261 |
+
input_ids = labels = [
|
| 262 |
+
tokenized.input_ids[0] for tokenized in tokenized_list
|
| 263 |
+
]
|
| 264 |
+
input_ids_lens = labels_lens = [
|
| 265 |
+
tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item()
|
| 266 |
+
for tokenized in tokenized_list
|
| 267 |
+
]
|
| 268 |
+
return dict(
|
| 269 |
+
input_ids=input_ids,
|
| 270 |
+
labels=labels,
|
| 271 |
+
input_ids_lens=input_ids_lens,
|
| 272 |
+
labels_lens=labels_lens,
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def _mask_targets(target, tokenized_lens, speakers):
|
| 277 |
+
# cur_idx = 0
|
| 278 |
+
cur_idx = tokenized_lens[0]
|
| 279 |
+
tokenized_lens = tokenized_lens[1:]
|
| 280 |
+
target[:cur_idx] = IGNORE_INDEX
|
| 281 |
+
for tokenized_len, speaker in zip(tokenized_lens, speakers):
|
| 282 |
+
if speaker == "human":
|
| 283 |
+
target[cur_idx+2:cur_idx + tokenized_len] = IGNORE_INDEX
|
| 284 |
+
cur_idx += tokenized_len
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def _add_speaker_and_signal(header, source, get_conversation=True):
|
| 288 |
+
"""Add speaker and start/end signal on each round."""
|
| 289 |
+
BEGIN_SIGNAL = "### "
|
| 290 |
+
END_SIGNAL = "\n"
|
| 291 |
+
conversation = header
|
| 292 |
+
for sentence in source:
|
| 293 |
+
from_str = sentence["from"]
|
| 294 |
+
if from_str.lower() == "human":
|
| 295 |
+
from_str = conversation_lib.default_conversation.roles[0]
|
| 296 |
+
elif from_str.lower() == "gpt":
|
| 297 |
+
from_str = conversation_lib.default_conversation.roles[1]
|
| 298 |
+
else:
|
| 299 |
+
from_str = 'unknown'
|
| 300 |
+
sentence["value"] = (BEGIN_SIGNAL + from_str + ": " +
|
| 301 |
+
sentence["value"] + END_SIGNAL)
|
| 302 |
+
if get_conversation:
|
| 303 |
+
conversation += sentence["value"]
|
| 304 |
+
conversation += BEGIN_SIGNAL
|
| 305 |
+
return conversation
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def preprocess_multimodal(
|
| 309 |
+
sources: Sequence[str],
|
| 310 |
+
data_args: DataArguments
|
| 311 |
+
) -> Dict:
|
| 312 |
+
is_multimodal = data_args.is_multimodal
|
| 313 |
+
if not is_multimodal:
|
| 314 |
+
return sources
|
| 315 |
+
|
| 316 |
+
for source in sources:
|
| 317 |
+
for sentence in source:
|
| 318 |
+
if DEFAULT_IMAGE_TOKEN in sentence['value']:
|
| 319 |
+
sentence['value'] = sentence['value'].replace(DEFAULT_IMAGE_TOKEN, '').strip()
|
| 320 |
+
sentence['value'] = DEFAULT_IMAGE_TOKEN + '\n' + sentence['value']
|
| 321 |
+
sentence['value'] = sentence['value'].strip()
|
| 322 |
+
if "mmtag" in conversation_lib.default_conversation.version:
|
| 323 |
+
sentence['value'] = sentence['value'].replace(DEFAULT_IMAGE_TOKEN, '<Image>' + DEFAULT_IMAGE_TOKEN + '</Image>')
|
| 324 |
+
replace_token = DEFAULT_IMAGE_TOKEN
|
| 325 |
+
if data_args.mm_use_im_start_end:
|
| 326 |
+
replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
|
| 327 |
+
sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token)
|
| 328 |
+
|
| 329 |
+
return sources
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def preprocess_llama_2(
|
| 333 |
+
sources,
|
| 334 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
| 335 |
+
has_image: bool = False
|
| 336 |
+
) -> Dict:
|
| 337 |
+
conv = conversation_lib.default_conversation.copy()
|
| 338 |
+
roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
|
| 339 |
+
|
| 340 |
+
# Apply prompt templates
|
| 341 |
+
conversations = []
|
| 342 |
+
for i, source in enumerate(sources):
|
| 343 |
+
if roles[source[0]["from"]] != conv.roles[0]:
|
| 344 |
+
# Skip the first one if it is not from human
|
| 345 |
+
source = source[1:]
|
| 346 |
+
|
| 347 |
+
conv.messages = []
|
| 348 |
+
for j, sentence in enumerate(source):
|
| 349 |
+
role = roles[sentence["from"]]
|
| 350 |
+
assert role == conv.roles[j % 2], f"{i}"
|
| 351 |
+
conv.append_message(role, sentence["value"])
|
| 352 |
+
conversations.append(conv.get_prompt())
|
| 353 |
+
|
| 354 |
+
# Tokenize conversations
|
| 355 |
+
|
| 356 |
+
if has_image:
|
| 357 |
+
input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0)
|
| 358 |
+
else:
|
| 359 |
+
input_ids = tokenizer(
|
| 360 |
+
conversations,
|
| 361 |
+
return_tensors="pt",
|
| 362 |
+
padding="longest",
|
| 363 |
+
max_length=tokenizer.model_max_length,
|
| 364 |
+
truncation=True,
|
| 365 |
+
).input_ids
|
| 366 |
+
|
| 367 |
+
targets = input_ids.clone()
|
| 368 |
+
|
| 369 |
+
assert conv.sep_style == conversation_lib.SeparatorStyle.LLAMA_2
|
| 370 |
+
|
| 371 |
+
# Mask targets
|
| 372 |
+
sep = "[/INST] "
|
| 373 |
+
for conversation, target in zip(conversations, targets):
|
| 374 |
+
total_len = int(target.ne(tokenizer.pad_token_id).sum())
|
| 375 |
+
|
| 376 |
+
rounds = conversation.split(conv.sep2)
|
| 377 |
+
cur_len = 1
|
| 378 |
+
target[:cur_len] = IGNORE_INDEX
|
| 379 |
+
for i, rou in enumerate(rounds):
|
| 380 |
+
if rou == "":
|
| 381 |
+
break
|
| 382 |
+
|
| 383 |
+
parts = rou.split(sep)
|
| 384 |
+
if len(parts) != 2:
|
| 385 |
+
break
|
| 386 |
+
parts[0] += sep
|
| 387 |
+
|
| 388 |
+
if has_image:
|
| 389 |
+
round_len = len(tokenizer_image_token(rou, tokenizer))
|
| 390 |
+
instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2
|
| 391 |
+
else:
|
| 392 |
+
round_len = len(tokenizer(rou).input_ids)
|
| 393 |
+
instruction_len = len(tokenizer(parts[0]).input_ids) - 2
|
| 394 |
+
|
| 395 |
+
target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
|
| 396 |
+
|
| 397 |
+
cur_len += round_len
|
| 398 |
+
target[cur_len:] = IGNORE_INDEX
|
| 399 |
+
|
| 400 |
+
if cur_len < tokenizer.model_max_length:
|
| 401 |
+
if cur_len != total_len:
|
| 402 |
+
target[:] = IGNORE_INDEX
|
| 403 |
+
print(
|
| 404 |
+
f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}."
|
| 405 |
+
f" (ignored)"
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
return dict(
|
| 409 |
+
input_ids=input_ids,
|
| 410 |
+
labels=targets,
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
def preprocess_v1(
|
| 415 |
+
sources,
|
| 416 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
| 417 |
+
has_image: bool = False
|
| 418 |
+
) -> Dict:
|
| 419 |
+
conv = conversation_lib.default_conversation.copy()
|
| 420 |
+
roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
|
| 421 |
+
|
| 422 |
+
# Apply prompt templates
|
| 423 |
+
conversations = []
|
| 424 |
+
for i, source in enumerate(sources):
|
| 425 |
+
if roles[source[0]["from"]] != conv.roles[0]:
|
| 426 |
+
# Skip the first one if it is not from human
|
| 427 |
+
source = source[1:]
|
| 428 |
+
|
| 429 |
+
conv.messages = []
|
| 430 |
+
for j, sentence in enumerate(source):
|
| 431 |
+
role = roles[sentence["from"]]
|
| 432 |
+
assert role == conv.roles[j % 2], f"{i}"
|
| 433 |
+
conv.append_message(role, sentence["value"])
|
| 434 |
+
conversations.append(conv.get_prompt())
|
| 435 |
+
|
| 436 |
+
# Tokenize conversations
|
| 437 |
+
|
| 438 |
+
if has_image:
|
| 439 |
+
input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0)
|
| 440 |
+
else:
|
| 441 |
+
input_ids = tokenizer(
|
| 442 |
+
conversations,
|
| 443 |
+
return_tensors="pt",
|
| 444 |
+
padding="longest",
|
| 445 |
+
max_length=tokenizer.model_max_length,
|
| 446 |
+
truncation=True,
|
| 447 |
+
).input_ids
|
| 448 |
+
|
| 449 |
+
targets = input_ids.clone()
|
| 450 |
+
|
| 451 |
+
assert conv.sep_style == conversation_lib.SeparatorStyle.TWO
|
| 452 |
+
|
| 453 |
+
# Mask targets
|
| 454 |
+
sep = conv.sep + conv.roles[1] + ": "
|
| 455 |
+
for conversation, target in zip(conversations, targets):
|
| 456 |
+
total_len = int(target.ne(tokenizer.pad_token_id).sum())
|
| 457 |
+
|
| 458 |
+
rounds = conversation.split(conv.sep2)
|
| 459 |
+
cur_len = 1
|
| 460 |
+
target[:cur_len] = IGNORE_INDEX
|
| 461 |
+
for i, rou in enumerate(rounds):
|
| 462 |
+
if rou == "":
|
| 463 |
+
break
|
| 464 |
+
|
| 465 |
+
parts = rou.split(sep)
|
| 466 |
+
if len(parts) != 2:
|
| 467 |
+
break
|
| 468 |
+
parts[0] += sep
|
| 469 |
+
|
| 470 |
+
if has_image:
|
| 471 |
+
round_len = len(tokenizer_image_token(rou, tokenizer))
|
| 472 |
+
instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2
|
| 473 |
+
else:
|
| 474 |
+
round_len = len(tokenizer(rou).input_ids)
|
| 475 |
+
instruction_len = len(tokenizer(parts[0]).input_ids) - 2
|
| 476 |
+
|
| 477 |
+
if i != 0 and not tokenizer.legacy: # compatible with transformers==4.32.0
|
| 478 |
+
# The legacy and non-legacy modes handle special tokens differently
|
| 479 |
+
instruction_len -= 1
|
| 480 |
+
|
| 481 |
+
# Ignore the user instructions
|
| 482 |
+
target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
|
| 483 |
+
cur_len += round_len
|
| 484 |
+
|
| 485 |
+
if i != 0 and not tokenizer.legacy: # compatible with transformers==4.32.0
|
| 486 |
+
# The legacy and non-legacy modes handle special tokens differently
|
| 487 |
+
cur_len -= 1
|
| 488 |
+
|
| 489 |
+
target[cur_len:] = IGNORE_INDEX
|
| 490 |
+
|
| 491 |
+
if cur_len < tokenizer.model_max_length:
|
| 492 |
+
if cur_len != total_len:
|
| 493 |
+
target[:] = IGNORE_INDEX
|
| 494 |
+
print(
|
| 495 |
+
f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}."
|
| 496 |
+
f" (ignored)"
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
return dict(
|
| 500 |
+
input_ids=input_ids,
|
| 501 |
+
labels=targets,
|
| 502 |
+
)
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
def preprocess_mpt(
|
| 506 |
+
sources,
|
| 507 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
| 508 |
+
) -> Dict:
|
| 509 |
+
conv = conversation_lib.default_conversation.copy()
|
| 510 |
+
roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
|
| 511 |
+
|
| 512 |
+
# Apply prompt templates
|
| 513 |
+
conversations = []
|
| 514 |
+
for i, source in enumerate(sources):
|
| 515 |
+
if roles[source[0]["from"]] != conv.roles[0]:
|
| 516 |
+
# Skip the first one if it is not from human
|
| 517 |
+
source = source[1:]
|
| 518 |
+
|
| 519 |
+
conv.messages = []
|
| 520 |
+
for j, sentence in enumerate(source):
|
| 521 |
+
role = roles[sentence["from"]]
|
| 522 |
+
assert role == conv.roles[j % 2], f"{i}"
|
| 523 |
+
conv.append_message(role, sentence["value"])
|
| 524 |
+
conversations.append(conv.get_prompt())
|
| 525 |
+
|
| 526 |
+
# Tokenize conversations
|
| 527 |
+
input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0)
|
| 528 |
+
targets = input_ids.clone()
|
| 529 |
+
assert conv.sep_style == conversation_lib.SeparatorStyle.MPT
|
| 530 |
+
|
| 531 |
+
# Mask targets
|
| 532 |
+
sep = conv.sep + conv.roles[1]
|
| 533 |
+
for conversation, target in zip(conversations, targets):
|
| 534 |
+
total_len = int(target.ne(tokenizer.pad_token_id).sum())
|
| 535 |
+
|
| 536 |
+
rounds = conversation.split(conv.sep)
|
| 537 |
+
re_rounds = [conv.sep.join(rounds[:3])] # system + user + gpt
|
| 538 |
+
for conv_idx in range(3, len(rounds), 2):
|
| 539 |
+
re_rounds.append(conv.sep.join(rounds[conv_idx:conv_idx+2])) # user + gpt
|
| 540 |
+
cur_len = 0
|
| 541 |
+
target[:cur_len] = IGNORE_INDEX
|
| 542 |
+
for i, rou in enumerate(re_rounds):
|
| 543 |
+
if rou == "":
|
| 544 |
+
break
|
| 545 |
+
|
| 546 |
+
parts = rou.split(sep)
|
| 547 |
+
if len(parts) != 2:
|
| 548 |
+
break
|
| 549 |
+
parts[0] += sep
|
| 550 |
+
round_len = len(tokenizer_image_token(rou, tokenizer)) + len(tokenizer_image_token(conv.sep, tokenizer))
|
| 551 |
+
instruction_len = len(tokenizer_image_token(parts[0], tokenizer))
|
| 552 |
+
target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
|
| 553 |
+
|
| 554 |
+
cur_len += round_len
|
| 555 |
+
target[cur_len:] = IGNORE_INDEX
|
| 556 |
+
|
| 557 |
+
if cur_len < tokenizer.model_max_length:
|
| 558 |
+
if cur_len != total_len:
|
| 559 |
+
target[:] = IGNORE_INDEX
|
| 560 |
+
print(
|
| 561 |
+
f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}."
|
| 562 |
+
f" (ignored)"
|
| 563 |
+
)
|
| 564 |
+
|
| 565 |
+
return dict(
|
| 566 |
+
input_ids=input_ids,
|
| 567 |
+
labels=targets,
|
| 568 |
+
)
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
def preprocess_plain(
|
| 572 |
+
sources: Sequence[str],
|
| 573 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
| 574 |
+
) -> Dict:
|
| 575 |
+
# add end signal and concatenate together
|
| 576 |
+
conversations = []
|
| 577 |
+
for source in sources:
|
| 578 |
+
assert len(source) == 2
|
| 579 |
+
assert DEFAULT_IMAGE_TOKEN in source[0]['value']
|
| 580 |
+
source[0]['value'] = DEFAULT_IMAGE_TOKEN
|
| 581 |
+
conversation = source[0]['value'] + source[1]['value'] + conversation_lib.default_conversation.sep
|
| 582 |
+
conversations.append(conversation)
|
| 583 |
+
# tokenize conversations
|
| 584 |
+
input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations]
|
| 585 |
+
targets = copy.deepcopy(input_ids)
|
| 586 |
+
for target, source in zip(targets, sources):
|
| 587 |
+
tokenized_len = len(tokenizer_image_token(source[0]['value'], tokenizer))
|
| 588 |
+
target[:tokenized_len] = IGNORE_INDEX
|
| 589 |
+
|
| 590 |
+
return dict(input_ids=input_ids, labels=targets)
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
def preprocess(
|
| 594 |
+
sources: Sequence[str],
|
| 595 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
| 596 |
+
has_image: bool = False
|
| 597 |
+
) -> Dict:
|
| 598 |
+
"""
|
| 599 |
+
Given a list of sources, each is a conversation list. This transform:
|
| 600 |
+
1. Add signal '### ' at the beginning each sentence, with end signal '\n';
|
| 601 |
+
2. Concatenate conversations together;
|
| 602 |
+
3. Tokenize the concatenated conversation;
|
| 603 |
+
4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX.
|
| 604 |
+
"""
|
| 605 |
+
if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.PLAIN:
|
| 606 |
+
return preprocess_plain(sources, tokenizer)
|
| 607 |
+
if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.LLAMA_2:
|
| 608 |
+
return preprocess_llama_2(sources, tokenizer, has_image=has_image)
|
| 609 |
+
if conversation_lib.default_conversation.version.startswith("v1"):
|
| 610 |
+
return preprocess_v1(sources, tokenizer, has_image=has_image)
|
| 611 |
+
if conversation_lib.default_conversation.version == "mpt":
|
| 612 |
+
return preprocess_mpt(sources, tokenizer)
|
| 613 |
+
# add end signal and concatenate together
|
| 614 |
+
conversations = []
|
| 615 |
+
for source in sources:
|
| 616 |
+
header = f"{conversation_lib.default_conversation.system}\n\n"
|
| 617 |
+
conversation = _add_speaker_and_signal(header, source)
|
| 618 |
+
conversations.append(conversation)
|
| 619 |
+
# tokenize conversations
|
| 620 |
+
def get_tokenize_len(prompts):
|
| 621 |
+
return [len(tokenizer_image_token(prompt, tokenizer)) for prompt in prompts]
|
| 622 |
+
|
| 623 |
+
if has_image:
|
| 624 |
+
input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations]
|
| 625 |
+
else:
|
| 626 |
+
conversations_tokenized = _tokenize_fn(conversations, tokenizer)
|
| 627 |
+
input_ids = conversations_tokenized["input_ids"]
|
| 628 |
+
|
| 629 |
+
targets = copy.deepcopy(input_ids)
|
| 630 |
+
for target, source in zip(targets, sources):
|
| 631 |
+
if has_image:
|
| 632 |
+
tokenized_lens = get_tokenize_len([header] + [s["value"] for s in source])
|
| 633 |
+
else:
|
| 634 |
+
tokenized_lens = _tokenize_fn([header] + [s["value"] for s in source], tokenizer)["input_ids_lens"]
|
| 635 |
+
speakers = [sentence["from"] for sentence in source]
|
| 636 |
+
_mask_targets(target, tokenized_lens, speakers)
|
| 637 |
+
|
| 638 |
+
return dict(input_ids=input_ids, labels=targets)
|
| 639 |
+
|
| 640 |
+
|
| 641 |
+
class LazySupervisedDataset(Dataset):
|
| 642 |
+
"""Dataset for supervised fine-tuning."""
|
| 643 |
+
|
| 644 |
+
def __init__(self, data_path: str,
|
| 645 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
| 646 |
+
data_args: DataArguments):
|
| 647 |
+
super(LazySupervisedDataset, self).__init__()
|
| 648 |
+
list_data_dict = json.load(open(data_path, "r"))
|
| 649 |
+
|
| 650 |
+
rank0_print("Formatting inputs...Skip in lazy mode")
|
| 651 |
+
self.tokenizer = tokenizer
|
| 652 |
+
self.list_data_dict = list_data_dict
|
| 653 |
+
self.data_args = data_args
|
| 654 |
+
|
| 655 |
+
def __len__(self):
|
| 656 |
+
return len(self.list_data_dict)
|
| 657 |
+
|
| 658 |
+
@property
|
| 659 |
+
def lengths(self):
|
| 660 |
+
length_list = []
|
| 661 |
+
for sample in self.list_data_dict:
|
| 662 |
+
img_tokens = 128 if 'image' in sample else 0
|
| 663 |
+
length_list.append(sum(len(conv['value'].split()) for conv in sample['conversations']) + img_tokens)
|
| 664 |
+
return length_list
|
| 665 |
+
|
| 666 |
+
@property
|
| 667 |
+
def modality_lengths(self):
|
| 668 |
+
length_list = []
|
| 669 |
+
for sample in self.list_data_dict:
|
| 670 |
+
cur_len = sum(len(conv['value'].split()) for conv in sample['conversations'])
|
| 671 |
+
cur_len = cur_len if 'image' in sample else -cur_len
|
| 672 |
+
length_list.append(cur_len)
|
| 673 |
+
return length_list
|
| 674 |
+
|
| 675 |
+
def __getitem__(self, i) -> Dict[str, torch.Tensor]:
|
| 676 |
+
flag = False
|
| 677 |
+
while not flag:
|
| 678 |
+
try:
|
| 679 |
+
sources = self.list_data_dict[i]
|
| 680 |
+
if isinstance(i, int):
|
| 681 |
+
sources = [sources]
|
| 682 |
+
assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME
|
| 683 |
+
if 'image' in sources[0]:
|
| 684 |
+
image_file = self.list_data_dict[i]['image']
|
| 685 |
+
image_folder = self.data_args.image_folder
|
| 686 |
+
processor = self.data_args.image_processor
|
| 687 |
+
image = Image.open(os.path.join(image_folder, image_file)).convert('RGB')
|
| 688 |
+
if self.data_args.image_aspect_ratio == 'pad':
|
| 689 |
+
def expand2square(pil_img, background_color):
|
| 690 |
+
width, height = pil_img.size
|
| 691 |
+
if width == height:
|
| 692 |
+
return pil_img
|
| 693 |
+
elif width > height:
|
| 694 |
+
result = Image.new(pil_img.mode, (width, width), background_color)
|
| 695 |
+
result.paste(pil_img, (0, (width - height) // 2))
|
| 696 |
+
return result
|
| 697 |
+
else:
|
| 698 |
+
result = Image.new(pil_img.mode, (height, height), background_color)
|
| 699 |
+
result.paste(pil_img, ((height - width) // 2, 0))
|
| 700 |
+
return result
|
| 701 |
+
image = expand2square(image, tuple(int(x*255) for x in processor.image_mean))
|
| 702 |
+
image = processor.preprocess(image, return_tensors='pt')['pixel_values'][0]
|
| 703 |
+
else:
|
| 704 |
+
image = processor.preprocess(image, return_tensors='pt')['pixel_values'][0]
|
| 705 |
+
sources = preprocess_multimodal(
|
| 706 |
+
copy.deepcopy([e["conversations"] for e in sources]),
|
| 707 |
+
self.data_args)
|
| 708 |
+
else:
|
| 709 |
+
sources = copy.deepcopy([e["conversations"] for e in sources])
|
| 710 |
+
data_dict = preprocess(
|
| 711 |
+
sources,
|
| 712 |
+
self.tokenizer,
|
| 713 |
+
has_image=('image' in self.list_data_dict[i]))
|
| 714 |
+
if isinstance(i, int):
|
| 715 |
+
data_dict = dict(input_ids=data_dict["input_ids"][0],
|
| 716 |
+
labels=data_dict["labels"][0])
|
| 717 |
+
|
| 718 |
+
# image exist in the data
|
| 719 |
+
if 'image' in self.list_data_dict[i]:
|
| 720 |
+
data_dict['image'] = image
|
| 721 |
+
elif self.data_args.is_multimodal:
|
| 722 |
+
# image does not exist in the data, but the model is multimodal
|
| 723 |
+
crop_size = self.data_args.image_processor.crop_size
|
| 724 |
+
data_dict['image'] = torch.zeros(3, crop_size['height'], crop_size['width'])
|
| 725 |
+
flag = True
|
| 726 |
+
except Exception as e:
|
| 727 |
+
print(e)
|
| 728 |
+
i = random.randint(0, len(self.list_data_dict) - 1)
|
| 729 |
+
return data_dict
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
@dataclass
|
| 733 |
+
class DataCollatorForSupervisedDataset(object):
|
| 734 |
+
"""Collate examples for supervised fine-tuning."""
|
| 735 |
+
|
| 736 |
+
tokenizer: transformers.PreTrainedTokenizer
|
| 737 |
+
|
| 738 |
+
def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]:
|
| 739 |
+
input_ids, labels = tuple([instance[key] for instance in instances]
|
| 740 |
+
for key in ("input_ids", "labels"))
|
| 741 |
+
input_ids = torch.nn.utils.rnn.pad_sequence(
|
| 742 |
+
input_ids,
|
| 743 |
+
batch_first=True,
|
| 744 |
+
padding_value=self.tokenizer.pad_token_id)
|
| 745 |
+
labels = torch.nn.utils.rnn.pad_sequence(labels,
|
| 746 |
+
batch_first=True,
|
| 747 |
+
padding_value=IGNORE_INDEX)
|
| 748 |
+
input_ids = input_ids[:, :self.tokenizer.model_max_length]
|
| 749 |
+
labels = labels[:, :self.tokenizer.model_max_length]
|
| 750 |
+
batch = dict(
|
| 751 |
+
input_ids=input_ids,
|
| 752 |
+
labels=labels,
|
| 753 |
+
attention_mask=input_ids.ne(self.tokenizer.pad_token_id),
|
| 754 |
+
)
|
| 755 |
+
|
| 756 |
+
if 'image' in instances[0]:
|
| 757 |
+
images = [instance['image'] for instance in instances]
|
| 758 |
+
if all(x is not None and x.shape == images[0].shape for x in images):
|
| 759 |
+
batch['images'] = torch.stack(images)
|
| 760 |
+
else:
|
| 761 |
+
batch['images'] = images
|
| 762 |
+
|
| 763 |
+
return batch
|
| 764 |
+
|
| 765 |
+
|
| 766 |
+
def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer,
|
| 767 |
+
data_args) -> Dict:
|
| 768 |
+
"""Make dataset and collator for supervised fine-tuning."""
|
| 769 |
+
train_dataset = LazySupervisedDataset(tokenizer=tokenizer,
|
| 770 |
+
data_path=data_args.data_path,
|
| 771 |
+
data_args=data_args)
|
| 772 |
+
data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer)
|
| 773 |
+
return dict(train_dataset=train_dataset,
|
| 774 |
+
eval_dataset=None,
|
| 775 |
+
data_collator=data_collator)
|
| 776 |
+
|
| 777 |
+
|
| 778 |
+
def train(attn_implementation=None):
|
| 779 |
+
global local_rank
|
| 780 |
+
|
| 781 |
+
parser = transformers.HfArgumentParser(
|
| 782 |
+
(ModelArguments, DataArguments, TrainingArguments))
|
| 783 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
| 784 |
+
local_rank = training_args.local_rank
|
| 785 |
+
training_args._frozen = False # compatible with transformers==4.32.0
|
| 786 |
+
data_args._frozen = False # compatible with transformers==4.32.0
|
| 787 |
+
model_args._frozen = False # compatible with transformers==4.32.0
|
| 788 |
+
compute_dtype = (torch.float16 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32))
|
| 789 |
+
|
| 790 |
+
bnb_model_from_pretrained_args = {}
|
| 791 |
+
if training_args.bits in [4, 8]:
|
| 792 |
+
from transformers import BitsAndBytesConfig
|
| 793 |
+
bnb_model_from_pretrained_args.update(dict(
|
| 794 |
+
device_map={"": training_args.device},
|
| 795 |
+
load_in_4bit=training_args.bits == 4,
|
| 796 |
+
load_in_8bit=training_args.bits == 8,
|
| 797 |
+
quantization_config=BitsAndBytesConfig(
|
| 798 |
+
load_in_4bit=training_args.bits == 4,
|
| 799 |
+
load_in_8bit=training_args.bits == 8,
|
| 800 |
+
llm_int8_threshold=6.0,
|
| 801 |
+
llm_int8_has_fp16_weight=False,
|
| 802 |
+
bnb_4bit_compute_dtype=compute_dtype,
|
| 803 |
+
bnb_4bit_use_double_quant=training_args.double_quant,
|
| 804 |
+
bnb_4bit_quant_type=training_args.quant_type # {'fp4', 'nf4'}
|
| 805 |
+
)
|
| 806 |
+
))
|
| 807 |
+
|
| 808 |
+
if model_args.vision_tower is not None:
|
| 809 |
+
if 'mpt' in model_args.model_name_or_path:
|
| 810 |
+
config = transformers.AutoConfig.from_pretrained(model_args.model_name_or_path, trust_remote_code=True)
|
| 811 |
+
config.attn_config['attn_impl'] = training_args.mpt_attn_impl
|
| 812 |
+
model = LlavaMptForCausalLM.from_pretrained(
|
| 813 |
+
model_args.model_name_or_path,
|
| 814 |
+
config=config,
|
| 815 |
+
cache_dir=training_args.cache_dir,
|
| 816 |
+
**bnb_model_from_pretrained_args
|
| 817 |
+
)
|
| 818 |
+
else:
|
| 819 |
+
model = LlavaLlamaForCausalLM.from_pretrained(
|
| 820 |
+
model_args.model_name_or_path,
|
| 821 |
+
cache_dir=training_args.cache_dir,
|
| 822 |
+
attn_implementation=attn_implementation,
|
| 823 |
+
torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
|
| 824 |
+
**bnb_model_from_pretrained_args
|
| 825 |
+
)
|
| 826 |
+
else:
|
| 827 |
+
model = transformers.LlamaForCausalLM.from_pretrained(
|
| 828 |
+
model_args.model_name_or_path,
|
| 829 |
+
cache_dir=training_args.cache_dir,
|
| 830 |
+
attn_implementation=attn_implementation,
|
| 831 |
+
torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
|
| 832 |
+
**bnb_model_from_pretrained_args
|
| 833 |
+
)
|
| 834 |
+
model.config.use_cache = False
|
| 835 |
+
|
| 836 |
+
if model_args.freeze_backbone:
|
| 837 |
+
model.model.requires_grad_(False)
|
| 838 |
+
|
| 839 |
+
if training_args.bits in [4, 8]:
|
| 840 |
+
from peft import prepare_model_for_kbit_training
|
| 841 |
+
model.config.torch_dtype=(torch.float32 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32))
|
| 842 |
+
model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=training_args.gradient_checkpointing)
|
| 843 |
+
|
| 844 |
+
if training_args.gradient_checkpointing:
|
| 845 |
+
if hasattr(model, "enable_input_require_grads"):
|
| 846 |
+
model.enable_input_require_grads()
|
| 847 |
+
else:
|
| 848 |
+
def make_inputs_require_grad(module, input, output):
|
| 849 |
+
output.requires_grad_(True)
|
| 850 |
+
model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
|
| 851 |
+
|
| 852 |
+
if training_args.lora_enable:
|
| 853 |
+
from peft import LoraConfig, get_peft_model
|
| 854 |
+
lora_config = LoraConfig(
|
| 855 |
+
r=training_args.lora_r,
|
| 856 |
+
lora_alpha=training_args.lora_alpha,
|
| 857 |
+
target_modules=find_all_linear_names(model),
|
| 858 |
+
lora_dropout=training_args.lora_dropout,
|
| 859 |
+
bias=training_args.lora_bias,
|
| 860 |
+
task_type="CAUSAL_LM",
|
| 861 |
+
)
|
| 862 |
+
if training_args.bits == 16:
|
| 863 |
+
if training_args.bf16:
|
| 864 |
+
model.to(torch.bfloat16)
|
| 865 |
+
if training_args.fp16:
|
| 866 |
+
model.to(torch.float16)
|
| 867 |
+
rank0_print("Adding LoRA adapters...")
|
| 868 |
+
model = get_peft_model(model, lora_config)
|
| 869 |
+
|
| 870 |
+
if 'mpt' in model_args.model_name_or_path:
|
| 871 |
+
tokenizer = transformers.AutoTokenizer.from_pretrained(
|
| 872 |
+
model_args.model_name_or_path,
|
| 873 |
+
cache_dir=training_args.cache_dir,
|
| 874 |
+
model_max_length=training_args.model_max_length,
|
| 875 |
+
padding_side="right"
|
| 876 |
+
)
|
| 877 |
+
else:
|
| 878 |
+
tokenizer = transformers.AutoTokenizer.from_pretrained(
|
| 879 |
+
model_args.model_name_or_path,
|
| 880 |
+
cache_dir=training_args.cache_dir,
|
| 881 |
+
model_max_length=training_args.model_max_length,
|
| 882 |
+
padding_side="right",
|
| 883 |
+
use_fast=False,
|
| 884 |
+
)
|
| 885 |
+
|
| 886 |
+
if model_args.version == "v0":
|
| 887 |
+
if tokenizer.pad_token is None:
|
| 888 |
+
smart_tokenizer_and_embedding_resize(
|
| 889 |
+
special_tokens_dict=dict(pad_token="[PAD]"),
|
| 890 |
+
tokenizer=tokenizer,
|
| 891 |
+
model=model,
|
| 892 |
+
)
|
| 893 |
+
elif model_args.version == "v0.5":
|
| 894 |
+
tokenizer.pad_token = tokenizer.unk_token
|
| 895 |
+
else:
|
| 896 |
+
tokenizer.pad_token = tokenizer.unk_token
|
| 897 |
+
if model_args.version in conversation_lib.conv_templates:
|
| 898 |
+
conversation_lib.default_conversation = conversation_lib.conv_templates[model_args.version]
|
| 899 |
+
else:
|
| 900 |
+
conversation_lib.default_conversation = conversation_lib.conv_templates["vicuna_v1"]
|
| 901 |
+
|
| 902 |
+
if model_args.vision_tower is not None:
|
| 903 |
+
model.get_model().initialize_vision_modules(
|
| 904 |
+
model_args=model_args,
|
| 905 |
+
fsdp=training_args.fsdp
|
| 906 |
+
)
|
| 907 |
+
|
| 908 |
+
vision_tower = model.get_vision_tower()
|
| 909 |
+
vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device)
|
| 910 |
+
|
| 911 |
+
data_args.image_processor = vision_tower.image_processor
|
| 912 |
+
data_args.is_multimodal = True
|
| 913 |
+
|
| 914 |
+
model.config.image_aspect_ratio = data_args.image_aspect_ratio
|
| 915 |
+
model.config.image_grid_pinpoints = data_args.image_grid_pinpoints
|
| 916 |
+
|
| 917 |
+
model.config.tune_mm_mlp_adapter = training_args.tune_mm_mlp_adapter = model_args.tune_mm_mlp_adapter
|
| 918 |
+
# freeze llm: only tune mlp layer
|
| 919 |
+
if model_args.tune_mm_mlp_adapter or training_args.freeze_llm:
|
| 920 |
+
print("Only tune mlp adapter.")
|
| 921 |
+
model.requires_grad_(False)
|
| 922 |
+
for p in model.get_model().mm_projector.parameters():
|
| 923 |
+
p.requires_grad = True
|
| 924 |
+
|
| 925 |
+
model.config.freeze_mm_mlp_adapter = training_args.freeze_mm_mlp_adapter
|
| 926 |
+
if training_args.freeze_mm_mlp_adapter:
|
| 927 |
+
for p in model.get_model().mm_projector.parameters():
|
| 928 |
+
p.requires_grad = False
|
| 929 |
+
|
| 930 |
+
# tune vit position embedding
|
| 931 |
+
model.config.tune_vit_pos_embedding = training_args.tune_vit_pos_embedding = model_args.tune_vit_pos_embedding
|
| 932 |
+
if model_args.tune_vit_pos_embedding:
|
| 933 |
+
print("Tuning ViT position embedding.")
|
| 934 |
+
for name, p in model.get_model().vision_tower.named_parameters():
|
| 935 |
+
if "position_embedding" in name:
|
| 936 |
+
p.requires_grad = True
|
| 937 |
+
print("\tvit pos embedding name: ", name)
|
| 938 |
+
|
| 939 |
+
|
| 940 |
+
if training_args.bits in [4, 8]:
|
| 941 |
+
model.get_model().mm_projector.to(dtype=compute_dtype, device=training_args.device)
|
| 942 |
+
|
| 943 |
+
model.config.mm_use_im_start_end = data_args.mm_use_im_start_end = model_args.mm_use_im_start_end
|
| 944 |
+
training_args.use_im_start_end = model_args.mm_use_im_start_end
|
| 945 |
+
model.config.mm_use_im_patch_token = model_args.mm_use_im_patch_token
|
| 946 |
+
model.initialize_vision_tokenizer(model_args, tokenizer=tokenizer)
|
| 947 |
+
|
| 948 |
+
if training_args.bits in [4, 8]:
|
| 949 |
+
from peft.tuners.lora import LoraLayer
|
| 950 |
+
for name, module in model.named_modules():
|
| 951 |
+
if isinstance(module, LoraLayer):
|
| 952 |
+
if training_args.bf16:
|
| 953 |
+
module = module.to(torch.bfloat16)
|
| 954 |
+
if 'norm' in name:
|
| 955 |
+
module = module.to(torch.float32)
|
| 956 |
+
if 'lm_head' in name or 'embed_tokens' in name:
|
| 957 |
+
if hasattr(module, 'weight'):
|
| 958 |
+
if training_args.bf16 and module.weight.dtype == torch.float32:
|
| 959 |
+
module = module.to(torch.bfloat16)
|
| 960 |
+
|
| 961 |
+
data_module = make_supervised_data_module(tokenizer=tokenizer,
|
| 962 |
+
data_args=data_args)
|
| 963 |
+
trainer = LLaVATrainer(model=model,
|
| 964 |
+
tokenizer=tokenizer,
|
| 965 |
+
args=training_args,
|
| 966 |
+
**data_module)
|
| 967 |
+
|
| 968 |
+
if list(pathlib.Path(training_args.output_dir).glob("checkpoint-*")):
|
| 969 |
+
trainer.train(resume_from_checkpoint=True)
|
| 970 |
+
else:
|
| 971 |
+
trainer.train()
|
| 972 |
+
trainer.save_state()
|
| 973 |
+
|
| 974 |
+
model.config.use_cache = True
|
| 975 |
+
|
| 976 |
+
if training_args.lora_enable:
|
| 977 |
+
state_dict = get_peft_state_maybe_zero_3(
|
| 978 |
+
model.named_parameters(), training_args.lora_bias
|
| 979 |
+
)
|
| 980 |
+
non_lora_state_dict = get_peft_state_non_lora_maybe_zero_3(
|
| 981 |
+
model.named_parameters()
|
| 982 |
+
)
|
| 983 |
+
if training_args.local_rank == 0 or training_args.local_rank == -1:
|
| 984 |
+
model.config.save_pretrained(training_args.output_dir)
|
| 985 |
+
model.save_pretrained(training_args.output_dir, state_dict=state_dict)
|
| 986 |
+
torch.save(non_lora_state_dict, os.path.join(training_args.output_dir, 'non_lora_trainables.bin'))
|
| 987 |
+
else:
|
| 988 |
+
safe_save_model_for_hf_trainer(trainer=trainer,
|
| 989 |
+
output_dir=training_args.output_dir)
|
| 990 |
+
|
| 991 |
+
|
| 992 |
+
if __name__ == "__main__":
|
| 993 |
+
train()
|