Spaces:
Running
Running
vk
commited on
Commit
·
43917f9
1
Parent(s):
5b777f6
first commit
Browse files- .gitattributes +1 -0
- .gitignore +2 -0
- app.py +193 -0
- download.py +5 -0
- paligemma_tokenizer.model +3 -0
- requirements.txt +9 -0
.gitattributes
CHANGED
|
@@ -7,6 +7,7 @@
|
|
| 7 |
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
*.joblib filter=lfs diff=lfs merge=lfs -text
|
|
|
|
| 10 |
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
*.model filter=lfs diff=lfs merge=lfs -text
|
|
|
|
| 7 |
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.jpg filter=lfs diff=lfs merge=lfs -text
|
| 11 |
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 12 |
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 13 |
*.model filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
saved_model
|
| 2 |
+
big_vision_repo
|
app.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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depth=1 \
|
| 7 |
+
https://github.com/google-research/big_vision big_vision_repo")
|
| 8 |
+
import sys
|
| 9 |
+
|
| 10 |
+
if "big_vision_repo" not in sys.path:
|
| 11 |
+
sys.path.append("big_vision_repo")
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
import functools
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
import jax
|
| 18 |
+
import numpy as np
|
| 19 |
+
import ml_collections
|
| 20 |
+
|
| 21 |
+
import tensorflow as tf
|
| 22 |
+
import sentencepiece
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# Import model definition from big_vision
|
| 27 |
+
from big_vision.models.proj.paligemma import paligemma
|
| 28 |
+
from big_vision.trainers.proj.paligemma import predict_fns
|
| 29 |
+
|
| 30 |
+
# Import big vision utilities
|
| 31 |
+
import big_vision.datasets.jsonl
|
| 32 |
+
import big_vision.utils
|
| 33 |
+
import big_vision.sharding
|
| 34 |
+
from glob import glob
|
| 35 |
+
import cv2
|
| 36 |
+
from time import time
|
| 37 |
+
import gradio as gr
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def preprocess_image(image, size=224):
|
| 42 |
+
# Model has been trained to handle images of different aspects ratios
|
| 43 |
+
# resized to 224x224 in the range [-1, 1]. Bilinear and antialias resize
|
| 44 |
+
# options are helpful to improve quality in some tasks.
|
| 45 |
+
image = np.asarray(image)
|
| 46 |
+
if image.ndim == 2: # Convert image without last channel into greyscale.
|
| 47 |
+
image = np.stack((image,)*3, axis=-1)
|
| 48 |
+
image = image[..., :3] # Remove alpha layer.
|
| 49 |
+
assert image.shape[-1] == 3
|
| 50 |
+
|
| 51 |
+
image = tf.constant(image)
|
| 52 |
+
image = tf.image.resize(image, (size, size), method='bilinear', antialias=True)
|
| 53 |
+
return image.numpy() / 127.5 - 1.0 # [0, 255]->[-1,1]
|
| 54 |
+
|
| 55 |
+
def preprocess_tokens(prefix, suffix=None, seqlen=None):
|
| 56 |
+
# Model has been trained to handle tokenized text composed of a prefix with
|
| 57 |
+
# full attention and a suffix with causal attention.
|
| 58 |
+
separator = "\n"
|
| 59 |
+
tokens = tokenizer.encode(prefix, add_bos=True) + tokenizer.encode(separator)
|
| 60 |
+
mask_ar = [0] * len(tokens) # 0 to use full attention for prefix.
|
| 61 |
+
mask_loss = [0] * len(tokens) # 0 to not use prefix tokens in the loss.
|
| 62 |
+
|
| 63 |
+
if suffix:
|
| 64 |
+
suffix = tokenizer.encode(suffix, add_eos=True)
|
| 65 |
+
tokens += suffix
|
| 66 |
+
mask_ar += [1] * len(suffix) # 1 to use causal attention for suffix.
|
| 67 |
+
mask_loss += [1] * len(suffix) # 1 to use suffix tokens in the loss.
|
| 68 |
+
|
| 69 |
+
mask_input = [1] * len(tokens) # 1 if it's a token, 0 if padding.
|
| 70 |
+
if seqlen:
|
| 71 |
+
padding = [0] * max(0, seqlen - len(tokens))
|
| 72 |
+
tokens = tokens[:seqlen] + padding
|
| 73 |
+
mask_ar = mask_ar[:seqlen] + padding
|
| 74 |
+
mask_loss = mask_loss[:seqlen] + padding
|
| 75 |
+
mask_input = mask_input[:seqlen] + padding
|
| 76 |
+
|
| 77 |
+
return jax.tree.map(np.array, (tokens, mask_ar, mask_loss, mask_input))
|
| 78 |
+
|
| 79 |
+
def postprocess_tokens(tokens):
|
| 80 |
+
tokens = tokens.tolist() # np.array to list[int]
|
| 81 |
+
try: # Remove tokens at and after EOS if any.
|
| 82 |
+
eos_pos = tokens.index(tokenizer.eos_id())
|
| 83 |
+
tokens = tokens[:eos_pos]
|
| 84 |
+
except ValueError:
|
| 85 |
+
pass
|
| 86 |
+
return tokenizer.decode(tokens)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def get_response(image,prefix):
|
| 95 |
+
if len(prefix)<1:
|
| 96 |
+
prefix="caption en"
|
| 97 |
+
print('caption:',prefix)
|
| 98 |
+
image = preprocess_image(image)
|
| 99 |
+
examples = []
|
| 100 |
+
tokens, mask_ar, _, mask_input = preprocess_tokens(prefix, seqlen=SEQLEN)
|
| 101 |
+
|
| 102 |
+
examples.append({
|
| 103 |
+
"image": np.asarray(image),
|
| 104 |
+
"text": np.asarray(tokens),
|
| 105 |
+
"mask_ar": np.asarray(mask_ar),
|
| 106 |
+
"mask_input": np.asarray(mask_input),
|
| 107 |
+
})
|
| 108 |
+
examples[-1]["_mask"] = np.array(True)
|
| 109 |
+
|
| 110 |
+
batch = jax.tree.map(lambda *x: np.stack(x), *examples)
|
| 111 |
+
batch = big_vision.utils.reshard(batch, data_sharding)
|
| 112 |
+
|
| 113 |
+
# print('gonna predict')
|
| 114 |
+
start = time()
|
| 115 |
+
|
| 116 |
+
# Make model predictions
|
| 117 |
+
tokens = decode({"params": params}, batch=batch,
|
| 118 |
+
max_decode_len=SEQLEN, sampler="greedy")
|
| 119 |
+
|
| 120 |
+
# print('predict done')
|
| 121 |
+
|
| 122 |
+
# Fetch model predictions to device and detokenize.
|
| 123 |
+
tokens, mask = jax.device_get((tokens, batch["_mask"]))
|
| 124 |
+
tokens = tokens[mask] # remove padding examples.
|
| 125 |
+
responses = [postprocess_tokens(t) for t in tokens]
|
| 126 |
+
end = time()
|
| 127 |
+
|
| 128 |
+
print(responses)
|
| 129 |
+
print('\n')
|
| 130 |
+
print('Time elpased ', end - start)
|
| 131 |
+
|
| 132 |
+
return responses[0]
|
| 133 |
+
|
| 134 |
+
def download_model():
|
| 135 |
+
print('downloading model')
|
| 136 |
+
os.system('gdown 1-HyAeenHhS0xu2m9-fvsZw5sGhytsf7s')
|
| 137 |
+
|
| 138 |
+
def show_example(path):
|
| 139 |
+
return cv2.cvtColor(cv2.imread(path), cv2.COLOR_BGR2RGB)
|
| 140 |
+
|
| 141 |
+
if __name__ == "__main__":
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
iface = gr.Interface(
|
| 145 |
+
cache_examples=False,
|
| 146 |
+
fn=get_response,
|
| 147 |
+
inputs=[gr.Image(type="numpy"), gr.Textbox(placeholder="caption en")],
|
| 148 |
+
examples=[[show_example('test-images/b20d494a-cdebe83e.jpg')],[show_example('test-images/b43eb946-b8bc931c.jpg')],[show_example('test-images/b7d13f97-74ae37ed.jpg')],[show_example('test-images/bce15cb0-2d6aec27.jpg')],[show_example('test-images/b5e6efc0-345b365d.jpg')]],
|
| 149 |
+
outputs=[gr.Textbox(label="Response")],
|
| 150 |
+
title="Traffic Understanding with Multi-modal LLM",
|
| 151 |
+
description="Traffic Understanding with Multi-modal LLM")
|
| 152 |
+
|
| 153 |
+
SEQLEN = 128
|
| 154 |
+
|
| 155 |
+
# Don't let TF use the GPU or TPUs
|
| 156 |
+
tf.config.set_visible_devices([], "GPU")
|
| 157 |
+
tf.config.set_visible_devices([], "TPU")
|
| 158 |
+
|
| 159 |
+
TOKENIZER_PATH = "paligemma_tokenizer.model"
|
| 160 |
+
MODEL_PATH = './traffic-vqa_ckpt_person1.npz'
|
| 161 |
+
|
| 162 |
+
# if not (os.path.exists(MODEL_PATH)):
|
| 163 |
+
# download_model()
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
backend = jax.lib.xla_bridge.get_backend()
|
| 167 |
+
print(f"JAX version: {jax.__version__}")
|
| 168 |
+
print(f"JAX platform: {backend.platform}")
|
| 169 |
+
print(f"JAX devices: {jax.device_count()}")
|
| 170 |
+
|
| 171 |
+
LLM_VARIANT = "gemma2_2b"
|
| 172 |
+
|
| 173 |
+
model_config = ml_collections.FrozenConfigDict({
|
| 174 |
+
"llm": {"vocab_size": 257_152, "variant": LLM_VARIANT, "final_logits_softcap": 0.0},
|
| 175 |
+
"img": {"variant": "So400m/14", "pool_type": "none", "scan": True, "dtype_mm": "float16"}
|
| 176 |
+
})
|
| 177 |
+
model = paligemma.Model(**model_config)
|
| 178 |
+
tokenizer = sentencepiece.SentencePieceProcessor(TOKENIZER_PATH)
|
| 179 |
+
|
| 180 |
+
# Load params - this can take up to 1 minute in T4 colabs.
|
| 181 |
+
params = paligemma.load(None, MODEL_PATH, model_config)
|
| 182 |
+
|
| 183 |
+
# Define `decode` function to sample outputs from the model.
|
| 184 |
+
decode_fn = predict_fns.get_all(model)['decode']
|
| 185 |
+
decode = functools.partial(decode_fn, devices=jax.devices(), eos_token=tokenizer.eos_id())
|
| 186 |
+
|
| 187 |
+
mesh = jax.sharding.Mesh(jax.devices(), ("data"))
|
| 188 |
+
|
| 189 |
+
data_sharding = jax.sharding.NamedSharding(
|
| 190 |
+
mesh, jax.sharding.PartitionSpec("data"))
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
iface.launch()
|
download.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
wget --no-check-certificate "https://drive.google.com/uc?export=download&id=1-HyAeenHhS0xu2m9-fvsZw5sGhytsf7s" -O your_desired_filename.ext
|
paligemma_tokenizer.model
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8986bb4f423f07f8c7f70d0dbe3526fb2316056c17bae71b1ea975e77a168fc6
|
| 3 |
+
size 4264023
|
requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gdown
|
| 2 |
+
jax
|
| 3 |
+
flax
|
| 4 |
+
overrides
|
| 5 |
+
ml_collections
|
| 6 |
+
einops~=0.7
|
| 7 |
+
sentencepiece
|
| 8 |
+
tensorflow
|
| 9 |
+
opencv_python
|