【DW组队学】llm-algo-leetcode 05LLaMA3 Block 教程 + 00PyTorch 热身
这里写自定义目录标题纯粹的复健流程00. PyTorch 热身Part 1: 张量维度变换与 einopsPart 2: 嵌入层 (Embedding Layer) 的本质纯粹的复健流程很久没有摸过这些库现在重新拾起来有点困难。00. PyTorch 热身# 导入所有必需的库importtorchimporttorch.nnasnnimporttorch.nn.functionalasFimporteinopsPart 1: 张量维度变换与einopsdeftensor_warmup(x:torch.Tensor): 假设 x 是一批图像的特征 (例如在多模态大模型中)形状为 [batch_size, channels, height, width] 我们需要将其展平为序列 (Sequence)以输入给 Transformer。 目标形状: [batch_size, height * width, channels] # # TODO 1.1: 使用原生的 PyTorch 方法 (permute reshape/flatten) 完成变换# 提示: 先调整维度顺序再合并空间维度# # x_native ???x_nativex.permute(0,2,3,1)\.reshape(len(x),len(x[0][0][0])*len(x[0][0]),len(x[0]))[batch_size,channels,height,width]x.shape x_nativex.permute(0,2,3,1)\.reshape(batch_size,height*width,channels)# # TODO 1.2: 使用 einops.rearrange 优雅地完成完全相同的操作# 提示: 使用括号表示要合并的维度# # x_einops ???x_einopseinops.rearrange(x,b c h w - b (h w) c)returnx_native,x_einops# 来个单测看看tensor_atorch.randn(2,3,224,224)# print(tensor_a)print(tensor_a.shape)tensor_a_native,tensor_a_einopstensor_warmup(tensor_a)# print(tensor_a_native)print(tensor_a_native.shape)# print(tensor_a_einops)print(tensor_a_einops.shape)两个x_native的写法得到的结果都是一样的图片我就不贴两遍了但是显然可读性没有einops.rearrange()这种要好。Part 2: 嵌入层 (Embedding Layer) 的本质未完待续