支付宝可以给第三方网站做担保么/app001推广平台官网

支付宝可以给第三方网站做担保么,app001推广平台官网,wordpress调用百度地图吗,网站开发的背景尽管人们对越来越大的语言模型一直很感兴趣,但MistralAI 向我们表明,规模只是相对而言的,而对边缘计算日益增长的兴趣促使我们使用小型语言获得不错的结果。压缩技术提供了一种替代方法。在本文中,我将解释这些技术,并…

尽管人们对越来越大的语言模型一直很感兴趣,但MistralAI 向我们表明,规模只是相对而言的,而对边缘计算日益增长的兴趣促使我们使用小型语言获得不错的结果。压缩技术提供了一种替代方法。在本文中,我将解释这些技术,并提供一些简单的代码片段作为示例。

模型压缩是在不影响机器学习模型有效性的情况下最小化其大小的行为。由于大型神经网络经常因过度参数化而包含冗余计算单元,因此这种方法对它们非常有效。

压缩意味着减少参数数量或整体内存占用,从而减小模型大小(例如从 10 GB 到 9 GB)。此过程有助于提高模型在存储和推理速度方面的效率,使其更容易在资源有限的环境中部署。常见的模型压缩技术包括:

  1. 量化:通过改变模型权重的精度(例如从 32 位浮点数到 8 位整数)来减少内存占用。
  2. 修剪:删除不太重要的权重或神经元,减少参数的数量。
  3. 知识提炼:训练较小的模型(学生)来模仿较大模型(老师)的行为,将知识提炼为具有类似性能的压缩版本。
  4. 权重共享:通过设计或后期训练,在不同层之间使用共享权重来减少存储要求。

1. 模型量化

模型量化通过将权重或激活的精度表示(通常为 32 位或 16 位)转换为较低精度表示(例如 8 位、4 位甚至二进制)来压缩 LLM。我们可以量化权重、激活函数或使用其他技巧:

权重量化:神经网络使用的权重通常存储为 32 位或 16 位浮点数。量化将这些权重降低到较低的位宽,例如 8 位整数 (INT8) 或 4 位整数 (INT4)。这是通过将原始权重范围映射到具有较少位的较小范围来实现的,从而显著减少内存使用量。

激活量化:与权重类似,激活(推理期间的层输出)可以量化为较低的精度。通过用更少的位表示激活,模型在推理期间的内存占用量会减少。

量化感知训练 (QAT):在 QAT 中,模型在模拟量化的同时进行训练,使其能够适应较低的精度。这有助于保持准确性,因为模型学会了对量化效应更加稳健(查看Tailor 等人的Arxiv)。

训练后量化 (PTQ):此方法涉及以全精度正常训练模型,然后应用量化。虽然 PTQ 更简单、更快速,但与 QAT 相比,它可能会导致准确率大幅下降(如Wang 等人在 NIPS2021中所述)。

使用 bitsandbytes 可以非常轻松地实现权重量化。安装库:

pip install torch transformers bitsandbytes

例如,对于 GPT2,运行代码:


from transformers import AutoModelForCausalLM, AutoTokenizer
import torch# Specify the model you want to use
model_name = "gpt2"  # You can replace this with any other LLM model
# Load the tokenizer
tokenizer = AutoTokenizer.from_pretrained(model_name)
# Load the model with 8-bit quantization using bitsandbytes
model = AutoModelForCausalLM.from_pretrained(model_name,load_in_8bit=True,  # Enable 8-bit quantizationdevice_map="auto"   # Automatically allocate to available device (CPU/GPU)
)
# Example text for inference
input_text = "Weight Quantization is an efficient technique for compressing language models."
input_ids = tokenizer(input_text, return_tensors="pt").input_ids.to("cuda")
# Generate text
with torch.no_grad():output_ids = model.generate(input_ids, max_length=50)
# Decode and print the generated text
output_text = tokenizer.decode(output_ids[0], skip_special_tokens=True)
print(output_text)

2. 修剪

修剪会移除不必要或不太重要的权重、神经元或整个层,就像从树上移除不必要的树枝一样。这可以减小模型的大小、加快推理速度并降低内存和计算要求,使其更高效,同时尽可能保持原始性能。

这不像量化那么简单,因为我们首先需要找到冗余的东西。例如,我们需要找到冗余参数,然后在没有这些参数的情况下对模型进行微调。

最常见的情况是,我们会移除权重、神经元或层,但人们对注意力头修剪(特定于基于 Transformer 的模型)的兴趣日益浓厚,将其作为一种结构化修剪形式(查看Wang 等人的Arxiv)。在这里,每个注意力层都有多个头。有些头对模型性能的贡献比其他头更大,因此注意力头修剪会移除不太重要的头。

