在亚马逊云科技上对Stable Diffusion模子提示词、输出图像内容举行安全考核 ...

打印 上一主题 下一主题

主题 888|帖子 888|积分 2664

项目简介:

小李哥将继续每天介绍一个基于亚马逊云科技AWS云计算平台的环球前沿AI技能办理方案,资助大家快速了解国际上最热门的云计算平台亚马逊云科技AWS AI最佳实践,并应用到自己的日常工作里。
本次介绍的是怎样在亚马逊云科技机器学习托管服务SageMaker上部署开源大模子Stable Diffusion,使用亚马逊云科技Comprehend对模子输入提示词举行有害性检测,并使用亚马逊云科技Rekognition服务对天生图像内容举行有害性检测,构建负责任的AI防止大模子被滥用。本架构设计全部采用了云原生Serverless架构,提供可扩展和安全的AI办理方案。本方案的办理方案架构图如下:

方案所需基础知识   

什么是 Amazon SageMaker?

Amazon SageMaker 是亚马逊云科技提供的一站式机器学习服务,资助开发者和数据科学家轻松构建、练习和部署机器学习模子。SageMaker 提供了全面的工具,从数据准备、模子练习到部署和监控,覆盖了机器学习项目的全生命周期。通过 SageMaker,用户可以加速机器学习模子的开发和上线,并确保模子在生产情况中的稳定性和性能。
什么是 Amazon Comprehend?

Amazon Comprehend 是亚马逊云科技提供的一项自然语言处理惩罚(NLP)服务,能够自动从文本中提取有代价的信息。通过机器学习技能,Comprehend 可以识别文本中的实体、感情、关键词、语言、主题等,资助企业更好地明白和分析大量非布局化数据。它实用于客户反馈分析、内容分类、文档处理惩罚等场景,使得信息挖掘和数据洞察变得更加简单和高效。
什么是 Amazon Rekognition?

Amazon Rekognition 是亚马逊云科技提供的一项图像和视频分析服务。它使用深度学习技能来检测、识别和分析图像中的对象、场景、面部表情、文字等。Rekognition 可以应用于多种场景,如面部识别、内容考核、对象检测和人群统计等,资助企业自动化处理惩罚图像和视频数据,提升效率并增强安全性。
什么是 Stable Diffusion?

Stable Diffusion 是一种先辈的天生式 AI 模子,专门用于天生高质量的图像。通过扩散模子技能,Stable Diffusion 能够将简单的文本形貌转化为逼真的图像。这个模子具有强大的天生能力,可以应用于艺术创作、广告设计、游戏开发等范畴,为用户提供丰富的视觉内容天生工具。

为什么要对 Stable Diffusion 输入输出内容举行安全考核?

防止不当内容天生

Stable Diffusion 可以根据输入的文本天生图像,但如果输入的文本内容不当或恶意,大概会天生带有敏感、违法或不道德内容的图像。对输入输出内容举行考核,能够有用防止此类内容的天生和传播,确保模子的使用符合道德和法律标准。
掩护用户隐私

在天生图像时,大概涉及到用户的私家信息或敏感数据。通过考核输入输出内容,可以确保这些信息不会被意外泄漏或滥用,掩护用户的隐私权。
遵遵法律法规

各国对天生和传播图像内容有差别的法律规定。通过对内容举行考核,企业可以确保天生的图像符合所在国家或地区的法律法规,制止法律风险。
维护品牌荣誉

对内容举行安全考核,有助于防止不符合公司代价观或大概损害品牌荣誉的内容天生,从而维护品牌的形象和公众信任。


本方案包括的内容

1. 在SageMaker上部署开源大模子Stable Diffusion

2. 在SageMaker上调用Stable Diffusion模子API天生图片

3. 将Stable Diffusion模子API节点集成到云端应用上

4. 评估大模子输入问题的有害性

5. 对大模子输出图片举行安全考核


项目搭建详细步骤:

