IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 人工智能 -> TorchServe搭建codeBERT分类模型服务 -> 正文阅读

[人工智能]TorchServe搭建codeBERT分类模型服务

背景

最近在做有关克隆代码检测的相关工作,克隆代码是软件开发过程中的常见现象,它在软件开发前期能够提升生产效率,产生一定的正面效益,然而随着系统规模变大,也会产生降低软件稳定性,软件bug传播,系统维护困难等负面作用。本次训练基于codeBERT的分类模型,任务是给定两个函数片段,判断这两个函数片段是否相似,TorchServe主要用于PyTorch模型的部署,现将使用TorchServe搭建克隆代码检测服务过程总结如下。

TorchServe简介

TorchServe是部署PyTorch模型服务的工具,由Facebook和AWS合作开发,是PyTorch开源项目的一部分。它可以使得用户更快地将模型用于生产,提供了低延迟推理API,支持模型的热插拔,多模型服务,A/B test版本控制,以及监控指标等功能。TorchServe架构图如下图所示:

TorchServe框架主要分为四个部分:Frontend是TorchServe的请求和响应的处理部分;Worker Process 指的是一组运行的模型实例,可以由管理API设定运行的数量;Model Store是模型存储加载的地方;Backend用于管理Worker Process。

codeBERT是什么?

codeBERT是一个预训练的语言模型,由微软和哈工大发布。我们知道传统的BERT模型是面向自然语言的,而codeBERT是面向自然语言和编程语言的模型,codeBERT可以处理Python,Java,JavaScript等,能够捕捉自然语言和编程语言的语义关系,可以用来做自然语言代码搜索,代码文档生成,代码bug检查以及代码克隆检测等任务。当然我们也可以利用CodeBERT直接提取编程语言的token embeddings,从而进行相关任务。

环境搭建

安装TorchServe

pip install torchserve
pip install torch-model-archiever

编写Handler类

Handler是我们自定义开发的类,TorchServe运行的时候会执行Handler类,其主要功能就是处理input data,然后通过一系列处理操作返回结果,其中模型的初始化等也是由handler处理。其中Handler类继承自BaseHandler,我们需要重写其中的initialize,preprocess,inference等。

  1. initialize方法
class CloneDetectionHandler(BaseHandler,ABC):
    def __int__(self):
        super(CloneDetectionHandler,self).__init__()
        self.initialized = False
    def initialize(self, ctx):
        self.manifest = ctx.manifest
        logger.info(self.manifest)
        properties = ctx.system_properties
        model_dir = properties.get("model_dir")
        serialized_file = self.manifest['model']['serializedFile']
        model_pt_path = os.path.join(model_dir,serialized_file)
        self.device = torch.device("cuda:"+str(properties.get("gpu_id")) if torch.cuda.is_available() else "cpu")
        config_class, model_class,tokenizer_class = MODEL_CLASSES['roberta']
        config = config_class.from_pretrained("microsoft/codebert-base")
        config.num_labels = 2
        self.tokenizer = tokenizer_class.from_pretrained("microsoft/codebert-base")
        self.bert = model_class(config)
        self.model = Model(self.bert,config,self.tokenizer)
        self.model.load_state_dict(torch.load(model_pt_path))
        self.model.to(self.device)
        self.model.eval()
        logger.info('Clone codeBert model from path {0} loaded successfully'.format(model_dir))
        self.initialized = True
  1. preprocess方法
def preprocess(self, requests):
            input_batch = None
            for idx,data in enumerate(requests):
                input_text = data.get("data")
                if input_text is None:
                    input_text = data.get("body")
                logger.info("Received codes:'%s'",input_text)
                if isinstance(input_text,(bytes,bytearray)):
                    input_text = input_text.decode('utf-8')
                code1 = input_text['code1']
                code2 = input_text['code2']
                code1 = " ".join(code1.split())
                code2 = " ".join(code2.split())
                logger.info("code1:'%s'", code1)
                logger.info("code2:'%s'", code2)
                inputs = self.tokenizer.encode_plus(code1,code2,max_length=512,pad_to_max_length=True, add_special_tokens=True, return_tensors="pt")
                input_ids = inputs["input_ids"].to(self.device)
                if input_ids.shape is not None:
                    if input_batch is None:
                        input_batch = input_ids
                    else:
                        input_batch = torch.cat((input_batch,input_ids),0)
            return input_batch
  1. inference方法
