Home Technology peripherals AI By changing a few lines of code, PyTorch's alchemy speed is soaring and model optimization time is greatly reduced.

By changing a few lines of code, PyTorch's alchemy speed is soaring and model optimization time is greatly reduced.

Apr 11, 2023 pm 12:16 PM
Model train

How to improve the speed of PyTorch "Alchemy"?

Recently, well-known machine learning and AI researcher Sebastian Raschka showed us his trick. According to him, his method reduced the BERT optimization time from 22.63 minutes to 3.15 minutes by changing only a few lines of code without affecting the accuracy of the model, and the training speed was increased by a full 7 times.

By changing a few lines of code, PyTorchs alchemy speed is soaring and model optimization time is greatly reduced.

##The author even stated that if you have 8 GPUs available, the entire training process only requires It takes 2 minutes to achieve 11.5x performance acceleration.

By changing a few lines of code, PyTorchs alchemy speed is soaring and model optimization time is greatly reduced.

Let’s take a look at how he achieved it.

Make PyTorch model training faster

The first is the model. The author uses the DistilBERT model for research. It is a streamlined version of BERT and is 40 times smaller than BERT. %, but with almost no performance loss. The second is the data set. The training data set is the IMDB Large Movie Review, a large movie review data set, which contains a total of 50,000 movie reviews. The author will use method c in the figure below to predict movie review sentiment in the dataset.

By changing a few lines of code, PyTorchs alchemy speed is soaring and model optimization time is greatly reduced.

After the basic tasks have been explained clearly, the following is the training process of PyTorch. In order to let everyone better understand this task, the author also intimately introduces a warm-up exercise, that is, how to train the DistilBERT model on the IMDB movie review data set. If you want to run the code yourself, you can set up a virtual environment using the relevant Python libraries, as shown below:

The versions of the relevant software are as follows:

By changing a few lines of code, PyTorchs alchemy speed is soaring and model optimization time is greatly reduced.

Now omit the boring data loading introduction, you only need to understand that this article divides the data set into 35,000 training examples, 5000 validation examples and 10000 test examples. The required code is as follows:

By changing a few lines of code, PyTorchs alchemy speed is soaring and model optimization time is greatly reduced.

#Screenshot of the code part

Full code address:

https://github.com/rasbt/faster-pytorch-blog /blob/main/1_pytorch-distilbert.py​

Then run the code on the A100 GPU and get the following results:

By changing a few lines of code, PyTorchs alchemy speed is soaring and model optimization time is greatly reduced.

Partial results screenshot

As shown in the above code, the model goes from round 2 to round 3 There was a little overfitting at the beginning of the round, and the verification accuracy dropped from 92.89% to 92.09%. After fine-tuning the model for 22.63 minutes, the final test accuracy was 91.43%.

Use the Trainer class##The next step is to improve the above code. The improvement part is mainly to wrap the PyTorch model in LightningModule so that you can use the Trainer class from Lightning. Some code screenshots are as follows:

By changing a few lines of code, PyTorchs alchemy speed is soaring and model optimization time is greatly reduced.

Full code address: https://github.com/rasbt/faster-pytorch-blog/blob/main/2_pytorch- with-trainer.py

#The above code creates a LightningModule, which defines how to perform training, validation and testing. Compared to the code given previously, the main change is in Part 5 (i.e. 5 Finetuning), which is fine-tuning the model. Unlike before, the fine-tuning part wraps the PyTorch model in the LightningModel class and uses the Trainer class to fit the model.

By changing a few lines of code, PyTorchs alchemy speed is soaring and model optimization time is greatly reduced.

The previous code showed that the verification accuracy dropped from round 2 to round 3, but the improved The code uses ModelCheckpoint to load the best model. On the same machine, the model achieved 92% test accuracy in 23.09 minutes.

By changing a few lines of code, PyTorchs alchemy speed is soaring and model optimization time is greatly reduced.

It should be noted that if checkpointing is disabled and PyTorch is allowed to run in non-deterministic mode, this run will eventually get the same running time as normal PyTorch (The time is 22.63 minutes instead of 23.09 minutes).

Automatic mixed precision training

Further, if the GPU supports mixed precision training, you can turn on the GPU to improve computing efficiency . The authors use automatic mixed-precision training, switching between 32-bit and 16-bit floating point without sacrificing accuracy.

By changing a few lines of code, PyTorchs alchemy speed is soaring and model optimization time is greatly reduced.

##Under this optimization, using the Trainer class, automatic Mixed precision training:

By changing a few lines of code, PyTorchs alchemy speed is soaring and model optimization time is greatly reduced.

The above operation can reduce the training time from 23.09 minutes to 8.75 minutes, which is almost 3 times faster times. The accuracy on the test set is 92.2%, even slightly improved from the previous 92.0%.

By changing a few lines of code, PyTorchs alchemy speed is soaring and model optimization time is greatly reduced.

Use Torch.Compile static image

Recent PyTorch 2.0 announcement display , the PyTorch team introduced the new toch.compile function. This function can speed up PyTorch code execution by generating optimized static graphs instead of using dynamic graphs to run PyTorch code.