1. 打开亚马逊云科技控制台,进入Amazon SageMaker服务主页,点击Open Studio进入模子开发情况。

2. 创建一个新的Jupyte NoteBook文件,复制以下代码安装须要依赖并指明Stable Diffusion模子ID。
  1. %pip install --upgrade sagemaker --quiet
  2. model_id = "model-imagegeneration-stabilityai-stable-diffusion-xl-base-1-0"
复制代码
3. 运行以下代码罗列出JumpStart中,可以快速部署的用于天生图片的所有Stable Diffusion大模子
  1. import IPython
  2. from ipywidgets import Dropdown
  3. from sagemaker.jumpstart.notebook_utils import list_jumpstart_models
  4. from sagemaker.jumpstart.filters import And
  5. filter_value = And("task == imagegeneration")
  6. ss_models = list_jumpstart_models(filter=filter_value)
  7. dropdown = Dropdown(
  8.     value=model_id,
  9.     options=ss_models,
  10.     description="Sagemaker Pre-Trained Image Generation Models:",
  11.     style={"description_width": "initial"},
  12.     layout={"width": "max-content"},
  13. )
  14. display(IPython.display.Markdown("## Select a pre-trained model from the dropdown menu"))
  15. display(dropdown)
复制代码
4. 运行以下代码开始部署Stable Diffusion大模子。
  1. # Deploy the model
  2. from sagemaker.jumpstart.model import JumpStartModel
  3. from sagemaker.serializers import JSONSerializer
  4. import time
  5. # The model is deployed on an ml.g5.4xlarge instance. To see all the supported parameters by the JumpStartModel
  6. # class use this link - https://sagemaker.readthedocs.io/en/stable/api/inference/model.html#sagemaker.jumpstart.model.JumpStartModel
  7. my_model = JumpStartModel(model_id=dropdown.value)
  8. predictor = my_model.deploy()
  9. # Wait for a few seconds so model the is properly loaded.
  10. time.sleep(60)
复制代码
5. 运行以下代码,导入调用大模子的须要依赖,配置图片天生哀求参数,这里我们的图片天生提示词为”天生一个亚马逊雨林中的美洲虎图片“。同时我们定一个图片解码函数”decode_and_show“用于显示天生的图片,末了调用图片天生API "redictor.predict()"天生图片。
  1. from PIL import Image
  2. import io
  3. import base64
  4. import json
  5. import boto3
  6. from typing import Union, Tuple
  7. import os
  8. payload = {
  9.     "text_prompts": [{"text": "jaguar in the Amazon rainforest"}],
  10.     "width": 1024,
  11.     "height": 1024,
  12.     "sampler": "DPMPP2MSampler",
  13.     "cfg_scale": 7.0,
  14.     "steps": 50,
  15.     "seed": 133,
  16.     "use_refiner": True,
  17.     "refiner_steps": 40,
  18.     "refiner_strength": 0.2,
  19. }
  20. def decode_and_show(model_response) -> None:
  21.     """
  22.     Decodes and displays an image from SDXL output
  23.     Args:
  24.         model_response (GenerationResponse): The response object from the deployed SDXL model.
  25.     Returns:
  26.         None
  27.     """
  28.     image = Image.open(io.BytesIO(base64.b64decode(model_response)))
  29.     display(image)
  30.     image.close()
  31. response = predictor.predict(payload)
  32. # If you get a time out error, check the endpoint logs in Amazon CloudWatch for the model loading status
  33. # and invoke it again.
  34. decode_and_show(response["generated_image"])
