Stable Diffusion API Serverless
AI 绘画平台难开发,难变现?试试 Stable Diffusion API Serverless 版解决方案
Stable Diffusion 模型,已经成为 AI 行业从传统深度学习时代走向 AIGC 时代的标志性里程碑。越来越多的开发者借助 stable-diffusion-webui (以下简称 SDWebUI) 能力进行 AI 绘画领域创业或者业务上新,获得高流量及商业价值,但是面对多客户、高并发的复杂场景,使用原生 Stable Diffusion API 会面临以下挑战:
- 显卡资源昂贵且难以购买,GPU卡池管理技术门槛高:高性能的 GPU 资源不仅价格昂贵,而且往往难以大规模采购。此外,GPU 卡池的有效管理和维护需要复杂的技术支持,也带来了额外的挑战。
- 难以应对高并发:原生的 Stable Diffusion API 采用单实例推理模式,其并发处理能力有限。在面对高并发场景时,尤其是并发请求具有大的波动性时,资源配置难以精确预测,从而可能导致系统错误和业务中断。
- 多模型切换难度大:当不同模型的请求在高并发条件下同时发送到同一实例时,频繁的模型切换成为一个显著的瓶颈。这种切换不仅消耗巨大,而且影响了推理效率,使得多模型部署在实际应用中变得复杂和低效。
为了帮助用户高效率、低成本应对企业级复杂场景,函数计算团队正式推出 Stable Diffusion API Serverless 版解决方案,通过使用该方案,用户可以充分利用 Stable Diffusion +Serverless 技术优势快速开发上线 AI 绘画应用,期待为广大开发者 AI 绘画创业及变现提供思路。
应用场景
Stable Diffusion API Serverless 版本提供了多种可能性,以适应不同的应用场景和业务需求。
1. 个性化内容创作:利用 Stable Diffusion API,内容创作者和数字艺术家可以快速生成个性化的艺术作品和图像。例如,艺术家可以根据用户的描述或关键词,即时创作出独特的艺术风格图像,实现个性化的艺术创作和用户互动。2. 广告和市场营销:在广告和市场营销领域,Stable Diffusion API 可以用来生成吸引人的视觉内容,从而增强广告效果。例如,企业可以根据产品特性和目标受众的偏好,快速创建多样化的广告图像,以提升品牌形象和市场吸引力。3. 游戏和娱乐产业:在游戏和娱乐产业中,Stable Diffusion API 可以被用来增强用户体验,通过生成独特的游戏背景、角色和元素来丰富游戏世界。例如,游戏开发者可以使用 API 来设计独特的游戏环境和角色,为玩家提供更丰富和个性化的游戏体验。方案优势
Stable Diffusion API Serverless 版本在多方面提供了显著的优势,特别是在简化部署、成本效率、推理效率、资源管理、并发处理和用户体验上。以下是这些优势的具体体现:
1. 上手简单,快速部署:借助阿里云 Serverless 应用中心,用户可以实现快速部署,大幅简化传统 Stable Diffusion API 的复杂部署流程。这使得开发者能够快速上手并专注于应用的开发和创新。2. 计费灵活,成本效益显著:Serverless 版本提供按需计费模式,用户仅需为实际使用的资源付费,无需预先投资昂贵的硬件。这种灵活的计费方式大幅降低了总体成本,尤其适合资源需求波动的场景。3. 优化的模型管理,提升推理效率:通过优化多模型的管理和部署,Serverless 版本有效提高了推理效率。减少模型切换和加载的频率,确保了快速、稳定的推理性能。4. 自动扩缩容,高效资源管理:利用自动扩缩容机制,Serverless 版本根据实时需求灵活调整资源使用,避免了资源浪费并保障了服务的连续性。5. 异步处理和排队机制,优化并发处理:Serverless 版本通过引入异步处理和高效排队机制,克服了高并发场景下的挑战,保证了服务的高可用性和响应速度。总之,Stable Diffusion API Serverless 版本集成了阿里云 Serverless 技术的核心优势,提供了一种高效、成本有效且用户友好的解决方案,为开发者在 AI 绘画和其他 AI 应用领域的创新和商业化提供支持。
方案架构图:
名词解释:
-
admin,提供模型管理,包括模型上传+删除等
-
webui,提供界面化的调试功能,主要是模型和参数调整、插件安装等,达到更好出图效果
-
proxy,API的前端服务,提供非推理之外的功能,主要包括结果、进度查询等
-
control,控制推理实例最大并发实例数。通过控制control的并发度,控制下游多函数推理服务的实例数
-
agent+sd-api, 推理服务,
注意事项:
-
使用过程中会动态创建sdapi函数,每个checkpoint对应一个函数,并且会在ots中function表中记录对应的函数详情。如果想删除动态创建的函数,请清理对应ots中function表的函数记录,避免后续调用出问题
-
异步推理结果会默认存放到oss中,存放到image/default路径下
部署 Stable Diffusion API Serverless 版
准备工作
1. 开通云产品
-
函数计算FC:用于提供 CPU+GPU 算力
-
对象存储 OSS:用于保存输出图片结果;同时存储请求中的中转图片,便面直接传递 base64导致超出请求的 body 限制
-
表格存储Tablestore:用于存储推理结果、函数信息等
-
文件存储 NAS:用于多节点共享存储空间
部署 Stable Diffusion Serverless API
1. 进入函数计算FC 3.0 控制台,点击左侧“应用”进行应用中心。如果老用户曾经创建过应用,点击“创建应用”也可直达应用中心。注意:一定要确保左上角是“函数计算 FC 3.0” 如果不是可以查看右上角找到“进入函数计算3.0”
2. 点击“人工智能”分类,选择“fc-stable-diffusion-v3”模版,点击“立即创建”
3.确定详细参数进行应用创建,您可以重点注意三个信息的填写,其他使用默认值即可。
- 地域:选择距离您较近的地区,如果后续有更多出图需要,可以考虑选择海外地区,以方便 hugging face 等网站的连接
- 命名空间:如果您已经部署多个 SD,请在这里进行区分,新用户可使用默认值
-
绘图类型:选择艺术字
4. 首次使用需要额外的权限,可以根据提示“前往授权”
5. 点击“创建应用”,勾选了解内容,点击“同意并继续部署”,等待大约1分钟
6. 生成 WebUI 域名(注意保护此链接不外传以免耗费您账户的费用),不要点击链接,直接切换到右侧“ Serverless API "
7. 点击“Serverless API" 点击“初始化 Serverless API",再次确认已经开通“FC、OSS、OTS” 三款产品,勾选“已阅读”点击“下一步”
8. 进行“角色名”的授权,勾选“启用 Serverless API",OTS实例创建方式可以默认“自动创建”,确认后等待大约 30秒
9. 创建好 Serverless API,就可以参考下面API定义开始进行测试生产使用。
Stable Diffusion API Serverless 版支持的 API 详情
API 接口主要分两类:
-
非推理类接口,用于结果和进度查询、模型管理、应用重启等
-
推理类接口,文生图、图生图、图片放大等
具体可以参考: https://github.com/devsapp/serverless-stable-diffusion-api/blob/main/api/api.yaml
1. 模型相关API模型的注册、更新和删除都通过admin界面化操作即可
1.1 获取模型列表 API
GET /models
response:
2. 推理相关API[{"type": "stableDiffusion","name": "model_v1","ossPath": "/path/to/oss/model_v1","etag": "3f786850e387550fdab836ed7e6dc881de23001b","status": "loaded", // registering|loading|loaded|unloaded|deleted"registeredTime": "2023-01-01T12:00:00Z","lastModificationTime": "2023-01-10T12:00:00Z"}]
支持文生图和图生图
支持同步模式和异步模式两种,默认同步模式
-
同步模式, header中添加{"Request-Type":"sync"},不添加默认为同步模式
-
异步模式, header中添加{"Request-Type":"async"}
POST /txt2img
request: 其中stable_diffusion_model, sd_vae新加字段,其他保持跟原生webui:txt2img保持一致
其中controlnet中图片支持两种格式:
-
图片的base64编码:备注:base64请求存在超过FC异步请求body上限可能,如果超过上限请使用oss方式
-
oss上图片路径,支持png/jpg/jpeg
{"stable_diffusion_model": "diffusion_v1", // sd主模型"sd_vae": "vae_v1", // vae模型"enable_hr": true,"denoising_strength": 0.5,"firstphase_width": 640,"firstphase_height": 480,"hr_scale": 2,"hr_upscaler": "upscale_method_v1","hr_second_pass_steps": 10,"hr_resize_x": 1280,"hr_resize_y": 960,"hr_sampler_name": "sampler_v1","hr_prompt": "High resolution prompt","hr_negative_prompt": "Negative high resolution prompt","prompt": "Mountain landscape during sunset","styles": ["style1","style2"],"seed": 123456,"subseed": 789,"subseed_strength": 5,"seed_resize_from_h": 480,"seed_resize_from_w": 640,"sampler_name": "sampler_v2","batch_size": 32,"n_iter": 1000,"steps": 100,"cfg_scale": 1,"width": 640,"height": 480,"restore_faces": true,"tiling": false,"do_not_save_samples": false,"do_not_save_grid": false,"negative_prompt": "Avoid mountains","eta": 5,"s_min_uncond": 1,"s_churn": 3,"s_tmax": 10,"s_tmin": 1,"s_noise": 2,"override_settings": {"settingKey": "settingValue"},"override_settings_restore_afterwards": true,"script_args": [{"argKey": "argValue"}],"sampler_index": "index_v1","script_name": "script_v1","send_images": true,"save_images": true,"alwayson_scripts": {"controlnet": {"args": [{"image":"base64srcimg|image/default/xxxx.png", //支持传输base64和oss对应图片path(png/jpg/jpeg)"enabled":True,"module":"canny","model":"control_v11p_sd15_scribble","weight":1,"resize_mode":"Crop and Resize","low_vram":False,"processor_res":512,"threshold_a":100,"threshold_b":200,"guidance_start":0,"guidance_end":1,"pixel_perfect":True,"control_mode":"Balanced","input_mode":"simple","batch_images":"","output_dir":"","loopback":False}]}}}
response:
2.2 img2img{"status":"succeeded", // 推理任务状态"taskId":"1HmyrbhBJD", // 推理任务id, 后续结果获取,进度查询,取消推理都依赖于该id"ossUrl" :["xxxxx"] // 同步模式下返回的oss上图片临时地址(有一定时效性)}
POST /img2img request: 其中stable_diffusion_model,sd_vae新加字段,其他保持跟原生webui:img2img保持一致
其中controlnet和init_images中图片支持两种格式:
-
图片的base64编码:备注:base64请求存在超过FC异步请求body上限可能,如果超过上限请使用oss方式
-
oss上图片路径,支持png/jpg/jpeg
{"stable_diffusion_model": "diffusion_v2", // sd主模型"sd_vae": "vae_v2", // vae模型"init_images": [ //支持base64、oss图片地址两种格式"Base64SrcImg|ossPath","Base64SrcImg|ossPath"],"resize_mode": 1,"denoising_strength": 0.8,"image_cfg_scale": 2,"mask": "mask_path","mask_blur": 3,"mask_blur_x": 2,"mask_blur_y": 2,"inpainting_fill": 4,"inpaint_full_res": true,"inpaint_full_res_padding": 2,"inpainting_mask_invert": 0,"initial_noise_multiplier": 5,"prompt": "Forest landscape","styles": ["styleA","styleB"],"seed": 654321,"subseed": 987,"subseed_strength": 6,"seed_resize_from_h": 480,"seed_resize_from_w": 640,"sampler_name": "sampler_v3","batch_size": 64,"n_iter": 500,"steps": 50,"cfg_scale": 2,"width": 1280,"height": 960,"restore_faces": false,"tiling": true,"do_not_save_samples": false,"do_not_save_grid": true,"negative_prompt": "Avoid forests","eta": 6,"s_min_uncond": 2,"s_churn": 4,"s_tmax": 11,"s_tmin": 2,"s_noise": 3,"override_settings": {"settingKeyV2": "settingValueV2"},"override_settings_restore_afterwards": false,"script_args": ["arg1","arg2"],"sampler_index": "index_v2","include_init_images": false,"script_name": "script_v2","send_images": false,"save_images": true,"alwayson_scripts": {"controlnet": {"args": [{"image":"base64srcimg|ossPath", //支持base64、oss图片地址两种格式"enabled":True,"module":"canny","model":"control_v11p_sd15_scribble","weight":1,"resize_mode":"Crop and Resize","low_vram":False,"processor_res":512,"threshold_a":100,"threshold_b":200,"guidance_start":0,"guidance_end":1,"pixel_perfect":True,"control_mode":"Balanced","input_mode":"simple","batch_images":"","output_dir":"","loopback":False}]}}}
response:
{"status":"succeeded", // 推理任务状态"taskId":"1HmyrbhBJD", // 推理任务id, 后续结果获取,进度查询,取消推理都依赖于该id"ossUrl" :["xxxxx"] // 同步模式下返回的oss上图片临时地址(有一定时效性)}
3. 图片处理 API图片放大
图片放大, 支持单张图片处理,暂不支持批量处理。respone返回taskId,调用获取结果接口获取图片地址即可
其中image支持两种格式:
-
图片的base64
-
oss上图片路径,支持png/jpg/jpeg
POST /extra_images
request:
{"resize_mode": 0,"show_extras_results": True,"gfpgan_visibility": 0,"codeformer_visibility": 0,"codeformer_weight": 0,"upscaling_resize": 4,"upscaling_crop": True,"upscaler_1": "Lanczos","upscaler_2": "None","extras_upscaler_2_visibility": 0,"upscale_first": False,"image":self.file_to_base64(),"image" : "base64|ossPath" //支持传输base64和oss对应图片path(png/jpg/jpeg)}
response:
{"status":"succeeded","taskId":"TovRrc0Jnr","ossUrl" :["xxxxx"] // 同步模式下返回的oss上图片临时地址(有一定时效性)}
4. 结果相关 API
4.1 获取结果
通过taskid获取推理结果
GET /tasks/{taskId}/result
response:
{"images":["images/admin/Xldf9m80im_1.png" // images 推理结果, oss图片path],"ossUrl" :["xxxxx"], oss上图片临时地址(有一定时效性)"info":{ // info 推理过程中产生信息"all_negative_prompts":[""],"all_prompts":["cute beautiful blonde, very detailed, 21 years old, inoccent face, natural wave hair, blue eyes, high-res, masterpiece, best quality,intricate details, highly detailed,sharp focus, detailed skin,realistic skin texture,texture, detailed eyes \u003clora:shuimobysimV3:1\u003e"],"all_seeds":[3896184641],"all_subseeds":[6579621],"alwayson_scripts":"","batch_size":1,"cfg_scale":7,"clip_skip":1,"denoising_strength":0,"do_not_save_grid":false,"do_not_save_samples":false,"enable_hr":false,"eta":null,"extra_generation_params":{},"face_restoration_model":null,"firstphase_height":0,"firstphase_width":0,"height":512,"hr_negative_prompt":"","hr_prompt":"","hr_resize_x":0,"hr_resize_y":0,"hr_sampler_name":null,"hr_scale":2,"hr_second_pass_steps":0,"hr_upscaler":null,"index_of_first_image":0,"infotexts":["cute beautiful blonde, very detailed, 21 years old, inoccent face, natural wave hair, blue eyes, high-res, masterpiece, best quality,intricate details, highly detailed,sharp focus, detailed skin,realistic skin texture,texture, detailed eyes \u003clora:shuimobysimV3:1\u003e\nSteps: 50, Sampler: Euler, CFG scale: 7.0, Seed: 3896184641, Size: 512x512, Model hash: 18ed2b6c48, Model: xxmix9realistic_v40, Denoising strength: 0, Version: v1.5.1"],"is_using_inpainting_conditioning":false,"job_timestamp":"20230828073155","n_iter":1,"negative_prompt":"","override_settings":{},"override_settings_restore_afterwards":true,"prompt":"cute beautiful blonde, very detailed, 21 years old, inoccent face, natural wave hair, blue eyes, high-res, masterpiece, best quality,intricate details, highly detailed,sharp focus, detailed skin,realistic skin texture,texture, detailed eyes \u003clora:shuimobysimV3:1\u003e","restore_faces":false,"s_churn":0,"s_min_uncond":0,"s_noise":1,"s_tmax":null,"s_tmin":0,"sampler_index":"Euler","sampler_name":"Euler","save_images":false,"script_args":[],"script_name":null,"sd_model_hash":"18ed2b6c48","seed":3896184641,"seed_resize_from_h":-1,"seed_resize_from_w":-1,"send_images":true,"steps":50,"styles":[],"subseed":6579621,"subseed_strength":0,"tiling":false,"width":512},"parameters":{ // parameters实际推理过程中的参数"all_negative_prompts":[""],"all_prompts":["cute beautiful blonde, very detailed, 21 years old, inoccent face, natural wave hair, blue eyes, high-res, masterpiece, best quality,intricate details, highly detailed,sharp focus, detailed skin,realistic skin texture,texture, detailed eyes \u003clora:shuimobysimV3:1\u003e"],"all_seeds":[3896184641],"all_subseeds":[6579621],"alwayson_scripts":"","batch_size":1,"cfg_scale":7,"clip_skip":1,"denoising_strength":0,"do_not_save_grid":false,"do_not_save_samples":false,"enable_hr":false,"eta":null,"extra_generation_params":{},"face_restoration_model":null,"firstphase_height":0,"firstphase_width":0,"height":512,"hr_negative_prompt":"","hr_prompt":"","hr_resize_x":0,"hr_resize_y":0,"hr_sampler_name":null,"hr_scale":2,"hr_second_pass_steps":0,"hr_upscaler":null,"index_of_first_image":0,"infotexts":["cute beautiful blonde, very detailed, 21 years old, inoccent face, natural wave hair, blue eyes, high-res, masterpiece, best quality,intricate details, highly detailed,sharp focus, detailed skin,realistic skin texture,texture, detailed eyes \u003clora:shuimobysimV3:1\u003e\nSteps: 50, Sampler: Euler, CFG scale: 7.0, Seed: 3896184641, Size: 512x512, Model hash: 18ed2b6c48, Model: xxmix9realistic_v40, Denoising strength: 0, Version: v1.5.1"],"is_using_inpainting_conditioning":false,"job_timestamp":"20230828073155","n_iter":1,"negative_prompt":"","override_settings":{},"override_settings_restore_afterwards":true,"prompt":"cute beautiful blonde, very detailed, 21 years old, inoccent face, natural wave hair, blue eyes, high-res, masterpiece, best quality,intricate details, highly detailed,sharp focus, detailed skin,realistic skin texture,texture, detailed eyes \u003clora:shuimobysimV3:1\u003e","restore_faces":false,"s_churn":0,"s_min_uncond":0,"s_noise":1,"s_tmax":null,"s_tmin":0,"sampler_index":"Euler","sampler_name":"Euler","save_images":false,"script_args":[],"script_name":null,"sd_model_hash":"18ed2b6c48","seed":3896184641,"seed_resize_from_h":-1,"seed_resize_from_w":-1,"send_images":true,"steps":50,"styles":[],"subseed":6579621,"subseed_strength":0,"tiling":false,"width":512},"taskId":"Xldf9m80im"}
4.2 查询进度
推理进度查询
GET /tasks/{taskId}/progress, 同webui中的progress
response:
{"currentImage":"","etaRelative":0.10594336,"progress":0.99,"state":{"interrupted":false,"job":"scripts_txt2img","job_count":1,"job_no":0,"job_timestamp":"20230828073155","sampling_step":49,"sampling_steps":50,"skipped":false},"taskId":"Xldf9m80im"}
4.3 取消推理
取消对应任务
POST /tasks/{taskId}/cancellation
5. 动态资源相关 API
5.1 获取动态创建sd函数
获取动态创建的sdapi函数
GET /list/sdapi/fucntions
response
{"functions":[{"functionName":"sd_739f6de96fdbb66704296cd11ab3f96c182fde7f2cbbb127185b184a43414dea","model":"chilloutmix_NiPrunedFp16Fix.safetensors"}],"status":"success"}
5.2 更新动态创建sd资源
批量更新动态创建sd函数资源,比如镜像、环境变量、cpu、显存等。其中models不指定代表更新所有动态创建sd函数资源。
POST /batch_update_sd_resource
request
{"models": ["chilloutmix_NiPrunedFp16Fix.safetensors"],"cpu": 4,"memorySize": 16384, // MB"image": "xxx","extraArgs": "--api --nowebui --no-hashing","instanceType": "fc.gpu.ampere.1","gpuMemorySize": 16384, // MB"timeout": 60, //s"env": {},"vpcConfig":{"securityGroupId":"xxx","vSwitchIds":["xxx"],"vpcId":"xxx"},"nasConfig": {"groupId" : 123,"mountPoints": [{"enableTLS": true|false,"mountDir": "xxx","serverAddr": "dddd"}],"userId": 123},"mountPoints":[{"bucketName": "xxx","bucketPath": "xxx","endpoint": "xxx","mountDir": "ddd","readOnly": true|false}]}
response
5.3 批量删除动态创建函数接口批量删除动态创建的函数,入参函数列表 POST /del/sd/functions request{"status": "success|fail","failFuncList": ["xxx"], // 失败的函数列表"errMsg": ["xxxx"] //错误信息}
{"functions":["xxxxx"]}
responese
6. 其他接口// status_code=200{"status":"success"}// status_code=500{"fails":[{"err":"xxxx","functionName":"xxxx"}],"status":"fail"}
-
原生webui-api接口, 除了上面支持的功能接口,剩下的api接口
-
插件自定义的api接口
其中支持同步、异步模式+任务模式
-
同步/异步, header中设置Request-Type, 其中值sync为同步模式,async为异步模式, 不设置该值默认为同步模式, 异步获取结果需要从上面的获取结果接口(tasks/{taskId}/result)获取最终的结果
-
任务模式,header中设置Task-Flag,会将结果保存到ots进行持久化, 同样支持同步+异步
最佳实践
为了方便大家直观体验一下该解决方案成效,基于函数计算团队开发者的基于 Stable Diffusion Serverless API 解决方案搭建的 AI 文字生成应用,作为一个实验demo 开放体验,期待为广大开发者 AI 绘画创业及变现提供一些有益思考。生成 AI 艺术字应用教程:https://developer.aliyun.com/article/1427587
部署成功的AI绘画应用
开源代码 github :
https://github.com/devsapp/serverless-stable-diffusion-api
可以自己基于开源代码加工开发
微信扫一扫
关注该公众号

浙公网安备 33010602011771号