FILE sources/0081/SPARC/attn_util.py
21: class SelectedIndexBuffer:
22:     def __init__(self):
23:         self.indices1 = (
24:             []
25:         )  # Buffer to store selected token indices from the current token generation step
26:         self.indices2 = (
27:             []
28:         )  # Buffer to store selected token indices from the previous token generation step
29:         self.input_len = 0  # Length of the input sequence
30:         self.num_image_patches = None
31: 
32:     def update_indices1(self, indices, image_token_index):
33:         """
34:         Updates indices1 with the selected token indices from a specific layer (e.g., the 20th layer).
35:         This is called during the current token generation to store new selections.
36:         The image_token_index offset is applied to adjust for the position of image tokens.
37:         """
38:         indices = indices + image_token_index
39:         indices = indices.squeeze(dim=-1)
40:         self.indices1 = indices
41: 
42:     def update_indices2(self):
43:         """
44:         Copies indices1 to indices2.
45:         Called at the beginning of a new token generation step so that calibration can use
46:         the indices selected from the previous step.
47:         """
48:         self.indices2 = self.indices1
49: 
50:     def update_input_len(self, len):
51:         self.input_len = len
52: 
53:     def reset(self):
54:         self.indices1 = []
55:         self.indices2 = []
56:         self.input_len = 0
57:         self.num_image_patches = None
58: 
59:     def calibrate(self, value, alpha):
60:         """
61:         Applies calibration to token representations using indices from the previous step (indices2).
62:         The calibration scales selected token positions by a factor alpha.
63:         """
64:         if len(self.indices2) > 0:
65:             value[:, :, self.indices2] *= alpha
66: 
67:     def update_patch_num(self, num_image_patches):
68:         self.num_image_patches = num_image_patches
145:         kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
146:     cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
147:     query_states, key_states = apply_rotary_pos_emb(
148:         query_states, key_states, cos, sin, position_ids
149:     )
150: 
151:     if self.layer_idx == 0:
152:         indices_buffer.update_indices2()
153: 
154:     if self.layer_idx >= se_layers[0] and self.layer_idx <= se_layers[1]:
155:         if len(indices_buffer.indices2) > 0:
156:             indices_buffer.calibrate(past_key_value.value_cache[self.layer_idx], alpha)
157: 
158:     if len(past_key_value.key_cache) > self.layer_idx:
159:         # generation
160:         gen_new_token = True
161:     else:
162:         # pre-filling
163:         gen_new_token = False
164: 
165:     if past_key_value is not None:
166:         cache_kwargs = {"sin": sin, "cos": cos}  # Specific to RoPE models
167:         key_states, value_states = past_key_value.update(
168:             key_states, value_states, self.layer_idx, cache_kwargs
169:         )
170: 
171:     key_states = repeat_kv(key_states, self.num_key_value_groups)
172:     value_states = repeat_kv(value_states, self.num_key_value_groups)
173: 
185:             raise ValueError(
186:                 f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
187:             )
188:         attn_weights = attn_weights + attention_mask
189: 
190:     # upcast attention to fp32
191:     attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(
192:         query_states.dtype
193:     )
194:     attn_weights = nn.functional.dropout(
195:         attn_weights, p=self.attention_dropout, training=self.training
196:     )
197: 
198:     if gen_new_token == False and self.layer_idx == 0:
199:         indices_buffer.update_patch_num(
200:             attn_weights.shape[-1] - indices_buffer.input_len
201:         )
202: 
203:     image_attention = attn_weights[
204:         :,
205:         :,
206:         -1,
207:         image_token_index : image_token_index + indices_buffer.num_image_patches,
208:     ].mean(dim=1)
209: 
210:     if gen_new_token:
211:         if selected:
212:             # mean by head dim
213:             ratio = (image_attention - self.image_attention) / self.image_attention
214:             ratio = ratio.squeeze(dim=0)
215:             indices = (ratio >= tau).nonzero()
216:             indices_buffer.update_indices1(indices, image_token_index)
217: 
218:     if not gen_new_token:
219:         self.image_attention = image_attention
220:     else:
221:         self.image_attention = (
222:             1 - beta
223:         ) * image_attention + beta * self.image_attention
224: 
225:     attn_output = torch.matmul(attn_weights, value_states)
226: 
255: 
256:     return attn_output, attn_weights, past_key_value
257: 
258: 
259: def add_custom_attention_layers(
260:     model,
261:     lm_model="llama",
262:     alpha=1,
263:     beta=0,
264:     tau=2,
265:     selected_layer=20,
266:     se_layers=(0, 31),
267:     indices_buffer=None,
268: ):
269: 
270:     for i, layer in enumerate(model.model.layers):
271:         selected = True if selected_layer == i else False
272:         forward_ = partial(
273:             forward,
274:             alpha=alpha,
275:             beta=beta,
276:             tau=tau,
277:             selected=selected,
278:             se_layers=se_layers,
279:             indices_buffer=indices_buffer,
280:         )
281:         layer.self_attn.forward = MethodType(forward_, layer.self_attn)

