Home Technology peripherals AI The PyTorch team rewrote the 'split everything' model, which is 8 times faster than the original implementation

The PyTorch team rewrote the 'split everything' model, which is 8 times faster than the original implementation

Nov 22, 2023 pm 03:45 PM
pytorch project

How should we optimize Meta's "split everything" model? This blog written by the PyTorch team will help you answer it from simple to deep.

From the beginning of the year to now, generative AI has developed rapidly. But many times, we have to face a difficult problem: how to speed up the training, reasoning, etc. of generative AI, especially when using PyTorch.

In this article, researchers from the PyTorch team provide us with a solution. The article focuses on how to use pure native PyTorch to accelerate generative AI models. It also introduces new PyTorch features and practical examples of how to combine them.

What was the result? The PyTorch team said they rewrote Meta's "Split Everything" (SAM) model, resulting in code that is 8 times faster than the original implementation without losing accuracy, all optimized using native PyTorch.

The PyTorch team rewrote the split everything model, which is 8 times faster than the original implementation

Blog address: https://pytorch.org/blog/accelerating-generative-ai/

See By the end of this article, you will know:

  • Torch.compile: PyTorch model compiler, PyTorch 2.0 has added a new function called torch. compile (), can accelerate the existing model through one line of code;
  • GPU quantization: accelerate the model by reducing the calculation accuracy;
  • SDPA (Scaled Dot Product Attention): A memory-efficient attention implementation;
  • Semi-structured (2:4) Sparseness: A sparse memory format optimized for GPU;
  • Nested Tensor: Nested Tensor packs {tensor, mask} together to batch non-uniformly sized data into a single tensor, such as images of different sizes;
  • Triton Custom Operations: Use the Triton Python DSL to write GPU operations and easily integrate them into various components of PyTorch through custom operator registration.

The PyTorch team rewrote the split everything model, which is 8 times faster than the original implementation

#                                                                                                                                                                                                                               to be increased throughput and reduced memory overhead brought by PyTorch’s native features.

SAM was proposed by Meta. For more information about this research, please refer to "
CV no longer exists? Released by Meta "Split everything" AI model, CV may usher in GPT-3 moment".

The PyTorch team rewrote the split everything model, which is 8 times faster than the original implementation

Next, the article introduces the SAM optimization process, including performance analysis, bottleneck identification, and how to integrate these new features into PyTorch to solve these problems faced by SAM. In addition, this article also introduces some new features of PyTorch: torch.compile, SDPA, Triton kernels, Nested Tensor, and semi-structured sparsity.

The content of this article is in-depth step by step. At the end of the article, the fast version of SAM will be introduced. Interested friends can download it on GitHub. In addition, this article also uses the Perfetto UI to The data is visualized to illustrate the application value of each PyTorch feature.

GitHub address: https://github.com/pytorch-labs/segment-anything-fast

Rewriting of the SAM that splits all models

The study shows that the SAM baseline data type used in this article is float32 dtype, the batch size is 1, and the The results of viewing the kernel trace with PyTorch Profiler are as follows:

The PyTorch team rewrote the split everything model, which is 8 times faster than the original implementation

This article found that SAM has two places that can be optimized:

#The first is the long call to aten::index, which is caused by the tensor index operation (such as []) caused by the underlying call. However, the actual time the GPU spends on aten::index is relatively low. The reason is that during the process of starting two cores, aten::index blocks cudaStreamSynchronize between the two. This means that the CPU waits for the GPU to finish processing until the second core is launched. Therefore, in order to optimize SAM, this paper believes that one should strive to eliminate blocking GPU synchronization that causes idle time.

The second is that SAM spends a lot of GPU time in matrix multiplications (dark green in the image above), which is common in Transformers. If we could reduce the amount of GPU time a SAM model spends on matrix multiplications, we could significantly speed up SAM.

Next, this article uses SAM’s throughput (img/s) and memory overhead (GiB) to establish a baseline. After that comes the optimization process.

The PyTorch team rewrote the split everything model, which is 8 times faster than the original implementation

Bfloat16 half precision (plus GPU sync and batch processing)

To solve To solve the above problem, that is, making matrix multiplication take less time, this article turns to bfloat16. Bfloat16 is a commonly used half-precision type that can save a lot of computing time and memory by reducing the precision of each parameter and activation.

The PyTorch team rewrote the split everything model, which is 8 times faster than the original implementation

