<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Huili Yu on Medium]]></title>
        <description><![CDATA[Stories by Huili Yu on Medium]]></description>
        <link>https://medium.com/@freshtechyy?source=rss-81e2a307d7db------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Eh757jtJm4bHQ2fZ5FaoAw.jpeg</url>
            <title>Stories by Huili Yu on Medium</title>
            <link>https://medium.com/@freshtechyy?source=rss-81e2a307d7db------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 10:22:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@freshtechyy/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Transformer — A detailed explanation from perspectives of tensor shapes and PyTorch implementation.]]></title>
            <link>https://medium.com/@freshtechyy/transformer-a-detailed-explanation-from-perspectives-of-tensor-shapes-and-pytorch-implementation-74fdff967de6?source=rss-81e2a307d7db------2</link>
            <guid isPermaLink="false">https://medium.com/p/74fdff967de6</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Huili Yu]]></dc:creator>
            <pubDate>Thu, 25 Jan 2024 07:39:41 GMT</pubDate>
            <atom:updated>2024-01-25T07:39:41.152Z</atom:updated>
            <content:encoded><![CDATA[<h3>Transformer — A detailed explanation from perspectives of tensor shapes and PyTorch implementation.</h3><p>A detailed explanation to transformer based on tensor shapes and PyTorch implementation.</p><p>We are in the era of generative AI and many Large Language Models (LLMs), like GPTs, Llama, and Palm, etc., allow us to accomplish tasks very efficiently. The key building block of the LLMs is transformer presented in [1]. To understand how the LLMs work and incorporate them into our lives, it is crucial to study details of the transformer.</p><p>There are many existing tutorials about the transformer. In this post, I like to explain the transformer from a different perspective. As a developer in the field of AI, I realize that to really understand and grasp a technology it is better to implement the technology. And a lot of time I find that figuring out the dimensions of tensors throughout the entire implementation greatly helps me understand how the technology works. Accordingly, in this post, I will explain the transformer based on the shapes of the tensors throughout the transformer and its implementation in PyTorch.</p><h3>Overall Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ngiX8StEDehf4dfyP8Sc5Q.png" /><figcaption>Figure 1. Transformer architecture.</figcaption></figure><p>Transformer was initialized designed for solving sequence-to-sequence problem [1], like machine translation, for which input or source sequences are provided to the transformer and then the transformer generates output sequences. As shown in Fig. 1, the transformer consists of an encoder, a decoder, a linear layer and a softmax layer. In the encoder, the input or source sequences first pass through the input embedding layer to generate high dimensional input embeddings and then the positional encoding is added to the input embeddings to maintain the relative positions of the tokens in the sequence. Then the input embeddings with the positional encoding added pass through several encoder layers to generate the output of encoder.</p><p>Similarly, in the decoder, the output sequences or target sequences pass through the output embedding layer, the positional encoding layer, and several decoder layers to generate the output of decoder. Note that each decoder layer also takes the output of encoder as one of the inputs. A linear layer and a softmax layer are applied to the output of decoder to generate the probability for each token over the output vocabulary.</p><p>Note that in Fig. 1, notations like (bs, N), (bs, M, d_ model), (bs, M, out_vocab_size), etc., represent the shape of tensors throughout the transformer. The notations align with the tensor shape in PyTorch. For example, (bs, N) is a two dimensional tensor, where bs is the batch size and N is the input or source sequence length. The notation (bs, M, d_model) is a three dimensional tensor, where bs is the batch size, M is the output or target sequence length, and d_model is the size of the model embedding. The notation (bs, M, out_vocab_size) is a three dimensional tensor, where bs is the batch size, M is the output or target sequence length, out_vocab_size is the size of output vocabulary.</p><p>I will explain how each component works and the shapes of tensors in each component in the following sections.</p><h3>Inputs and Outputs</h3><h4>Input Sequence and Output Sequence</h4><p>I like to first talk about what the input sequence we should provide to the transformer and what the output sequence the transformer will generate.</p><p>In the sequence-to-sequence problem, the input sequence is given to the transformer, and then the transformer predicts the output sequence. Take machine translation as an example. A sequence of words in a source language is first tokenized by a tokenizer that generates a sequence of tokens. The sequence of tokens is the input sequence to the transformer. The transformer predicts another sequence of tokens, which is the output sequence. The output sequence will be detokenized by the tokenizer to generate a sequence of words in a target language. Some commonly used tokenizers are Byte-Pair Encoding (BPE), WordPiece, and SentencePiece, etc. Tokenizer is not the focus of this post. Please refer to existing tutorials on them.</p><p>Note that there is a slightly difference about the output sequence between training and inference modes of the transformer. During training, the output sequences are from the training dataset. One or more output sequences in a batch are provided to the transformer, which predicts the outputs for each output sequence. Consider an English to Chinese translation problem, as shown in Fig. 2.</p><p>During the training, our dataset has many pairs of English-Chinese sentences. For one such a pair, we feed the English sentence (e.g., I love Artificial Intelligence) as the input sequence to the encoder and feed the Chinese sentence (e.g., 我爱人工智能) to as the output sequence to the decoder. As the decoder of the transformer is an autoregressive model, it predicts the current token based on all previously predicted tokens. So, we add a special word “START” to the original output sequence in order for the transformer to handle the starting point of the sequence. Now, the output sequence to the decoder becomes “START我爱人工智能”. With the input and output sequences, the transformer predicts probability over entire Chinese vocabulary for each token of the output sequence. Finally, these probability predictions and the target sequence are used to compute the cross-entropy loss for the training. The target sequence (e.g., “我爱人工智能END”) is the right-shift version of the output sequence followed by a special word “END” to indicate the end of the sequence.</p><figure><img alt="transformer training" src="https://cdn-images-1.medium.com/max/1024/1*2p7qcbGYmPvSEXc_OgvvvQ.jpeg" /><figcaption>Figure 2. Input and output sequences during transformer training for machine translation. Image by author.</figcaption></figure><p>As data for both input sequences and output sequences are available beforehand, training can be done in parallel. The tensors for dummy input and output sequences with specified shapes can be implemented in PyTorch as follows.</p><pre># Dummy input and output sequences<br># src_data shape: (batch_size, src_seq_len)<br># tgt_data shape: (batch_size, tgt_seq_len)<br>src_data = torch.randint(0, src_vocab_size, (batch_size, src_seq_len))<br>tgt_data = torch.randint(0, tgt_vocab_size, (batch_size, tgt_seq_len))</pre><p>In the inference mode of the transformer, there are no data beforehand that are used for the output sequence. The transformer starts from “START” and predict the first word “我”, and then uses the sequence “START我” to predict the second word “爱”, and then uses the sequence “START我爱” to predict the third word “人”, and repeat this prediction until the end of the sentence.</p><figure><img alt="transformer inference" src="https://cdn-images-1.medium.com/max/1024/1*UGSbAK-PO-7YgUAqihAtJQ.jpeg" /><figcaption>Figure 3. Input and output sequences during transformer inference for machine translation. Image by author.</figcaption></figure><h4>Input/Output Embedding</h4><p>The transformer encodes tokens into high dimensional embeddings which capture the semantic meaning of tokens, making it easier for transformer to understand relationships between them. Let us consider the following implementation example of embedding in PyTorch.</p><pre># Encoder embedding for input sequences<br>encoder_embedding = torch.nn.Embedding(src_vocab_size, d_model)<br># src_emb shape: (batch_size, src_seq_len, d_model)<br>src_emb = encoder_embedding(src_data)<br><br># Decoder embedding for output sequences<br>decoder_embedding = torch.nn.Embedding(tgt_vocab_size, d_model)<br># tgt_emb shape: (batch_size, tgt_seq_len, d_model)<br>tgt_emb = decoder_embedding(tgt_data)</pre><p>The torch.nn.Embedding layer is used to convert the input (source) and output (target) sequences from their original integer representation (indices) into dense, continuous embeddings. The torch.nn.Embedding layer initializes a lookup table of shape (src_vocab_size/tgt_vocab_size, d_model), where each row of the table represents the embedding vector for a particular token in the input/output vocabulary. During the forward pass, the layer takes the input/output sequence (a tensor of shape (batch_size, src_seq_len/tgt_seq_len)) and returns a tensor of shape (batch_size, src_seq_len/tgt_seq_len, d_model), where each token is replaced with its corresponding embedding vector.</p><h3>Encoder Layer and Decoder Layer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-2zYDxhbvjkSqzhP0u85Ig.png" /><figcaption>Figure 4. Encoder layer and decoder layer. Image by author.</figcaption></figure><h4>Encoder Layer</h4><p>The encoder layer in the transformer refines the input representation through a combination of self-attention and feedforward neural networks, enabling it to capture intricate dependencies and contextual information within the input sequence. Multiple stacked encoder layers hierarchically enhance the input representation for improved feature extraction.</p><p>As shown in Fig. 4, the encoder layer consists of a multi-head self-attention network and a feedforward network incorporating residual connections and layer normalization. The residual connections address the vanishing gradient problem and make it easier for the model to learn identity mappings. The layer normalization normalizes the activations across the embedding dimension, helping stabilize training by reducing internal covariate shift and improving the convergence of the model.</p><p>The PyTorch implementation of the layer normalization is as follows. The layer normalization does not change the tensor shape.</p><pre># Normalization along embedding dimension<br>layer_norm = torch.nn.LayerNorm(d_model)<br># x shape: (bs, src_seq_len, d_model)<br># x_norm shape: (bs, src_seq_len, d_model)<br>x_norm = layer_norm(x)</pre><p>The input to the encoder layer is either the embeddings of input sequences or the output of previous encoder layer. The shapes of tensors along the encoder layer are same as the embeddings’ shape of input sentences: (bs, N, d_model), where N is the input sequence length.</p><h4>Decoder Layer</h4><p>The decoder layer in the transformer is responsible for autoregressively generating output sequences by utilizing self-attention to capture local dependencies within the sequence of tokens generated by the decoder itself during the autoregressive process , and encoder-decoder attention (cross-attention) to incorporate global context from the input/source sequence, ensuring the production of coherent and contextually relevant sequences.</p><p>Similarly, the decoder layer of the transformer consists of multi-head attention layers, feedforward layers, and layer normalization. However, different from the encoder layer, which only consider one multi-head self-attention layer, there are one masked multi-head self-attention layer and one multi-head cross-attention (encoder-decoder) layer.</p><p>The decoder layer takes the output sequence embeddings or the output of previous decoder layer, and the output of last encoder layer of the encoder. The shapes of tensors along the decoder layer are same as the output sequence embeddings’ shape: (bs, M, d_model), where M is the output sequence length.</p><h3>Attention</h3><p>In this section, I will first introduce general attentions including single head and multi-head attentions. Then based on the general attentions, I will explain the multi-head self-attention used in the encoder layer, masked multi-head self-attention and multi-head cross-attention used in the decoder layer.</p><h4>General Single-Head Attention for A Single Sequence (Batch Size = 1)</h4><figure><img alt="general single-head attention with bs is 1" src="https://cdn-images-1.medium.com/max/1024/1*ZY93DFLDKus5unw6XZr9rg.png" /><figcaption>Figure 5. General single-head attention for a single sequence (batch size = 1). Image by author.</figcaption></figure><p>Figure 5 is a diagram of showing how a general single-head attention is computed when the batch size is 1 and the shapes of tensors used in the computation. The general single-head attention involves three tensors: Q (query), K (key), and V (value). It first computes the alignment of the ith component (row vector) of query Q with the jth component (row vector) of key K by the scaled dot product</p><figure><img alt="scaled dot-product" src="https://cdn-images-1.medium.com/max/612/1*3qSMg8wYhcoxQj5uy7mr3Q.png" /><figcaption>Equation 1. Scaled dot product of a row vector of Q and a row vector of K. Image by author.</figcaption></figure><p>Then the attention scores can be computed from the alignment by using Softmax along the axis of j. Finally, the attention scores are used as weights and the output corresponding to the ith component of Q is computed as the weighted sum of all the components (row vectors) of value V. Note that the reason that the scaled dot product is used instead of the regular dot product is because scaling the dot product down by a factor proportional to the square root of the dimensionality prevents the dot product from being too large, which can lead to issues such as vanishing or exploding gradients. In particular, the scaled dot product has the following benefits.</p><ul><li>The softmax function in attention mechanisms involves exponentiating the attention scores. Large dot products can result in very large values, which can lead to numerical instability during training. Scaled the dot products helps control the scale of the resulting values and gradients.</li><li>Scaling the dot products ensures that the attention scores are not overly sensitive to the magnitude of the input vectors, which results in a better-conditioned optimization problem and more effective learning.</li></ul><p>The general single-head (batch size is 1) attention can be efficiently computed in parallel, as shown in Fig. 6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K3RAHU1d1OzIyw3HZ4cBSA.png" /><figcaption>Figure 6. Computation of general single-head attention for batch size equal to 1 and corresponding tensor shapes. Image by author.</figcaption></figure><h4>General Single-Head Attention for Multiple Sequences (Batch Size = bs)</h4><p>The computation given by Fig. 6 can be easily extend to the case where the batch size is greater than 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XDMJzbRyQp-mSJVyRLrfDQ.png" /><figcaption>Figure 7. Computation of general single-head attention for multiple sequences (batch size greater than 1) and corresponding tensor shapes. Image by author.</figcaption></figure><h4>General Multi-Head Attention for A Single Sequence (Batch Size = 1)</h4><p>Multi-head attention is used in the transformer to capture multiple aspects of information in the data sequence. Consider a sentence: “The movie was not great, but the acting was excellent.” The single-head attention may only focus on the negative sentiment “not great” and may struggle to capture the positive sentiment “excellent” because the single-head attention has already committed to attending primarily to the negative sentiment.</p><p>Now, consider a multi-head attention model with, let’s say, two attention heads. Each head can attend to different aspects of the sentence simultaneously. Head 1 may focus on the negative sentiment part of the sentence “not great” while Head 2 may focus on the positive sentiment part of the sentence “excellent”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HSP5xv-Nu33JqHukZN9TMg.png" /><figcaption>Figure 8. General multi-head attention for a single sequence (batch size = 1). Image by author.</figcaption></figure><p>In multi-head attention, say s heads, Q, K, and V are split along the embedding dimension into s copies of Q, K and V. Then, each copy of Q, K, and V is input to the general single-head attention to generate an output. Finally, s outputs are concatenated along the embedding dimension into an overall output.</p><p>The computation of multi-head attention for a single sequence can be computed as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NwY0-u-lVaD8nwmyfsUxiw.png" /><figcaption>Figure 9. Computation of general multi-head attention for a single sequence (batch size equal to 1) and corresponding tensor shapes. Image by author.</figcaption></figure><h4>General Multi-Head Attention for Multiple Sequences (Batch Size = bs)</h4><p>The computation given by Fig. 9 can be extended to the multiple sequences case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UercXc97JPvIb2B4iUOAcw.png" /><figcaption>Figure 10. Computation of general multi-head attention for multiple sequences (batch size greater than 1) and corresponding tensor shapes. Image by author.</figcaption></figure><h4>Multi-head self-attention in the encoder layer of transformer</h4><p>Having introduced the general attentions, let’s now discuss the three kinds of attentions used in the transformer. I first discuss the multi-head self-attention in the encoder layer of the transformer.</p><p>The multi-head self-attention follows the same computation flow as shown in Fig. 10. The difference is that four learnable weighting matrices are incorporated into the computation. Figure 11 shows these matrices and their shapes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cb-nsT7vZcEvw2NrveRJyA.png" /><figcaption>Figure 11. Learnable weighting matrices used in the multi-head self-attention of the encoder layer in transformer. Image by author.</figcaption></figure><p>With these learnable weighting matrices, the computation of the multi-head self-attention is given by Fig. 12.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*P5y-M9mS8SlffWaQFJVI4g.png" /><figcaption>Figure 12. Computation of multi-head self-attention used in the encoder layer of transformer and corresponding tensor shapes. Image by author.</figcaption></figure><h4>Masked Multi-Head Self-Attention in Decoder of Transformer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t69bzUcfTUTexd2mXYQyww.png" /><figcaption>Figure 13. Masked (single-head) self-attention in the decoder layer of transformer. Image by author. The figure is for single-head case for easy understanding, and the computation is extendable to multi-head case.</figcaption></figure><p>The multi-head self-attention in the decoder layer is used to capture dependencies within the tokens of the output sequence. Different from the encoder, the decoder of the transformer generates output in an autoregressive manner, which means it predicts the output for the token at the current location based on only previously generated tokens. Therefore, during the training phase, all the future tokens need to be masked out when computing the alignment and the attention scores. That is why the multi-head self-attention in the decoder layer is called masked multi-head self-attention.</p><p>Figure 13 shows how the mask is applied when computing the alignment of Q and K. Note that all the upper right elements of the alignment E are -inf. After going through Softmax, those elements become 0s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*voCGqq0TomaEUnPmYDqvrw.png" /><figcaption>Equation 2. Scaled dot product of a row vector of Q and a row vector of K for masked (single-head) self-attention. Image by author.</figcaption></figure><p>With the mask, the masked multi-head self-attention follows the same computation flow as shown in Fig. 12. The mask can be implemented in PyTorch by using <strong>torch.triu</strong> and <strong>torch.Tensor.masked_fill</strong> functions.</p><pre># tgt: output/target sequences, shape: (batch_size, tgt_seq_len)<br># tgt_mask shape: (batch_size, 1, tgt_seq_len, 1)<br>tgt_mask = torch.ones_like(tgt).unsqueeze(1).unsqueeze(3)<br><br># length of output/target sequences<br>tgt_seq_len = tgt.size(1)<br><br># torch.triu() returns upper triangular part of identity matrix<br># depending on value of diagonal. <br># nopeak_mask shape: (1, tgt_seq_len, tgt_seq_len)<br>nopeak_mask = (1 - torch.triu(torch.ones(1, tgt_seq_len, tgt_seq_len), diagonal=1).bool()<br><br># (batch_size, 1, tgt_seq_len, 1) &amp; (1, tgt_seq_len, tgt_seq_len) broadcast<br># into (batch_size, 1, tgt_seq_len, tgt_seq_len)<br># tgt_mask shape: (batch_size, 1, tgt_seq_len, tgt_seq_len)<br>tgt_mask = tgt_mask &amp; nopeak_mask<br><br># Some code about computing attention<br># ...<br><br># Apply mask to the alignment<br>alignment = alignment.masked_filled(tgt_mask==0, -1e9)</pre><h4>Multi-Head Cross-Attention in Decoder of Transformer</h4><p>The multi-head cross-attention (encoder-decoder attention) in the decoder layer is designed to capture context from the input/source sequence. So, Q is formed by the output of the masked multi-head self-attention of the decoder layer, and K and V are both formed by the output of the last encoder layer. Figure 14 shows Q, K, V, weighting matrices, and their shapes for the multi-head cross-attention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WD0ZX4q7B8Ddn85WU7zeTw.png" /><figcaption>Figure 14. Q, K, V, weighting matrices, and their shapes for the multi-head cross-attention. Image by author.</figcaption></figure><p>Similarly, given the output sequences of the masked multi-head self-attention of the decoder layer, and the output sequences of the last encoder layer, the multi-head cross-attention follows the same computation flow as shown in Fig. 12.</p><h3>Positional Encoding</h3><p>As demonstrated in the sections above, input sequences are processed in parallel in the transformer, which means that the model doesn’t inherently understand the sequential order of the tokens. Therefore, the positional encoding is added to the input/output sequence embeddings to capture the sequential nature of the tokens.</p><p>A good positional encoding needs to meet the following requirements.</p><ul><li>Unique encoding for each position in the sequence.</li><li>Consistent distance between any two positions across sequences with different lengths.</li><li>Generalizable to longer sequences without any efforts.</li></ul><p>Figure 15 shows the positional encoding used in [1].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*67owtZrt1CSZ2xRWHRmuzg.png" /><figcaption>Figure 15. Positional encoding. Image by author.</figcaption></figure><p>A positional encoding vector with d_model dimension is added to the embedding at each position of the input/output sequences. The positional encoding vector consists of sin and cos functions at various frequencies. As dimension increases (from 0 to d_model-1), the frequency decreases and the wavelength increases. The intuition is that the components with lower frequencies encode the position in fine-grained levels and the components with higher frequencies encode the position in coarse-grained levels. Combining the fine-grained and coarse grained representations lead to a unique encoding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vOmFa88pMqVTJT4yfl3T0w.png" /><figcaption>Figure 16. Positional encoding vectors at different sequence positions. Image by author.</figcaption></figure><p>Figure 17 verifies the distance (inner product) between the positional encodings at two positions of input/output sequence is only related to the difference between two positions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PHsJLLUcWlHiVzeWuNaCMw.png" /><figcaption>Figure 17. Distance between the positional encodings at two positions of input/output sequence. Image by author.</figcaption></figure><h3>Feedforward Layers in Encoder Layer And Decoder Layer</h3><p>There is a feedforward layer in both the encoder layer and the decoder layer. The feedforward layer consists of two linear layers and one nonlinear activation function relu. The first linear layer (fully connected) maps the embedding size from d_model to d_ff (e.g., 2048), and the second linear layer (fully connected) maps the embedding dimension from d_ff back to d_model. These feedfoward layers introduce non-linearity to the transformer, increasing the model capacity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*E4Fv5j4Z7QWeI2JIWtoScg.png" /><figcaption>Figure 18. Feedforward layers in encoder and decoder. Image by author.</figcaption></figure><h3>Output Layer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*FDp-Me9r89z_z7dOQM5Zwg.png" /><figcaption>Figure 19. Linear layer for output. Image by author.</figcaption></figure><p>There is a linear layer (fully connected layer) mapping output of the decoder of the transformer to the logits, which are further passed through the Softmax function to generate the probability of current token over the target data vocabulary.</p><h3>Entire PyTorch Implementation</h3><p>With the introduction of all the components of the transformer, we can implement the transformer in PyTorch. You can find the entire implementation in the <a href="https://github.com/freshtechyy/transformer/tree/main"><strong>Github</strong></a><strong>.</strong></p><h4>Multi-Head Attention</h4><p>As discussed above, there are three kinds of multi-head attentions in the transformer: multi-head self-attention in the encoder layer, masked multi-head self-attention in the decoder layer, and multi-head cross-attention in the decoder layer. We can design a multi-head attention class to handle all 3 cases as follows. The forward function takes different Q, K, V, and mask for different kinds of attention computations. In addition, I also list the shapes of tensors which help understanding of computations.</p><pre>import torch<br>import math<br><br>class MultiHeadAttention(torch.nn.Module):<br>  def __init__(self, d_model, num_heads):<br>    &quot;&quot;&quot;<br>    d_model: model embedding dimension<br>    num_heads: number of attention heads<br>    &quot;&quot;&quot;<br>    super(MultiHeadAttention, self).__init__()<br>    assert d_model % num_heads == 0, &quot;d_model must be divisible by num_heads&quot;<br>    self.d_model = d_model<br>    self.num_heads = num_heads<br>    # embedding dimension per head<br>    self.d_head = d_model // num_heads<br>    <br>    self.W_q = torch.nn.Linear(d_model, d_model)<br>    self.W_k = torch.nn.Linear(d_model, d_model)<br>    self.W_v = torch.nn.Linear(d_model, d_model)<br>    self.W_o = torch.nn.Linear(d_model, d_model)<br><br>  def reshape_heads(self, x):<br>    batch_size, seq_len, _ = x.size()<br>    return x.view(batch_size, seq_len, <br>                  self.num_heads,<br>                  self.d_head).transpose(1, 2)<br><br>  def scaled_dot_product_attention(self, Q, K, V, mask=None):<br>    &quot;&quot;&quot;<br>    Compute the scaled dot product attention.<br>    Q: query sequences, shape: (bs, num_heads, src_seq_len/tgt_seq_len, d_head)<br>    K: key sequences, shape: (bs, num_heads, src_seq_len/tgt_seq_len, d_head)<br>    V: value sequences, shape: (bs, num_heads, src_seq_len/tgt_seq_len, d_head)<br>    mask: attention mask<br>    Return: the scaled dot product attention.<br>    &quot;&quot;&quot;<br>    # Compute alignment of Q and K<br>    # Three cases of alignment shape:<br>    #   self-attention in encoder: (bs, num_heads, src_seq_len, src_seq_len)<br>    #   masked self-attention in decoder: <br>    #     (bs, num_heads, tgt_seq_len, tgt_seq_len)<br>    #   cross-attention in decoder: (bs, num_heads, tgt_seq_len, src_seq_len)<br>    alignment = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_head)<br>    <br>    # Apply mask<br>    if mask is not None:<br>      alignment = alignment.masked_fill(mask==0, -1e9)<br>    <br>    # Compute attention score<br>    # attn_scores shape: same as alignment&#39;s shape<br>    attn_scores = torch.softmax(alignment, dim=-1)<br><br>    # Output<br>    # output shape: (bs, num_heads, src_seq_len/tgt_seq_len, d_head)<br>    output = torch.matmul(attn_scores, V)<br>    <br>    return output<br>  <br>  def reshape_heads_back(self, x):<br>    batch_size, _, seq_len, _ = x.size()<br>    return x.transpose(1, 2).contiguous().view(batch_size, seq_len, -1)<br><br>  def forward(self, Q, K, V, mask=None):<br>    &quot;&quot;&quot;<br>    Q: sequences for query<br>    K: sequences for key<br>    V: sequences for value<br>      Three cases for shapes of Q, K, V<br>        self-attention in encoder: (bs, src_seq_len, d_model) for Q, K, and V<br>        masked self-attention in decoder: (bs, tgt_seq_len, d_model) <br>          for Q, K, and V<br>        cross-attention in decoder: (bs, tgt_seq_len, d_model) for Q,<br>          (bs, src_seq_len, d_model) for K and V<br>    mask: attention mask<br>      two cases for shape of mask<br>        self-attention in encoder and cross-attention in decoder: <br>          src_mask shape: (bs, 1, 1, src_seq_len)<br>        masked self-attention in decoder: <br>          tgt_mask shape: (bs, 1, tgt_seq_len, tgt_seq_len)<br>        <br>    Return: output of multi-head attention<br>    &quot;&quot;&quot;<br>    # Apply weights and reshape heads from <br>    # (bs, src_seq_len/tgt_seq_len, d_model) to <br>    # (bs, num_heads, src_seq_len/tgt_seq_len, d_head)<br>    Q = self.reshape_heads(self.W_q(Q))<br>    K = self.reshape_heads(self.W_k(K))<br>    V = self.reshape_heads(self.W_v(V))<br>    <br>    # Compute attention score using scaled dot production attention<br>    # attn_output shape: (bs, num_heads, src_seq_len/tgt_seq_len, d_head)<br>    attn_output = self.scaled_dot_product_attention(Q, K, V, mask)<br><br>    # Compute output<br>    # output shape: (bs, src_seq_len/tgt_seq_len, d_model)<br>    output = self.W_o(self.reshape_heads_back(attn_output))<br><br>    return output</pre><h4>Feedforward Layer</h4><p>We can write the code for the feedforward layer used in both the encoder layer and the decoder layer as follows.</p><pre>class PositionWiseFeedforward(torch.nn.Module):<br>  def __init__(self, d_model, d_ff):<br>    &quot;&quot;&quot;<br>    d_model: dimension of model embedding<br>    d_ff: dimension of feedforward embedding<br>    &quot;&quot;&quot;<br>    super(PositionWiseFeedforward, self).__init__()<br>    self.fc1 = torch.nn.Linear(d_model, d_ff)<br>    self.fc2 = torch.nn.Linear(d_ff, d_model)<br>    self.relu = torch.nn.ReLU()<br><br>  def forward(self, x):<br>    &quot;&quot;&quot;<br>    x: input<br>    &quot;&quot;&quot;<br>    return self.fc2(self.relu(self.fc1(x)))</pre><h4>Encoder Layer</h4><pre>class EncoderLayer(torch.nn.Module):<br>  def __init__(self, d_model, num_heads, d_ff, dropout):<br>    &quot;&quot;&quot;<br>    d_model: dimension of model embedding<br>    num_heads: number of attention heads<br>    d_ff: dimension of feedforward embedding<br>    dropout: dropout rate<br>    &quot;&quot;&quot;<br>    super(EncoderLayer, self).__init__()<br>    self.self_attn = MultiHeadAttention(d_model, num_heads)<br>    self.feedforward = PositionWiseFeedforward(d_model, d_ff)<br>    self.norm1 = torch.nn.LayerNorm(d_model)<br>    self.norm2 = torch.nn.LayerNorm(d_model)<br>    self.dropout = torch.nn.Dropout(dropout)<br>  <br>  def forward(self, x, mask):<br>    &quot;&quot;&quot;<br>    x: input sequences, shape: (bs, src_seq_len, d_model)<br>    mask: attention mask (src_mask), all elements are 1, <br>      shape: (bs, 1, 1, src_seq_len)<br>    &quot;&quot;&quot;<br>    # Q, K, V for self_attn in encoder are all input sequences<br>    # attn_output shape: (bs, src_seq_len, d_model)<br>    attn_output = self.self_attn(x, x, x, mask)<br><br>    # dropout is applied to the output of self-attention to avoid over-fitting<br>    # residual, and layer normalization<br>    # x shape: (bs, src_seq_len, d_model)<br>    x = self.norm1(x + self.dropout(attn_output))<br><br>    # ff_output shape: (bs, src_seq_len, d_model)<br>    ff_output = self.feedforward(x)<br><br>    # dropout is applied to the output of feedforward to avoid over-fitting<br>    # residual, and layer normalization<br>    # x shape: (bs, src_seq_len, d_model)<br>    x = self.norm2(x + self.dropout(ff_output))<br>    return x</pre><p>In the encoder layer implementation, two dropout layers have been added to the output of the self-attention layer and the output of the feedforward layer to avoid overfitting.</p><h4>Decoder Layer</h4><pre>class DecoderLayer(torch.nn.Module):<br>  def __init__(self, d_model, num_heads, d_ff, dropout):<br>    &quot;&quot;&quot;<br>    d_model: dimension of model embedding<br>    num_heads: number of attention heads<br>    d_ff: dimension of feedforward embedding<br>    dropout: dropout rate<br>    &quot;&quot;&quot;<br>    super(DecoderLayer, self).__init__()<br>    self.self_attn = MultiHeadAttention(d_model, num_heads)<br>    self.cross_attn = MultiHeadAttention(d_model, num_heads)<br>    self.feedforward = PositionWiseFeedforward(d_model, d_ff)<br>    self.norm1 = torch.nn.LayerNorm(d_model)<br>    self.norm2 = torch.nn.LayerNorm(d_model)<br>    self.norm3 = torch.nn.LayerNorm(d_model)<br>    self.dropout = torch.nn.Dropout(dropout)<br><br>  def forward(self, x, enc_output, src_mask, tgt_mask):<br>    &quot;&quot;&quot;<br>    x: output sequences, shape: (bs, tgt_seq_len, d_model)<br>    enc_output: output of last encoder layer, shape: (bs, src_seq_len, d_model)<br>    src_mask: attention mask is passed to cross-attention<br>      src_mask shape: (bs, 1, 1, src_seq_len) <br>    tgt_mask: attention mask is passed to masked self-attention<br>      tgt_mask shape: (bs, 1, tgt_seq_len, tgt_seq_len)<br>    &quot;&quot;&quot;<br>    # Q, K, V for self_attn in decoder are all output sequences<br>    # attn_output shape: (bs, tgt_seq_len, d_model)<br>    attn_output = self.self_attn(x, x, x, tgt_mask)<br>    <br>    # Dropout, residual and layer norm<br>    # x shape: (bs, tgt_seq_len, d_model)<br>    x = self.norm1(x + self.dropout(attn_output))<br>    <br>    # Q is attn_output after layer norm 1, <br>    # K and V are are output of last encoder layer (enc_output)<br>    # attn_output shape: (bs, tgt_seq_len, d_model)<br>    attn_output = self.cross_attn(x, enc_output, enc_output, src_mask)<br><br>    # Dropout, residual and layer norm<br>    # x shape: (bs, tgt_seq_len, d_model)<br>    x = self.norm2(x + self.dropout(attn_output))<br><br>    # Feedforward<br>    # ff_output shape: (bs, tgt_seq_len, d_model)<br>    ff_output = self.feedforward(x)<br><br>    # Dropout, residual and layer norm<br>    # x shape: (bs, tgt_seq_len, d_model)<br>    x = self.norm3(x + self.dropout(ff_output))<br>    return x</pre><p>Similarly, in the decoder layer implementation, three dropout layers have been added to the output of the masked self-attention layer, the output of the cross-attention layer and the output of the feedforward layer.</p><h4>Positional Encoding</h4><p>Here is the code for the positional encoding.</p><pre>class PositionalEncoding(torch.nn.Module):<br>  def __init__(self, d_model, max_seq_len):<br>    &quot;&quot;&quot;<br>    d_model: dimension of model embedding<br>    max_seq_len: maximum length of positional encoding, <br>      &gt;= max(src_seq_len, tgt_seq_len)<br>    &quot;&quot;&quot;<br>    super(PositionalEncoding, self).__init__()<br><br>    # pe shape: (max_seq_len, d_model)<br>    pe = torch.zeros(max_seq_len, d_model)<br>    # position shape: (max_seq_len, 1)<br>    position = torch.arange(0, max_seq_len, dtype=torch.float).unsqueeze(1)<br>    # freq_term shape: (d_model/2)<br>    freq_term = torch.exp(torch.arange(0, d_model, 2).float() * \<br>                -(math.log(10000.0) / d_model))<br>    # pe[:, 0::2] shape: (max_seq_len, d_model/2)<br>    pe[:, 0::2] = torch.sin(position * freq_term)<br>    # pe[:, 1::2] shape: (max_seq_len, d_model/2)<br>    pe[:, 1::2] = torch.cos(position * freq_term)<br><br>    # register_buffer saves pe in state_dict of model <br>    # along with other trainable parameters.<br>    # Now, pe shape becomes (1, max_seq_len, d_model)<br>    self.register_buffer(&#39;pe&#39;, pe.unsqueeze(0))<br>    <br>  def forward(self, x):<br>    &quot;&quot;&quot;<br>    Add positional encoding to input sequences or output sequences<br>    x: input sequences or output sequences<br>    &quot;&quot;&quot;<br>    # Get positional encoding up to the length of input/output sequences<br>    return x + self.pe[:, :x.size(1)]</pre><h4>Transformer</h4><p>The overall transformer code is as follows. The code includes a function <strong>generate_masks</strong> that generates masks for different kinds of attentions used in the transformer.</p><pre>class Transformer(torch.nn.Module):<br>  def __init__(self, src_vocab_size, tgt_vocab_size,<br>               d_model, num_heads, num_layers, d_ff,<br>               max_seq_len, dropout):<br>    &quot;&quot;&quot;<br>    src_vocab_size: vocabulary size of input sequences<br>    tgt_vocab_size: vocabulary size of output sequences<br>    d_model: dimension of model embedding<br>    num_heads: number of attention heads<br>    num_layers: number of encoder/decoder layers<br>    d_ff: dimension of feedforward embedding<br>    max_seq_len: maximum length of generated positional encoding<br>    dropout: dropout rate<br>    &quot;&quot;&quot;<br>    super(Transformer, self).__init__()<br>    # Input and output embeddings<br>    self.encoder_embedding = torch.nn.Embedding(src_vocab_size, d_model)<br>    self.decoder_embedding = torch.nn.Embedding(tgt_vocab_size, d_model)<br>    <br>    # Positional encoding<br>    self.positional_encoding = PositionalEncoding(d_model, max_seq_len)<br>    <br>    # Encoder layers<br>    self.encoder_layers = torch.nn.ModuleList([<br>        EncoderLayer(d_model, num_heads, d_ff, dropout) \<br>          for _ in range(num_layers)<br>      ]<br>    )<br><br>    # Decoder layers<br>    self.decoder_layers = torch.nn.ModuleList([<br>        DecoderLayer(d_model, num_heads, d_ff, dropout) \<br>          for _ in range(num_layers)<br>      ]<br>    )<br>    <br>    # Linear layer for output<br>    self.fc = torch.nn.Linear(d_model, tgt_vocab_size)<br><br>    # Dropout<br>    self.dropout = torch.nn.Dropout(dropout)<br><br>  def generate_mask(self, src, tgt):<br>    &quot;&quot;&quot;<br>    src: input sequences, shape: (bs, src_seq_len)<br>    tgt: output sequences, shape: (bs, tgt_seq_len)<br>    Returns: <br>      mask for self-attention in encoder and <br>        cross-attention in decoder (all 1s)<br>      mask for masked self-attention in decoder<br>    &quot;&quot;&quot;<br>    # src_mask shape: (bs, 1, 1, src_seq_len), all elements are 1<br>    src_mask = torch.ones_like(src).unsqueeze(1).unsqueeze(2)<br>    # tgt_mask shape: (bs, 1, tgt_seq_len, 1)<br>    tgt_mask = torch.ones_like(tgt).unsqueeze(1).unsqueeze(3)<br>    tgt_seq_len = tgt.size(1)<br>    # nopeak_mask shape: (1, tgt_seq_len, tgt_seq_len)<br>    nopeak_mask = (1 - torch.triu(torch.ones(1, tgt_seq_len, tgt_seq_len),<br>                                  diagonal=1)).bool()<br>    nopeak_mask = nopeak_mask.to(src.device)<br>    # tgt_mask shape becomes (bs, 1, tgt_seq_len, tgt_seq_len)<br>    # due to broadcasting<br>    tgt_mask = tgt_mask &amp; nopeak_mask<br>    return src_mask, tgt_mask<br>  <br>  def forward(self, src, tgt):<br>    &quot;&quot;&quot;<br>    src: input sequences, shape: (bs, src_seq_len)<br>    tgt: output sequences, shape: (bs, tgt_seq_len)<br>    &quot;&quot;&quot;<br>    # Generate masks for encoder and decoder<br>    # src_mask shape: (bs, 1, 1, src_seq_len)<br>    # tgt_mask shape: (bs, 1, tgt_seq_len, tgt_seq_len)<br>    src_mask, tgt_mask = self.generate_mask(src, tgt)<br>    <br>    # Embeddings of input sequences<br>    # src_emb shape: (bs, src_seq_len, d_model)<br>    src_emb = self.dropout(<br>      self.positional_encoding(self.encoder_embedding(src))<br>    )<br><br>    # Embeddings of output sequences<br>    # tgt_emb shape: (bs, tgt_seq_len, d_model)<br>    tgt_emb = self.dropout(<br>      self.positional_encoding(self.decoder_embedding(tgt))<br>    )<br><br>    # Transformer encoder<br>    # enc_output shape: (bs, src_seq_len, d_model)<br>    enc_output = src_emb<br>    for enc_layer in self.encoder_layers:<br>      enc_output = enc_layer(enc_output, src_mask)<br><br>    # Transformer decoder<br>    # dec_output shape: (bs, tgt_seq_len, d_model)<br>    dec_output = tgt_emb<br>    for dec_layer in self.decoder_layers:<br>      # both src_mask and tgt_mask are passed to decoder layer<br>      # src_mask is passed to self-attention in decoder layer<br>      # tgt_mask is passed to cross-attention in decoder layer<br>      dec_output = dec_layer(dec_output, enc_output, src_mask, tgt_mask)<br><br>    # Linear layer<br>    #output shape: (bs, tgt_seq_len, tgt_vocab_size)<br>    output = self.fc(dec_output)<br><br>    return output</pre><h4>Training</h4><p>The code for training the transformer is as follows.</p><pre># Data and model configurations<br>src_vocab_size = 4000<br>tgt_vocab_size = 5000<br>max_seq_len = 100<br>src_seq_len = 50<br>tgt_seq_len = 60<br>d_model = 512<br>num_heads = 8<br>num_layers = 6<br>d_ff = 2048<br>dropout = 0.1<br>batch_size = 64<br>lr = 1e-4<br>beta1 = 0.9<br>beta2 = 0.98<br>eps = 1e-9<br>epochs = 10<br><br># Create transformer model<br>transformer = Transformer(src_vocab_size, tgt_vocab_size, <br>                          d_model, num_heads, num_layers, <br>                          d_ff, max_seq_len, dropout)<br><br># Dummy data used in each training iteration (to be replaced with real data)<br># src_data shape: (batch_size, src_seq_length)<br>src_data = torch.randint(0, src_vocab_size, (batch_size, src_seq_len))<br># tgt_data shape: (batch_size, tgt_seq_length)<br>tgt_data = torch.randint(0, tgt_vocab_size, (batch_size, tgt_seq_len))<br><br># Loss<br>criterion = torch.nn.CrossEntropyLoss()<br><br># Optimizer<br>optimizer = torch.optim.Adam(transformer.parameters(),<br>                             lr=lr,<br>                             betas=(beta1, beta2),<br>                             eps=eps)<br><br># Device<br>device = torch.device(&quot;cuda:0&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br>transformer.to(device)<br>src_data = src_data.to(device)<br>tgt_data = tgt_data.to(device)<br><br># Training loop<br>for epoch in range(epochs):<br>  optimizer.zero_grad()<br>  output = transformer(src_data, tgt_data[:, :-1])<br>  loss = criterion(output.contiguous().view(-1, tgt_vocab_size),<br>                   tgt_data[:, 1:].contiguous().view(-1))<br>  loss.backward()<br>  optimizer.step()<br>  print(f&quot;Epoch: {epoch+1}, Loss: {loss.item()}&quot;)</pre><h3>Conclusions</h3><p>In this post, I gave a detailed introduction to the transformer through the tensor shapes and the PyTorch implementation. I hope the post helps you understand the concepts and computations of the transformer, which further helps you study the LLMs built on top of the transformer.</p><p>Thanks for spending time reading the post!</p><h3>References</h3><p>[1] A. Vaswani, et. al, “Attention is All You Need”, <a href="https://arxiv.org/pdf/1706.03762.pdf">https://arxiv.org/pdf/1706.03762.pdf</a>.</p><h4><a href="https://mlearning.substack.com/about">WRITER at MLearning.ai</a> / <a href="https://open.substack.com/pub/mlearning/p/ai-act-safe-prompts-practical-examples-europe?r=z7zu8&amp;utm_campaign=post&amp;utm_medium=web">🇪🇺 NEW Europe AI Act</a> / <a href="https://open.substack.com/pub/mlearning/p/20k-ai-art-prompts-generator-guide-collection?r=z7zu8&amp;utm_campaign=post&amp;utm_medium=web">20K+ Art Prompts</a></h4><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74fdff967de6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deployment of PyTorch Model Using NCNN for Mobile Devices — Part 2]]></title>
            <link>https://medium.com/@freshtechyy/deployment-of-pytorch-model-using-ncnn-for-mobile-devices-part-2-ff28e9aaf0d6?source=rss-81e2a307d7db------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff28e9aaf0d6</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[deployment-model]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <dc:creator><![CDATA[Huili Yu]]></dc:creator>
            <pubDate>Tue, 16 May 2023 20:06:35 GMT</pubDate>
            <atom:updated>2023-05-16T20:06:35.167Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deployment of PyTorch Model Using NCNN for Mobile Devices — Part 2</h3><p>An introductory example of deploying a pretrained PyTorch model into an Android app using NCNN for mobile devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*Ssp31LOpODHDkOHMitL6tg.png" /><figcaption>Deployment of deep neural network on mobile phone. (a) image by author, (b) image by author, (c) image from “Attention is All You Need” Vaswani et al. [1], (d) image by Shiwa ID on <a href="https://unsplash.com/@shiwa_id">Unsplash</a>.</figcaption></figure><h4>Introduction</h4><p>As more and more deep neural networks, like CNNs, Transformers, and Large Language Models (LLMs), generative models, etc., have been developed to increase the level of artificial intelligence (AI), it is also important to deploy the deep neural networks to mobile devices, like smart phones, AR glasses, etc., to boost the usages of the deep neural networks in our lives.</p><p>In <a href="https://medium.com/mlearning-ai/deployment-of-pytorch-model-using-ncnn-bceff5d846b0">my previous post</a>, I gave an introductory example about deploying a pretrained PyTorch model into a C++ app using NCNN. In this post, I will talk about how to integrate the C++ app into an Android app for a mobile phone. Assuming that you have read my previous post “<a href="https://medium.com/mlearning-ai/deployment-of-pytorch-model-using-ncnn-bceff5d846b0">Deployment of PyTorch Model Using NCNN for Mobile Device — Part 1</a>” that talks about how to generate the NCNN model from the PyTorch model and how to make an C++ app that loads the NCNN model and performs inference, I will start with the generated C++ app and the NCNN model, and integrate them into an Android app for the mobile phone. I will continue to use the image classification example discussed in my previous post.</p><h4>Environment setup</h4><p>Let’s first set up the environment, including installation and set up of Android Studio, NDK (Native Development Kit), OpenCV for Android, and NCNN for Android.</p><p>Android studio can be installed by following <a href="https://developer.android.com/studio/install">Android Studio installation page</a>[2]. I create a new Native C++ app and select Java as the language for the image classification app. Then I install and set up necessary libraries, including OpenCV for Android and NCNN Android, and integrate the image classification C++ inference code into the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lqiHqCopWJSJBnY3aZuTDg.png" /><figcaption>Project structure of image classification app — image by author.</figcaption></figure><p>As shown in the figure above, the app consists of the following files and necessary libraries.</p><ul><li><strong>OpenCV-android-sdk</strong>. It is used for loading input images.</li><li><strong>ncnn-20230223-android-vulkan</strong>. It is the NCNN library for performing inference.</li><li><strong>CMakeLists.txt</strong>. It is automatically generated by Android Studio. But we need to modify it to compile the app.</li><li><strong>native-lib.cpp</strong>. A C++ source file is called by Java code using Java Native Interface (JNI). It is the entry point of native C++ code in the app.</li><li><strong>inference.h</strong> and <strong>inference.cpp</strong>. They are the source and header files for the image classification inference function, and the function is called by native-lib.cpp.</li><li><strong>MainActivity.java</strong>. It is a Java class file in an Android app that serves as the main entry point for the app’s user interface. It calls the native functions defined in native-lib.cpp.</li><li><strong>activity_main.xml</strong>. It shows the user interface components for visualizing the image classification result.</li><li>Model files. The NCNN model files are placed in the “asset” folder.</li><li>Input files. The input image files are placed in the “drawable” folder.</li></ul><p>To write native code in Android, we need to first install Native Development Kit (NDK). NDK is a set of tools that allows us to write and use native C or C++ code in Android applications. NDK can be installed via Android Studio by following <strong>Tools -&gt; SDK Managers -&gt; SDK Tools</strong>. A Settings window pops up and NDK can be installed by selecting the <strong>NDK</strong> checkbox and clicking<strong> </strong>the<strong> Apply</strong> button.</p><figure><img alt="NDK installation" src="https://cdn-images-1.medium.com/max/950/1*V1LAwGaun9tx_t2VZ7dHjA.png" /><figcaption>NDK installation — image by author.</figcaption></figure><p>OpenCV Android can be downloaded and set up in Android by the following steps.</p><ul><li>Download Android release of OpenCV from <a href="https://opencv.org/releases/">https://opencv.org/releases/</a>;</li><li>Extract it and move the subfolder <strong>OpenCV-android-sdk</strong> under it into app/src/main/cpp in the image classification app that we are making;</li><li>Set <strong>OpenCV_DIR</strong> in app/src/main/cpp/CMakeLists.txt.</li></ul><p>Similiarly, NCNN Android can be downloaded and set up in Android by the following steps.</p><ul><li>Download <strong>ncnn-android-vulkan</strong> from <a href="https://github.com/Tencent/ncnn/releases">https://github.com/Tencent/ncnn/releases</a>, e.g. ncnn-20230223-android-vulkan.zip;</li><li>Extract it into app/src/main/cpp;</li><li>Set the <strong>ncnn_DIR</strong> path in app/src/main/cpp/CMakeLists.txt.</li></ul><p>After installing the necessary libraries, I make <strong>inference.h</strong> and <strong>inference.cpp</strong>.</p><pre>/**<br> * inference.h<br> */<br>#ifndef IMAGECLASSIFICATION_INFERENCE_H<br>#define IMAGECLASSIFICATION_INFERENCE_H<br><br>#include &lt;opencv2/core.hpp&gt;<br>#include &lt;android/asset_manager.h&gt;<br><br>/**<br> * @brief Perform inference for classifying a given image using the NCNN model.<br> * @param src: input image in OpenCV Mat format.<br> * @param mgr: AAssetManager pointer for loading NCNN model files in assets folder.<br> * @return the predicted class<br> */<br>std::string Inference(cv::Mat&amp; src, AAssetManager* mgr);<br><br>#endif //IMAGECLASSIFICATION_INFERENCE_H</pre><pre>/**<br> * inference.cpp<br> */<br>#include &lt;algorithm&gt;<br>#include &lt;vector&gt;<br>#include &lt;string&gt;<br><br>#include &lt;opencv2/imgproc.hpp&gt;<br><br>#include &quot;net.h&quot;<br>#include &quot;inference.h&quot;<br><br>// Perform inference for classifying a given image using the NCNN model<br>std::string Inference(cv::Mat&amp; src, AAssetManager* mgr) {<br>    std::vector&lt;std::string&gt; classes = {&quot;plane&quot;, &quot;car&quot;,  &quot;bird&quot;, &quot;cat&quot;,<br>                                        &quot;deer&quot;,  &quot;dog&quot;,  &quot;frog&quot;, &quot;horse&quot;,<br>                                        &quot;ship&quot;,  &quot;truck&quot;};<br><br>    // Load model<br>    ncnn::Net net;<br>    int ret = net.load_param(mgr, &quot;image_classifier_opt.param&quot;);<br>    if (ret) {<br>        __android_log_print(ANDROID_LOG_ERROR, &quot;load_param_error&quot;,<br>                            &quot;Failed to load the model parameters&quot;);<br>    }<br>    ret = net.load_model(mgr,&quot;image_classifier_opt.bin&quot;);<br>    if (ret) {<br>        __android_log_print(ANDROID_LOG_ERROR, &quot;load_weight_error&quot;,<br>                            &quot;Failed to load the model weights&quot;);<br>    }<br><br>    // Convert image data to ncnn format<br>    // opencv image in bgr, model needs rgb<br>    ncnn::Mat input = ncnn::Mat::from_pixels(src.data,<br>                                             ncnn::Mat::PIXEL_BGR2RGB,<br>                                             src.cols, src.rows);<br><br>    // Data preprocessing (normalization)<br>    const float mean_vals[3] = {0.4914f*255.f,<br>                                0.4822f*255.f,<br>                                0.4465f*255.f};<br>    const float norm_vals[3] = {1/0.2470f/255.f,<br>                                1/0.2435f/255.f,<br>                                1/0.2616f/255.f};<br>    // In ncnn, substract_mean_normalize needs input pixels in [0, 255]<br>    input.substract_mean_normalize(mean_vals, norm_vals);<br><br>    // Inference<br>    ncnn::Extractor extractor = net.create_extractor();<br>    extractor.input(&quot;input&quot;, input);<br>    ncnn::Mat C2, C3, C4, C5, output;<br>    extractor.extract(&quot;output&quot;, output);<br><br>    // Flatten<br>    ncnn::Mat out_flatterned = output.reshape(output.w * output.h * output.c);<br>    std::vector&lt;float&gt; scores;<br>    scores.resize(out_flatterned.w);<br>    for (int j=0; j&lt;out_flatterned.w; j++) {<br>        scores[j] = out_flatterned[j];<br>    }<br><br>    // Get predicted class<br>    std::string pred_class = classes[std::max_element(scores.begin(),<br>        scores.end()) - scores.begin()];<br>    return pred_class;<br>}</pre><p>The inference function is called by <strong>native-lib.cpp</strong>.</p><pre>/**<br> * native-lib.cpp<br> */<br>#include &lt;jni.h&gt;<br>#include &lt;string&gt;<br>#include &lt;android/bitmap.h&gt;<br>#include &lt;opencv2/core.hpp&gt;<br>#include &lt;opencv2/imgproc.hpp&gt;<br>#include &lt;android/log.h&gt;<br>#include &lt;android/asset_manager.h&gt;<br>#include &lt;android/asset_manager_jni.h&gt;<br>#include &quot;inference.h&quot;<br><br>/**<br> * @brief Convert input image from bitmap to OpenCV Mat.<br> * @tparam env: JNIEnv pointer.<br> * @tparam bitmap: input image in bitmap format.<br> * @param bst: output input image in OpenCV format.<br> * @param needUnPremultiplyAlpha: boolean variable to convert image color space<br> */<br>void Bitmap2Mat(JNIEnv * env, jobject bitmap, <br>                cv::Mat&amp; dst, jboolean needUnPremultiplyAlpha) {<br>    AndroidBitmapInfo  info;    // uses jnigraphics<br>    void*              pixels = 0;<br><br>    CV_Assert( AndroidBitmap_getInfo(env, bitmap, &amp;info) &gt;= 0 );<br>    CV_Assert( info.format == ANDROID_BITMAP_FORMAT_RGBA_8888 ||<br>               info.format == ANDROID_BITMAP_FORMAT_RGB_565 );<br>    CV_Assert( AndroidBitmap_lockPixels(env, bitmap, &amp;pixels) &gt;= 0 );<br>    CV_Assert( pixels );<br>    dst.create(info.height, info.width, CV_8UC4);<br>    if( info.format == ANDROID_BITMAP_FORMAT_RGBA_8888 )<br>    {<br>        cv::Mat tmp(info.height, info.width, CV_8UC4, pixels);<br>        if(needUnPremultiplyAlpha) cvtColor(tmp, dst, cv::COLOR_mRGBA2RGBA);<br>        else tmp.copyTo(dst);<br>    } else {<br>        cv::Mat tmp(info.height, info.width, CV_8UC2, pixels);<br>        cvtColor(tmp, dst, cv::COLOR_BGR5652RGBA);<br>    }<br>    AndroidBitmap_unlockPixels(env, bitmap);<br>    return;<br>}<br><br>/**<br> * @brief Entry point of C++ code and MainActivity.java will call this function.<br> * @tparam env: JNIEnv pointer.<br> * @tparam bitmapIn: input image in bitmap format.<br> * @param assetManager: AssetManager object for loading NCNN model files in assets folder.<br> * @Return predicted class.<br> */<br>extern &quot;C&quot; JNIEXPORT jstring JNICALL<br>Java_com_example_imageclassification_MainActivity_ImageClassification(<br>        JNIEnv* env,<br>        jobject,<br>        jobject bitmapIn,<br>        jobject assetManager) {<br>    cv::Mat src;<br>    Bitmap2Mat(env, bitmapIn, src, false);   // Convert bitmap to OpenCV Mat<br>    cv::Mat resized_src;<br>    cv::resize(src, resized_src, cv::Size(32, 32), cv::INTER_LINEAR);<br>    cv::cvtColor(resized_src, resized_src, cv::COLOR_RGBA2RGB);<br><br>    AAssetManager* mgr = AAssetManager_fromJava(env, assetManager);<br>    std::string pred_class = Inference(resized_src, mgr);    // Image classification<br>    return env-&gt;NewStringUTF(pred_class.c_str());<br>}</pre><p>Given all the C++ files, I make the <strong>CMakeLists.txt</strong> file.</p><pre># For more information about using CMake with Android Studio, read the<br># documentation: https://d.android.com/studio/projects/add-native-code.html<br><br># Sets the minimum version of CMake required to build the native library.<br>cmake_minimum_required(VERSION 3.22.1)<br><br># Declares and names the project.<br>project(&quot;imageclassification&quot;)<br><br># Creates and names a library, sets it as either STATIC<br># or SHARED, and provides the relative paths to its source code.<br># You can define multiple libraries, and CMake builds them for you.<br># Gradle automatically packages shared libraries with your APK.<br><br># OpenCV<br>set(OpenCV_STATIC on)<br>set(OpenCV_DIR ${CMAKE_SOURCE_DIR}/OpenCV--android--sdk/sdk/native/jni)<br>find_package(OpenCV REQUIRED)<br><br>set(ncnn_DIR ${CMAKE_SOURCE_DIR}/ncnn--20230223--android--vulkan/${ANDROID_ABI}/lib/cmake/ncnn)<br>find_package(ncnn REQUIRED)<br><br>add_library( # Sets the name of the library.<br>        imageclassification<br><br>        # Sets the library as a shared library.<br>        SHARED<br><br>        # Provides a relative path to your source file(s).<br>        inference.cpp<br>        native--lib.cpp)<br><br># Searches for a specified prebuilt library and stores the path as a<br># variable. Because CMake includes system libraries in the search path by<br># default, you only need to specify the name of the public NDK library<br># you want to add. CMake verifies that the library exists before<br># completing its build.<br><br>find_library( # Sets the name of the path variable.<br>        log--lib<br><br>        # Specifies the name of the NDK library that<br>        # you want CMake to locate.<br>        log)<br>find_library(jnigraphics--lib jnigraphics)<br># Specifies libraries CMake should link to your target library. You<br># can link multiple libraries, such as libraries you define in this<br># build script, prebuilt third--party libraries, or system libraries.<br><br>target_link_libraries( # Specifies the target library.<br>        imageclassification<br><br>        # Links the target library to the log library<br>        # included in the NDK.<br>        ncnn<br>        ${OpenCV_LIBS}<br>        ${jnigraphics--lib}<br>        ${log--lib})</pre><p>After finishing the native code, I add the code in the <strong>MainActivity.java</strong> file that calls the native code to get the classification result and display the result in the user interface.</p><pre>package com.example.imageclassification;<br><br>import androidx.appcompat.app.AppCompatActivity;<br>import android.content.res.AssetManager;<br>import android.content.res.Resources;<br>import android.graphics.Bitmap;<br>import android.graphics.BitmapFactory;<br>import android.os.Bundle;<br>import android.view.View;<br>import android.widget.Button;<br>import android.widget.TextView;<br><br>import com.example.imageclassification.databinding.ActivityMainBinding;<br><br>public class MainActivity extends AppCompatActivity {<br><br>    // Used to load the &#39;imageclassification&#39; library on application startup.<br>    static {<br>        System.loadLibrary(&quot;imageclassification&quot;);<br>    }<br><br>    private ActivityMainBinding binding;<br><br>    @Override<br>    protected void onCreate(Bundle savedInstanceState) {<br>        super.onCreate(savedInstanceState);<br><br>        binding = ActivityMainBinding.inflate(getLayoutInflater());<br>        setContentView(binding.getRoot());<br><br>        Button btn_classify = (Button) findViewById(R.id.btn_classify);<br>        btn_classify.setOnClickListener(new View.OnClickListener() {<br>            public void onClick(View v) {<br>                Resources res = getResources();<br>                Bitmap bitmapIn = <br>                  BitmapFactory.decodeResource(res, R.drawable.car);<br>                TextView pred = (TextView) findViewById(R.id.textView);<br>                pred.setText(ImageClassification(bitmapIn, getAssets()));<br>            }<br>        });<br>    }<br><br>    /**<br>     * A native method that is implemented by the &#39;imageclassification&#39; native library,<br>     * which is packaged with this application.<br>     */<br>    public native String ImageClassification(Bitmap bitmapIn, <br>                                             AssetManager assetManager);<br>}</pre><p>With all the files being created, the app can be built by doing (<strong>Build-&gt;Make Project</strong>) and run by clicking <strong>Run ’app’</strong> button in Android Studio. You will first see the left image below, and then by clicking the “CLASSIFY” button, you will see that the car image is successfully classified into the car object.</p><figure><img alt="Image classification result" src="https://cdn-images-1.medium.com/max/1024/1*fia_mig2zOWUm05hTwWyzA.png" /><figcaption>Image classification result — image by author.</figcaption></figure><p>The complete implementation of the code deployment into Android is available from the <a href="https://github.com/freshtechyy/NCNN-Android-image-classification-example"><strong>Github</strong></a>.</p><h4>Conclusions</h4><p>In this post, I discussed how to integrate the C++ code with the NCNN inference engine into Android for model deployment on the mobile phone. My discussions cover all the necessary steps to make the deployment working, including Android Studio installation, NDK installation in Android, OpenCV and NCNN setup in Android, how to integrate the C++ inference code with NCNN into Android, and how to make CMakeLists.txt to compile the C++ code in Android, and how to modify MainActivity.java to call the C++ inference code.</p><p>I hope this post together with my previous posts <a href="https://medium.com/mlearning-ai/deployment-of-pytorch-model-using-ncnn-bceff5d846b0">here</a> and <a href="https://medium.com/@freshtechyy/deploying-pytorch-model-into-a-c-application-using-onnx-runtime-f9967406564b">here</a> provide you an end-to-end pipeline of deploying a pretrained PyTorch model into Android for model deployment on mobile devices. You can easily tailor the pipeline for deploying your deep learning models on mobile devices. Hope these series of posts help. Thanks for reading.</p><h4>References</h4><p>[1] Vaswani et al., Attention is All You Need, Dec. 2017.</p><p>[2] Android. https://developer.android.com/studio/install, 2023.</p><p>[3] Tencent, NVIDIA CUDA Convolutional Neural Network, <a href="https://github.com/tencent/ncnn">https://github.com/tencent/ncnn</a>, 2019.</p><h4><a href="https://open.substack.com/pub/mlearning/p/ai-app-development-machine-learning-innovation?r=z7zu8&amp;utm_campaign=post&amp;utm_medium=web"><strong>BECOME</strong></a><strong> a WRITER at </strong><a href="https://mlearning.substack.com/"><strong>MLearning.ai</strong></a><strong>. </strong><a href="https://open.substack.com/pub/mlearning/p/local-machine-no-cloud-private-ai-gpt-cpu-gpu?r=z7zu8&amp;utm_campaign=post&amp;utm_medium=web">Local AI Solutions</a></h4><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff28e9aaf0d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deployment of PyTorch Model Using NCNN for Mobile Devices — Part 1]]></title>
            <link>https://medium.com/@freshtechyy/deployment-of-pytorch-model-using-ncnn-bceff5d846b0?source=rss-81e2a307d7db------2</link>
            <guid isPermaLink="false">https://medium.com/p/bceff5d846b0</guid>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[ncnn]]></category>
            <category><![CDATA[ai-model-deployment]]></category>
            <dc:creator><![CDATA[Huili Yu]]></dc:creator>
            <pubDate>Thu, 04 May 2023 23:33:59 GMT</pubDate>
            <atom:updated>2023-05-16T01:24:48.267Z</atom:updated>
            <content:encoded><![CDATA[<p>An introductory example of deploying a pretrained PyTorch model into a C++ app using NCNN for mobile devices.</p><figure><img alt="Network deployment on mobile phone." src="https://cdn-images-1.medium.com/max/699/1*Ssp31LOpODHDkOHMitL6tg.png" /><figcaption>Deployment of deep neural network on mobile phone. (a) image by author, (b) image by author, (c) image from “Attention is All You Need” Vaswani et al. [1], (d) image by Shiwa ID on <a href="https://unsplash.com/@shiwa_id">Unsplash</a>.</figcaption></figure><h4>Introduction</h4><p>Many deep learning models, like CNNs, Transformers, etc., have been developed today, and Large Language Models (LLMs), like ChatGPT, greatly boost the level of model intelligence. To increase their usages in real life, it is important to explore how to deploy the models to mobile devices, like smart phones, AR glasses, etc. So, this article is to provide an introductory example about how to deploy a pretrained PyTorch model into a C++ app using NCNN, which can be further integrated into Android for mobile devices.</p><p>In particular, I like to discuss the following contents.</p><ul><li>What is NCNN?</li><li>Pipeline of deploying a pretrained PyTorch model into a C++ app using using NCNN.</li><li>An introductory example of deploying the pretrained PyTorch model into the C++ app using NCNN.</li></ul><h4>NCNN (Neural Network Computing Library)</h4><p>NCNN is a high-performance neural network inference framework developed by Tencent, which is designed specifically for mobile and embedded devices [2]. NCNN is lightweight and efficient, making it an ideal choice for deploying deep learning models on devices with limited computational resources.</p><p>The model of the NCNN consists of two files: .param and .bin. The .param file contains the model structure and parameter information, including layer types, layer names, layer parameters, and input/output shapes. This file is typically a lightweight text file that can be easily parsed and loaded by the NCNN framework.</p><p>The .bin file contains the trained model weights in binary format. These weights are learned during the training process and are used to make predictions during inference. The .bin file is usually much larger than the .param file, as it contains the actual numerical values of the learned parameters.</p><h4>Pipeline of deploying a pretrained PyTorch model into C++ app using NCNN</h4><figure><img alt="PyTorch model deployment pipeline using NCNN" src="https://cdn-images-1.medium.com/max/1005/1*pY6TQSr7JZisGdogyM-esA.png" /><figcaption>Pipeline of deploying a pretrained PyTorch model into C++ app using NCNN — image by author.</figcaption></figure><p>For the deployment, a pretrained PyTorch model (.pth/.pt) is first converted to an ONNX file (.onnx) in PyTorch. Then the .onnx model file will be converted by the NCNN converter to the NCNN model consisting of two files: a .param file and a .bin file. Finally, the NCNN model files are loaded by a C++ code to perform the inference using the NCNN library. The C++ code can be further integrated into Android to perform inference on mobile devices. In this post, I focus my discussion on the deployment of the NCNN model on a Linux (Ubuntu) computer. I will talk about the integration of the C++ inference code into Android in my next post.</p><h4>Conversion to ONNX file</h4><p>In my previous post, <a href="https://medium.com/@freshtechyy/deploying-pytorch-model-into-a-c-application-using-onnx-runtime-f9967406564b">Deploying PyTorch Model into a C++ Application Using ONNX Runtime</a>, I discussed how to convert a PyTorch pretrained model to an ONNX file using <strong>torch.onnx.export</strong> function in PyTorch. For more detailed information about ONNX and the conversion, please refer to my previous post.</p><pre>torch.onnx.export(net,       # model being run       <br>                  x,         # model input<br>                  &quot;model.onnx&quot;,  # where to save the model<br>                  export_params=True, # store the trained weights<br>                  opset_version=11,   # the ONNX version<br>                  do_constant_folding=True,<br>                  input_names= [&#39;input&#39;], # set model input names    <br>                  output_names=[&#39;output&#39;], # set model output names<br>)</pre><h4>An end-to-end example of deploying the pretrained PyTorch model into C++ app using NCNN</h4><p>I still use the <a href="https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html">PyTorch tutorial image classification example for CIFAR10 dataset</a> [3], discussed in <a href="https://medium.com/@freshtechyy/deploying-pytorch-model-into-a-c-application-using-onnx-runtime-f9967406564b">my previous post</a>, to explain how to use NCNN to do the deployment. My explanation starts from the point where <strong>image_classifier.onnx </strong>has been generated by PyTorch. Next step is to convert <strong>image_classifier.onnx</strong> to the model format required by NCNN.</p><p>To use NCNN, I first install and set up NCNN in Ubuntu. Below are the steps of installing NCNN.</p><pre>git clone https://github.com/Tencent/ncnn.git<br>cd ncnn<br>mkdir -p build<br>cd build<br>cmake -DCMAKE_BUILD_TYPE=Release -DNCNN_VULKAN=OFF \ <br>-DNCNN_SYSTEM_GLSLANG=ON -DNCNN_BUILD_EXAMPLES=ON \<br>-DNCNN_SHARED_LIB=ON ..<br>make<br>make install</pre><p>After NCNN has been installed, two useful tools <strong>onnx2ncnn </strong>and <strong>ncnnoptimize</strong> are generated in <strong>ncnn_root/build/tools/onnx/</strong> and <strong>ncnn_root/build/tools/</strong>, respectively, where <strong>ncnn_root</strong> is the root directory of NCNN.</p><p>For this example, I will create the following file tree and I put all the model files to the <strong>models </strong>subdirectory<strong>.</strong></p><figure><img alt="file tree" src="https://cdn-images-1.medium.com/max/524/1*gsjUIUzHExDU5QPPrxCWIg.png" /><figcaption>File tree of the root directory of the image classification example — image by author.</figcaption></figure><p>I copy <strong>onnx2ncnn</strong> and <strong>ncnnoptimize</strong> to the root directory of this example. In the root directory, I convert the ONNX model to the NCNN model by executing the following commands.</p><pre>python3 -m onnxsim models/image_classifier.onnx \<br>models/image_classifier_sim.onnx<br>./onnx2ncnn models/image_classifier_sim.onnx \<br>models/image_classifier.param models/image_classifier.bin<br>./ncnnoptimize models/image_classifier.param models/image_classifier.bin \<br>models/image_classifier_opt.param models/image_classifier_opt.bin 65536</pre><p>Among the above commands, the ONNX model is first optimized by <strong>onnxsim</strong> to generate an optimized ONNX model with faster execution time and lower memory usage. The optimized ONNX model is then converted to the NCNN model by <strong>onnx2ncnn</strong>. Finally, the NCNN model is further optimized by <strong>ncnnoptimize</strong> to reduce size and complexity while maintaining accuracy for deployment on mobile and embedded devices. The number 65536 is the maximum input image size that the optimized model can handle.</p><p>With the optimized NCNN model, I write the C++ inference code for performing image classification. I first make the CMakeLists.txt file for compiling the project. To use NCNN, I specify the include and the link directories of NCNN. Also, since OpenCV is used to load the input image and visualize results, I set up OpenCV in <strong>CMakeLists.txt</strong> too (assuming OpenCV has been installed).</p><figure><img alt="NCNN_cmake" src="https://cdn-images-1.medium.com/max/1024/1*lcl8IlcHoq84zIC8L-JPxA.png" /><figcaption>CMakeLists.txt — image by author.</figcaption></figure><p>Now, it is time to make <strong>image_classifier.cpp</strong>.</p><pre>#include &lt;iostream&gt;<br>#include &lt;fstream&gt;<br>#include &lt;stdio.h&gt;<br>#include &lt;algorithm&gt;<br>#include &lt;vector&gt;<br>#include &lt;string&gt;<br>    <br>#include &lt;opencv2/core/core.hpp&gt;<br>#include &lt;opencv2/highgui/highgui.hpp&gt;<br>#include &lt;opencv2/imgproc/imgproc.hpp&gt;<br>    <br>#include &quot;net.h&quot;    // must include this file in order to use NCNN net.<br>    <br>int main(int argc, char** argv) {<br>    // Load image<br>    std::string imagepath(&quot;../images/horse.png&quot;);<br>    cv::Mat img = cv::imread(imagepath, cv::IMREAD_COLOR);<br>    if (img.empty()) {<br>        std::cerr &lt;&lt; &quot;Unable to read image file &quot; &lt;&lt; imagepath &lt;&lt; std::endl;<br>        return -1;<br>    }<br>    <br>    // Specify the names of all classes for image classification<br>    std::vector&lt;std::string&gt; classes = {&quot;plane&quot;, &quot;car&quot;,  &quot;bird&quot;, &quot;cat&quot;,<br>                                        &quot;deer&quot;,  &quot;dog&quot;,  &quot;frog&quot;, &quot;horse&quot;,<br>                                        &quot;ship&quot;,  &quot;truck&quot;};<br>    <br>    // Load NCNN model<br>    ncnn::Net net;<br>    int ret = net.load_param(&quot;../models/image_classifier_opt.param&quot;);<br>    if (ret) std::cerr &lt;&lt; &quot;Failed to load model parameters&quot; &lt;&lt; std::endl; <br>    ret = net.load_model(&quot;../models/image_classifier_opt.bin&quot;);<br>    if (ret) std::cerr &lt;&lt; &quot;Failed to load model weights&quot; &lt;&lt; std::endl;<br>    <br>    // Convert image data to ncnn format<br>    // opencv image in bgr, model needs bgr<br>    ncnn::Mat input = ncnn::Mat::from_pixels(img.data, <br>        ncnn::Mat::PIXEL_BGR, img.cols, img.rows);<br>    <br>    // Preprocessing of image data<br>    const float mean_vals[3] = {0.5f*255.f, 0.5f*255.f, 0.5f*255.f};<br>    const float norm_vals[3] = {1/0.5f/255.f, 1/0.5f/255.f, 1/0.5f/255.f};<br>    input.substract_mean_normalize(mean_vals, norm_vals);<br>    <br>    // Inference<br>    ncnn::Extractor extractor = net.create_extractor();<br>    extractor.input(&quot;input&quot;, input);<br>    ncnn::Mat output;<br>    extractor.extract(&quot;output&quot;, output);<br>    <br>    // Flatten<br>    ncnn::Mat out_flatterned = output.reshape(output.w * output.h * output.c);<br>    std::vector&lt;float&gt; scores;<br>    scores.resize(out_flatterned.w);<br>    for (int j=0; j&lt;out_flatterned.w; j++) {<br>        scores[j] = out_flatterned[j];<br>    }<br><br>    // Prediction based on scores<br>    std::string pred_class = <br>        classes[std::max_element(scores.begin(), <br>                                 scores.end()) - scores.begin()];<br><br>    std::cout &lt;&lt; &quot;The predicted class is &quot; &lt;&lt; pred_class &lt;&lt; &quot;.&quot; &lt;&lt; std::endl;<br><br>    // Save and visualize results<br>    cv::imwrite(&quot;../images/out_horse.png&quot;, img);<br>    cv::namedWindow(&quot;Input_image&quot;, cv::WINDOW_NORMAL);<br>    cv::imshow(&quot;Input_image&quot;, img);<br>    cv::waitKey(0);<br>    std::cout &lt;&lt; &quot;Completed&quot; &lt;&lt; std::endl;<br>    return 0;<br>}</pre><p>In <strong>image_classifier.cpp</strong>, the input image is first loaded by OpenCV. Then the NCNN model files, .param and .bin, are loaded. Note that If net.load_param and net.load_model run successfully, 0 values are returned. Otherwise, non-zero values are returned to show the loading failure.</p><pre>ncnn::Net net;<br>int ret = net.load_param(&quot;../models/image_classifier_opt.param&quot;);<br>if (ret) std::cerr &lt;&lt; &quot;Failed to load model parameters&quot; &lt;&lt; std::endl; <br>ret = net.load_model(&quot;../models/image_classifier_opt.bin&quot;);<br>if (ret) std::cerr &lt;&lt; &quot;Failed to load model weights&quot; &lt;&lt; std::endl;</pre><p>Next, the OpenCV image needs to be converted to the format NCNN requires. Since the OpenCV image is in BGR format and the model requires BGR image as the input, I use <strong>ncnn::Mat::PIXEL_BGR</strong>.</p><pre>ncnn::Mat input = ncnn::Mat::from_pixels(img.data, ncnn::Mat::PIXEL_BGR, <br>                                         img.cols, img.rows);</pre><p>In order to perform inference correctly, the image needs to be normalized in the same way, as the way used in the training phase. However, <strong>subtract_mean_normalize</strong> takes the image pixels in [0, 255] and normalizes the image pixel by <em>X * (1 / std) — mean * (1/std)</em>, where <em>X</em> stands for pixel intensity for BGR channels, <em>mean</em> is 255 ∗ [0.5, 0.5, 0.5] for BGR channels, and <em>std</em> is 255∗[0.5, 0.5, 0.5] for BGR channels, and [0.5, 0.5, 0.5] and [0.5, 0.5, 0.5] are mean and standard deviation for the image pixels in [0, 1] for the CIFAR10 dataset. Therefore, the input image is normalized in C++ as follows.</p><pre>const float mean_vals[3] = {0.5f*255.f, 0.5f*255.f, 0.5f*255.f};<br>const float norm_vals[3] = {1/0.5f/255.f, 1/0.5f/255.f, 1/0.5f/255.f};<br>input.substract_mean_normalize(mean_vals, norm_vals);</pre><p>The inference is performed by <strong>ncnn_Extractor</strong>. The names of the input node and the output node need to be provided in order to perform inference and extract the result. Since I specify the name of the input node as “input” and specified the name of the output node as “output” when I convert the PyTorch model to the ONNX model, I provide those names to <strong>ncnn_Extractor</strong>.</p><pre>ncnn::Extractor extractor = net.create_extractor();<br>extractor.input(&quot;input&quot;, input);<br>ncnn::Mat output;<br>extractor.extract(&quot;output&quot;, output);</pre><p>The inference results are then flattened to get prediction scores over the classes of the CIFAR10 dataset. The predicted class is the class with the maximum score.</p><pre>// Flatten<br>ncnn::Mat out_flatterned = output.reshape(output.w * output.h * output.c);<br>std::vector&lt;float&gt; scores;<br>scores.resize(out_flatterned.w);<br>for (int j=0; j&lt;out_flatterned.w; j++) {<br>    scores[j] = out_flatterned[j];<br>}<br><br>// Prediction based on scores<br>std::string pred_class = <br>    classes[std::max_element(scores.begin(), scores.end()) - scores.begin()];</pre><p>At this point, we are ready to compile and run the code to see the image classification result.</p><pre>mkdir build &amp;&amp; cd build<br>cmake ..<br>make<br>./image_classification</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*iYy196U8hPIh7RWD86H5_w.png" /><figcaption>Image classification result using NCNN</figcaption></figure><p>We see that the horse image is correctly classified as the horse.</p><p>The complete implementation of the deployment discussed above is available from the <a href="https://github.com/freshtechyy/NCNN-Deployment-image-classification-example"><strong>Github</strong></a>, which starts from training to the deployment into the C++ image classification using NCNN.</p><h4>Conclusions</h4><p>In this post, I gave an introductory example about deploying a pretrained PyTorch model into a C++ app using NCNN. In particular, I discussed (a) what is NCC?, (b) the pipeline of deploying a pretrained PyTorch model into the C++ app using NCNN, and (c) a concrete image classification example showing the PyTorch pretrained model deployment into the C++ app using NCNN. We see the correct image classification result using NCNN in an Ubuntu computer showing the success of the deployment.</p><p>In my next article, I will talk about how to integrate the C++ image classification code into Android for mobile device deployment. Thank you for reading.</p><h4>References</h4><p>[1] Vaswani et al., Attention is All You Need, Dec. 2017.</p><p>[2] Tencent, NVIDIA CUDA Convolutional Neural Network, <a href="https://github.com/tencent/ncnn">https://github.com/tencent/ncnn</a>, 2019.</p><p>[3] PyTorch, PyTorch tutorial on image classification example, <a href="https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html">https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html</a>, 2023</p><h4><a href="https://open.substack.com/pub/mlearning/p/alternative-chatgpt-plugins-free-browsing-alpha?r=z7zu8&amp;utm_campaign=post&amp;utm_medium=webhttps://open.substack.com/pub/mlearning/p/alternative-chatgpt-plugins-free-browsing-alpha?r=z7zu8&amp;utm_campaign=post&amp;utm_medium=web">BECOME</a> a <a href="https://mlearning.substack.com/">WRITER</a> at <a href="https://open.substack.com/pub/mlearning/p/ai-app-development-machine-learning-innovation?r=z7zu8&amp;utm_campaign=post&amp;utm_medium=web">MLearning.ai</a></h4><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bceff5d846b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Weight Initialization for Deep Neural Network]]></title>
            <link>https://medium.com/@freshtechyy/weight-initialization-for-deep-neural-network-e0302b6f5bf3?source=rss-81e2a307d7db------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0302b6f5bf3</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[weight-initialization]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[model-training]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Huili Yu]]></dc:creator>
            <pubDate>Wed, 05 Apr 2023 09:25:44 GMT</pubDate>
            <atom:updated>2023-04-05T09:25:44.569Z</atom:updated>
            <content:encoded><![CDATA[<p>A detailed introduction to the evolution of weight initialization for deep neural network.</p><p>Deep neural network consists of a large amount of weights and biases that are initialized before training and are then updated during the training. Choosing the initial values of the weights and biases has a significant impact on the training convergence and therefore model performance. In this post, I will talk about the evolution of weight initialization from the simplest strategy to the strategy that is commonly used for training a deep neural network with many layers. Then I will summarize what the initialization strategy to choose under different circumstances of training.</p><p>It is a common practice to set the initial values of the biases as 0s [1]. In this post, I will focus my discussions on weight initialization strategies.</p><h4>Constant Initialization</h4><p>The simplest way is to initialize the weights as constants, e.g., 0s. However, this way leads to several problems.</p><figure><img alt="Problems of constant weight initialization." src="https://cdn-images-1.medium.com/max/1024/1*WMAfTyHOPmckfmNaWSZUrA.png" /><figcaption>Figure 1. Vanishing gradient and symmetry problem resulting from constant weight initialization — image by author.</figcaption></figure><p>Let us first consider zero weight initialization where all weights of the network are initialized as 0s. As demonstrated in Fig. 1, all the neurons are zeros during forward propagation, and the gradients of the weights are also be 0s during back propagation, which leads to vanishing gradient.</p><p>If the weights are initialized as other non-zero constants, like 1s, all the neurons in one layer will have the same value and will represent only one feature during forward propagation. In addition, the weights will have the same gradients during backward propagation. This causes that the neurons in one network layer perform same as one neuron does during training, which makes the network fail to learn different features from the input. This problem is called the symmetry problem.</p><h4>Random Initialization</h4><p>The random initialization breaks the symmetry problem by giving random values to the weights, which makes neurons perform differently. In random initialization, the weights are drawn from a zero-mean Gaussian distribution.</p><figure><img alt="Random initialization" src="https://cdn-images-1.medium.com/max/233/1*cQjY5SIeGJvzO85svu-uNg.png" /><figcaption>Figure 2. For random initialization, weights are drawn from a zero-mean Gaussian distribution — image by author.</figcaption></figure><p>The PyTorch example code for random initialization is as follows.</p><pre>import torch.nn as nn<br>import torch.nn.init as init<br>fc = nn.Linear(in_features=784, out_features=256)<br>conv = nn.Conv2d(in_channels=3, out_channels=64, kernel_size=3)<br>init.normal_(fc.weight, mean=0.0, std=0.02)<br>init.constant_(fc.bias, 0.0)<br>init.normal_(conv.weight, mean=0.0, std=0.02)<br>init.constant_(conv.bias, 0.0)</pre><p>The problem of the random initialization is that it may lead to vanishing or exploding layer outputs in the deep neural network, depending on the variance of Gaussian distribution.</p><figure><img alt="Derivation of relationship between variance of layer outputs and variance of input data" src="https://cdn-images-1.medium.com/max/1024/1*rLwGtK4SfkHaTNOSf5-x7A.png" /><figcaption>Figure 3. Derivation of relationship between variance of layer outputs and variance of input data — image by author. Note that the notations in this figure follow the notations in Figure 1.</figcaption></figure><p>Based on Fig. 3, If the variance of initial weights is set too small, the variance of layer outputs may be extremely small or vanishing due to the accumulation of small variance during forward propagation. On the contrary, if the variance of initial weights is set too large, the variance of layer outputs may be extremely large or exploding due to the accumulation of large variance during forward propagation. The vanishing layer output may cause the network to stop learning while the exploding layer output may cause the training to be unstable or diverge.</p><h4>Xavier Initialization and He’s Initialization</h4><figure><img alt="Xavier and He’s initialization" src="https://cdn-images-1.medium.com/max/1024/1*IF5dowcmB6u6993kyw0Bsw.png" /><figcaption>Figure 4. Xavier initialization and He’s initialization — image by author. Note that the notations in this figure follow the notations in Figure 1 and Figure 3.</figcaption></figure><p>Figure 4 shows the variance propagation between two neurons at two consecutive layers of the network during forward propagation. We can see that the output variance of the neuron at current layer is propagated from the output variance of the neuron at previous layer by multiplying by the product of the number of incoming connections (<em>fan_in</em>) to current layer and the variance of the corresponding weight at current layer. To keep the variance from being vanishing and exploding during forward propagation, the product needs to be equal to 1.</p><p>Similarly, to keep variance from vanishing and exploding during backward propagation, the product of the number of outgoing connections (<em>fan_</em>out) from current layer and the variance of the corresponding weight at current layer needs to be equal to 1.</p><p>Xavier initialization [2] and He’s initialization [3] are two solutions that are designed to maintain variance during forward propagation and during backward propagation.</p><p><strong>Xavier Initialization</strong></p><p>Xavier initialization draws the weights of one layer in the network from uniform distribution.</p><figure><img alt="Xavier initialization" src="https://cdn-images-1.medium.com/max/623/1*4VNK_Co2W-aMN7ankWYDaA.png" /><figcaption>Figure 5. Xavier initialization — image by author.</figcaption></figure><p>As presented in [2], the Xavier initialization approach maintains the variance of layer outputs during forward propagation and the variance of weight gradients during backward propagation for a five-layer network using hyperbolic tangent (<em>tanh</em>) activation. However, Xavier initialization is designed for <em>tanh</em> or <em>sigmoid</em> activation, and may lead to a reduction of gradients during back propagation due to the vanishing gradient problem caused by <em>tanh</em> or <em>sigmoid</em>. Therefore, Xavier initialization may not be suitable for a deep neural network using <em>ReLU</em> activation.</p><p>The PyTorch example code for Xavier initialization is as follows.</p><pre>import torch.nn as nn<br>import torch.nn.init as init<br>fc = nn.Linear(in_features=784, out_features=256)<br>conv = nn.Conv2d(in_channels=3, out_channels=64, kernel_size=3)<br>init.xavier_uniform_(fc.weight)<br>init.constant_(fc.bias, 0.0)<br>init.xavier_uniform_(conv.weight)<br>init.constant_(conv.bias, 0.0)</pre><p><strong>He’s Initialization</strong></p><p>He’s initialization, specifically designed for deep neural network with the ReLU activation that helps to reduce the vanishing gradient problem, allows the network to learn deeper representations. He’s initialization draws the weights of one layer in the network from Gaussian distribution given by Fig. 6.</p><figure><img alt="He’s initialization" src="https://cdn-images-1.medium.com/max/623/1*cdBVHzOlhSDt3y9d7wM1KQ.png" /><figcaption>Figure 6. He’s initialization — image by author.</figcaption></figure><p>The PyTorch example code for He’s initialization is as follows.</p><pre>import torch.nn as nn<br>import torch.nn.init as init<br>fc = nn.Linear(in_features=784, out_features=256)<br>conv = nn.Conv2d(in_channels=3, out_channels=64, kernel_size=3)<br>init.kaiming_normal_(fc.weight, mode=&#39;fan_in&#39;, nonlinearity=&#39;relu&#39;)<br>init.constant_(fc.bias, 0.0)<br>init.kaiming_normal_(conv.weight, mode=&#39;fan_in&#39;, nonlinearity=&#39;relu&#39;)<br>init.constant_(conv.bias, 0.0)</pre><p>In the code above, <em>fan_in</em> is used to maintain the variance of the layer outputs during forward propagation. The mode can also be set at <em>fan_out</em> if maintaining the variance of weight gradients during backward propagation is needed.</p><h4>Initialization for Batch Normalization</h4><p>Batch norm layers normalize the distribution of layer outputs during training, which reduces the dependency of the deep network on weight initialization strategies [4]. The weights and biases of all batch normalization layers are usually initialized as 1s and 0s, respectively.</p><p>The PyTorch example code for initializing weights and biases of batch norm layers is as follows.</p><pre>import torch.nn as nn<br>import torch.nn.init as init<br>bn = nn.BatchNorm2d(64)<br>init.constant_(bn.weight, 1.0)<br>init.constant_(bn.bias, 0.0)</pre><h4>Strategy Selection</h4><figure><img alt="Selection of initialization strategies" src="https://cdn-images-1.medium.com/max/760/1*yPOf1Z1nIOcRtOxN3H96kw.png" /><figcaption>Figure 7. Selection of initialization strategies.</figcaption></figure><p>After going through the evolution of weight initialization strategies, we summarize which strategy to select for different scenarios.</p><p>In the case that a pretrained model is available, we should initialize the model using the pretrained weights because the model was already pretrained after extensive hyperparameter tunings by authors/creators of the model. Therefore, we should use the pretrained weight and fine-tune the model for our application instead of training the model from scratch.</p><p>If the pretrained weights are not available or we design the model from scratch, we then need to train the model from scratch. In those cases, if the model utilizes batch norm layers, then we can simply use random initialization with a small variance because batch norm layers reduce the model dependency on the initial weight scale.</p><p>If the model does not have batch norm layers, then He’s initialization is recommended especially for training a deep network with many layers.</p><h4>Conclusions</h4><p>In this article, I went through the evolution of the strategies of model weight initialization, and I also listed their PyTorch implementation. Finally, I summarized how we select different strategies based on our needs.</p><p>I hope this article help you understand existing weight initialization strategies and select the right one for training your network. Thanks for your time on reading this article!</p><h4>References</h4><p>[1] <a href="https://cs231n.github.io/neural-networks-2/">https://cs231n.github.io/neural-networks-2/</a>.</p><p>[2] Xavier and Yoshua., <a href="http://proceedings.mlr.press/v9/glorot10a/glorot10a.pdf">Understanding the difficulty of training deep feedforward neural networks</a>, 2010.</p><p>[3] He et al., <a href="https://paperswithcode.com/paper/delving-deep-into-rectifiers-surpassing-human">Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification</a>, 2015.</p><p>[4] Sergey Ioffe and Christian Szegedy, <a href="https://arxiv.org/pdf/1502.03167.pdf">Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift</a>, 2015</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0302b6f5bf3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fusing Backbone Features using Feature Pyramid Network (FPN)]]></title>
            <link>https://medium.com/@freshtechyy/fusing-backbone-features-using-feature-pyramid-network-fpn-c652aa6a264b?source=rss-81e2a307d7db------2</link>
            <guid isPermaLink="false">https://medium.com/p/c652aa6a264b</guid>
            <category><![CDATA[feature-pyramid-network]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[resnet]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Huili Yu]]></dc:creator>
            <pubDate>Wed, 09 Nov 2022 04:46:32 GMT</pubDate>
            <atom:updated>2022-11-09T04:46:32.883Z</atom:updated>
            <content:encoded><![CDATA[<h4>An introduction to FPN architecture and code implementation.</h4><p>In my previous <a href="https://medium.com/@freshtechyy/a-detailed-introduction-to-resnet-and-its-implementation-in-pytorch-744b13c8074a">post</a>, I gave a detailed introduction to a powerful backbone network ResNet. As I described in the previous post, in many applications, the different levels of feature maps output by the backbone network need to be fused together to provide enhanced features for prediction heads. The fusion work is performed by the neck network. In this article, I like to talk about a popular neck network: Feature Pyramid Network (FPN) and explain how to use it to fuse the features output by ResNet. I will cover both its detailed architecture and code implementation in PyTorch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*-g9ifqulNyCk5gUCxM90Og.jpeg" /><figcaption>Figure 1. FPN is used as a neck network to fuse features from backbone network — image by author.</figcaption></figure><h4>Feature Pyramid Network (FPN)</h4><p>Feature Pyramid Network (FPN), developed in [1], is a neck network that fuses features with various levels of resolution obtained by a backbone network, like ResNet. As we know, a CNN (Convolution Neural Network) based backbone applies a series of convolution layers to an input image to obtain a set of feature maps with decreasing levels of resolution due to downsampling caused by pooling or convolution with a stride unequal to one.</p><p>The low resolution feature maps capture more global information of the image and represent richer semantic meaning while the high resolution feature maps focus more on the local information and provide more accurate spatial information. The goal of FPN is to combine the high and low resolution feature maps to enhance the features with both accurate spatial information and rich semantic meaning.</p><p>Figure 2 shows how FPN works. The FPN includes a bottom-up pathway and a top-down pathway. In the bottom-up pathway, a backbone network, like ResNet, is used to perform feature extraction to extract features with decreasing levels of spatial resolution. As the levels of resolution decreases, the semantic meaning of the feature maps increases, as indicated by the thickness of box boundaries in blue.</p><p>In the top-down pathway, the feature maps are fused to have both rich semantic meaning and accurate spatial information. As shown in Fig. 2, the feature map with the highest resolution has the same level of semantic meaning as the feature map with the lowest resolution. To construct the feature map at the current level, the feature map at the previous level needs to first perform 2x upsampling (either using bilinear or nearest neighbor interpolation), and then perform element-wise addition with the corresponding feature map in the bottom-up pathway by a lateral connection. Since different levels of feature maps may have different number of channels, 1x1 convolution is used in the lateral connection to unify the number of channels of both feature maps that are used to perform the element-wise addition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y832sFXNcTvd-NZSCdfaCQ.jpeg" /><figcaption>Figure 2. Feature Pyramid Network (FPN), modified from <a href="https://arxiv.org/pdf/1612.03144.pdf">source</a>.</figcaption></figure><p>Due to its strength of constructing feature maps with both rich semantic meaning and high spatial accuracy, FPN is widely used in many computer vision problems: (a) it helps detect small objects for object detection problem, (b) it helps refine the segmentation boundaries for segmentation problem, etc. Note that besides the element-wise addition shown in Fig. 2, feature map channel-wise concatenation is also used to fuse two feature maps. <a href="https://pjreddie.com/media/files/papers/YOLOv3.pdf">YOLOV3</a>[2] is an example of using FPN-based feature map channel-wise concatenation to detect small objects for object detection.</p><h4><strong>Fusing features from ResNet</strong></h4><p>Figure 3 shows an example of combining ResNet-50 and FPN to obtain enhanced features P2-P6. A 1x1 convolution is first applied to each feature map from C2-C5 output by ResNet-50, which unifies the number of channels of those feature maps to 256. Then the unified feature maps from C5 to C3 are upsampled by 2 and element-wise added to the unified feature maps at the next levels, i.e., C4-C2. Another 3x3 convolution is augmented to each of the resulting feature maps from C5 to C2 to provide the outputs from P5 to P2. The output P6 can be obtained by performing the max-pooling operation with kernel size 1 and stride 2 on P5. The outputs P2-P5 will be used in various prediction heads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f7ZGSQelvHuNnm8HWForSg.jpeg" /><figcaption>Figure 3. Example of combining ResNet-50 and FPN — image by author.</figcaption></figure><h4><strong>Implementation In PyTorch</strong></h4><p>The implementation consists of two parts: ResNet and FPN. I provided the implementation of ResNet in my previous <a href="https://medium.com/@freshtechyy/a-detailed-introduction-to-resnet-and-its-implementation-in-pytorch-744b13c8074a">post</a>. Here I focus my implementation on the FPN part of the architecture shown in Fig. 3, which takes C2-C5 from ResNet and outputs P2-P6.</p><p>Below is the ResnetFPN class that consists of ResNet (refer to my previous <a href="https://medium.com/@freshtechyy/a-detailed-introduction-to-resnet-and-its-implementation-in-pytorch-744b13c8074a">post</a>) and FPN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*VF0-9oFLgT9d2q5D2XBpug.png" /><figcaption>Figure 4. ResNetFPN class — image by author.</figcaption></figure><p>The FPN class consists of 4 layers, which generate features P2-P5, and 1 max-pooling layer that generates feature P6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*MVY6EucSvk7uzEkJIFryZA.png" /><figcaption>Figure 5. FPN class — image by author.</figcaption></figure><p>The layer used to generate P2-P5 is defined in FPNBlock.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*X2-EQVnE3t1zIgsOIo7duw.png" /><figcaption>Figure 6. FPNBlock class — image by author.</figcaption></figure><p>The complete PyTorch implementation of ResNet+FPN is available from the <a href="https://github.com/freshtechyy/resnet/blob/main/resnet_fpn.py">Github</a>.</p><h4><strong>Conclusions</strong></h4><p>In this article, I gave a detailed introduction to FPN and how to use FPN to fuse the feature maps output by ResNet to generate the enhanced features that will be used in various prediction heads. I also provided my implementation of ResNet+FPN in PyTorch.</p><p>In my future articles, I will talk about how to incorporate the enhanced features output by ResNet+FPN into prediction heads for various computer vision tasks. Thanks for your time in reading this article.</p><h4><strong>References</strong></h4><p>[1] T. Lin, et. al, “Feature Pyramid Networks for object detection”, CVPR, 2016.</p><p>[2] J. Redmon and A. Farhadi, “YOLOV3: An Incremental Improvement”, <a href="https://arxiv.org/abs/1804.02767.">https://arxiv.org/abs/1804.02767.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c652aa6a264b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Detailed Introduction to ResNet and Its Implementation in PyTorch]]></title>
            <link>https://medium.com/@freshtechyy/a-detailed-introduction-to-resnet-and-its-implementation-in-pytorch-744b13c8074a?source=rss-81e2a307d7db------2</link>
            <guid isPermaLink="false">https://medium.com/p/744b13c8074a</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[convolution-neural-net]]></category>
            <category><![CDATA[feature-extraction]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[resnet]]></category>
            <dc:creator><![CDATA[Huili Yu]]></dc:creator>
            <pubDate>Thu, 27 Oct 2022 04:28:02 GMT</pubDate>
            <atom:updated>2022-10-27T04:28:02.795Z</atom:updated>
            <content:encoded><![CDATA[<h4>A deep tutorial on the ResNet architectures and implementation</h4><h3>Introduction</h3><p>In general, a deep learning model for computer vision problems, like image classification, object detection, semantic segmentation, etc., consists of three components: backbone, neck, and heads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*56KaQFlQ2MK-q7rprDfx6A.jpeg" /><figcaption>Figure 1. The deep learning network consisting of backbone, neck, and prediction heads — image by author.</figcaption></figure><p>The backbone network extracts features from the input image and produces feature maps at different levels of resolution. The feature maps at the lower level contain more accurate spatial information due to their high resolution while the feature maps at the higher level have richer semantic information due to their large receptive field.</p><p>The neck network fuses the features from all the levels to enhance features with both higher accuracy and richer semantic meaning. One example of the neck network is Feature Pyramid Network (FPN). I will cover the FPN network in my next post.</p><p>Based on the enhanced features fused by the neck network, various head networks are used to perform different tasks. For example, for object detection, classification head and regression head are normally used for classifying the object classes and regressing the object bounding boxes.</p><p>In this article, I will cover one of the most powerful backbone networks, ResNet [1], which stands for Residual Network, from both architecture and code implementation perspectives.</p><h3><strong>Why ResNet?</strong></h3><p>There are many backbone networks, such as VGG, GoogLeNet, ResNet, and so on. ResNet was developed to facilitate training of deep networks by introducing skip connections or shortcuts between the network layers.</p><p>To address complex problems like computer vision, a deep learning network needs to have a large number of layers to gain large capacity. However, a large number of layers may lead to difficulty of training the network due to the vanishing gradient problem. Consider an example shown in Fig. 2, where a part of network <em>H(x)</em> consists of two layers: layer1 and layer2. If the magnitude of the partial derivative <em>H(x)</em> with respect to <em>x</em> is much less than 1, due to existence of activation functions, like Sigmoid, the gradient of <em>x</em> propagated from the gradient of <em>H(x)</em> is very small. This is called the gradient vanishing problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*4kakz-PJyXuvud8q2iTafg.jpeg" /><figcaption>Figure 2. Vanishing gradient — image by author.</figcaption></figure><p>However, if a skip connection or shortcut is added from <em>x</em> to <em>H(x)</em>, as shown in Fig. 3, the network learns the residual <em>F(x)=H(x)-x</em>, which is much easier. For this network with the skip connection,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*A3KhjsnegckhuHsev0ojOw.gif" /></figure><p>The gradient of <em>x</em> can be easily propagated from the gradient of <em>H(x)</em>. Therefore, the vanishing gradient problem is effectively addressed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4lcPC5HE8lArMfw1YPN3pQ.jpeg" /><figcaption>Figure 3. Skip connection in ResNet — image by author.</figcaption></figure><h3><strong>ResNet Architectures</strong></h3><p>The commonly used ResNet architectures include ResNet18, ResNet-34, ResNet-50, ResNet-101, and ResNet-152, each of which has different residual block structure and different number of residual blocks, as shown in Fig. 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*887-nKSxPB_i0Buo8coreQ.jpeg" /><figcaption>Figure 4. ResNet architectures — image by author.</figcaption></figure><p>As shown in Fig. 4, each of five ResNet architectures consists of five convolutional layers (conv1, conv2_x — conv5_x), an average pooling layer, a fully connected layer and softmax. The five convolutional layers are the backbone network, as I discussed above. ResNet was first developed for image classification on the ImageNet dataset [2]. The average pooling layer, fully connected layer, and softmax together form the classification head for 1000 object classes of the ImageNet dataset.</p><p>The backbone networks of ResNet, pretrained using ImageNet, are widely used to extract features at different levels of resolution (feature maps after conv2_x, conv3_x, conv4_x, and conv5_x). Those features are followed by particular neck and heads and fine-tuned for particular tasks, like object detection, semantic segmentation, etc.</p><p>The five ResNet architectures use the residual block as the basic building block. Each of the convolutional layers from conv2_x to conv5_x uses different number of the residual blocks. For examples, as indicated by the red ellipses in Fig. 4, in ResNet-18, the number of the residual blocks used in conv2_x, conv3_x, conv4_x conv5_x is 2, 2, 2 and 2, respectively. In ResNet-50, the number of the residual blocks used in conv2_x, conv3_x, conv4_x conv5_x is 3, 4, 6 and 3, respectively.</p><p>The structure of the residual block used by ResNet-18 and ResNet-34 is different from the one used by ResNet-50, ResNet-101, and ResNet-152, as shown in Fig. 5. Starting from ResNet-50, the bottleneck structure is used to reduce the model parameters by alternating 1x1 and 3x3 convolutions. As shown in Fig. 5, compared to two convolutions of 3x3, 64 and 3x3, 256, the number of model parameters are reduced from 294912 to 69632. Another advantage of the bottleneck structure is that more activations are introduced due to more convolutions. Accordingly, the nonlinearity and model capacity is increased.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6hw4IgsgkjGHJMcUlKenHw.jpeg" /><figcaption>Figure 5. Residual blocks — image by author.</figcaption></figure><p>ResNet extracts features at decreasing levels of resolution from conv2_x to conv5_x. In particular, s2 (stride=2) is used in the first 3x3 convolutions of the first residual blocks for conv3_x, conv4_x, and conv5_x to downsample feature maps to get larger receptive field. Therefore, special care is given to those residual blocks to match spatial dimension of feature maps and number of channels in order to perform the add operations for the skip connections.</p><p>Figure 6 shows the skip connections go through 1x1 convolutions with s2 in the first residual blocks of conv3_x layers used in ResNet 18, 34, and ResNet 50, 101, 152, respectively, to match spatial dimension of feature maps and number of channels for the add operations of the skip connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mZrhax6-H-pHSe47ovnWCg.jpeg" /><figcaption>Figure 6. The first residual blocks of conv3_x — image by author.</figcaption></figure><h3>Code implementation in PyTorch</h3><p>The code implementation facilitates the deep understanding of the architectures mentioned above. The code is written in PyTorch.</p><h4>ResNet model</h4><p>Below is the code for the ResNet model corresponding to Fig. 4. Depending on the input residual block structure and number of residual blocks for conv2_x, conv3_x, conv4_x, and conv5_x, the corresponding ResNet model from ResNet-18, 34, 50, 101, and 152 can be generated. Applying the model to a given input image, the feature maps C2-C5 from conv2_x to conv5_x can be extracted.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49e5fa0c47515c6ce1d14ea555716551/href">https://medium.com/media/49e5fa0c47515c6ce1d14ea555716551/href</a></iframe><h4>Residual block for ResNet-18 and ResNet-34</h4><p>ResNet-18, 34 use the basic version of the residual block corresponding to the left architectures of Figs 5 and 6.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de13e1e6ebc6d2be6e27b664ceb07f5d/href">https://medium.com/media/de13e1e6ebc6d2be6e27b664ceb07f5d/href</a></iframe><h4>Residual block for ResNet-50, 101, and 152</h4><p>ResNet-50, 101, and 152 use the bottleneck block as the residual block, corresponding to the right architectures of Figs 5 and 6.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fb68bfa5224a5c4670cb9a3a769fea3/href">https://medium.com/media/3fb68bfa5224a5c4670cb9a3a769fea3/href</a></iframe><p>The complete PyTorch implementation of ResNet is available from the <a href="https://github.com/freshtechyy/resnet.git">Github</a>.</p><h4>Conclusions</h4><p>In this article, I give a detailed introduction to ResNet from both architecture and implementation perspectives. I first describe why ResNet is used as a powerful backbone network for feature extraction in deep neural networks. Then, I illustrate the architecture details about ResNet architectures, including ResNet-18, ResNet-34, ResNet-50, ResNet-101, and ResNet-152. Finally, I provide the code implementation of the ResNet architectures.</p><p>In my future article, I will talk about how to combine ResNet with a neck network, like FPN, to enhance extracted features. Thanks for your time in reading this article.</p><h4>References</h4><p>[1] K. He, et. al, “Deep Residual Learning for Image Recognition”, CVPR, 2016.</p><p>[2] J. Deng, et. al, “ImageNet: A large-scale hierarchical image database”, CVPR, 2009.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=744b13c8074a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying PyTorch Model into a C++ Application Using ONNX Runtime]]></title>
            <link>https://medium.com/@freshtechyy/deploying-pytorch-model-into-a-c-application-using-onnx-runtime-f9967406564b?source=rss-81e2a307d7db------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9967406564b</guid>
            <category><![CDATA[c-plus-plus-language]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ml-model-deployment]]></category>
            <category><![CDATA[onnx-runtime]]></category>
            <dc:creator><![CDATA[Huili Yu]]></dc:creator>
            <pubDate>Wed, 13 Jul 2022 23:08:47 GMT</pubDate>
            <atom:updated>2022-07-13T23:08:47.608Z</atom:updated>
            <content:encoded><![CDATA[<p>A simple end-to-end example of deploying a pretrained PyTorch model into a C++ app using ONNX Runtime with GPU</p><h3>Introduction</h3><p>A lot of machine learning and deep learning models are developed and trained in Python-based frameworks like PyTorch and Tensorflow, etc. However, when we deploy the pretrained models for production related tasks, we often need to integrate the models into the production pipeline, which is normally written in C++ for faster real time performance.</p><p>Many existing tools and frameworks enable us to deploy the pretrained models into a C++ app, e.g., ONNX runtime for edge and server, NCNN and MNN for mobile device, and TensorRT for Nvidia embedded platforms. In this article, I like to discuss how to deploy a pretrained PyTorch model into a C++ app using ONNX Runtime (GPU) by an end-to-end example.</p><p>In particular, I like to discuss the following contents.</p><ul><li>What is ONNX?</li><li>What is ONNX Runtime?</li><li>Pipeline of deploying the pretrained PyTorch model into the C++ app using ONNX Runtime.</li><li>An end-to-end example of deploying the pretrained PyTorch model into the C++ app using ONNX Runtime.</li></ul><h3>ONNX</h3><p>Open Neural Network eXchange (ONNX) is an open file format designed for machine learning for storing pretrained models. It allows various AI frameworks to store and interact with model data in the same format. The specifications and codes of ONNX are mainly developed by companies such as Microsoft, Amazon, Facebook and IBM.</p><h3>ONNX Runtime</h3><p>ONNX Runtime is a cross-platform machine-learning model accelerator, with a flexible interface to integrate hardware-specific libraries. ONNX Runtime is capable of executing the neural network model using different execution providers, like CPU, CUDA, and TensorRT, etc. It can also be used with models from various frameworks, like PyTorch, Tensorflow/Keras, TFLite, scikit-learn, etc.</p><p>ONNX runtime inference allows for the deployment of the pretrained PyTorch models into the C++ app.</p><h3>Pipeline of deploying the pretrained PyTorch model into the C++ app using ONNX Runtime</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bDq_gXadoH38vPAxydaBgA.png" /><figcaption>Figure 1. Pipeline of deploying the pretrained PyTorch model into the C++ app using ONNX Runtime — image by author.</figcaption></figure><p>The above figure demonstrates the deployment pipeline of the pretrained PyTorch model into the C++ app using ONNX Runtime. Given the file of the model pretrained in PyTorch (either a .pth file or .pt file), we first convert the file to a file in ONNX format (.onnx file). The conversion also happens in PyTorch. The generated onnx file is input to the C++ app that calls the ONNX Runtime C++ API to perform the inference.</p><h4>Conversion from the PyTorch model to ONNX</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*o6vvRclhgshZ3QXzO0X68Q.png" /><figcaption>Figure 2. PyTorch model conversion to .onnx file — image by author.</figcaption></figure><p>The conversion from .pth/.pt file to .onnx file can be simply performed in PyTorch by four steps. Firstly, the network needs to be created, and if the inference is performed on GPU, then the model needs to be put to CUDA.</p><pre>net = Model()<br>net.cuda()</pre><p>Secondly, the model parameters stored in the .pth/.pt file are loaded to the model.</p><pre>PATH = &#39;model.pth&#39;<br>net.load_state_dict(torch.load(PATH))<br>net.eval()</pre><p>After creating the model, we then specify the input. The input can be simply set at a random tensor with the right shape required by the model. The shape needs to be in the format of NCHW (batch size * number of channels * height * width). For example, the input can be set as follows.</p><pre>x = torch.randn((1, 3, 32, 32)).cuda()</pre><p>Finally, given the model and the input, the .onnx file can be exported by</p><pre>torch.onnx.export(net,       # model being run       <br>                  x,         # model input<br>                  &quot;model.onnx&quot;,  # where to save the model<br>                  export_params=True, # store the trained weights<br>                  opset_version=11,   # the ONNX version<br>                  do_constant_folding=True,<br>                  input_names= [&#39;input&#39;], # set model input names    <br>                  output_names=[&#39;output&#39;], # set model output names<br>)</pre><h4>Inference using ONNX Runtime</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jOwMHTkM56xN_2UACI0fcg.png" /><figcaption>Figure 3. Inference using ONNX Runtime — image by author.</figcaption></figure><p>Performing inference using ONNX Runtime C++ API consists of two steps: initialization and inference. In the initialization step, the runtime environment for ONNX Runtime is created and the options for the ONNX Runtime Session are set up. Given the runtime environment, Session options, and a pretrained ONNX model, the ONNX Runtime Session is created. The ONNX Runtime Session is used to (a) when combined with the created allocator, extract the information of the model inputs and outputs, like number, name, type, and shape of the model inputs/outputs, (b) to run the inference in the inference step.</p><p>Receiving the number, name, type, and shape of the model inputs and outputs from the initialization step, the inference step performs the inference task. It first creates the input and output tensors and allocates the memory for the tensors. Then, the ONNX Runtime Session is run to perform the inference. Finally, the inference results are postprocessed to get final prediction results.</p><h3>An end-to-end example of deploying the pretrained PyTorch model into the C++ app using ONNX Runtime</h3><p>In this article, I used <a href="https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html">the PyTorch tutorial image classification example</a>. With this tutorial example, my focus is to provide an end-to-end pipeline of deploying the pretrained PyTorch model into the C++ application using ONNX Runtime, which is easy to understand.</p><p>The complete implementation of the pipeline is available from the <a href="https://github.com/freshtechyy/ONNX-Runtime-GPU-image-classifciation-example">Github</a>, which starts from training to the deployment into the C++ image classification application.</p><p>Below I will describe the major components of how to use ONNX Runtime C++ API to deploy the pretrained model into the C++ app. For other parts of the pipeline, please refer to the <a href="https://github.com/freshtechyy/ONNX-Runtime-GPU-image-classifciation-example">Github</a>.</p><p>I make an image classifier class which has field variables for ONNX Runtime environment, session, names and shape of the model inputs and outputs. These variables will be used by the ONNX Runtime inference.</p><pre>class ImageClassifier {<br> private:<br>  // ORT Environment<br>  std::shared_ptr&lt;Ort::Env&gt; mEnv;<br>  <br>  // Session<br>  std::shared_ptr&lt;Ort::Session&gt; mSession;<br>  <br>  // Inputs<br>  char* mInputName;<br>  std::vector&lt;int64_t&gt; mInputDims;    // shape<br>  <br>  // Outputs<br>  char* mOutputName;<br>  std::vector&lt;int64_t&gt; mOutputDims;    // shape</pre><p>The initialization step, as shown in Fig. 3, is then performed in the class constructor to create the runtime environment, session, and allocator.</p><pre>/******* Create ORT environment *******/<br>std::string instanceName{&quot;Image classifier inference&quot;};<br>mEnv = std::make_shared&lt;Ort::Env&gt;      (OrtLoggingLevel::ORT_LOGGING_LEVEL_WARNING,instanceName.c_str());</pre><pre>/******* Create ORT session *******/<br>// Set up options for session<br>Ort::SessionOptions sessionOptions;<br>// Enable CUDA<br>sessionOptions.AppendExecutionProvider_CUDA(OrtCUDAProviderOptions{});<br>// Sets graph optimization level (Here, enable all possible optimizations)<br>sessionOptions.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_ALL);<br>// Create session by loading the onnx model<br>mSession = std::make_shared&lt;Ort::Session&gt;(*mEnv, modelFilepath.c_str(), sessionOptions);</pre><pre>/******* Create allocator *******/<br>// Allocator is used to get model information<br>Ort::AllocatorWithDefaultOptions allocator;</pre><p>The info of the model inputs and outputs, like number, name, and shape of the inputs/outputs is also obtained in the class constructor using the created session and allocator.</p><pre>/******* Inputs *******/<br>// Number of input nodes<br>size_t numInputNodes = mSession-&gt;GetInputCount();</pre><pre>// Name of input<br>// 0 means the first input<br>mInputName = mSession-&gt;GetInputName(0, allocator);</pre><pre>// Input type<br>Ort::TypeInfo inputTypeInfo = mSession-&gt;GetInputTypeInfo(0);<br>auto inputTensorInfo = inputTypeInfo.GetTensorTypeAndShapeInfo();<br>ONNXTensorElementDataType inputType = inputTensorInfo.GetElementType();</pre><pre>// Input shape<br>mInputDims = inputTensorInfo.GetShape();</pre><pre>/******* Outputs *******/<br>// Number of output nodes<br>size_t numOutputNodes = mSession-&gt;GetOutputCount();</pre><pre>// Name of output<br>// 0 mans the first output<br>mOutputName = mSession-&gt;GetOutputName(0, allocator);</pre><pre>// Output type<br>Ort::TypeInfo outputTypeInfo = mSession-&gt;GetOutputTypeInfo(0);<br>auto outputTensorInfo = outputTypeInfo.GetTensorTypeAndShapeInfo();<br>ONNXTensorElementDataType outputType = outputTensorInfo.GetElementType();</pre><pre>// Output shape<br>mOutputDims = outputTensorInfo.GetShape();</pre><p>After the initialization step, the inference on each image is performed using ONNX Runtime C++ API, as shown in Fig. 3. Firstly, the image is loaded and preprocessed in order to be compatible with the pretrained model input. Then, I create the input tensors in the format required by the ONNX Runtime.</p><pre>// Load an input image<br>cv::Mat img = cv::imread(imageFilepath, cv::IMREAD_COLOR);<br>cv::Mat scaledImage, preprocessedImage;</pre><pre>// Scale image pixels from [0 255] to [-1, 1]<br>img.convertTo(scaledImage, CV_32F, 2.0f / 255.0f, -1.0f);</pre><pre>// Convert HWC to CHW<br>cv::dnn::blobFromImage(scaledImage, preprocessedImage);</pre><pre>// Create input tensor buffer and assign preprocessed image to the buffer<br>size_t inputTensorSize = vectorProduct(mInputDims);<br>std::vector&lt;float&gt; inputTensorValues(inputTensorSize);<br>inputTensorValues.assign(preprocessedImage.begin&lt;float&gt;(),<br>preprocessedImage.end&lt;float&gt;());</pre><pre>// Create input tensors of ORT::Value, which is a tensor format used by ONNX Runtime<br>std::vector&lt;Ort::Value&gt; inputTensors;<br>Ort::MemoryInfo memoryInfo = Ort::MemoryInfo::CreateCpu(OrtAllocatorType::OrtArenaAllocator, OrtMemType::OrtMemTypeDefault);<br>inputTensors.push_back(Ort::Value::CreateTensor&lt;float&gt;(memoryInfo, inputTensorValues.data(),inputTensorSize,mInputDims.data(),mInputDims.size()));</pre><p>Similarly, I create the output tensors as follows.</p><pre>// Create output tensor buffer<br>size_t outputTensorSize = vectorProduct(mOutputDims);<br>std::vector&lt;float&gt; outputTensorValues(outputTensorSize);</pre><pre>// Create output tensors of ORT::Value<br>std::vector&lt;Ort::Value&gt; outputTensors;<br>outputTensors.push_back(Ort::Value::CreateTensor&lt;float&gt;(memoryInfo, outputTensorValues.data(), outputTensorSize,mOutputDims.data(), mOutputDims.size()));</pre><p>Having created the input and output tensors, I call the method of Session run to perform the inference.</p><pre>std::vector&lt;const char*&gt; inputNames{mInputName};<br>std::vector&lt;const char*&gt; outputNames{mOutputName};</pre><pre>// 1 means number of inputs and outputs<br>mSession-&gt;Run(Ort::RunOptions{nullptr}, inputNames.data(),inputTensors.data(), 1, outputNames.data(),outputTensors.data(), 1);</pre><p>Finally, I postprocess the inference results to get the predicted class for the input image.</p><pre>// Get the inference result<br>float* floatarr =<br>outputTensors.front().GetTensorMutableData&lt;float&gt;();</pre><pre>// Compute the index of the predicted class<br>// 10 means number of classes in total<br>int cls_idx = std::max_element(floatarr, floatarr + 10) - floatarr;</pre><p>Below are the classification results on some example images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6CVSiPrYg0QPyj5w2UsEgg.png" /><figcaption>Figure 4. Image classification results using ONNX Runtime in C++ — image by author.</figcaption></figure><h3>Conclusions</h3><p>In this article, I use a simple image classification example to illustrate how to deploy the pretrained PyTorch model into a C++ application using ONNX Runtime (GPU) in an end-to-end manner.</p><p>In my future articles, I will introduce more topics about deep learning model deployment using different frameworks. Thanks for your time on reading this article.</p><h3>References</h3><ul><li><a href="https://onnxruntime.ai/">https://onnxruntime.ai/</a></li><li><a href="https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html">https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9967406564b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Comprehensive Introduction to Self-Driving Cars — Part 1: Introduction]]></title>
            <link>https://medium.com/@freshtechyy/a-comprehensive-introduction-to-self-driving-cars-part-1-introduction-99d0e0fd56b?source=rss-81e2a307d7db------2</link>
            <guid isPermaLink="false">https://medium.com/p/99d0e0fd56b</guid>
            <category><![CDATA[autonomous-driving]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[high-tech]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Huili Yu]]></dc:creator>
            <pubDate>Sat, 28 May 2022 03:15:49 GMT</pubDate>
            <atom:updated>2022-05-28T03:15:49.902Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Comprehensive Introduction to Self-Driving Cars — Part 1: Introduction</h3><h4>Introduction to self-driving car, including definition, applications, technologies, levels of driving automation.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1WLtuQQhHhhZK1CV" /><figcaption>Photo by <a href="https://unsplash.com/@rpnickson?utm_source=medium&amp;utm_medium=referral">Roberto Nickson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Self-driving cars have been a hot topic for years and have received significant attentions from both academy and car industry. Once fully developed and matured, they will bring great convenience and safety to various aspects of our lives.</p><p>As a high-tech application, many cutting-edge technologies have been involved in self-driving cars, including hardware, software, and algorithms, etc., which are widely used in different industries too. Accordingly, learning and understanding how self-driving cars wok and grasping key technologies help you not only get familiar with self-driving cars per se, but also equip you with a rich set of skills that are crucial for your careers in various industries.</p><p>So, I am planning a series of articles that comprehensively guide you through different aspects of self-driving cars, including levels of driving automation and functionalities, top players, hardware configuration, software architecture, hardware/software provider, and key technologies and algorithms.</p><p>The first article answers the following questions.</p><ul><li>What are self-driving cars? Benefits for us?</li><li>Commercial applications.</li><li>What technologies are involved?</li><li>Levels of driving automation and classification of self-driving cars.</li></ul><h3>What are self-driving cars? Benefits for us?</h3><p>Self-driving cars are the vehicles with autonomous driving capability. They are able to understand their surrounding environment, interact with other traffics, and make reasonable decisions to navigate to their destinations. The autonomous driving capability provides us many benefits. Below are some examples.</p><ul><li>Driver’s fatigue due to a long driving can be relieved;</li><li>The challenging driving operations, like parallel parking, reverse parking, etc., are made easier;</li><li>Car parking problems can be effectively addressed because self-driving cars do not need to be parked nearby the destination;</li><li>Self-driving cars are very beneficial for those who have challenges related to driving, like the elderly and the disabled.</li></ul><h3>Commercial applications</h3><p>Self-driving cars have many commercial applications, such as local driverless taxi, good delivery, autonomous trucking, autonomous mining, and intelligent port operations. At present, many well-known companies worldwide, such as Waymo, Cruise, Aurora, TuSimple, etc., have been developing and deploying autonomous driving technologies for driverless taxi and autonomous trucking. At the same time, many new electric vehicle manufactures and traditional automakers have integrated different levels of Advanced Driver Assistance Systems (ADAS) on consumer-oriented vehicles, such as, Tesla’s Full Self-Driving (FSD) system, and Xiaopeng’s Navigation Guided Pilot (NGP) system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AJgfueWfWN8ba-Mq8d6Mng.png" /><figcaption>Example applications of self-driving cars. (a) Grendelkhan, <a href="https://creativecommons.org/licenses/by-sa/4.0">CC BY-SA 4.0</a>, via <a href="https://commons.wikimedia.org/wiki/File:Waymo_self-driving_car_front_view.gk.jpg">Wikimedia Commons</a>, (b) Anonymousfox36, <a href="https://creativecommons.org/licenses/by-sa/4.0">CC BY-SA 4.0</a>, via <a href="https://commons.wikimedia.org/wiki/File:Meituan_autonomous_delivery_vehicle_IMG003.jpg">Wikimedia Commons</a>, (c) Steve Jurvetson, <a href="https://creativecommons.org/licenses/by/2.0/">CC BY 2.0</a>, via <a href="https://commons.wikimedia.org/wiki/File:Uber_OTTO_autonomous_driving_truck.jpg">Wikimedia Commons</a>, (d) RobSimmons223311, <a href="https://creativecommons.org/licenses/by-sa/4.0">CC BY-SA 4.0</a>, via <a href="https://commons.wikimedia.org/wiki/File:Ferrexpo_autonomous_truck.jpg">Wikimedia Commons</a></figcaption></figure><h3>Technologies involved</h3><p>There are a variety of disciplines and technical fields involved in self-driving cars. Examples of technical fields are: computer science, artificial intelligence, robotics, sensors, data science, communications, automatic control, vehicle engineering, etc.</p><figure><img alt="Technologies in self-driving cars." src="https://cdn-images-1.medium.com/max/1024/1*cfoOCwzgvGv1Bp9t1qNfug.png" /><figcaption>Technologies involved in self-driving cars — Image by author.</figcaption></figure><p>These technologies are often used in many other applications. For example, vehicle and pedestrian detection, lane marker detection, drivable space detection, etc., in the perception module of self-driving cars require extensive use of deep learning technology and computer vision technology. For another example, the localization module of self-driving cars is achieved by Simultaneous Localization and Mapping (SLAM) technology and vision-based or Lidar-based odometry. The sensor fusion module may be achieved by leveraging the state estimation technology, like Kalman Filter, or Particle Filter, etc. All these technologies are widely used in Augmented Reality (AR), robotics, and smart drones, etc. In addition, sensors used by self-driving cars, like camera, Lidar, Radar, etc., have also been used in the above applications.</p><p>Accordingly, skills and knowledge obtained by learning self-driving cars are essential not only for a career in the industry of self-driving cars but also careers in many other industries, like AR, robotics, and smart drones, etc.</p><h3>Levels of driving automation and classification</h3><p>The Society of Automotive Engineers (SAE) defines six levels of driving automation ranging from Level 0 (full manual) to Level 5 (fully autonomous) [1].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iixFSdDXHB9Cbw-jn_GUJA.png" /><figcaption>Levels of driving automation — Image by author.</figcaption></figure><p>At Level 0, the driver needs to operate the vehicle all the way, and the automated driving system only provides warnings and momentary assistance to the driver. Examples include Autonomous Emergency Braking (AEB), Blind Spot Detection (BSD), and Lane Departure Warning (LDW).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F1w2N3_cpI7ycVdYZJw45g.png" /><figcaption>Level 0 features. (a) Ford Motor Company, <a href="https://creativecommons.org/licenses/by/2.0/deed.en">CC BY 2.0</a>, via <a href="https://commons.wikimedia.org/wiki/File:Collision_Warning_Brake_Support.jpg">Wikimedia Commons</a>, (b) <a href="https://en.wikipedia.org/wiki/User:Jeremykemp">Jeremykemp</a>, via <a href="https://commons.wikimedia.org/wiki/File:Blindspot_three_cars_illus.svg">Wikimedia Commons</a>, (c) Image by author.</figcaption></figure><p>For AEB, the automated driving system detects the presence of pedestrians or vehicles ahead using forward-looking radars or cameras, and sends a warning to the driver. The BSD function sends a warning to the driver if there exist vehicles in the blind spot of the ego-vehicle. The LDW function detects whether the ego-vehicle deviates from the current driving lane, and if the deviation occurs, it sends an alarm to the driver.</p><p>At Level 1, the automated driving system controls the ego-vehicle in only one direction (either longitudinal or lateral). In the longitudinal direction, the driving system provides acceleration/brake support to the driver. In the lateral direction, the driving system provides steering support to the driver. Examples of features at Level 1 are Lane Centering (LC)and Adaptive Cruise Control (ACC). For the LC feature, the automated driving system steers the ego-vehicle to drive along the center line of the current lane. The ACC feature, once receiving detections about the preceding vehicle in the current lane of the ego-vehicle using the equipped sensors like camera, Lidar, radar, etc., automatically adjusts the speed of the ego-vehicle and maintains the ego-vehicle at a constant distance from the preceding vehicle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e_MVkKiG-16duvic0xRVmA.png" /><figcaption>Level 1 features. (a)Ian Maddox , <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.en">CC BY-SA 4.0</a>, via <a href="https://commons.wikimedia.org/wiki/File:Tesla_Autopilot_Engaged_in_Model_X.jpg">Wikimedia Commons</a>, (b) M. Minderhoud and Malyszkz, <a href="https://creativecommons.org/licenses/by-sa/3.0/deed.en">CC BY-SA 3.0</a> , via <a href="https://commons.wikimedia.org/wiki/File:Schema_ICC.svg">Wikimedia Commons</a>.</figcaption></figure><p>At Level 2, the automated driving system controls the ego-vehicle in both longitudinal and lateral directions simultaneously.</p><p>Note that for Levels 0–2, the automated driving system only provides driver assist features and the driver <strong>must</strong> constantly supervise the features for safety. Starting from Level 3, the driving autonomy changes to the automated driving features from driver assist features.</p><p>Level 3 provides the automated driving features under limited driving conditions. At Level 3, the automated driving system fulfills most of driving features without the need of supervision from the driver. In case some automated driving feature fails, the system sends warnings to the driver who needs to take over the vehicle within limited time.</p><p>Unlike the Level 2 features, which have been unified and developed over the car makers worldwide, there is a lack of unified definition about the driving conditions for the Level 3 features. Also, worldwide policies and regulations about the Level 3 driving have yet been formulated. Car makers define their own Level 3 driving scenarios. For example, Audi defined the Traffic Jam Assist (TJA) as a Level 3 feature in its A8 vehicle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*NoBIl56ClH1wCMQbINvZLA.png" /><figcaption>Level 3 Traffic Jam Assist (TJA) — Image by author.</figcaption></figure><p>Based on the SAE definition, on one hand, the Level 3 automated driving system allows the driver’s hands off the steering wheel. Without the need of supervising the driving system, the driver is able to do other activities, like playing game, working, etc. On the other hand, the Level 3 definition requires the driver to take over the vehicle within limited time. The two aspects of the definition seem conflicting to each other. It is hard to answer: (i) to what extent can the driver be released from driving? (ii) does the driver need to constantly get ready to take over? (iii) is the driver able to take over the vehicle within limited time if the driving system fails? (iv) does the driver need to take special trainings in order to take over in time? All aforementioned uncertainties affect the evolution of the Level 3 automated driving system.</p><p>Beyond Level 3, here come the two highest levels of automated driving: Level 4 and Level 5. For the features of these two levels, the driver needs to neither supervise the features nor take over the vehicle. All the driving tasks are fulfilled by the automated driving system. Accordingly, the steering wheel and the foot pedal may not be installed in the vehicle. The difference between Level 4 and Level 5 is that Level 4 provides the features under specified conditions, like harbors and ports, mining zones, and parks, etc. The variations of these specified conditions are more predictable and lead to lower technical challenges than Level 5. Compared to Level 4, Level 5 achieves the highest level of autonomy and allows for automated driving under all conditions.</p><h3>Summary</h3><p>In this article, we first introduce the definition of automated driving, commercial applications, and technologies involved. We also cover in detail the SAE levels of driving automation.</p><p>In the next article, we will describe the top players in the industry of self-driving cars and their technology and product development routes.</p><h3>Reference</h3><p>[1] <a href="https://www.sae.org/blog/sae-j3016-update">https://www.sae.org/blog/sae-j3016-update</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99d0e0fd56b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>