File size: 33,473 Bytes
34ea840
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
from transformers import AutoTokenizer, LlavaNextProcessor, LlavaNextForConditionalGeneration, BitsAndBytesConfig
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
import torch
from PIL import Image
import requests
import numpy as np
import os
import sys
import random
from urllib.parse import quote 
from PIL import Image
import io
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
#os.environ["CUDA_VISIBLE_DEVICES"] = "3"
from src.model_architecture import print_detailed_layers
import matplotlib.pyplot as plt
import math
import torchvision.transforms as transforms
import torch.nn as nn
from dataclasses import asdict
from vllm import LLM, EngineArgs, SamplingParams
from vllm.lora.request import LoRARequest
from vllm.multimodal.utils import fetch_image
from vllm.utils import FlexibleArgumentParser
from typing import NamedTuple, Optional

def print_gpu_memory():
    for i in range(torch.cuda.device_count()):
        print(f"GPU {i}:")
        print(f"  Memory allocated: {torch.cuda.memory_allocated(i) / 1e9:.2f} GB")
        print(f"  Memory reserved: {torch.cuda.memory_reserved(i) / 1e9:.2f} GB")

def move_prefix_kv_to_model_device(prefix_kv, model):
    """
    Ensure that each layer's key-value tensors in prefix_kv are on the correct device
    based on where the corresponding layer resides in a sharded model.
    """
    new_prefix_kv = []
    for layer_idx, (key, value) in enumerate(prefix_kv):
        if key is not None and value is not None:
            # Get the device of the corresponding layer
            layer_device = next(model.language_model.model.layers[layer_idx].parameters()).device
            key = key.to(layer_device)
            value = value.to(layer_device)
        new_prefix_kv.append((key, value))
    return tuple(new_prefix_kv)

def load_model(model_name, model_path, max_memory=None):
    print("Loading processor and model...")
    if model_name == 'llava':
        processor = LlavaNextProcessor.from_pretrained(model_path, use_fast=True)
        tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True)
        if max_memory:
            model = LlavaNextForConditionalGeneration.from_pretrained(
                model_path,
                torch_dtype=torch.float16,
                device_map="auto", 
                max_memory=max_memory,
                low_cpu_mem_usage=True,
            )
        else:
            model = LlavaNextForConditionalGeneration.from_pretrained(
                model_path,
                torch_dtype=torch.float16,
                low_cpu_mem_usage=True,
            )
            model.to("cuda")
    elif model_name == 'qwen':
        processor = AutoProcessor.from_pretrained(model_path, use_fast=True, min_pixels=256 * 28 * 28, max_pixels=1280 * 28 * 28)
        tokenizer = None
        if max_memory:
            model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
                model_path, 
                torch_dtype=torch.float16, 
                device_map="auto",
                # attn_implementation="flash_attention_2",
                max_memory=max_memory,
                low_cpu_mem_usage=True)
        else:
            model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
                model_path, 
                torch_dtype=torch.float16, 
                # attn_implementation="flash_attention_2",
                low_cpu_mem_usage=True)
            model.to("cuda")
        
    return processor, tokenizer, model