FILE sources/0081/SPARC/eval.py
29:     buffer = SelectedIndexBuffer()
30: 
31:     if args.alpha != 1.0:
32:         add_custom_attention_layers(
33:             model=model,
34:             alpha=args.alpha,
35:             beta=args.beta,
36:             tau=args.tau,
37:             selected_layer=args.selected_layer,
38:             se_layers=(args.start_layer, args.end_layer),
39:             indices_buffer=buffer,
40:         )
73:         zip(data_loader, annotations), total=len(annotations)
74:     ):
75:         input_ids = input_ids.to(device="cuda", non_blocking=True)
76: 
77:         img_save = {}
78:         img_save["image_id"] = img_id[0]
79: 
80:         buffer.update_input_len(len(input_ids[0]) - 1)
81: 
82:         with torch.inference_mode():
83:             output_ids = model.generate(
84:                 input_ids,
85:                 images=image_tensor.to(
86:                     dtype=torch.float16, device="cuda", non_blocking=True
87:                 ),
88:                 image_sizes=image_sizes,
89:                 do_sample=True if args.temperature > 0 else False,
90:                 temperature=args.temperature,
91:                 top_p=args.top_p,
92:                 num_beams=args.num_beams,
93:                 max_new_tokens=args.max_new_tokens,
94:                 use_cache=True,
95:             )
96: 
97:         outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[
98:             0
99:         ].strip()
100: 
101:         buffer.reset()
102: 
103:         img_save["caption"] = outputs
129:     parser.add_argument("--experiment_name", type=str, default=None)
130:     parser.add_argument("--conv-mode", type=str, default="vicuna_v1")
131:     parser.add_argument("--num-chunks", type=int, default=1)
132:     parser.add_argument("--chunk-idx", type=int, default=0)
133:     parser.add_argument("--temperature", type=float, default=0)
134:     parser.add_argument("--top_p", type=float, default=None)
135:     parser.add_argument("--num_beams", type=int, default=1)
136:     parser.add_argument("--max_new_tokens", type=int, default=512)
137:     parser.add_argument("--alpha", type=float, default=1.0)
138:     parser.add_argument("--beta", type=float, default=0.0)
139:     parser.add_argument("--tau", type=float, default=2)
140:     parser.add_argument("--selected_layer", type=int, default=20)
141:     parser.add_argument("--start_layer", type=int, default=0)
142:     parser.add_argument("--end_layer", type=int, default=31)
143:     parser.add_argument("--seed", type=int, default=42)