修剪的示例代码如下,我们从 GPT2 模型中删除一定比例的权重:


import torch
import torch.nn.utils.prune as prune
from transformers import AutoModelForCausalLM, AutoTokenizer# Load the pretrained model and tokenizer
model_name = "gpt2"  # You can replace this with any other LLM model
model = AutoModelForCausalLM.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
# Define a pruning method (here we use L1 unstructured pruning)
def prune_model_layer(layer, amount=0.3):# Prune 30% of the weights with the lowest L1 norm in the linear layersfor name, module in layer.named_modules():if isinstance(module, torch.nn.Linear):prune.l1_unstructured(module, name="weight", amount=amount)print(f"Pruned layer {name} with amount {amount}")
# Apply pruning to all transformer layers in the model
for layer in model.transformer.h:prune_model_layer(layer, amount=0.3)  # Prune 30% of the weights
# Check the sparsity of the model
total_params = 0
pruned_params = 0
for name, module in model.named_modules():if isinstance(module, torch.nn.Linear):total_params += module.weight.nelement()pruned_params += torch.sum(module.weight == 0).item()
print(f"Total parameters: {total_params}")
print(f"Pruned parameters: {pruned_params}")
print(f"Sparsity: {pruned_params / total_params:.2%}")
# Test the pruned model on a sample input
input_text = "Pruning is an effective way to compress language models."
input_ids = tokenizer(input_text, return_tensors="pt").input_ids
# Generate text using the pruned model
with torch.no_grad():output_ids = model.generate(input_ids, max_length=50)
# Decode and print the generated text
output_text = tokenizer.decode(output_ids[0], skip_special_tokens=True)
print(output_text)

3. 模型蒸馏

模型蒸馏是一种将“知识”从一个大型、更复杂的模型(称为教师模型)转移到一个较小、更简单的模型(称为学生模型)的技术,该模型可能具有较少的参数。这一过程使学生模型能够达到接近教师模型的性能,同时在规模或速度上效率更高,正如我们在开始时承诺的那样。

该过程从大型、预先训练的 LLM 开始,作为教师模型,例如 GPT2 或 LLama。该模型通常非常准确,但需要大量计算资源进行推理。

训练一个更小、更高效的模型(“学生模型”)来模仿教师模型的行为,例如 miniGPT2 或 TinyLlama(尽管 Tinyllama 的构建方式不同)。学生模型从原始训练数据和教师模型生成的输出(软标签)中学习。

以下是从老师GPT2开始的Python师生互动示例:


import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from datasets import load_dataset
import torch.nn.functional as F# Load the teacher (large) and student (smaller) models
teacher_model_name = "gpt2"  # You can replace this with any large LLM
student_model_name = "tiny-gpt2"  # A smaller variant to act as the student
# Load the teacher model and tokenizer
teacher_model = AutoModelForCausalLM.from_pretrained(teacher_model_name).to("cuda")
teacher_tokenizer = AutoTokenizer.from_pretrained(teacher_model_name)
# Load the student model and tokenizer
student_model = AutoModelForCausalLM.from_pretrained(student_model_name).to("cuda")
student_tokenizer = AutoTokenizer.from_pretrained(student_model_name)
# Load a dataset for training (e.g., Wikitext for language modeling)
dataset = load_dataset("wikitext", "wikitext-2-raw-v1", split="train")
# Set training parameters
learning_rate = 5e-5
epochs = 3
optimizer = torch.optim.AdamW(student_model.parameters(), lr=learning_rate)
# Set temperature for softening probabilities
temperature = 2.0
alpha = 0.5  # Weighting factor for combining loss functions
# Training loop for knowledge distillation
for epoch in range(epochs):for i, example in enumerate(dataset):# Get the input textinput_text = example["text"]# Skip empty linesif not input_text.strip():continue# Tokenize the input text for the teacher and student modelsteacher_inputs = teacher_tokenizer(input_text, return_tensors="pt", truncation=True, padding="max_length", max_length=32).to("cuda")student_inputs = student_tokenizer(input_text, return_tensors="pt", truncation=True, padding="max_length", max_length=32).to("cuda")# Get teacher predictions (soft labels)with torch.no_grad():teacher_outputs = teacher_model(**teacher_inputs)teacher_logits = teacher_outputs.logits / temperatureteacher_probs = F.softmax(teacher_logits, dim=-1)# Get student predictionsstudent_outputs = student_model(**student_inputs)student_logits = student_outputs.logits# Calculate distillation loss (Kullback-Leibler divergence)distillation_loss = F.kl_div(input=F.log_softmax(student_logits / temperature, dim=-1),target=teacher_probs,reduction="batchmean",log_target=False) * (temperature ** 2)# Calculate student task loss (Cross-Entropy with true labels)target_labels = student_inputs["input_ids"]task_loss = F.cross_entropy(student_logits.view(-1, student_logits.size(-1)), target_labels.view(-1), ignore_index=student_tokenizer.pad_token_id)# Combined lossloss = alpha * distillation_loss + (1 - alpha) * task_loss# Backpropagation and optimizationoptimizer.zero_grad()loss.backward()optimizer.step()# Print training progressif i % 100 == 0:print(f"Epoch [{epoch + 1}/{epochs}], Step [{i}], Loss: {loss.item():.4f}")
print("Knowledge distillation completed!")