def generate_response_batch_img(model_name, processor, model, prompts, images=None, steer=False):
    """Process multiple prompts with optional images in batch"""
    # Configure tokenizer
    if not hasattr(processor.tokenizer, 'padding_side') or processor.tokenizer.padding_side != 'left':
        processor.tokenizer.padding_side = 'left'

    # Prepare conversations
    conversations = []
    if images:
        # For image-text batches
        img_ptr = 0
        for prompt in prompts:
            # Count <image> tokens in prompt to determine how many images to use
            num_images = prompt.count('<image>')
            if num_images == 0:
                # Text-only prompt
                conversations.append([{"role": "user", "content": [{"type": "text", "text": prompt}]}])
                continue
            current_images = images[img_ptr : img_ptr + num_images]
            img_ptr += num_images
            
            content = [{"type": "text", "text": prompt}]
            for img in current_images:
                content.append({"type": "image", "image": img})
            
            conversations.append([{"role": "user", "content": content}])
    else:
        # Text-only batches
        conversations = [
            [{"role": "user", "content": [{"type": "text", "text": prompt}]}]
            for prompt in prompts
        ]

    # Apply chat template
    formatted_inputs = [
        processor.apply_chat_template(conv, add_generation_prompt=True) 
        for conv in conversations
    ]

    # Common batch parameters
    batch_params = {
        "padding": True,
        "return_tensors": "pt",
        "truncation": True,
        "max_length": 2048
    }

    if model_name == 'llava':
        # LLaVA processing
        if images:
            inputs = processor(
                text=formatted_inputs,
                images=[img for conv in conversations for img in conv[0]['content'] if img.get('type') == 'image'],
                **batch_params
            ).to(model.device)
        else:
            inputs = processor(
                text=formatted_inputs,
                **batch_params
            ).to(model.device)
        
        outputs = model.generate(
            **inputs,
            max_new_tokens=10**3,
            pad_token_id=processor.tokenizer.pad_token_id
        )
        
        return processor.batch_decode(
            outputs, 
            skip_special_tokens=True
        )

    elif model_name == 'qwen':
        # Qwen processing
        if images:
            image_list = [
                item["image"] 
                for conv in conversations 
                for item in conv[0]["content"] 
                if item["type"] == "image"
            ]
            inputs = processor(
                text=formatted_inputs,
                images=image_list,
                **batch_params
            ).to(model.device)
        else:
            inputs = processor(
                text=formatted_inputs,
                **batch_params
            ).to(model.device)
        
        generated_ids = model.generate(
            **inputs,
            max_new_tokens=10**3,
            pad_token_id=processor.tokenizer.pad_token_id,
            eos_token_id=processor.tokenizer.eos_token_id,
        )
        
        # Trim input IDs
        generated_ids_trimmed = [
            out_ids[len(in_ids):] 
            for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
        ]
        
        return processor.batch_decode(
            generated_ids_trimmed, 
            skip_special_tokens=True, 
            clean_up_tokenization_spaces=False
        )

    else:
        raise ValueError(f"Unsupported model: {model_name}")
    
class ModelRequestData(NamedTuple):
    engine_args: EngineArgs
    prompt: str
    image_data: list[Image.Image]
    stop_token_ids: Optional[list[int]] = None
    chat_template: Optional[str] = None
    lora_requests: Optional[list[LoRARequest]] = None
    
def generate_response_vllm(processor, model, prompts, images=None, steer=False):
    """Process multiple prompts with optional images in batch"""
    # Configure tokenizer
    if not hasattr(processor.tokenizer, 'padding_side') or processor.tokenizer.padding_side != 'left':
        processor.tokenizer.padding_side = 'left'

    # Prepare conversations
    conversations = []
    if images:
        # For image-text batches
        img_ptr = 0
        for prompt, combine_images in zip(prompts, images):
            content = [{"type": "text", "text": prompt}]
            for img in combine_images:
                content.append({"type": "image", "image": img})
            
            conversations.append([{"role": "user", "content": content}])
    else:
        # Text-only batches
        conversations = [
            [{"role": "user", "content": [{"type": "text", "text": prompt}]}]
            for prompt in prompts
        ]
    # Apply chat template
    formatted_inputs = [
        processor.apply_chat_template(conv, add_generation_prompt=True) 
        for conv in conversations
    ]
    
    combined_messages = []
    for (input, image) in zip(formatted_inputs, images):
        combined_messages.append({
            "prompt": input,
            "multi_modal_data": {
                "image": image
            }
        })
        
    sampling_params = SamplingParams(temperature=0.0,
                                    max_tokens=10**3)
    
    
    outputs = model.generate(
        combined_messages,
        sampling_params=sampling_params)
    
    return [output.outputs[0].text for output in outputs]