复制代码
我们在开发情况里可以看到大模子天生的图片内容。

 6. 接下来我们进入到无服务器计算服务Lambda中,创建一个函数”check_toxicity_function“,用于调用Amazon Comprehend服务的API,模子检测输入文字的有害性并返回到客户端。我们复制以下代码到Lambda函数中
  1. import json
  2. import boto3
  3. import os
  4. comprehend = boto3.client('comprehend')
  5. THRESHOLD = float(os.environ['THRESHOLD'])
  6. def check_toxicity(text_prompts):
  7.     detected_labels = []
  8.     for prompt in text_prompts:
  9.         response = comprehend.detect_toxic_content(
  10.             TextSegments=[
  11.                 {
  12.                     "Text": prompt['text']
  13.                 }
  14.             ],
  15.             LanguageCode='en'
  16.         )
  17.         labels = response['ResultList'][0]['Labels']
  18.         # DIY section
  19.         # Replace l['Name'] with {l['Name']:l['Score']} so that detected
  20.         # is an array of json objects
  21.         detected = [l['Name']for l in labels if l['Score'] > THRESHOLD]
  22.         if detected:
  23.             detected_labels.extend(detected)
  24.     return detected_labels
  25. def lambda_handler(event, context):
  26.     print("event is ", json.dumps(event))
  27.     try:
  28.         text_prompts = [json.loads(event['body'].strip('"'))]
  29.         detected_labels = check_toxicity(text_prompts)
  30.         if detected_labels:
  31.             return {
  32.                 'statusCode': 200,
  33.                 'headers': {
  34.                     'Content-Type': 'application/json',
  35.                     'Access-Control-Allow-Headers': 'Content-Type',
  36.                     'Access-Control-Allow-Origin': '*',
  37.                     'Access-Control-Allow-Methods': 'OPTIONS,POST'
  38.                 },
  39.                 'body': json.dumps({'detected_labels': detected_labels})
  40.             }
  41.         else:
  42.             return {
  43.                 'statusCode': 200,
  44.                 'headers': {
  45.                     'Content-Type': 'application/json',
  46.                     'Access-Control-Allow-Headers': 'Content-Type',
  47.                     'Access-Control-Allow-Origin': '*',
  48.                     'Access-Control-Allow-Methods': 'OPTIONS,POST'
  49.                 },
  50.                 'body': json.dumps({'detected_labels': 'non-toxic content and safe to proceed'})
  51.             }
  52.     except Exception as e:
  53.         print(f"Error: {e}")
  54.         return {
  55.             'statusCode': 500,
  56.             'headers': {
  57.                 'Content-Type': 'application/json',
  58.                 'Access-Control-Allow-Headers': 'Content-Type',
  59.                 'Access-Control-Allow-Origin': '*',
  60.                 'Access-Control-Allow-Methods': 'OPTIONS,POST'
  61.             },
  62.             'body': json.dumps({'error': 'An error occurred while processing the request'})
  63.         }
