Repository navigation
Expand file tree
/
Copy pathvllm-script.py
More file actions
2684 lines (2233 loc) · 138 KB
/
Copy pathvllm-script.py
File metadata and controls
2684 lines (2233 loc) · 138 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
"""
vllm-nexus-gui-hybrid.py
"""
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import socket
import json
import threading
from vllm import AsyncLLMEngine, SamplingParams
import subprocess
import GPUtil
import time
import os
import torch
import psutil
import mmap
import sys
from datetime import datetime
import re
import pynvml
class VLLMServerGUI:
def __init__(self, master):
self.master = master
master.title("VLLM-DRAM-VRAM Server Manager")
# Configuration parameters storage
self.config = {
'model_path': '',
'ip': self.get_local_ip(),
'port': 8000,
'gpu_count': 1,
'mem_ratio': 95, # Increase VRAM utilization
'max_tokens': 4096, # Increase max tokens
'kv_dtype': 'float16',
'block_size': 16,
'max_blocks': '',
'calculate_scales': True,
'max_model_len': 4096, # Reduce max_model_len to save memory
# Memory offload related configuration
'enable_memory_offload': True, # Enable memory offload by default
'memory_offload_ratio': 70, # Increase memory offload ratio
'memory_channels': 4,
'reserved_memory': 20
}
# Server process
self.server_process = None
# API address
self.api_address = None
# Main interface layout
self.create_widgets()
# Load configuration
self.load_config()
# Professional monitoring flag
self.monitoring = True
# Start GPU monitoring thread
threading.Thread(target=self.update_gpu_stats, daemon=True).start()
def get_local_ip(self):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return IP
def create_widgets(self):
# Basic Configuration Area
self.config_frame = ttk.LabelFrame(self.master, text="Basic Configuration")
self.config_frame.pack(padx=10, pady=5, fill='x')
# Model Path
ttk.Label(self.config_frame, text="Model Path:").grid(row=0, column=0)
self.model_path_entry = ttk.Entry(self.config_frame, width=50)
self.model_path_entry.grid(row=0, column=1)
self.model_path_entry.insert(0, self.config['model_path'])
ttk.Button(self.config_frame, text="Browse", command=self.select_model_path).grid(row=0, column=2)
# Add Save Config button and Recommend Settings button
save_config_button = ttk.Button(self.config_frame, text="Save Config", command=self.save_config_with_message)
save_config_button.grid(row=0, column=3, padx=5)
recommend_button = ttk.Button(self.config_frame, text="Recommend Settings", command=self.recommend_settings)
recommend_button.grid(row=0, column=4, padx=5)
# IP Address
ttk.Label(self.config_frame, text="IP Address:").grid(row=1, column=0)
self.ip_entry = ttk.Entry(self.config_frame)
self.ip_entry.grid(row=1, column=1, sticky='w')
self.ip_entry.insert(0, self.config['ip'])
# Port
ttk.Label(self.config_frame, text="Port:").grid(row=2, column=0)
self.port_entry = ttk.Entry(self.config_frame)
self.port_entry.grid(row=2, column=1, sticky='w')
self.port_entry.insert(0, str(self.config['port']))
# GPU Count
ttk.Label(self.config_frame, text="GPU Count:").grid(row=3, column=0)
self.gpu_count_var = tk.StringVar(value=str(self.config['gpu_count']))
gpu_count_combo = ttk.Combobox(self.config_frame, textvariable=self.gpu_count_var,
values=["1", "2", "3", "4"], width=5)
gpu_count_combo.grid(row=3, column=1, sticky='w')
# VRAM Ratio
ttk.Label(self.config_frame, text="VRAM Ratio (%):").grid(row=4, column=0)
self.mem_ratio_entry = ttk.Entry(self.config_frame)
self.mem_ratio_entry.grid(row=4, column=1, sticky='w')
self.mem_ratio_entry.insert(0, str(self.config['mem_ratio']))
# Max Tokens
ttk.Label(self.config_frame, text="Max Tokens:").grid(row=5, column=0)
self.max_tokens_var = tk.StringVar(value=str(self.config['max_tokens']))
ttk.Entry(self.config_frame, textvariable=self.max_tokens_var, width=8).grid(row=5, column=1)
ttk.Label(self.config_frame, text="(Response tokens should not be less than total sequence length)", foreground="gray").grid(row=6, column=0, columnspan=2, sticky='w')
# Max Sequence Length
ttk.Label(self.config_frame, text="Max Sequence Length:").grid(row=5, column=2)
self.max_model_len_var = tk.StringVar(value=str(self.config['max_model_len']))
max_model_len_combo = ttk.Combobox(self.config_frame, textvariable=self.max_model_len_var,
values=["2048", "4096", "8192", "16384", "32768", "65536"], width=8)
max_model_len_combo.grid(row=5, column=3)
ttk.Label(self.config_frame, text="(Please choose appropriate parameters based on hardware conditions)", foreground="gray").grid(row=6, column=2, columnspan=2, sticky='w')
# KV Cache Configuration
cache_frame = ttk.LabelFrame(self.config_frame, text="KV Cache Configuration")
cache_frame.grid(row=7, column=0, columnspan=3, sticky="ew", pady=5)
# Cache Precision
ttk.Label(cache_frame, text="Cache Precision:").grid(row=0, column=0)
self.kv_dtype_var = tk.StringVar(value=self.config['kv_dtype'])
ttk.Combobox(cache_frame, textvariable=self.kv_dtype_var,
values=["float16", "float32"], width=8).grid(row=0, column=1)
# Cache Block Size
ttk.Label(cache_frame, text="Block Size (tokens):").grid(row=0, column=2)
self.block_size_var = tk.StringVar(value=str(self.config['block_size']))
ttk.Entry(cache_frame, textvariable=self.block_size_var, width=8).grid(row=0, column=3)
# Max Cache Blocks
ttk.Label(cache_frame, text="Max Blocks:").grid(row=1, column=0)
self.max_blocks_var = tk.StringVar(value=str(self.config['max_blocks']))
ttk.Entry(cache_frame, textvariable=self.max_blocks_var, width=8).grid(row=1, column=1)
ttk.Label(cache_frame, text="(Leave blank for auto)").grid(row=1, column=2)
# Dynamic Scaling Option
self.calculate_scales_var = tk.BooleanVar(value=self.config['calculate_scales'])
ttk.Checkbutton(cache_frame, text="Enable Dynamic Scaling",
variable=self.calculate_scales_var).grid(row=1, column=3)
# Add Advanced Performance Settings Area
self.create_advanced_settings()
# Monitoring Panel
monitor_frame = ttk.LabelFrame(self.master, text="GPU Monitoring")
monitor_frame.pack(padx=10, pady=5, fill='both', expand=True)
# GPU Status Display
columns = ('GPU', 'VRAM Usage', 'GPU Usage', 'Temperature', 'Power', 'KV Cache Hit Rate')
self.gpu_tree = ttk.Treeview(monitor_frame, columns=columns, show='headings')
for col in columns:
self.gpu_tree.heading(col, text=col)
self.gpu_tree.column(col, width=100)
self.gpu_tree.pack(fill='both', expand=True)
# Status Display Area
self.status_text = tk.Text(monitor_frame, height=10)
self.status_text.pack(fill='both')
# Server Control Buttons
button_frame = ttk.Frame(self.config_frame)
button_frame.grid(row=8, column=0, columnspan=3, pady=5)
ttk.Button(button_frame, text="Start Server", command=self.start_server).grid(row=0, column=0, padx=5)
ttk.Button(button_frame, text="Stop Server", command=self.stop_server).grid(row=0, column=1, padx=5)
# API Address Display
self.api_label = ttk.Label(self.config_frame, text="API Address:")
self.api_label.grid(row=9, column=0, columnspan=3)
# Add Memory Offload Configuration Frame
offload_frame = ttk.LabelFrame(self.config_frame, text="Memory Offload Configuration")
offload_frame.grid(row=10, column=0, columnspan=3, sticky="ew", pady=5)
# Enable Memory Offload Option
self.enable_offload_var = tk.BooleanVar(value=self.config['enable_memory_offload'])
ttk.Checkbutton(offload_frame, text="Enable Memory Offload",
variable=self.enable_offload_var).grid(row=0, column=0)
# Memory Channel Count
ttk.Label(offload_frame, text="Memory Channels:").grid(row=0, column=1)
self.memory_channels_var = tk.StringVar(value=str(self.config['memory_channels']))
ttk.Combobox(offload_frame, textvariable=self.memory_channels_var,
values=["2", "4", "8", "16"], width=5).grid(row=0, column=2)
# Memory Offload Ratio
ttk.Label(offload_frame, text="Memory Offload Ratio (%):").grid(row=1, column=0)
self.memory_offload_ratio_var = tk.StringVar(value=str(self.config['memory_offload_ratio']))
ttk.Entry(offload_frame, textvariable=self.memory_offload_ratio_var, width=5).grid(row=1, column=1)
# Reserved System Memory Ratio
ttk.Label(offload_frame, text="Reserved System Memory (%):").grid(row=1, column=2)
self.reserved_memory_var = tk.StringVar(value=str(self.config['reserved_memory']))
ttk.Entry(offload_frame, textvariable=self.reserved_memory_var, width=5).grid(row=1, column=3)
# Add Advanced Description
ttk.Label(offload_frame, text="(Enabling this allows loading large models exceeding VRAM, but reduces inference speed)",
foreground="gray").grid(row=2, column=0, columnspan=4, sticky='w')
# Add "Check Compatibility" button
self.check_compatibility_button = ttk.Button(
self.config_frame,
text="Check Compatibility",
command=self.check_model_compatibility
)
self.check_compatibility_button.grid(row=1, column=3, padx=5, pady=5, sticky="w")
# Add Performance Monitoring Panel
self.add_performance_monitoring()
def select_model_path(self):
path = filedialog.askdirectory()
if path:
self.config['model_path'] = path
self.model_path_entry.delete(0, tk.END) # Clear current content
self.model_path_entry.insert(0, path) # Insert new path
def start_server(self):
"""Start VLLM Server"""
if not self.config['model_path']:
messagebox.showerror("Error", "Please select a model path first")
return
if hasattr(self, 'server_process') and self.server_process and self.server_process.poll() is None:
messagebox.showinfo("Hint", "Server is already running")
return
# Check model compatibility
if not self.check_model_compatibility():
if not messagebox.askokcancel("Warning", "Model compatibility check found potential issues, continue starting server?"):
return
# Clean GPU memory
self.clean_gpu_memory()
# Set environment variables to avoid memory fragmentation issues
env = os.environ.copy()
# Apply CUDA memory chunk size from advanced settings
cuda_split_size = self.config.get('advanced_cuda_split_size', 128) # Default 128MB
env['PYTORCH_CUDA_ALLOC_CONF'] = f'expandable_segments:True,max_split_size_mb:{cuda_split_size}'
self.status_text.insert(tk.END, f"CUDA memory chunk size: {cuda_split_size}MB\n")
env['CUDA_VISIBLE_DEVICES'] = ','.join([str(i) for i in range(self.config['gpu_count'])])
env['OMP_NUM_THREADS'] = '4' # Limit OpenMP threads
env['MKL_NUM_THREADS'] = '4' # Limit MKL threads
# Add performance optimization environment variables
env['CUDA_DEVICE_MAX_CONNECTIONS'] = '1' # Optimize CUDA connections
env['NCCL_P2P_DISABLE'] = '1' # For single GPU, disabling P2P may improve performance
env['CUDA_AUTO_BOOST'] = '1' # Enable GPU auto boost frequency
env['VLLM_USE_ASYNC_CUDA_MALLOC'] = '1' # Use asynchronous CUDA memory allocation
# Get system memory size
system_memory = psutil.virtual_memory().total / (1024 * 1024 * 1024) # GB
# Choose whether to enable memory-efficient linear layers based on hardware
if system_memory > 16: # Only enable if system memory is sufficient
env['VLLM_ENABLE_MEMORY_EFFICIENT_LINEAR'] = '1' # Enable memory-efficient linear layers
# Log startup information
self.status_text.insert(tk.END, "\n===== Starting Server =====\n")
self.status_text.insert(tk.END, f"Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
self.status_text.insert(tk.END, f"Model Path: {self.config['model_path']}\n")
self.status_text.insert(tk.END, f"GPU Count: {self.config['gpu_count']}\n")
self.status_text.insert(tk.END, f"VRAM Ratio: {self.config['mem_ratio']}%\n")
# Check GPU monitoring thread
if not self.monitoring:
self.monitoring = True
threading.Thread(target=self.update_gpu_stats, daemon=True).start()
# Save configuration
self.save_config()
# Pre-allocate memory space to prevent out-of-memory during runtime
self.preallocate_memory_buffer()
# Initialize KV cache monitoring
self.kv_cache_hits = 0
self.kv_cache_misses = 0
# Check if memory offload is needed
if self.config['enable_memory_offload']:
try:
self.status_text.insert(tk.END, "Setting up memory offload...\n")
# Calculate model size
model_size = self.estimate_model_size()
# Get available VRAM
available_vram = self.get_available_vram(use_ratio=self.config['mem_ratio'] / 100)
self.status_text.insert(tk.END, f"Model size: {model_size:.2f}GB, Available VRAM: {available_vram:.2f}GB\n")
# Calculate memory size to offload
offload_ratio = self.config['memory_offload_ratio'] / 100
initial_offload_size = model_size * offload_ratio
self.status_text.insert(tk.END, f"Offloading {initial_offload_size:.2f}GB to system memory (Ratio: {self.config['memory_offload_ratio']}%)\n")
# Set up memory-mapped file
self.setup_memory_offload(model_size, offload_ratio)
# Check VLLM supported parameters
self.status_text.insert(tk.END, "Checking VLLM supported parameters...\n")
# Calculate available system memory (considering reserved ratio)
available_memory = self.get_available_system_memory()
reserved_ratio = self.config['reserved_memory'] / 100
safe_memory = available_memory * (1 - reserved_ratio)
# Get actual allocated memory size
actual_offload_size = 0
if hasattr(self, 'mm') and self.mm:
try:
# Get memory-mapped file size
map_file = os.path.join(os.getcwd(), "model_offload", "model_offload.bin")
if os.path.exists(map_file):
actual_offload_size = os.path.getsize(map_file) / (1024 * 1024 * 1024)
self.status_text.insert(tk.END, f"Actual allocated memory-mapped size: {actual_offload_size:.2f}GB\n")
except Exception as e:
self.status_text.insert(tk.END, f"Failed to get memory-mapped size: {str(e)}\n")
# Dynamically adjust required memory size
min_required_size = min(18, model_size * 0.8) # At least 80% of model size
if actual_offload_size < min_required_size:
self.status_text.insert(tk.END, f"Warning: Actual allocated memory-mapped size is insufficient {min_required_size:.1f}GB, model may not load\n")
if not messagebox.askokcancel("Warning",
f"Actual allocated memory-mapped size is only {actual_offload_size:.2f}GB, recommended at least {min_required_size:.1f}GB.\nContinue?"):
return False
# Calculate reasonable swap space size - dynamically adjust based on model size
# For small models (<10GB), use smaller swap space
if model_size < 10:
swap_size = max(2.0, model_size * 0.1)
else:
# For large models, use larger swap space
swap_size = max(4.0, model_size * 0.15)
# Ensure it doesn't exceed 20% of safe memory
swap_size = min(swap_size, safe_memory * 0.2)
# Calculate reasonable CPU offload size - dynamically adjust based on model size and available VRAM
available_vram = self.get_available_vram(use_ratio=self.config['mem_ratio'] / 100)
# If model size exceeds available VRAM, calculate the portion to offload
if model_size > available_vram:
# Size to offload = Model size - Available VRAM + extra buffer (1GB)
min_offload_size = model_size - available_vram + 1.0
# Ensure at least 60% of the model is offloaded
offload_size = max(min_offload_size, model_size * 0.6)
else:
# If the model can fit entirely in VRAM, still offload a portion for stability
offload_size = model_size * 0.3
# Ensure it doesn't exceed 70% of safe memory
offload_size = min(offload_size, safe_memory * 0.7)
# Calculate total memory usage
total_mem_usage = swap_size + offload_size
mem_usage_ratio = total_mem_usage / safe_memory * 100
self.status_text.insert(tk.END, f"Available system memory: {available_memory:.2f}GB, Safe memory: {safe_memory:.2f}GB\n")
self.status_text.insert(tk.END, f"Calculated swap space: {swap_size:.2f}GB, CPU Offload: {offload_size:.2f}GB\n")
self.status_text.insert(tk.END, f"Total memory usage: {total_mem_usage:.2f}GB ({mem_usage_ratio:.1f}% of safe memory)\n")
# Ensure max_num_batched_tokens is greater than or equal to max_num_seqs
max_tokens = max(self.config['max_tokens'], 256) # Ensure at least 256
# Build command
cmd = [
'vllm', 'serve',
self.config['model_path'],
'--host', self.config['ip'],
'--port', str(self.config['port']),
'--tensor-parallel-size', str(self.config['gpu_count']),
'--gpu-memory-utilization', str(self.config['mem_ratio'] / 100),
'--max-num-batched-tokens', str(max_tokens),
'--block-size', str(self.config['block_size']),
'--max-model-len', str(self.config['max_model_len']),
'--dtype', 'half' # Force half precision
]
# Add max blocks (if specified)
if self.config['max_blocks']:
cmd.extend(['--num-gpu-blocks', self.config['max_blocks']])
# Add swap space parameter
swap_param = f"{swap_size:.2f}" # Remove GiB unit, use only number
cmd.extend(['--swap-space', swap_param])
self.status_text.insert(tk.END, f"Adding swap space parameter: --swap-space {swap_param} (GB)\n")
# Add CPU offload parameter
offload_param = f"{offload_size:.2f}" # Remove GB unit, use only number
cmd.extend(['--cpu-offload-gb', offload_param])
self.status_text.insert(tk.END, f"Adding CPU offload parameter: --cpu-offload-gb {offload_param} (GB)\n")
# Add enforce-eager mode to avoid out-of-memory during CUDA graph capture phase
cmd.append('--enforce-eager')
self.status_text.insert(tk.END, "Adding enforce-eager parameter: --enforce-eager\n")
self.status_text.insert(tk.END, f"Memory offload enabled, available CPU memory: {safe_memory:.2f}GB\n")
# Log full command
cmd_str = ' '.join(cmd)
self.status_text.insert(tk.END, f"Full command: {cmd_str}\n")
self.status_text.see(tk.END)
except Exception as e:
self.status_text.insert(tk.END, f"Error setting up memory offload: {str(e)}\n")
import traceback
self.status_text.insert(tk.END, traceback.format_exc())
if not messagebox.askokcancel("Error",
f"Error setting up memory offload: {str(e)}\nContinue starting server (without memory offload)?"):
return
# If memory offload setup fails, use basic command
max_tokens = max(self.config['max_tokens'], 256) # Ensure at least 256
cmd = [
'vllm', 'serve',
self.config['model_path'],
'--host', self.config['ip'],
'--port', str(self.config['port']),
'--tensor-parallel-size', str(self.config['gpu_count']),
'--gpu-memory-utilization', str(self.config['mem_ratio'] / 100),
'--max-num-batched-tokens', str(max_tokens),
'--block-size', str(self.config['block_size']),
'--max-model-len', str(self.config['max_model_len']),
'--dtype', 'half', # Force half precision
'--enforce-eager' # Add enforce-eager mode to avoid out-of-memory during CUDA graph capture phase
]
else:
# If memory offload is not needed, use basic command
max_tokens = max(self.config['max_tokens'], 256) # Ensure at least 256
cmd = [
'vllm', 'serve',
self.config['model_path'],
'--host', self.config['ip'],
'--port', str(self.config['port']),
'--tensor-parallel-size', str(self.config['gpu_count']),
'--gpu-memory-utilization', str(self.config['mem_ratio'] / 100),
'--max-num-batched-tokens', str(max_tokens),
'--block-size', str(self.config['block_size']),
'--max-model-len', str(self.config['max_model_len']),
'--dtype', 'half', # Force half precision
'--enforce-eager' # Add enforce-eager mode to avoid out-of-memory during CUDA graph capture phase
]
# Add performance optimization parameters
performance_args = [
'--max-num-seqs', '32', # Increase max sequences
'--disable-log-stats', # Disable statistics logging, reduce overhead
'--kv-cache-dtype', 'auto', # Use auto-select KV cache precision
'--trust-remote-code' # Trust remote code, support more models
]
# Apply batch size from advanced settings
batch_size = self.config.get('advanced_batch_size', 16) # Default 16
performance_args.extend(['--max-num-batched-tokens', str(max(batch_size * 256, max_tokens))])
self.status_text.insert(tk.END, f"Batch size: {batch_size}\n")
# Add memory bandwidth optimization parameters
if int(self.block_size_var.get()) < 32:
# If block size is less than 32, suggest increasing to 32 to improve memory bandwidth utilization
self.status_text.insert(tk.END, f"Note: Current block size ({self.block_size_var.get()}) is small, may affect memory bandwidth utilization\n")
self.status_text.insert(tk.END, "Suggest using a larger block size (32-64) to improve memory bandwidth utilization\n")
# Check for Flash Attention support
if self.check_flash_attention_support():
performance_args.append('--enable-chunked-prefill')
self.status_text.insert(tk.END, "Enabling chunked prefill optimization\n")
# Add performance parameters to command
cmd.extend(performance_args)
# Start server asynchronously
try:
self.status_text.insert(tk.END, "Starting server process...\n")
self.server_process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
env=env # Use modified environment variables
)
# Wait for a short period, check if the process exits immediately
time.sleep(1)
if self.server_process.poll() is not None:
# Process exited, get output
output, _ = self.server_process.communicate()
error_msg = f"Failed to start server: {output.decode()}"
self.status_text.insert(tk.END, f"{error_msg}\n")
# Attempt fallback method
return self.fallback_start_server(error_msg)
# Start monitoring thread
threading.Thread(target=self.monitor_server_output).start()
# Update API address
# Note: GET /v1 returning 404 is normal, please use specific API endpoint supporting POST for requests
api_base = f"http://{self.config['ip']}:{self.config['port']}/v1"
self.api_label.config(text=f"API Address: {api_base}")
self.status_text.insert(tk.END, f"\nServer starting...\nAPI Address: {api_base}\n")
self.status_text.see(tk.END)
return True
except Exception as e:
error_msg = f"Failed to start server: {str(e)}"
self.status_text.insert(tk.END, f"{error_msg}\n")
import traceback
self.status_text.insert(tk.END, traceback.format_exc())
# Attempt fallback method
return self.fallback_start_server(error_msg)
def stop_server(self):
try:
# First stop all monitoring threads
self.monitoring = False
# Wait for a short period for threads to exit
time.sleep(0.5)
if hasattr(self, 'server_process') and self.server_process and self.server_process.poll() is None:
self.server_process.terminate()
try:
self.server_process.wait(timeout=5)
self.status_text.insert(tk.END, "\nServer stopped.\n")
except subprocess.TimeoutExpired:
self.status_text.insert(tk.END, "\nStopping server timed out, but server may have stopped.\n")
else:
self.status_text.insert(tk.END, "\nServer is not running.\n")
# Clean up memory offload resources
self.cleanup_memory_offload()
except Exception as e:
messagebox.showerror("Error", f"Failed to stop server: {str(e)}")
finally:
# Ensure monitoring flag is set to False
self.monitoring = False
# Disable auto-tuning
if hasattr(self, 'auto_tune_var'):
self.auto_tune_var.set(False)
self.api_label.config(text="API Address: Server not started")
def cleanup_memory_offload(self):
"""Clean up memory offload resources"""
try:
# Clean up memory buffer
self.cleanup_memory_buffer()
# Clean up multi-channel loader
if hasattr(self, 'multi_channel_loader') and self.multi_channel_loader is not None:
try:
# Call loader's close method
if hasattr(self.multi_channel_loader, 'close'):
self.multi_channel_loader.close()
self.multi_channel_loader = None
self.status_text.insert(tk.END, "Multi-channel loader closed\n")
except Exception as e:
self.status_text.insert(tk.END, f"Error closing multi-channel loader: {str(e)}\n")
elif hasattr(self, 'channel_loaders'):
# Compatible with older code versions
for loader in self.channel_loaders:
if hasattr(loader, 'mm') and loader.mm:
loader.mm.close()
if hasattr(loader, 'mm_file') and loader.mm_file:
loader.mm_file.close()
self.channel_loaders = []
# Clean up memory map
if hasattr(self, 'mm') and self.mm:
self.mm.close()
self.mm = None
if hasattr(self, 'mm_file') and self.mm_file:
self.mm_file.close()
self.mm_file = None
self.status_text.insert(tk.END, "Memory-mapped resources released\n")
except Exception as e:
self.status_text.insert(tk.END, f"Error releasing memory-mapped resources: {str(e)}\n")
def monitor_server_output(self):
"""Monitor server output and detect errors"""
error_patterns = [
# Out of memory errors
(r"CUDA out of memory", "GPU Out of Memory"),
(r"OutOfMemoryError", "Out of Memory"),
(r"OOM", "Out of Memory"),
# Model loading errors
(r"Error loading model", "Model Loading Error"),
(r"Failed to load", "Model Loading Failed"),
# Parameter errors
(r"ValueError", "Parameter Error"),
(r"TypeError", "Type Error"),
# Permission errors
(r"PermissionError", "Permission Error"),
# Network errors
(r"ConnectionError", "Connection Error"),
(r"Address already in use", "Port Already in Use"),
# General errors
(r"Error:", "Error Occurred"),
(r"Exception:", "Exception Occurred"),
(r"Traceback", "Program Crash")
]
# Token generation pattern
token_pattern = r"Processed (\d+) tokens"
# Record startup time
start_time = time.time()
error_detected = False
error_message = ""
server_started = False
while True:
if not hasattr(self, 'server_process') or self.server_process is None:
self.status_text.insert(tk.END, "Server process does not exist\n")
break
if self.server_process.poll() is not None:
self.status_text.insert(tk.END, f"Server process exited with code: {self.server_process.poll()}\n")
break
try:
output = self.server_process.stdout.readline()
if not output:
time.sleep(0.1)
continue
output_text = output.decode(errors='replace')
self.status_text.insert(tk.END, output_text)
self.status_text.see(tk.END)
# Check for token generation information
token_match = re.search(token_pattern, output_text)
if token_match:
tokens = int(token_match.group(1))
self.update_token_count(tokens)
# Check for error messages
for pattern, error_type in error_patterns:
if re.search(pattern, output_text, re.IGNORECASE):
error_detected = True
error_message = f"{error_type}: {output_text.strip()}"
self.status_text.insert(tk.END, f"Error detected: {error_type}\n")
break
# If error detected, wait for a while to collect more logs, then try to recover
if error_detected:
# Continue reading some output to get more error information
for _ in range(10): # Read up to 10 lines of extra output
try:
more_output = self.server_process.stdout.readline()
if more_output:
more_text = more_output.decode(errors='replace')
self.status_text.insert(tk.END, more_text)
error_message += "\n" + more_text.strip()
except:
break
time.sleep(0.1)
# If it's an out of memory error, try fallback startup method
if "Out of Memory" in error_message:
self.status_text.insert(tk.END, "Out of memory error detected, attempting fallback startup method...\n")
# Stop current process
try:
self.server_process.terminate()
self.server_process.wait(timeout=5)
except:
pass
# Attempt to start using fallback method
self.fallback_start_server(error_message)
return
# If port is already in use, try a different port
elif "Port Already in Use" in error_message:
self.status_text.insert(tk.END, "Port already in use detected, attempting to use a different port...\n")
# Stop current process
try:
self.server_process.terminate()
self.server_process.wait(timeout=5)
except:
pass
# Attempt to use a different port
self.config['port'] += 1
self.status_text.insert(tk.END, f"Attempting to use new port: {self.config['port']}\n")
self.start_server()
return
else:
# Other errors, display error message and ask user if they want to try fallback method
if messagebox.askokcancel("Error", f"An error occurred while starting the server:\n{error_message}\n\nAttempt to start using fallback method?"):
# Stop current process
try:
self.server_process.terminate()
self.server_process.wait(timeout=5)
except:
pass
# Attempt to start using fallback method
self.fallback_start_server(error_message)
return
# Check if successfully started (usually API related information appears within a few seconds)
if "API server" in output_text and time.time() - start_time > 5:
self.status_text.insert(tk.END, "Server started successfully\n")
server_started = True
# After server starts successfully, perform automatic performance optimization
if not hasattr(self, 'performance_optimized') or not self.performance_optimized:
threading.Thread(target=self.auto_optimize_performance, daemon=True).start()
self.performance_optimized = True
except Exception as e:
self.status_text.insert(tk.END, f"Error monitoring server output: {str(e)}\n")
time.sleep(1)
def update_gpu_stats(self):
while self.monitoring:
try:
gpus = GPUtil.getGPUs()
self.gpu_tree.delete(*self.gpu_tree.get_children())
for gpu in gpus:
# Use nvidia-smi to get power information
try:
power_info = subprocess.run(
['nvidia-smi', f'--id={gpu.id}', '--query-gpu=power.draw', '--format=csv,noheader,nounits'],
capture_output=True,
text=True
)
power_draw = power_info.stdout.strip()
except:
power_draw = "N/A"
self.gpu_tree.insert('', 'end', values=(
gpu.id,
f"{gpu.memoryUsed}MB/{gpu.memoryTotal}MB",
f"{gpu.load*100:.1f}%",
f"{gpu.temperature}°C",
f"{power_draw}W" if power_draw and power_draw != "N/A" else "N/A",
"0.0%" # KV Cache Hit Rate not supported yet
))
time.sleep(2)
except Exception as e:
self.status_text.insert(tk.END, f"GPU monitoring error: {e}\n")
self.status_text.see(tk.END)
time.sleep(5)
def get_gpu_stats(self):
"""Get GPU statistics, return list of dictionaries"""
try:
# Use pynvml library instead of executing nvidia-smi command
pynvml.nvmlInit()
gpu_count = pynvml.nvmlDeviceGetCount()
gpu_stats = []
for i in range(gpu_count):
handle = pynvml.nvmlDeviceGetHandleByIndex(i)
# Get GPU utilization
utilization = pynvml.nvmlDeviceGetUtilizationRates(handle)
gpu_util = f"{utilization.gpu} %"
mem_util = f"{utilization.memory} %"
# Get temperature
temp = pynvml.nvmlDeviceGetTemperature(handle, pynvml.NVML_TEMPERATURE_GPU)
# Get power consumption
try:
power = pynvml.nvmlDeviceGetPowerUsage(handle) / 1000.0
power_draw = f"{power:.1f} W"
except:
power_draw = "N/A"
gpu_stat = {
'utilization.gpu': gpu_util,
'utilization.memory': mem_util,
'temperature.gpu': f"{temp} C",
'power.draw': power_draw
}
gpu_stats.append(gpu_stat)
pynvml.nvmlShutdown()
return gpu_stats
except ImportError:
# If pynvml is not installed, return a simulated status message and log a warning
self.status_text.insert(tk.END, "Warning: pynvml not installed, cannot get GPU information. Please install with pip install nvidia-ml-py3.\n")
# Return a dictionary with default values to prevent program crash
return [{'utilization.gpu': '0 %', 'utilization.memory': '0 %', 'temperature.gpu': '0 C', 'power.draw': 'N/A'}]
except Exception as e:
# Log error but return an empty result set instead of raising an exception
self.status_text.insert(tk.END, f"Error getting GPU statistics: {str(e)}\n")
return []
def load_config(self):
try:
with open('server_config.json', 'r') as f:
loaded_config = json.load(f)
self.config.update(loaded_config)
# Update values on the interface
self.model_path_entry.delete(0, tk.END)
self.model_path_entry.insert(0, self.config['model_path'])
self.ip_entry.delete(0, tk.END)
self.ip_entry.insert(0, self.config['ip'])
self.port_entry.delete(0, tk.END)
self.port_entry.insert(0, str(self.config['port']))
self.gpu_count_var.set(str(self.config['gpu_count']))
self.mem_ratio_entry.delete(0, tk.END)
self.mem_ratio_entry.insert(0, str(self.config['mem_ratio']))
self.max_tokens_var.set(str(self.config['max_tokens']))
self.max_model_len_var.set(str(self.config['max_model_len'])) # Load max_model_len
# Load memory offload configuration
if 'enable_memory_offload' in self.config:
self.enable_offload_var.set(self.config['enable_memory_offload'])
if 'memory_channels' in self.config:
self.memory_channels_var.set(str(self.config['memory_channels']))
if 'memory_offload_ratio' in self.config:
self.memory_offload_ratio_var.set(str(self.config['memory_offload_ratio']))
if 'reserved_memory' in self.config:
self.reserved_memory_var.set(str(self.config['reserved_memory']))
except FileNotFoundError:
pass
def save_config(self):
with open('server_config.json', 'w') as f:
json.dump(self.config, f, indent=4)
def save_config_with_message(self):
# First call update_config to ensure configuration is updated
if self.update_config():
# Save configuration
self.save_config()
messagebox.showinfo("Success", "Configuration saved to server_config.json")
def select_calibrated_model(self):
path = filedialog.askdirectory(title="Select Calibrated Model Directory")
if path:
self.calibrated_model_var.set(path)
self.config['calibrated_model'] = path
def check_fp8_support(self):
try:
if not torch.cuda.is_available():
return False
capability = torch.cuda.get_device_capability()
# Requires Ampere or newer architecture (compute capability >= 8.0)
return capability[0] >= 8
except Exception as e:
print(f"Failed to check FP8 support: {e}")
return False
def run_calibration(self):
if not self.check_fp8_support():
messagebox.showerror("Error", "Current GPU does not support FP8 quantization")
return
if not self.config['model_path']:
messagebox.showerror("Error", "Please select a model path first")
return
# Generate calibration script
calibration_script = f"""
from datasets import load_dataset
from transformers import AutoModelForCausalLM, AutoTokenizer
from llmcompressor.transformers import oneshot
# Load model
model = AutoModelForCausalLM.from_pretrained("{self.config['model_path']}",
device_map="auto",
torch_dtype="auto")
tokenizer = AutoTokenizer.from_pretrained("{self.config['model_path']}")
# Configure calibration parameters
NUM_CALIBRATION_SAMPLES = 512
MAX_SEQUENCE_LENGTH = 2048
# Load dataset
ds = load_dataset("HuggingFaceH4/ultrachat_200k", split="train_sft")
ds = ds.shuffle(seed=42).select(range(NUM_CALIBRATION_SAMPLES))
def process_and_tokenize(example):
text = tokenizer.apply_chat_template(example["messages"], tokenize=False)
return tokenizer(
text,
padding=False,
max_length=MAX_SEQUENCE_LENGTH,
truncation=True,
add_special_tokens=False,
)
ds = ds.map(process_and_tokenize, remove_columns=ds.column_names)
# Quantization configuration
recipe = '''
quant_stage:
quant_modifiers:
QuantizationModifier:
kv_cache_scheme:
num_bits: 8
type: float
strategy: tensor
dynamic: false
symmetric: true
'''
# Apply quantization
oneshot(
model=model,
dataset=ds,
recipe=recipe,
max_seq_length=MAX_SEQUENCE_LENGTH,
num_calibration_samples=NUM_CALIBRATION_SAMPLES,
)
# Save quantized model
SAVE_DIR = "{os.path.basename(self.config['model_path'])}-FP8-KV"
model.save_pretrained(SAVE_DIR, save_compressed=True)
tokenizer.save_pretrained(SAVE_DIR)
"""
# Save and run calibration script
with open("run_calibration.py", "w") as f:
f.write(calibration_script)
# Detect OS, use appropriate method to start process
try:
if sys.platform == 'win32':
# Windows system
subprocess.Popen(["python", "run_calibration.py"],
cwd=os.getcwd(),
creationflags=subprocess.CREATE_NEW_CONSOLE)
else:
# Linux/Mac system
subprocess.Popen(["python", "run_calibration.py"],
cwd=os.getcwd())
messagebox.showinfo("Calibration", "Calibration process started, please wait for completion...")
except Exception as e:
self.status_text.insert(tk.END, f"Failed to start calibration process: {str(e)}\n")
messagebox.showerror("Error", f"Failed to start calibration process: {str(e)}")
def get_available_system_memory(self):
"""Get available system memory (GB)"""
mem = psutil.virtual_memory()
# Return available memory (GB)
return mem.available / (1024 * 1024 * 1024)
def get_available_vram(self, use_ratio=None):
"""Get available VRAM (GB)"""
try:
gpus = GPUtil.getGPUs()
if not gpus:
return 0
# If using multiple GPUs, calculate total VRAM
if self.config['gpu_count'] > 1:
total_vram = sum([gpu.memoryTotal for gpu in gpus[:self.config['gpu_count']]])
else:
total_vram = gpus[0].memoryTotal
# Convert to GB and apply VRAM ratio
ratio = use_ratio if use_ratio is not None else (self.config['mem_ratio'] / 100)
return total_vram * ratio / 1024
except Exception as e:
self.status_text.insert(tk.END, f"Error getting VRAM information: {e}\n")
return 0
def estimate_model_size(self):
"""Estimate model size (GB)"""
try:
# Simple estimation: check total size of .bin files in model directory