def generate_response_conversation_vllm(processor, model, conversations, images=None):
    """Process multiple prompts with optional images in batch"""
    # Configure tokenizer
    if not hasattr(processor.tokenizer, 'padding_side') or processor.tokenizer.padding_side != 'left':
        processor.tokenizer.padding_side = 'left'

    # Apply chat template
    formatted_inputs = [
        processor.apply_chat_template(conv, add_generation_prompt=True) 
        for conv in conversations
    ]
    
    combined_messages = []
    for (input, image) in zip(formatted_inputs, images):
        combined_messages.append({
            "prompt": input,
            "multi_modal_data": {
                "image": image
            }
        })
        
    sampling_params = SamplingParams(temperature=0.0,
                                    max_tokens=10**3,
                                    top_p=1.0,
                                    n=1)
    
    
    outputs = model.generate(
        combined_messages,
        sampling_params=sampling_params)
    
    return [output.outputs[0].text for output in outputs]
    # return [
    #     [output.outputs[i].text for i in range(len(output.outputs))]
    #     for output in outputs
    # ]
        
      
def generate_response(processor, model, image, prompt, steer=False):
    conversation = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": prompt},
                {"type": "image"}
            ],
        }
    ]
    formatted_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)

    inputs = processor(images=image, text=formatted_prompt, return_tensors="pt").to("cuda") # Remove device
    output = model.generate(**inputs, 
                        max_new_tokens=10**3)
    return processor.decode(output[0], skip_special_tokens=True)
    
def generate_response_rag(processor, model, image, prompt, similar_infos, google_infos=None):
    conversation = []
    images = []
    for value in similar_infos.values():
        images.append(value['image'])
        if google_infos is not None:
            description = google_infos
        else:
            description = value['desc']
        conversation.append({
            "role": "user",
        "content": [
            {"type": "text", "text": "Reference: " + description},
            {"type": "image", "image": value['image']}
        ]
        })
    images.append(image)
    conversation.append({
            "role": "user",
            "content": [
                {"type": "text", "text": prompt},
                {"type": "image", "image": image}
            ],
        })
    formatted_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)

    inputs = processor(images=images, text=formatted_prompt, return_tensors="pt").to(model.device)
    output = model.generate(**inputs, 
                        max_new_tokens=10**3)
    return processor.decode(output[0], skip_special_tokens=True)   
    