4. 权重共享

通过在多个模型组件之间共享参数,我们可以减少神经网络的内存占用。当部分或所有层共享同一组权重而不是每个层或组件都有唯一的权重时,模型必须保留的参数数量会大大减少。可以先验地定义模型的架构,事先使用共享权重,或者在训练后将权重共享作为模型压缩技术。例如,一种可能性是将权重聚类,如下面的代码所示:


import torch
import numpy as np
from sklearn.cluster import KMeansdef apply_weight_sharing(model, num_clusters=16):# Iterate through each parameter in the modelfor name, param in model.named_parameters():if param.requires_grad:  # Only consider trainable parameters# Flatten the weights into a 1D array for clusteringweights = param.data.cpu().numpy().flatten().reshape(-1, 1)# Apply k-means clusteringkmeans = KMeans(n_clusters=num_clusters)kmeans.fit(weights)# Replace weights with their corresponding cluster centroidscluster_centroids = kmeans.cluster_centers_labels = kmeans.labels_# Map the original weights to their shared valuesshared_weights = np.array([cluster_centroids[label] for label in labels]).reshape(param.data.shape)# Update the model's parameters with the shared weightsparam.data = torch.tensor(shared_weights, dtype=param.data.dtype).to(param.device)return model
# Example usage with a pre-trained model
from transformers import GPT2LMHeadModel
model = GPT2LMHeadModel.from_pretrained("gpt2")
model = apply_weight_sharing(model, num_clusters=16)  # Apply weight sharing with 16 clusters
print("Weight sharing applied to the model!")

在本文中,我介绍了一些减少现有语言模型占用空间的技术。这显然不是一个过于全面的列表,因为每天都有许多方法在改进,但它应该能给你一些额外的技能。使用小语言模型来减少信息占用空间的替代方法仍然存在。

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

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

相关文章

大华HTTP协议在智联视频超融合平台中的接入方法

一. 大华HTTP协议介绍 大华HTTP协议是大华股份(Dahua Technology)为其安防监控设备开发的一套基于HTTP/HTTPS的通信协议,主要用于设备与客户端(如PC、手机、服务器)之间的数据交互。该协议支持设备管理、视频流获取、…

7、vue3做了什么

大佬认为有何优点: 组合式api----逻辑集中、对ts有更好的支持RFC–开放了一个讨论机制,可以看到每一个api的提案,方便源码维护,功能扩展,大家一起讨论 官方rfc响应式独立,new Proxy,天生自带来…

多人在线聊天系统,创建群,视频,语音,自带带授权码

多人在线聊天系统,创建群,视频,语音 带授权码,授权码限制 10 个网站,需要下载研究吧 在线聊天,创建群,表情,图片,文件,视频,语音,自…

NFC 碰一碰发视频源码搭建,支持OEM

一、引言 NFC(Near Field Communication)近场通信技术,以其便捷、快速的数据交互特性,正广泛应用于各个领域。其中,NFC 碰一碰发视频这一应用场景,为用户带来了新颖且高效的视频分享体验。想象一下&#x…

C++从入门到入土(八)——多态的原理

目录 前言 多态的原理 动态绑定与静态绑定 虚函数表 小结 前言 在前面的文章中,我们介绍了C三大特性之一的多态,我们主要介绍了多态的构成条件,但是对于多态的原理我们探讨的是不够深入的,下面这这一篇文章,我们将…

Linux目录理解

前言 最近在复习linux,发现有些目录总是忘记内容,发现有些还是得从原义和实际例子去理解会记忆深刻些。以下是个人的一些理解 Linux目录 常见的Linux下的目录如下: 1. 根目录 / (Root Directory) 英文含义:/ 是文件系统的根…

c++领域展开第十七幕——STL(vector容器的模拟实现以及迭代器失效问题)超详细!!!!

