PyTorch指南:17个技巧让你的深度学习模型训练变得飞快!

Accelerate分布式训练实战:零修改迁移单卡PyTorch模型 分布式训练是深度学习工程化的核心能力,其本质是通过多设备协同提升模型训练效率与规模上限。原理上依赖数据并行、梯度同步与混合精度等关键技术,技术价值在于降低显存压力、加速收敛、支撑大模型落地。典型应用场景包括多卡GPU训练、跨机集群微调、生产环境CI/CD集成及Hugging Face生态适配。本文聚焦PyTorch原生分布式封装工具Accelerate,围绕‘零代码侵入’和‘自动设备管理’两大热词,详解如何不改训练循环即可实现单卡→多卡→多机的平滑演进,覆盖初始化配置、prepare机制、backward替 阅读详情

                                                                            Fly-AI竞赛服务平台 flyai.com

在开始学习之前推荐大家可以多在  FlyAI竞赛服务平台多参加训练和竞赛,以此来提升自己的能力。FlyAI是为AI开发者提供数据竞赛并支持GPU离线训练的一站式服务平台。每周免费提供项目开源算法样例,支持算法能力变现以及快速的迭代算法模型。

 关注“FlyAI社区”公众号【后台回复“Pytorch”,即可获取原文链接】

英文原文:Faster Deep Learning Training with PyTorch – a 2021 Guide

标签:深度学习

Say, you're training a deep learning model in PyTorch. What can you do to make your training finish faster?

假设你正在使用pytorch训练深度学习模型,那么如何能够加快模型训练速度呢?

In this post, I'll provide an overview of some of the lowest-effort, highest-impact ways of accelerating the training of deep learning models in PyTorch. For each of the methods, I'll briefly summarize the idea, try to estimate the expected speed-up and discuss some limitations. I will focus on conveying the most important parts and point to further resources for each of them. Mostly, I'll focus on changes that can be made directly within PyTorch without introducing additional libraries and I'll assume that you are training your model on GPU(s).

在本文中,我会介绍一些高效的pytorch深度学习模型加速方法。对于某种方法,我会对其思路进行简要介绍,然后给出其提升速度并讨论其限制。我会把我认为重要的部分着重介绍,并在每个部分展示一些实例。接下来我假设你使用GPU训练模型,这些方法基本不需要导入其他库,只需要pytorch内进行更改即可。

The suggestions – roughly sorted from largest to smallest expected speed-up – are:

以下是我根据大概的加速效果对不同策略的排序:

Consider using a different learning rate schedule.

调整不同的学习率;

Use multiple workers and pinned memory in DataLoader.

在DataLoader中使用多个工作者和钉住内存。

Max out the batch size.

最大化批处理大小;

Use Automatic Mixed Precision (AMP).

使用自动混合精度AMP;

Consider using a different optimizer.

考虑不同的优化器;

Turn on cudNN benchmarking.

打开cuDNN基准;

Beware of frequently transferring data between CPUs and GPUs.

当心CPU与GPU频繁的数据转换;

Use gradient/activation checkpointing.

使用梯度/激活检查点;

Use gradient accumulation.

梯度累积;

Use DistributedDataParallel for multi-GPU training.

通过DistributedDataParallel进行多GPU训练;

Set gradients to None rather than 0.

将梯度设置为None而不是0;

Use .as_tensor rather than .tensor()

使用.as_tensor而不是.tensor;

Turn off debugging APIs if not needed.

如无必要,关闭调试API;

Use gradient clipping.

梯度裁剪;

Turn off bias before BatchNorm.

BatchNorm之前关闭偏差;

Turn off gradient computation during validation.

验证过程中关闭梯度计算;

Use input and batch normalization.

规范化输入和批处理。

1. Consider using another learning rate schedule

The learning rate (schedule) you choose has a large impact on the speed of convergence as well as the generalization performance of your model.

在训练中使用的学习速率调整计划会极大影响收敛速率以及模型泛化能力.

Cyclical Learning Rates and the 1Cycle learning rate schedule are both methods introduced by Leslie N. Smith (here and here), and then popularised by fast.ai's Jeremy Howard and Sylvain Gugger (here and here). Essentially, the 1Cycle learning rate schedule looks something like this:

Leslie N. Smith 提出了周期学习速率和1-周期学习速率计划,然后被fast.ai 的 Jeremy Howard 和 Sylvain Gugger 推广了.总的来说, 1-周期学习速率计划中,学习速率的变化如下图所示:

图片

Sylvain writes:

[1cycle consists of] two steps of equal lengths, one going from a lower learning rate to a higher one than go back to the minimum. The maximum should be the value picked with the Learning Rate Finder, and the lower one can be ten times lower. Then, the length of this cycle should be slightly less than the total number of epochs, and, in the last part of training, we should allow the learning rate to decrease more than the minimum, by several orders of magnitude.

[1个周期由]两个长度相等的步骤组成,一个是从较低的学习率到较高的学习率,然后再回到最小值。最大值应该是用学习率查找器选取的值,较低的可以低十倍。然后,这个循环的长度应该略小于总的纪元数,而且,在训练的最后一部分,我们应该让学习率比最小值降低几个数量级。

In the best case this schedule achieves a massive speed-up – what Smith calls Superconvergence – as compared to conventional learning rate schedules. Using the 1Cycle policy he needs ~10x fewer training iterations of a ResNet-56 on ImageNet to match the performance of the original paper, for instance). The schedule seems to perform robustly well across common architectures and optimizers.