def get_past_key_value_text(processor, tokenizer, model, question, image, prompt, prefix_idx, top_tokens,filter_stop_words=True, random=False):
    #Tokenize input
    #image = Image.open(image).convert("RGB") 
    # compress_info = generate_response(processor, model, image, f"[QUESTION]{question} [CAPTION]{prompt} Compress informations useful for the question from text and image with only THREE words! This token can be semantically unmeaningful")
    # compress_info = compress_info.split('[/INST]')[1].strip()
    # print(compress_info)
    conversation = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": f"[QUESTION]{question} [REFERENCE]{prompt}"},
                #{"type": "text", "text": f"[QUESTION]{question} [CAPTION]{prompt} summarize useful information for question:"},
                # {"type": "text", "text": prompt},
                {"type": "image"} # add Image
            ],
        }
    ]
    formatted_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
    input_ids = processor(images=image, text=formatted_prompt, return_tensors="pt") # add Image
    # input_ids = processor(text=formatted_prompt, return_tensors="pt")
    
    def find_subsequence_indices(input_ids, prompt_tokens):
        """Find the start and end indices of prompt_tokens inside input_ids."""
        input_ids_list = input_ids[0].tolist()
        prompt_tokens_list = prompt_tokens[0].tolist()
        for i in range(len(input_ids_list)):
            if input_ids_list[i : i + 3] == prompt_tokens_list[4:7]:
                return i, i+len(prompt_tokens_list)-6
        return None, None  # Not found


    # Enable evaluation mode (disable dropout)
    model.eval()
    # Generate next token with attention weights
    with torch.no_grad():
        outputs = model(**input_ids, use_cache=True, output_attentions=True)
        #outputs = model(**input_ids, use_cache=True)

    past_key_values = outputs.past_key_values
    # print(past_key_values[0][0].shape)
    tokens = input_ids['input_ids'].cpu().tolist()[0]
    token_info = [(token, tokenizer.decode([token])) for token in tokens]
    img_token_idxs = [i for i in range(len(token_info)) if token_info[i][0]==32000]
    non_img_indices = list(range(img_token_idxs[-1]+1, len(token_info)))
    #print(token_info)
    # #####Visualize Attention######
    # for layer in range(32):
    #     last_layer_attention = outputs.attentions[layer][0].cpu().numpy()
    #     print(last_layer_attention.shape)
    #     np.save(f'/home/wenyi/llava_project/attention/{layer}_layer_attention.npy', last_layer_attention)
    #     last_layer_attention = last_layer_attention.mean(axis=0)
    #     actual_min = np.min(last_layer_attention)
    #     actual_max = 0.1
    #     print(actual_min,actual_max)
    #     plt.figure()
    #     plt.imshow(last_layer_attention, cmap="viridis", vmin=actual_min, vmax=actual_max)
    #     plt.colorbar()
    #     plt.title(f"Attention Weights ({layer} Layer)")
    #     plt.savefig(f"/home/wenyi/llava_project/attention/attention_weight_{layer}.jpg")
    # ########### Average to compress Vision Tokens ###########   
    # print(len(img_token_idxs))
    def group_and_average_past_kv(img_token_idxs, past_key_values, group_size=10):
        groups = [img_token_idxs[i:i + group_size] for i in range(0, len(img_token_idxs), group_size)]
        new_seq_len = len(groups) + len(non_img_indices)
        final_past_key_values = []
        # Iterate over each layer's key-value pair
        for layer_idx, (layer_k, layer_v) in enumerate(past_key_values):
            batch_size, num_heads, _, head_dim = layer_k.shape
            # Move tensors to CPU first
            # layer_k = layer_k.to("cpu")
            # layer_v = layer_v.to("cpu")
            # Initialize new tensors with reduced sequence length
            new_k = torch.zeros((batch_size, num_heads, new_seq_len, head_dim), 
                            dtype=layer_k.dtype)
            new_v = torch.zeros((batch_size, num_heads, new_seq_len, head_dim), 
                            dtype=layer_v.dtype)
            for group_idx, group in enumerate(groups):
                group_k = layer_k[..., group, :].mean(dim=-2, keepdim=True)
                group_v = layer_v[..., group, :].mean(dim=-2, keepdim=True)
                new_k[..., group_idx:group_idx+1, :] = group_k
                new_v[..., group_idx:group_idx+1, :] = group_v
            #add text tokens
            new_k[..., len(groups):new_seq_len, :] = layer_k[..., non_img_indices, :]
            new_v[..., len(groups):new_seq_len, :] = layer_v[..., non_img_indices, :]
            final_past_key_values.append((new_k, new_v))
        return final_past_key_values
    past_key_values = group_and_average_past_kv(img_token_idxs, past_key_values)
    # print(past_key_values[0][0].shape)
    ############################################
    ########### Top Attention Weight to compress Vision Tokens ###########
    def select_top_tokens_past_kv(past_key_values, top200_img_token_idxs, non_img_indices):
        new_seq_len = 200 + len(non_img_indices)  # 200 top visual tokens + all text tokens
        final_past_key_values = []
        # Iterate over each layer's key-value pair
        for layer_idx, (layer_k, layer_v) in enumerate(past_key_values):
            batch_size, num_heads, _, head_dim = layer_k.shape            
            # Initialize new tensors with new sequence length
            new_k = torch.zeros((batch_size, num_heads, new_seq_len, head_dim), 
                            dtype=layer_k.dtype, device=layer_k.device)
            new_v = torch.zeros((batch_size, num_heads, new_seq_len, head_dim), 
                            dtype=layer_v.dtype, device=layer_v.device)            
            # Copy top 200 visual tokens
            new_k[..., :200, :] = layer_k[..., top200_img_token_idxs, :]
            new_v[..., :200, :] = layer_v[..., top200_img_token_idxs, :]
            # Copy all text tokens
            new_k[..., 200:new_seq_len, :] = layer_k[..., non_img_indices, :]
            new_v[..., 200:new_seq_len, :] = layer_v[..., non_img_indices, :]
            final_past_key_values.append((new_k, new_v))
        return final_past_key_values   
    
    # Select top 200 visual tokens
    # layer_attention = outputs.attentions[0][0].cpu().numpy()
    # layer_attention = np.mean(layer_attention, axis=0) 
    # attention_avg = np.mean(layer_attention, axis=0) 
    # img_attention_scores = attention_avg[img_token_idxs]
    # top200_relative_indices = np.argsort(img_attention_scores)[-200:] 
    # top200_img_token_idxs = [img_token_idxs[i] for i in top200_relative_indices]
    # past_key_values = select_top_tokens_past_kv(past_key_values, top200_img_token_idxs, non_img_indices)
    
    # top200_scores = attention_avg[top200_img_token_idxs]
    # plt.figure(figsize=(10, 6))
    # plt.hist(top200_scores, bins=100, range=(0, 0.05), alpha=0.7)
    # plt.title('Distribution of Top 200 Attention Scores')
    # plt.xlabel('Top 200 Attention Score')
    # plt.ylabel('Frequency')
    # plt.xlim(0, 0.05)
    # plt.grid(True, alpha=0.3)
    # plt.savefig(f"/home/wenyi/llava_project/attention/top200_attention_score.jpg")
    # print("Past key value shape:", past_key_values[0][0].shape)


    if top_tokens is not None:
        # Extract attention weights
        text_start_idx = (input_ids['input_ids'][0] == 28792).nonzero()[0].item()
        prompt_start_idx, prompt_end_idx = 1, 2
        token_info = [(token, tokenizer.decode([token])) for token in input_ids['input_ids'][0, text_start_idx+prompt_start_idx:text_start_idx+prompt_end_idx].tolist()]
        #token_info = [(i, tokenizer.decode([i])) for i in [i.item() for i in input_ids[0]]]
        for id, text in token_info:
            print(f"ID: {id}, Text: {text}")
        top_indices = [idx for idx in range(text_start_idx + prompt_start_idx, text_start_idx + prompt_end_idx)]
        
        final_past_key_values = []
        # Iterate over each layer's key-value pair
        for layer_idx, (key, value) in enumerate(past_key_values):
            # Keep only tokens at `top_indices`
            filtered_key = key[:, :, top_indices, :]  # Shape: (batch_size, num_heads, len(top_indices), head_dim)
            filtered_value = value[:, :, top_indices, :]  # Shape: (batch_size, num_heads, len(top_indices), head_dim)
            # Append filtered results
            final_past_key_values.append((filtered_key, filtered_value))
    else:
        final_past_key_values = list(past_key_values)
    ##### Only keep past_key_values at a specific layer #####
    for layer_idx in range(len(final_past_key_values)):
        if layer_idx not in prefix_idx: 
            final_past_key_values[layer_idx] = (None, None)   
    return tuple(final_past_key_values)