文章目录 前言vector——基本模型vector——迭代器模拟实现vector——容量函数以及push_back、pop_backvector——默认成员函数vector——运算符重载vector——插入和删除函数vector——实现过程的问题迭代器失效memcpy的浅拷贝问题 总结 前言 上篇博客我们已经详细介绍了vecto…

植物知识分享论坛毕设

1.这四个文件直接是什么关系?各自都是什么作用?他们之间是如何联系的? 关系与联系 UserController.java 负责接收外部请求,调用 UserService.java 里的方法来处理业务, 而 UserService.java 又会调用 UserMapper.jav…

Business processes A bridge to SAP and a guide to SAP TS410 certification

Business processes A bridge to SAP and a guide to SAP TS410 certification

算法 之 ST表

文章目录 区间最大值 ST表(Sparse Table)是一种高效处理静态数据区间查询的数据结构,主要的作用是用于快速查询区间的最值,区间GCD,区间按位与或 在这里以区间最大值为例子说明st表的模版 总体的思想就是定义dp[i][j]表示下标为i长度为2^j的区间的最大值…

Deepseek X 文心智能体:谐音梗广告创意大师

体验链接 飞书文档 一、引言 在当今竞争激烈的市场环境下,广告创意对于产品或服务的推广至关重要。谐音广告以其独特的语言魅力,能够迅速吸引受众的注意力并留下深刻印象。本智能体旨在利用 DeepSeek 模型强大的语言分析和推理能力,为用户…

TCP简单链接的编程实现

TCP简单链接的编程实现 本文主要介绍TCP应用层的编码实现。 TCP是一种面向连接的、可靠的、基于字节流的传输层协议,它是互联网协议套件(TCP/IP)中的核心协议之一,广泛应用于需要可靠数据传输的场景,如:网…

【RHCE实验】搭建主从DNS、WEB等服务器

目录 需求 环境搭建 配置nfs服务器 配置web服务器 配置主从dns服务器 主dns服务器 从dns服务器 配置客户端 客户端测试 需求 客户端通过访问 www.nihao.com 后,能够通过 dns 域名解析,访问到 nginx 服务中由 nfs 共享的首页文件,内容…

【HarmonyOS Next之旅】DevEco Studio使用指南(三)

目录 1 -> 一体化工程迁移 1.1 -> 自动迁移 1.2 -> 手动迁移 1.2.1 -> API 10及以上历史工程迁移 1.2.2 -> API 9历史工程迁移 1 -> 一体化工程迁移 DevEco Studio从 NEXT Developer Beta1版本开始,提供开箱即用的开发体验,将SD…

nodejs使用 mysql2 模块获取 mysql 中的 json字段,而不是 mysql

mysql 模块获取的 json 字段,是字符串mysql2 模块获取的 json 字段,是符合预期的 json 对象 mysql mysql2 最后编辑于:2025-02-24 22:16:53 © 著作权归作者所有,转载或内容合作请联系作者 喜欢的朋友记得点赞、收藏、关注哦!…

【网工第6版】第1章 计算机网络概论

目录 1计算机网络形成和发展 ■计算机网络 ■我国互联网发展 ■计算机网路分类 ■计算机网络应用 2 OSI和TCP/IP参考模型 ■网络分层的意义 ■OSI参考模型 ■TCP/IP参考模型 ■TCP/IP参考模型协议 3 数据封装与解封过程 ■封装 ■解封 1计算机网络形成和发展 ■计…

理解我们单片机拥有的资源

目录 为什么要查询单片机拥有的资源 所以,去哪些地方可以找数据手册 一个例子:STM32F103C8T6 前言 本文章隶属于项目: Charliechen114514/BetterATK: This is a repo that helps rewrite STM32 Common Repositorieshttps://github.com/C…

《我的Python觉醒之路》之转型Python(十五)——控制流

[今天是2025年3月17日,继续复习第一章节、第二章节的内容 ] 《我的Python觉醒之路》之转型Python(十四)——控制流

AndroidStudio+Android8.0下的Launcher3 导入,编译,烧录,调试

文章目录 编译完成搜索输出文件Android.mk配置gradle编译环境报错一报错二报错三输出文件下载INSTALL_FAILED_TEST_ONLY查找系统签名查找签名工具开始签名查看签名签名问题重新生成秘钥解决方案生成成功挽救错误:重新刷机更换testkey秘钥keystore生成keystoreINSTALL_FAILED_S…

Linux--gdb/cgdb

ok,我们今天学习gdb的安装和使用 调试器-gdb/cgdb使用 VS、VScode编写的代码一般都是release格式的,gdb 的格式一般是debug 换成debug模式命令 :-g gdb会记录最新的一条命令,直接回车就是默认执行该命令 一个调试周期下,断点…