从零开发短视频电商 在AWS上用SageMaker部署自定义模型

文章目录

    • 简介
    • 使用model.tar.gz
      • 1.从huggingface上下载模型
      • 2.自定义代码
      • 3.打包为tar 文件
      • 4.上传model.tar.gz到S3
      • 5.部署推理
    • 使用hub
      • 1.在sagemaker上新建个jupyterlab
      • 2.上传官方示例ipynb文件
      • 3.指定HF_MODEL_ID和HF_TASK进行部署和推理
    • inference.py官方示例

简介

  • 原始链接:https://huggingface.co/docs/sagemaker/inference#deploy-with-modeldata
  • https://docs.datarobot.com/en/docs/more-info/how-to/aws/sagemaker/sagemaker-deploy.html
    • 这个可以是java环境或者python环境。

部署的都是从huggingface上的model或者根据huaggingface上的model进行fine-tune后的

一般输入格式如下:

text-classification request body

{
    "inputs": "Camera - You are awarded a SiPix Digital Camera! call 09061221066 fromm landline. Delivery within 28 days."
}
question-answering request body

{
    "inputs": {
        "question": "What is used for inference?",
        "context": "My Name is Philipp and I live in Nuremberg. This model is used with sagemaker for inference."
    }
}
zero-shot classification request body

{
    "inputs": "Hi, I recently bought a device from your company but it is not working as advertised and I would like to get reimbursed!",
    "parameters": {
        "candidate_labels": [
            "refund",
            "legal",
            "faq"
        ]
    }
}

所有官方示例

  • https://github.com/huggingface/notebooks/tree/main/sagemaker

推理工具

  • https://github.com/aws/sagemaker-huggingface-inference-toolkit

使用model.tar.gz

1.从huggingface上下载模型

由于模型文件比较大,需要先安装git-lfs

CentOS7安装Git LFS的方法如下:

# 安装必要的软件包:
sudo yum install curl-devel expat-devel gettext-devel openssl-devel zlib-devel
# 安装Git LFS:
curl -s https://packagecloud.io/install/repositories/github/git-lfs/script.rpm.sh | sudo bash
# 安装
sudo yum install git-lfs
# 配置Git LFS:
git lfs install
# 检测是否安装成功:
git lfs version
如果出现版本信息,说明安装成功。

从huaggingface上clone你想使用的模型,以https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2 为例子

git clone https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2

在这里插入图片描述

2.自定义代码

允许用户覆盖 HuggingFaceHandlerService 的默认方法。您需要创建一个名为 code/ 的文件夹,其中包含 inference.py 文件。

  • HuggingFaceHandlerService

目录结构如下

model.tar.gz/
|- pytorch_model.bin
|- ....
|- code/
  |- inference.py
  |- requirements.txt 

inference.py 文件包含自定义推理模块, requirements.txt 文件包含应添加的其他依赖项。自定义模块可以重写以下方法:

  • model_fn(model_dir) 覆盖加载模型的默认方法。返回值 model 将在 predict 中用于预测。 predict 接收参数 model_dir ,即解压后的 model.tar.gz 的路径。
  • transform_fn(model, data, content_type, accept_type) 使用您的自定义实现覆盖默认转换函数。您需要在 transform_fn 中实现您自己的 preprocesspredictpostprocess 步骤。此方法不能与下面提到的 input_fnpredict_fnoutput_fn 组合使用。
  • input_fn(input_data, content_type) 覆盖默认的预处理方法。返回值 data 将在 predict 中用于预测。输入是:
    • input_data 是您请求的原始正文。
    • content_type 是请求标头中的内容类型。
  • predict_fn(processed_data, model) 覆盖默认的预测方法。返回值 predictions 将在 postprocess 中使用。输入是 processed_data ,即 preprocess 的结果。
  • output_fn(prediction, accept) 覆盖后处理的默认方法。返回值 result 将是您请求的响应(例如 JSON )。输入是:
    • predictionspredict 的结果。
    • accept 是 HTTP 请求的返回接受类型,例如 application/json

以下是包含 model_fninput_fnpredict_fnoutput_fn 的自定义推理模块的示例:

from sagemaker_huggingface_inference_toolkit import decoder_encoder

def model_fn(model_dir):
    # implement custom code to load the model
    loaded_model = ...
    
    return loaded_model 

def input_fn(input_data, content_type):
    # decode the input data  (e.g. JSON string -> dict)
    data = decoder_encoder.decode(input_data, content_type)
    return data