复制代码
7. 我们再建一个新的Lambda函数”classifier_lambda_function“,调用Amazon Rekognition服务API对Stable Diffusion天生的图片举行内容考核。复制以下代码到Lambda中。
  1. import io
  2. import base64
  3. import json
  4. import boto3
  5. import os
  6. import uuid
  7. import ast
  8. comprehend = boto3.client('comprehend')
  9. sagemaker_runtime = boto3.client("runtime.sagemaker")
  10. rekognition = boto3.client('rekognition')
  11. s3_client = boto3.client('s3')
  12. s3 = boto3.resource('s3')
  13. ENDPOINT_NAME = os.environ["ENDPOINT_NAME"]
  14. bucket_name = os.environ['BUCKET_NAME']
  15. THRESHOLD = 0.2
  16. s3_folder = 'generated_images/'
  17. def query_endpoint(prompt):
  18.     response = sagemaker_runtime.invoke_endpoint(
  19.         EndpointName=ENDPOINT_NAME, ContentType="application/json", Body=json.dumps(prompt,separators=(',', ':')).encode("utf-8")
  20.     )
  21.     print("response is ",response)
  22.     result = json.loads(response["Body"].read().decode())
  23.     return result
  24.    
  25.    
  26. def detect_moderation(img_bytes):
  27.     confidence_data = [ ]
  28.     response = rekognition.detect_moderation_labels(
  29.         Image={
  30.         'Bytes': base64.b64decode(img_bytes)
  31.         })
  32.     for label in response['ModerationLabels']:
  33.         confidence = label['Name'] + ' : ' + str(label['Confidence'])
  34.         print (label['Name'] + ' : ' + str(label['Confidence']))
  35.         print("confidence is ", confidence)
  36.         confidence_data.append(confidence + "\n")
  37.    
  38.     return confidence_data
  39. def lambda_handler(event,context):
  40.     print("event is ",json.dumps(event))
  41.     pm_str=json.loads(event["body"].strip('"'))
  42.     prompt = {
  43.         "text_prompts":  [(pm_str)],
  44.         }
  45.     print(prompt)
  46.     response = query_endpoint(prompt)
  47.     if "generated_image" in response:
  48.         image_data = response["generated_image"]
  49.         confLevel = detect_moderation(image_data)
  50.         print(confLevel, len(confLevel))
  51.         
  52.         if len(confLevel) > 0:
  53.             return {
  54.                     'statusCode': 400,
  55.                     'headers': {
  56.                         'Access-Control-Allow-Headers': 'Content-Type',
  57.                         'Access-Control-Allow-Origin': '*',
  58.                         'Access-Control-Allow-Methods': 'OPTIONS,POST'
  59.                     },
  60.                     'body': json.dumps(confLevel)
  61.                 }
  62.         else:
  63.             imageBytes = io.BytesIO(base64.b64decode(image_data))
  64.             file_name = f'generated-image-{uuid.uuid4()}.jpg'
  65.    
  66.             s3_client.upload_fileobj(
  67.                 imageBytes,
  68.                 bucket_name,
  69.                 f'{s3_folder}{file_name}',
  70.                 ExtraArgs={'ContentType': 'image/jpeg'}
  71.             )
  72.             return {
  73.                     'statusCode': 200,
  74.                     'headers': {
  75.                         'Content-Type': 'image/png',
  76.                         'Access-Control-Allow-Headers': 'Content-Type',
  77.                         'Access-Control-Allow-Origin': '*',
  78.                         'Access-Control-Allow-Methods': 'OPTIONS,POST'
  79.                     },
  80.                     'body': json.dumps(file_name),
  81.                     'isBase64Encoded': True
  82.             }
  83.     else:
  84.         return {
  85.             'statusCode': 400,
  86.             'headers': {
  87.                 'Access-Control-Allow-Headers': 'Content-Type',
  88.                 'Access-Control-Allow-Origin': '*',
  89.                 'Access-Control-Allow-Methods': 'OPTIONS,POST'
  90.             },
  91.             'body': json.dumps({'error': 'Response is not in the expected format'})
  92.     }
  93.       
复制代码
8. 接下来我们为Lambda函数前面添加一个API Gateway,作为API管理服务并提供对外袒露的API端点,在该服务中我们定义差别的HTTP方法、路径,绑定差别的Lambda函数来管理API。
如使用POST方法调用路径/classifier时,我们触发Lambda函数:”classifier_lambda_function“。使用POST方法调用路径/classifier/checkToxicity时,我们出发函数:”check_toxicity_function“。
同时API Gateway服务提供了端点URL供用户访问。

9. 本架构中我们使用到了CloudFront对API和网页哀求举行加速,我们进入CloudFront服务页面中,复制并打开URL。

10. 首先我们对提示词文字举行检测,我们输入问题得到了回复”提示词包含侮辱性词汇“。

11. 我们再在相同界面中输入”天生一个明朗的一天“,该提示词通过了文字有害性检测,天生的图片也通过安全查抄,乐成显示在天生界面中。


以上就是在亚马逊云科技上使用亚马逊云科技上使用Amazon Sagemaker部署Stable Diffusion模子,并对输入提示词和输出图像内容举行安全考核,的全部步骤。接待大家未来与我一起,未来获取更多国际前沿的天生式AI开发方案。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

石小疯

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表