codemo commited on
Commit
107f99d
·
verified ·
1 Parent(s): d8b36db

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -0
app.py CHANGED
@@ -45,6 +45,47 @@ model = AutoModel.from_pretrained(
45
  )
46
  model = model.eval().to(device)
47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  MODEL_CONFIGS = {
49
  "⚡ Gundam": {"base_size": 1024, "image_size": 640, "crop_mode": True},
50
  "🚀 Tiny": {"base_size": 512, "image_size": 512, "crop_mode": False},
 
45
  )
46
  model = model.eval().to(device)
47
 
48
+ # 创建设备兼容的推理包装器
49
+ original_infer = model.infer
50
+
51
+ def device_compatible_infer(*args, **kwargs):
52
+ """设备兼容的推理包装器,支持 CPU/GPU 自动切换"""
53
+ import torch
54
+
55
+ # 临时修补 torch.cuda.is_available 和相关方法
56
+ old_is_available = torch.cuda.is_available
57
+ old_cuda_method = None
58
+
59
+ try:
60
+ # 如果是 CPU 模式,劫持 CUDA 调用
61
+ if device == "cpu":
62
+ torch.cuda.is_available = lambda: False
63
+
64
+ # 修补 tensor.cuda() 方法
65
+ def cpu_wrapper(self, *args, **kwargs):
66
+ return self.cpu()
67
+
68
+ # 保存原始方法
69
+ if hasattr(torch.Tensor, '_original_cuda'):
70
+ old_cuda_method = torch.Tensor._original_cuda
71
+ else:
72
+ old_cuda_method = torch.Tensor.cuda
73
+ torch.Tensor._original_cuda = old_cuda_method
74
+
75
+ torch.Tensor.cuda = cpu_wrapper
76
+
77
+ # 调用原始 infer 方法
78
+ return original_infer(*args, **kwargs)
79
+
80
+ finally:
81
+ # 恢复原始方法
82
+ torch.cuda.is_available = old_is_available
83
+ if old_cuda_method is not None:
84
+ torch.Tensor.cuda = old_cuda_method
85
+
86
+ # 替换模型的 infer 方法
87
+ model.infer = device_compatible_infer
88
+
89
  MODEL_CONFIGS = {
90
  "⚡ Gundam": {"base_size": 1024, "image_size": 640, "crop_mode": True},
91
  "🚀 Tiny": {"base_size": 512, "image_size": 512, "crop_mode": False},