-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
3309 lines (2808 loc) · 130 KB
/
app.py
File metadata and controls
3309 lines (2808 loc) · 130 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
# -*- coding: utf-8 -*-
"""
MLSharp-3D-Maker - 统一版本
支持 NVIDIA/AMD/Intel GPU 和 CPU,自动检测并优化
"""
import sys
import os
import subprocess
import platform
import traceback
import argparse
import shutil
import uuid
import threading
import webbrowser
import time
import asyncio
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from typing import Optional, Tuple, Dict, Any, List
from pydantic import BaseModel, Field
import numpy as np
import torch
import json
import yaml
from loguru import logger
from metrics import init_metrics, get_metrics_manager
from i18n import i18n
# 设置输出编码为 UTF-8(Windows)
if sys.platform == 'win32':
import codecs
sys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach())
sys.stderr = codecs.getwriter('utf-8')(sys.stderr.detach())
sys.stdin = codecs.getreader('utf-8')(sys.stdin.detach())
# ================= 配置类 =================
@dataclass
class AppConfig:
"""应用配置"""
base_dir: str
python_env: str
assets_dir: str
checkpoint: str
temp_dir: str
@classmethod
def from_current_dir(cls) -> 'AppConfig':
"""从当前目录创建配置"""
base_dir = os.path.dirname(os.path.abspath(__file__))
return cls(
base_dir=base_dir,
python_env=os.path.join(base_dir, "python_env"),
assets_dir=os.path.join(base_dir, "model_assets"),
checkpoint=os.path.join(base_dir, "model_assets", "sharp_2572gikvuh.pt"),
temp_dir=os.path.join(base_dir, "temp_workspace")
)
@dataclass
class GPUConfig:
"""GPU 配置"""
available: bool = False
vendor: str = "Unknown"
name: str = "N/A"
cuda_version: Optional[str] = None
count: int = 0
compute_capability: int = 0
supports_tf32: bool = False
supports_bf16: bool = False
use_amp: bool = False
use_cudnn_benchmark: bool = False
use_tf32: bool = False
is_rocm: bool = False
# 内存回收配置
enable_auto_gc: bool = True # 启用自动垃圾回收
auto_gc_interval: int = 30 # 自动检查间隔(秒)
auto_gc_threshold: float = 85.0 # 触发清理的阈值(百分比)
enable_smart_reclaim: bool = True # 启用智能内存回收
@dataclass
class CLIArgs:
"""命令行参数"""
mode: str = 'auto'
port: int = 8000
host: str = '127.0.0.1'
no_browser: bool = False
no_amp: bool = False
no_cudnn_benchmark: bool = False
config_file: Optional[str] = None
input_size: Tuple[int, int] = (1536, 1536)
gradient_checkpointing: bool = False
checkpoint_segments: int = 3
enable_cache: bool = True
no_cache: bool = False # 禁用缓存
cache_size: int = 100
clear_cache: bool = False
enable_auto_tune: bool = False
redis_url: Optional[str] = None
enable_webhook: bool = False
app_config: Optional[AppConfig] = None # 应用配置(用于性能自动调优)
# GPU 内存回收参数
enable_auto_gc: bool = True # 启用自动垃圾回收
auto_gc_interval: int = 30 # 自动检查间隔(秒)
auto_gc_threshold: float = 85.0 # 触发清理的阈值(百分比)
enable_smart_reclaim: bool = True # 启用智能内存回收
# 语言设置
language: str = 'zh' # 语言设置 ('zh' 或 'en')
# ================= 配置文件加载 =================
def load_config_file(config_path: str) -> Dict[str, Any]:
"""
从配置文件加载配置
支持 YAML 和 JSON 格式
Args:
config_path: 配置文件路径
Returns:
配置字典
Raises:
FileNotFoundError: 配置文件不存在
ValueError: 配置文件路径不安全
"""
# 路径安全验证
config_path_real = os.path.realpath(config_path)
# 检查文件扩展名是否合法
file_ext = os.path.splitext(config_path_real)[1].lower()
if file_ext not in ['.yaml', '.yml', '.json']:
raise ValueError(i18n.t('config_format_unsupported').format(file_ext))
# 检查文件是否存在
if not os.path.exists(config_path_real):
raise FileNotFoundError(i18n.t('config_not_found').format(config_path))
# 安全检查:确保配置文件路径在合理范围内
# 允许当前工作目录、用户主目录、应用目录等
cwd_real = os.path.realpath(os.getcwd())
allowed_paths = [cwd_real]
# 添加用户主目录(如果有)
home_dir = os.path.expanduser('~')
if home_dir and os.path.exists(home_dir):
allowed_paths.append(os.path.realpath(home_dir))
# 添加常见的配置目录
for allowed in allowed_paths:
if config_path_real.startswith(allowed):
break
else:
# 如果不在允许的路径内,发出警告但仍允许加载(因为用户可能有意指定外部配置)
import warnings
warnings.warn(i18n.t('config_path_unexpected').format(config_path_real))
try:
with open(config_path_real, 'r', encoding='utf-8') as f:
if file_ext in ['.yaml', '.yml']:
return yaml.safe_load(f)
elif file_ext == '.json':
return json.load(f)
else:
raise ValueError(i18n.t('config_format_unsupported').format(file_ext))
except Exception as e:
raise RuntimeError(i18n.t('config_load_failed').format(e))
def validate_input_size(width: int, height: int) -> Tuple[int, int]:
"""
验证并调整输入尺寸以符合模型要求
SHaRP 模型的编码器使用基于补丁的分割,要求:
- 尺寸必须能被 64 整除(补丁大小)
- 宽度和高度必须相等
- 最大尺寸限制为 1536(SPN 编码器在更大尺寸下会出现补丁分割问题)
Args:
width: 输入宽度
height: 输入高度
Returns:
调整后的 (width, height)
"""
# 检查宽高是否相等
if width != height:
print(i18n.t('print_size_mismatch').format(width, height))
size = max(width, height)
width = height = size
print(i18n.t('print_adjusted').format(width, height))
# 限制最大尺寸为 1536(SPN 编码器在更大尺寸下会出现补丁分割问题)
max_size = 1536
if width > max_size or height > max_size:
print(i18n.t('print_exceeds_max').format(width, height, max_size, max_size))
print(i18n.t('print_patch_error'))
print(i18n.t('print_adjusted').format(max_size, max_size))
width = height = max_size
# 检查是否能被 64 整除
if width % 64 != 0 or height % 64 != 0:
print(i18n.t('print_not_divisible').format(width, height))
# 向上取整到最近的 64 倍数
width = ((width + 63) // 64) * 64
height = ((height + 63) // 64) * 64
print(i18n.t('print_adjusted').format(width, height))
# 再次检查调整后的尺寸是否超过最大值
if width > max_size or height > max_size:
print(i18n.t('print_still_exceeds').format(width, height))
print(i18n.t('print_adjusted').format(max_size, max_size))
width = height = max_size
return width, height
def merge_config_with_args(config: Dict[str, Any], args: CLIArgs) -> Dict[str, Any]:
"""
合并配置文件和命令行参数
命令行参数优先级高于配置文件
Args:
config: 配置文件字典
args: 命令行参数
Returns:
合并后的配置字典
"""
# 服务器配置
if args.host != '127.0.0.1':
config.setdefault('server', {})['host'] = args.host
if args.port != 8000:
config.setdefault('server', {})['port'] = args.port
# 启动模式
if args.mode != 'auto':
config['mode'] = args.mode
# 浏览器配置
if args.no_browser:
config.setdefault('browser', {})['auto_open'] = False
# GPU 配置
if args.no_amp:
config.setdefault('gpu', {})['enable_amp'] = False
if args.no_cudnn_benchmark:
config.setdefault('gpu', {})['enable_cudnn_benchmark'] = False
# 推理配置
if args.input_size != (1536, 1536):
config.setdefault('inference', {})['input_size'] = list(args.input_size)
# 优化配置
if args.gradient_checkpointing:
config.setdefault('optimization', {})['gradient_checkpointing'] = True
if args.checkpoint_segments != 3:
config.setdefault('optimization', {})['checkpoint_segments'] = args.checkpoint_segments
# 缓存配置
if args.enable_cache:
config.setdefault('cache', {})['enabled'] = True
if args.no_cache:
config.setdefault('cache', {})['enabled'] = False
if args.cache_size != 100:
config.setdefault('cache', {})['size'] = args.cache_size
# GPU 内存回收配置
if not args.enable_auto_gc:
config.setdefault('gpu', {})['enable_auto_gc'] = False
if args.auto_gc_interval != 30:
config.setdefault('gpu', {})['auto_gc_interval'] = args.auto_gc_interval
if args.auto_gc_threshold != 85.0:
config.setdefault('gpu', {})['auto_gc_threshold'] = args.auto_gc_threshold
if not args.enable_smart_reclaim:
config.setdefault('gpu', {})['enable_smart_reclaim'] = False
return config
def config_to_cli_args(config: Dict[str, Any]) -> CLIArgs:
"""
将配置字典转换为 CLIArgs
Args:
config: 配置字典
Returns:
CLIArgs 对象
"""
server = config.get('server', {})
browser = config.get('browser', {})
gpu = config.get('gpu', {})
inference = config.get('inference', {})
optimization = config.get('optimization', {})
cache = config.get('cache', {})
input_size = tuple(inference.get('input_size', [1536, 1536]))
return CLIArgs(
mode=config.get('mode', 'auto'),
port=server.get('port', 8000),
host=server.get('host', '127.0.0.1'),
no_browser=not browser.get('auto_open', True),
no_amp=not gpu.get('enable_amp', True),
no_cudnn_benchmark=not gpu.get('enable_cudnn_benchmark', True),
config_file=None,
input_size=input_size,
gradient_checkpointing=optimization.get('gradient_checkpointing', False),
checkpoint_segments=optimization.get('checkpoint_segments', 3),
enable_cache=cache.get('enabled', True),
cache_size=cache.get('size', 100),
enable_auto_gc=gpu.get('enable_auto_gc', True),
auto_gc_interval=gpu.get('auto_gc_interval', 30),
auto_gc_threshold=gpu.get('auto_gc_threshold', 85.0),
enable_smart_reclaim=gpu.get('enable_smart_reclaim', True)
)
# ================= 日志工具 =================
class Logger:
"""日志工具类 - 基于 loguru"""
def __init__(self):
"""初始化日志系统"""
# 移除默认的 handler
logger.remove()
# 添加控制台 handler - 改进格式,增加更多上下文信息
logger.add(
sys.stdout,
format="<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> | <level>{message}</level>",
level="INFO",
colorize=True,
backtrace=True,
diagnose=True
)
# 添加文件 handler(可选)
log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = os.path.join(log_dir, f"mlsharp_{time.strftime('%Y%m%d')}.log")
logger.add(
log_file,
format="{time:YYYY-MM-DD HH:mm:ss.SSS} | {level: <8} | {name}:{function}:{line} | {message}",
level="DEBUG",
rotation="10 MB",
retention="14 days", # 增加保留时间
compression="zip",
backtrace=True,
diagnose=True
)
@staticmethod
def section(title_key: str, char: str = '=', length: int = 60):
"""打印分隔线
Args:
title_key: 翻译键或直接文本
"""
title = i18n.t(title_key) if hasattr(i18n, 't') and i18n.t(title_key) != title_key else title_key
print(f"\n{char * length}")
print(f"[INFO] {title}")
print(f"{char * length}\n")
@staticmethod
def styled_section(title: str, style: str = 'default'):
"""打印样式化的分隔线"""
styles = {
'default': ('=', '-', '─'),
'highlight': ('*', '•', '◆'),
'warning': ('!', '!', '⚠'),
'success': ('+', '+', '✓'),
'error': ('×', '×', '✗'),
'info': ('→', '→', 'ℹ')
}
if style not in styles:
style = 'default'
border, separator, icon = styles[style]
logger.opt(colors=True).info(f"<yellow>{border * 20}</yellow> <cyan>{icon} {title}</cyan> <yellow>{border * 20}</yellow>")
@staticmethod
def progress_info(current: int, total: int, message: str = None):
"""显示进度信息"""
if message is None:
message = i18n.t('progress_processing')
percentage = (current / total) * 100 if total > 0 else 0
bar_length = 20
filled_length = int(bar_length * current // total) if total > 0 else 0
bar = '█' * filled_length + '-' * (bar_length - filled_length)
logger.info(f"{message}: |{bar}| {percentage:.1f}% ({current}/{total})")
@staticmethod
def error(error_msg: str, solution: Optional[str] = None, exc_info: Optional[Exception] = None):
"""打印错误信息和解决方案
Args:
error_msg: 错误消息
solution: 可选的解决方案提示
exc_info: 可选的异常对象,如果提供则打印堆栈信息
"""
logger.opt(colors=True).error(f"<red>❌ {i18n.t('log_error')}:</red> {error_msg}")
if solution:
logger.opt(colors=True).info(f"<green>💡 {i18n.t('log_solution')}:</green> {solution}")
# 只在有活跃异常或显式传入异常时打印堆栈
if exc_info is not None:
logger.opt(colors=True).debug(f"<magenta>📋 {i18n.t('log_detail_error')}:</magenta>\n{traceback.format_exception(type(exc_info), exc_info, exc_info.__traceback__)}")
elif sys.exc_info()[0] is not None:
logger.opt(colors=True).debug(f"<magenta>📋 {i18n.t('log_detail_error')}:</magenta>\n{traceback.format_exc()}")
@staticmethod
def success(msg: str):
"""打印成功信息"""
logger.opt(colors=True).success(f"<green>✓</green> {msg}")
@staticmethod
def warning(msg: str):
"""打印警告信息"""
logger.opt(colors=True).warning(f"<yellow>⚠</yellow> {msg}")
@staticmethod
def info(msg: str):
"""打印信息"""
logger.opt(colors=True).info(f"{msg}")
@staticmethod
def debug(msg: str):
"""打印调试信息"""
logger.opt(colors=True).debug(f"<cyan>🔍</cyan> {msg}")
@staticmethod
def exception(msg: str, exc_info: Optional[Exception] = None):
"""打印异常信息
Args:
msg: 异常消息
exc_info: 可选的异常对象
"""
logger.opt(colors=True).error(f"<red>💥 {i18n.t('log_exception')}:</red> {msg}")
# 只在有活跃异常或显式传入异常时打印堆栈
if exc_info is not None:
logger.opt(colors=True).debug(f"<magenta>📋 {i18n.t('log_detail_exception')}:</magenta>\n{traceback.format_exception(type(exc_info), exc_info, exc_info.__traceback__)}")
elif sys.exc_info()[0] is not None:
logger.opt(colors=True).debug(f"<magenta>📋 {i18n.t('log_detail_exception')}:</magenta>\n{traceback.format_exc()}")
@staticmethod
def critical(msg: str, solution: Optional[str] = None, exc_info: Optional[Exception] = None):
"""打印严重错误信息
Args:
msg: 严重错误消息
solution: 可选的紧急解决方案
exc_info: 可选的异常对象
"""
logger.opt(colors=True).critical(f"<red>🔥 {i18n.t('log_critical')}:</red> {msg}")
if solution:
logger.opt(colors=True).info(f"<green>🚨 {i18n.t('log_emergency_solution')}:</green> {solution}")
# 只在有活跃异常或显式传入异常时打印堆栈
if exc_info is not None:
logger.opt(colors=True).debug(f"<magenta>📋 {i18n.t('log_detail_error')}:</magenta>\n{traceback.format_exception(type(exc_info), exc_info, exc_info.__traceback__)}")
elif sys.exc_info()[0] is not None:
logger.opt(colors=True).debug(f"<magenta>📋 {i18n.t('log_detail_error')}:</magenta>\n{traceback.format_exc()}")
@staticmethod
def performance(msg: str):
"""打印性能相关信息"""
logger.opt(colors=True).info(f"<blue>⏱️ {i18n.t('log_performance')}:</blue> {msg}")
@staticmethod
def gpu_info(msg: str):
"""打印GPU相关信息"""
logger.opt(colors=True).info(f"<cyan>🎮 {i18n.t('log_gpu')}:</cyan> {msg}")
@staticmethod
def cache_info(msg: str):
"""打印缓存相关信息"""
logger.opt(colors=True).info(f"<purple>📦 {i18n.t('log_cache')}:</purple> {msg}")
@staticmethod
def plain_success(msg: str):
"""打印不带样式的成功信息(用于特殊场景)"""
logger.success(msg)
@staticmethod
def plain_warning(msg: str):
"""打印不带样式的警告信息(用于特殊场景)"""
logger.warning(msg)
@staticmethod
def plain_info(msg: str):
"""打印不带样式的信息(用于特殊场景)"""
logger.info(msg)
@staticmethod
def plain_debug(msg: str):
"""打印不带样式的调试信息(用于特殊场景)"""
logger.debug(msg)
@staticmethod
def plain_exception(msg: str):
"""打印不带样式的异常信息(用于特殊场景)"""
logger.exception(msg)
# ================= 命令行参数解析 =================
def parse_command_args() -> Tuple[CLIArgs, Optional[Dict[str, Any]]]:
"""解析命令行参数
Returns:
(CLIArgs, 配置文件字典或None)
"""
# 先解析语言参数,以便帮助信息可以使用正确的语言
import sys
lang = 'zh' # 默认语言
for i, arg in enumerate(sys.argv):
if arg in ('--lang', '--language'):
if i + 1 < len(sys.argv) and sys.argv[i + 1] in ('zh', 'en'):
lang = sys.argv[i + 1]
break
# 设置语言
i18n.set_language(lang)
parser = argparse.ArgumentParser(
description=i18n.t('cli_description'),
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=i18n.t('cli_epilog') if hasattr(i18n, 'translations') and 'cli_epilog' in i18n.translations.get(lang, {}) else """
启动模式说明:
auto 自动检测并选择最佳模式(默认)
gpu 强制使用 GPU 模式(自动检测厂商)
cpu 强制使用 CPU 模式
nvidia 强制使用 NVIDIA GPU 模式
amd 强制使用 AMD GPU 模式(ROCm)
配置文件:
支持 YAML 和 JSON 格式
配置文件优先级低于命令行参数
示例:
python app.py # 自动检测模式
python app.py --mode gpu # 强制 GPU 模式
python app.py --config config.yaml # 使用配置文件
python app.py --port 8080 # 使用 8080 端口
"""
)
parser.add_argument('--mode', '-m', type=str, default='auto',
choices=['auto', 'gpu', 'cpu', 'nvidia', 'amd'],
help=i18n.t('arg_mode_help'))
parser.add_argument('--port', '-p', type=int, default=8000,
help=i18n.t('arg_port_help'))
parser.add_argument('--host', type=str, default='127.0.0.1',
help=i18n.t('arg_host_help'))
parser.add_argument('--no-browser', action='store_true',
help=i18n.t('arg_no_browser_help'))
parser.add_argument('--no-amp', action='store_true',
help=i18n.t('arg_no_amp_help'))
parser.add_argument('--no-cudnn-benchmark', action='store_true',
help=i18n.t('arg_no_cudnn_help'))
parser.add_argument('--config', '-c', type=str, default=None,
help=i18n.t('arg_config_help'))
parser.add_argument('--input-size', type=int, nargs=2, default=[1536, 1536],
metavar=('WIDTH', 'HEIGHT'),
help=i18n.t('arg_input_size_help'))
parser.add_argument('--gradient-checkpointing', action='store_true',
help=i18n.t('arg_gradient_help'))
parser.add_argument('--checkpoint-segments', type=int, default=3,
help=i18n.t('arg_segments_help'))
parser.add_argument('--enable-cache', action='store_true', default=True,
help=i18n.t('arg_cache_help'))
parser.add_argument('--no-cache', action='store_true',
help=i18n.t('arg_no_cache_help'))
parser.add_argument('--cache-size', type=int, default=100,
help=i18n.t('arg_cache_size_help'))
parser.add_argument('--clear-cache', action='store_true',
help=i18n.t('arg_clear_cache_help'))
parser.add_argument('--enable-auto-tune', action='store_true',
help=i18n.t('arg_auto_tune_help'))
parser.add_argument('--redis-url', type=str, default=None,
help=i18n.t('arg_redis_help'))
parser.add_argument('--enable-webhook', action='store_true',
help=i18n.t('arg_webhook_help'))
# GPU 内存回收参数
parser.add_argument('--enable-auto-gc', action='store_true', default=True,
help=i18n.t('arg_auto_gc_help'))
parser.add_argument('--no-auto-gc', action='store_true',
help=i18n.t('arg_no_auto_gc_help'))
parser.add_argument('--auto-gc-interval', type=int, default=30,
help=i18n.t('arg_gc_interval_help'))
parser.add_argument('--auto-gc-threshold', type=float, default=85.0,
help=i18n.t('arg_gc_threshold_help'))
parser.add_argument('--enable-smart-reclaim', action='store_true', default=True,
help=i18n.t('arg_smart_reclaim_help'))
parser.add_argument('--no-smart-reclaim', action='store_true',
help=i18n.t('arg_no_smart_reclaim_help'))
# 语言设置
parser.add_argument('--lang', '--language', type=str, default='zh',
choices=['zh', 'en'],
help=i18n.t('arg_lang_help'))
args = parser.parse_args()
# 确保语言设置正确(以防通过参数解析改变)
i18n.set_language(args.lang)
# 处理缓存参数
enable_cache = args.enable_cache and not args.no_cache
# 转换 input_size 为元组
input_size = tuple(args.input_size)
# 验证输入尺寸
validated_width, validated_height = validate_input_size(*input_size)
if validated_width != input_size[0] or validated_height != input_size[1]:
Logger.info(i18n.t('input_size_adjusted').format(input_size[0], input_size[1], validated_width, validated_height))
input_size = (validated_width, validated_height)
# 加载配置文件
config_dict = None
if args.config:
try:
config_dict = load_config_file(args.config)
# 合并配置文件和命令行参数
config_dict = merge_config_with_args(config_dict, args)
# 转换为 CLIArgs
cli_args = config_to_cli_args(config_dict)
cli_args.config_file = args.config
cli_args.language = args.lang # 设置语言
except Exception as e:
print(f"[ERROR] {i18n.t('load_config_failed', e)}")
print(f"[INFO] {i18n.t('use_default_config_and_args')}")
# 处理内存回收参数
enable_auto_gc = args.enable_auto_gc and not args.no_auto_gc
enable_smart_reclaim = args.enable_smart_reclaim and not args.no_smart_reclaim
cli_args = CLIArgs(
mode=args.mode,
port=args.port,
host=args.host,
no_browser=args.no_browser,
no_amp=args.no_amp,
no_cudnn_benchmark=args.no_cudnn_benchmark,
config_file=None,
input_size=input_size,
gradient_checkpointing=args.gradient_checkpointing,
checkpoint_segments=args.checkpoint_segments,
enable_cache=enable_cache,
cache_size=args.cache_size,
clear_cache=args.clear_cache,
enable_auto_tune=args.enable_auto_tune,
enable_auto_gc=enable_auto_gc,
auto_gc_interval=args.auto_gc_interval,
auto_gc_threshold=args.auto_gc_threshold,
enable_smart_reclaim=enable_smart_reclaim,
language=args.lang # 设置语言
)
else:
# 处理内存回收参数
enable_auto_gc = args.enable_auto_gc and not args.no_auto_gc
enable_smart_reclaim = args.enable_smart_reclaim and not args.no_smart_reclaim
cli_args = CLIArgs(
mode=args.mode,
port=args.port,
host=args.host,
no_browser=args.no_browser,
no_amp=args.no_amp,
no_cudnn_benchmark=args.no_cudnn_benchmark,
config_file=None,
input_size=input_size,
gradient_checkpointing=args.gradient_checkpointing,
checkpoint_segments=args.checkpoint_segments,
enable_cache=enable_cache,
cache_size=args.cache_size,
clear_cache=args.clear_cache,
enable_auto_tune=args.enable_auto_tune,
enable_auto_gc=enable_auto_gc,
auto_gc_interval=args.auto_gc_interval,
auto_gc_threshold=args.auto_gc_threshold,
enable_smart_reclaim=enable_smart_reclaim,
language=args.lang # 设置语言
)
# 设置 app_config(性能自动调优需要)
app_config = AppConfig.from_current_dir()
cli_args.app_config = app_config
return cli_args, config_dict
# ================= 导入 FastAPI 相关模块 =================
import uvicorn
from fastapi import FastAPI, UploadFile, File
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
# ================= GPU 管理器 =================
class GPUManager:
"""GPU 管理器"""
def __init__(self, config: GPUConfig, args: CLIArgs):
self.config = config
self.args = args
self.app_config = args.app_config if hasattr(args, 'app_config') else None
self.device = torch.device("cpu")
@staticmethod
def detect_gpu_vendor_wmi() -> str:
"""通过 WMI 检测显卡厂商"""
try:
# 首先尝试使用 PowerShell Get-CimInstance(Windows 11 推荐)
result = subprocess.run(
['powershell', '-Command',
'Get-CimInstance Win32_VideoController | Select-Object -ExpandProperty Name'],
capture_output=True, text=True, encoding='utf-8', errors='ignore'
)
if result.returncode == 0 and result.stdout.strip():
lines = result.stdout.strip().split('\n')
# 优先检测 NVIDIA/AMD 独立显卡,避免被 Intel 集显干扰
nvidia_found = False
amd_found = False
intel_found = False
for line in lines:
name = line.strip().lower()
if 'nvidia' in name or 'geforce' in name or 'quadro' in name or 'tesla' in name or 'rtx' in name or 'gtx' in name:
nvidia_found = True
elif 'amd' in name or 'radeon' in name or 'rx' in name:
amd_found = True
elif 'intel' in name or 'iris' in name or 'uhd' in name or 'arc' in name:
intel_found = True
# 返回优先级最高的厂商
if nvidia_found:
return 'NVIDIA'
elif amd_found:
return 'AMD'
elif intel_found:
return 'Intel'
else:
# 回退到 wmic 命令(Windows 10 及更早版本)
result = subprocess.run(
['wmic', 'path', 'win32_VideoController', 'get', 'name'],
capture_output=True, text=True, encoding='utf-8', errors='ignore'
)
if result.returncode == 0:
lines = result.stdout.strip().split('\n')[1:]
nvidia_found = False
amd_found = False
intel_found = False
for line in lines:
name = line.strip().lower()
if 'nvidia' in name or 'geforce' in name or 'quadro' in name or 'tesla' in name or 'rtx' in name or 'gtx' in name:
nvidia_found = True
elif 'amd' in name or 'radeon' in name or 'rx' in name:
amd_found = True
elif 'intel' in name or 'iris' in name or 'uhd' in name or 'arc' in name:
intel_found = True
if nvidia_found:
return 'NVIDIA'
elif amd_found:
return 'AMD'
elif intel_found:
return 'Intel'
except Exception as e:
Logger.warning(i18n.t('wmi_detection_failed').format(e))
return 'Unknown'
@staticmethod
def check_rocm_available() -> bool:
"""检查 ROCm 是否可用"""
try:
if torch.cuda.is_available():
if hasattr(torch.version, 'hip') and torch.version.hip is not None:
return True
device_name = torch.cuda.get_device_name(0).lower()
if 'amd' in device_name or 'radeon' in device_name:
return True
return False
except Exception as e:
Logger.warning(i18n.t('rocm_detection_failed').format(e))
return False
def initialize(self) -> torch.device:
"""初始化 GPU 设备"""
Logger.section("gpu_init_title")
if self.args.mode != 'auto':
Logger.info(i18n.t('user_specified_mode_info').format(self.args.mode.upper()))
else:
Logger.info(i18n.t('auto_detect_mode'))
force_mode = self.args.mode
if force_mode == 'cpu':
Logger.info(i18n.t('force_cpu_mode'))
try:
if torch.cuda.is_available() and force_mode != 'cpu':
self.config.available = True
self.config.name = torch.cuda.get_device_name(0)
self.config.cuda_version = torch.version.cuda
self.config.count = torch.cuda.device_count()
self.config.is_rocm = self.check_rocm_available()
system_vendor = self.detect_gpu_vendor_wmi()
# 优先根据 GPU 名称判断厂商
gpu_name_lower = self.config.name.lower()
# 判断 GPU 类型
if self.config.is_rocm:
self.config.vendor = "AMD"
Logger.success(i18n.t('amd_gpu_detected').format(self.config.name))
Logger.info(" ROCm: Yes")
elif 'nvidia' in gpu_name_lower or 'geforce' in gpu_name_lower or 'quadro' in gpu_name_lower or 'tesla' in gpu_name_lower or 'rtx' in gpu_name_lower or 'gtx' in gpu_name_lower:
self.config.vendor = "NVIDIA"
Logger.success(i18n.t('nvidia_gpu_detected').format(self.config.name))
elif 'amd' in gpu_name_lower or 'radeon' in gpu_name_lower or 'rx' in gpu_name_lower:
self.config.vendor = "AMD"
Logger.success(i18n.t('amd_gpu_detected').format(self.config.name))
elif 'intel' in gpu_name_lower or 'iris' in gpu_name_lower or 'uhd' in gpu_name_lower or 'arc' in gpu_name_lower:
self.config.vendor = "Intel"
Logger.success(i18n.t('intel_gpu_detected').format(self.config.name))
else:
# 如果 GPU 名称无法判断,使用系统检测结果
if system_vendor == 'NVIDIA':
self.config.vendor = "NVIDIA"
Logger.success(i18n.t('nvidia_gpu_detected').format(self.config.name))
elif system_vendor == 'AMD':
self.config.vendor = "AMD"
Logger.success(i18n.t('amd_gpu_detected').format(self.config.name))
elif system_vendor == 'Intel':
self.config.vendor = "Intel"
Logger.success(i18n.t('intel_gpu_detected').format(self.config.name))
else:
self.config.vendor = "Unknown"
Logger.warning(i18n.t('unknown_gpu_detected').format(self.config.name))
Logger.info(i18n.t('cuda_version_info').format(self.config.cuda_version))
Logger.info(i18n.t('gpu_count_info').format(self.config.count))
# 强制模式处理
if force_mode == 'nvidia':
if self.config.vendor != "NVIDIA":
Logger.warning(i18n.t('force_nvidia_mode').format(self.config.vendor))
self.config.vendor = "NVIDIA"
Logger.info(i18n.t('set_nvidia_mode'))
elif force_mode == 'amd':
if self.config.vendor != "AMD":
Logger.warning(i18n.t('force_amd_mode').format(self.config.vendor))
self.config.vendor = "AMD"
Logger.info(i18n.t('set_amd_mode'))
# 获取显卡属性
props = torch.cuda.get_device_properties(0)
self.config.compute_capability = props.major * 10 + props.minor
self.config.supports_tf32 = props.major >= 8
self.config.supports_bf16 = props.major >= 8
Logger.info(i18n.t('compute_capability_info_full').format(f"{props.major}.{props.minor}"))
Logger.info(i18n.t('gpu_memory_info_full').format(props.total_memory / 1024**3))
if props.total_memory < 4 * 1024**3:
Logger.warning(i18n.t('low_vram_warning'))
# 配置优化
self._configure_optimizations(props)
# 运行自动调优(如果启用)
self.run_auto_tune()
self.device = torch.device("cuda")
else:
self._setup_cpu_mode()
except Exception as e:
Logger.error(i18n.t('gpu_init_failed').format(e))
self.device = torch.device("cpu")
self.config.available = False
# CPU 优化设置
if not self.config.available:
torch.set_num_threads(os.cpu_count())
os.environ['OMP_NUM_THREADS'] = str(os.cpu_count())
os.environ['MKL_NUM_THREADS'] = str(os.cpu_count())
Logger.success(i18n.t('cpu_optimization_enabled').format(os.cpu_count()))
# 启动 GPU 自动内存监控
if self.config.available and self.args.enable_auto_gc:
Logger.info(i18n.t('gpu_memory_management'))
Logger.success(i18n.t('auto_gc_enabled'))
Logger.info(i18n.t('gc_interval_info').format(self.args.auto_gc_interval))
Logger.info(i18n.t('gc_threshold_info').format(self.args.auto_gc_threshold))
self.start_auto_monitor(
interval_seconds=self.args.auto_gc_interval,
threshold_percent=self.args.auto_gc_threshold
)
elif self.config.available:
Logger.info(i18n.t('gpu_memory_management'))
Logger.info(i18n.t('auto_gc_disabled'))
return self.device
def _configure_optimizations(self, props):
"""配置 GPU 优化选项"""
Logger.info(i18n.t('configure_optimizations'))
# cuDNN Benchmark
if self.config.vendor == "NVIDIA" and self.config.compute_capability >= 60 and not self.args.no_cudnn_benchmark:
try:
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.deterministic = False
self.config.use_cudnn_benchmark = True
Logger.success(i18n.t('cudnn_enabled_status'))
except Exception as e:
Logger.warning(i18n.t('cudnn_enable_failed').format(e))
else:
if self.config.vendor != "NVIDIA":
Logger.info(i18n.t('cudnn_not_applicable'))
else:
Logger.warning(i18n.t('cudnn_disabled_capability'))
# TensorFloat32
if self.config.vendor == "NVIDIA" and self.config.supports_tf32:
try:
torch.set_float32_matmul_precision('high')
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
self.config.use_tf32 = True
Logger.success(i18n.t('tf32_enabled_status'))
except Exception as e:
Logger.warning(i18n.t('tf32_enable_failed').format(e))
else:
if self.config.vendor != "NVIDIA":
Logger.info(i18n.t('tf32_not_applicable'))
else:
Logger.warning(i18n.t('tf32_disabled_support'))
# 混合精度
if self.config.compute_capability >= 53 and not self.args.no_amp:
self.config.use_amp = True
Logger.success(i18n.t('amp_enabled_status'))
else:
Logger.warning(i18n.t('amp_disabled_capability'))
def run_auto_tune(self):
"""
运行性能自动调优
自动测试不同的优化配置组合,选择最优配置
"""
if not self.args.enable_auto_tune:
return
try:
# 如果没有指定配置文件,使用默认的 config.yaml
config_file_path = self.args.config_file
if not config_file_path:
config_file_path = os.path.join(self.app_config.base_dir, 'config.yaml')
Logger.info(i18n.t('using_default_config_file').format(config_file_path))
tuner = PerformanceAutoTuner(self.config, self.device, config_file_path=config_file_path)
best_config = tuner.benchmark_optimizations()
if best_config:
Logger.success(i18n.t('tuning_complete'))
Logger.info(i18n.t('config_applied'))
else:
Logger.warning(i18n.t('tuning_failed_default'))
except Exception as e:
Logger.warning(i18n.t('tuning_failed').format(e))
Logger.info(i18n.t('use_default_config'))
def _setup_cpu_mode(self):
"""设置 CPU 模式"""
system_vendor = self.detect_gpu_vendor_wmi()
self.config.vendor = system_vendor
self.device = torch.device("cpu")
Logger.warning(i18n.t('cpu_mode'))
Logger.info(i18n.t('cuda_unavailable_cpu_mode'))
if system_vendor == "AMD":
Logger.info(i18n.t('amd_no_rocm'))
elif system_vendor == "NVIDIA":
Logger.info(i18n.t('nvidia_no_cuda'))
elif system_vendor == "Intel":