def concatenate_past_key_values(all_past_key_values, prefix_idx, group_indices=None, filter_idx_list=None):
    # Initialize the combined past_key_values
    num_layers = len(all_past_key_values[0])
    combined = []
    
    for layer_idx in range(num_layers):
        if layer_idx not in prefix_idx:
            combined.append((None, None))
            continue
            
        # Get all key tensors and all value tensors for this layer
        layer_keys = []
        layer_values = []
        
        for i, past_kv in enumerate(all_past_key_values):
            if past_kv[layer_idx][0] is not None:  # Check if layer was kept
                if filter_idx_list is not None:
                    # print(past_kv[layer_idx][0].shape)
                    # print(filter_idx_list[i])
                    # layer_keys.append(past_kv[layer_idx][0])
                    # layer_values.append(past_kv[layer_idx][1])
                    layer_keys.append(past_kv[layer_idx][0][:, :, filter_idx_list[i], :])
                    layer_values.append(past_kv[layer_idx][1][:, :, filter_idx_list[i], :])
                else:
                    layer_keys.append(past_kv[layer_idx][0])
                    layer_values.append(past_kv[layer_idx][1])
        
        # Concatenate along sequence length dimension (dim=2)
        combined_keys = torch.cat(layer_keys, dim=2)
        combined_values = torch.cat(layer_values, dim=2)
        if group_indices is not None:
            group_keys = []
            group_values = []
            for indices in group_indices.values():
                #print('indices:',list(indices))
                group_keys.append(combined_keys[:, :, list(indices), :].mean(dim=2, keepdim=True))
                group_values.append(combined_values[:, :, list(indices), :].mean(dim=2, keepdim=True))
            group_keys = torch.cat(group_keys, dim=2)
            group_values = torch.cat(group_values, dim=2)
            combined.append((group_keys, group_values))
        else:
            combined.append((combined_keys, combined_values))
    
    return tuple(combined)

