pvyas96 commited on
Commit
cbad06d
Β·
verified Β·
1 Parent(s): d75cfa9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -88
app.py CHANGED
@@ -5,59 +5,52 @@ import re
5
  import time
6
  from PIL import Image
7
  import torch
8
- import spaces
9
- #import subprocess
10
- #subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
11
 
 
 
12
 
 
13
  processor = AutoProcessor.from_pretrained("HuggingFaceTB/SmolVLM-Instruct")
14
- model = AutoModelForVision2Seq.from_pretrained("HuggingFaceTB/SmolVLM-Instruct",
15
- torch_dtype=torch.bfloat16,
16
- #_attn_implementation="flash_attention_2"
17
- )
 
18
 
 
19
  def model_inference(
20
  input_dict, history, decoding_strategy, temperature, max_new_tokens,
21
  repetition_penalty, top_p
22
  ):
23
  text = input_dict["text"]
24
- print(input_dict["files"])
25
  if len(input_dict["files"]) > 1:
26
- images = [Image.open(image).convert("RGB") for image in input_dict["files"]]
27
  elif len(input_dict["files"]) == 1:
28
- images = [Image.open(input_dict["files"][0]).convert("RGB")]
29
-
30
-
31
- if text == "" and not images:
32
  gr.Error("Please input a query and optionally image(s).")
33
 
34
  if text == "" and images:
35
- gr.Error("Please input a text query along the image(s).")
36
-
37
-
38
-
39
 
40
  resulting_messages = [
41
- {
42
- "role": "user",
43
- "content": [{"type": "image"} for _ in range(len(images))] + [
44
- {"type": "text", "text": text}
45
- ]
46
- }
47
  ]
 
 
48
  prompt = processor.apply_chat_template(resulting_messages, add_generation_prompt=True)
49
  inputs = processor(text=prompt, images=[images], return_tensors="pt")
50
- inputs = {k: v.to("cuda") for k, v in inputs.items()}
 
51
  generation_args = {
52
  "max_new_tokens": max_new_tokens,
53
  "repetition_penalty": repetition_penalty,
54
-
55
  }
56
 
57
- assert decoding_strategy in [
58
- "Greedy",
59
- "Top P Sampling",
60
- ]
61
  if decoding_strategy == "Greedy":
62
  generation_args["do_sample"] = False
63
  elif decoding_strategy == "Top P Sampling":
@@ -66,8 +59,9 @@ def model_inference(
66
  generation_args["top_p"] = top_p
67
 
68
  generation_args.update(inputs)
69
- # Generate
70
- streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens= True)
 
71
  generation_args = dict(inputs, streamer=streamer, max_new_tokens=max_new_tokens)
72
  generated_text = ""
73
 
