2023年的深度学习入门指南(6) - 在你的电脑上运行大模型

这篇具有很好参考价值的文章主要介绍了2023年的深度学习入门指南(6) - 在你的电脑上运行大模型。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

2023年的深度学习入门指南(6) - 在你的电脑上运行大模型

上一篇我们介绍了大模型的基础,自注意力机制以及其实现Transformer模块。因为Transformer被PyTorch和TensorFlow等框架所支持,所以我们只要能够配置好框架的GPU或者其他加速硬件的支持,就可以运行起来了。

而想运行大模型,恐怕就没有这么容易了,很有可能你需要一台Linux电脑。因为目前流行的AI软件一般都依赖大量的开源工具,尤其是要进行优化的情况下,很可能需要从源码进行编译。一旦涉及到开源软件和编译这些事情,在Windows上的难度就变成hard模式了。

大部分开发者自身都是在开源系统上做开发的,Windows的适配关注得较少,甚至完全不关心。虽然从Cygwin, MinGW, CMake到WSL,各方都为Windows上支持大量Linux开源库进行了不少努力,但是就像在Linux上没有Windows那么多游戏一样,这是生态的问题。

我们先选取几个Windows的兼容性稍好的项目,让用Windows的同学们也可以体验本机的大模型。

Nomic AI gpt4all (基于LLaMA)

2022年末chatgpt横空出世之后,Meta公司认为openai背离了open的宗旨,于是半开放了他们的大模型LLaMA。半开放的原因是,网络的权重文件需要跟Meta公司申请。
LLaMA主要是针对英语材料进行训练,也引用了部分使用拉丁字母和西里尔字母的语言。它的分词器可以支持汉语和日语,但是并没有使用汉语和日语的材料。

因为不并对所有人开放,我们讲解LLaMA是没有意义的。但是我们可以尝试一些基于LLaMA的项目,比如Nomic AI的gpt4all。

gpt4all的贴心之处是针对Windows, M1 Mac和Intel Mac三种平台都进行了适配,当然默认肯定是支持Linux的。而且,推理使用CPU就可以。

下面我们就将其运行起来吧。

首先下载gpt4all的代码:

git clone https://github.com/nomic-ai/gpt4all

第二步,下载量化之后的网络权重值文件:https://the-eye.eu/public/AI/models/nomic-ai/gpt4all/gpt4all-lora-quantized.bin

第三步,将下载的gpt4all-lora-quantized.bin放在gpt4all的chat目录下

第四步,运行gpt4all-lora-quantized可执行文件。以Windows平台为例,就是运行gpt4all-lora-quantized-win64.exe。可以在powershell中执行,也可以直接点击。

运行后,当加载完模型之后,我们就可以跟gpt4all对话了:

2023年的深度学习入门指南(6) - 在你的电脑上运行大模型,深度学习,人工智能

下面是gpt4all生成的C++快速排序的代码:

Please generate quick sort algorithm in C++ language
Here’s how you can implement Quick Sort Algorithm using C++ :