def concatenate_past_key_values_textimg(all_past_key_values, prefix_idx):
    prefix_kvs_img = all_past_key_values[0]
    prefix_kvs_text = all_past_key_values[1]
    # Initialize the combined past_key_values
    num_layers = len(prefix_kvs_img[0])
    combined = []
    
    for layer_idx in range(num_layers):
        if layer_idx not in prefix_idx:
            combined.append((None, None))
            continue
            
        # Get all key tensors and all value tensors for this layer
        layer_keys = []
        layer_values = []
        
        for pair_idx, img_pair in enumerate(prefix_kvs_img):
            if img_pair[layer_idx][0] is not None:  # Check if layer was kept
                text_pair = prefix_kvs_text[pair_idx]
                imgtext_k = torch.cat([img_pair[layer_idx][0], text_pair[layer_idx][0]], dim=2)
                layer_keys.append(imgtext_k)
                imgtext_v = torch.cat([img_pair[layer_idx][1], text_pair[layer_idx][1]], dim=2)
                layer_values.append(imgtext_v)
        
        # Concatenate along sequence length dimension (dim=2)
        combined_keys = torch.cat(layer_keys, dim=2)
        #combined_keys = compress_hidden_states(combined_keys)
        combined_values = torch.cat(layer_values, dim=2)
        combined.append((combined_keys, combined_values))
    
    return tuple(combined)


def generate_response_with_kv(processor, model, image, prompt, prefix_kv):
    conversation = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": prompt},
                {"type": "image"}
            ],
        }
    ]
    formatted_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
    inputs = processor(images=image, text=formatted_prompt, return_tensors="pt")
    try:
        output = model.generate(**inputs, 
                                max_new_tokens=10**3,
                                past_key_values=prefix_kv,
                                use_cache=True)
    except:
        model = model.model
        output = model.generate(**inputs, 
                                max_new_tokens=10**3,
                                past_key_values=prefix_kv,
                                use_cache=True)
    return processor.decode(output[0], skip_special_tokens=True)

