Monimoy commited on
Commit
34fdfd1
·
verified ·
1 Parent(s): ff68ccb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +138 -138
app.py CHANGED
@@ -1,139 +1,139 @@
1
- # app.py
2
- import os
3
- import gradio as gr
4
- import torch
5
- from PIL import Image
6
- from transformers import AutoTokenizer, AutoModelForCausalLM
7
- import timm
8
- from torchvision import transforms
9
- from llama_cpp import Llama
10
- from peft import PeftModel
11
-
12
- # 1. Model Definitions (Same as in training script)
13
- class SigLIPImageEncoder(torch.nn.Module):
14
- def __init__(self, model_name='resnet50', embed_dim=512, pretrained_path=None):
15
- super().__init__()
16
- self.model = timm.create_model(model_name, pretrained=False, num_classes=0, global_pool='avg') # pretrained=False
17
- self.embed_dim = embed_dim
18
- self.projection = torch.nn.Linear(self.model.num_features, embed_dim)
19
-
20
- if pretrained_path:
21
- self.load_state_dict(torch.load(pretrained_path, map_location=torch.device('cpu'))) # Load to CPU first
22
- print(f"Loaded SigLIP image encoder from {pretrained_path}")
23
- else:
24
- print("Initialized SigLIP image encoder without pretrained weights.")
25
-
26
- def forward(self, image):
27
- features = self.model(image)
28
- embedding = self.projection(features)
29
- return embedding
30
-
31
- # 2. Load Models and Tokenizer
32
- phi3_model_path = "QuantFactory/Phi-3-mini-4k-instruct-GGUF" # Path to your quantized Phi-3 GGUF model
33
- peft_model_path = "./qlora_phi3_model"
34
- image_model_name = 'resnet50'
35
- image_embed_dim = 512
36
- siglip_pretrained_path = "image_encoder.pth" # Path to your pretrained SigLIP model
37
-
38
- device = torch.device("cpu") # Force CPU
39
- print(f"Using device: {device}")
40
-
41
- # Load Tokenizer (using a compatible tokenizer)
42
- text_tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-4k-instruct", trust_remote_code=True) # Or a compatible tokenizer
43
- text_tokenizer.pad_token = text_tokenizer.eos_token # Important for training
44
-
45
- # Image Transformations
46
- image_transform = transforms.Compose([
47
- transforms.Resize((224, 224)),
48
- transforms.ToTensor(),
49
- transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
50
- ])
51
-
52
- # Load SigLIP Image Encoder
53
- image_encoder = SigLIPImageEncoder(model_name=image_model_name, embed_dim=image_embed_dim, pretrained_path=siglip_pretrained_path).to(device)
54
- image_encoder.eval() # Set to evaluation mode
55
-
56
- # Load Phi-3 model using llama.cpp
57
- #base_model = Llama(
58
- # model_path=phi3_model_path,
59
- # n_gpu_layers=0, # Ensure no GPU usage
60
- # n_ctx=2048, # Adjust context length as needed
61
- # verbose=True,
62
- #)
63
-
64
-
65
- #base_model = Llama.from_pretrained(
66
- # repo_id="QuantFactory/Phi-3-mini-4k-instruct-GGUF",
67
- # filename="Phi-3-mini-4k-instruct.Q2_K.gguf",
68
- # n_gpu_layers=0,
69
- # n_ctx=2048,
70
- # verbose=True
71
- #)
72
-
73
- base_model_name="microsoft/Phi-3-mini-4k-instruct"
74
- device = "cpu"
75
-
76
- base_model = AutoModelForCausalLM.from_pretrained(base_model_name, torch_dtype=torch.float32, device_map={"": device})
77
-
78
-
79
- # Load and merge
80
- model = PeftModel.from_pretrained(base_model, peft_model_path, offload_dir='./offload')
81
- model = model.merge_and_unload()
82
- print("phi-3 model loaded sucessfully")
83
- # 3. Inference Function
84
- def predict(image, question):
85
- """
86
- Takes an image and a question as input and returns an answer.
87
- """
88
- if image is None or question is None or question == "":
89
- return "Please provide both an image and a question."
90
-
91
- try:
92
- image = Image.fromarray(image).convert("RGB")
93
- image = image_transform(image).unsqueeze(0).to(device)
94
-
95
- # Get image embeddings
96
- with torch.no_grad():
97
- image_embeddings = image_encoder(image)
98
- # Flatten the image embeddings for simplicity
99
- image_embeddings = image_embeddings.flatten().tolist()
100
-
101
- # Create the prompt with image embeddings
102
- prompt = f"Question: {question}\nImage Embeddings: {image_embeddings}\nAnswer:"
103
-
104
- # Generate answer using llama.cpp
105
- output = model(
106
- prompt,
107
- max_tokens=128,
108
- stop=["Q:", "\n"],
109
- echo=False,
110
- )
111
-
112
- answer = output["choices"][0]["text"].strip()
113
-
114
- return answer
115
-
116
- except Exception as e:
117
- return f"An error occurred: {str(e)}"
118
-
119
- # 4. Gradio Interface
120
- iface = gr.Interface(
121
- fn=predict,
122
- inputs=[
123
- gr.Image(label="Upload an Image"),
124
- gr.Textbox(label="Ask a Question about the Image", placeholder="What is in the image?")
125
- ],
126
- outputs=gr.Textbox(label="Answer"),
127
- title="Image Question Answering with Phi-3 and SigLIP (CPU)",
128
- description="Ask questions about an image and get answers powered by Phi-3 (llama.cpp) and SigLIP.",
129
- examples=[
130
- ["cat_0006.png", "Create a interesting story about this image?"],
131
- ["bird_0004.png", "Can you describe this image?"],
132
- ["truck_0003.png", "Elaborate the setting of the image"],
133
- ["ship_0007.png", "Explain the purpose of image"]
134
- ]
135
- )
136
-
137
- # 5. Launch the App
138
- if __name__ == "__main__":
139
  iface.launch()
 
