学习资料
InfiniTensor冬季训练营编程基础课第六课《PyTorch入门》
发表于:

PyTorch入门课程封面

2026年1月9日,2025冬季 InfiniTensor 大模型与人工智能系统训练营编程基础课第六课《PyTorch入门》正式开讲。

本课程将带领大家从零开始掌握 PyTorch 这一深度学习框架的核心概念,为后续的大模型开发与训练打下坚实基础。

为什么选择PyTorch?

PyTorch 是由 Meta(原 Facebook)开发的开源深度学习框架,具有以下显著优势:

  • 动态计算图机制:更灵活的模型构建与调试体验
  • 简洁的Python接口:与Python生态无缝集成
  • 强大的自动求导系统:简化梯度计算与反向传播
  • 活跃的社区与丰富的生态系统:包括torchvision、torchtext、torchaudio等

目前,PyTorch已成为工业界最主流的深度学习平台之一,也是大模型开发与训练的首选框架。

课程内容概览

1. PyTorch核心概念:Tensor

Tensor 是 PyTorch 中最重要的数据结构,它统一表示标量、向量、矩阵和高维数组。

Tensor的构造方式

import torch

# 1. 直接构造
data = [[1, 2], [3, 4]]
x_data = torch.tensor(data)

# 2. 来自NumPy数组
import numpy as np
np_array = np.array(data)
x_np = torch.from_numpy(np_array)

# 3. 基于其他Tensor,从而保留其他 Tensor 的部分属性
z = torch.ones_like(x)  # 创建与x相同形状的全1 Tensor

# 4. 随机初始化
shape = (2, 3,)
rand_tensor = torch.rand(shape)  # 随机Tensor

Tensor的基本属性

# 获取Tensor的基本属性
print("Shape:", x.shape)       # (2, 3)
print("Data type:", x.dtype)   # torch.int64
print("Device:", x.device)     # cpu
# 将 Tensor 转移到计算设备上
if torch.cuda.is_available():
    x = x.to('cuda')
elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
    # For Mac Users
    x = x.to('mps')

print(f"Device tensor is stored on: {x.device}")

Tensor的计算操作

# 逐元素计算
a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5, 6])
c = a + b  # [5, 7, 9]

# 广播机制
a = torch.randn(3, 4, 5)  # 3x4x5
b = torch.randn(4, 5)     # 4x5
c = a + b                 # 自动广播为3x4x5

# 变换操作
x = torch.randn(2, 3, 4)
print(x.view(2, 1, 3, 4).shape)  # (2, 1, 3, 4)
print(x.reshape(6, 4).shape)     # (6, 4)
print(x.permute(1, 0, 2).shape)  # (3, 2, 4)
print(x.transpose(1, 2).shape)   # (2, 4, 3)
print(x.unsqueeze(-1).shape)     # (2, 3, 4, 1)
print(x.view(2, 1, 3, 4).squeeze().shape)   # (2, 3, 4)

# 对于转置,可以简单地使用 x.T 进行维度的从高到低的反转
print(x.T.shape)   # (4, 3, 2)

# 矩阵乘法
a = torch.randn(2, 3)
b = torch.randn(3, 4)
c = a @ b                 # 2x4 矩阵乘法

2. 神经网络构建:nn.Module

在PyTorch中,所有神经网络结构都是torch.nn.Module的子类。

自定义线性层示例

import torch.nn as nn

class MyLinear(nn.Module):
    def __init__(self, in_features, out_features):
        super().__init__()

        # 权重矩阵 W: (out_features, in_features)
        self.weight = torch.randn(out_features, in_features)

        # 偏置 b: (out_features,)
        self.bias = torch.randn(out_features)

    def forward(self, x):
        # 定义其计算流程,x 为输入 Tensor,返回值为输出 Tensor
        # x: (N, in_features)
        # x @ W^T -> (N, out_features)
        return x @ self.weight.t() + self.bias

# 调用实现的 MyLinear Module
linear = MyLinear(in_features=3, out_features=2)

x = torch.randn(4, 3)   # 4 条数据,每条 3 个特征

# 直接调用 linear(input),等同于调用 linear.forward(input)
y = linear(x)

print("input shape:", x.shape)  # (4, 3)
print("output shape:", y.shape) # (4, 2)
print(y)

使用内置模块构建MLP

# 简单的多层感知机实现
class SimpleMLP(nn.Module):
    def __init__(self, input_dim, hidden_dim, output_dim):
        super().__init__()
        # nn.Linear 的参数使用 Kaiming Uniform
        self.fc1 = nn.Linear(input_dim, hidden_dim)
        self.act = nn.ReLU()
        self.fc2 = nn.Linear(hidden_dim, output_dim)

    def forward(self, x):
        x = self.fc1(x)
        x = self.act(x)
        x = self.fc2(x)
        return x

model = SimpleMLP(5, 10, 3)
input = torch.rand((4, 5))

