seemggoel commited on
Commit
dd19729
·
verified ·
1 Parent(s): e7986f8

Rename modal.py to model.py

Browse files
Files changed (2) hide show
  1. modal.py +0 -300
  2. model.py +106 -0
modal.py DELETED
@@ -1,300 +0,0 @@
1
- import os
2
- import numpy as np
3
- import torch
4
- import torch.nn as nn
5
- from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments, Trainer, WhisperProcessor, WhisperForConditionalGeneration, PreTrainedModel,BitsAndBytesConfig
6
- from peft import prepare_model_for_kbit_training, LoraConfig, get_peft_model, TaskType
7
- from tqdm import tqdm
8
- import json
9
- import librosa
10
- from dataclasses import dataclass
11
- from typing import Any, Dict, List, Union
12
- import gc
13
- import torch.nn.functional as F
14
-
15
- # # Define multimodal projector class
16
- # class ProjectionBlock(nn.Module):
17
- # def __init__(self, input_dim, output_dim):
18
- # super().__init__()
19
- # self.pre_norm = nn.LayerNorm(input_dim)
20
- # self.proj = nn.Sequential(nn.Linear(input_dim, output_dim), nn.GELU(), nn.Linear(output_dim, output_dim))
21
-
22
- # def forward(self, x):
23
- # return self.proj(self.pre_norm(x))
24
-
25
- import torch
26
- import torch.nn as nn
27
-
28
- class CrossAttentionBlock(nn.Module):
29
- def __init__(self, embed_dim, num_heads=8, dropout=0.1):
30
- super().__init__()
31
- self.attention = nn.MultiheadAttention(embed_dim, num_heads, dropout=dropout)
32
- self.norm1 = nn.LayerNorm(embed_dim)
33
- self.norm2 = nn.LayerNorm(embed_dim)
34
- self.ffn = nn.Sequential(
35
- nn.Linear(embed_dim, embed_dim * 4),
36
- nn.GELU(),
37
- nn.Linear(embed_dim * 4, embed_dim),
38
- nn.Dropout(dropout)
39
- )
40
-
41
- def forward(self, x, context):
42
- # Self attention
43
- attended, _ = self.attention(
44
- query=self.norm1(x),
45
- key=self.norm1(context),
46
- value=self.norm1(context)
47
- )
48
- x = x + attended
49
-
50
- # FFN
51
- x = x + self.ffn(self.norm2(x))
52
- return x
53
-
54
- ## Updated on 23rd November
55
- class ProjectionBlock(nn.Module):
56
- def __init__(self, input_dim, output_dim):
57
- super().__init__()
58
- self.pre_norm = nn.LayerNorm(input_dim)
59
- self.proj = nn.Sequential(
60
- nn.Linear(input_dim, output_dim * 2), # Increase intermediate dimension
61
- nn.GELU(),
62
- nn.Linear(output_dim * 2, output_dim) # Project to final dimension
63
- )
64
-
65
- def forward(self, x):
66
- # Add shape validation
67
- if len(x.shape) == 2: # If input is [batch_size, features]
68
- return self.proj(self.pre_norm(x))
69
- elif len(x.shape) == 3: # If input is [batch_size, seq_len, features]
70
- return self.proj(self.pre_norm(x.mean(dim=1))) # Pool sequence dimension
71
- else:
72
- raise ValueError(f"Unexpected input shape: {x.shape}")
73
-
74
- ##Updated on 23rd November
75
- # class EnhancedMultimodalProjector(nn.Module):
76
- # def __init__(self, image_input_dim, audio_input_dim, output_dim, num_heads=8):
77
- # super().__init__()
78
-
79
- # # Adjust projectors to match Phi-3's hidden size (1024)
80
- # self.image_proj = ProjectionBlock(image_input_dim, output_dim)
81
- # self.audio_proj = ProjectionBlock(audio_input_dim, output_dim)
82
-
83
- # # Cross-attention blocks
84
- # self.image_audio_cross_attn = CrossAttentionBlock(output_dim, num_heads)
85
- # self.audio_image_cross_attn = CrossAttentionBlock(output_dim, num_heads)
86
-
87
- # # Final fusion layer
88
- # self.fusion_layer = nn.Sequential(
89
- # nn.LayerNorm(output_dim * 2),
90
- # nn.Linear(output_dim * 2, output_dim),
91
- # nn.GELU(),
92
- # nn.Linear(output_dim, output_dim)
93
- # )
94
- class EnhancedMultimodalProjector(nn.Module):
95
- def __init__(self, image_input_dim, audio_input_dim=1024, output_dim=1024, num_heads=8):
96
- super().__init__()
97
- self.image_proj = ProjectionBlock(image_input_dim, output_dim)
98
- self.audio_proj = ProjectionBlock(audio_input_dim, output_dim)
99
- self.image_audio_cross_attn = CrossAttentionBlock(output_dim, num_heads)
100
- self.audio_image_cross_attn = CrossAttentionBlock(output_dim, num_heads)
101
- self.fusion_layer = nn.Sequential(
102
- nn.LayerNorm(output_dim * 2),
103
- nn.Linear(output_dim * 2, output_dim),
104
- nn.GELU(),
105
- nn.Linear(output_dim, output_dim)
106
- )
107
-
108
- def forward(self, image_embedding=None, audio_embedding=None):
109
- # Add shape validation and adjustment
110
- if image_embedding is not None and image_embedding.dim() < 2:
111
- raise ValueError("Expected `image_embedding` to have at least 2 dimensions.")
112
- if audio_embedding is not None and audio_embedding.dim() < 2:
113
- raise ValueError("Expected `audio_embedding` to have at least 2 dimensions.")
114
- if image_embedding is not None and len(image_embedding.shape) == 2:
115
- image_embedding = image_embedding.unsqueeze(1) # Add sequence dimension
116
- if audio_embedding is not None and len(audio_embedding.shape) == 2:
117
- audio_embedding = audio_embedding.unsqueeze(1) # Add sequence dimension
118
-
119
- # Initial projections
120
- projected_image = self.image_proj(image_embedding) if image_embedding is not None else None
121
- projected_audio = self.audio_proj(audio_embedding) if audio_embedding is not None else None
122
-
123
- if projected_image is not None and projected_audio is not None:
124
- # Ensure correct shapes for cross-attention
125
- attended_image = self.image_audio_cross_attn(projected_image, projected_audio)
126
- attended_audio = self.audio_image_cross_attn(projected_audio, projected_image)
127
-
128
- # Combine the attended features
129
- fused_features = torch.cat([attended_image, attended_audio], dim=-1)
130
- final_output = self.fusion_layer(fused_features)
131
-
132
- return final_output, final_output
133
-
134
- elif projected_image is not None:
135
- return projected_image, None
136
- elif projected_audio is not None:
137
- return None, projected_audio
138
- else:
139
- return None, None
140
-
141
- # Update the Phi3WithProjector to use the enhanced projector
142
- class Phi3WithProjector(PreTrainedModel):
143
- def __init__(self, config, phi3_model, projector):
144
- super().__init__(config)
145
- self.phi3_model = phi3_model
146
- self.projector = projector
147
- self.supports_gradient_checkpointing = True
148
-
149
- def forward(self, input_ids=None, attention_mask=None, inputs_embeds=None,
150
- image_embeddings=None, audio_embeddings=None, labels=None, **kwargs):
151
- if inputs_embeds is None:
152
- inputs_embeds = self.phi3_model.get_input_embeddings()(input_ids)
153
-
154
- # Get fused embeddings from enhanced projector
155
- projected_features, _ = self.projector(image_embeddings, audio_embeddings)
156
-
157
- # Concatenate embeddings if we have projected features
158
- if projected_features is not None:
159
- combined_embeddings = torch.cat([inputs_embeds, projected_features.unsqueeze(1)], dim=1)
160
- # Extend attention mask
161
- extended_attention_mask = torch.cat([
162
- attention_mask,
163
- torch.ones((attention_mask.shape[0], 1), device=attention_mask.device)
164
- ], dim=1)
165
- else:
166
- combined_embeddings = inputs_embeds
167
- extended_attention_mask = attention_mask
168
-
169
- # Adjust labels if needed
170
- if labels is not None and projected_features is not None:
171
- labels = torch.cat([
172
- labels,
173
- torch.full((labels.shape[0], 1), -100, dtype=labels.dtype, device=labels.device)
174
- ], dim=1)
175
-
176
- return self.phi3_model(
177
- inputs_embeds=combined_embeddings,
178
- attention_mask=extended_attention_mask,
179
- labels=labels,
180
- **kwargs
181
- )
182
-
183
-
184
- class MultimodalProjector(nn.Module):
185
- def __init__(self, image_input_dim, audio_input_dim, output_dim):
186
- super().__init__()
187
- self.image_proj = ProjectionBlock(image_input_dim, output_dim)
188
- self.audio_proj = ProjectionBlock(audio_input_dim, output_dim)
189
-
190
- def forward(self, image_embedding=None, audio_embedding=None):
191
- projected_image = self.image_proj(image_embedding) if image_embedding is not None else None
192
- projected_audio = self.audio_proj(audio_embedding) if audio_embedding is not None else None
193
- return projected_image, projected_audio
194
-
195
-
196
-
197
- class Phi3WithProjector(PreTrainedModel):
198
- def __init__(self, config, phi3_model, projector):
199
- super().__init__(config)
200
- self.phi3_model = phi3_model
201
- self.projector = projector
202
- self.supports_gradient_checkpointing = True
203
-
204
-
205
- def forward(self, input_ids=None, attention_mask=None, inputs_embeds=None, image_embeddings=None, audio_embeddings=None, labels=None, **kwargs):
206
- # Use get_input_embeddings() to retrieve the embeddings layer
207
- if inputs_embeds is None:
208
- inputs_embeds = self.phi3_model.get_input_embeddings()(input_ids)
209
-
210
- # Project both image and audio embeddings to the appropriate dimension
211
- projected_image, projected_audio = self.projector(image_embeddings, audio_embeddings)
212
-
213
- # Concatenate the embeddings
214
- embeddings_to_concat = [inputs_embeds]
215
- if projected_image is not None:
216
- embeddings_to_concat.append(projected_image.unsqueeze(1))
217
- if projected_audio is not None:
218
- embeddings_to_concat.append(projected_audio.unsqueeze(1))
219
-
220
- combined_embeddings = torch.cat(embeddings_to_concat, dim=1)
221
-
222
- # Modify how the attention mask is extended
223
- extended_attention_mask = attention_mask.clone() # Start with a copy
224
-
225
- # Extend for image and audio, if present
226
- if projected_image is not None:
227
- extended_attention_mask = torch.cat([extended_attention_mask, torch.ones_like(extended_attention_mask[:, :1])], dim=1)
228
- if projected_audio is not None:
229
- extended_attention_mask = torch.cat([extended_attention_mask, torch.ones_like(extended_attention_mask[:, :1])], dim=1)
230
-
231
- # Adjust labels to match the extended input sequence length
232
- if labels is not None:
233
- # Pad labels with -100 to ignore the added tokens in the loss calculation
234
- num_added_tokens = sum(1 for emb in [projected_image, projected_audio] if emb is not None)
235
- labels = torch.cat([labels, torch.full((labels.shape[0], num_added_tokens), -100, dtype=labels.dtype, device=labels.device)], dim=1)
236
- outputs = self.phi3_model(
237
- inputs_embeds=combined_embeddings,
238
- attention_mask=extended_attention_mask,
239
- labels=labels,
240
- **kwargs
241
- )
242
-
243
- # Add auxiliary losses for multimodal alignment
244
- if image_embeddings is not None or audio_embeddings is not None:
245
- loss = outputs.loss
246
-
247
- # Add contrastive loss for multimodal alignment
248
- if image_embeddings is not None and audio_embeddings is not None:
249
- img_proj, audio_proj = self.projector(image_embeddings, audio_embeddings)
250
- contrastive_loss = self.compute_contrastive_loss(img_proj, audio_proj)
251
- loss = loss + 0.1 * contrastive_loss # Weight the auxiliary loss
252
-
253
- outputs.loss = loss
254
-
255
-
256
-
257
-
258
- return outputs
259
-
260
- def get_input_embeddings(self):
261
- """Returns the model's input embeddings."""
262
- return self.phi3_model.get_input_embeddings()
263
-
264
- def set_input_embeddings(self, value):
265
- """Sets the model's input embeddings."""
266
- self.phi3_model.set_input_embeddings(value)
267
-
268
-
269
- # Instead, use the built-in gradient checkpointing
270
- def enable_gradient_checkpointing(self):
271
- """Enable gradient checkpointing for the model."""
272
- if hasattr(self.phi3_model, "gradient_checkpointing_enable"):
273
- self.phi3_model.gradient_checkpointing_enable()
274
- else:
275
- self.phi3_model.config.use_cache = False
276
- self.phi3_model.train() # Ensure model is in training mode
277
-
278
- def disable_gradient_checkpointing(self):
279
- """Disable gradient checkpointing for the model."""
280
- if hasattr(self.phi3_model, "gradient_checkpointing_disable"):
281
- self.phi3_model.gradient_checkpointing_disable()
282
- else:
283
- self.phi3_model.config.use_cache = True
284
-
285
- def compute_contrastive_loss(self, img_features, audio_features):
286
- # Normalize features
287
- img_features = F.normalize(img_features, dim=-1)
288
- audio_features = F.normalize(audio_features, dim=-1)
289
-
290
- # Compute similarity matrix
291
- similarity = torch.matmul(img_features, audio_features.transpose(0, 1))
292
-
293
- # Temperature-scaled cross entropy loss
294
- temperature = 0.07
295
- labels = torch.arange(similarity.size(0)).to(similarity.device)
296
- loss = F.cross_entropy(similarity / temperature, labels)
297
-
298
- return loss
299
-
300
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
model.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Step 2: Import necessary libraries
2
+ import gradio as gr
3
+ from PIL import Image
4
+ from transformers import CLIPProcessor, CLIPModel, AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
5
+ from peft import PeftConfig, PeftModel
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+ from transformers.cache_utils import DynamicCache, StaticCache
10
+
11
+
12
+ # Step 3: Set device and default dtype
13
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
14
+ torch.set_default_dtype(torch.float16)
15
+
16
+ # Step 4: Load CLIP model and processor
17
+ clip_model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32", torch_dtype=torch.float16).to(DEVICE)
18
+ clip_processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32", use_fast=True)
19
+
20
+ # Step 5: Define the MultiModalModel class
21
+ class MultiModalModel(nn.Module):
22
+ def __init__(self, phi_model_name="microsoft/phi-3-mini-4k-instruct", clip_model_name="openai/clip-vit-base-patch32"):
23
+ super().__init__()
24
+ self.phi = None # Will be set after loading the PEFT model
25
+ self.tokenizer = AutoTokenizer.from_pretrained(phi_model_name, trust_remote_code=True)
26
+ self.tokenizer.add_special_tokens({"additional_special_tokens": ["[IMG]"], "pad_token": "<pad>"})
27
+ self.clip = CLIPModel.from_pretrained(clip_model_name, torch_dtype=torch.float16).eval().to(DEVICE)
28
+ image_embedding_dim = self.clip.config.projection_dim
29
+ phi_hidden_size = 3072 # Hardcoded for Phi-3 mini
30
+ self.image_projection = nn.Sequential(
31
+ nn.Linear(image_embedding_dim, phi_hidden_size, dtype=torch.float16),
32
+ nn.LayerNorm(phi_hidden_size, dtype=torch.float16),
33
+ nn.Dropout(0.1)
34
+ ).to(DEVICE)
35
+ nn.init.xavier_uniform_(self.image_projection[0].weight, gain=1.0)
36
+ nn.init.zeros_(self.image_projection[0].bias)
37
+
38
+ def forward(self, text_input_ids, attention_mask=None, image_embedding=None):
39
+ image_embedding = torch.clamp(image_embedding, min=-1e4, max=1e4)
40
+ image_embedding = F.normalize(image_embedding, dim=-1, eps=1e-5).to(torch.float16)
41
+ with torch.no_grad():
42
+ self.image_projection[0].weight.clamp_(-1.0, 1.0)
43
+ self.image_projection[0].bias.clamp_(-1.0, 1.0)
44
+ projected_image = 1.0 * self.image_projection(image_embedding)
45
+ projected_image = torch.clamp(projected_image, min=-1e4, max=1e4)
46
+ if torch.isnan(projected_image).any() or torch.isinf(projected_image).any():
47
+ print("Warning: Projected image contains NaN or Inf values after clamping, replacing with zeros")
48
+ projected_image = torch.where(
49
+ torch.logical_or(torch.isnan(projected_image), torch.isinf(projected_image)),
50
+ torch.zeros_like(projected_image),
51
+ projected_image
52
+ )
53
+ if projected_image.dim() == 2:
54
+ projected_image = projected_image.unsqueeze(1)
55
+ text_embeddings = self.phi.get_input_embeddings()(text_input_ids)
56
+ fused_embeddings = text_embeddings.clone()
57
+ img_token_id = self.tokenizer.convert_tokens_to_ids("[IMG]")
58
+ img_token_mask = (text_input_ids == img_token_id)
59
+ for i in range(fused_embeddings.shape[0]):
60
+ img_positions = img_token_mask[i].nonzero(as_tuple=True)[0]
61
+ if img_positions.numel() > 0:
62
+ fused_embeddings[i, img_positions[0], :] = projected_image[i, 0, :]
63
+ if torch.isnan(fused_embeddings).any() or torch.isinf(fused_embeddings).any():
64
+ print("Warning: Fused embeddings contain NaN or Inf values, replacing with zeros")
65
+ fused_embeddings = torch.where(
66
+ torch.logical_or(torch.isnan(fused_embeddings), torch.isinf(fused_embeddings)),
67
+ torch.zeros_like(fused_embeddings),
68
+ fused_embeddings
69
+ )
70
+ return fused_embeddings
71
+
72
+ # Step 6: Load the fine-tuned model weights from Epoch_0
73
+ def load_model():
74
+
75
+ # 1. Load PEFT Config
76
+ peft_model_id = "/content/drive/MyDrive/V6_Checkpoints/Epoch_peft_1" # Path to the saved PEFT directory
77
+ config = PeftConfig.from_pretrained(peft_model_id) #Use the config to determine the base model
78
+
79
+ attn_implementation = "eager"
80
+ cache = DynamicCache()
81
+
82
+ quantization_config = BitsAndBytesConfig(load_in_8bit=True)
83
+ base_model = AutoModelForCausalLM.from_pretrained(
84
+ config.base_model_name_or_path,
85
+ return_dict=True,
86
+ quantization_config=quantization_config,
87
+ device_map="auto",
88
+ trust_remote_code=False,
89
+ torch_dtype=torch.float16,
90
+ attn_implementation="eager"
91
+ )
92
+ base_model.gradient_checkpointing_enable()
93
+ peft_model = PeftModel.from_pretrained(base_model, peft_model_id)
94
+ tokenizer = AutoTokenizer.from_pretrained(peft_model_id)
95
+ special_tokens = {"additional_special_tokens": ["[IMG]"], "pad_token": "<pad>"}
96
+ tokenizer.add_special_tokens(special_tokens)
97
+ peft_model.resize_token_embeddings(len(tokenizer))
98
+ tokenizer.pad_token = tokenizer.eos_token
99
+
100
+ model = MultiModalModel(phi_model_name=config.base_model_name_or_path)
101
+ #model.load_state_dict(torch.load("/content/drive/MyDrive/V7_Checkpoints_2ndMarch2025/Epoch_0/model_state_dict.pth"), strict=False)
102
+ model.phi = peft_model
103
+ model.to(DEVICE)
104
+ model.eval()
105
+ return model, tokenizer
106
+