@@ -76,63 +70,69 @@ def model_inference(
76
  thread.join()
77
 
78
  buffer = ""
79
-
80
-
81
  for new_text in streamer:
82
-
83
- buffer += new_text
84
- generated_text_without_prompt = buffer#[len(ext_buffer):]
85
- time.sleep(0.01)
86
- yield buffer
87
-
88
 
89
- demo = gr.ChatInterface(fn=model_inference, title="Geoscience AI Interpreter",
90
- description="This app take the thin sections, seismic images etc. and interpret them. You just upload an image and text along with it. It works best with single turn conversations, so clear the conversation after a single turn.",
91
- textbox=gr.MultimodalTextbox(label="Query Input", file_types=["image"], file_count="multiple"), stop_btn="Stop Generation", multimodal=True,
92
- additional_inputs=[gr.Radio(["Top P Sampling",
93
- "Greedy"],
94
- value="Greedy",
95
- label="Decoding strategy",
96
- #interactive=True,
97
- info="Higher values is equivalent to sampling more low-probability tokens.",
98
-
99
- ), gr.Slider(
100
- minimum=0.0,
101
- maximum=5.0,
102
- value=0.4,
103
- step=0.1,
104
- interactive=True,
105
- label="Sampling temperature",
106
- info="Higher values will produce more diverse outputs.",
107
- ),
108
- gr.Slider(
109
- minimum=8,
110
- maximum=1024,
111
- value=512,
112
- step=1,
113
- interactive=True,
114
- label="Maximum number of new tokens to generate",
115
- ), gr.Slider(
116
- minimum=0.01,
117
- maximum=5.0,
118
- value=1.2,
119
- step=0.01,
120
- interactive=True,
121
- label="Repetition penalty",
122
- info="1.0 is equivalent to no penalty",
123
- ),
124
- gr.Slider(
125
- minimum=0.01,
126
- maximum=0.99,
127
- value=0.8,
128
- step=0.01,
129
- interactive=True,
130
- label="Top P",
131
- info="Higher values is equivalent to sampling more low-probability tokens.",
132
- )],cache_examples=False
133
- )
134
-
135
-
136
-
 
 
 
 
 
 
 
 
 
 
 
137
 
138
- demo.launch(debug=True)
 
 
5
  import time
6
  from PIL import Image
7
  import torch
 
 
 
8
 
9
+ # Check for GPU availability
10
+ device = "cuda" if torch.cuda.is_available() else "cpu"
11
 
12
+ # Load model and processor
13
  processor = AutoProcessor.from_pretrained("HuggingFaceTB/SmolVLM-Instruct")
14
+ model = AutoModelForVision2Seq.from_pretrained(
15
+ "HuggingFaceTB/SmolVLM-Instruct",
16
+ torch_dtype=torch.bfloat16 if device == "cuda" else torch.float32,
17
+ device_map="auto" if device == "cpu" else None # Automatically maps to CPU if no GPU
18
+ ).to(device)
19
 
20
+ # Inference function
21
  def model_inference(
22
  input_dict, history, decoding_strategy, temperature, max_new_tokens,
23
  repetition_penalty, top_p
24
  ):
25
  text = input_dict["text"]
 
26
  if len(input_dict["files"]) > 1:
27
+ images = [Image.open(image).convert("RGB") for image in input_dict["files"]]
28
  elif len(input_dict["files"]) == 1:
29
+ images = [Image.open(input_dict["files"][0]).convert("RGB")]
30
+ else:
 
 
31
  gr.Error("Please input a query and optionally image(s).")
32
 
33
  if text == "" and images:
34
+ gr.Error("Please input a text query along with the image(s).")
 
 
 
35
 
36
  resulting_messages = [
37
+ {
38
+ "role": "user",
39
+ "content": [{"type": "image"} for _ in range(len(images))] + [
40
+ {"type": "text", "text": text}
 
 
41
  ]
42
+ }
43
+ ]
44
  prompt = processor.apply_chat_template(resulting_messages, add_generation_prompt=True)
45
  inputs = processor(text=prompt, images=[images], return_tensors="pt")
46
+ inputs = {k: v.to(device) for k, v in inputs.items()}
47
+
48
  generation_args = {
49
  "max_new_tokens": max_new_tokens,
50
  "repetition_penalty": repetition_penalty,
 
51
  }
52
 
53
+ assert decoding_strategy in ["Greedy", "Top P Sampling"]
 
 
 
54
  if decoding_strategy == "Greedy":
55
  generation_args["do_sample"] = False
56
  elif decoding_strategy == "Top P Sampling":
 
59
  generation_args["top_p"] = top_p
60
 
61
  generation_args.update(inputs)
62
+
63
+ # Stream generation
64
+ streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
65
  generation_args = dict(inputs, streamer=streamer, max_new_tokens=max_new_tokens)
66
  generated_text = ""
67
 
 
70
  thread.join()
71
 
72
  buffer = ""
 
 
73
  for new_text in streamer:
74
+ buffer += new_text
75
+ yield buffer
 
 
 
 
76
 
77
+ # Gradio interface
78
+ demo = gr.ChatInterface(
79
+ fn=model_inference,
80
+ title="Geoscience AI Interpreter",
81
+ description=(
82
+ "This app interprets thin sections, seismic images, etc. "
83
+ "Upload an image and a text query. Works best with single-turn conversations. "
84
+ "Clear the conversation after a single turn."
85
+ ),
86
+ textbox=gr.MultimodalTextbox(
87
+ label="Query Input", file_types=["image"], file_count="multiple"
88
+ ),
89
+ stop_btn="Stop Generation",
90
+ multimodal=True,
91
+ additional_inputs=[
92
+ gr.Radio(
93
+ ["Top P Sampling", "Greedy"],
94
+ value="Greedy",
95
+ label="Decoding strategy",
96
+ info="Higher values are equivalent to sampling more low-probability tokens.",
97
+ ),
98
+ gr.Slider(
99
+ minimum=0.0,
100
+ maximum=5.0,
101
+ value=0.4,
102
+ step=0.1,
103
+ interactive=True,
104
+ label="Sampling temperature",
105
+ info="Higher values produce more diverse outputs.",
106
+ ),
107
+ gr.Slider(
108
+ minimum=8,
109
+ maximum=1024,
110
+ value=512,
111
+ step=1,
112
+ interactive=True,
113
+ label="Maximum number of new tokens to generate",
114
+ ),
115
+ gr.Slider(
116
+ minimum=0.01,
117
+ maximum=5.0,
118
+ value=1.2,
119
+ step=0.01,
120
+ interactive=True,
121
+ label="Repetition penalty",
122
+ info="1.0 is equivalent to no penalty.",
123
+ ),
124
+ gr.Slider(
125
+ minimum=0.01,
126
+ maximum=0.99,
127
+ value=0.8,
128
+ step=0.01,
129
+ interactive=True,
130
+ label="Top P",
131
+ info="Higher values are equivalent to sampling more low-probability tokens.",
132
+ ),
133
+ ],
134
+ cache_examples=False,
135
+ )
136
 
137
+ # Launch Gradio app
138
+ demo.launch(debug=True)