// Implementation of QuickSort() function for array A[] with size N and pivot value P[N/2]
void QS(int *A, int n) { // Function prototype declaration
    if (n <=1 ) return;   /* If there is only one element in the input Array */
        // QuickSort() function for array A[] with size N and pivot value P[N/2]
        else{                      //else statement to check condition of quick sort algorithm.
            int i = n-1, j=0;               /* Indexes used in the loop*/
             while (i>= 0) {              /* Loop for sorting elements */
                if(A[j]> A[i]){ // Swap condition to check element's position.
                    int temp = A[i];       // Copying value of array index i into a temporary variable 'temp'.
                    A[i]=A[j];             /* Exchanging values at two indices */
                }else{// Swap condition to check element's position.
                    int temp = A[j];       // Copying value of array index j into a temporary variable 'temp'.
                    A[i]=A[j], A[j] = temp; /* Exchanging values at two indices */
                }               i--, j++;             /* Decrement and increment loop indexes*/
            }; // End of while Loop for sorting elements.
        }//End if statement to check condition QuickSort() function call with array A[] size N & pivot value P[N/2].

恭喜你!你终于成功在自己的电脑上跑起了一个跟chatgpt一样了不起的预训练大模型。

这个模型虽然能力比chatgpt差了不少,但是它的模型来自LLaMA,训练数据部分取自chatgpt的对话记录,采用了低秩适应(LoRA: Low-Rank Adaptation)和量化的技术来缩减模型大小。每一项技术都是目前的前沿技术。

清华团队的单卡大模型:ChatGLM-6B

清华团队的ChatGLM-6B也是一个目标为运行在单GPU卡上的大模型,其底座为1300万参数的ChatGLM。

下图是2022年10月斯坦福大学对当时主要大模型的评测结果:
2023年的深度学习入门指南(6) - 在你的电脑上运行大模型,深度学习,人工智能

从上图数据来看,虽然ChatGLM是落后于InstuctGPT的chatgpt,但是从跟其它模型的比较来看实力还不错。

我们就来试试基于ChatGLM的压缩后的效果。

我们先下载代码:

git clone https://github.com/THUDM/ChatGLM-6B

然后安装其依赖的库:

pip install -r requirements.txt

上面的gpt4all的Python编程接口不支持Windows,而ChatGLM-6B基于Hugging Face Transformer库开发,支持Windows下的Python编程,我们写个代码来调用它吧:

from transformers import AutoTokenizer, AutoModel

tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True)
model = AutoModel.from_pretrained("THUDM/chatglm-6b-int4-qe", trust_remote_code=True).half().cuda()
model = model.eval()
response, history = model.chat(tokenizer, "用C++实现快速排序", history=[])
print(response)

输出的结果如下:

2023年的深度学习入门指南(6) - 在你的电脑上运行大模型,深度学习,人工智能

#include <iostream>
using namespace std;

void swap(int& a, int& b) {
    int temp = a;
    a = b;
    b = temp;
}

int partition(int arr[], int low, int high) {
    int pivot = arr[high];
    int i = (low - 1);

    for (int j = low; j < high - 1; j++) {
        if (arr[j] < pivot) {
            i++;
            swap(arr[i], arr[j]);
        }
    }
    swap(arr[i+1], arr[high]);
    return i+1;
}

void quicksort(int arr[], int low, int high) {
    if (low < high) {
        int pi = partition(arr, low, high);
        quicksort(arr, low, pi - 1);
        quicksort(arr, pi + 1, high);
    }
}

int main() {
    int arr[] = {5, 2, 9, 1, 6, 3, 8};
    int n = sizeof(arr) / sizeof(arr[0]);

    quicksort(arr, 0, n-1);

    cout << arr[0] << endl;
    return 0;
}

是不是效果还可以?有点chatgpt的意思了吧?

如果你的PyTorch或者Tensorflow的GPU支持装好了的话,这个推理就是用GPU来完成的。我选用了最省显存的4位量化,如果你的显卡更好,可以选择压缩比更低一些的模型。

这里面我们可以引出Transformer时代的门户,hugging face。我们在上面代码中所使用的from的 transformers库,就是hugging face出品的。

from transformers import AutoTokenizer, AutoModel

2023年的深度学习入门指南(6) - 在你的电脑上运行大模型,深度学习,人工智能

从上图我们可以看到,Hugging face基本上就是各种Transformer模型的集散地。使用Hugging face的接口,就可以使用基本上所有的开源的大模型。

大模型是如何炼成的

虽然网络权值需要申请,但是Meta的LLaMA大模型的模型代码是开源的。我们来看看LLaMA的Transformer跟我们上一节构造的标准的Transformer有什么区别:

class Transformer(nn.Module):
    def __init__(self, params: ModelArgs):
        super().__init__()
        self.params = params
        self.vocab_size = params.vocab_size
        self.n_layers = params.n_layers

        self.tok_embeddings = ParallelEmbedding(
            params.vocab_size, params.dim, init_method=lambda x: x
        )

        self.layers = torch.nn.ModuleList()
        for layer_id in range(params.n_layers):
            self.layers.append(TransformerBlock(layer_id, params))

        self.norm = RMSNorm(params.dim, eps=params.norm_eps)
        self.output = ColumnParallelLinear(
            params.dim, params.vocab_size, bias=False, init_method=lambda x: x
        )

        self.freqs_cis = precompute_freqs_cis(
            self.params.dim // self.params.n_heads, self.params.max_seq_len * 2
        )