def large_weight_idx(outputs, custom_labels, prompt_start_idx=0, prompt_end_idx=100, top_num=5, filter_stop_words=True, random=False):
    # attentions = outputs.attentions
    # ## Extract attention from the last layer 
    # attention_matrix = attentions[-1] # Last layer
    # last_layer_attention = attention_matrix[0].cpu().numpy()
    # last_token_idx = last_layer_attention.shape[-1] - 1
    # last_layer_attention = last_layer_attention[:, last_token_idx, 1:-6] # remove </s> and ending hint tokens
    # #visualize_attention_weight(last_layer_attention, input_ids, path='attention_mat.jpg')
    
    # avg_attention = np.mean(last_layer_attention, axis=0) 
    
    if filter_stop_words:
        stop_words = {"a", "of", "to", "on", "and", "or", "the", "with", "is", "are",
                    "", ",", "'", ".", ":", ";", "(", ")", "[", "]", "{", "}", "!", "?", "*",
                    }
    else:
        stop_words = {}
    # # Step 1: Create a filtered list of valid tokens
    # valid_tokens = [(custom_labels[1:-6][i], avg_attention[i])  
    #                 for i in range(len(avg_attention))  
    #                 if (custom_labels[1:-6][i].lower() not in stop_words)
    #                 and i>=prompt_start_idx
    #                 and i<=prompt_end_idx]  # Exclude stop words
    # # # Step 2: Sort by attention weight and get the top `top_num`
    # # valid_tokens.sort(key=lambda x: x[1], reverse=True)  # Sort by attention score (descending)
    # # top_tokens = valid_tokens[:top_num]  
    # # top_indices = np.argsort(avg_attention)[-top_num:][::-1]  # Get top indices (highest attention)
    # # print("\nTop Tokens with Highest Attention (Excluding Stopwords):")
    # # for token, score in top_tokens:
    # #     print(f"Token: {token}, Attention Score: {score:.4f}")
    # # final_indices = [custom_labels.index(token) for token, _ in top_tokens]
    # # Filter tokens with attention score > 0.01
    # threshold = 0
    # filtered_tokens = [x for x in valid_tokens if (x[1] > threshold)]
    # # Sort filtered tokens by attention weight (descending)
    # filtered_tokens.sort(key=lambda x: x[1], reverse=True)

    # print("\nTokens with Attention Score > 0:")
    # for token, score in filtered_tokens:
    #     print(f"Token: {token}, Attention Score: {score:.4f}")
    #### Temp Version
    filtered_tokens = [(custom_labels[i], 0)  
                    for i in range(len(custom_labels))  
                    if (custom_labels[i].lower() not in stop_words)
                    # and i>=prompt_start_idx
                    # and i<=prompt_end_idx
                    ]  # Exclude stop words
    # Get indices for the filtered tokens
    final_indices = [custom_labels.index(token)+prompt_start_idx for token, _ in filtered_tokens][:10]
    # if random:
    #     final_indices = np.random.choice(range(last_layer_attention.shape[-1]), size=top_num, replace=False).tolist()
    #return final_indices, attentions
    return final_indices, None

def large_weight_idx_img(outputs, top_num=5, random=False):
    attentions = outputs.attentions
    ## Extract attention from the last layer 
    attention_matrix = attentions[-1] # Last layer
    last_layer_attention = attention_matrix[0].cpu().numpy()
    last_layer_attention = np.mean(last_layer_attention, axis=1) 
    avg_attention = np.mean(last_layer_attention, axis=0) 
    # Step 2: Sort by attention weight and get the top `top_num`
    sorted_indices = np.argsort(avg_attention)[::-1]
    top_indices = sorted_indices[:top_num]
    top_weights = avg_attention[top_indices]
    # print("\nTop Tokens with Highest Attention (Excluding Stopwords):")
    # for indice in top_indices:
    #     print(f"Indice: {indice}, Attention Score: {avg_attention[indice]:.4f}")
    if random:
        top_indices = np.random.choice(range(last_layer_attention.shape[-1]), size=top_num, replace=False).tolist()
    top_indices = np.sort(np.array(top_indices))
    return top_indices, last_layer_attention

