Vercel部署含PyTorch模型的Flask API遇data is too long错误求助
解决方案:Vercel部署PyTorch模型API报错"data is too long"
错误原因
Vercel的Lambda运行环境对部署包大小有严格限制(通常上限为50MB),PyTorch库本身体积较大,再加上GAN模型文件,最终构建产物超出限制,导致部署失败。
可行解决方案
1. 改用轻量版PyTorch依赖
替换标准PyTorch为CPU轻量版,大幅减少依赖体积:
- 在项目根目录的
requirements.txt中指定CPU版本的PyTorch:torch==2.0.0+cpu torchvision==0.15.1+cpu --extra-index-url https://download.pytorch.org/whl/cpu
2. 模型文件托管到外部存储,运行时加载
不要将模型打包进部署包,而是上传到云存储,在API启动时远程加载:
- 修改
gan_runner.py的load_model函数,添加远程下载逻辑:
注:首次请求会有模型下载延迟,后续请求复用本地缓存。import requests import os def load_model(): model_path = "./pretrained_model.pth" # 本地无模型则从远程下载 if not os.path.exists(model_path): model_url = "你的模型远程存储地址" response = requests.get(model_url) with open(model_path, "wb") as f: f.write(response.content) # 原有模型加载逻辑 model = ... # 你的模型初始化代码 return model
3. 拆分Serverless函数,隔离模型依赖
将模型相关逻辑拆分到单独的API函数,避免和Flask主应用打包:
- 在项目根目录创建
api/upscale.py,迁移模型处理逻辑:from PIL import Image import io from gan_runner import load_model, img_to_tensor, scale MODEL = load_model() def handler(request): if request.method != "POST": return {"error": "Method not allowed"}, 405 img_file = request.files.get("img") # 复用原文件校验逻辑 if img_file is None or img_file.filename == "": return {"error": "No file was provided."}, 400 if not "." in img_file.filename or img_file.filename.rsplit(".",1)[1].lower() not in ["png","jpg","jpeg"]: return {"error": "Only image files are allowed"}, 400 img_bytes = img_file.read() img_LR = img_to_tensor(img_bytes) output = scale(img_LR, MODEL) result_img = Image.fromarray(output.astype("uint8")) rawBytes = io.BytesIO() result_img.save(rawBytes, "PNG") rawBytes.seek(0) return rawBytes, 200, {"Content-Type": "image/PNG"} - 修改
vercel.json配置,指向新的API函数:{ "version": 2, "builds": [ { "src": "./api/*.py", "use": "@vercel/python" } ], "routes": [ { "src": "/upscale", "dest": "/api/upscale.py" } ] } - 可移除原
index.py或简化为静态页面入口。
4. 压缩模型体积
通过量化或剪枝减小模型文件大小:
- 模型量化:将模型转为INT8格式,体积可缩减75%左右:
import torch.quantization def load_model(): model = ... # 加载原始模型 model.qconfig = torch.quantization.get_default_qconfig('x86') torch.quantization.prepare(model, inplace=True) torch.quantization.convert(model, inplace=True) return model - 模型剪枝:移除冗余权重,具体可参考PyTorch官方剪枝工具文档。
内容的提问来源于stack exchange,提问作者James
相关产品推荐
相关产品推荐