# 直接调用 model(input),等同于调用 model.forward(input)
output = model(input)
output # shape: (4, 3)

# 使用Sequential简化
model = nn.Sequential(
    nn.Linear(5, 10),
    nn.ReLU(),
    nn.Linear(10, 3)
)

input = torch.rand((4, 5))
output = model(input)
output # shape: (4, 3)

3. 数据处理:Dataset与DataLoader

PyTorch提供了torch.utils.data.Datasettorch.utils.data.DataLoader来处理数据。

自定义Dataset

from torch.utils.data import Dataset

# 一个能够实现所指定 transform 方法的自定义 Dataset
class MyTransformedDataset(Dataset):
    def __init__(self, data, labels, transform=None):
        self.data = data            # 通常为 torch.Tensor 或 numpy.ndarray
        self.labels = labels
        self.transform = transform  # 可以传入任何函数或预定义的 torchvision.transforms 组合

    def __len__(self):
        return len(self.data)

    def __getitem__(self, idx):
        x = self.data[idx]
        y = self.labels[idx]

        # 在此应用 transform(如归一化、随机旋转等)
        if self.transform:
            x = self.transform(x)

        # 可以返回任意 Python 基本类型,如包含两个数据的 tuple
        return x, y

# 定义一个变换流程(示例:归一化)
my_transform = lambda x: (x - x.mean()) / x.std()

# 构造伪数据
X = torch.randn(1000, 10)
y = torch.randint(0, 2, (1000,))

dataset = MyTransformedDataset(X, y, transform=my_transform)

使用DataLoader

from torch.utils.data import DataLoader

# 紧接着上述自定义 dataset 示例
loader = DataLoader(dataset, batch_size=32, shuffle=True)

# 模拟训练循环中使用 DataLoader
for batch_idx, (batch_x, batch_y) in enumerate(loader):
    # 打印每个 batch 的基本信息
    print(f"Batch {batch_idx}:")
    print("  X shape:", batch_x.shape)
    print("  y shape:", batch_y.shape)
    print("  X sample:", batch_x[0])
    print("  y sample:", batch_y[0])

    # 这里可以插入模型 forward / loss / backward / optimizer 等逻辑
    # output = model(batch_x)
    # loss = criterion(output, batch_y)
    # ...

    if batch_idx >= 2:
        break  # 这里只演示前几个 batch,避免输出过长

4. HuggingFace Transformers:开箱即用的NLP工具

HuggingFace Transformers库提供了多种预训练模型和开箱即用的API。

推理示例

import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification

# 情感分析任务示例
checkpoint = "distilbert-base-uncased-finetuned-sst-2-english"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = AutoModelForSequenceClassification.from_pretrained(checkpoint).cuda()
model.eval()

texts = [
    "This library is extremely useful.",
    "This is a terrible user experience."
]

inputs = tokenizer(texts, padding=True, truncation=True, return_tensors="pt")
inputs = {k: v.cuda() for k, v in inputs.items()}

with torch.no_grad():
    outputs = model(**inputs)

# logits: (batch, num_labels)
logits = outputs.logits
probs = torch.softmax(logits, dim=-1)

# 概率输出
print(logits.shape, probs)

# 把概率映射回标签名
id2label = model.config.id2label
pred_ids = probs.argmax(dim=-1).tolist()
preds = [(texts[i], id2label[pred_ids[i]], float(probs[i, pred_ids[i]].cpu())) for i in range(len(texts))]
preds

使用预训练模型进行文本生成


from transformers import AutoTokenizer, AutoModelForCausalLM

# 文本生成任务示例
checkpoint = "Qwen/Qwen3-0.6B"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = AutoModelForCausalLM.from_pretrained(checkpoint).cuda()
model.eval()

prompt = "讲一个故事:"
inputs = tokenizer(prompt, return_tensors="pt")
inputs = {k: v.cuda() for k, v in inputs.items()}

with torch.no_grad():
    generated = model.generate(
        **inputs,
        max_new_tokens=60,
        do_sample=True,
        temperature=0.9,
        top_p=0.95
    )

text_out = tokenizer.decode(generated[0], skip_special_tokens=True)
text_out

课程收获

通过本课程,你将能够:

  1. 理解PyTorch的核心概念与数据结构
  2. 掌握Tensor的基本操作与计算
  3. 构建自定义神经网络模型
  4. 使用Dataset和DataLoader进行数据处理
  5. 调用预训练模型进行快速推理
  6. 为后续的大模型开发与训练打下坚实基础

课程预告

后续课程将深入讲解大模型训练、推理与优化技术,包括分布式训练、推理性能调优等主题课程。

InfiniTensor大模型与人工智能系统训练营,助你从基础到前沿,掌握大模型相关核心技能!

💡 学习贴士

更多细节及完整课程内容,请观看直播或查看课程回放。

链接:https://www.infinitensor.com/camp/winter2025

📚 训练营报名持续进行中

扫码报名与加入群聊,或点击 「阅读原文」 直达官网报名