1
+ # app.py
2
+ import os
3
+ import gradio as gr
4
+ import torch
5
+ from PIL import Image
6
+ from transformers import AutoTokenizer, AutoModelForCausalLM
7
+ import timm
8
+ from torchvision import transforms
9
+ from llama_cpp import Llama
10
+ from peft import PeftModel
11
+
12
+ # 1. Model Definitions (Same as in training script)
13
+ class SigLIPImageEncoder(torch.nn.Module):
14
+ def __init__(self, model_name='resnet50', embed_dim=512, pretrained_path=None):
15
+ super().__init__()
16
+ self.model = timm.create_model(model_name, pretrained=False, num_classes=0, global_pool='avg') # pretrained=False
17
+ self.embed_dim = embed_dim
18
+ self.projection = torch.nn.Linear(self.model.num_features, embed_dim)
19
+
20
+ if pretrained_path:
21
+ self.load_state_dict(torch.load(pretrained_path, map_location=torch.device('cpu'))) # Load to CPU first
22
+ print(f"Loaded SigLIP image encoder from {pretrained_path}")
23
+ else:
24
+ print("Initialized SigLIP image encoder without pretrained weights.")
25
+
26
+ def forward(self, image):
27
+ features = self.model(image)
28
+ embedding = self.projection(features)
29
+ return embedding
30
+
31
+ # 2. Load Models and Tokenizer
32
+ phi3_model_path = "QuantFactory/Phi-3-mini-4k-instruct-GGUF" # Path to your quantized Phi-3 GGUF model
33
+ peft_model_path = "./qlora_phi3_model"
34
+ image_model_name = 'resnet50'
35
+ image_embed_dim = 512
36
+ siglip_pretrained_path = "image_encoder.pth" # Path to your pretrained SigLIP model
37
+
38
+ device = torch.device("cpu") # Force CPU
39
+ print(f"Using device: {device}")
40
+
41
+ # Load Tokenizer (using a compatible tokenizer)
42
+ text_tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-4k-instruct", trust_remote_code=True) # Or a compatible tokenizer
43
+ text_tokenizer.pad_token = text_tokenizer.eos_token # Important for training
44
+
45
+ # Image Transformations
46
+ image_transform = transforms.Compose([
47
+ transforms.Resize((224, 224)),
48
+ transforms.ToTensor(),
49
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
50
+ ])
51
+
52
+ # Load SigLIP Image Encoder
53
+ image_encoder = SigLIPImageEncoder(model_name=image_model_name, embed_dim=image_embed_dim, pretrained_path=siglip_pretrained_path).to(device)
54
+ image_encoder.eval() # Set to evaluation mode
55
+
56
+ # Load Phi-3 model using llama.cpp
57
+ #base_model = Llama(
58
+ # model_path=phi3_model_path,
59
+ # n_gpu_layers=0, # Ensure no GPU usage
60
+ # n_ctx=2048, # Adjust context length as needed
61
+ # verbose=True,
62
+ #)
63
+
64
+
65
+ #base_model = Llama.from_pretrained(
66
+ # repo_id="QuantFactory/Phi-3-mini-4k-instruct-GGUF",
67
+ # filename="Phi-3-mini-4k-instruct.Q2_K.gguf",
68
+ # n_gpu_layers=0,
69
+ # n_ctx=2048,
70
+ # verbose=True
71
+ #)
72
+
73
+ base_model_name="microsoft/Phi-3-mini-4k-instruct"
74
+ device = "cuda"
75
+
76
+ base_model = AutoModelForCausalLM.from_pretrained(base_model_name, torch_dtype=torch.float32, device_map={"": device})
77
+
78
+
79
+ # Load and merge
80
+ model = PeftModel.from_pretrained(base_model, peft_model_path, offload_dir='./offload')
81
+ model = model.merge_and_unload()
82
+ print("phi-3 model loaded sucessfully")
83
+ # 3. Inference Function
84
+ def predict(image, question):
85
+ """
86
+ Takes an image and a question as input and returns an answer.
87
+ """
88
+ if image is None or question is None or question == "":
89
+ return "Please provide both an image and a question."
90
+
91
+ try:
92
+ image = Image.fromarray(image).convert("RGB")
93
+ image = image_transform(image).unsqueeze(0).to(device)
94
+
95
+ # Get image embeddings
96
+ with torch.no_grad():
97
+ image_embeddings = image_encoder(image)
98
+ # Flatten the image embeddings for simplicity
99
+ image_embeddings = image_embeddings.flatten().tolist()
100
+
101
+ # Create the prompt with image embeddings
102
+ prompt = f"Question: {question}\nImage Embeddings: {image_embeddings}\nAnswer:"
103
+
104
+ # Generate answer using llama.cpp
105
+ output = model(
106
+ prompt,
107
+ max_tokens=128,
108
+ stop=["Q:", "\n"],
109
+ echo=False,
110
+ )
111
+
112
+ answer = output["choices"][0]["text"].strip()
113
+
114
+ return answer
115
+
116
+ except Exception as e:
117
+ return f"An error occurred: {str(e)}"
118
+
119
+ # 4. Gradio Interface
120
+ iface = gr.Interface(
121
+ fn=predict,
122
+ inputs=[
123
+ gr.Image(label="Upload an Image"),
124
+ gr.Textbox(label="Ask a Question about the Image", placeholder="What is in the image?")
125
+ ],
126
+ outputs=gr.Textbox(label="Answer"),
127
+ title="Image Question Answering with Phi-3 and SigLIP (CPU)",
128
+ description="Ask questions about an image and get answers powered by Phi-3 (llama.cpp) and SigLIP.",
129
+ examples=[
130
+ ["cat_0006.png", "Create a interesting story about this image?"],
131
+ ["bird_0004.png", "Can you describe this image?"],
132
+ ["truck_0003.png", "Elaborate the setting of the image"],
133
+ ["ship_0007.png", "Explain the purpose of image"]
134
+ ]
135
+ )
136
+
137
+ # 5. Launch the App
138
+ if __name__ == "__main__":
139
  iface.launch()