在最好的情况下,与传统的学习率策略相比,上述方法有望实现了巨大加速(Smith称之为超收敛)。例如,ResNet-56通过使用1周期策略,在ImageNet上将减少约10倍的训练迭代,与原论文性能相当。在常见的结构和优化器中,上述时间策略表现更好。

PyTorch implements both of these methods torch.optim.lr_scheduler.CyclicLR and torch.optim.lr_scheduler.OneCycleLR, see the documentation.

PyTorch提供了torch.optim.lr_scheduler.CyclicLR和torch.optim.lr_scheduler.OneCycleLR两种方法实现该操作,请参阅相关文档。

One drawback of these schedulers is that they introduce a number of additional hyperparameters. This post and this repo, offer a nice overview and implementation of how good hyper-parameters can be found including the Learning Rate Finder mentioned above.

这些调度器的一个缺点是引入了许多额外的超参数。这篇文章和仓库对如何查找好的超参数(包括上文提及的学习率)提供了详细概述和实现。

Why does this work? It doesn't seem entirely clear but one possible explanation might be that regularly increasing the learning rate helps to traverse saddle points in the loss landscape more quickly.

至于为什么要这样做?现今并不完全清楚,但一个可能的解释是:定期提高学习率有助于更快越过损失鞍点。

2. Use multiple workers and pinned memory in DataLoader

When using torch.utils.data.DataLoader, set num_workers > 0, rather than the default value of 0, and pin_memory=True, rather than the default value of False. Details of this are explained here.

在使用 torch.utils.data.DataLoader时,令 num_workers > 0,而不是默认值 0,同时设置 pin_memory=True,而不是默认值 False。至于为什么这么做,这篇文章会给你答案。

Szymon Micacz achieves a 2x speed-up for a single training epoch by using four workers and pinned memory.

根据上述方法,Szymon Micacz 在四个 worker 和页锁定内存的情况下,在单个epoch中实现了 2 倍加速。

A rule of thumb that people are using to choose the number of workers is to set it to four times the number of available GPUs with both a larger and smaller number of workers leading to a slow down.Note that increasing num_workers will increase your CPU memory consumption.

根据经验,一般将进程数量设置为可用 GPU 数量的四倍,大于或小于这个值都会降低训练速度。但是要注意,增加num_workers会增加 CPU 内存消耗。

3. Max out the batch size