我们看到,为了加强并发训练,Meta的全连接网络用的是它们自己的ColumnParallelLinear。它们的词嵌入层也是自己做的并发版。

根据层次数,它也是堆了若干层的TransformerBlock。

我们再来看这个Block:

class TransformerBlock(nn.Module):
    def __init__(self, layer_id: int, args: ModelArgs):
        super().__init__()
        self.n_heads = args.n_heads
        self.dim = args.dim
        self.head_dim = args.dim // args.n_heads
        self.attention = Attention(args)
        self.feed_forward = FeedForward(
            dim=args.dim, hidden_dim=4 * args.dim, multiple_of=args.multiple_of
        )
        self.layer_id = layer_id
        self.attention_norm = RMSNorm(args.dim, eps=args.norm_eps)
        self.ffn_norm = RMSNorm(args.dim, eps=args.norm_eps)

    def forward(self, x: torch.Tensor, start_pos: int, freqs_cis: torch.Tensor, mask: Optional[torch.Tensor]):
        h = x + self.attention.forward(self.attention_norm(x), start_pos, freqs_cis, mask)
        out = h + self.feed_forward.forward(self.ffn_norm(h))
        return out

我们发现,它没有使用标准的多头注意力,而是自己实现了一个注意力类。

class Attention(nn.Module):
    def __init__(self, args: ModelArgs):
        super().__init__()

        self.n_local_heads = args.n_heads // fs_init.get_model_parallel_world_size()
        self.head_dim = args.dim // args.n_heads

        self.wq = ColumnParallelLinear(
            args.dim,
            args.n_heads * self.head_dim,
            bias=False,
            gather_output=False,
            init_method=lambda x: x,
        )
        self.wk = ColumnParallelLinear(
            args.dim,
            args.n_heads * self.head_dim,
            bias=False,
            gather_output=False,
            init_method=lambda x: x,
        )
        self.wv = ColumnParallelLinear(
            args.dim,
            args.n_heads * self.head_dim,
            bias=False,
            gather_output=False,
            init_method=lambda x: x,
        )
        self.wo = RowParallelLinear(
            args.n_heads * self.head_dim,
            args.dim,
            bias=False,
            input_is_parallel=True,
            init_method=lambda x: x,
        )

        self.cache_k = torch.zeros(
            (args.max_batch_size, args.max_seq_len, self.n_local_heads, self.head_dim)
        ).cuda()
        self.cache_v = torch.zeros(
            (args.max_batch_size, args.max_seq_len, self.n_local_heads, self.head_dim)
        ).cuda()

闹了半天就是支持了并发和加了cache的多头注意力,K,V,Q穿了个马甲,本质上还是多头自注意力。

其它有趣的工程

LM Flow

LM Flow也是最近很火的项目,它是香港科技大学在LLaMA的基础上搞的全流程开源的,可以在单3090 GPU上进行训练的工程。

其地址在:https://github.com/OptimalScale/LMFlow

LMFlow目前的独特价值在于,它提供的流程比较完整。

比如,在目前的开源项目中,LMFlow是少有的提供了Instruction Tuning的工程。

我们来看个Instruction Tuning的例子:

{"id": 0, "instruction": "The sentence you are given might be too wordy, complicated, or unclear. Rewrite the sentence and make your writing clearer by keeping it concise. Whenever possible, break complex sentences into multiple sentences and eliminate unnecessary words.", "input": "If you have any questions about my rate or if you find it necessary to increase or decrease the scope for this project, please let me know.", "infer30b_before_item": " Output: The sentence you are given might be too wordy, complicated, or unclear. Rewrite the sentence and make your writing clearer by keeping it concise. Whenever possible, break complex sentences into multiple sentences and eliminate unnecessary words. If you have any questions about my rate or if you find it necessary to increase or decrease the scope for this project, please let me know.\n---\nInput: Input: The sentence you are given might be too wordy, complicated, or unclear. Rewrite the sentence and make your writing clearer by keeping it concise. Whenever possible, break complex sentences into multiple sentences and eliminate unnecessary words. If you have any questions about my rate or if you find it necessary to increase or decrease the scope for this project, please let me know.\n Output: Output: The sentence you are given might be too wordy, complicated, or unclear. Rewrite the sentence and make your writing clearer by keeping it concise. Whenever possible, break complex sentences into multiple sentences and eliminate unnecessary words. If you have any questions about my rate or if you find it necessary to increase or decrease the scope for this project, please let me know.\n---\nInput: Input: The sentence you are given might be too wordy, complicated,", "infer30b_after_item": " \n Output: If you have any questions about my rate or need to adjust the scope for this project, please let me know. \n\n", "infer13b_before_item": " The sentence you are given might be too wordy, complicated, or unclear. Rewrite the sentence and make your writing clearer by keeping it concise. Whenever possible, break complex sentences into multiple sentences and eliminate unnecessary words. If you have any questions about my rate or if you find it necessary to increase or decrease the scope for this project, please let me know.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "infer13b_after_item": " \n Output: If you have any questions about my rate or if you find it necessary to increase or decrease the scope for this project, please let me know. \n\n", "infer7b_before_item": " The sentence you are given might be too wordy, complicated, or unclear. Rewrite the sentence and make your writing clearer by keeping it concise. Whenever possible, break complex sentences into multiple sentences and eliminate unnecessary words. If you have any questions about my rate or if you find it necessary to increase or decrease the scope for this project, please let me know.\nInput: The sentence you are given might be too wordy, complicated, or unclear. Rewrite the sentence and make your writing clearer by keeping it concise. Whenever possible, break complex sentences into multiple sentences and eliminate unnecessary words. If you have any questions about my rate or if you find it necessary to increase or decrease the scope for this project, please let me know.\nOutput: The sentence you are given might be too wordy, complicated, or unclear. Rewrite the sentence and make your writing clearer by keeping it concise. Whenever possible, break complex sentences into multiple sentences and eliminate unnecessary words. If you have any questions about my rate or if you find it necessary to increase or decrease the scope for this project, please let me know.\nInput: The sentence you are given might be too wordy, complicated, or unclear. Rewrite the sentence and make your writing clearer by", "infer7b_after_item": " \n Output: If you have any questions about my rate or if you find it necessary to increase or decrease the scope for this project, please let me know. \n\n"}

这让我们见识到了,原来纠错就是这样搞的。这是LLaMA中所缺少的。

HuggingGPT

最近浙大和微软的团队又推出了充分利用Hugging Face的门户中枢地位的Jarvis工程。

2023年的深度学习入门指南(6) - 在你的电脑上运行大模型,深度学习,人工智能

很不幸的是,上面的两个工程,加上前面工程的高级应用,很难在Windows上面完成。我们后面将统一介绍这些需要在Linux环境下的实验。文章来源地址https://www.toymoban.com/news/detail-601879.html

小结

  1. 通过对大模型进行剪枝、降秩、量化等手段,我们是可以在资源受限的电脑上运行推理的。当然,性能是有所损失的。我们可以根据业务场景去平衡,如果能用prompt engineer解决最好
  2. HuggingFace是预训练大模型的编程接口和模型集散地
  3. 大模型的基本原理仍然是我们上节学习的自注意力模型

到了这里,关于2023年的深度学习入门指南(6) - 在你的电脑上运行大模型的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 2023年的深度学习入门指南(9) - SIMD和通用GPU编程

    深度学习从一开始就跟GPU有不解之缘,因为算力是深度学习不可或缺的一部分。 时至今日,虽然多任务编程早已经深入人心,但是很多同学还没有接触过CPU上的SIMD指令,更不用说GPGPU的编程。这一篇我们先给SIMD和GPU编程扫个盲,让大家以后用到的时候有个感性认识。 从多线

    2024年02月02日
    浏览(33)
  • 2023年的深度学习入门指南(2) - 给openai API写前端

    上一篇我们说了,目前的大规模预训练模型技术还避免不了回答问题时出现低级错误。 但是其实,人类犯的逻辑错误也是层出不穷。 比如,有人就认为要想学好chatgpt,就要先学好Python。 其隐含的推理过程可能是这样的: TensorFlow需要使用Python PyTorch需要使用Python Scikit-Learn需

    2023年04月08日
    浏览(33)
  • 2023年的深度学习入门指南(26) - 在自己电脑上运行通义千问7b模型

    通过量化,通义千问4位量化的模型大小为5.86G,可以在3060等小于16G的家用GPU上也可以运行起来。 通义千问7b提供了4位量化好的Qwen/Qwen-7B-Chat-Int4模型,我们直接调用就好。 首先安装依赖包: 如果你是Linux环境的话,可以安装下Flash-Attention来加速: Windows下暂时还用不了,这个

    2024年02月10日
    浏览(36)
  • 测牛学堂:2023软件测试入门学习指南(测试方法之边界值法)

    边界值分析法 边界值:输入数据是一个有序的集合或者范围的时候,处于集合范围的边界上的值。 边界值的几个常用的概念: 上点:边界上的点。比如条件是(1,9)那么上点就是2和9 离点:开区间的离点,就是反方向去取。(1,9) 的离点,就是2和8 内点:范围内除了上点和

    2023年04月25日
    浏览(29)
  • 手把手带你入门深度学习(一):保姆级Anaconda和PyTorch环境配置指南

    B站:马上就更!!!_bilibili CSDN:手把手带你入门深度学习(一):保姆级Anaconda和PyTorch环境配置指南_百年后封笔-CSDN博客 Github:封笔 公众号:百年后封笔 你好,我是封笔! 如今深度学习技术的不断演进,我们的生活发生着翻天覆地的变化,无论是计算机视觉、自然语言处

    2024年02月08日
    浏览(50)
  • kotlin入门教程指南(2023最新)

    Kotlin 是一个基于 JVM 的新的编程语言,目前在国外非常火热,并且在一步步走向国内市场 Kotlin有以下好处: 强大的IDE。而且是JetBrains第一方支持,不是3年更新一次的第三方插件; 库多生态强。Kotlin的设计者非常重视和Java的互操作,所以Kotlin号称可以无缝衔接所有Java库。

    2024年02月14日
    浏览(27)
  • 立体匹配入门指南(8):视差图、深度图、点云

    本篇是比较简单的基础概念,刚入门的朋友可能是需要的。 视差图 三维点云 首先,我们要介绍下这三个概念。 视差(disparity) 视差 d d d 等于同名点对在左视图的列坐标减去在右视图上的列坐标,是 像素单位 d = x l − x r d=x_l-x_r d = x l ​ − x r ​ 立体视觉里,视差概念在极

    2023年04月08日
    浏览(32)
  • 【机器学习学习】第一天:入门指南

    引言 当今社会,机器学习技术已经被广泛应用于许多领域,如自然语言处理、图像处理和金融分析等。然而,机器学习这一领域需要掌握大量的数学知识和编程技能,因此对于初学者来说,可能会感到非常困难。本文将为初学者提供一份机器学习入门指南,帮助他们了解机器

    2024年02月02日
    浏览(28)
  • 一位计科学长写给 2023 级计算机类和人工智能专业的同学们的程序设计入门指南

    本指南内容较多,但你们若能耐心读完,你们将收获很多…… 欢迎访问作者的主页:Xi Xu’s Home Page 什么是程序设计和程序设计语言? 程序设计 1 (programming),或称编程,是给程序解决出特定问题的过程,软件开发过程中的重要步骤。程序设计方法往往以某种程序设计语言

    2024年02月16日
    浏览(39)
  • 前端学习路线指南:从入门到精通【①】

    作为一个前端开发者,学习前端技术是必不可少的。然而,由于前端领域的广阔和不断演进的技术栈,对于初学者来说可能会感到困惑。本篇文章将为你提供一个清晰的前端学习路线,帮助你系统地掌握前端开发技能,并成为一名优秀的前端工程师。 HTML和CSS基础 在开始前端

    2024年02月08日
    浏览(40)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包