FILE sources/0081/SPARC/dataset_loader.py
65:         elif self.dataset_type == "coco":
66:             image_file = line
67:             img_id = int(image_file.split(".jpg")[0][-6:])
68: 
69:         qs = "Please describe this image in detail."
70: 
71:         if self.model_config.mm_use_im_start_end:
72:             qs = (
73:                 DEFAULT_IM_START_TOKEN
74:                 + DEFAULT_IMAGE_TOKEN
75:                 + DEFAULT_IM_END_TOKEN
76:                 + "\n"
77:                 + qs
78:             )
79:         else:
80:             qs = DEFAULT_IMAGE_TOKEN + "\n" + qs
81: 
82:         conv = conv_templates["vicuna_v1"].copy()
83:         conv.append_message(conv.roles[0], qs)
84:         conv.append_message(conv.roles[1], None)
85:         prompt = conv.get_prompt()
86: 
87:         image = Image.open(os.path.join(self.image_folder, image_file)).convert("RGB")
88:         image_tensor = process_images([image], self.image_processor, self.model_config)[
89:             0
90:         ]
91: 
92:         input_ids = tokenizer_image_token(
93:             prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt"
94:         )
95: 
143:     tokenizer,
144:     image_processor,
145:     model_config,
146:     num_chunks=1,
147:     chunk_idx=0,
148:     seed=42,
149: ):
150:     # Dataset type
151:     assert dataset_type in ["coco", "iiw", "docci"]
152: 
153:     if dataset_type == "coco":
154:         annotations = os.listdir(image_folder)
155:     else:
156:         annotations = [
157:             json.loads(q) for q in open(os.path.expanduser(annotation_file), "r")
158:         ]
159:         annotations = get_chunk(annotations, num_chunks, chunk_idx)
160: 
161:     if dataset_type in ["coco", "docci"]:
162:         rng = random.Random(seed)
163:         annotations = rng.sample(annotations, 500)
164: 
165:     data_loader = create_data_loader(
166:         dataset_type,
167:         annotations,
168:         image_folder,
169:         tokenizer,
170:         image_processor,
171:         model_config,
172:     )
173: 
174:     return data_loader, annotations

FILE sources/0081/SPARC/clair.py
16: 
17: class LLMEngine:
18:     @staticmethod
19:     def from_string(model_name):
20:         if model_name == "gpt-4o":
21:             return OpenAIEngine(model_name="gpt-4o")
22:         elif model_name == "chat-gpt":
23:             return OpenAIEngine(model_name="gpt-3.5-turbo")
24:         else:
36:     def call(self, prompt, n_completions, temperature=0.0, max_tokens=1024):
37:         messages = [{"role": "user", "content": prompt}]
38:         response = self.api.chat.completions.create(
39:             model=self.model_name,
40:             messages=messages,
41:             n=n_completions,
42:             temperature=temperature,
43:             max_tokens=max_tokens,
44:         )
45: 
46:         return [r.message.content for r in response.choices]
143:         rng = random.Random(args.seed)
144:         annotations = rng.sample(annotations, 500)
145: 
146:     directory = os.path.dirname(save_path)
147: 
148:     if not os.path.exists(directory):
149:         os.makedirs(directory)
150: 
151:     save_file = open(save_path, "w")
152: 
153:     clairs = []
154:     for answer, annotation in tqdm(zip(answers, annotations), total=len(answers)):
155:         save_output = {}
156:         if args.data_type == "iiw":
157:             references = [annotation["IIW"]]
158:         elif args.data_type == "docci":
159:             references = [annotation["description"]]
160:         candidates = [answer["caption"]]
161: 
162:         clair_score = clair(candidates, references, model="gpt-4o")
163: 
164:         # print(f"ref: {references[0]}")
165:         # print(f"cand: {candidates[0]}")
166:         # print(clair_score)
167: 
168:         clairs.append(clair_score)
169:         save_output["score"] = clair_score[0]
170:         save_output["reason"] = clair_score[1]
171: 

FILE sources/0081/SPARC/chair.py
432:                     hallucinated_word_count += 1
433:                     cap_dict["mscoco_hallucinated_words"].append((word, node_word))
434:                     cap_dict["hallucination_idxs"].append(idx)
435:                     hallucinated = True
436:                 else:
437:                     recall_gt_objects.add(node_word)
438: 
439:             # count hallucinated caps
440:             num_caps += 1
441:             len_caps += len(raw_words)
442:             if hallucinated:
443:                 num_hallucinated_caps += 1
444: 
445:             # add
446:             num_gt_objects += len(gt_objects)
447:             num_recall_gt_objects += len(recall_gt_objects)
448: 
449:             cap_dict["metrics"]["CHAIRs"] = int(hallucinated)
450:             cap_dict["metrics"]["CHAIRi"] = 0.0
451:             cap_dict["metrics"]["Recall"] = 0.0
452:             cap_dict["metrics"]["Len"] = 0.0
453: 
454:             if len(words) > 0:
455:                 cap_dict["metrics"]["CHAIRi"] = len(
456:                     cap_dict["mscoco_hallucinated_words"]
457:                 ) / float(len(words))
458: 
459:             # add
460:             if len(gt_objects) > 0:
461:                 cap_dict["metrics"]["Recall"] = len(recall_gt_objects) / len(gt_objects)
462: 
463:             output["sentences"].append(cap_dict)
464: 
465:         chair_s = num_hallucinated_caps / num_caps
466:         chair_i = hallucinated_word_count / coco_word_count
467:         # add
468:         recall = num_recall_gt_objects / num_gt_objects
469:         avg_len = 0.01 * len_caps / num_caps
470: 
471:         output["overall_metrics"] = {
472:             "CHAIRs": chair_s,
473:             "CHAIRi": chair_i,
474:             "Recall": recall,
475:             "Len": avg_len,
476:         }
477: 
478:         return output
479: 
480: 
481: def load_generated_captions(cap_file, image_id_key: str, caption_key: str):
482:     # Read in captions
483:     # it should be list of dict
484:     ext = os.path.splitext(cap_file)[-1]
485:     if ext == ".json":
486:         caps = json.load(open(cap_file))
487:     elif ext == ".jsonl":
488:         caps = [json.loads(s) for s in open(cap_file)]
489:     else:
490:         raise ValueError(f"Unspported extension {ext} for cap_file: {cap_file}")
491: 

