从零开发短视频电商 在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_encoderdef model_fn(model_dir):# implement custom code to load the modelloaded_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 datadef predict_fn(data, model):# call your custom model with the dataoutputs = model(data , ... )return predictionsdef 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_encoderdef model_fn(model_dir):# implement custom code to load the modelloaded_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 dataoutputs = 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 embeddingsinput_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 embeddingsinput_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 Hubtokenizer = 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 tokenizermodel, tokenizer = model_and_tokenizer# Tokenize sentencessentences = data.pop("inputs", data)encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')# Compute token embeddingswith torch.no_grad():model_output = model(**encoded_input)# Perform poolingsentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])# Normalize embeddingssentence_embeddings = F.normalize(sentence_embeddings, p=2, dim=1)# return dictonary, which will be json serializablereturn {"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, BertModeldef 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_dictdef 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_bodyreturn requestdef 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.mzph.cn/news/238276.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Mysql的基础问题原理

存储引擎: 存储引擎是Inndb。它支持行级锁,以及表级锁, 支持事务操作, 需要主键,若未声明主键,则会寻找表中的 not null 以及 unique 修饰的字段。若表中无此类字段,会隐式生成字段。 索引&…

解决win10下强制设置web浏览器为microsoft edge的方法

目录 问题场景实现方法禁止edge默认选项设置默认浏览器 反思 问题场景 因为一些特殊的原因,我需要第二个浏览器,我的第一个浏览器是google的chrome浏览器,所以我选择的是windows的默认浏览器,就是microsoft edge浏览器&#xff0…

UI Grounding 学习笔记