By changing a few lines of code, PyTorchs alchemy speed is soaring and model optimization time is greatly reduced.

Since PyTorch 2.0 has not yet been officially released, torchtriton must be installed first and updated to This feature is only available in the latest version of PyTorch.

By changing a few lines of code, PyTorchs alchemy speed is soaring and model optimization time is greatly reduced.


Then modify the code by adding this line:

By changing a few lines of code, PyTorchs alchemy speed is soaring and model optimization time is greatly reduced.

Distributed data parallelism on 4 GPUs

The above describes the mixed precision training of accelerating code on a single GPU. Next, we introduce the multi-GPU training strategy. The figure below summarizes several different multi-GPU training techniques.

By changing a few lines of code, PyTorchs alchemy speed is soaring and model optimization time is greatly reduced.

If you want to achieve distributed data parallelism, you can achieve it through DistributedDataParallel, just modify it Trainer can be used with just one line of code.

By changing a few lines of code, PyTorchs alchemy speed is soaring and model optimization time is greatly reduced.

After this step of optimization, on 4 A100 GPUs, this code ran for 3.52 minutes and reached 93.1 % test accuracy.

By changing a few lines of code, PyTorchs alchemy speed is soaring and model optimization time is greatly reduced.

By changing a few lines of code, PyTorchs alchemy speed is soaring and model optimization time is greatly reduced.

#DeepSpeed

Finally, the author explores the results of using the deep learning optimization library DeepSpeed ​​and the multi-GPU strategy in Trainer. First you must install the DeepSpeed ​​library:

By changing a few lines of code, PyTorchs alchemy speed is soaring and model optimization time is greatly reduced.

Then you only need to change one line of code to enable the library:

By changing a few lines of code, PyTorchs alchemy speed is soaring and model optimization time is greatly reduced.

After this wave, it took 3.15 minutes to reach a test accuracy of 92.6%. However, PyTorch also has an alternative to DeepSpeed: fully-sharded DataParallel, called with strategy="fsdp", which finally took 3.62 minutes to complete.

By changing a few lines of code, PyTorchs alchemy speed is soaring and model optimization time is greatly reduced.

The above is the author’s method to improve the training speed of PyTorch model. Interested friends can Follow the original blog and give it a try, I believe you will get the results you want.

The above is the detailed content of By changing a few lines of code, PyTorch's alchemy speed is soaring and model optimization time is greatly reduced.. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Open source! Beyond ZoeDepth! DepthFM: Fast and accurate monocular depth estimation! Open source! Beyond ZoeDepth! DepthFM: Fast and accurate monocular depth estimation! Apr 03, 2024 pm 12:04 PM

0.What does this article do? We propose DepthFM: a versatile and fast state-of-the-art generative monocular depth estimation model. In addition to traditional depth estimation tasks, DepthFM also demonstrates state-of-the-art capabilities in downstream tasks such as depth inpainting. DepthFM is efficient and can synthesize depth maps within a few inference steps. Let’s read about this work together ~ 1. Paper information title: DepthFM: FastMonocularDepthEstimationwithFlowMatching Author: MingGui, JohannesS.Fischer, UlrichPrestel, PingchuanMa, Dmytr

The world's most powerful open source MoE model is here, with Chinese capabilities comparable to GPT-4, and the price is only nearly one percent of GPT-4-Turbo The world's most powerful open source MoE model is here, with Chinese capabilities comparable to GPT-4, and the price is only nearly one percent of GPT-4-Turbo May 07, 2024 pm 04:13 PM

Imagine an artificial intelligence model that not only has the ability to surpass traditional computing, but also achieves more efficient performance at a lower cost. This is not science fiction, DeepSeek-V2[1], the world’s most powerful open source MoE model is here. DeepSeek-V2 is a powerful mixture of experts (MoE) language model with the characteristics of economical training and efficient inference. It consists of 236B parameters, 21B of which are used to activate each marker. Compared with DeepSeek67B, DeepSeek-V2 has stronger performance, while saving 42.5% of training costs, reducing KV cache by 93.3%, and increasing the maximum generation throughput to 5.76 times. DeepSeek is a company exploring general artificial intelligence

KAN, which replaces MLP, has been extended to convolution by open source projects KAN, which replaces MLP, has been extended to convolution by open source projects Jun 01, 2024 pm 10:03 PM

Earlier this month, researchers from MIT and other institutions proposed a very promising alternative to MLP - KAN. KAN outperforms MLP in terms of accuracy and interpretability. And it can outperform MLP running with a larger number of parameters with a very small number of parameters. For example, the authors stated that they used KAN to reproduce DeepMind's results with a smaller network and a higher degree of automation. Specifically, DeepMind's MLP has about 300,000 parameters, while KAN only has about 200 parameters. KAN has a strong mathematical foundation like MLP. MLP is based on the universal approximation theorem, while KAN is based on the Kolmogorov-Arnold representation theorem. As shown in the figure below, KAN has