Use bfloat16 to replace the padding type

Remove GPU synchronization, this article found that there are two places that can be optimized.

The PyTorch team rewrote the split everything model, which is 8 times faster than the original implementation

The PyTorch team rewrote the split everything model, which is 8 times faster than the original implementation

Specifically (refer to the picture above for easier understanding, the variable names that appear are all in the code), the study found that in SAM In the image encoder, there are variables q_coords and k_coords that act as coordinate scalers. These variables are allocated and processed on the CPU. However, once these variables are used to index in rel_pos_resized, these indexing operations will automatically move these variables to the GPU, and this copy will cause GPU synchronization. To solve the above problem, the study noted that this part can be solved by rewriting it using torch.where as shown above.

Kernel Trace

After applying these changes, this article noted that a single kernel There is a significant time interval between calls, especially in small batches (here 1). In order to gain a deeper understanding of this phenomenon, this article begins with a performance analysis of SAM inference with a batch size of 8:

The PyTorch team rewrote the split everything model, which is 8 times faster than the original implementation

When looking at the time spent per core, this article It is observed that most of the GPU time of SAM is spent on elementwise kernels and softmax operations.

Now you can see that the relative cost of matrix multiplication is much smaller.

The PyTorch team rewrote the split everything model, which is 8 times faster than the original implementation

Combining GPU synchronization and bfloat16 optimization, SAM performance is improved by 3 times.

The PyTorch team rewrote the split everything model, which is 8 times faster than the original implementation

Torch.compile(graph breaks and CUDA graphs)

This article found that there are many small operations in the process of in-depth study of SAM. They It is believed that using a compiler to fuse operations has great benefits, so PyTorch has made the following optimizations for torch.compile:

  • Change nn.LayerNorm or Sequences of operations such as nn.GELU are fused into a single GPU kernel;
  • #Fuse operations immediately following the matrix multiplication kernel to reduce the number of GPU kernel calls.

#With these optimizations, the research reduces the number of GPU global memory roundtrips, resulting in faster inference. We can now try torch.compile on SAM’s image encoder. To maximize performance, this article uses some advanced compilation techniques:

The PyTorch team rewrote the split everything model, which is 8 times faster than the original implementation

Kernel Tracing

The PyTorch team rewrote the split everything model, which is 8 times faster than the original implementation

The results show that torch.compile works very well.

The PyTorch team rewrote the split everything model, which is 8 times faster than the original implementation

#It can be observed that softmax takes up a large part of the time, followed by various GEMM variants. The following measurements are for batch sizes of 8 and above.

The PyTorch team rewrote the split everything model, which is 8 times faster than the original implementation

SDPA: scaled_dot_product_attention

Next, this article conducts a review on SDPA (scaled_dot_product_attention) For the experiment, the focus of the research is the attention mechanism. In general, native attention mechanisms scale quadratically with sequence length in time and memory. PyTorch's SDPA operations are built on the memory-efficient attention principles of Flash Attention, FlashAttentionV2, and xFormer, which can significantly speed up GPU attention. Combined with torch.compile, this operation allows the expression and fusion of a common pattern in variants of MultiheadAttention. After a small change, the model can now use scaled_dot_product_attention.

The PyTorch team rewrote the split everything model, which is 8 times faster than the original implementation

Kernel Tracing

You can now see memory efficient attention kernel occupancy Significant computation time on GPU:

The PyTorch team rewrote the split everything model, which is 8 times faster than the original implementation

Using PyTorch's native scaled_dot_product_attention, batch sizes can be significantly increased. The graph below shows the changes for batch sizes of 32 and above.

The PyTorch team rewrote the split everything model, which is 8 times faster than the original implementation

After that, the research also experimented with Triton, NestedTensor, batch processing Predict_torch, int8 quantization, semi-structured (2:4) sparsity and other operations.

For example, this article uses a custom positional Triton kernel and observes measurement results with a batch size of 32.

The PyTorch team rewrote the split everything model, which is 8 times faster than the original implementation

Using Nested Tensor, variations in batch size 32 and above.

The PyTorch team rewrote the split everything model, which is 8 times faster than the original implementation

#Measurements for batch sizes of 32 and above after adding quantization.

The PyTorch team rewrote the split everything model, which is 8 times faster than the original implementation

