NYUAD-ComNets commited on
Commit
41efcc3
·
verified ·
1 Parent(s): 20ffb88

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +30 -22
README.md CHANGED
@@ -30,7 +30,7 @@ The proposed solutions offer a more nuanced understanding of memes for accurate
30
 
31
 
32
 
33
- # Finetuned Gemma 3 Embedding Model
34
 
35
  ``` python
36
 
@@ -39,13 +39,17 @@ import torch
39
  import torch._dynamo
40
  from tqdm import tqdm # Progress bar library
41
  from unsloth import FastVisionModel
 
42
  from datasets import load_dataset
43
 
44
- def convert_to_conversation(sample):
 
 
 
45
  lis=[]
46
  lis.append({"type": "text", "text": sample["text"]})
47
  lis.append({"type": "image", "image": sample["image"]})
48
-
49
  conversation = [
50
  {
51
  "role": "system",
@@ -61,11 +65,12 @@ def convert_to_conversation(sample):
61
  pass
62
 
63
  dataset = load_dataset("QCRI/ArGuard-Task1", split="dev_test")
 
64
  converted_dataset = [convert_to_conversation(sample) for sample in dataset]
65
 
66
  # 1. Disable compiler optimization conflicts
67
- torch._dynamo.config.disable = True
68
- torch._dynamo.reset()
69
 
70
  # 2. Load your fine-tuned model and processor
71
  model_path = "NYUAD-ComNets/Gemma3_meme_classification"
@@ -81,7 +86,7 @@ instruction = "classify meme into Hateful or Not"
81
  all_embeddings = []
82
  labels_list = []
83
 
84
- num_iterations = min(500, len(converted_dataset))
85
 
86
  print(f"Starting embedding extraction for {num_iterations} items...")
87
 
@@ -104,24 +109,26 @@ for idx in tqdm(range(num_iterations), desc="Extracting Embeddings"):
104
  templated_text = processor.apply_chat_template(conversation, tokenize=False)
105
  inputs = processor(text=templated_text, images=sample_image, return_tensors="pt").to("cuda")
106
 
107
- # 5. Safe Extraction via .generate()
 
108
  with torch.no_grad():
109
  with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
110
- outputs = model.generate(
111
- **inputs,
112
- max_new_tokens=1,
113
- output_hidden_states=True,
114
- return_dict_in_generate=True
115
- )
116
-
117
- # 6. Extract final hidden layer states
118
- last_hidden_states = outputs.hidden_states[0][-1]
119
-
120
- # 7. Perform Mean Pooling and send directly to CPU memory
121
- multimodal_embedding = last_hidden_states.mean(dim=1).squeeze(0).float()
122
 
123
- # Convert torch tensor to a clean numpy row vector and append
124
- all_embeddings.append(multimodal_embedding.cpu().numpy())
 
125
  labels_list.append(sample_label)
126
 
127
  except Exception as e:
@@ -131,7 +138,8 @@ for idx in tqdm(range(num_iterations), desc="Extracting Embeddings"):
131
  embedding_matrix = np.vstack(all_embeddings)
132
 
133
  print("Final Concatenated Array Shape:", embedding_matrix.shape)
134
- np.save("test_embeddings.npy", embedding_matrix)
 
135
  ```
136
 
137
 
 
30
 
31
 
32
 
33
+ # Finetuned Gemma 3 Embedding Model with mean pooling
34
 
35
  ``` python
36
 
 
39
  import torch._dynamo
40
  from tqdm import tqdm # Progress bar library
41
  from unsloth import FastVisionModel
42
+
43
  from datasets import load_dataset
44
 
45
+ instruction = "classify meme into Hateful or Not"
46
+
47
+ def convert_to_conversation(sample):
48
+
49
  lis=[]
50
  lis.append({"type": "text", "text": sample["text"]})
51
  lis.append({"type": "image", "image": sample["image"]})
52
+
53
  conversation = [
54
  {
55
  "role": "system",
 
65
  pass
66
 
67
  dataset = load_dataset("QCRI/ArGuard-Task1", split="dev_test")
68
+
69
  converted_dataset = [convert_to_conversation(sample) for sample in dataset]
70
 
71
  # 1. Disable compiler optimization conflicts
72
+ #torch._dynamo.config.disable = True
73
+ #torch._dynamo.reset()
74
 
75
  # 2. Load your fine-tuned model and processor
76
  model_path = "NYUAD-ComNets/Gemma3_meme_classification"
 
86
  all_embeddings = []
87
  labels_list = []
88
 
89
+ num_iterations = len(converted_dataset)
90
 
91
  print(f"Starting embedding extraction for {num_iterations} items...")
92
 
 
109
  templated_text = processor.apply_chat_template(conversation, tokenize=False)
110
  inputs = processor(text=templated_text, images=sample_image, return_tensors="pt").to("cuda")
111
 
112
+
113
+ # 5. Forward Pass
114
  with torch.no_grad():
115
  with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
116
+ outputs = model(**inputs, output_hidden_states=True, return_dict=True)
117
+
118
+ # 6. Extract final layer and attention mask
119
+ last_hidden_states = outputs.hidden_states[-1] # [batch_size, seq_len, hidden_dim]
120
+ attention_mask = inputs["attention_mask"] # [batch_size, seq_len]
121
+
122
+ # 7. Masked Mean Pooling (Ignores padding tokens entirely)
123
+ input_mask_expanded = attention_mask.unsqueeze(-1).expand(last_hidden_states.size()).float()
124
+ sum_embeddings = torch.sum(last_hidden_states * input_mask_expanded, dim=1)
125
+ sum_mask = torch.clamp(input_mask_expanded.sum(dim=1), min=1e-9)
126
+
127
+ all_embedding = (sum_embeddings / sum_mask).squeeze(0).float()
128
 
129
+ all_embeddings.append(all_embedding.cpu().numpy())
130
+
131
+
132
  labels_list.append(sample_label)
133
 
134
  except Exception as e:
 
138
  embedding_matrix = np.vstack(all_embeddings)
139
 
140
  print("Final Concatenated Array Shape:", embedding_matrix.shape)
141
+
142
+ np.save("test_gemma3_mean_embeddings.npy", embedding_matrix)
143
  ```
144
 
145