-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutiles.py
executable file
·2329 lines (1920 loc) · 108 KB
/
utiles.py
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
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt
from PIL import Image
from llavanext.mm_utils import tokenizer_image_token, get_model_name_from_path
from torch_kmeans import KMeans
from memory_bank.memory_utils import summarize_memory_event_personality, enter_name, save_local_memory, HfArgumentParser, DataArguments, ModelArguments
from memory_bank.prompt_utils import *
from memory_bank.summarize_memory import LLMClientLLaMA3
from longva.conversation import conv_templates, SeparatorStyle
from transformers import EvalPrediction, Trainer
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline, AutoModel
from sklearn.manifold import TSNE
from sklearn.decomposition import PCA
from sklearn.preprocessing import MinMaxScaler
from sentence_transformers.util import cos_sim
from collections import deque, defaultdict
# from sentence_transformers import SentenceTransformer
# from sentence_transformers.util import cos_sim
# from sentence_transformers.quantization import quantize_embeddings
import random
import math
import time
import numpy as np
import re
import json
import tqdm
import threading
# 定义颜色代码
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
BLUE = "\033[34m"
PURPLE = "\033[35m"
CYAN = "\033[36m"
WHITE = "\033[37m"
RESET = "\033[0m"
class TreeNode:
def __init__(self, centroids, labels=None, depth=0):
self.centroids = centroids
self.labels = labels
self.children = []
self.depth = depth
class MultimodalTreeNode:
def __init__(self, centroids, text, text_distance=None, image_distance=None, labels=None, depth=0):
self.centroids = centroids
self.text = text
self.text_distance = text_distance
self.image_distance = image_distance
self.labels = labels
self.children = []
self.depth = depth
def expand2square(pil_img, background_color):
width, height = pil_img.size
if width == height:
return pil_img
elif width > height:
result = Image.new(pil_img.mode, (width, width), background_color)
result.paste(pil_img, (0, (width - height) // 2))
return result
else:
result = Image.new(pil_img.mode, (height, height), background_color)
result.paste(pil_img, ((height - width) // 2, 0))
return result
def process_images(images, image_processor, model_cfg):
# image_aspect_ratio = getattr(model_cfg, "image_aspect_ratio", None)
new_images = []
for image in images:
# image = expand2square(image, tuple(int(x * 255) for x in image_processor.image_mean))
image = image_processor.preprocess(image, return_tensors="pt")["pixel_values"][0]
new_images.append(image) # [ dim resize_w resize_h ]
if len(images) > 1:
new_images = [torch.stack(new_images, dim=0)] # [num_images dim resize_w resize_h ]
# print("len new_images:{}".format(len(new_images)))
if all(x.shape == new_images[0].shape for x in new_images):
new_images = torch.stack(new_images, dim=0) # num_image num_patches dim resize_w resize_h
# when using "pad" mode and only have one image the new_images tensor dimension is [ 1 dim resize_w resize_h ]
# print("new_images:{}".format(new_images.shape))
return new_images
def compute_gradients(img):
sobel_x = torch.tensor([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], dtype=torch.float32, device=img.device).unsqueeze(0).unsqueeze(0)
sobel_y = torch.tensor([[-1, -2, -1], [0, 0, 0], [1, 2, 1]], dtype=torch.float32, device=img.device).unsqueeze(0).unsqueeze(0)
Ix = F.conv2d(img.unsqueeze(0), sobel_x, padding=1)
Iy = F.conv2d(img.unsqueeze(0), sobel_y, padding=1)
return Ix.squeeze(0), Iy.squeeze(0)
def Optical_flow(last_frame, current_frame, image_processor, model, threshold, device='cuda:0'):
window_size = 5
# threshold = 0.21 # 设置光流法阈值
eps = 1e-6
assert last_frame is not None
current_image_tensor = process_images([Image.fromarray(current_frame)], image_processor, model.config).to(device).squeeze(0)
# [1 3 h w]
last_image_tensor = process_images([Image.fromarray(last_frame)], image_processor, model.config).to(device).squeeze(0)
if current_image_tensor.dim() == 3:
current_image_tensor_gray = 0.2989 * current_image_tensor[0, :, :] + 0.5870 * current_image_tensor[1, :, :] + 0.1140 * current_image_tensor[2, :, :]
last_image_tensor_gray = 0.2989 * last_image_tensor[0, :, :] + 0.5870 * last_image_tensor[1, :, :] + 0.1140 * last_image_tensor[2, :, :]
else:
current_image_tensor_gray = current_image_tensor
last_image_tensor_gray = last_image_tensor
# Compute gradients on GPU
Ix, Iy = compute_gradients(last_image_tensor_gray.unsqueeze(0))
It = current_image_tensor_gray - last_image_tensor_gray
# print("Ix:{}, Iy:{}, It:{}".format(Ix.shape, Iy.shape, It.shape))
# Initialize flow vectors on GPU
u = torch.zeros_like(Ix, device=Ix.device)
v = torch.zeros_like(Ix, device=Ix.device)
w = window_size // 2
# Prepare for batch processing
Ix_windows = F.unfold(Ix.unsqueeze(0), kernel_size=(window_size, window_size)).transpose(1, 2)
Iy_windows = F.unfold(Iy.unsqueeze(0), kernel_size=(window_size, window_size)).transpose(1, 2)
It_windows = F.unfold(It.unsqueeze(0).unsqueeze(0), kernel_size=(window_size, window_size)).transpose(1, 2)
A = torch.stack((Ix_windows, Iy_windows), dim=3)
b = -It_windows
# # Solve for flow vectors in batch
# nu = torch.linalg.solve(A_T_A, A_T_b) # 出现非奇异解,导致无法计算出结果
# Using Lucas-Karthy method
# Reshape to (batch_size, num_windows, window_size*window_size, 2)
A = A.view(A.size(0), -1, window_size*window_size, 2)
b = b.view(b.size(0), -1, window_size*window_size)
# Compute A^T * A and A^T * b
A_T_A = torch.matmul(A.transpose(2, 3), A)
A_T_b = torch.matmul(A.transpose(2, 3), b.unsqueeze(3)).squeeze(3)
# Add regularization term to A_T_A
eye = torch.eye(A_T_A.size(-1), device=A_T_A.device)
A_T_A += eps * eye
# Solve for flow vectors in batch
nu = torch.linalg.solve(A_T_A, A_T_b)
u_flat = nu[:, :, 0]
v_flat = nu[:, :, 1]
# Reshape flow vectors to image shape
# Calculate correct output size for fold
output_height = Ix.shape[1] - window_size + 1
output_width = Ix.shape[2] - window_size + 1
# Ensure the data is suitable for fold operation
u_flat = u_flat.view(1, output_height, output_width)
v_flat = v_flat.view(1, output_height, output_width)
# Compute magnitude of flow vectors
mag = torch.sqrt(u_flat**2 + u_flat**2)
mean_mag = mag.mean().item()
del Ix_windows
del Iy_windows
del It_windows
del current_image_tensor_gray
del last_image_tensor_gray
del last_image_tensor
if mean_mag > threshold:
return True, mean_mag, current_image_tensor
else:
return False, mean_mag, current_image_tensor
def SSIM(last_frame, current_frame, image_processor, model, threshold, window_size=11, sigma=1.5, device='cuda'):
# 将图像转换为张量,并将其发送到指定的设备上
# current_image_tensor_gray = img1.to(device)
# last_image_tensor_gray = img2.to(device)
assert last_frame is not None
current_image_tensor = process_images([Image.fromarray(current_frame)], image_processor, model.config).cuda().squeeze(0)
# [1 3 h w]
last_image_tensor = process_images([Image.fromarray(last_frame)], image_processor, model.config).cuda().squeeze(0)
if current_image_tensor.dim() == 3:
current_image_tensor_gray = 0.2989 * current_image_tensor[0, :, :] + 0.5870 * current_image_tensor[1, :, :] + 0.1140 * current_image_tensor[2, :, :]
last_image_tensor_gray = 0.2989 * last_image_tensor[0, :, :] + 0.5870 * last_image_tensor[1, :, :] + 0.1140 * last_image_tensor[2, :, :]
else:
current_image_tensor_gray = current_image_tensor
last_image_tensor_gray = last_image_tensor
# print("current_image_tensor_gray:{}".format(current_image_tensor_gray.shape))
current_image_tensor_gray = current_image_tensor_gray.unsqueeze(0).unsqueeze(0)
last_image_tensor_gray = last_image_tensor_gray.unsqueeze(0).unsqueeze(0)
# # 函数用于计算局部的高斯权重
# def gaussian(window_size, sigma):
# # gauss = torch.Tensor([torch.exp(-(x - window_size//2)**2/float(2*sigma**2)) for x in range(window_size)])
# gauss = torch.Tensor([torch.exp(-(x - window_size//2)**2 / (2*sigma**2)) for x in range(window_size)])
# return gauss/gauss.sum()
def gaussian(window_size, sigma):
gauss = torch.Tensor([torch.exp(torch.tensor(-(x - window_size//2)**2 / (2*sigma**2))) for x in range(window_size)])
return gauss / gauss.sum()
# 计算 SSIM 的局部高斯权重
# window = gaussian(window_size, sigma).unsqueeze(1).unsqueeze(2).to(device)
# 计算高斯核
_1D_window = gaussian(window_size, sigma).unsqueeze(1)
_2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)
window = _2D_window.to(device)
# print("window:{}".format(window.shape))
# print("current_image_tensor_gray:{}".format(current_image_tensor_gray.shape))
# assert 1==2
# 计算均值
mu1 = F.conv2d(input=current_image_tensor_gray, weight=window, stride=1, padding=window_size//2)
mu2 = F.conv2d(input=last_image_tensor_gray, weight=window, stride=1, padding=window_size//2)
# 计算方差
mu1_sq = mu1.pow(2)
mu2_sq = mu2.pow(2)
mu1_mu2 = mu1 * mu2
# 计算图像的标准差
sigma1_sq = F.conv2d(input=current_image_tensor_gray * current_image_tensor_gray, weight=window, stride=1, padding=window_size//2) - mu1_sq
sigma2_sq = F.conv2d(input=last_image_tensor_gray * last_image_tensor_gray, weight=window, stride=1, padding=window_size//2) - mu2_sq
sigma12 = F.conv2d(input=current_image_tensor_gray * last_image_tensor_gray, weight=window, stride=1, padding=window_size//2) - mu1_mu2
# 常数 C1 和 C2
C1 = (0.01)**2
C2 = (0.03)**2
# 计算 SSIM
ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))
# 对 SSIM 进行平均池化,得到最终的 SSIM 分数
ssim_score = ssim_map.mean()
# return ssim_score
if ssim_score > threshold:
return True, ssim_score, current_image_tensor
else:
return False, ssim_score, current_image_tensor
def calculate_forgetting_probabilities(length, tau=10):
"""根据艾宾浩斯遗忘曲线计算每个位置的遗忘概率"""
t = np.arange(length)
R_t = np.exp(-t / tau)
return R_t / R_t.sum()
def select_data_without_replacement(queue, probabilities, selection_length=10):
"""根据遗忘概率从队列中选择数据,确保没有重复"""
indices = np.arange(len(queue))
selected_indices = np.random.choice(indices, size=selection_length, replace=False, p=probabilities)
selected_data = [queue[idx] for idx in selected_indices]
return selected_data
def compress_spatial_features(feature_list, compress_rate):
comperssed_spatial_features = []
assert len(feature_list) > 0, "compressed feature must larger then 0"
all_features = torch.cat(feature_list)
patch_size = round(math.sqrt(all_features.shape[1]))
# print(fea)
B, SEQ, DIM = all_features.shape
# print("all feature:{}".format(all_features.shape))
assert patch_size * patch_size == feature_list[0].shape[1], f"For ViT feature map, {patch_size}*{patch_size}={patch_size**2} != {all_features.shape[1]}"
all_features = all_features.reshape(-1, patch_size, patch_size, DIM).permute(0, 3, 1, 2)
# print("all feature:{}".format(all_features.shape))
pooled_features = F.avg_pool2d(all_features, (compress_rate, compress_rate)).permute(0, 2, 3, 1)
pooled_features = pooled_features.reshape(B, -1, DIM)
# print("pooled features:{}".format(pooled_features.shape))
# for feature in feature_list:
# feature = feature.reshape(-1, patch_size, patch_size, DIM).permute(0, 3, 1, 2)
# feature = F.avg_pool2d(feature, (patch_size // compress_rate, patch_size // compress_rate))
# feature = feature.permute(0, 2, 3, 1)
# feature = feature.reshape(B, -1, DIM) # 1 comperss*comperss DIM
comperssed_spatial_features = list(torch.split(pooled_features, 1))
return comperssed_spatial_features
def weighted_kmeans_feature(img_feature, video_max_frames, weights=None):
if weights is None:
weights = torch.ones(img_feature.size(0), dtype=img_feature.dtype, device=img_feature.device)
def weighted_kmeans_torch(X, num_clusters, weights=None, distance='euclidean', tol=1e-4, max_iter=10):
indices = torch.randperm(X.size(0), device=X.device)[:num_clusters]
centroids = X[indices]
for i in range(max_iter):
if distance == 'euclidean':
dists = ((X.unsqueeze(1) - centroids.unsqueeze(0)) ** 2).sum(dim=2).sqrt()
else:
raise NotImplementedError("Only Euclidean distance is supported yet")
labels = torch.argmin(dists, dim=1)
weighted_sum = torch.zeros_like(centroids)
weights_sum = torch.zeros(num_clusters, dtype=X.dtype, device=X.device)
for j in range(num_clusters):
cluster_mask = labels == j
weighted_sum[j] = torch.sum(weights[cluster_mask, None] * X[cluster_mask], dim=0)
weights_sum[j] = torch.sum(weights[cluster_mask])
mask = weights_sum > 0
new_centroids = torch.zeros_like(weighted_sum)
new_centroids[mask] = weighted_sum[mask] / weights_sum[mask, None]
if mask.sum() < num_clusters: # fix nan centroids
new_centroids[~mask] = torch.stack([X[random.randint(0, X.size(0) - 1)] for _ in range(num_clusters - mask.sum())])
diff = torch.norm(centroids - new_centroids, dim=1).sum()
if diff < tol:
break
centroids = new_centroids
return centroids, labels, weights_sum, i
T, P, D = img_feature.shape
T0 = video_max_frames
if T <= T0:
return img_feature, weights, [[[i] for i in range(T)]]
X = img_feature.view(T, -1) # [T, P, D]
centroids, labels, weights, exit_step = weighted_kmeans_torch(X, T0, weights)
reduced_feature = centroids.view(T0, P, D)
# print(f'Note: perform weighted kmeans feature {img_feature.shape} to {reduced_feature.shape}, exit at step={exit_step}') # actually, K=T0
step_indices = [[] for _ in range(T0)]
for i in range(T0):
step_indices[i] = [j for j in range(T) if labels[j] == i]
return reduced_feature, labels
def k_means_clustering(X, num_clusters, max_iter=10):
"""对输入的张量进行 K-means 聚类"""
indices = torch.randperm(X.size(0), device=X.device)[:num_clusters]
centroids = X[indices]
for i in range(max_iter):
dists = ((X.unsqueeze(1) - centroids.unsqueeze(0)) ** 2).sum(dim=2).sqrt()
labels = torch.argmin(dists, dim=1)
new_centroids = torch.stack([X[labels == j].mean(dim=0) for j in range(num_clusters)])
if torch.allclose(new_centroids, centroids):
break
centroids = new_centroids
return centroids, labels
def building_memory_tree(feature_list, compress_rate, chunk_size, num_clusters, depth):
time_1 = time.time()
feature_list = compress_spatial_features(feature_list, compress_rate)
time_2 = time.time()
chunk_feature_list = [feature_list[i:i + chunk_size] for i in range(0, len(feature_list), chunk_size)]
time_3 = time.time()
# 对每个子序列进行 K-means 聚类
nodes = []
for sub_seq in chunk_feature_list:
sub_seq_feature = torch.cat(sub_seq, dim=0)
# print(sub_seq_feature.shape) #
[reduced_feature, weights, step_indices, labels] = weighted_kmeans_feature(sub_seq_feature, num_clusters)
node = TreeNode(reduced_feature, labels, depth)
nodes.append(node)
time_4 = time.time() # 主要时间花销发生在这个一步
# 对每个节点的聚类中心递归地构建树
for node in nodes:
if node.centroids.size(0) > num_clusters:
child_node = building_memory_tree(node.centroids, compress_rate, chunk_size, num_clusters, depth + 1)
node.children.append(child_node)
time_5 = time.time()
print("time spend:{}/{}/{}/{}".format((time_2-time_1), (time_3-time_2), (time_4-time_3), (time_5-time_4)))
return nodes
def buildingd_memory_tree_buttom_up(k_means_chunk_feature_list, num_clusters, interval):
"""从底层到顶层构建树状结构"""
nodes = [TreeNode(tensor, depth=0) for tensor in k_means_chunk_feature_list]
while len(nodes) > 1:
new_nodes = []
for i in range(0, len(nodes), interval):
chunk = nodes[i:i + interval]
centroids_list = [node.centroids for node in chunk] # len 10 144 1024
combined_centroids = torch.cat(centroids_list, dim=0) #
if combined_centroids.shape[0] > num_clusters:
new_centroids, labels = weighted_kmeans_feature(combined_centroids, num_clusters)
else:
new_centroids = combined_centroids
new_node = TreeNode(new_centroids, depth=chunk[0].depth + 1)
for j, node in enumerate(chunk):
new_node.children.append(node)
new_nodes.append(new_node)
nodes = new_nodes
return nodes[0]
def buildingd_memory_tree_buttom_up_with_summarize_token(k_means_chunk_feature_list, num_clusters, interval, summarizer, input_ids, tokenizer, chunked_feature_list):
def make_summary_prompt(caption_list):
order = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth"]
new_caption =[]
for index, caption in enumerate(caption_list):
new_caption.append("The caption of the {} video clip is:{} \n".format(order[index], caption))
qs = " ".join(new_caption)
qs = "You need to write a summary of the following, including as many key details as possible into one sentence." + qs
conv = conv_templates["qwen_1_5_summarize"].copy()
conv.append_message(conv.roles[0], qs)
conv.append_message(conv.roles[1], None)
summarize_prompt = conv.get_prompt()
# print(question)
# captioning_input_ids = tokenizer_image_token(captioning_prompt, summarizer_tokenzier, IMAGE_TOKEN_INDEX, return_tensors='pt')
summarize_ids = torch.tensor(tokenizer(summarize_prompt).input_ids , dtype=torch.long)
summarize_ids = summarize_ids.unsqueeze(0).cuda()
return summarize_ids
"""从底层到顶层构建树状结构"""
# base_captions = [summarizer.]
output_list = [] # prepare summary
for chunk_feature in chunked_feature_list: # len
dimension = chunk_feature[0].shape[-1]
chunk_feature = torch.cat(chunk_feature, dim=0).reshape(-1, dimension)
with torch.no_grad():
output_ids = summarizer.generate_with_image_embedding(
input_ids,
image_embeddings=[chunk_feature],
modalities=["video"],
# question_ids=ques_ids,
# modalities="image",
do_sample=True ,
temperature=0.1,
top_p=None,
num_beams=1,
max_new_tokens=128,
use_cache=False)
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
output_list.append(outputs)
nodes = [MultimodalTreeNode(tensor, text, depth=0) for (tensor, text) in zip(k_means_chunk_feature_list, output_list)]
while len(nodes) > 1:
new_nodes = []
for i in range(0, len(nodes), interval):
chunk = nodes[i:i + interval]
centroids_list = [node.centroids for node in chunk] # len 10 144 1024
caption_list = output_list[i:i+interval]
combined_centroids = torch.cat(centroids_list, dim=0) #
if combined_centroids.shape[0] > num_clusters:
new_centroids, labels = weighted_kmeans_feature(combined_centroids, num_clusters)
else:
new_centroids = combined_centroids
summarize_ids = make_summary_prompt(caption_list)
# making summarize for tree model
with torch.no_grad():
output_ids = summarizer.generate_with_image_embedding(
summarize_ids,
image_embeddings= None,
modalities=["video"],
# question_ids=ques_ids,
# modalities="image",
do_sample=True ,
temperature=0.1,
top_p=None,
num_beams=1,
max_new_tokens=256,
use_cache=False)
summarize_text = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
new_node = MultimodalTreeNode(new_centroids, summarize_text, depth=chunk[0].depth + 1)
for j, node in enumerate(chunk):
new_node.children.append(node)
new_nodes.append(new_node)
nodes = new_nodes
return nodes[0]
def fast_building_memory_tree_summarize_token(k_means_chunk_feature_list, num_clusters, interval, summarizer, input_ids, tokenizer, chunked_feature_list, existing_tree=None):
def print_tree_x(node, indent=0):
"""打印树状结构"""
if isinstance(node, list):
for single_node in node:
print(" " * indent + f"{RED}Depth{RESET}: {single_node.depth}, {RED}Centroids{RESET}: {single_node.centroids.shape}, {RED}Text{RESET} :{single_node.text}")
if single_node.children is not None:
for child in single_node.children:
print_tree_x(child, indent + 4)
else:
print(" " * indent + f"{RED}Depth{RESET}: {node.depth}, {RED}Centroids{RESET}: {node.centroids.shape}, {RED}Text{RESET} :{node.text}")
for child in node.children:
print_tree_x(child, indent + 4)
def make_summary_prompt(caption_list):
order = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth"]
new_caption =[]
for index, caption in enumerate(caption_list):
new_caption.append("The caption of the {} video clip is:{} \n".format(order[index], caption))
qs = " ".join(new_caption)
qs = "You need to write a summary of the following, including as many key details as possible into one sentence." + qs
conv = conv_templates["qwen_1_5_summarize"].copy()
conv.append_message(conv.roles[0], qs)
conv.append_message(conv.roles[1], None)
summarize_prompt = conv.get_prompt()
# print(question)
# captioning_input_ids = tokenizer_image_token(captioning_prompt, summarizer_tokenzier, IMAGE_TOKEN_INDEX, return_tensors='pt')
summarize_ids = torch.tensor(tokenizer(summarize_prompt).input_ids , dtype=torch.long)
summarize_ids = summarize_ids.unsqueeze(0)
return summarize_ids
def get_summarize_depth(nodes, interval):
depth_count = defaultdict(int)
depth_count.clear()
for node in nodes:
depth_count[node.depth] += 1
# 找出最高优先级的深度
max_depth = max(depth_count.keys())
for depth in range(max_depth, -1, -1):
if depth_count[depth] % interval == 0 and depth_count[depth] > 0: # 判断目前需要使用的深度
return depth, depth_count
return 0 ,depth_count
output_list = [] # prepare summary
for chunk_feature in chunked_feature_list:
dimension = chunk_feature[0].shape[-1]
chunk_feature = torch.cat(chunk_feature, dim=0).reshape(-1, dimension).to(summarizer.device)
# print("chunk_feature", chunk_feature.shape)
# time.sleep(2) # 模拟计算时间
with torch.no_grad():
output_ids = summarizer.generate_with_image_embedding(
input_ids.to(summarizer.device),
image_embeddings=[chunk_feature],
modalities=["video"],
# question_ids=ques_ids,
# modalities="image",
do_sample=True ,
temperature=0.1,
top_p=None,
# num_beams=1,
max_new_tokens=128,
use_cache=False)
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
output_list.append(outputs)
nodes = [MultimodalTreeNode(tensor, text, depth=0) for (tensor, text) in zip(k_means_chunk_feature_list, output_list)]
if existing_tree:
# nodes.append(existing_tree)
nodes = existing_tree + nodes
summarize_depth, depth_count = get_summarize_depth(nodes, interval)
start_index = next((index for index, node in enumerate(nodes) if node.depth == summarize_depth), None)
chunk_length = len([x for x in nodes if x.depth == summarize_depth])
print("summarize_depth:{}/ start_index:{}/ chunk_length:{} / len(nodes):{}".format(summarize_depth, start_index, chunk_length, len(nodes)))
# if chunk_length % interval >= 0 and len(nodes) > 0: # for first
if chunk_length % interval >= 0 and len(nodes) > 0 and chunk_length >= interval:
print("building summarize node for {} clip".format(start_index + 1))
# for i in range(0 + clip * interval, len(nodes), interval):
# chunk = nodes[(clip - 1) * interval : (clip - 1) * interval + interval]
chunk = nodes[start_index: start_index + interval]
centroids_list = [node.centroids for node in chunk]
caption_list = [node.text for node in chunk]
combined_centroids = torch.cat(centroids_list, dim=0)
if combined_centroids.shape[0] > num_clusters:
new_centroids, labels = weighted_kmeans_feature(combined_centroids, num_clusters)
else:
new_centroids = combined_centroids
summarize_ids = make_summary_prompt(caption_list)
with torch.no_grad():
output_ids = summarizer.generate_with_image_embedding(
summarize_ids.to(summarizer.device),
image_embeddings= None,
modalities=["video"],
# question_ids=ques_ids,
# modalities="image",
do_sample=True ,
temperature=0.1,
top_p=None,
# num_beams=1,
max_new_tokens=256,
use_cache=False)
summarize_text = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
# time.sleep(2) # 模拟计算时间
new_node = MultimodalTreeNode(new_centroids, summarize_text, depth=chunk[0].depth + 1)
for j, node in enumerate(chunk):
new_node.children.append(node) # 将之前的list全部进行总结
nodes[start_index: start_index + interval] = [new_node]
print_tree_x(nodes)
return nodes
else:
print_tree_x(nodes)
return nodes
def search_tree_multi_modal_with_embedding(node, query, image_embedding, model, tokenizer, top_k=1):
"""在树中沿着每一层相似度最高的分支不断寻找,并将每一层对应的特征都提取出来"""
# The model works really well with cls pooling (default) but also with mean pooling.
def pooling(outputs: torch.Tensor, inputs, strategy: str = 'cls') -> np.ndarray:
if strategy == 'cls':
outputs = outputs[:, 0]
elif strategy == 'mean':
outputs = torch.sum(
outputs * inputs["attention_mask"][:, :, None], dim=1) / torch.sum(inputs["attention_mask"])
else:
raise NotImplementedError
return outputs.detach().cpu().numpy()
path_features = []
path_text = []
# x = torch.nn.functional.normalize(torch.cat([query, image_embedding], dim=0), p=2, dim=0)
print("Question:{}".format(query))
query_ids = tokenizer(query, padding=True, return_tensors='pt')
for k, v in query_ids.items():
query_ids[k] = v.cuda()
outputs_1 = model(**query_ids).last_hidden_state
query_embedding = pooling(outputs_1, query_ids, 'cls')
current_node = node
while current_node.children:
best_child_index = None
best_sim = 0
# 计算查询张量与每个子节点的所有特征张量之间的相似度
for i, child in enumerate(current_node.children):
# distances = torch.cdist(query.unsqueeze(0), child.centroids.view(-1, query.size(-1)).unsqueeze(0)).squeeze(0)
# text_tensor = torch.tensor(tokenizer(current_node.text).input_ids , dtype=torch.float16).unsqueeze(0).cuda()
print("text:{}".format(child.text))
text_ids = tokenizer(child.text, padding=True, return_tensors='pt')
for k, v in text_ids.items():
text_ids[k] = v.cuda()
outputs_2 = model(**text_ids).last_hidden_state
text_embedding = pooling(outputs_2, text_ids, 'cls')
# distance_text = (x @ torch.nn.functional.normalize(text_embeddings, p=2, dim=0).permute(1, 0)).mean(0).mean(0) # remember to normalize the embedding
# distance_image = (x @ torch.nn.functional.normalize(child.centroids.view(-1, query.size(-1)), p=2, dim=0).permute(1, 0)).mean(0).mean(0)
sim = cos_sim(text_embedding[0], query_embedding[0])
# current_node.text_distance = distance_text
# current_node.image_distance = distance_image
print(f"{RED}sim{RESET}:{sim} in depth:{current_node.depth} {i} child")
# distance = (query @ child.centroids.view(-1, query.size(-1)).permute(1, 0)).sum(0).sum(0) # len x 1024 @ len x 1024 = len x len
# min_distance, _ = distances.min(dim=0)
if sim > best_sim:
best_sim = sim
best_child_index = i
else:
continue
print(f"{BLUE}best_child_index:{RESET}{best_child_index}")
# 选择相似度最高的子节点
path_features.append(current_node.children[best_child_index].centroids)
path_text.append(current_node.children[best_child_index].text)
current_node = current_node.children[best_child_index]
# path_features.append(current_node.centroids) # 添加最底层节点的特征
# path_text.append(current_node.text)
return path_features, path_text
def fast_search_tree_multi_modal_with_embedding(all_nodes, query, image_embedding, model, tokenizer, top_k=1):
"""在树中沿着每一层相似度最高的分支不断寻找,并将每一层对应的特征都提取出来"""
# The model works really well with cls pooling (default) but also with mean pooling.
def pooling(outputs: torch.Tensor, inputs, strategy: str = 'cls') -> np.ndarray:
if strategy == 'cls':
outputs = outputs[:, 0]
elif strategy == 'mean':
outputs = torch.sum(
outputs * inputs["attention_mask"][:, :, None], dim=1) / torch.sum(inputs["attention_mask"])
else:
raise NotImplementedError
return outputs.detach().cpu().numpy()
path_features = []
path_text = []
redundant_nodes = []
# x = torch.nn.functional.normalize(torch.cat([query, image_embedding], dim=0), p=2, dim=0)
# print("Question:{}".format(query))
query_ids = tokenizer(query, padding=True, return_tensors='pt')
for k, v in query_ids.items():
query_ids[k] = v.cuda()
outputs_1 = model(**query_ids).last_hidden_state
query_embedding = pooling(outputs_1, query_ids, 'cls')
for node in all_nodes:
current_node = node
if current_node.depth == 0:
redundant_nodes.append(node)
else:
while current_node.children :
# if current_node.
best_child_index = None
best_sim = 0
# 计算查询张量与每个子节点的所有特征张量之间的相似度
for i, child in enumerate(current_node.children):
# distances = torch.cdist(query.unsqueeze(0), child.centroids.view(-1, query.size(-1)).unsqueeze(0)).squeeze(0)
# text_tensor = torch.tensor(tokenizer(current_node.text).input_ids , dtype=torch.float16).unsqueeze(0).cuda()
print("text:{}".format(child.text))
text_ids = tokenizer(child.text, padding=True, return_tensors='pt')
for k, v in text_ids.items():
text_ids[k] = v.cuda()
outputs_2 = model(**text_ids).last_hidden_state
text_embedding = pooling(outputs_2, text_ids, 'cls')
# distance_text = (x @ torch.nn.functional.normalize(text_embeddings, p=2, dim=0).permute(1, 0)).mean(0).mean(0) # remember to normalize the embedding
# distance_image = (x @ torch.nn.functional.normalize(child.centroids.view(-1, query.size(-1)), p=2, dim=0).permute(1, 0)).mean(0).mean(0)
sim = cos_sim(text_embedding[0], query_embedding[0])
# current_node.text_distance = distance_text
# current_node.image_distance = distance_image
print(f"{RED}sim{RESET}:{sim} in depth:{current_node.depth} {i} child")
# distance = (query @ child.centroids.view(-1, query.size(-1)).permute(1, 0)).sum(0).sum(0) # len x 1024 @ len x 1024 = len x len
# min_distance, _ = distances.min(dim=0)
if sim > best_sim:
best_sim = sim
best_child_index = i
else:
continue
print(f"{BLUE}best_child_index:{RESET}{best_child_index}")
# 选择相似度最高的子节点
path_features.append(current_node.children[best_child_index].centroids)
path_text.append(current_node.children[best_child_index].text)
current_node = current_node.children[best_child_index]
# 针对存在的冗余节点再进行一次计算
best_index = 0
best_sim = 0
if len(redundant_nodes) >= 1:
for i,node in enumerate(redundant_nodes):
print("text:{}".format(node.text))
text_ids = tokenizer(node.text, padding=True, return_tensors='pt')
for k, v in text_ids.items():
text_ids[k] = v.cuda()
outputs_2 = model(**text_ids).last_hidden_state
text_embedding = pooling(outputs_2, text_ids, 'cls')
# distance_text = (x @ torch.nn.functional.normalize(text_embeddings, p=2, dim=0).permute(1, 0)).mean(0).mean(0) # remember to normalize the embedding
# distance_image = (x @ torch.nn.functional.normalize(child.centroids.view(-1, query.size(-1)), p=2, dim=0).permute(1, 0)).mean(0).mean(0)
sim = cos_sim(text_embedding[0], query_embedding[0])
# current_node.text_distance = distance_text
# current_node.image_distance = distance_image
print(f"{RED}sim{RESET}:{sim} in depth:{node.depth} {i} child")
# distance = (query @ child.centroids.view(-1, query.size(-1)).permute(1, 0)).sum(0).sum(0) # len x 1024 @ len x 1024 = len x len
# min_distance, _ = distances.min(dim=0)
if sim > best_sim:
best_sim = sim
best_index = i
else:
continue
print(f"{BLUE}best_redundant_index:{RESET}{best_index}")
path_features.append(redundant_nodes[best_index].centroids)
path_text.append(redundant_nodes[best_index].text)
# else:
# # using the nearst feature
# best_index = 0
# print(f"{BLUE}best_redundant_index:{RESET}{best_index}")
# path_features.append(redundant_nodes[best_index].centroids)
# path_text.append(redundant_nodes[best_index].text)
# path_features.append(current_node.centroids) # 添加最底层节点的特征
# path_text.append(current_node.text)
return path_features, path_text
def fast_search_tree_multi_modal_with_embedding_not_repeat(all_nodes, query, image_embedding, model, tokenizer, top_k=1):
"""Search the tree by finding the branch with the highest similarity at each depth and extract the corresponding features."""
def pooling(outputs: torch.Tensor, inputs, strategy: str = 'cls') -> np.ndarray:
if strategy == 'cls':
outputs = outputs[:, 0]
elif strategy == 'mean':
outputs = torch.sum(
outputs * inputs["attention_mask"][:, :, None], dim=1) / torch.sum(inputs["attention_mask"])
else:
raise NotImplementedError
return outputs.detach().cpu().numpy()
def get_query_embedding(query, tokenizer, model):
query_ids = tokenizer(query, padding=True, return_tensors='pt')
for k, v in query_ids.items():
query_ids[k] = v.cuda()
outputs_1 = model(**query_ids).last_hidden_state
return pooling(outputs_1, query_ids, 'cls')
def get_text_embedding(text, tokenizer, model):
text_ids = tokenizer(text, padding=True, return_tensors='pt')
for k, v in text_ids.items():
text_ids[k] = v.cuda()
outputs_2 = model(**text_ids).last_hidden_state
return pooling(outputs_2, text_ids, 'cls')
path_features = []
path_text = []
# Compute the query embedding once
query_embedding = get_query_embedding(query, tokenizer, model)
# Step 1: Find the most similar node with depth > 0
best_node_index = None
best_node_sim = 0
best_node_depth = 0
for i, node in enumerate(all_nodes):
if node.depth > 0: # Consider nodes with depth > 0
text_embedding = get_text_embedding(node.text, tokenizer, model)
sim = cos_sim(text_embedding[0], query_embedding[0])
if sim > best_node_sim:
best_node_sim = sim
best_node_index = i
best_node_depth = node.depth
if best_node_index is None:
print("No nodes with depth > 0 found.")
return path_features, path_text
# Use the most similar node to search its children
current_node = all_nodes[best_node_index]
print(f"Best node index: {best_node_index}, similarity: {best_node_sim}, depth: {best_node_depth}")
while current_node.children:
best_child_index = None
best_child_sim = 0
for i, child in enumerate(current_node.children):
text_embedding = get_text_embedding(child.text, tokenizer, model)
sim = cos_sim(text_embedding[0], query_embedding[0])
if sim > best_child_sim:
best_child_sim = sim
best_child_index = i
if best_child_index is not None:
print(f"Best child index: {best_child_index}, similarity: {best_child_sim}")
path_features.append(current_node.children[best_child_index].centroids)
path_text.append(current_node.children[best_child_index].text)
current_node = current_node.children[best_child_index]
else:
break
return path_features, path_text
def search_tree_multi_modal(node, query, image_embedding, model, tokenizer, top_k=1):
"""在树中沿着每一层相似度最高的分支不断寻找,并将每一层对应的特征都提取出来"""
path_features = []
path_text = []
x = torch.nn.functional.normalize(torch.cat([query, image_embedding], dim=0), p=2, dim=0)
current_node = node
while current_node.children:
best_child_index = None
best_distance = float('inf')
# 计算查询张量与每个子节点的所有特征张量之间的相似度
for i, child in enumerate(current_node.children):
# distances = torch.cdist(query.unsqueeze(0), child.centroids.view(-1, query.size(-1)).unsqueeze(0)).squeeze(0)
# text_tensor = torch.tensor(tokenizer(current_node.text).input_ids , dtype=torch.float16).unsqueeze(0).cuda()
text_ids = tokenizer(current_node.text).input_ids
text_embeddings = model.get_model().embed_tokens(torch.tensor(text_ids, dtype=torch.long, device='cuda')) # num_text_token 4096
distance_text = (x @ torch.nn.functional.normalize(text_embeddings, p=2, dim=0).permute(1, 0)).mean(0).mean(0) # remember to normalize the embedding
distance_image = (x @ torch.nn.functional.normalize(child.centroids.view(-1, query.size(-1)), p=2, dim=0).permute(1, 0)).mean(0).mean(0)
distance = 0.5*distance_text + 0.1*distance_image
# current_node.text_distance = distance_text
# current_node.image_distance = distance_image
print("distance:{}/{}".format(distance_text, distance_image))
# distance = (query @ child.centroids.view(-1, query.size(-1)).permute(1, 0)).sum(0).sum(0) # len x 1024 @ len x 1024 = len x len
# min_distance, _ = distances.min(dim=0)
if distance < best_distance:
best_distance = distance
best_child_index = i
else:
best_child_index = i
continue
# 选择相似度最高的子节点
path_features.append(current_node.centroids)
path_text.append(current_node.text)
current_node = current_node.children[best_child_index]
path_features.append(current_node.centroids) # 添加最底层节点的特征
path_text.append(current_node.text)
return path_features, path_text
def search_tree(node, query, top_k=1):
"""在树中沿着每一层相似度最高的分支不断寻找,并将每一层对应的特征都提取出来"""
path_features = []
current_node = node
while current_node.children:
best_child_index = None
best_distance = float('inf')
# 计算查询张量与每个子节点的所有特征张量之间的相似度
for i, child in enumerate(current_node.children):
# distances = torch.cdist(query.unsqueeze(0), child.centroids.view(-1, query.size(-1)).unsqueeze(0)).squeeze(0)
distance = (query @ child.centroids.view(-1, query.size(-1)).permute(1, 0)).sum(0).sum(0) # len x 1024 @ len x 1024 = len x len
# min_distance, _ = distances.min(dim=0)
if distance < best_distance:
best_distance = distance
best_child_index = i
else:
best_child_index = i
# 选择相似度最高的子节点
path_features.append(current_node.centroids)
current_node = current_node.children[best_child_index]
path_features.append(current_node.centroids) # 添加最底层节点的特征
return path_features
def long_short_memory_update(feature_bank, short_window=10, remember_window=4, tau=10, compress_rate=2, chunk_size=100, num_clusters=10, interval=3 ):
"""
this fucntion is used for updating the long short memory buffer
"""
############# building short memory ###################
assert len(feature_bank) > short_window
waite_FIFO = feature_bank[-short_window:]
assert len(waite_FIFO) > remember_window
forgetting_probs = calculate_forgetting_probabilities(short_window, tau=tau)
short_memory_buffer = select_data_without_replacement(waite_FIFO, forgetting_probs, remember_window)
############# building long memory ###################
if compress_rate > 1:
compressed_spatial_feature_list = compress_spatial_features(feature_bank, compress_rate)
else:
compressed_spatial_feature_list = feature_bank
chunk_feature_list = [compressed_spatial_feature_list[i:i + chunk_size] for i in range(0, len(compressed_spatial_feature_list), chunk_size)] # length100
k_means_chunk_feature_list = [weighted_kmeans_feature(torch.cat(chunk_feature), num_clusters)[0] if len(chunk_feature)> 10 else torch.cat(chunk_feature) for chunk_feature in chunk_feature_list] # length100 最后一个不需要聚类
long_memory_tree = buildingd_memory_tree_buttom_up(k_means_chunk_feature_list, num_clusters, interval)
# print("time spend:{}/{}/{}".format((time_2-time_1), (time_3-time_2), (time_4-time_3)))
return short_memory_buffer, long_memory_tree
def long_short_memory_update_with_summarize(feature_bank, summarizer, tokenizer, input_ids, short_window=10, remember_window=4, tau=10, compress_rate=2, chunk_size=100, num_clusters=10, interval=3 ):
"""
this fucntion is used for updating the long short memory buffer
"""
def print_tree(node, indent=0):
"""打印树状结构"""
print(" " * indent + f"{RED}Depth{RESET}: {node.depth}, {RED}Centroids{RESET}: {node.centroids.shape}, {RED}Text{RESET} :{node.text}")
for child in node.children:
print_tree(child, indent + 4)
############# building short memory ###################
print("<<<<<<< building short memory >>>>>>>>>>>")
if len(feature_bank) > short_window:
# assert len(feature_bank) > short_window
waite_FIFO = feature_bank[-short_window:]
else:
short_window = len(feature_bank)
waite_FIFO = feature_bank
# assert len(waite_FIFO) > remember_window
if remember_window > len(waite_FIFO):
remember_window = len(waite_FIFO)
forgetting_probs = calculate_forgetting_probabilities(short_window, tau=tau)
short_memory_buffer = select_data_without_replacement(waite_FIFO, forgetting_probs, remember_window)
############# building long memory with image captioning ###################
if compress_rate > 1:
compressed_spatial_feature_list = compress_spatial_features(feature_bank, compress_rate) # len
else:
compressed_spatial_feature_list = feature_bank
chunk_feature_list = [compressed_spatial_feature_list[i:i + chunk_size] for i in range(0, len(compressed_spatial_feature_list), chunk_size)] # length100
k_means_chunk_feature_list = [weighted_kmeans_feature(torch.cat(chunk_feature), num_clusters)[0] if len(chunk_feature)> chunk_size else torch.cat(chunk_feature) for chunk_feature in chunk_feature_list] # length100 最后一个不需要聚类
print("<<<<<<< building long memory tree >>>>>>>>>>>")
long_memory_tree = buildingd_memory_tree_buttom_up_with_summarize_token(k_means_chunk_feature_list, num_clusters, interval, summarizer, input_ids, tokenizer, chunk_feature_list)
print_tree(long_memory_tree)
# print("time spend:{}/{}/{}".format((time_2-time_1), (time_3-time_2), (time_4-time_3)))
return short_memory_buffer, long_memory_tree