Skip to content

工具生态

绝大多数 AI 研究基于 PyTorch。提供了灵活的自动微分和 GPU 加速。

import torch
import torch.nn as nn
# 定义一个简单的 MLP
class MLP(nn.Module):
def __init__(self):
super().__init__()
self.layers = nn.Sequential(
nn.Linear(768, 256),
nn.ReLU(),
nn.Dropout(0.1),
nn.Linear(256, 10),
)
def forward(self, x):
return self.layers(x)
model = MLP()
x = torch.randn(4, 768) # batch=4
output = model(x)
print(output.shape) # torch.Size([4, 10])

HuggingFace Transformers — 预训练模型库

Section titled “HuggingFace Transformers — 预训练模型库”
from transformers import AutoModelForCausalLM, AutoTokenizer
# 加载模型和分词器
model_name = "gpt2"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
# 生成文本
inputs = tokenizer("The future of AI is", return_tensors="pt")
outputs = model.generate(**inputs, max_new_tokens=30)
print(tokenizer.decode(outputs[0]))
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
llm = ChatOpenAI(model="gpt-4o", temperature=0.7)
prompt = ChatPromptTemplate.from_messages([
("system", "你是一个 AI 技术专家。"),
("human", "用一句话解释 {concept}"),
])
chain = prompt | llm
response = chain.invoke({"concept": "Transformer"})
print(response.content)
Terminal window
# 安装后下载模型
ollama pull llama3.2
# 命令行使用
ollama run llama3.2 "解释什么是注意力机制"
# Python 调用
pip install ollama
import ollama
response = ollama.chat(
model="llama3.2",
messages=[{"role": "user", "content": "什么是 Transformer?"}],
)
print(response["message"]["content"])
import chromadb
# 创建 Chroma 客户端
client = chromadb.Client()
collection = client.create_collection("docs")
# 添加文档
collection.add(
documents=["Transformer 是 Attention 机制的架构", "CNN 用于图像处理"],
ids=["doc1", "doc2"],
)
# 查询
results = collection.query(
query_texts=["什么是 Attention"],
n_results=1,
)
print(results["documents"][0]) # ['Transformer 是 Attention 机制的架构']
场景推荐工具
模型训练PyTorch + HuggingFace
快速原型Ollama + LangChain
生产部署vLLM / TGI
向量检索Chroma (原型) / Milvus (生产)
数据标注Label Studio
实验追踪Weights & Biases