您现在的位置是:首页 > 文章详情

AI 绘画平台难开发,难变现?试试 Stable Diffusion API Serverless 版解决方案

日期:2024-01-29点击:24

作者:王佳、江昱、筱姜

Stable Diffusion 模型,已经成为 AI 行业从传统深度学习时代走向 AIGC 时代的标志性里程碑。越来越多的开发者借助 stable-diffusion-webui(以下简称 SDWebUI)能力进行 AI 绘画领域创业或者业务上新,获得高流量及商业价值,但是面对多客户、高并发的复杂场景,使用原生 Stable Diffusion API 会面临以下挑战:

1. 显卡资源昂贵且难以购买,GPU 卡池管理技术门槛高: 高性能的 GPU 资源不仅价格昂贵,而且往往难以大规模采购。此外,GPU 卡池的有效管理和维护需要复杂的技术支持,也带来了额外的挑战。

2. 难以应对高并发: 原生的 Stable Diffusion API 采用单实例推理模式,其并发处理能力有限。在面对高并发场景时,尤其是并发请求具有大的波动性时,资源配置难以精确预测,从而可能导致系统错误和业务中断。

3. 多模型切换难度大: 当不同模型的请求在高并发条件下同时发送到同一实例时,频繁的模型切换成为一个显著的瓶颈。这种切换不仅消耗巨大,而且影响了推理效率,使得多模型部署在实际应用中变得复杂和低效。

为了帮助用户高效率、低成本应对企业级复杂场景,函数计算团队正式推出 Stable Diffusion API Serverless 版解决方案,通过使用该方案,用户可以充分利用 Stable Diffusion +Serverless 技术优势快速开发上线 AI 绘画应用,期待为广大开发者 AI 绘画创业及变现提供思路。

基于 Stable Diffusion API Serverless 版解决方案搭建的,部署 AI 艺术字应用活动火热进行中!生成姓氏头像赢新春好礼,欢迎点击 “阅读原文” 体验。

活动链接:https://developer.aliyun.com/topic/fcnewyear

应用场景

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,推理服务

<!---->

    • 一个模型(checkpoints)创建一个函数,每个函数支持弹多个实例,总的实例数通过 control 并发度进行控制。
    • 之所以一个模型(checkpoints)创建一个函数,是为了避免多模型并发推理使用场景下的模型间的频繁切换带来的开销,提升推理效率,进而达到给用户降本的效果
    • sd_ 开头的都是动态创建函数

注意事项:

  • 使用过程中会动态创建 sdapi 函数,每个 checkpoint 对应一个函数,并且会在 ots 中 function 表中记录对应的函数详情。如果想删除动态创建的函数,请清理对应 ots 中 function 表的函数记录,避免后续调用出问题
  • 异步推理结果会默认存放到 oss 中,存放到 image/default 路径下

部署 Stable Diffusion API Serverless 版

准备工作

开通云产品:

  • 函数计算 FC:用于提供 CPU+GPU 算力
  • 对象存储 OSS:用于保存输出图片结果;同时存储请求中的中转图片,便面直接传递 base64 导致超出请求的 body 限制
  • 表格存储 Tablestore:用于存储推理结果、函数信息等
  • 文件存储 NAS:用于多节点共享存储空间

部署 Stable Diffusion Serverless API

  1. 进入函数计算 FC 3.0 控制台,点击左侧“应用”进行应用中心。如果老用户曾经创建过应用,点击“创建应用”也可直达应用中心

  1. 点击“人工智能”分类,选择“fc-stable-diffusion-v3”模版,点击“立即创建”

  1. 确定详细参数进行应用创建,您可以重点注意三个信息的填写,其他使用默认值即可。
  • 地域:选择距离您较近的地区,如果后续有更多出图需要,可以考虑选择海外地区,以方便 hugging face 等网站的连接
  • 命名空间:如果您已经部署多个 SD,请在这里进行区分,新用户可使用默认值
  • 绘图类型:选择艺术字

  1. 首次使用需要额外的权限,可以根据提示“前往授权”

  1. 点击“创建应用”,勾选了解内容,点击“同意并继续部署”,等待大约 1 分钟

  1. 生成 WebUI 域名(注意保护此链接不外传以免耗费您账户的费用),不要点击链接,直接切换到右侧“Serverless API”

  1. 点击“Serverless API”点击“初始化 Serverless API”,再次确认已经开通“FC、OSS、OTS”三款产品,勾选“已阅读”点击“下一步”

  1. 进行“角色名”的授权,勾选“启用 Serverless API”,OTS 实例创建方式可以默认“自动创建”,确认后等待大约 30 秒

  1. 创建好 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 /modelsresponse:

[ { "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" } ] 

2. 推理相关 API

支持文生图和图生图

支持同步模式和异步模式两种,默认同步模式

  • 同步模式:header 中添加 {"Request-Type":"sync"},不添加默认为同步模式
  • 异步模式:header 中添加 {"Request-Type":"async"}

推理结果会同步存储到 oss 和 ots 中,可以通过 /tasks/{taskId}/result 接口获取推理结果(oss 图片地址、推理参数等)

2.1 txt2img

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:

{ "status":"succeeded", // 推理任务状态 "taskId":"1HmyrbhBJD", // 推理任务id, 后续结果获取,进度查询,取消推理都依赖于该id "ossUrl" :["xxxxx"] // 同步模式下返回的oss上图片临时地址(有一定时效性) } 

2.2 img2img

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

3.1 图片放大

图片放大,支持单张图片处理,暂不支持批量处理。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:

{ "status": "success|fail", "failFuncList": ["xxx"], // 失败的函数列表 "errMsg": ["xxxx"] //错误信息 } 

5.3 批量删除动态创建函数接口

批量删除动态创建的函数,入参函数列表

POST /del/sd/functions

request:

{ "functions":["xxxxx"] } responese // status_code=200 { "status":"success" } // status_code=500 { "fails":[ { "err":"xxxx", "functionName":"xxxx" } ], "status":"fail" } 

6. 其他接口

  • 原生 webui-api 接口,除了上面支持的功能接口,剩下的 api 接口
  • 插件自定义的 api 接口

其中支持同步、异步模式+任务模式:

  • 同步/异步,header 中设置 Request-Type,其中值 sync 为同步模式,async 为异步模式,不设置该值默认为同步模式,异步获取结果需要从上面的获取结果接口(tasks/{taskId}/result)获取最终的结果
  • 任务模式,header 中设置 Task-Flag,会将结果保存到 ots 进行持久化,同样支持同步+异步

最佳实践

为了方便大家直观体验一下该解决方案成效,基于函数计算团队开发者的基于 Stable Diffusion Serverless API 解决方案搭建的 AI 文字生成应用,作为一个实验 demo 开放体验,期待为广大开发者 AI 绘画创业及变现提供一些有益思考。直接参加体验活动,送好礼!

活动链接:https://developer.aliyun.com/topic/fcnewyear

部署成功的 AI 绘画应用:

眯着眼睛看看是什么字?

开源代码
github : https://github.com/devsapp/serverless-stable-diffusion-api

可以自己基于开源代码加工开发

原文链接:https://my.oschina.net/u/3874284/blog/10983752
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章