Hello, electric Atlas! Boston Dynamics robot comes back to life, 180-degree weird moves scare Musk Hello, electric Atlas! Boston Dynamics robot comes back to life, 180-degree weird moves scare Musk Apr 18, 2024 pm 07:58 PM

Boston Dynamics Atlas officially enters the era of electric robots! Yesterday, the hydraulic Atlas just "tearfully" withdrew from the stage of history. Today, Boston Dynamics announced that the electric Atlas is on the job. It seems that in the field of commercial humanoid robots, Boston Dynamics is determined to compete with Tesla. After the new video was released, it had already been viewed by more than one million people in just ten hours. The old people leave and new roles appear. This is a historical necessity. There is no doubt that this year is the explosive year of humanoid robots. Netizens commented: The advancement of robots has made this year's opening ceremony look like a human, and the degree of freedom is far greater than that of humans. But is this really not a horror movie? At the beginning of the video, Atlas is lying calmly on the ground, seemingly on his back. What follows is jaw-dropping

The vitality of super intelligence awakens! But with the arrival of self-updating AI, mothers no longer have to worry about data bottlenecks The vitality of super intelligence awakens! But with the arrival of self-updating AI, mothers no longer have to worry about data bottlenecks Apr 29, 2024 pm 06:55 PM

I cry to death. The world is madly building big models. The data on the Internet is not enough. It is not enough at all. The training model looks like "The Hunger Games", and AI researchers around the world are worrying about how to feed these data voracious eaters. This problem is particularly prominent in multi-modal tasks. At a time when nothing could be done, a start-up team from the Department of Renmin University of China used its own new model to become the first in China to make "model-generated data feed itself" a reality. Moreover, it is a two-pronged approach on the understanding side and the generation side. Both sides can generate high-quality, multi-modal new data and provide data feedback to the model itself. What is a model? Awaker 1.0, a large multi-modal model that just appeared on the Zhongguancun Forum. Who is the team? Sophon engine. Founded by Gao Yizhao, a doctoral student at Renmin University’s Hillhouse School of Artificial Intelligence.

AI subverts mathematical research! Fields Medal winner and Chinese-American mathematician led 11 top-ranked papers | Liked by Terence Tao AI subverts mathematical research! Fields Medal winner and Chinese-American mathematician led 11 top-ranked papers | Liked by Terence Tao Apr 09, 2024 am 11:52 AM

AI is indeed changing mathematics. Recently, Tao Zhexuan, who has been paying close attention to this issue, forwarded the latest issue of "Bulletin of the American Mathematical Society" (Bulletin of the American Mathematical Society). Focusing on the topic "Will machines change mathematics?", many mathematicians expressed their opinions. The whole process was full of sparks, hardcore and exciting. The author has a strong lineup, including Fields Medal winner Akshay Venkatesh, Chinese mathematician Zheng Lejun, NYU computer scientist Ernest Davis and many other well-known scholars in the industry. The world of AI has changed dramatically. You know, many of these articles were submitted a year ago.

Kuaishou version of Sora 'Ke Ling' is open for testing: generates over 120s video, understands physics better, and can accurately model complex movements Kuaishou version of Sora 'Ke Ling' is open for testing: generates over 120s video, understands physics better, and can accurately model complex movements Jun 11, 2024 am 09:51 AM

What? Is Zootopia brought into reality by domestic AI? Exposed together with the video is a new large-scale domestic video generation model called "Keling". Sora uses a similar technical route and combines a number of self-developed technological innovations to produce videos that not only have large and reasonable movements, but also simulate the characteristics of the physical world and have strong conceptual combination capabilities and imagination. According to the data, Keling supports the generation of ultra-long videos of up to 2 minutes at 30fps, with resolutions up to 1080p, and supports multiple aspect ratios. Another important point is that Keling is not a demo or video result demonstration released by the laboratory, but a product-level application launched by Kuaishou, a leading player in the short video field. Moreover, the main focus is to be pragmatic, not to write blank checks, and to go online as soon as it is released. The large model of Ke Ling is already available in Kuaiying.

The U.S. Air Force showcases its first AI fighter jet with high profile! The minister personally conducted the test drive without interfering during the whole process, and 100,000 lines of code were tested for 21 times. The U.S. Air Force showcases its first AI fighter jet with high profile! The minister personally conducted the test drive without interfering during the whole process, and 100,000 lines of code were tested for 21 times. May 07, 2024 pm 05:00 PM

Recently, the military circle has been overwhelmed by the news: US military fighter jets can now complete fully automatic air combat using AI. Yes, just recently, the US military’s AI fighter jet was made public for the first time and the mystery was unveiled. The full name of this fighter is the Variable Stability Simulator Test Aircraft (VISTA). It was personally flown by the Secretary of the US Air Force to simulate a one-on-one air battle. On May 2, U.S. Air Force Secretary Frank Kendall took off in an X-62AVISTA at Edwards Air Force Base. Note that during the one-hour flight, all flight actions were completed autonomously by AI! Kendall said - "For the past few decades, we have been thinking about the unlimited potential of autonomous air-to-air combat, but it has always seemed out of reach." However now,

See all articles