The end of the article is semi-structured sparsity. The study shows that matrix multiplication is still a bottleneck that needs to be faced. The solution is to use sparsification to approximate matrix multiplication. By sparse matrices (i.e. zeroing out the values) fewer bits can be used to store weights and activation tensors. The process of setting which weights in a tensor is set to zero is called pruning. Pruning out smaller weights can potentially reduce model size without significant loss of accuracy.

There are many methods of pruning, ranging from completely unstructured to highly structured. While unstructured pruning theoretically has minimal impact on accuracy, GPUs, although very efficient at doing large dense matrix multiplications, may suffer significant performance degradation in sparse cases. A pruning method recently supported by PyTorch aims to strike a balance called semi-structured (or 2:4) sparsity. This sparse storage reduces the original tensor by 50% while producing a dense tensor output. See illustration below.

The PyTorch team rewrote the split everything model, which is 8 times faster than the original implementation

#To use this sparse storage format and the associated fast kernels, the next thing to do is to prune the weights. This article selects the smallest two weights for pruning at a sparsity of 2:4. Changing the weights from the default PyTorch ("strided") layout to this new semi-structured sparse layout is easy. To implement apply_sparse (model), only 32 lines of Python code are needed:

The PyTorch team rewrote the split everything model, which is 8 times faster than the original implementation

At a sparsity of 2:4, this article observes vit_b and SAM when the batch size is 32 Peak performance:

The PyTorch team rewrote the split everything model, which is 8 times faster than the original implementation

Finally, to summarize this article in one sentence: This article introduces the fastest Segment Anything implementation on PyTorch so far, with the help of a series of new officially released Function, this article rewrites the original SAM in pure PyTorch without losing accuracy.

Interested readers can check out the original blog for more information.

Reference link: https://pytorch.org/blog/accelerating-generative-ai/

The above is the detailed content of The PyTorch team rewrote the 'split everything' model, which is 8 times faster than the original implementation. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

The author of ControlNet has another hit! The whole process of generating a painting from a picture, earning 1.4k stars in two days The author of ControlNet has another hit! The whole process of generating a painting from a picture, earning 1.4k stars in two days Jul 17, 2024 am 01:56 AM

It is also a Tusheng video, but PaintsUndo has taken a different route. ControlNet author LvminZhang started to live again! This time I aim at the field of painting. The new project PaintsUndo has received 1.4kstar (still rising crazily) not long after it was launched. Project address: https://github.com/lllyasviel/Paints-UNDO Through this project, the user inputs a static image, and PaintsUndo can automatically help you generate a video of the entire painting process, from line draft to finished product. follow. During the drawing process, the line changes are amazing. The final video result is very similar to the original image: Let’s take a look at a complete drawing.

Topping the list of open source AI software engineers, UIUC's agent-less solution easily solves SWE-bench real programming problems Topping the list of open source AI software engineers, UIUC's agent-less solution easily solves SWE-bench real programming problems Jul 17, 2024 pm 10:02 PM

The AIxiv column is a column where this site publishes academic and technical content. In the past few years, the AIxiv column of this site has received more than 2,000 reports, covering top laboratories from major universities and companies around the world, effectively promoting academic exchanges and dissemination. If you have excellent work that you want to share, please feel free to contribute or contact us for reporting. Submission email: liyazhou@jiqizhixin.com; zhaoyunfeng@jiqizhixin.com The authors of this paper are all from the team of teacher Zhang Lingming at the University of Illinois at Urbana-Champaign (UIUC), including: Steven Code repair; Deng Yinlin, fourth-year doctoral student, researcher

Posthumous work of the OpenAI Super Alignment Team: Two large models play a game, and the output becomes more understandable Posthumous work of the OpenAI Super Alignment Team: Two large models play a game, and the output becomes more understandable Jul 19, 2024 am 01:29 AM

If the answer given by the AI ​​model is incomprehensible at all, would you dare to use it? As machine learning systems are used in more important areas, it becomes increasingly important to demonstrate why we can trust their output, and when not to trust them. One possible way to gain trust in the output of a complex system is to require the system to produce an interpretation of its output that is readable to a human or another trusted system, that is, fully understandable to the point that any possible errors can be found. For example, to build trust in the judicial system, we require courts to provide clear and readable written opinions that explain and support their decisions. For large language models, we can also adopt a similar approach. However, when taking this approach, ensure that the language model generates

From RLHF to DPO to TDPO, large model alignment algorithms are already 'token-level' From RLHF to DPO to TDPO, large model alignment algorithms are already 'token-level' Jun 24, 2024 pm 03:04 PM