学习资料 【OpenMMLab社区开放麦讲座】《颠覆性创新:多模态对话与精准区域分割 - VPGTrans & NExT-Chat》 1. 学术关键字 LLM Detection 2. 相关论文 InstructBLIP:指令微调RT-DETRVPGTrans: Transfer Visual Prompt Generator across LLMs (Ne…

【Java】Mybatis

MyBatis JavaEE三层框架:表现层、业务层、持久层。 现在开始学习持久层。持久层就是负责与数据库打交道的代码。 框架:就是一个半成品软件。在框架的基础上,可以更加高效地写出代码。 1、MyBatis快速入门 1、准备工作(创建sp…

SpringMVC配置文件

springMVC-servlet.xml springMVC配置 放在resources下 <?xml version"1.0" encoding"UTF-8"?> <beans xmlns"http://www.springframework.org/schema/beans"xmlns:context"http://www.springframework.org/schema/context&quo…

【大模型】快速体验百度智能云千帆AppBuilder搭建知识库与小助手

文章目录 前言千帆AppBuilder什么是千帆AppBuilderAppBuilder能做什么 体验千帆AppBuilderJava知识库高考作文小助手 总结 前言 前天&#xff0c;在【百度智能云智算大会】上&#xff0c;百度智能云千帆AppBuilder正式开放服务。这是一个AI原生应用开发工作台&#xff0c;可以…

【C++入门到精通】互斥锁 (Mutex) C++11 [ C++入门 ]

阅读导航 引言一、Mutex的简介二、Mutex的种类1. std::mutex &#xff08;基本互斥锁&#xff09;2. std::recursive_mutex &#xff08;递归互斥锁&#xff09;3. std::timed_mutex &#xff08;限时等待互斥锁&#xff09;4. std::recursive_timed_mutex &#xff08;限时等待…

【沁恒蓝牙mesh】CH58x DataFlash 详解

本文主要介绍了 沁恒蓝牙芯片 CH58x 的 DataFlash 分区以及读写操作以及原理 &#x1f4cb; 个人简介 &#x1f496; 作者简介&#xff1a;大家好&#xff0c;我是喜欢记录零碎知识点的小菜鸟。&#x1f60e;&#x1f4dd; 个人主页&#xff1a;欢迎访问我的 Ethernet_Comm 博…

Oracle重建索引详解

更新&#xff1a;2023-05-17 18:08 一、Oracle重建索引命令 Oracle重建索引可以通过ALTER INDEX命令来完成。下面是示例代码&#xff1a; ALTER INDEX index_name REBUILD [PARAMETERS];其中&#xff0c;index_name是需要重建的索引名称&#xff0c;PARAMETERS是可选的重建参…

CUMT--Java复习--JDBC编程

目录 一、JDBC简介 二、数据库访问 1、加载数据库驱动 2、建立数据连接 3、创建Statement对象 4、执行SQL语句 5、访问结果集 三、MetaData接口 1、DatabaseMetaData接口 2、ResultSetMetaData接口 四、事务 1、JDBC中的事务 2、保存点 3、批量更新 一、JDBC简…

【LeetCode】459. 重复的子字符串(KMP2.0)

今日学习的文章链接和视频链接 leetcode题目地址&#xff1a;459. 重复的子字符串 代码随想录题解地址&#xff1a;代码随想录 题目简介 给定一个非空的字符串 s &#xff0c;检查是否可以通过由它的一个子串重复多次构成。 看到题目的第一想法(可以贴代码&#xff09; 1.…

韵达快递查询入口,一键将退回件筛选出来

批量查询韵达快递单号的物流信息&#xff0c;并将退回件一键筛选出来。 所需工具&#xff1a; 一个【快递批量查询高手】软件 韵达快递单号若干 操作步骤&#xff1a; 步骤1&#xff1a;运行【快递批量查询高手】软件&#xff0c;并登录 步骤2&#xff1a;点击主界面左上角的…

CSS-SVG-环形进度条

线上代码地址 <div class"circular-progress-bar"><svg><circle class"circle-bg" /><circle class"circle-progress" style"stroke-dasharray: calc(2 * 3.1415 * var(--r) * (var(--percent) / 100)), 1000" …

影响晶振频率稳定性的因素及解决方法

晶振作为电子设备中的核心元件&#xff0c;其频率稳定性对设备的性能和可靠性具有重要影响。晶发电子将介绍影响晶振频率稳定性的因素&#xff0c;并探讨相应的解决方法。 一、影响晶振频率稳定性的因素 频率&#xff1a;晶振的频率是影响其性能的最重要因素之一。在选择晶振…

初识Docker-什么是docker

Docker是一个快速交付应用、运行应用的技术 目录 一、Docker 二、运用场景 一、什么是Docker&#xff1f;它的作用是什么&#xff1f; Docker如何解决大型项目依赖关系复杂&#xff0c;不同组件依赖的兼容性问题? Docker允许开发中将应用、依赖、函数库、配置一起打包&…

基于SSM的勤工助学系统的设计与实现论文

勤工助学系统设计 摘要 随着信息互联网购物的飞速发展&#xff0c;一般企业都去创建属于自己的电商平台以及购物管理系统。本文介绍了勤工助学系统的开发全过程。通过分析企业对于勤工助学系统的需求&#xff0c;创建了一个计算机管理勤工助学系统的方案。文章介绍了勤工助学系…

SpringBoot访问外部接口的常见方式

文章目录 SpringBoot访问外部接口模拟服务接口RestTemplatepom.xmlRestTemplateConfigClientTestRestTemplateController.java结果 WebClientpom.xmlClientTestWebClientController.java结果 HttpClientpom.xmlClientTestHttpClientController.java结果 OkHttppom.xmlClientTes…

LeetCode Hot100 295.数据流的中位数

题目&#xff1a; 中位数是有序整数列表中的中间值。如果列表的大小是偶数&#xff0c;则没有中间值&#xff0c;中位数是两个中间值的平均值。 例如 arr [2,3,4] 的中位数是 3 。例如 arr [2,3] 的中位数是 (2 3) / 2 2.5 。 实现 MedianFinder 类: MedianFinder() 初始…

linux sed命令操作大全

经常使用&#xff0c;但有些总记不全&#xff0c;有时候经常查找&#xff0c;这次全部捋清楚做备忘&#xff0c;有需要的小伙伴欢迎收藏起来哦&#xff01; 查、增、改、删一应俱全&#xff0c;非常详细&#xff01; 目录 一、查看 查看第2行 查看第2行到第3行 查看第1行、…

移动SEO:如何针对任何设备优化您的网站

您快速进行 Google 搜索并阅读一堆结果。然后&#xff0c;您会发现一些网站具有您正在寻找的答案。 但是你从SERP中选择的第一个&#xff0c;也是最有前途的网站&#xff0c;在你最喜欢的移动设备上无法正常工作。 所以&#xff0c;你关闭它&#xff0c;看看下一个网站是否有…