(req: BatchPredictRequest)
| 144 | # 接口 2: 批量预测 (支撑 5x11 并发) |
| 145 | @app.post("/predict_batch", response_model=BatchPredictResponse) |
| 146 | async def predict_batch(req: BatchPredictRequest): |
| 147 | if model is None: raise HTTPException(500, "Model not ready") |
| 148 | |
| 149 | batch_size = len(req.images) |
| 150 | if batch_size == 0: return BatchPredictResponse(labels=[], logits_batch=[]) |
| 151 | |
| 152 | try: |
| 153 | # List -> Tensor -> GPU |
| 154 | # 这一步对于大 Batch 可能会有点慢,但比起 HTTP RTT 已经很快了 |
| 155 | input_tensor = torch.tensor(req.images).float().to(DEVICE) |
| 156 | input_tensor = input_tensor.view(-1, 3, 32, 32) |
| 157 | |
| 158 | with torch.no_grad(): # 必加:显存保护 |
| 159 | output = model(input_tensor) |
| 160 | pred_labels = output.argmax(dim=1).cpu().tolist() |
| 161 | pred_logits = output.cpu().tolist() |
| 162 | |
| 163 | return BatchPredictResponse(labels=pred_labels, logits_batch=pred_logits) |
| 164 | |
| 165 | except Exception as e: |
| 166 | raise HTTPException(500, str(e)) |
| 167 | |
| 168 | # 本地调试用 |
| 169 | if __name__ == "__main__": |
nothing calls this directly
no test coverage detected