The AIxiv column is a column where this site publishes academic and technical content. In the past few years, the AIxiv column of this site has received more than 2,000 reports, covering top laboratories from major universities and companies around the world, effectively promoting academic exchanges and dissemination. If you have excellent work that you want to share, please feel free to contribute or contact us for reporting. Submission email: liyazhou@jiqizhixin.com; zhaoyunfeng@jiqizhixin.com In the development process of artificial intelligence, the control and guidance of large language models (LLM) has always been one of the core challenges, aiming to ensure that these models are both powerful and safe serve human society. Early efforts focused on reinforcement learning methods through human feedback (RL

arXiv papers can be posted as 'barrage', Stanford alphaXiv discussion platform is online, LeCun likes it arXiv papers can be posted as 'barrage', Stanford alphaXiv discussion platform is online, LeCun likes it Aug 01, 2024 pm 05:18 PM

cheers! What is it like when a paper discussion is down to words? Recently, students at Stanford University created alphaXiv, an open discussion forum for arXiv papers that allows questions and comments to be posted directly on any arXiv paper. Website link: https://alphaxiv.org/ In fact, there is no need to visit this website specifically. Just change arXiv in any URL to alphaXiv to directly open the corresponding paper on the alphaXiv forum: you can accurately locate the paragraphs in the paper, Sentence: In the discussion area on the right, users can post questions to ask the author about the ideas and details of the paper. For example, they can also comment on the content of the paper, such as: "Given to

A significant breakthrough in the Riemann Hypothesis! Tao Zhexuan strongly recommends new papers from MIT and Oxford, and the 37-year-old Fields Medal winner participated A significant breakthrough in the Riemann Hypothesis! Tao Zhexuan strongly recommends new papers from MIT and Oxford, and the 37-year-old Fields Medal winner participated Aug 05, 2024 pm 03:32 PM

Recently, the Riemann Hypothesis, known as one of the seven major problems of the millennium, has achieved a new breakthrough. The Riemann Hypothesis is a very important unsolved problem in mathematics, related to the precise properties of the distribution of prime numbers (primes are those numbers that are only divisible by 1 and themselves, and they play a fundamental role in number theory). In today's mathematical literature, there are more than a thousand mathematical propositions based on the establishment of the Riemann Hypothesis (or its generalized form). In other words, once the Riemann Hypothesis and its generalized form are proven, these more than a thousand propositions will be established as theorems, which will have a profound impact on the field of mathematics; and if the Riemann Hypothesis is proven wrong, then among these propositions part of it will also lose its effectiveness. New breakthrough comes from MIT mathematics professor Larry Guth and Oxford University

Axiomatic training allows LLM to learn causal reasoning: the 67 million parameter model is comparable to the trillion parameter level GPT-4 Axiomatic training allows LLM to learn causal reasoning: the 67 million parameter model is comparable to the trillion parameter level GPT-4 Jul 17, 2024 am 10:14 AM

Show the causal chain to LLM and it learns the axioms. AI is already helping mathematicians and scientists conduct research. For example, the famous mathematician Terence Tao has repeatedly shared his research and exploration experience with the help of AI tools such as GPT. For AI to compete in these fields, strong and reliable causal reasoning capabilities are essential. The research to be introduced in this article found that a Transformer model trained on the demonstration of the causal transitivity axiom on small graphs can generalize to the transitive axiom on large graphs. In other words, if the Transformer learns to perform simple causal reasoning, it may be used for more complex causal reasoning. The axiomatic training framework proposed by the team is a new paradigm for learning causal reasoning based on passive data, with only demonstrations

The first Mamba-based MLLM is here! Model weights, training code, etc. have all been open source The first Mamba-based MLLM is here! Model weights, training code, etc. have all been open source Jul 17, 2024 am 02:46 AM

The AIxiv column is a column where this site publishes academic and technical content. In the past few years, the AIxiv column of this site has received more than 2,000 reports, covering top laboratories from major universities and companies around the world, effectively promoting academic exchanges and dissemination. If you have excellent work that you want to share, please feel free to contribute or contact us for reporting. Submission email: liyazhou@jiqizhixin.com; zhaoyunfeng@jiqizhixin.com. Introduction In recent years, the application of multimodal large language models (MLLM) in various fields has achieved remarkable success. However, as the basic model for many downstream tasks, current MLLM consists of the well-known Transformer network, which

See all articles