FILE sources/0081/SPARC/scripts/llava/captioning_coco.sh
1: DEVICE=0
2: EXP_NAME=COCO # results will be saved as $SAVE_FOLDER/$EXP_NAME.jsonl
3: ALPHA=1.1 # paramerter for attention re-weighting
4: BETA=0.1 # parameter for EMA
5: TAU=1.5 # Threshold
6: LAYER=20 # layer used for token selection
7: 
8: MODEL_PATH=liuhaotian/llava-v1.5-7b
9: DATASET_TYPE=coco # Dataset type: options are coco, iiw, or docci
10: # Path to input images
11: IMAGE_FOLDER="/home/mingi/data/coco/val2014"
12: 
13: # Directory where results will be saved
14: SAVE_FOLDER="/home/mingi/experiments/SPARC/results"
15: SEED=42 # Random seed for evaluation data sampling (used only for coco_val and docci)
16: 
17: set -e
18: CUDA_VISIBLE_DEVICES=$DEVICE python -m eval \
19:     --experiment_name $EXP_NAME \
20:     --model-path $MODEL_PATH \
21:     --dataset_type $DATASET_TYPE \
22:     --alpha $ALPHA \
23:     --beta $BETA \
24:     --image-folder $IMAGE_FOLDER \
25:     --save_path $SAVE_FOLDER \
26:     --start_layer 0 \
27:     --end_layer 31 \
28:     --selected_layer $LAYER \
29:     --tau $TAU \
30:     --seed $SEED

FILE sources/0081/SPARC/scripts/llava_next/captioning_docci.sh
1: DEVICE=1
2: EXP_NAME=DOCCI_llava-next # results will be saved as $SAVE_FOLDER/$EXP_NAME.jsonl
3: ALPHA=1.1 # paramerter for attention re-weighting
4: BETA=0.1 # parameter for EMA
5: TAU=4.0 # Threshold
6: LAYER=20 # layer used for token selection
7: 
8: MODEL_PATH=liuhaotian/llava-v1.6-vicuna-7b
9: DATASET_TYPE=docci # Dataset type: options are coco, iiw, or docci
10: # Path to input images
11: IMAGE_FOLDER="/home/mingi/experiments/LLaVA/data/eval/DOCCI/images"
12: # Path to annotation file
13: ANNOTATION_FILE="/home/mingi/experiments/LLaVA/data/eval/DOCCI/docci_descriptions.jsonl"
14: # Directory where results will be saved
15: SAVE_FOLDER="/home/mingi/experiments/SPARC/results"
16: SEED=42 # Random seed for evaluation data sampling (used only for coco_val and docci)
17: 
18: set -e
19: CUDA_VISIBLE_DEVICES=$DEVICE python -m eval \
20:     --experiment_name $EXP_NAME \
21:     --model-path $MODEL_PATH \
22:     --dataset_type $DATASET_TYPE \
23:     --alpha $ALPHA \
24:     --beta $BETA \
25:     --image-folder $IMAGE_FOLDER \
26:     --annotation-file $ANNOTATION_FILE \
27:     --save_path $SAVE_FOLDER \
28:     --start_layer 0 \
29:     --end_layer 31 \
30:     --selected_layer $LAYER \
31:     --tau $TAU \
32:     --seed $SEED