def inference(self, input_batch):
    inferences = []
    logits = self.model(input_batch)
    num_rows = logits[0].shape[0]
    for i in range(num_rows):
    out = logits[0][i].unsqueeze(0)
    y_hat = out.argmax(0).item()
    predicted_idx = str(y_hat)
    inferences.append(predicted_idx)
    return inferences

模型打包

使用toch-model-archiver工具进行打包,将模型参数文件以及其所依赖包打包在一起,在当前目录下会生成mar文件

torch-model-archiver --model-name BERTClass --version 1.0 \
    --serialized-file ./CloneDetection.bin \
    --model-file ./model.py \
    --handler ./handler.py \

启动服务

torchserve --start --ncs --model-store ./modelstore --models BERTClass.mar

服务测试

import requests
import json
diff_codes = {
    "code1": "    private void loadProperties() {\n        if (properties == null) {\n            properties = new Properties();\n            try {\n                URL url = getClass().getResource(propsFile);\n                properties.load(url.openStream());\n            } catch (IOException ioe) {\n                ioe.printStackTrace();\n            }\n        }\n    }\n",
    "code2": "    public static void copyFile(File in, File out) throws IOException {\n        FileChannel inChannel = new FileInputStream(in).getChannel();\n        FileChannel outChannel = new FileOutputStream(out).getChannel();\n        try {\n            inChannel.transferTo(0, inChannel.size(), outChannel);\n        } catch (IOException e) {\n            throw e;\n        } finally {\n            if (inChannel != null) inChannel.close();\n            if (outChannel != null) outChannel.close();\n        }\n    }\n"
}
res = requests.post('http://127.0.0.1:8080/predictions/BERTClass",json=diff_codes).text

第二个请求输入克隆代码对,模型预测结果为1,两段代码段相似,是克隆代码对。克隆代码大体分为句法克隆和语义克隆,本例展示的句法克隆,即对函数名,类名,变量名等重命名,增删部分代码片段还相同的代码对。

clone_codes = {
    "code1":"    public String kodetu(String testusoila) {\n        MessageDigest md = null;\n        try {\n            md = MessageDigest.getInstance(\"SHA\");\n            md.update(testusoila.getBytes(\"UTF-8\"));\n        } catch (NoSuchAlgorithmException e) {\n            new MezuLeiho(\"Ez da zifraketa algoritmoa aurkitu\", \"Ados\", \"Zifraketa Arazoa\", JOptionPane.ERROR_MESSAGE);\n            e.printStackTrace();\n        } catch (UnsupportedEncodingException e) {\n            new MezuLeiho(\"Errorea kodetzerakoan\", \"Ados\", \"Kodeketa Errorea\", JOptionPane.ERROR_MESSAGE);\n            e.printStackTrace();\n        }\n        byte raw[] = md.digest();\n        String hash = (new BASE64Encoder()).encode(raw);\n        return hash;\n    }\n",
    "code2":"    private StringBuffer encoder(String arg) {\n        if (arg == null) {\n            arg = \"\";\n        }\n        MessageDigest md5 = null;\n        try {\n            md5 = MessageDigest.getInstance(\"MD5\");\n            md5.update(arg.getBytes(SysConstant.charset));\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n        return toHex(md5.digest());\n    }\n"
}
res = requests.post('http://127.0.0.1:8080/predictions/BERTClass",json=clone_codes).text

关闭服务

torchserve --stop

总结

本文主要介绍了如何用TorchServe部署PyTorch模型的流程,首先需要编写hanlder类型文件,然后用torch-model-archiver工具进行模型打包,最后torchserve启动服务,部署流程相对比较简单。

  人工智能 最新文章
2022吴恩达机器学习课程——第二课(神经网
第十五章 规则学习
FixMatch: Simplifying Semi-Supervised Le
数据挖掘Java——Kmeans算法的实现
大脑皮层的分割方法
【翻译】GPT-3是如何工作的
论文笔记:TEACHTEXT: CrossModal Generaliz
python从零学(六)
详解Python 3.x 导入(import)
【答读者问27】backtrader不支持最新版本的
上一篇文章      下一篇文章      查看所有文章
加:2022-10-22 21:15:35  更:2022-10-22 21:19:15 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/20 0:02:08-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码