def predict_fn(data, model):
    # call your custom model with the data
    outputs = model(data , ... )
    return predictions

def output_fn(prediction, accept):
    # convert the model output to the desired output format (e.g. dict -> JSON string)
    response = decoder_encoder.encode(prediction, accept)
    return response

仅使用 model_fntransform_fn 自定义推理模块:

from sagemaker_huggingface_inference_toolkit import decoder_encoder

def model_fn(model_dir):
    # implement custom code to load the model
    loaded_model = ...
    
    return loaded_model 

def transform_fn(model, input_data, content_type, accept):
     # decode the input data (e.g. JSON string -> dict)
    data = decoder_encoder.decode(input_data, content_type)

    # call your custom model with the data
    outputs = model(data , ... ) 

    # convert the model output to the desired output format (e.g. dict -> JSON string)
    response = decoder_encoder.encode(output, accept)

    return response

重点,这里的话我们 all-MiniLM-L6-v2的示例代码如下:

from transformers import AutoTokenizer, AutoModel
import torch
import torch.nn.functional as F

#Mean Pooling - Take attention mask into account for correct averaging
def mean_pooling(model_output, attention_mask):
    token_embeddings = model_output[0] #First element of model_output contains all token embeddings
    input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
    return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)


# Sentences we want sentence embeddings for
sentences = ['This is an example sentence', 'Each sentence is converted']

# Load model from HuggingFace Hub
tokenizer = AutoTokenizer.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')
model = AutoModel.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')

# Tokenize sentences
encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')

# Compute token embeddings
with torch.no_grad():
    model_output = model(**encoded_input)

# Perform pooling
sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])

# Normalize embeddings
sentence_embeddings = F.normalize(sentence_embeddings, p=2, dim=1)

print("Sentence embeddings:")
print(sentence_embeddings)

我们需要改造下,改为我们自己需要的自定义代码:

from transformers import AutoTokenizer, AutoModel
import torch
import torch.nn.functional as F

# 这个方法直接同上
def mean_pooling(model_output, attention_mask):
    token_embeddings = model_output[0] #First element of model_output contains all token embeddings
    input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
    return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)

# 覆盖 -- 模型加载 参考all-MiniLM-L6-v2给出的示例代码
def model_fn(model_dir):
  # Load model from HuggingFace Hub
  tokenizer = AutoTokenizer.from_pretrained(model_dir)
  model = AutoModel.from_pretrained(model_dir)
  return model, tokenizer
# 覆盖 -- 预测方法 参考all-MiniLM-L6-v2给出的示例代码
def predict_fn(data, model_and_tokenizer):
    # destruct model and tokenizer
    model, tokenizer = model_and_tokenizer
    
    # Tokenize sentences
    sentences = data.pop("inputs", data)
    encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')

    # Compute token embeddings
    with torch.no_grad():
        model_output = model(**encoded_input)

    # Perform pooling
    sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])

    # Normalize embeddings
    sentence_embeddings = F.normalize(sentence_embeddings, p=2, dim=1)
    
    # return dictonary, which will be json serializable
    return {"vectors": sentence_embeddings[0].tolist()}

3.打包为tar 文件

cd all-MiniLM-L6-v2
tar zcvf model.tar.gz *

4.上传model.tar.gz到S3

5.部署推理

这里有好几种方式可选。

第一种:在jupyterlab执行这个脚本,替换model等参数即可。

  • https://github.com/huggingface/notebooks/blob/main/sagemaker/10_deploy_model_from_s3/deploy_transformer_model_from_s3.ipynb

第二种:这个是吧上面所有步骤都包含了,但是这种无法处理我们在私有环境fine-tune后的模型。

  • https://github.com/huggingface/notebooks/blob/main/sagemaker/17_custom_inference_script/sagemaker-notebook.ipynb

第三种:可视化部署,我重点介绍下这个吧

入口如下:

注意下面的选项

  • 容器框架根据实际情况选择,这里我们就选择如图
  • S3 URI
  • IAM role:
    • 可以去IAM创建角色
      • AmazonS3FullAccess
      • AmazonSageMakerFullAccess
    • 也可以去JumpStart中的model去复制过来。

使用hub

原文:https://huggingface.co/docs/sagemaker/inference#deploy-a-model-from-the–hub

这种方式没有上面的方式灵活度高,支持的model也没有上面的方式多。

