当前位置: 首页 > news >正文

LLM推理部署(六):TogetherAI推出世界上LLM最快推理引擎,性能超过vLLM和TGI三倍

LLM能有多快?答案在于LLM推理的最新突破。

       TogetherAI声称,他们在CUDA上构建了世界上最快的LLM推理引擎,该引擎运行在NVIDIA Tensor Core GPU上。Together推理引擎可以支持100多个开源大模型,比如Llama-2,并在Llama-2–70B-Chat上每秒生成117个tokens,在Llama2–13B-Chat中每秒生成171个tokens。

文本将从以下几点进行介绍:

  • Together推理引擎技术;
  • 使用Python API进行LLM推理;
  • 与LangChain的集成;
  • 管理聊天历史记录

一、TogetherAI推动LLM推理的极限

       TogetherAI新的LLM推理引擎性能超过vLLM和TGI,如下图所示:

       定价合理,Llama-2–13b Chat不仅比GPT 3.5 Turbo便宜6倍,而且速度快1.85倍。

TogetherAI推理引擎的方法结合了以下三个关键技术:

FlashAttention-2:可以提高LLM的训练和微调速度4倍以上,并在NVIDIA A100s上实现了72%的模型FLOP利用率。这一点很重要,因为传统的注意力计算受内存带宽限制,通常会进行大量内存交换。Flash Attention重组矩阵运算以减少内存交换,使模型速度翻倍或更多;

Flash-Decoding:加快推理过程中的注意力计算,对超长序列,生成速度可以提高8倍。对输入序列中的多个tokens通过重新组织句子计算可以批处理注意力计算。对短Prompt影响很小,但对于较长的序列(例如,10ktokens),性能可能会翻倍;

Medusa:在LLM的最后隐藏状态之上添加多个头来预测下一个token,然后使用模型来验证这个预测的token,推理速度可以提高2倍。

让我们看看TogetherAI在实践中是如何工作的。