This is a somewhat contentious point. Generally, however, it seems like using the largest batch size your GPU memory permits will accelerate your training (see NVIDIA's Szymon Migacz, for instance). Note that you will also have to adjust other hyperparameters, such as the learning rate, if you modify the batch size. A rule of thumb here is to double the learning rate as you double the batch size.

一直以来,人们对于调大batch没有定论。一般来说,在GPU内存允许的情况下增大batch将会增快训练速度,但同时还需要调整学习率等其他超参数。根据经验,batch大小加倍时,学习率也相应加倍。

OpenAI has a nice empirical paper on the number of convergence steps needed for different batch sizes. Daniel Huynh runs some experiments with different batch sizes (also using the 1Cycle policy discussed above) where he achieves a 4x speed-up by going from batch size 64 to 512.

OpenAI 的论文表明不同的batch大小收敛周期不同。Daniel Huynh用不同的batch大小进行了一些实验(使用上述1Cycle 策略),实验中他将 batch大小由64增加到512,实现了4倍加速。

One of the downsides of using large batch sizes, however, is that they might lead to solutions that generalize worse than those trained with smaller batches.

然而也要注意,较大的batch会降低模型泛化能力,反之亦然。

4. Use Automatic Mixed Precision (AMP)

The release of PyTorch 1.6 included a native implementation of Automatic Mixed Precision training to PyTorch. The main idea here is that certain operations can be run faster and without a loss of accuracy at semi-precision (FP16) rather than in the single-precision (FP32) used elsewhere. AMP, then, automatically decide which operation should be executed in which format. This allows both for faster training and a smaller memory footprint.

PyTorch1.6支持本地自动混合精度训练。与单精度 (FP32) 相比,一些运算在不损失准确率的情况下,使用半精度 (FP16)速度更快。AMP能够自动决定应该以哪种精度执行哪种运算,这样既可以加快训练速度,又减少了内存占用。

In the best case, the usage of AMP would look something like this:

AMP的使用如下所示:

import torch# Creates once at the beginning of trainingscaler = torch.cuda.amp.GradScaler()for data, label in data_iter:
   optimizer.zero_grad()
   # Casts operations to mixed precision
   with torch.cuda.amp.autocast():
      loss = model(data)

   # Scales the loss, and calls backward()
   # to create scaled gradients
   scaler.scale(loss).backward()

   # Unscales gradients and calls
   # or skips optimizer.step()
   scaler.step(optimizer)

   # Updates the scale for next iteration
   scaler.update()

Benchmarking a number of common language and vision models on NVIDIA V100 GPUs, Huang and colleagues find that using AMP over regular FP32 training yields roughly 2x – but upto 5.5x – training speed-ups.

Huang及其同事在NVIDIA V100 GPU上对一些常用语言和视觉模型进行了基准测试,发现在FP32训练中使用AMP提高约2倍的训练速度,最高甚至达到5.5倍。

Currently, only CUDA ops can be autocast in this way. See the documentation here for more details on this and other limitations.

目前,只有CUDA支持上述方式,查看本文档了解更多信息。

5. Consider using another optimizer

AdamW is Adam with weight decay (rather than L2-regularization) which was popularized by fast.ai and is now available natively in PyTorch as torch.optim.AdamW. AdamW seems to consistently outperform Adam in terms of both the error achieved and the training time. See this excellent blog post on why using weight decay instead of L2-regularization makes a difference for Adam.

AdamW是由fast.ai提出的具有权重衰减(而非 L2 正则化)的Adam, PyTorch中通过torch.optim.AdamW实现。在误差和训练时间上,AdamW都优于Adam。查看此文章了解为什么权重衰减使得Adam产生更好效果。

Both Adam and AdamW work well with the 1Cycle policy described above.

Adam和AdamW都很适合前文提到的1Cycle策略。

There are also a few not-yet-native optimizers that have received a lot of attention recently, most notably LARS (pip installable implementation) and LAMB.

此外,LARS和LAMB等其他优化器也受到广泛关注。

NVIDA's APEX implements fused versions of a number of common optimizers such as Adam. This implementation avoid a number of passes to and from GPU memory as compared to the PyTorch implementation of Adam, yielding speed-ups in the range of 5%.

NVIDA的APEX对Adam等常见优化器进行优化融合,相比PyTorch中的原始Adam,由于避免了GPU内存之间的多次传递,训练速度提升约 5%。

6. Turn on cudNN benchmarking

If your model architecture remains fixed and your input size stays constant, setting torch.backends.cudnn.benchmark = True might be beneficial (docs). This enables the cudNN autotuner which will benchmark a number of different ways of computing convolutions in cudNN and then use the fastest method from then on.

如果你的模型架构是固定的,同时输入大小保持不变,那么设置torch.backends.cudnn.benchmark = True可能会提升模型速度(帮助文档)。通过启用cudNN自动调节器,可以在cudNN中对多种计算卷积的方法进行基准测试,然后选择最快的方法。

For a rough reference on the type of speed-up you can expect from this, Szymon Migacz achieves a speed-up of 70% on a forward pass for a convolution and a 27% speed-up for a forward + backward pass of the same convolution.

至于提速效果,Szymon Migacz在前向卷积时提速70%,在同时向前和后向卷积时提升了27%。

One caveat here is that this autotuning might become very slow if you max out the batch size as mentioned above.

注意,如果你想要根据上述方法最大化批大小,该自动调整可能会非常耗时。

7. Beware of frequently transferring data between CPUs and GPUs

Beware of frequently transferring tensors from a GPU to a CPU usingtensor.cpu() and vice versa using tensor.cuda() as these are relatively expensive. The same applies for .item() and .numpy() – use .detach() instead.

通过tensor.cpu()可以将张量从GPU传输到CPU,反之使用tensor.cuda(),但这样的数据转化代价较高。.item()和.numpy()的使用也是如此,建议使用.detach()。

If you are creating a new tensor, you can also directly assign it to your GPU using the keyword argument device=torch.device('cuda:0').

如果要创建新的张量,使用关键字参数device=torch.device('cuda:0')将其直接分配给GPU。

If you do need to transfer data, using .to(non_blocking=True), might be useful as long as you don't have any synchronization points after the transfer.

最好使用.to(non_blocking=True)传输数据,确保传输后没有任何同步点即可。

If you really have to, you might want to give Santosh Gupta's SpeedTorch a try, although it doesn't seem entirely clear when this actually does/doesn't provide speed-ups.

如果你认为有必要,你可能会想试试Santosh Gupta的SpeedTorch,尽管它似乎并不完全清楚这实际上什么时候能/不提供加速。

8. Use gradient/activation checkpointing

Quoting directly from the documentation:

直接引用文件中的话:

Checkpointing works by trading compute for memory. Rather than storing all intermediate activations of the entire computation graph for computing backward, the checkpointed part does not save intermediate activations, and instead recomputes them in backward pass. It can be applied on any part of a model.

检查点通过将计算保存到内存来工作。检查点在反向传播算法过程中并不保存计算图的中间激活,而是在反向传播时重新计算,其可用于模型的任何部分。

Specifically, in the forward pass, function will run in torch.no_grad() manner, i.e., not storing the intermediate activations. Instead, the forward pass saves the inputs tuple and the function parameter. In the backwards pass, the saved inputs and function is retrieved, and the forward pass is computed on function again, now tracking the intermediate activations, and then the gradients are calculated using these activation values.

具体来说,在前向传播中,function以torch.no_grad()方式运行,不存储任何中间激活。相反,前向传递将保存输入元组和function参数。在反向传播时,检索保存的输入和function,并再次对function进行正向传播,记录中间激活,并使用这些激活值计算梯度。

So while this will might slightly increase your run time for a given batch size, you'll significantly reduce your memory footprint. This in turn will allow you to further increase the batch size you're using allowing for better GPU utilization.

因此,对于特定的批处理大小,这可能会稍微增加运行时间,但会显着减少内存消耗。反过来,你可以进一步增加批处理大小,从而更好地利用GPU。

While checkpointing is implemented natively as torch.utils.checkpoint (docs), it does seem to take some thought and effort to implement properly. Priya Goyal has a good tutorial demonstrating some of the key aspects of checkpointing.

虽然检查点可以通过torch.utils.checkpoint方便实现,但仍需要里哦阿姐其思想与本质。Priya Goyal的教程很清晰的演示了检查点的一些关键思想,推荐阅读。

9. Use gradient accumulation

Another approach to increasing the batch size is to accumulate gradients across multiple .backward() passes before calling optimizer.step().

增加批处理大小的另一种方法是在调用Optimizer.step()之对多个.backward()传递梯度进行累积。

Following a post by Hugging Face's Thomas Wolf, gradient accumulation can be implemented as follows:

根据Hugging Face的Thomas Wolf发表的文章,可以按以下方式实现梯度累积:

model.zero_grad()                                   # Reset gradients tensors    
for i, (inputs, labels) in enumerate(training_set):    
predictions = model(inputs)                     # Forward pass    
loss = loss_function(predictions, labels)       # Compute loss function    
loss = loss / accumulation_steps                # Normalize our loss (if averaged)    
loss.backward()                                 # Backward pass    
if (i+1) % accumulation_steps == 0:             # Wait for several backward steps    
optimizer.step()                            # Now we can do an optimizer step    
model.zero_grad()                           # Reset gradients tensors    
if (i+1) % evaluation_steps == 0:           # Evaluate the model when we...    
evaluate_model()                        # ...have no gradients accumulated

This method was developed mainly to circumvent GPU memory limitations and I'm not entirely clear on the trade-off between having additional .backward() loops. This discussion on the fastai forum seems to suggest that it can in fact accelerate training, so it's probably worth a try.view rawgradient_accumulation.py hosted with ❤ by GitHub

该方法主要是为了规避GPU内存的限制,但对其他.backward()循环之间的取舍我并不清楚。fastai论坛上的讨论似乎表明它实际上是可以加速训练的,因此值得一试。详情查看GitHub托管的rawgradient_accumulation.py。

10. Use Distributed Data Parallel for multi-GPU training

Methods to accelerate distributed training probably warrant their own post but one simple one is to use torch.nn.DistributedDataParallel rather than torch.nn.DataParallel. By doing so, each GPU will be driven by a dedicated CPU core avoiding the GIL issues of DataParallel.

通过分布式训练加快模型速度的一种简单的方法是使用torch.nn.DistributedDataParallel而不是torch.nn.DataParallel。这样,每个GPU将由专用的CPU内核驱动,从而避免了DataParallel的GIL问题。

11. Set gradients to None rather than 0

Use .zero_grad(set_to_none=True) rather than .zero_grad().

设置.zero_grad(set_to_none=True)而不是.zero_grad()。

Doing so will let the memory allocator handle the gradients rather than actively setting them to 0. This will lead to yield a modest speed-up as they say in the documentation, so don't expect any miracles.

这样内存分配器处理梯度而不是主动将其设置为0,这会产生该文档所示的适度加速,但不要抱有过大期望。

Watch out, doing this is not side-effect free! Check the docs for the details on this.

注意,这样做不会有任何副作用!阅读文档查看更多信息。

12. Use .as_tensor() rather than .tensor()

torch.tensor() always copies data. If you have a numpy array that you want to convert, use torch.as_tensor() or torch.from_numpy() to avoid copying the data.

torch.tensor()本质是复制数据,因此,如果要转换numpy数组,使用torch.as_tensor()或torch.from_numpy()可以避免复制数据。

13. Turn on debugging tools only when actually needed

Pytorch offers a number of useful debugging tools like the autograd.profiler, autograd.grad_check, and autograd.anomaly_detection. Make sure to use them to better understand when needed but to also turn them off when you don't need them as they will slow down your training.

Pytorch提供了许多调试工具,例如autograd.profiler, autograd.grad_check和autograd.anomaly_detection。使用时一定要谨慎,这些调试工具显然会影响训练速度,因此在不需要时将其关闭。

14. Use gradient clipping

Originally used to avoid exploding gradients in RNNs, there is both some empirical evidence as well as some theoretical support that clipping gradients (roughly speaking: gradient = min(gradient, threshold) ) accelerates convergence.

为了避免RNN中的梯度爆炸,使用梯度裁剪gradient = min(gradient, threshold)可以起到加速收敛作用,这一方法已得到理论和实验的支持。

Hugging Face's Transformer implementation is a really clean example of how to use gradient clipping as well as some of the other methods such as AMP mentioned in this post.

Hugging Face的Transformer提供了将梯度裁剪和AMP等其他方法有效结合的清晰示例。

In PyTorch this can be done using torch.nn.utils.clip_grad_norm_ (documentation).

在PyTorch中,也可使用torch.nn.utils.clip_grad_norm_(文档查阅)完成此操作。

It's not entirely clear to me which models benefit how much from gradient clipping but it seems to be robustly useful for RNNs, Transformer-based and ResNets architectures and a range of different optimizers.

虽然我尚不完全清楚哪种模型可以从梯度裁剪中受益,但毫无疑问的是,对于RNN、基于Transformer和ResNets结构的一系列优化器来说,该方法显然是起到一定作用的。

15. Turn off bias before BatchNorm

This is a very simple one: turn off the bias of layers before BatchNormalization layers. For a 2-D convolutional layer, this can be done by setting the bias keyword to False: torch.nn.Conv2d(..., bias=False, ...). (Here's a reminder why this makes sense.)

在BatchNormalization层之前关闭之前层的偏差是一种简单有效的方法。对于二维卷积层,可以通过将bias关键字设置为False实现,即torch.nn.Conv2d(..., bias=False, ...)。阅读该文档了解其原理。

You will save some parameters, I would however expect the speed-up of this to be relatively small as compared to some of the other methods mentioned here.

与其他方法相比,该方法的速度提升是有的。

16. Turn off gradient computation during validation

This one is straightforward: set torch.no_grad() during validation.

在模型验证时令torch.no_grad()

17. Use input and batch normalization

You're probably already doing this but you might want to double-check:

也许你已经在这样做了,但还是要仔细检查,反复确认:

Are you normalizing your input?

是否规范化输入?

Are you using batch-normalization?

是否规范化批处理?

Bonus tip from the comments: Use JIT to fuse point-wise operations.

其他技巧:使用JIT实现逐点融合

If you have adjacent point-wise operations you can use PyTorch JIT to combine them into one FusionGroup which can then be launched on a single kernel rather than multiple kernels as would have been done per default. You'll also save some memory reads and writes.

如果要执行相邻逐点操作,可以使用PyTorch JIT将它们组合成一个FusionGroup,然后在单内核上启动,而不是像默认情况那样在多个内核上启动,同时还可以保存一些内存进行读写。

Szymon Migacz shows how you can use the @torch.jit.script decorator to fuse the operations in a GELU, for instance:

Szymon Migacz展示了如何使用@torch.jit.script装饰器融合GELU操作融合,如下:

@torch.jit.script
def fused_gelu(x):
    return x * 0.5 * (1.0 + torch.erf(x / 1.41421))

In this case, fusing the operations leads to a 5x speed-up for the execution of fused_gelu as compared to the unfused version.

相比于未融合版本,融合这些操作可以使fused_gelu的执行速度提高5倍。

See also this post for an example of how Torchscript can be used to accelerate an RNN.

查阅此文章获取更多使用Torchscript加速RNN的示例。

Hat tip to u/Patient_Atmosphere45 on Reddit for the suggestion.

当然,你还可以在Reddit上与u/Patient_Atmosphere45交流讨论。

Sources and additional resources

Many of the tips listed above come from Szymon Migacz' talk and post in the PyTorch docs.

本文许多技巧参考自Szymon Migacz的演讲及PyTorch文档。

PyTorch Lightning's William Falcon has two interesting posts with tips to speed-up training. PyTorch Lightning does already take care of some of the points above per-default.

PyTorch Lightning的作者William Falcon在这两篇文章中介绍了关于加快训练的内容。同时,PyTorch Lightning已集成以上一些技巧与方法。

Thomas Wolf at Hugging Face has a number of interesting articles on accelerating deep learning – with a particular focus on language models.

Hugging Face的作者Thomas Wolf也写了一系列文章介绍深度学习的加速-尤其是语言模型。

The same goes for Sylvain Gugger and Jeremy Howard: they have many interesting posts in particular on learning rates and AdamW.

Sylvain Gugger和Jeremy Howard写了很多关于学习率和AdamW的文章。

Thanks to Ben Hahn, Kevin Klein and Robin Vaaler for their feedback on a draft of this post!

感谢Ben Hahn,Kevin Klein和Robin Vaaler对本文撰写提供的帮助!

 

更多深度学习竞赛项目,大家可移步官网进行查看和参赛!

更多精彩内容请访问FlyAI-AI竞赛服务平台;为AI开发者提供数据竞赛并支持GPU离线训练的一站式服务平台;每周免费提供项目开源算法样例,支持算法能力变现以及快速的迭代算法模型。

挑战者,都在FlyAI!!!

 

【Docker】Docker基础入门 一、Docker简介 Docker 是一个开源的应用容器引擎,基于Go 语言并遵从 Apache2.0 协议开源。 Docker 可以让开发者打包他们的应用以及依赖包到一个轻量级、可移植的容器中,然后发布到任何流行的 Linux 机器上,也可以实现虚拟化。 容器是完全使用沙箱机制,相互之间不会有任何接口(类似 iPhone 的 app),更重要的是容器性能开销极低。 Docker 从 17.03 版本之后分为 CE(Community Edition: 社区版) 和 EE(Enterprise .. 阅读详情

相关推荐

PyTorch CNN图像分类实战:从训练调优到libtorch部署

CNN图像分类是计算机视觉最基础且高频的工业任务,其核心在于模型结构设计、数据预处理鲁棒性与训练动态调控能力。PyTorch凭借清晰的梯度流和灵活的模块化设计,成为CNN落地首选框架;但真实项目中常面临验证崩盘、推理OOM、部署不一致等工程瓶颈。本文聚焦PyTorch图像分类全链路实践,深入解析ResNet18结构选型依据、BatchNorm运行统计陷阱、OneCycleLR学习率调度原理,并打通TorchScript导出与libtorch C++部署路径,覆盖数据加载IO优化、标签平滑防过拟合、混合精度加

靓靓软件工作室 584

一步一步理解大模型:激活检查点技术

方法中,它首先恢复在前向传播过程中保存的RNG状态,然后运行前向传播函数以重新计算激活状态,并使用保存的梯度进行反向传播。在深度学习模型的训练过程中,前向传播会计算并存储每一层的激活值,这些激活值在后向传播时被用来计算梯度。然而,对于深度很大的模型,这种方式可能会导致内存溢出,因为需要存储大量的激活值。激活检查点(Activation Checkpointing)是一种用于优化深度学习模型训练的技术,它可以在内存使用和计算效率之间进行权衡,以在有限的硬件资源下训练更大的模型。具体实现的关键是一个名为。

chattyfish的博客 3936

学习率衰减实战指南:从原理到PyTorch工业级配置

学习率衰减是深度学习优化中的核心机制,本质源于随机梯度下降(SGD)收敛性理论——要求学习率序列满足∑ηₜ发散且∑ηₜ²收敛,以兼顾全局探索与局部精调。它并非辅助技巧,而是防止训练后期震荡、突破精度瓶颈的关键工程手段。在图像分类、目标检测、NLP等主流任务中,合理选用Cosine Annealing、Step Decay等策略,并协同Warmup与Batch Size动态缩放(η₀ ∝ √B),可显著提升模型收敛速度、稳定性和泛化能力。本文聚焦PyTorch落地细节,覆盖参数速查、代码实现、多卡适配及高频报

dianqi0560的博客 489

PyTorch 节省显存技巧:Activation Checkpointing

本文介绍了 PyTorch 中的激活检查点技术,旨在减小内存占用,同时提供更多计算资源。其中详细讨论了 PyTorch 中的自动求导机制,以及两种激活检查点的实现方式:可重新进入(reentrant)和不可重新进入(non-reentrant)。特别关注了非可重新进入版本的新特性,包括嵌套检查点、在检查点内调用 .grad()/.backward() 的支持、非确定性检查和调试性的改进、在指定 retain_graph 时的内存节省等。同时,还介绍了可重新进入变体的实现方式,并提供了简单的用法示例。

kebijuelun的博客 4897

深度学习训练四要素:epoch、batch、batch_size、iteration实战解析

在深度学习模型训练中,epoch、batch、batch_size和iteration是控制数据流与参数更新的核心工程概念。它们共同决定了梯度计算精度、显存占用效率、收敛稳定性及硬件吞吐能力。理解其内在原理——如batch_size对梯度噪声与正则效应的影响、epoch作为数据分布学习周期的本质、iteration作为监控与调度的基本时间单位——是避免OOM、loss震荡、过拟合等常见问题的关键。这些参数广泛应用于CNN图像分类、LSTM时序预测、ViT视觉建模等主流任务,在PyTorch/TensorFl

weixin_28689193的博客 281

解决PyTorch CUDA版本不匹配:从驱动到运行时完整配置指南

CUDA作为NVIDIA GPU的并行计算平台,其核心原理是通过统一的架构释放GPU的大规模并行处理能力,为深度学习等计算密集型任务提供硬件加速。在技术实现上,CUDA通过驱动层、运行时层和应用层的协同工作,将计算任务映射到GPU的数千个核心上执行。其技术价值在于显著提升了矩阵运算、神经网络训练等任务的效率,成为现代人工智能开发的基石。在实际应用场景中,PyTorch等主流框架深度依赖CUDA实现模型加速,但环境配置中常见的“RuntimeError: CUDA error: no kernel image

cigang4063的博客 415

[LLM]大模型训练DeepSpeed(一)-原理介绍

DeepSpeed是由Microsoft提供的分布式训练工具,旨在支持更大规模的模型和提供更多的优化策略和工具。与其他框架相比,DeepSpeed支持更大规模的模型和提供更多的优化策略和工具。其中,主要优势在于支持更大规模的模型、提供了更多的优化策略和工具(例如 ZeRO 和 Offload 等)

摩登都市天空---专栏 7万+

PyTorch强化学习实战(17)——强化学习训练加速

我们已经学习了若干提升[深度Q网络 (Deep Q-Network, DQN) 方法稳定性与收敛速度的实用技巧。这些技巧通过对经典 DQN 方法进行改良(例如向网络注入噪声或展开贝尔曼方程),以更短的训练时间获得更优策略。而本节我们将探索另一种加速路径:通过调整方法实现细节来提升训练效率。这虽属纯工程优化范畴,却因其实用价值而至关重要。

盼小辉丶的博客 131

【DeepSpeed】激活检查点(Activation Checkpointing):内存优化技术

激活检查点(Activation Checkpointing)是 DeepSpeed 提供的一种内存优化技术,用于在深度学习模型训练中减少激活值(intermediate activations)的内存占用,特别适合大规模模型或显存受限场景。心思想:不是存储所有层的激活值,而是仅保存部分关键层的激活值(检查点)。在反向传播时,丢弃未保存的激活值,并在需要时通过重新运行前向传播(recomputation)来恢复。这种方法以额外的计算开销(重新计算前向传播)换取显著的显存节省。

彬彬侠的博客 2884

PyTorch实现YOLOv3-tiny:从环境搭建到模型优化的完整实践指南

目标检测是计算机视觉的核心任务之一,旨在识别图像中物体的位置与类别。其主流算法通常基于卷积神经网络,通过骨干网络提取特征,再经由检测头输出预测框。这类技术在安防监控、自动驾驶和工业质检等实时性要求高的场景中具有重要价值。YOLO系列算法因其单阶段、高效率的特性,成为实时目标检测的经典选择。本文以轻量化的YOLOv3-tiny模型为例,详细阐述了使用PyTorch框架进行项目实践的完整流程。内容涵盖如何正确配置PyTorch与CUDA开发环境以避开常见安装陷阱,深入解析了包括Darknet骨干网络和多尺度检测

weixin_29098117的博客 309

✨从零搭建 Ubuntu22.04 + Python3.11 + PyTorch2.5.1 GPU Docker 镜像并上传 Docker Hub

构建一个带 GPU 支持的深度学习开发镜像;使用 PyTorch 2.5.1(CUDA 12.4)环境;发布并托管 Docker 镜像至 Docker Hub;验证 GPU 环境正常运行!🎉 这将极大提升你的项目部署效率,尤其是在多人协作或跨平台部署场景中。

用大模型重构生活:猫奴程序员的AI智能日常记录 1578

小白学 PyTorch 系列:54个超强 pytorch 操作

是 PyTorch 中用于定义和搭建模型的基类。通过继承该类,可以创建自定义的深度学习模型。# 自定义模型类# 创建模型实例# 查看模型结构你可以通过继承类来创建自定义的损失函数。# 自定义损失函数类# 使用自定义损失函数你可以自定义模型参数的初始化方法。# 自定义初始化方法# 在模型中应用初始化方法你可以通过继承类来创建自定义学习率调度器。# 自定义学习率调度器类# 自定义学习率调度逻辑pass# 使用自定义学习率调度器继承类可以自定义数据加载器。# 自定义数据加载器类。

Python数据挖掘 2190

GitLab社区版vs企业版:本地部署性能对比与选型建议(含实测数据)

本文深入对比GitLab社区版(CE)与企业版(EE)在本地部署中的性能差异与功能特性,提供实测数据与选型建议。测试显示EE版在并发克隆、CI流水线启动等场景性能提升显著,尤其适合需要高级安全合规与CI/CD功能的团队。文章还包含硬件配置指南与成本效益分析,帮助技术决策者做出明智选择。

weixin_28828243的博客 295

⭐ 深度学习入门体系(第 17 篇): 学习率:为什么它能决定训练成败?

学习率是深度学习中最重要的超参数之一,它直接影响模型训练的成败。本文系统讲解了学习率的核心概念和作用机制:学习率控制参数更新的步长,如同驾驶中的油门力度,过大导致震荡发散,过小则训练缓慢。文章分析了学习率不合适的典型症状,并介绍了主流学习率调度策略(如Warmup+Cosine),提供了PyTorch实现代码。最后总结了8条工程实践共识,强调学习率是模型训练的"命门",掌握其调节技巧能显著提升训练效率。

weixin_43679228的博客 978

Qt Location实战:5分钟搞定地图插件切换与卫星图源加载(附完整代码)

本文是Qt Location开发系列教程的实战指南,详细讲解如何在Qt应用中快速实现地图插件(如Esri、OSM、MapboxGL)的动态切换与卫星图源的加载。通过清晰的代码示例,帮助开发者理解插件机制,解决常见配置问题,并在5分钟内构建出具备交互式地图切换功能的应用程序。

kafka6courier的博客 526

别再只看K线了!用Python自制筹码分布图,可视化Winner函数帮你判断支撑压力

本文详细介绍了如何用Python自制筹码分布图,通过数据清洗、算法实现和动态可视化,帮助投资者更准确地判断股票支撑压力位。文章重点讲解了Winner函数的应用,结合筹码分布与交易策略,提升交易决策的精准度。

weixin_42520796的博客 315

实测PyTorch-2.x-Universal-Dev-v1.0:GPU加速训练速度提升明显

本文介绍了如何在星图GPU平台上自动化部署PyTorch-2.x-Universal-Dev-v1.0镜像,显著提升深度学习模型的GPU加速训练效率。该镜像预装了完整的开发工具链,支持CUDA优化和编译加速,特别适用于图像分类等计算机视觉任务,实测显示ResNet-50训练速度提升达1.5倍。

weixin_42602726的博客 151

保姆级教程:用Python 3.10和Ollama在Windows上搞定LightRAG本地部署(附环境配置避坑指南)

本文提供了一份详细的Windows系统下LightRAG本地部署指南,涵盖Python 3.10环境配置、Ollama模型服务安装到LightRAG核心组件部署的全流程。特别针对Windows平台常见问题提供解决方案,帮助开发者快速搭建高效的检索增强生成(RAG)系统,实现专业领域知识的智能检索与整合。

weixin_28725407的博客 489

实测minimind:消费级显卡两小时从零训练64M参数语言模型

语言模型的训练通常被认为需要庞大的算力资源,但通过合理的模型架构与数据策略,个人开发者也能在消费级显卡上完成从零训练。本文以minimind项目为例,实测了64M参数模型在单张RTX 4090上两小时的训练过程,涵盖硬件门槛、数据预处理、超参数调整与loss曲线分析。通过实际生成效果评估小模型的能力边界,并分享了显存优化、梯度爆炸等常见问题的排查技巧。这类小规模模型训练实验,为深入理解Transformer工作原理和大模型技术提供了低成本的实践路径。

weixin_34211761的博客 379

YOLOv11与Roboflow数据预处理实战:从原始数据到高性能模型

摘要 Roboflow平台与YOLOv11的结合为计算机视觉开发者提供了高效的工作流。Roboflow提供数据集管理、预处理、增强和导出的一站式解决方案,支持多种标注格式并与YOLOv11无缝集成。YOLOv11在YOLO系列基础上进行了架构创新,包括深度宽度优化、C3k2机制和C2PSA注意力机制,提供从纳米版到超大版的多种模型变体。 使用Roboflow的流程包括:注册工作区、收集/导入数据(支持本地和公开数据集)、专业标注(含SAM辅助)、预处理(尺寸调整、归一化等)和数据增强(几何变换和颜色调整)。

本博客聚焦 YOLOv11 全流程落地,涵盖架构优化、数据集处理、训练技巧与多场景部署,兼及国产数据库、Java 开发与 AI 模型应用,内容兼顾理论与工程实践,为开发者提供系统干货,助力高效提升技术能力。 350

AgentScope深入分析-ReActAgent

ReActAgent 是 AgentScope 框架中最核心的智能体实现,它完美诠释了"推理-行动"(Reasoning-Acting)循环的精髓。本文将深入分析 ReActAgent 的类继承关系、核心执行流程,以及状态管理、钩子机制、实时介入等关键技术点。通过阅读本文,你会理解智能体如何与模型交互、如何执行工具、如何处理中断,以及这些机制背后的设计考量。模块化:通过组合不同的组件(模型、格式化器、工具集、记忆)来构建智能体透明性:所有关键流程都对开发者可见,可以精确控制可扩展性。

842

PyTorch Conference 2024大会概况及FlagGems/FlagAttention算子库亮相

因此,本届 PyTorch 大会所宣讲的绝大多数内容都或多或少涉及大模型的训练、微调、对齐、推理、量化、部署、评测、数据、结构细节、底层编译优化等关键话题,以及整个 PyTorch 生态社群在过去一年中与之相关的努力。本届的例行报告本身包含五个部分,其中最后三个分别对应 PyTorch 官方今年新推出的三个原生大模型库:用于大规模预训练的 TorchTitan、用于大模型微调的 TorchTune、用于大模型端侧部署推理的 TorchChat。大会为过去一年中 PyTorch 社区的杰出贡献者颁发了奖项。

qq_41610763的博客 755

Dify框架面试内容整理-如何优化Dify的应用性能?

为1536维)可选用 PCA、FAISS 的量化压缩方法降低维度(如128、256、512);对知识库预览、任务流配置等页面,使用 nginx/cache-control 减少请求。API 响应耗时(P50/P95)、Token 使用量、缓存命中率、向量检索耗时;对 Prompt+输入内容计算 Hash,缓存相同请求的返回结果;使用占位符 + 函数拼接,按需组合 Prompt,而非静态长模板;数据量大时,应在构建索引前清洗冗余段落、统一格式,避免重复向量。维度越低,检索越快,但可能影响召回准确度,需平衡。

不务正业的猿 1551

PyTorch、TensorFlow与JAX实战选型指南:研究落地与生产部署的工程权衡

AI框架不仅是代码工具,更是连接算法构想与硬件执行的‘思维翻译器’。从自动微分原理到计算图编译机制,不同框架在动态性、确定性与函数式表达上存在根本差异。PyTorch以eager模式支撑快速迭代与调试友好性,TensorFlow依托SavedModel与XLA保障云上部署一致性与边缘量化能力,JAX则通过jit/grad/vmap提供高阶可微分编程范式。技术价值体现在研究复现效率、生产SLA达标率与跨平台可维护性;典型场景覆盖金融风控模型迭代、医疗影像辅助诊断部署及工业预测性维护系统构建。本文基于12个跨行

weixin_30423977的博客 376

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

CNN与RNN协同建模:时空联合深度学习实战指南

深度学习中,卷积神经网络(CNN)和循环神经网络(RNN)分别代表空间特征提取与时间序列建模的两大基础范式。其核心原理在于:CNN通过局部感受野与权值共享捕获图像、频谱图等网格化数据的空间不变性;RNN及其门控变体(LSTM/GRU)则借助隐状态循环传递建模长程时序依赖。这种互补性赋予模型处理视频、医疗影像、工业传感器流等多模态时空数据的技术价值——既避免纯CNN忽略时间演化,也克服纯RNN丢失空间结构。典型应用场景涵盖动作识别、CT影像分析、设备故障预测等需同步理解‘是什么’与‘会怎样’的任务。本文聚焦C

weixin_34246529的博客 297

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

学习率衰减:深度学习训练的数值稳定性核心机制

学习率衰减是保障神经网络稳定收敛的基础优化技术,其本质源于梯度下降在非凸高维空间中的Lipschitz连续性约束——学习率必须动态适配损失曲面局部平滑度变化。它并非调参技巧,而是连接优化理论(如热力学退火、凸优化边界条件)与工程实践(如BatchNorm稳定性、混合精度兼容性)的关键枢纽。主流策略如余弦退火、ReduceLROnPlateau和指数衰减,分别对应不同收敛阶段的探索-开发权衡;而warmup融合、分布式同步、多任务分层调度等工业级实践,则直接决定模型泛化能力与部署鲁棒性。本文深入解析四大策略原

ajwh64482的博客 450

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

上一篇: SIGIR2020|KEPS:知识图谱和个性化搜索碰撞的火花
下一篇: AI 大神 Chris Olah:在你的领域,如何培养好的科研品味?
iFlyAI
博客等级 码龄9年 238粉丝 134原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值