1.在sagemaker上新建个jupyterlab

2.上传官方示例ipynb文件

  • https://github.com/huggingface/notebooks/blob/main/sagemaker/11_deploy_model_from_hf_hub/deploy_transformer_model_from_hf_hub.ipynb

3.指定HF_MODEL_ID和HF_TASK进行部署和推理

inference.py官方示例

  • https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-script-mode/pytorch_bert/deploy_bert_outputs.html#Write-the-Inference-Script
import os
import json
from transformers import BertTokenizer, BertModel

def model_fn(model_dir):
    """
    Load the model for inference
    """

    model_path = os.path.join(model_dir, 'model/')

    # Load BERT tokenizer from disk.
    tokenizer = BertTokenizer.from_pretrained(model_path)

    # Load BERT model from disk.
    model = BertModel.from_pretrained(model_path)

    model_dict = {'model': model, 'tokenizer':tokenizer}

    return model_dict

def predict_fn(input_data, model):
    """
    Apply model to the incoming request
    """

    tokenizer = model['tokenizer']
    bert_model = model['model']

    encoded_input = tokenizer(input_data, return_tensors='pt')

    return bert_model(**encoded_input)

def input_fn(request_body, request_content_type):
    """
    Deserialize and prepare the prediction input
    """

    if request_content_type == "application/json":
        request = json.loads(request_body)
    else:
        request = request_body

    return request

def output_fn(prediction, response_content_type):
    """
    Serialize and prepare the prediction output
    """

    if response_content_type == "application/json":
        response = str(prediction)
    else:
        response = str(prediction)

    return response

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/263731.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【RocketMQ每日一问】rocketmq事务消息原理?

rocketmq事务消息原理? RocketMQ的事务消息主要由三部分组成:半消息(Half Message)、执行本地事务和事务补偿机制。下面详细介绍这三部分: 半消息(Half Message)用户向RocketMQ发送半消息&…

基于ssm的星巴克咖啡店管理系统论文

基于ssm的星巴克咖啡店管理系统 摘要 当下,正处于信息化的时代,许多行业顺应时代的变化,结合使用计算机技术向数字化、信息化建设迈进。以前星巴克咖啡店对于咖啡信息的管理和控制,采用人工登记的方式保存相关数据,这…

【AI提示词艺术】第11期 家居几种类型图处理和人像生成的技巧

家居处理和人像生成的技巧 AI处理家居图像具有以下优势: 自动化处理:AI可以自动处理大量的家居图像,无需人工干预。这大大提高了处理效率,节省了时间和人力成本。 快速识别和分类:AI可以快速准确地识别和分类家居图…

LSTM和GRU vs 普通的循环神经网络RNN

1、考虑下列三种情况下,对比一下普通RNN的表现和LSTM和GRU表现: (1)早期观测值对预测未来观测者具有非常重要的意义。 考虑一个极端情况,其中第一个观测值包含一个校验和, 目标是在序列的末尾辨别校验和是…

常见的弧形导轨有哪些

弧形导轨又叫圆弧导轨、滚轮圆弧导轨,是通过v形滚轮在圆弧v型导轨表面滚动,作圆周运动,运用广泛:数控机床、包装机械、输送设备、医疗器械、航空航天等设备;弧形导轨也分几种,常见的弧形导轨有以下几种&…

关于时区处理策略