def visualize_attention_weight(last_layer_attention, custom_labels, path='attention_mat.jpg'):
    head_num = last_layer_attention.shape[0]
    # Plot heatmap
    plt.imshow(last_layer_attention.T, cmap="viridis")
    plt.colorbar()
    plt.yticks(range(len(custom_labels)-7), custom_labels[1:-6])
    plt.xticks(range(head_num), range(head_num))
    plt.title("Attention Weights (Last Layer)")
    plt.savefig(path)

# Download and load the image
def pool_image(image, pooling_rounds=1):
    # Load image
    original_size = image.size
    #print(f"Original image size: {original_size}")

    # Convert to tensor
    transform = transforms.Compose([
        transforms.ToTensor()  # This converts PIL Image to tensor and normalizes to [0, 1]
    ])
    img_tensor = transform(image).unsqueeze(0)  # Add batch dimension [1, 3, H, W]

    # Method 1: Using nn.AvgPool2d
    pool = nn.AvgPool2d(kernel_size=2, stride=2)
    for _ in range(pooling_rounds):
        img_tensor = pool(img_tensor)

    # Convert back to PIL Image
    pooled_image = transforms.ToPILImage()(img_tensor.squeeze(0))
    #print(f"Pooled image size: {pooled_image.size}")
    return pooled_image

def load_image_from_url(url):
    image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
    return image
def calculate_image_sequence_length(image, patch_size=32):
    # Get image dimensions
    width, height = image.size
    
    # Calculate number of patches
    n_patches_h = height // patch_size
    n_patches_w = width // patch_size
    n_patches = n_patches_h * n_patches_w
    
    print(f"Image size: {width}x{height}")
    print(f"Number of patches (with {patch_size}x{patch_size} patch size):")
    print(f"Height patches: {n_patches_h}")
    print(f"Width patches: {n_patches_w}")
    print(f"Total patches: {n_patches}")
    
if __name__ == "__main__":
    from model_architecture import print_detailed_layers
    # Load model
    model_path = '/data/wenyi/llm_models/llava-1.6'
    processor, tokenizer, model = load_model(model_path)
    #print_detailed_layers(model)
    ####### Generate Response #########
    # Test with a sample image
    # pizza with salad on it
    test_url = "https://static01.nyt.com/images/2021/05/17/dining/as-salad-pizza/merlin_187444374_6d36e40a-9a49-46df-b32f-65c4edad94ca-threeByTwoMediumAt2X.jpg?quality=75&auto=webp"
    image = load_image_from_url(test_url)
    pooled_image = pool_image(image, pooling_rounds=2)
    print("Processing test image...")
    prompt1 = """This is an image of a pizza that appears to be topped with a variety of ingredients. """
    prompt2 = """The pizza has a golden-brown crust and is generously covered with green leafy vegetables, which could be arugula or a similar type of salad greens."""
    prompt3 = """There are also slices of what look like yellow squash or zucchini, and possibly some other vegetables or herbs. The pizza is cut into slices, and some of the toppings have fallen off, revealing the crust underneath. The pizza is placed on a piece of parchment paper, which is sitting on a surface that looks like a marble countertop. The overall presentation suggests a focus on fresh, healthy ingredients, and the pizza might be a vegetarian option."""
    #prompt4 = "zebras and deers standing around and eating the grass"
    
    prefix_kvs_text = [get_past_key_value_text(processor, tokenizer, model, pooled_image, prompt, prefix_idx=[3,4,5], top_tokens=None) for prompt in [prompt1, prompt2, prompt3]]

    # concat_prefix_kvs_text = concatenate_past_key_values(prefix_kvs_text, [3,4,5])
    # response = generate_response_with_kv(processor, model, image, 
    #                                      'Describe the image', 
    #                                      concat_prefix_kvs_text)
    # print(response)
    #get_past_key_value_text(tokenizer, model, prompt4, prefix_idx=[3,4,5], top_tokens=True)
    # import pandas as pd
    # captions = pd.read_csv('/data/wenyi/COCO2017_full/train/captions.csv')