akshit-g commited on
Commit
97974d9
Β·
1 Parent(s): e0b4ef2

update : CPU

Browse files
Files changed (4) hide show
  1. README.md +7 -5
  2. app.py +117 -0
  3. control_vectors.pt +3 -0
  4. requirements.txt +4 -0
README.md CHANGED
@@ -1,12 +1,14 @@
1
  ---
2
- title: SeeForMe LifeCrisis
3
- emoji: 🌍
4
- colorFrom: gray
5
- colorTo: red
6
  sdk: gradio
7
- sdk_version: 5.7.1
8
  app_file: app.py
9
  pinned: false
 
 
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: SeeForMe-LifeCrisis
3
+ emoji: 🌜
4
+ colorFrom: indigo
5
+ colorTo: blue
6
  sdk: gradio
7
+ sdk_version: 4.19.2
8
  app_file: app.py
9
  pinned: false
10
+ short_description: When you are questioning life and the meaning of life
11
+ license: apache-2.0
12
  ---
13
 
14
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
+ import torch
3
+ import re
4
+ import gradio as gr
5
+ from threading import Thread
6
+ from transformers import TextIteratorStreamer, AutoTokenizer, AutoModelForCausalLM
7
+ from PIL import ImageDraw
8
+ from torchvision.transforms.v2 import Resize
9
+
10
+ import subprocess
11
+ # subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
12
+
13
+ model_id = "vikhyatk/moondream2"
14
+ revision = "2024-05-20"
15
+ tokenizer = AutoTokenizer.from_pretrained(model_id, revision=revision)
16
+ moondream = AutoModelForCausalLM.from_pretrained(
17
+ model_id, trust_remote_code=True, revision=revision,
18
+ # torch_dtype=torch.bfloat16, device_map={"": "cuda"}
19
+ torch_dtype=torch.float32, device_map="cpu"
20
+ # attn_implementation="flash_attention_2"
21
+ )
22
+ moondream.eval()
23
+
24
+ control_vectors = torch.load("control_vectors.pt", map_location="cpu")
25
+ control_vectors = [t.to('cpu', dtype=torch.float32) for t in control_vectors]
26
+
27
+ class LayerWrapper(torch.nn.Module):
28
+ def __init__(self, og_layer, control_vectors, scale=4.2):
29
+ super().__init__()
30
+ self.og_layer = og_layer
31
+ self.control_vectors = control_vectors
32
+ self.scale = scale
33
+
34
+ def forward(self, *args, **kwargs):
35
+ layer_outputs = self.og_layer(*args, **kwargs)
36
+ layer_outputs = (layer_outputs[0] + self.scale * self.control_vectors, *layer_outputs[1:])
37
+ return layer_outputs
38
+
39
+ moondream.text_model.transformer.h = torch.nn.ModuleList([
40
+ LayerWrapper(layer, vector, 4.2)
41
+ for layer, vector in zip(moondream.text_model.transformer.h, control_vectors)
42
+ ])
43
+
44
+ @spaces.GPU(duration=10)
45
+ def answer_question(img, prompt):
46
+ image_embeds = moondream.encode_image(img)
47
+ streamer = TextIteratorStreamer(tokenizer, skip_special_tokens=True)
48
+ thread = Thread(
49
+ target=moondream.answer_question,
50
+ kwargs={
51
+ "image_embeds": image_embeds,
52
+ "question": prompt,
53
+ "tokenizer": tokenizer,
54
+ "streamer": streamer,
55
+ "repetition_penalty": 1.2,
56
+ "temperature": 0.1,
57
+ "do_sample": True,
58
+ "length_penalty": 1.2
59
+ },
60
+ )
61
+ thread.start()
62
+
63
+ buffer = ""
64
+ for new_text in streamer:
65
+ buffer += new_text
66
+ yield buffer.strip()
67
+
68
+ def extract_floats(text):
69
+ # Regular expression to match an array of four floating point numbers
70
+ pattern = r"\[\s*(-?\d+\.\d+)\s*,\s*(-?\d+\.\d+)\s*,\s*(-?\d+\.\d+)\s*,\s*(-?\d+\.\d+)\s*\]"
71
+ match = re.search(pattern, text)
72
+ if match:
73
+ # Extract the numbers and convert them to floats
74
+ return [float(num) for num in match.groups()]
75
+ return None # Return None if no match is found
76
+
77
+
78
+ def extract_bbox(text):
79
+ bbox = None
80
+ if extract_floats(text) is not None:
81
+ x1, y1, x2, y2 = extract_floats(text)
82
+ bbox = (x1, y1, x2, y2)
83
+ return bbox
84
+
85
+ def process_answer(img, answer):
86
+ if extract_bbox(answer) is not None:
87
+ x1, y1, x2, y2 = extract_bbox(answer)
88
+ draw_image = Resize(768)(img)
89
+ width, height = draw_image.size
90
+ x1, x2 = int(x1 * width), int(x2 * width)
91
+ y1, y2 = int(y1 * height), int(y2 * height)
92
+ bbox = (x1, y1, x2, y2)
93
+ ImageDraw.Draw(draw_image).rectangle(bbox, outline="red", width=3)
94
+ return gr.update(visible=True, value=draw_image)
95
+
96
+ return gr.update(visible=False, value=None)
97
+
98
+ with gr.Blocks() as demo:
99
+ gr.Markdown(
100
+ """
101
+ # 🌜 Just for Fun to discuss the meaning of life using [activation vectors]
102
+ """
103
+ )
104
+ with gr.Row():
105
+ prompt = gr.Textbox(label="Input", value="Describe this image.", scale=4)
106
+ submit = gr.Button("Submit")
107
+ with gr.Row():
108
+ img = gr.Image(type="pil", label="Upload an Image")
109
+ with gr.Column():
110
+ output = gr.Markdown(label="Response")
111
+ ann = gr.Image(visible=False, label="Annotated Image")
112
+
113
+ submit.click(answer_question, [img, prompt], output)
114
+ prompt.submit(answer_question, [img, prompt], output)
115
+ output.change(process_answer, [img, output], ann, show_progress=False)
116
+
117
+ demo.queue().launch()
control_vectors.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e233c0a671e74f0927ae189a9932f7d7236a347b07ab114bec7ca333c121d92
3
+ size 105518
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ timm==0.9.12
2
+ transformers==4.36.2
3
+ einops==0.7.0
4
+ accelerate==0.25.0