二、TogetherAI如何使用

      登录TogetherAI(https://www.together.ai/)并注册即可获得25美元的免费积分。

      TogetherAI提供了使用LLM的各种功能,可以在左侧导航窗格中看到其中的一些功能。

可以在“设置”中找到您的API密钥和帐单信息。

可以在UI上测试不同的功能,但我们真正想要的是通过API访问。

2.1 设置环境

      让我们从设置虚拟环境开始:

mkdir togetherai-serving && cd togetherai-servingpython3 -m venv togetherai-serving-envsource togetherai-serving-env/bin/activatepip3 install ipykernel jupyterpip3 install python-dotenvpip3 install --upgrade togetherpip3 install langchain huggingface_hub# Optionally, fire up VSCode or your favorite IDE and let's get rolling!code .

创建.env文件并添加TogetherAI API密钥:

TOGETHER_API_KEY=<Your API Key>

和导入所需的库:

import osimport timeimport jsonimport loggingfrom datetime import datetimeimport togetherfrom langchain.llms.base import LLMfrom langchain import PromptTemplate,  LLMChainfrom dotenv import load_dotenv # The dotenv library's load_dotenv function reads a .env file to load environment variables into the process environment. This is a common method to handle configuration settings securely.# Load env variablesload_dotenv()# Set up logginglogging.basicConfig(level=logging.INFO)

2.2 了解TogetherAI Python API

我们现在可以查看一下TogetherAI支持的模型,并选择一个来使用:

model_list = together.Models.list()print(f"There are {len(model_list)} models to choose from!")[model['name'] for model in model_list][:20]

总共支持103个模型,下面查看前20个模型

There are 103 models to choose from!['Austism/chronos-hermes-13b','EleutherAI/llemma_7b','EleutherAI/pythia-12b-v0', 'EleutherAI/pythia-1b-v0', 'EleutherAI/pythia-2.8b-v0', 'EleutherAI/pythia-6.9b', 'Gryphe/MythoMax-L2-13b', 'HuggingFaceH4/starchat-alpha', 'NousResearch/Nous-Hermes-13b', 'NousResearch/Nous-Hermes-Llama2-13b', 'NousResearch/Nous-Hermes-Llama2-70b', 'NousResearch/Nous-Hermes-llama-2-7b', 'NumbersStation/nsql-llama-2-7B', 'Open-Orca/Mistral-7B-OpenOrca', 'OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5', 'OpenAssistant/stablelm-7b-sft-v7-epoch-3', 'Phind/Phind-CodeLlama-34B-Python-v1', 'Phind/Phind-CodeLlama-34B-v2', 'SG161222/Realistic_Vision_V3.0_VAE', 'WizardLM/WizardCoder-15B-V1.0']

让我们使用“togethercomputer/lama-2–7b chat”来生成一个回复:

prompt = "<human>: What do you think about Large Language Models?\n<bot>:"model = "togethercomputer/llama-2-7b-chat"output = together.Complete.create(  prompt = prompt,  model = model,   max_tokens = 256,  temperature = 0.8,  top_k = 60,  top_p = 0.6,  repetition_penalty = 1.1,  stop = ['<human>', '\n\n'])print(json.dumps(output, indent = 4))

花了2秒才得到完整的答案,以下是输出:

{    "id": "8268eed93d23b903-AMS",    "status": "finished",    "prompt": [        "<human>: What do you think about Large Language Models?\n<bot>:"    ],    "model": "togethercomputer/llama-2-7b-chat",    "model_owner": "",    "tags": {},    "num_returns": 1,    "args": {        "model": "togethercomputer/llama-2-7b-chat",        "prompt": "<human>: What do you think about Large Language Models?\n<bot>:",        "top_p": 0.6,        "top_k": 60,        "temperature": 0.8,        "max_tokens": 256,        "stop": [            "<human>",            "\n\n"        ],        "repetition_penalty": 1.1,        "logprobs": null    },    "subjobs": [],    "output": {        "result_type": "language-model-inference",        "choices": [            {                "text": "Large language models, such as transformer-based models like BERT and RoBERTa, have been instrumental in achieving state-of-the-art results in a wide range of natural language processing (NLP) tasks. These models are trained on large amounts of text data and have the ability to learn complex patterns and relationships in language.\n\n"            }        ]    }}

以下是如何获得生成的响应:

print(output['output']['choices'][0]['text'])# Large language models, such as transformer-based models like BERT and # RoBERTa, have been instrumental in achieving state-of-the-art results # in a wide range of natural language processing (NLP) tasks. These models # are trained on large amounts of text data and have the ability to learn # complex patterns and relationships in language.

还可以使用流:

for token in together.Complete.create_streaming(prompt=prompt):    print(token, end="", flush=True)

现在,我们来看看LangChain集成。

三、TogetherAI与LangChain的集成

       为了在LangChain中使用TogetherAI,我们必须扩展基本LLM抽象类。

这里有一个创建自定义LLM包装器的示例代码(https://python.langchain.com/docs/modules/model_io/llms/custom_llm),但我们将通过类型验证、异常处理和日志记录使其变得更好。

class TogetherLLM(LLM):    """    Together LLM integration.    Attributes:        model (str): Model endpoint to use.        together_api_key (str): Together API key.        temperature (float): Sampling temperature to use.        max_tokens (int): Maximum number of tokens to generate.    """        model: str = "togethercomputer/llama-2-7b-chat"    together_api_key: str = os.environ["TOGETHER_API_KEY"]    temperature: float = 0.7    max_tokens: int = 512    @property    def _llm_type(self) -> str:        """Return type of LLM."""        return "together"    def _call(self, prompt: str, **kwargs: Any) -> str:            """Call to Together endpoint."""            try:                logging.info("Making API call to Together endpoint.")                return self._make_api_call(prompt)            except Exception as e:                logging.error(f"Error in TogetherLLM _call: {e}", exc_info=True)                raise    def _make_api_call(self, prompt: str) -> str:        """Make the API call to the Together endpoint."""        together.api_key = self.together_api_key        output = together.Complete.create(            prompt,            model=self.model,            max_tokens=self.max_tokens,            temperature=self.temperature,        )        logging.info("API call successful.")        return output['output']['choices'][0]['text']

       langchain.lms.base模块通过提供比直接实现_generate方法用户更友好的界面来简化与LLM的交互。

       类langchain.lms.base.LLM是LLM的一个抽象基类,这意味着它为其他类提供了一个模板,但并不意味着它自己被实例化。它旨在通过在内部处理LLM的复杂性,为LLM的工作提供一个更简单的界面,允许用户更容易地与这些模型交互。

       __call__方法允许像函数一样调用类,它检查缓存并在给定提示下运行LLM。

我们现在可以创建TogetherLLM的类实例:

llm = TogetherLLM(    model = model,    max_tokens = 256,    temperature = 0.8)

然后创建LLM链:

prompt_template = "You are a friendly bot, answer the following question: {question}"prompt = PromptTemplate(    input_variables=["question"], template=prompt_template)chat = LLMChain(llm=llm, prompt=prompt)

让我们开始对话:

chat("Can AI take over developer jobs?")
INFO:root:Making API call to Together endpoint.INFO:root:API call successful.{'question': 'Can AI take over developer jobs?', 'text': '\n\nNo, AI will not take over developer jobs. AI can assist developers in various ways, such as automating repetitive tasks, generating code, or analyzing data, but it will not replace human developers. Developers are needed to design, build, and maintain complex software systems, which require creativity, critical thinking, and problem-solving skills that AI systems do not possess. Additionally, the field of software development is constantly evolving, and new technologies and techniques are constantly being developed, which requires developers to stay up-to-date and adapt to new challenges.'}

让我们看看还能做些什么。

四、管理聊天历史记录

       单轮聊天是可以,但这是一个聊天模型,我们来学习一下如何管理聊天历史,以实现更连贯和上下文感知的互动。

       以下是LangChain文档中的一个简单图表,显示了流程:

       然而,不想使用LangChain的抽象,而是想重新实现LLMChain类,让用户更好地debug代码。

from typing import Listclass LLMChain:    def __init__(self, llm, prompt):        self.llm = llm        self.prompt = prompt        self.history: List[str] = []  # Initialize an empty list to keep track of the conversation history    def add_to_history(self, user_input: str, bot_response: str):        self.history.append(f"<human>: {user_input}")        self.history.append(f"<bot>: {bot_response}")    def generate_prompt(self, question: str) -> str:        history_str = "\n".join(self.history)  # Convert the history list into a single string        return f"{history_str}\n<human>: {question}\n<bot>:"    def ask(self, question: str) -> str:        full_prompt = self.generate_prompt(question)        response = self.llm._call(full_prompt)  # Assuming _call method handles the actual API call        self.add_to_history(question, response)        return response

       在这个实现中,我们每次调用ask方法时,会话历史都会更新为最新的交换。generate_prompt方法构造一个包含此历史记录的新Prompt来维护会话的上下文。

       通过以下实例看一些如何使用

# Usagellm = TogetherLLM(    model = model,    max_tokens = 256,    temperature = 0.8)prompt_template = "You are a friendly bot, answer the following question: {question}"prompt = PromptTemplate(    input_variables=["question"], template=prompt_template)chat = LLMChain(llm=llm, prompt=prompt)# Example interactionresponse = chat.ask("What is the weather like today?")print(response)  # Bot's response# The next call to chat.ask will include the previous interaction in the promptresponse = chat.ask("How can I enjoy such a weather?")print(response)

       你可能已经注意到,随着聊天历史的增长,很难管理模型的上下文窗口,有几种策略可以处理它,后面会继续分享,敬请期待。

参考文献:

[1] https://medium.com/@datadrifters/the-worlds-fastest-llm-inference-engine-3x-faster-than-vllm-and-tgi-a2ed9e33c55f?source=email-c63e4493b83d-1702407845871-digest.reader--a2ed9e33c55f----2-98------------------775b79bd_d6f0_4703_a101_7e17ca89ae00-1

[2] https://www.together.ai/blog/together-inference-engine-v1

相关文章:

LLM推理部署(六):TogetherAI推出世界上LLM最快推理引擎,性能超过vLLM和TGI三倍

LLM能有多快&#xff1f;答案在于LLM推理的最新突破。 TogetherAI声称&#xff0c;他们在CUDA上构建了世界上最快的LLM推理引擎&#xff0c;该引擎运行在NVIDIA Tensor Core GPU上。Together推理引擎可以支持100多个开源大模型&#xff0c;比如Llama-2&#xff0c;并在Llama-2–…...

Unity | 渡鸦避难所-2 | 搭建场景并添加碰撞器

1 规范项目结构 上期中在导入一系列的商店资源包后&#xff0c;Assets 目录已经变的混乱不堪 开发过程中&#xff0c;随着资源不断更新&#xff0c;遵循一定的项目结构和设计规范是非常必要的。这可以增加项目的可读性、维护性、扩展性以及提高团队协作效率 这里先做下简单的…...

展望2024年供应链安全

2023年是开展供应链安全&#xff0c;尤其是开源治理如火如荼的一年&#xff0c;开源治理是供应链安全最重要的一个方面&#xff0c;所以我们从开源治理谈起。我们先回顾一下2023的开源治理情况。我们从信通院《2023年中国企业开源治理全景观察》发布的信息。信通院调研了来自七…...

React 列表页实现

一、介绍 列表页是常用的功能&#xff0c;从后端获取列表数据&#xff0c;刷新到页面上。开发列表页需要考虑以下技术要点:1.如何翻页&#xff1b;2.如何进行内容搜索&#xff1b;3.何时进行页面刷新。 二、使用教程 1.user-service 根据用户id获取用户列表&#xff0c;返回…...

【程序人生】还记得当初自己为什么选择计算机?

✏️ 初识计算机&#xff1a; 还记得人生中第一次接触计算机编程是在高中&#xff0c;第一门编程语言是Python&#xff08;很可惜由于条件限制的原因&#xff0c;当时没能坚持学下去......现在想来有点后悔&#xff0c;没能坚持&#xff0c;唉......&#xff09;。但是&#xf…...

9-tornado-Template优化方法、个人信息案例、tornado中ORM的使用(peewee的使用、peewee_async)、WTForms的使用

在很多情况下&#xff0c;前端模板中在很多页面有都重复的内容可以使用&#xff0c;比如页头、页尾、甚至中间的内容都有可能重复。这时&#xff0c;为了提高开发效率&#xff0c;我们就可以考虑在共同的部分提取出来&#xff0c; 主要方法有如下&#xff1a; 1. 模板继承 2. U…...

IDEA中.java .class .jar的含义与联系

当使用IntelliJ IDEA这样的集成开发环境进行Java编程时&#xff0c;通常涉及.java源代码文件、.class编译后的字节码文件以及.jar可执行的Java存档文件。 1. .java 文件&#xff1a; 1.这些文件包含了Java源代码&#xff0c;以文本形式编写。它们通常位于项目中的源代码目录中…...

北斗三号短报文森林消防应急通信及天通野外图传综合方案

森林火灾突发性强、破坏性大、危险性高&#xff0c;是全球发生最频繁、处置最困难、危害最严重的自然灾害之一&#xff0c;是生态文明建设成果和森林资源安全的最大威胁&#xff0c;甚至可能引发生态灾难和社会危机。我国总体上是一个缺林少绿、生态脆弱的国家&#xff0c;是一…...

js Array.every()的使用

2023.12.13今天我学习了如何使用Array.every()的使用&#xff0c;这个方法是用于检测数组中所有存在的元素。 比如我们需要判断这个数组里面的全部元素是否都包含张三&#xff0c;可以这样写&#xff1a; let demo [{id: 1, name: 张三}, {id: 2, name: 张三五}, {id: 3, name…...

前端编码中快速填充内容--乱数假文

写前端页面的时候&#xff0c;如果要快速插入图片&#xff0c;可以使用 https://picsum.photos/ 详见笔者这篇博文&#xff1a; 工具网站&#xff1a;随机生成图片的网站-CSDN博客 可是&#xff0c;如果要快速填充文字内容该怎么做呢&#xff1f; 以前&#xff0c;我们都是…...

数据结构二维数组计算题,以行为主?以列为主?

1.假设以行序为主序存储二维数组Aarray[1..100,1..100]&#xff0c;设每个数据元素占2个存储单元&#xff0c;基地址为10&#xff0c;则LOC[5,5]&#xff08; &#xff09;。 A&#xff0e;808 B&#xff0e;818 C&#xff0e;1010 D&…...

springboot(ssm电影院订票信息管理系统 影院购票系统Java系统

springboot(ssm电影院订票信息管理系统 影院购票系统Java系统 开发语言&#xff1a;Java 框架&#xff1a;ssm/springboot vue JDK版本&#xff1a;JDK1.8&#xff08;或11&#xff09; 服务器&#xff1a;tomcat 数据库&#xff1a;mysql 5.7&#xff08;或8.0&#xff0…...

AI 问答-供应链管理-相关概念:SCM、SRM、MDM、DMS、ERP、OBS、CRM、WMS...

一、供应链管理是什么 供应链管理&#xff1a;理解供应链管理_snowli的博客-CSDN博客 二、SCM 供应链管理 SCM全称为“Supply Chain Management”&#xff0c;即供应链管理。 SCM是企业管理范畴中一个非常重要的概念&#xff0c;指的是企业与供应商、生产商、分销商等各方之…...

初学vue3与ts:vue3选项式api获取当前路由地址

vue2的获取方法 this.$route.pathvue3选项式api获取方法 import { useRouter } from vue-router; const router useRouter(); console.log(router) console.log(router.currentRoute.value.path)...

2023最新大模型实验室解决方案

人工智能是引领未来的新兴战略性技术&#xff0c;是驱动新一轮科技革命和产业变革的重要力量。近年来&#xff0c;人工智能相关技术持续演进&#xff0c;产业化和商业化进程不断提速&#xff0c;正在加快与千行百业深度融合。 大模型实验室架构图 大模型实验室建设内容 一、课…...

leetcode707.设计链表

题目描述 你可以选择使用单链表或者双链表&#xff0c;设计并实现自己的链表。 单链表中的节点应该具备两个属性&#xff1a;val 和 next 。val 是当前节点的值&#xff0c;next 是指向下一个节点的指针/引用。 如果是双向链表&#xff0c;则还需要属性 prev 以指示链表中的…...

【K8s】Kubernetes CRD 介绍(控制器)

文章目录 CRD 概述1. 操作CRD1.1 创建 CRD1.2 操作 CRD 2. 其他笔记2.1 Kubectl 发现机制2.2 校验 CR2.3 简称和属性 3. 架构设计3.1 控制器概览 参考 CRD 概述 CR&#xff08;Custom Resource&#xff09;其实就是在 Kubernetes 中定义一个自己的资源类型&#xff0c;是一个具…...

Python 小程序之PDF文档加解密

PDF文档的加密和解密 文章目录 PDF文档的加密和解密前言一、总体构思二、使用到的库三、PDF文档的加密1.用户输入模块2.打开并读取文档数据3.遍历保存数据到新文档4.新文档进行加密5.新文档命名生成路径6.保存新加密的文档 四、PDF文档的解密1.用户输入模块2.前提准备2.文件解密…...

使用python脚本一个简单的搭建ansible集群

1.环境说明&#xff1a; 角色主机名ip地址控制主机server192.168.174.150受控主机/被管节点client1192.168.174.151受控主机/被管节点client2192.168.174.152 2.安装python和pip包 yum install -y epel-release yum install -y python python-pip 3.pip安装依赖库 pip in…...

【价值几十万的仿抖音直播电商系统源码共享】

当下&#xff0c;传统的图文电商模式已经走向没落&#xff0c;以抖音为首的直播电商模式备受用户追捧&#xff0c;它具有实时直播和强互动的特点&#xff0c;是传统电商所不具备的优势。而且&#xff0c;当前正是直播电商的红利期&#xff0c;很多主播和品牌商都通过直播电商业…...

ES6从入门到精通:前言

ES6简介 ES6&#xff08;ECMAScript 2015&#xff09;是JavaScript语言的重大更新&#xff0c;引入了许多新特性&#xff0c;包括语法糖、新数据类型、模块化支持等&#xff0c;显著提升了开发效率和代码可维护性。 核心知识点概览 变量声明 let 和 const 取代 var&#xf…...

JavaScript 中的 ES|QL:利用 Apache Arrow 工具

作者&#xff1a;来自 Elastic Jeffrey Rengifo 学习如何将 ES|QL 与 JavaScript 的 Apache Arrow 客户端工具一起使用。 想获得 Elastic 认证吗&#xff1f;了解下一期 Elasticsearch Engineer 培训的时间吧&#xff01; Elasticsearch 拥有众多新功能&#xff0c;助你为自己…...

练习(含atoi的模拟实现,自定义类型等练习)

一、结构体大小的计算及位段 &#xff08;结构体大小计算及位段 详解请看&#xff1a;自定义类型&#xff1a;结构体进阶-CSDN博客&#xff09; 1.在32位系统环境&#xff0c;编译选项为4字节对齐&#xff0c;那么sizeof(A)和sizeof(B)是多少&#xff1f; #pragma pack(4)st…...

uni-app学习笔记二十二---使用vite.config.js全局导入常用依赖

在前面的练习中&#xff0c;每个页面需要使用ref&#xff0c;onShow等生命周期钩子函数时都需要像下面这样导入 import {onMounted, ref} from "vue" 如果不想每个页面都导入&#xff0c;需要使用node.js命令npm安装unplugin-auto-import npm install unplugin-au…...

最新SpringBoot+SpringCloud+Nacos微服务框架分享

文章目录 前言一、服务规划二、架构核心1.cloud的pom2.gateway的异常handler3.gateway的filter4、admin的pom5、admin的登录核心 三、code-helper分享总结 前言 最近有个活蛮赶的&#xff0c;根据Excel列的需求预估的工时直接打骨折&#xff0c;不要问我为什么&#xff0c;主要…...

【SQL学习笔记1】增删改查+多表连接全解析(内附SQL免费在线练习工具)

可以使用Sqliteviz这个网站免费编写sql语句&#xff0c;它能够让用户直接在浏览器内练习SQL的语法&#xff0c;不需要安装任何软件。 链接如下&#xff1a; sqliteviz 注意&#xff1a; 在转写SQL语法时&#xff0c;关键字之间有一个特定的顺序&#xff0c;这个顺序会影响到…...

【RockeMQ】第2节|RocketMQ快速实战以及核⼼概念详解(二)

升级Dledger高可用集群 一、主从架构的不足与Dledger的定位 主从架构缺陷 数据备份依赖Slave节点&#xff0c;但无自动故障转移能力&#xff0c;Master宕机后需人工切换&#xff0c;期间消息可能无法读取。Slave仅存储数据&#xff0c;无法主动升级为Master响应请求&#xff…...

NLP学习路线图(二十三):长短期记忆网络(LSTM)

在自然语言处理(NLP)领域,我们时刻面临着处理序列数据的核心挑战。无论是理解句子的结构、分析文本的情感,还是实现语言的翻译,都需要模型能够捕捉词语之间依时序产生的复杂依赖关系。传统的神经网络结构在处理这种序列依赖时显得力不从心,而循环神经网络(RNN) 曾被视为…...

ios苹果系统,js 滑动屏幕、锚定无效

现象&#xff1a;window.addEventListener监听touch无效&#xff0c;划不动屏幕&#xff0c;但是代码逻辑都有执行到。 scrollIntoView也无效。 原因&#xff1a;这是因为 iOS 的触摸事件处理机制和 touch-action: none 的设置有关。ios有太多得交互动作&#xff0c;从而会影响…...

ArcGIS Pro制作水平横向图例+多级标注

今天介绍下载ArcGIS Pro中如何设置水平横向图例。 之前我们介绍了ArcGIS的横向图例制作&#xff1a;ArcGIS横向、多列图例、顺序重排、符号居中、批量更改图例符号等等&#xff08;ArcGIS出图图例8大技巧&#xff09;&#xff0c;那这次我们看看ArcGIS Pro如何更加快捷的操作。…...