目录
大语言模型(LLM)核心介绍
1. 什么是大语言模型?
大语言模型(LLM) 是一种基于深度学习的自然语言处理(NLP)模型,它在海量文本数据上进行训练,能够理解、生成和处理人类语言。
核心特征
- 大:参数量巨大(通常数十亿甚至万亿级)
- 预训练:先在无标注数据上进行自监督学习(学习语言本身的结构和知识)
- 微调:针对特定任务进行有监督微调
- 生成能力:能够生成连贯、流畅的文本
2. 技术基础:Transformer架构
LLM大多基于Transformer架构(由Google在2017年提出),其核心是自注意力机制(Self-Attention),能够高效处理序列数据并捕获长距离依赖关系。
3. 发展历程中的关键模型
- GPT系列(OpenAI):GPT → GPT-2 → GPT-3 → GPT-4
- BERT(Google):双向编码器,擅长理解任务
- T5(Google):文本到文本的统一框架
- LLaMA(Meta):开源高效模型
- ChatGPT:基于GPT的对话优化版本
4. 两种主要模式
- 自回归模型(如GPT):单向,逐词生成,适合文本生成
- 自编码模型(如BERT):双向,看到整个输入,适合理解任务
5. 应用领域
- 智能对话系统(ChatGPT)
- 代码生成与补全(GitHub Copilot)
- 文本摘要与翻译
- 内容创作
- 知识问答
代码示例
使用使用本地运行的轻量级模型(ChatGLM3-6B)
from transformers import AutoTokenizer, AutoModel
import torch
class LocalChatGLM:
def __init__(self, model_path="THUDM/chatglm3-6b"):
"""初始化本地模型"""
print("正在加载本地模型...")
self.tokenizer = AutoTokenizer.from_pretrained(
model_path,
trust_remote_code=True,
revision="main" # 使用主分支
)
self.model = AutoModel.from_pretrained(
model_path,
trust_remote_code=True,
revision="main",
torch_dtype=torch.float16 # 使用半精度减少内存占用
).cuda() # 使用GPU
print("模型加载完成!")
def chat(self, prompt, history=[]):
"""与模型对话"""
response, updated_history = self.model.chat(
self.tokenizer,
prompt,
history=history,
temperature=0.7
)
return response, updated_history
# 使用示例
def local_model_example():
try:
# 使用较小的模型或本地下载的模型
chatglm = LocalChatGLM("THUDM/chatglm3-6b")
history = []
while True:
user_input = input("\n你: ")
if user_input.lower() in ['退出', 'exit', 'quit']:
break
response, history = chatglm.chat(user_input, history)
print(f"AI: {response}")
except Exception as e:
print(f"加载模型失败: {e}")
print("请尝试先下载模型到本地,或者使用API方案")
local_model_example()