前端会通过 App-Id 请求头附带 客户端时区 信息 前端传入的如果是 字符串,会自动根据 请求的客户端时区 解析为对应的 日期 如果前端传入的是时间戳,则无需额外解析转换 如果是 商户后台、管理后台 都统一基于 商户所在国家的时区(总台目前…

机器视觉:AI赋能缺陷检测,铸就芯片产品的大算力与高能效

导言:近年来,国内芯片行业快速发展,市场对芯片需求的不断增大,芯片的缺陷检测压力也越来越大。芯片产品在生产制造过程中,需要经历数道工序,每个生产环节的材料、环境、工艺参数等都有可能造成产品缺陷。不…

2023最新版JavaSE教程——第13天:泛型

目录 一、泛型概述1.1 生活中的例子1.2 泛型的引入 二、使用泛型举例2.1 集合中使用泛型2.1.1 举例2.1.2 练习 2.2 比较器中使用泛型2.2.1 举例2.2.2 练习 2.3 相关使用说明 三、自定义泛型结构3.1 泛型的基础说明3.2 自定义泛型类或泛型接口3.2.1 说明3.2.2 注意3.2.2 举例3.2…

react 2

1.快速搭建开发环境 2.react渲染流程 3.1 jsx基础 概念 3.2 jsx基础 本质 3.3 jsx基础 jsx表达式 3.4 jsx基础 实现列表渲染 3.5 jsx基础 实现条件渲染 3.5 jsx基础 实现复杂的条件渲染 4. react中事件绑定 5.react组建基础使用 6.1 useState 6.2 useState修改状态的规则 7.基础…

海外媒体发稿:雅虎全球发稿推广脱颖而出的10种方法-华媒舍

雅虎全球发稿是一项重要的推广手段,能够帮助企业和个人提升品牌知名度和曝光率。在众多的发稿中脱颖而出并不容易。本文将为您介绍10种让您的雅虎全球发稿在众多文章中脱颖而出的方法,帮助您取得更好的效果。 1. 深入研究目标受众 在撰写雅虎全球发稿前…

【排序算法】C语言实现选择排序与冒泡排序

文章目录 🚀前言🚀冒泡排序✈️冒泡排序的逻辑✈️冒泡排序coding 🚀选择排序✈️选择排序的逻辑✈️选择排序coding 🚀前言 这里是阿辉算法与数据结构专栏的第一篇文章,咱们就从排序算法开始讲起,排序算法…

优化企业员工管理的利器——ADManager Plus

在当今数字化的商业环境中,企业员工管理是组织成功运营的关键组成部分。为了提高效率、确保安全性和满足法规合规性要求,企业需要一种强大的工具来简化和集中管理其活跃目录(Active Directory)环境。ADManager Plus作为一款功能丰…

Ubuntu 常用命令之 zip 命令用法介绍

📑Linux/Ubuntu 常用命令归类整理 Ubuntu系统下的zip命令是用来压缩文件的。这个命令可以将一个或多个文件或者目录压缩成一个.zip文件,也可以将整个目录树压缩成一个.zip文件。 zip命令的基本格式 zip [选项] [压缩文件名] [要压缩的文件或目录...]z…

10、基于LunarLander登陆器的Dueling DDQN强化学习(含PYTHON工程)

10、基于LunarLander登陆器的Dueling DDQN强化学习(含PYTHON工程) LunarLander复现: 07、基于LunarLander登陆器的DQN强化学习案例(含PYTHON工程) 08、基于LunarLander登陆器的DDQN强化学习(含PYTHON工程…

Mybatis的关联查询(association和collection)

关联查询 实体间的关系(拥有 has、属于 belong) OneToOne:一对一关系(account ←→ user) OneToMany:一对多关系(user ←→ account) ManyToMany:多对多关系&#xff0…

测试框架|Burp Suite几个基本工具的使用

前阵子项目上想通过测试工具在网页上模拟返回错误代码 500 来查看页面的错误处理,然后去调查了下 burp suite,看了些基本工具的使用文档。虽然最后证实 burp suite 只能用来处理页面测试应用程序的实际行为和响应,而不是尝试模拟不存在的问题…

python脚本传参

sys.argvargparse 第一种:argparse 简单使用: import argparse # 创建一个参数解析实例 parser argparse.ArgumentParser(descriptionParameters) # 添加参数解析 parser.add_argument(--training_epoch, typeint, default3000) parser.add_argument(…

flutter + firebase 云消息通知教程 (android-安卓、ios-苹果)

如果能看到这篇文章的 一定已经对手机端的 消息推送通知 有了一定了解。 国内安卓厂商这里不提都有自己的FCM 可自行查找。(国内因无法科学原因 ,不能使用谷歌服务)只说海外的。 目前 adnroid 和 ios 推送消息分别叫 FCM 和 APNs。这里通过…

flutter开发windows应用的库

一、window_manager 这个插件允许 Flutter 桌面应用调整窗口的大小和位置 地址:https://github.com/leanflutter/window_manager二、win32 一个包,它使用FFI包装了一些最常见的Win32 API调用,使Dart代码可以访问这些调用,而不需…

华为交换机配置BGP的基本示例

BGP简介 定义 边界网关协议BGP(Border Gateway Protocol)是一种实现自治系统AS(Autonomous System)之间的路由可达,并选择最佳路由的距离矢量路由协议。早期发布的三个版本分别是BGP-1(RFC1105&#xff0…
最新文章