-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtestcon.py
More file actions
2331 lines (2040 loc) · 101 KB
/
testcon.py
File metadata and controls
2331 lines (2040 loc) · 101 KB
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
from fastcache_paths import ensure_sys_paths, CKPT_DIR, DATASETS_DIR, RESULTS_DIR
ensure_sys_paths()
import os
import torch
# torch.backends.cuda.enable_flash_sdp(True) # 启用 Flash Attention
# torch.backends.cuda.enable_mem_efficient_sdp(False) # 启用内存高效的attention
import json
import sys
import time
import numpy as np
from tqdm import tqdm
import random
from datetime import datetime
from PIL import Image
from pathlib import Path
from dataclasses import dataclass
import statistics
import logging
from typing import List, Dict, Optional, Any
from threading import Thread, Lock, Event
from queue import Queue
from concurrent.futures import ThreadPoolExecutor, as_completed
from torch.utils.data import Dataset, DataLoader
from torch.cuda.amp import autocast
import nvtx
from transformers import LlavaProcessor, LlavaForConditionalGeneration, OffloadedCache
from utils_ccm.module_ccm import KVCacheLinearDecoupleCompressor
from utils_ccm.utils_compress import *
from utils_ccm.utils_schedule import *
from utils_ccm.utils_kvcachePool import *
"""
v1.0
最基本的全流程静态并发系统。测量时长无bug。
v1.1
实现程序上的pd分离管理,测试性能。
于2024.12.26日23点完成。
v1.2
加入测量指标监视器。
于2024.12.29日21点完成。
v1.2.1
comp_mode添加进设置中
v1.2.2
kvc attention mask debug
v1.3
完成c环节独立batching
v1.3.1
指标测量改动。ccm超参最优。
v1.4
结束cuda.syn的同步,由此带来大批涨速。
v2.0
更改使用模式,成为完整的批量使用样例。
v2.1
加入内存管理机制,上限变高,但是内存删除可能引入开销。
v2.2
支持半精度,提升了总体吞吐上限。
v2.3
引入kvcache内存池,查看内存管理程度。
v2.4 *
正式提交。
"""
# @dataclass
# class TestResult:
# method: str # 'orig' 或 'comp'
# latency: List[float]
# success: bool
# valid_tokens: int = 0
# memory_usage: float = 0.0
# request_size: int = 0
# throughput: float = 0.0
# compression_ratio: Optional[float] = None
# compression_time: Optional[float] = None
@dataclass
class TestResult:
method: str
latency: List[float]
success: bool
memory_usage: float
request_id: List[str]
request_size: int
throughput: float
valid_tokens: int
compression_ratio: float = None
compression_time: float = None
timestamps: Dict[str, float] = None # 添加时间戳信息
class PerformanceMonitor:
"""性能监控类"""
def __init__(self):
self.reset()
def reset(self):
self.results = {
'orig': {
'latencies': [],
'throughputs': [],
'memory_usage': [],
'request_id': [],
'request_size': [],
'success_count': 0,
'valid_tokens': 0,
'total_count': 0
},
'comp': {
'latencies': [],
'throughputs': [],
'memory_usage': [],
'request_id': [],
'request_size': [],
'compression_ratios': [],
'compression_times': [],
'success_count': 0,
'valid_tokens': 0,
'total_count': 0
}
}
self.start_time = time.time()
def add_result(self, result: TestResult):
print('result.request_id', result.request_id)
method = result.method
self.results[method]['latencies'].append(result.latency)
self.results[method]['throughputs'].append(result.throughput)
self.results[method]['memory_usage'].append(result.memory_usage)
self.results[method]['request_id'].append(result.request_id)
self.results[method]['request_size'].append(result.request_size)
self.results[method]['valid_tokens'] += int(result.valid_tokens)
self.results[method]['success_count'] += int(result.success)
self.results[method]['total_count'] += 1
# print(result)
if method == 'comp' and result.success:
if result.compression_ratio:
self.results[method]['compression_ratios'].append(result.compression_ratio)
if result.compression_time:
self.results[method]['compression_times'].append(result.compression_time)
def proc_latencies(self):
ttft_list = []
tpot_list = []
for method, data in self.results.items():
if not data['latencies']:
continue
for i in range(len(data['latencies'])):
ttft_list += [data['latencies'][i][1]] * data['request_size'][i]
tpot_list += [data['latencies'][i][2]] * data['request_size'][i]
return ttft_list, tpot_list
def calculate_metrics(self, durations_dict, system_completion_times):
metrics = {}
duration = system_completion_times
for method, data in self.results.items():
if not data['latencies']:
continue
ttft_list, tpot_list = durations_dict['TTFT'], durations_dict['TPOT']
sorted_ttft = sorted(ttft_list)
sorted_tpot = sorted(tpot_list)
total = len(sorted_ttft)
p50_idx = int(total * 0.5)
p90_idx = int(total * 0.90)
p99_idx = min(int(total * 0.99), total - 1)
metrics[method] = {
"total_requests": data['total_count'],
"success_rate": (data['success_count'] / data['total_count'] * 100) if data['total_count'] > 0 else 0,
"requests_per_second": data['total_count'] / duration if duration > 0 else 0,
"avg_ttft": statistics.mean(sorted_ttft),
"median_ttft": sorted_ttft[p50_idx],
"p90_ttft": sorted_ttft[p90_idx],
"p99_ttft": sorted_ttft[p99_idx],
"min_ttft": min(sorted_ttft),
"max_ttft": max(sorted_ttft),
"avg_tpot": statistics.mean(sorted_tpot),
"median_tpot": sorted_tpot[p50_idx],
"p90_tpot": sorted_tpot[p90_idx],
"p99_tpot": sorted_tpot[p99_idx],
"min_tpot": min(sorted_tpot),
"max_tpot": max(sorted_tpot),
"avg_memory_usage": statistics.mean(data['memory_usage']),
"avg_throughput": data['valid_tokens'] / (duration+1e-5),
# "avg_throughput": statistics.mean(data['throughputs']),
"throughput_stddev": statistics.stdev(data['throughputs']) if len(data['throughputs']) > 1 else 0
}
if method == 'comp' and data.get('compression_ratios'):
metrics[method].update({
"avg_compression_ratio": statistics.mean(data['compression_ratios']),
"avg_compression_time": statistics.mean(data['compression_times']) if data[
'compression_times'] else 0
})
return metrics
# def calculate_metrics(self):
# metrics = {}
# duration = time.time() - self.start_time
#
# for method, data in self.results.items():
# if not data['latencies']:
# continue
# ttft_list, tpot_list = self.proc_latencies()
#
# sorted_ttft = sorted(ttft_list)
# sorted_tpot = sorted(tpot_list)
# total = len(sorted_ttft)
# p50_idx = int(total * 0.5)
# p90_idx = int(total * 0.90)
# p99_idx = min(int(total * 0.99), total - 1)
# metrics[method] = {
# "total_requests": data['total_count'],
# "success_rate": (data['success_count'] / data['total_count'] * 100) if data['total_count'] > 0 else 0,
# "requests_per_second": data['total_count'] / duration if duration > 0 else 0,
# "avg_ttft": statistics.mean(sorted_ttft),
# "median_ttft": sorted_ttft[p50_idx],
# "p90_ttft": sorted_ttft[p90_idx],
# "p99_ttft": sorted_ttft[p99_idx],
# "min_ttft": min(sorted_ttft),
# "max_ttft": max(sorted_ttft),
# "avg_tpot": statistics.mean(sorted_tpot),
# "median_tpot": sorted_tpot[p50_idx],
# "p90_tpot": sorted_tpot[p90_idx],
# "p99_tpot": sorted_tpot[p99_idx],
# "min_tpot": min(sorted_tpot),
# "max_tpot": max(sorted_tpot),
# "avg_memory_usage": statistics.mean(data['memory_usage']),
# "avg_throughput": data['valid_tokens'] / duration,
# # "avg_throughput": statistics.mean(data['throughputs']),
# "throughput_stddev": statistics.stdev(data['throughputs']) if len(data['throughputs']) > 1 else 0
# }
#
# if method == 'comp' and data.get('compression_ratios'):
# metrics[method].update({
# "avg_compression_ratio": statistics.mean(data['compression_ratios']),
# "avg_compression_time": statistics.mean(data['compression_times']) if data[
# 'compression_times'] else 0
# })
#
# return metrics
# def calculate_metrics(self):
# metrics = {}
# duration = time.time() - self.start_time
#
# ttft_list, tpot_list = self.proc_latencies()
#
# for method, data in self.results.items():
# if not data['latencies']:
# continue
#
# sorted_latencies = sorted(data['latencies'])
# total = len(sorted_latencies)
# p50_idx = int(total * 0.5)
# p95_idx = int(total * 0.95)
# p99_idx = min(int(total * 0.99), total - 1)
# metrics[method] = {
# "total_requests": data['total_count'],
# "success_rate": (data['success_count'] / data['total_count'] * 100) if data['total_count'] > 0 else 0,
# "requests_per_second": data['total_count'] / duration if duration > 0 else 0,
# "avg_latency": statistics.mean(data['latencies']),
# "median_latency": sorted_latencies[p50_idx],
# "p95_latency": sorted_latencies[p95_idx],
# "p99_latency": sorted_latencies[p99_idx],
# "min_latency": min(sorted_latencies),
# "max_latency": max(sorted_latencies),
# "avg_memory_usage": statistics.mean(data['memory_usage']),
# "avg_throughput": data['valid_tokens']/duration,
# # "avg_throughput": statistics.mean(data['throughputs']),
# "throughput_stddev": statistics.stdev(data['throughputs']) if len(data['throughputs']) > 1 else 0
# }
#
# if method == 'comp' and data.get('compression_ratios'):
# metrics[method].update({
# "avg_compression_ratio": statistics.mean(data['compression_ratios']),
# "avg_compression_time": statistics.mean(data['compression_times']) if data['compression_times'] else 0
# })
#
# return metrics
class ServiceMiddleware:
def __init__(self, max_workers, max_serve_batch_size, min_batch_threshold, std_batch_threshold_decoding,
max_wait_time):
self.max_workers = max_workers
self.max_serve_batch_size = max_serve_batch_size
self.min_batch_threshold = min_batch_threshold
self.max_wait_time = max_wait_time
# self.waiting_queue = Queue()
self.executor = ThreadPoolExecutor(max_workers=max_workers)
self.idle_workers = max_workers
self.idle_lock = Lock()
self.processed_prefill_batches = 0
self.processed_decode_batches = 0
self.system_total_time = 0
self.batch_times = []
self.completion_event = Event()
self.should_stop = False
self.start_time = None
# 新增: 初始化动态调度器
self.scheduler = DynamicScheduler(
max_batch_size=max_serve_batch_size,
min_batch_size=min_batch_threshold,
std_batch_threshold_decoding=std_batch_threshold_decoding,
max_wait_time=max_wait_time
)
# 使用Queue替代原有的waiting_queue
self.waiting_queue = Queue()
class CustomImageTextDataset(Dataset):
"""自定义数据集类"""
def __init__(self, data, processor, max_length=128):
self.data = data
self.processor = processor
self.max_length = max_length
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
dialog_data = self.data[idx]
questions = dialog_data[0]
image_text, image = questions[0]
vision_outputs = self.processor.image_processor(
images=image,
return_tensors="pt"
)
text_outputs = self.processor.tokenizer(
image_text,
padding="max_length",
truncation=True,
max_length=self.max_length,
return_tensors="pt"
)
return {
"pixel_values": vision_outputs.pixel_values.squeeze(0),
"input_ids": text_outputs.input_ids.squeeze(0),
"attention_mask": text_outputs.attention_mask.squeeze(0)
}
def print_gpu_memory(step):
"""打印GPU内存使用情况"""
allocated = torch.cuda.memory_allocated() / 1024 / 1024
print(f"\n=== {step} ===")
print(f"GPU Memory allocated: {allocated:.2f} MB")
class ImprovedConcurrentTester:
"""并发测试类"""
def __init__(self, model, processor, compressor, max_new_tokens, num_samples, compress_batch,
compression_ratio_list, gpu_info_path, use_compression, comp_mode,
device):
self.model = model
self.processor = processor
self.compressor = compressor
self.device = device
self.max_new_tokens = max_new_tokens
self.num_samples = num_samples
self.compress_batch = compress_batch
self.compression_ratio_list = compression_ratio_list
self.gpu_info_path = gpu_info_path
self.use_compression = use_compression
self.comp_mode = comp_mode
self.last_prefill_time = time.time()
self.cuda_stream = torch.cuda.Stream()
# self.timeCheck = TimeTik()
self.monitor = PerformanceMonitor()
self.timestamp_manager = TimestampManager()
# self.GPU_monitor = GPUMonitor(monitor_sys=False)
self.check_gpu_flag = False
# self.check_gpu_flag = True
self.GPU_monitor = GPUMonitor(interval=0.02)
self.kvcache_pool = KVCachePool(device=device)
self._init_press_list()
def _init_press_list(self):
self.press_type = [
'ccm',
'Knorm',
'StreamingLLM',
'RandomPress',
'SnapKV',
'ExpectedAttention',
'Quantized',
]
def _get_kv_cache_memory(self, past_key_values):
"""计算KV-cache内存占用"""
total_memory = 0
# print("past_key_values")
# print(len(past_key_values))
# print(len(past_key_values[0]))
# print(past_key_values[0][0].shape)
for layer in past_key_values:
k, v = layer
total_memory += k.numel() * k.element_size()
total_memory += v.numel() * v.element_size()
return total_memory / (1024 ** 2) # 转换为MB
def _split_past_kv_multi_batch(self, past_key_values, batch_indices=None):
"""
从past_key_values中提取多个batch的KV缓存
Args:
past_key_values: 原始KV缓存元组
batch_indices: list of int, 要提取的batch索引列表
Returns:
list of tuple, 每个batch对应的KV缓存列表
"""
batch_size = past_key_values[0][0].shape[0]
if batch_size == 1:
return [past_key_values]
if batch_indices is None:
# 获取batch大小并生成完整索引列表
batch_indices = list(range(batch_size))
# batch_idx_tensor = torch.tensor(batch_indices, device=past_key_values[0][0].device)
# num_layers = len(past_key_values)
# batch_size = len(batch_indices)
# 创建batch_size个空的past_key_values结构
result = []
for batch_idx in batch_indices:
# 对每个batch,创建其完整的层结构
batch_kv = list(
(
# layer_key.index_select(0, torch.tensor([batch_idx], device=layer_key.device)),
# layer_value.index_select(0, torch.tensor([batch_idx], device=layer_value.device))
layer_key[batch_idx:batch_idx+1],
layer_value[batch_idx:batch_idx+1]
# 不会产生多于内存
)
for layer_key, layer_value in past_key_values
)
result.append(batch_kv)
return result
def _integrated_compress_ccm(self, inputs, request_ids_list):
past_key_values_list_final = []
comp_past_key_values_list = []
# print("past_key_values_list", len(past_key_values_list), len(past_key_values_list[0]))
if self.check_gpu_flag:
_integrated_compress_ccm_stats = self.GPU_monitor.check_gpu_stats()
print('_integrated_compress_ccm', _integrated_compress_ccm_stats)
start_split_time = time.time()
# for past_key_values in past_key_values_list:
# past_key_values_list_final.extend(self._split_past_kv_multi_batch(past_key_values))
# del past_key_values
# past_key_values_list.clear()
# # 显式清空 CUDA 缓存
# torch.cuda.empty_cache()
if self.check_gpu_flag:
past_key_values_list_final_stats = self.GPU_monitor.check_gpu_stats()
print('past_key_values_list_final', past_key_values_list_final_stats)
print("start_split_time", time.time() - start_split_time)
compress_batch_size = self.compress_batch
start_p = 0
comp_duration_time = 0
final_compression_ratio_list = []
# print("past_key_values_list_final", len(past_key_values_list_final))
past_key_values_list_final = self.kvcache_pool.pop_kvcache(request_ids_list)
# 确实不涨1
while len(past_key_values_list_final) != 0:
# ref_count_past_key_values_list_final = sys.getrefcount(past_key_values_list_final[0])
# print(f"Tensor ref_count_past_key_values_list_final reference count: {ref_count_past_key_values_list_final}")
target_past_key_values = past_key_values_list_final[:compress_batch_size]
# ref_count_orig = sys.getrefcount(target_past_key_values[0])
# print(f"Tensor target_past_key_values1 reference count: {ref_count_orig}")
# ref_count_target_past_key_values = sys.getrefcount(target_past_key_values[0])
# print(f"Tensor target_past_key_values reference count: {ref_count_target_past_key_values}")
past_key_values_list_final = past_key_values_list_final[len(target_past_key_values):]
# past_key_values_list_final.clear()
# del past_key_values_list_final
# past_key_values_list_final = past_key_values_list_final_last
# del past_key_values_list_final_last
# ref_count_orig = sys.getrefcount(target_past_key_values[0])
# print(f"Tensor target_past_key_values2 reference count: {ref_count_orig}")
# ref_count_target_past_key_values = sys.getrefcount(target_past_key_values[0])
# print(f"Tensor target_past_key_values reference count: {ref_count_target_past_key_values}")
# 不涨2
end_p = start_p + len(target_past_key_values)
self.GPU_monitor.accum_state_round('compress')
if self.check_gpu_flag:
# self.GPU_monitor.accum_state_round('compress')
before_comp_stats = self.GPU_monitor.check_gpu_stats()
print('before_comp', before_comp_stats)
orig_past_key_values = self.merge_kv_cache(target_past_key_values)
# before_comp_stats = self.GPU_monitor.check_gpu_stats()
# 确实要涨1 merge_kv_cache
if self.check_gpu_flag:
before_comp_stats = self.GPU_monitor.check_gpu_stats()
print('要涨1', before_comp_stats)
del target_past_key_values # work的,涨完又降回去
if self.check_gpu_flag:
before_comp_stats = self.GPU_monitor.check_gpu_stats()
print('降回', before_comp_stats)
# print_gpu_memory('降吗')
torch.cuda.empty_cache()
if self.check_gpu_flag:
after_merge_stats = self.GPU_monitor.check_gpu_stats()
print('after_merge', after_merge_stats)
print(after_merge_stats['memory_used'] - before_comp_stats['memory_used'])
orig_memory = self._get_kv_cache_memory(orig_past_key_values)
kv_len = orig_past_key_values[0][0].shape[2]
# print(inputs["input_ids"][start_p:end_p,:], start_p, end_p)
comp_len = self.get_comp_len(inputs["input_ids"][start_p:end_p, :],
inputs["attention_mask"][start_p:end_p, :], kv_len)
# print("comp_len", comp_len)
comp_start = time.time()
self.timestamp_manager.record_timestamp(request_ids_list[start_p:end_p], 'compress_start', comp_start)
# ref_count_orig = sys.getrefcount(target_past_key_values[0])
# print(f"Tensor target_past_key_values3 reference count: {ref_count_orig}")
if self.check_gpu_flag:
after_merge_stats = self.GPU_monitor.check_gpu_stats()
print('near_comp', after_merge_stats)
comp_past_key_values = self.run_compressor(self.compressor,
orig_past_key_values, comp_len)
# ref_count_orig = sys.getrefcount(target_past_key_values[0])
# print(f"Tensor target_past_key_values4 reference count: {ref_count_orig}")
# print("comp_past_key_values", comp_past_key_values[0][0].shape)
# torch.cuda.synchronize()
_ = comp_past_key_values[0][0].shape # torch.cuda.synchronize()代替
if self.check_gpu_flag:
after_comp_stats = self.GPU_monitor.check_gpu_stats()
print('after_comp', after_comp_stats)
print('comp_mem_use', after_comp_stats['memory_used'] - after_merge_stats['memory_used'])
# ref_count_orig = sys.getrefcount(target_past_key_values[0])
# print(f"Tensor target_past_key_values reference count: {ref_count_orig}")
# for _target_tensor in target_past_key_values:
# del _target_tensor
# target_past_key_values.clear()
del orig_past_key_values
if self.check_gpu_flag:
after_comp_stats = self.GPU_monitor.check_gpu_stats()
print('del orig_past_key_values', after_comp_stats)
# comp_past_key_values_clone = [(k.detach().clone(), v.detach().clone()) for k,v in comp_past_key_values]
# after_comp_stats = self.GPU_monitor.check_gpu_stats()
# print('comp_past_key_values_clone', after_comp_stats)
#
# del comp_past_key_values
# # comp_past_key_values = None
# after_comp_stats = self.GPU_monitor.check_gpu_stats()
# print('del comp_past_key_values', after_comp_stats)
# # torch.cuda.empty_cache()
#
# del comp_past_key_values_clone
# # comp_past_key_values = None
# after_comp_stats = self.GPU_monitor.check_gpu_stats()
# print('del comp_past_key_values_clone', after_comp_stats)
torch.cuda.empty_cache()
if self.check_gpu_flag:
after_del_stats = self.GPU_monitor.check_gpu_stats()
print('after_del', after_del_stats)
print(after_del_stats['memory_used'] - after_comp_stats['memory_used'])
compress_finish = time.time()
self.timestamp_manager.record_timestamp(request_ids_list[start_p:end_p], 'compress_finish', compress_finish)
self.timestamp_manager.record_timestamp(request_ids_list[start_p:end_p], 'decoding_queueing',
compress_finish)
# print(self.compressor.)
# print(comp_past_key_values)
comp_past_key_values_list.append(comp_past_key_values)
memory_usage = self._get_kv_cache_memory(comp_past_key_values)
start_p = end_p
comp_duration_time += compress_finish - comp_start
final_compression_ratio_list.append(orig_memory / memory_usage if memory_usage > 0 else 0.0)
final_compression_ratio = sum(final_compression_ratio_list) / len(final_compression_ratio_list)
return comp_past_key_values_list, comp_duration_time, final_compression_ratio
def find_valid_lens(self, tensor, token_id=2):
"""计算有效序列长度"""
matches = tensor == token_id
positions = torch.argmax(matches.int(), dim=1, keepdim=True)
no_token_mask = ~matches.any(dim=1, keepdim=True)
positions = positions.masked_fill(no_token_mask, tensor.shape[1] - 1)
positions_list = positions.flatten().tolist()
return positions.sum().item(), positions_list
def get_comp_len(self, input_ids, attention_mask, kv_len):
"""计算压缩长度"""
real_position = attention_mask.long().cumsum(-1) - 1
# 预先访问一次tensor
# image_insert_pos = torch.where(input_ids == 32000)[1]
image_insert_pos = (input_ids == 32000).nonzero()[:, 1]
padding_over_pos = (real_position == 0).nonzero()[:, 1]
# padding_over_pos = torch.where(real_position == 0)[1]
batch_size = input_ids.shape[0]
comp_len = [[0, 0, 0] for _ in range(batch_size)]
for i_idx, i_input in enumerate(input_ids):
comp_len[i_idx][0] = int(padding_over_pos[i_idx])
comp_len[i_idx][2] = i_input[image_insert_pos[i_idx] + 1:].shape[-1]
comp_len[i_idx][1] = kv_len - comp_len[i_idx][2] - comp_len[i_idx][0]
return comp_len
def run_compressor(self, compressor, past_key_values, comp_len):
"""执行KV-Cache压缩"""
it_len = comp_len[0][1:] # 取出图像和文本长度
compressed_past_key_values = compressor(past_key_values, it_len)
return compressed_past_key_values
def _exec_compress(self, comp_mode, inputs, request_ids_list):
comp_past_key_values = None
comp_duration_time = 0
final_compression_ratio = 0
prefill_time = 0
if comp_mode == 'ccm':
self.GPU_monitor.accum_state_round('prefill')
# before_prefill_stats = self.GPU_monitor.check_gpu_stats()
# print('ccm_before_prefill', before_prefill_stats)
prefill_start = time.time()
self.timestamp_manager.record_timestamp(request_ids_list, 'prefill_start', prefill_start)
outputs = self.model(
input_ids=inputs["input_ids"],
attention_mask=inputs["attention_mask"],
pixel_values=inputs["pixel_values"],
use_cache=True,
return_dict=True,
)
# torch.cuda.empty_cache()
# print(outputs.logits.shape)
# print(outputs.image_hidden_states.shape)
# before_prefill_stats = self.GPU_monitor.check_gpu_stats()
# print('ccm_after_prefill', before_prefill_stats)
# 获取原始KV cache并计算内存占用
# orig_past_key_values = outputs.past_key_values
# torch.cuda.synchronize()
orig_past_key_values = outputs.past_key_values
prefill_finish = time.time()
prefill_time = prefill_finish - prefill_start
# compress_start = time.time()
self.timestamp_manager.record_timestamp(request_ids_list, 'prefill_finish', prefill_finish)
# self.timestamp_manager.record_timestamp(request_ids_list, 'compress_queueing', prefill_finish)
# self.timestamp_manager.record_timestamp(request_ids_list, 'compress_start', compress_start)
# ccm方法则直接传送
# orig_memory = self._get_kv_cache_memory(orig_past_key_values)
# # past_key_values_split = self._split_past_kv_multi_batch(orig_past_key_values)
# kv_len = orig_past_key_values[0][0].shape[2]
# comp_len = self.get_comp_len(inputs["input_ids"], inputs["attention_mask"], kv_len)
# comp_start_time = time.time()
# comp_past_key_values = self.run_compressor(self.compressor,
# orig_past_key_values, inputs["attention_mask"], comp_len)
# compress_finish = time.time()
# self.timestamp_manager.record_timestamp(request_ids_list, 'compress_finish', compress_finish)
# # print(self.compressor.)
# memory_usage = self._get_kv_cache_memory(comp_past_key_values)
# comp_duration_time = compress_finish - comp_start_time
# final_compression_ratio = orig_memory / memory_usage if memory_usage > 0 else 0.0
return orig_past_key_values, 0, 1, prefill_time
elif comp_mode in self.press_type: # other comp
# prefill_start = time.time()
press = press_select(comp_mode, 1 - 1 / self.compression_ratio_list[1])
print(press)
underlying_model = get_underlying_model(self.model)
prefill_start = time.time()
self.timestamp_manager.record_timestamp(request_ids_list, 'prefill_start', prefill_start)
comp_past_key_values = exec_compression_methods(self.model,
underlying_model, inputs, press,
comp_mode)
_ = comp_past_key_values[0][0].shape
# torch.cuda.synchronize()
# todo press.totalTime的计时需不需要cuda syn
compress_finish = time.time()
comp_duration_time = press.totalTime
prefill_finish = compress_finish - comp_duration_time
self.timestamp_manager.record_timestamp(request_ids_list, 'prefill_finish', prefill_finish)
self.timestamp_manager.record_timestamp(request_ids_list, 'compress_queueing', prefill_finish)
self.timestamp_manager.record_timestamp(request_ids_list, 'compress_start', prefill_finish)
self.timestamp_manager.record_timestamp(request_ids_list, 'compress_finish', compress_finish)
final_compression_ratio = 1 / (1 - 1 / self.compression_ratio_list[1])
return comp_past_key_values, comp_duration_time, final_compression_ratio, prefill_time
# prefill_fini_ = time.time()
# prefill_time = prefill_fini_ - prefill_start
# 0.63 0.047 存在很大的系统开销
# print("compress_time", prefill_time, comp_duration_time)
else:
print(f"Warn in _exec_compress: {comp_mode} matching failed.")
return comp_past_key_values, comp_duration_time, final_compression_ratio, prefill_time
# self.timeCheck.show_and_reset()
# return comp_past_key_values, comp_duration_time, final_compression_ratio, prefill_time
# def _process_batch(self, batch, use_compression=False, comp_mode='ccm'):
# # server
# """处理单个批次"""
# # try:
# with torch.cuda.stream(torch.cuda.Stream()):
# # 将输入移到设备上
# inputs = {
# 'input_ids': batch['input_ids'].to(self.device),
# 'attention_mask': batch['attention_mask'].to(self.device),
# 'pixel_values': batch['pixel_values'].to(self.device)
# }
#
# with torch.no_grad(), autocast(dtype=torch.float):
# # Forward pass 阶段
# input_ids_forward = inputs["input_ids"][:, :-1]
# request_size = inputs["input_ids"].shape[0]
# # outputs = self.model(
# # input_ids=input_ids_forward,
# # attention_mask=inputs["attention_mask"][:, :-1],
# # pixel_values=inputs["pixel_values"],
# # use_cache=True,
# # return_dict=True
# # )
# #
# # # 获取原始KV cache并计算内存占用
# # orig_past_key_values = outputs.past_key_values
# # orig_memory = self._get_kv_cache_memory(orig_past_key_values)
# input_forward = {
# "input_ids": inputs["input_ids"][:, :-1],
# "attention_mask": inputs["attention_mask"][:, :-1],
# "pixel_values": inputs["pixel_values"]
# }
# # 压缩阶段(如果启用)
# if use_compression:
# past_key_values, compression_time, compression_ratio, \
# prefill_time = self._exec_compress(comp_mode, input_forward)
# memory_usage = self._get_kv_cache_memory(past_key_values)
# # compression_ratio = orig_memory / memory_usage if memory_usage > 0 else 0.0
# else:
# prefill_start = time.time()
# outputs = self.model(
# input_ids=input_ids_forward,
# attention_mask=inputs["attention_mask"][:, :-1],
# pixel_values=inputs["pixel_values"],
# use_cache=True,
# return_dict=True
# )
# torch.cuda.synchronize()
# prefill_finish_ = time.time()
# prefill_time = prefill_finish_ - prefill_start
# # 获取原始KV cache并计算内存占用
# orig_past_key_values = outputs.past_key_values
# orig_memory = self._get_kv_cache_memory(orig_past_key_values)
# past_key_values = orig_past_key_values
# memory_usage = orig_memory
# compression_ratio = None
# compression_time = 0
# # prefill_time = time.time() - prefill_start
#
# # 生成阶段
# generation_start = time.time()
#
# # 准备生成输入
# batch_size = inputs['input_ids'].shape[0]
# kv_len = past_key_values[0][0].shape[2]
# kv_attention_mask = torch.cat([
# inputs['attention_mask'],
# torch.ones(
# (batch_size, kv_len - inputs['attention_mask'].shape[1]),
# dtype=inputs['attention_mask'].dtype,
# device=self.device
# )
# ], dim=-1)
#
# # 准备generation输入
# input_ids = torch.cat([kv_attention_mask, inputs['input_ids'][:, -1].unsqueeze(-1)], dim=1)
# attention_mask = torch.cat([kv_attention_mask, inputs['attention_mask'][:, -1].unsqueeze(-1)], dim=1)
#
# # 生成文本
# gen_outputs = self.model.generate(
# input_ids=input_ids,
# attention_mask=attention_mask,
# past_key_values=past_key_values,
# max_new_tokens=512 - inputs['input_ids'].shape[1],
# do_sample=True,
# temperature=0.7,
# use_cache=True,
# return_dict_in_generate=True,
# output_scores=True,
# )
#
# # 处理生成的序列并计算性能指标
# sequences = gen_outputs.sequences
# start_idx = int(kv_attention_mask.shape[1])
# generated_sequences = sequences[:, start_idx:]
#
# decoding_time = time.time() - generation_start
#
# #todo waiting time
#
# # todo valid_lens
# valid_lens = self.find_valid_lens(generated_sequences, self.processor.tokenizer.eos_token_id)
# # valid_lens = generated_sequences.numel()
# throughput = valid_lens / decoding_time if decoding_time > 0 else 0
#
# tokens_time = decoding_time / valid_lens
# latency = [0, prefill_time, tokens_time]
#
# # 清理GPU内存
# torch.cuda.empty_cache()
#
# return TestResult(
# method='comp' if use_compression else 'orig',
# latency=latency, # 只使用生成时间作为延迟
# success=True,
# memory_usage=memory_usage,
# request_size=request_size,
# throughput=throughput,
# valid_tokens=valid_lens,
# compression_ratio=compression_ratio,
# compression_time=compression_time,
#
# )
#
# # except Exception as e:
# # print(f"Error in batch processing: {str(e)}")
# # return TestResult(
# # method='comp' if use_compression else 'orig',
# # latency=0,
# # success=False,
# # memory_usage=0,
# # request_size=0,
# # compression_time=0,
# # throughput=0,
# # valid_tokens=0,
# # compression_ratio=None,
# # compression_time=None
# # )
def _batching_tensors(self, dict_list):
"""
Args:
dict_list (List[Dict[str, torch.Tensor]]): 字典列表,每个字典包含形状为[1, ...]的张量
Returns:
Dict[str, torch.Tensor]: 合并后的字典,包含batched张量
"""
if not dict_list:
return {}
# 获取所有可能的keys
keys = set()
for d in dict_list:
keys.update(d.keys())
# 初始化结果字典
batched_dict = {}
# 对每个key,收集所有张量并进行batching
for key in keys:
# 收集所有包含该key的张量
# check_none
if dict_list[0][key] == None:
batched_dict[key] = None
continue
tensor_list = []
for d in dict_list:
if key in d:
tensor = d[key]
# # 确保张量的第一个维度是1
# if tensor.shape[0] != 1:
# raise ValueError(f"张量 {key} 的第一个维度不是1,实际形状为 {tensor.shape}")
tensor_list.append(tensor)
if tensor_list:
# 使用torch.cat沿着第一个维度连接张量
batched_dict[key] = torch.cat(tensor_list, dim=0)
# del tensor_list
# print(key, batched_dict[key].shape[0])
return batched_dict
# here
def run_concurrent_test(self, dataloader, max_workers=4, num_samples=10, max_serve_batch_size=8,
min_batch_threshold=4, std_batch_threshold_decoding=2,
max_wait_time=5., worker_check_time=0.01, req_per_sec=1.,
gpu_info_path=None, use_compression=False,
comp_mode='ccm'):
"""
middleware: 维护请求队列和服务状态
collector_thread: 收集dataloader数据的独立线程
dispatcher_thread: 调度任务到服务端的独立线程
"""
fstr = f"max_workers: {max_workers}, " \
f"num_batches: {num_samples}, " \
f"max_serve_batch_size: {max_serve_batch_size}, " \
f"min_batch_threshold: {min_batch_threshold}, " \
f"max_wait_time: {max_wait_time}, " \
f"use_compression: {use_compression}, " \
f""
print(fstr)
self.last_prefill_time = time.time()
gpu_info_flag = False
if gpu_info_path is not None:
gpu_info_flag = True
middleware = ServiceMiddleware(max_workers, max_serve_batch_size, min_batch_threshold,
std_batch_threshold_decoding, max_wait_time)
# 启动收集线程和调度线程
collector = Thread(target=self._collect_requests, args=(dataloader, middleware, num_samples, req_per_sec))
dispatcher = Thread(target=self._dispatch_requests,
args=(middleware, num_samples, use_compression, comp_mode, worker_check_time))
self.monitor.start_time = time.time()
if gpu_info_flag:
self.GPU_monitor.start_monitoring()
collector.start()
dispatcher.start()
# 等待所有任务完成
collector.join()
dispatcher.join()
if gpu_info_flag:
self.GPU_monitor.stop_monitoring()
self.GPU_monitor.save_stats(self.gpu_info_path)
gpu_stats = self.GPU_monitor.get_stats()
# # 启动收集线程和调度线程
# collector = Thread(target=self._collect_requests, args=(dataloader, middleware, num_samples, req_per_sec))
# dispatcher = Thread(target=self._dispatch_requests,
# args=(middleware, num_samples, use_compression, worker_check_time))
#
# self.monitor.start_time = time.time()
# collector.start()
# # dispatcher.start()
#
# # 等待所有任务完成
# collector.join()
# self._dispatch_requests(middleware, num_samples, use_compression, worker_check_time)
# # self._dispatch_requests(middleware, num_samples)
analyze_times_result, durations = self.timestamp_manager.analyze_timestamps()
system_completion_time = middleware.system_total_time
system_total_generated_lens = analyze_times_result['total_generated_lens']
metrics = self.monitor.calculate_metrics(durations, system_completion_time)
return metrics, analyze_times_result, system_completion_time, system_total_generated_lens
def _collect_requests(self, dataloader, middleware, num_batches, req_per_sec=1.):
"""修改后的收集请求函数,将请求添加到调度器"""
print("num_batches", num_batches)
for i, batch in enumerate(dataloader):
if i >= num_batches: