text
stringlengths
81
47k
source
stringlengths
59
147
Question: <p>I started modeling a linear regression problem using dense layers (layers.dense), which works fine. I am really excited, and now I am trying to model a time series linear regression problem using CNN, but from my research in this link <a href="https://machinelearningmastery.com/keras-functional-api-deep-learning/" rel="nofollow noreferrer">Machine learning mastery</a></p> <p>A CNN works well with sequence data, but my data isn’t sequential. My data set can be found here <a href="https://stackoverflow.com/questions/57224353/is-my-training-data-set-too-complex-for-my-neural-network">Stack overflow question</a>.</p> <p>Is there a multivariate time series/ time series neural network architecture that I can use for time series linear/nonlinear regression?</p> Answer:
https://ai.stackexchange.com/questions/13651/what-are-the-possible-neural-network-architecture-for-linear-regression-or-time
Question: <p><strong>How do you decide that you have tested enough hyper-parameter combinations for a specific neural network architecture to discard it and move on to a new model?</strong></p> <p>Do you have a structured (generic) approach? In practice, what gives you the necessary performance (e.g. &gt;= 80% accuracy) the fastest (w.r.t. to your work-hours) assuming there is no SOTA that easily exceeds your requirements and extensive hyper-parameter optimization is infeasible?</p> Answer:
https://ai.stackexchange.com/questions/31954/how-do-you-decide-that-you-have-tested-enough-hyper-parameter-combinations-for-a
Question: <p>I ended up working with a neural network <span class="math-container">$N(\cdot)$</span> characterized by the following structure:<span class="math-container">$$N(x)=V[\text{ReLU}(Ax+b)+Cx+d],$$</span> with input <span class="math-container">$x \in \mathbb{R}^n$</span> and parameters <span class="math-container">$V\in\mathbb{R}^{1\times m}$</span>, <span class="math-container">$A$</span>, <span class="math-container">$C \in \mathbb{R}^{m \times n}$</span> and <span class="math-container">$b$</span>, <span class="math-container">$d \in \mathbb{R}^m$</span>. Does anyone know what sort of &quot;standard&quot; architecture it represents?</p> Answer:
https://ai.stackexchange.com/questions/41340/a-neural-network-with-peculiar-architecture
Question: <p>Traditionally, when working with tabular data, one can be sure(or at least know) that a model works because the included features could explain a target variable, say &quot;<em>Price of a ticket</em>&quot; good. More features can be then be engineered to explain the target variable even better.</p> <p>I have heard people say, that there is no need to hand-engineer features when working with CNNs or RNNs or Deep Neural Networks, provided all the advancements in AI and computation. So, my question is, how would one know, before training, why a particular architecture worked(or would work) when it did or why it didn't when the performance isn't acceptable or very bad. And also that not all of us would have the time to try out all possible architectures, how can one know or at least be sure that something would work for the problem in hand. Or to say, what are the things one needs to follow when designing an architecture to train for a problem, to ensure that an architecture will work?</p> Answer:
https://ai.stackexchange.com/questions/22590/how-can-one-be-sure-that-a-particular-neural-network-architecture-would-work
Question: <p>As a follow-up on <a href="https://ai.stackexchange.com/questions/39386/open-source-vocal-cloning-speech-to-speech-neural-style-transfer">Open-source vocal cloning (speech-to-speech neural style transfer)</a>, I want to create a voice clone. Unfortunately, the answers in the thread above do not apply to my language and dialect (European Portuguese). So I would like to DIY a voice clone with a text-to-speech service (Google, Polly, Azure) and a neural network trained to transfer the style. The difference with most vocal cloning systems is that I can generate any amount of aligned data: the system and I both read the same script.</p> <p>A quick search for <code>vocal cloning with parallel|aligned data</code> yields no results specific to this problem. But from reading a few papers and their emphasis on non-aligned data (e.g., &quot;learned in an unsupervised way from unaligned data&quot; <a href="https://avdnoord.github.io/homepage/vqvae/" rel="nofollow noreferrer">here</a>), I get the impression that style transfer with aligned data is a simpler problem that may have established solutions.</p> <p>What papers, code, or architecture implement vocal cloning with aligned data?</p> Answer:
https://ai.stackexchange.com/questions/42989/neural-network-architecture-or-code-for-style-transfer-with-aligned-data
Question: <p>I would like to generate sequences of tuples using a neural network algorithm such that the model trains on a dataset of sequences of tuples and generates synthetic sequences of tuples. Each tuple <code>t_i</code> in a sequence is made of two words and has the following format <code>t_i=(a_i,d_i)</code> where <code>a_i</code> is the ith activity of a person (e.g., eating, running, etc) and <code>d_i</code> is the day of week for <code>a_i</code> (e.g., Monday,Tuesday, etc). I would like to find a neural network algorithm that best suits this task.</p> <p>I have thought to use a RNN or LSTM architecture and I know that there are many sequence generation algorithms based on RNN/LSTM e.g., <a href="https://github.com/minimaxir/textgenrnn?tab=readme-ov-file" rel="nofollow noreferrer">this text generation algorithm</a> but I think these algorithms are made to generate sequences of single words and not sequences of tuple of words. Thus, I think in the case of my example, these algorithms treat a tuple as a single token and not two tokens and accordingly, they ignore the relationships that might exist between the sequence of activities and the sequence of days. I have also found some papers regarding next tuple prediction but my problem is not next tuple prediction but whole tuple sequence generation. Finally, I have also thought about the multivariate time series generation algorithms but I think these algorithms are made for tuples of numerical values and not for tuples of words (such as in my case). I would like to find a sequence generation algorithm (preferably with implementation available online) that is really designed for tuples of words or at least consider the concerns describe above. Are there any suggestions?</p> Answer:
https://ai.stackexchange.com/questions/48485/best-neural-network-algorithms-architectures-for-generating-synthetic-sequences
Question: <p>I have a dataset consisting of a set of samples. Each sample consists of two distinct desctized signals S1(t), S2(t). Both signals are synchronous; however, they show different aspects of a phenomena.</p> <p>I want to train a Convolutional Neural Network, but I don't know which architecture is appropriate for this kind of data. <br/></p> <p>I can consider two channels for input, each corresponding to one of the signals. But, I don't think convolving two signals can produce appropriate features.</p> <p>I believe the best way is to process each signal separately in the first layers, then join them in the classification layers in the final step. How can I achieve this? What architecture should I use?</p> Answer: <p>I don't know what you mean by <em>desctized signals</em> but if I understand your question correctly, separating two signal and passing them through same architecture of CNN (even with different parameters) is not a good idea. Because when they are together (as different channels) they will be treated differently by the CNN (each channel has its own parameters) and even this way the network is able to combine these two signals and get better results by information extracted from this combination.</p>
https://ai.stackexchange.com/questions/25349/appropriate-convolutional-neural-network-architecture-when-the-input-consists-of
Question: <p>Assume that I want to solve an issue with a neural network that either I can't fit to existing architectures (perceptron, Konohen, etc) or I'm simply not aware of the existence of those or I'm unable to understand their mechanics and I rely on my own instead.</p> <p>How can I automate the choice of the architecture/topology (that is, the number of layers, the type of activations, the type and direction of the connections, etc.) of a neural network for an arbitrary problem?</p> <p>I'm a beginner, yet I realized that in some architectures (or, at least, in perceptrons) it is very hard if not impossible to understand the inner mechanics, as the neurons of the hidden layers don't express any mathematically meaningful context.</p> Answer: <p>I think in this case, you'll probably want to use a genetic algorithm to generate a topology rather than working on your own. I personally like <a href="http://nn.cs.utexas.edu/downloads/papers/stanley.ec02.pdf" rel="nofollow noreferrer">NEAT (NeuroEvolution of Augmenting Topologies)</a>.</p> <p>The original NEAT paper involves evolving weights for connections, but if you only want a topology, you can use a weighting algorithm instead. You can also mix activation functions if you aren't sure which to use. <a href="http://blog.otoro.net/2016/05/07/backprop-neat/" rel="nofollow noreferrer">Here</a> is an example of using backpropagation and multiple neuron types.</p>
https://ai.stackexchange.com/questions/1391/how-can-i-automate-the-choice-of-the-architecture-of-a-neural-network-for-an-arb
Question: <p>I want to teach a neural network to distinguish between different types of defects. For that, I generated images of fake-defects. The images of the fake-defect types are attached.</p> <p><a href="https://i.sstatic.net/I0GO0.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/I0GO0.jpg" alt="border" /></a></p> <p><a href="https://i.sstatic.net/iKkdP.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/iKkdP.jpg" alt="Border" /></a></p> <p><a href="https://i.sstatic.net/UDJvo.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/UDJvo.jpg" alt="Single Dirt" /></a></p> <p><a href="https://i.sstatic.net/b636R.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/b636R.jpg" alt="Scratch" /></a></p> <p><a href="https://i.sstatic.net/S9rqQ.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/S9rqQ.jpg" alt="Dust" /></a></p> <p><a href="https://i.sstatic.net/lNUBV.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/lNUBV.jpg" alt="Dot" /></a></p> <p>I tried many different network architectures now:</p> <ul> <li>resnet18</li> <li>squeezenet</li> <li>own architectures: a narrow network with broad layers and high dropout rates.</li> </ul> <p>I have to say that some of these defects have really random shapes, like the type single-dirt or multi-dirt. I imagine that the classification should not be as easy as I thought before, due to the lack of repetitive features within the defects. But I always feel like the network is learning some &quot;weird&quot; features, which do not occur in the test set, and the results are really frustrating. I felt like teaching binary images had way better results, which should IMO be not the case.</p> <p>Still, I feel like a neural network should be able to learn to distinguish them.</p> <p>Which kind of network architecture would you recommend to classify the images in the attachment?</p> Answer:
https://ai.stackexchange.com/questions/22649/which-neural-network-should-i-use-to-distinguish-between-different-types-of-defe
Question: <p>Why do we use Convolutional Neural Network (CNN) for image data and not the Feedforward Neural Network (FNN)? Draw and explain the architecture of Convolutional Network</p> Answer: <p>I highly recommend you read the seminal work on convolutional neural networks (CNNs):</p> <p>Lecun, Y., &amp; Bengio, Y. (1995). Convolutional networks for images, speech, and time-series. In M. A. Arbib (Ed.), The handbook of brain theory and neural networks MIT Press.</p> <p>In summary, CNNs provide the following advantages over feedforward neural networks:</p> <ul> <li><p><strong>Local Connectivity</strong>: In CNNs, each neuron in a layer is connected only to a small region of the input. This reflects the way images are structured, where local groups of pixels are often strongly correlated, indicating the presence of specific local features like edges, textures, or colors. This local connectivity reduces the number of parameters in the network, making it more computationally efficient.</p> </li> <li><p><strong>Shared Weights and Translation Invariance</strong>: CNNs use the same weights across different parts of the input, a concept known as weight sharing. This approach not only reduces the number of parameters but also provides the network with a form of translation invariance, meaning the network can recognize an object regardless of its location in the image.</p> </li> <li><p><strong>Hierarchical Feature Learning</strong>: CNNs are designed to automatically and adaptively learn spatial hierarchies of features from input images. The layers in a CNN typically detect edges in the initial layers, shapes in the middle layers, and high-level content like object parts in the deeper layers. This hierarchical structure is particularly suited for image data, as images often contain hierarchical patterns.</p> </li> <li><p><strong>Reduction in Overfitting</strong>: Due to their architecture, CNNs tend to have fewer parameters than fully connected feedforward networks of similar depth, which reduces the risk of overfitting on image datasets. This is especially important in image recognition tasks, where the input data can be very high-dimensional (like high-resolution images).</p> </li> <li><p><strong>Efficiency in Image Processing</strong>: CNNs are particularly efficient for image processing tasks. The combination of local connectivity and shared weights makes them more suited to handle the high dimensionality of raw image data compared to fully connected networks, which can become impractically large for image inputs.</p> </li> </ul> <p><a href="https://i.sstatic.net/KxocZ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/KxocZ.png" alt="enter image description here" /></a> <strong>Typical Layers in a CNN</strong></p> <ol> <li><strong>Input Layer</strong>: This is where the network receives the image data. Images are typically represented as a 3D array of size height x width x depth (depth refers to color channels, e.g., RGB).</li> <li><strong>Convolutional Layer</strong>: The core building block of a CNN that performs most of the computational heavy lifting. This layer uses filters (or kernels) to convolve the input and produce feature maps. Each filter detects features such as edges, corners, etc.</li> <li><strong>Activation Layer (ReLU)</strong>: After each convolution operation, the activation layer, typically a Rectified Linear Unit (ReLU), is applied to introduce non-linearity into the model, allowing it to learn more complex patterns.</li> <li><strong>Pooling Layer</strong>: This layer is used to reduce the spatial size (width and height) of the input volume for the next convolutional layer. It helps decrease the computational power required to process the data through dimensionality reduction. Max pooling is the most common type.</li> <li><strong>Fully Connected Layer (FC)</strong>: Neurons in a fully connected layer have full connections to all activations in the previous layer, as seen in regular Neural Networks. These layers are typically placed near the end of CNN architectures and can be used to optimize objectives like class scores.</li> <li><strong>Output Layer</strong>: The final layer, often a fully connected layer, outputs the final predictions of the network. For classification tasks, this might be a softmax layer that provides probabilities for each class.</li> </ol>
https://ai.stackexchange.com/questions/43145/why-we-use-convolutional-neural-network-for-image-data-and-not-the-feedforward-n
Question: <p>I've been doing some class assignments recently on building various neural networks. For convolutional networks, there are several well-known architectures such as LeNet, VGG etc. Such "classic" models are frequently referenced as starting points when building new CNNs. </p> <p>Are there similar examples for RNN/LSTM networks? All I've found so far are articles and slides explaining recurrent neurons, LSTM layers, and the math behind them, but no well-known examples of entire multi-layered network architectures, unlike CNNs which seem to have in abundance.</p> Answer: <p>In the paper, <a href="https://arxiv.org/pdf/1503.04069.pdf" rel="nofollow noreferrer">LSTM: A Search Space Odyssey</a> (2017), by Klaus Greff et al., eight LSTM variants on three representative tasks (<a href="https://en.wikipedia.org/wiki/Speech_recognition" rel="nofollow noreferrer">speech recognition</a>, <a href="https://en.wikipedia.org/wiki/Handwriting_recognition" rel="nofollow noreferrer">handwriting recognition</a>, and <a href="https://arxiv.org/pdf/1206.6392.pdf" rel="nofollow noreferrer">polyphonic music modeling</a>) are compared. </p> <p>The compared variants are </p> <ol> <li><p><a href="ftp://ftp.idsia.ch/pub/juergen/nn_2005.pdf" rel="nofollow noreferrer">Vanilla LSTM</a> features three gates (input, forget, output), block input, a single cell, an output activation function, and <a href="https://pdfs.semanticscholar.org/e10f/98b86797ebf6c8caea6f54cacbc5a50e8b34.pdf" rel="nofollow noreferrer">peephole connections</a> (connections from the cell to the gates). The output of the block is recurrently connected back to the block input and all of the gates. The <a href="ftp://ftp.idsia.ch/pub/juergen/nn_2005.pdf" rel="nofollow noreferrer">vanilla LSTM</a> is trained using gradient descent and <a href="http://axon.cs.byu.edu/~martinez/classes/678/Papers/Werbos_BPTT.pdf" rel="nofollow noreferrer">back-propagation through time</a> (BPTT). The <a href="http://www.bioinf.jku.at/publications/older/2604.pdf" rel="nofollow noreferrer">original LSTM</a> (which is not the vanilla LSTM) does not contain, for example, the forget gate or the peephole connections (but the cell possesses a <em>constant error carousel</em>, a constant weight of <span class="math-container">$1$</span>). </p></li> <li><p>LSTM trained based on the <a href="https://en.wikipedia.org/wiki/Extended_Kalman_filter" rel="nofollow noreferrer"><em>decoupled extended Kalman filtering</em></a> <a href="https://www.elen.ucl.ac.be/Proceedings/esann/esannpdf/es2002-211.pdf" rel="nofollow noreferrer">(DEKF-LSTM)</a>, which enables the LSTM to be trained on some pathological cases at the cost of high computational complexity.</p></li> <li><p><a href="http://people.idsia.ch/~tino/papers/schmidhuber.neco07.pdf" rel="nofollow noreferrer">Vanilla LSTM trained with an evolution-based method (called <em>evolino</em>)</a>, instead of BPTT.</p></li> <li><p><a href="http://people.idsia.ch/~juergen/icann2009bayer.pdf" rel="nofollow noreferrer">LSTM block architectures evolved with a multi-objective evolutionary algorithm</a>, so that to maximize fitness on <a href="https://en.wikipedia.org/wiki/Context-sensitive_grammar" rel="nofollow noreferrer">context-sensitive grammar</a>.</p></li> <li><p><a href="https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/43905.pdf" rel="nofollow noreferrer">LSTM architectures for large scale acoustic modeling</a>, which introduces a <em>linear projection layer</em> that projects the output of the LSTM layer down before recurrent and forward connections in order to reduce the number of parameters for LSTM networks with many blocks.</p></li> <li><p>An <a href="https://ieeexplore.ieee.org/abstract/document/6981033" rel="nofollow noreferrer">LSTM architecture with a trainable scaling parameter for the slope of the gate activation functions</a>, which improves the performance of LSTM on an offline handwriting recognition dataset.</p></li> <li><p><a href="https://link.springer.com/chapter/10.1007%2F978-3-319-11179-7_1" rel="nofollow noreferrer">Dynamic Cortex Memory</a>, an LSTM composed of recurrent connections between the gates of a single block, but not between different blocks, which improves the convergence speed of LSTM.</p></li> <li><p><a href="https://arxiv.org/abs/1406.1078" rel="nofollow noreferrer">Gated Recurrent Unit (GRU)</a>, which simplifies the architecture of the LSTM by combining the input and forget gate into an <em>update gate</em>.</p></li> </ol> <p>There are other related neural network architectures, such as the <a href="https://arxiv.org/pdf/1410.5401.pdf" rel="nofollow noreferrer">neural Turing machine (NTM)</a> or <a href="https://www.nature.com/articles/nature20101" rel="nofollow noreferrer">differentiable neural computer (DNC)</a>. In general, there are several architectures that use LSTM blocks, even though they are not just recurrent neural networks. Other examples are the <a href="https://arxiv.org/abs/1511.06279" rel="nofollow noreferrer">neural programmer-interpreter (NPI)</a> or the <a href="https://arxiv.org/pdf/1705.02670.pdf" rel="nofollow noreferrer">meta-controller</a>.</p>
https://ai.stackexchange.com/questions/14280/what-are-some-examples-of-lstm-architectures
Question: <p>I have a CNN architecture for CIFAR-10 dataset which is as follows:</p> <blockquote> <p>Convolutions: 64, 64, pool</p> <p>Fully Connected Layers: 256, 256, 10</p> <p>Batch size: 60</p> <p>Optimizer: Adam(2e-4)</p> <p>Loss: Categorical Cross-Entropy</p> </blockquote> <p>When I train this model, training and testing accuracy along with loss has a very jittery behavior and does not converge properly.</p> <p>Is the defined architecture correct? Should I have a max-pooling layer after every convolution layer?</p> Answer: <p>To be honest, your model is not very clear. But basically after the convolution, you need to add non-linear layers. Otherwise, there is no point of Neural Networks.</p> <p>You can add a Relu layer for sure. </p>
https://ai.stackexchange.com/questions/18073/is-this-neural-network-architecture-appropriate-for-cifar-10
Question: <p>Consider a feedforward neural network. Suppose you have a layer of inputs, which is feedforward to a hidden layer, and feedforward both the input and hidden layers to an output layer. Is there a name for this architecture? A layer feeds forward around the layer after it?</p> Answer: <p>This could be called a <a href="https://arxiv.org/pdf/1512.03385.pdf" rel="nofollow noreferrer">residual neural network (ResNet)</a>, which is a neural network with skip connections, that is, connections that skip layers. </p> <p>Here's a screenshot of a figure from the paper <a href="https://arxiv.org/pdf/1512.03385.pdf" rel="nofollow noreferrer">Deep Residual Learning for Image Recognition</a> (2015), an important paper that shows the usefulness of these architectures.</p> <p><a href="https://i.sstatic.net/C5zjY.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/C5zjY.png" alt="enter image description here"></a></p>
https://ai.stackexchange.com/questions/17822/what-is-the-name-of-this-neural-network-architecture-with-layers-that-are-also-c
Question: <p>I am training a transformer based neural network and the validation loss is not decreasing, but the training loss does decrease. I am wondering if it's possible to debug or change the architecture such that this is reversed, or if I definitely need to debug my dataset.</p> Answer:
https://ai.stackexchange.com/questions/45555/is-there-any-purpose-of-altering-neural-network-architecture-if-validation-loss
Question: <p>This post continues the topic in the following post: <a href="https://ai.stackexchange.com/q/17553/2444">Is it possible to train a neural network with 3 inputs and 12 outputs?</a>.</p> <p>I conducted several experiments in MATLAB and selected those neural networks that best approximate the data.</p> <p>Here is a list of them:</p> <ul> <li><p>Cascade-forward backpropagation</p></li> <li><p>Elman backpropagation</p></li> <li><p>Generalized regression</p></li> <li><p>Radial basis (exact fit)</p></li> </ul> <p>I did not notice a fundamental difference in quality, except for Elman's backpropagation, which had a higher error than the rest.</p> <p>How to justify the choice of the structure of the neural network in this case?</p> Answer:
https://ai.stackexchange.com/questions/17571/how-do-i-determine-the-best-neural-network-architecture-for-a-problem-with-3-inp
Question: <p>I am working on a prediction problem where each outcome vector in my training data <span class="math-container">$y_i$</span> was generated to satisfy a set of linear constraints <span class="math-container">$A_i y_i = b_i$</span>. I know each <span class="math-container">$A_i$</span> and <span class="math-container">$b_i$</span> exactly. I want to be able to train the model on inputs <span class="math-container">$u_i$</span>, return predicted <span class="math-container">$\hat{y_i}$</span> such that <span class="math-container">$A_i \hat{y_i}= b_i$</span> <span class="math-container">$\forall i$</span>. Then, I should be able to predict new output vectors <span class="math-container">$\hat{z_j}$</span> off of new inputs <span class="math-container">$v_j$</span> with new linear constraints like <span class="math-container">$C_j \hat{z_j} = d_j$</span>. The new predictions <span class="math-container">$\hat{z_j}$</span> should then satisfy <span class="math-container">$C_j \hat{z_j} = d_j$</span> <span class="math-container">$\forall j$</span>.</p> <p>I know I can modify the loss function using a penalty <span class="math-container">$\rho$</span> akin to a Lagrangian, <span class="math-container">$L = MSE + \rho (b - Ax)$</span> but I have only seen examples of this where there is one set of linear constraints that is the same for all observations, <span class="math-container">$A x_i = b$</span> <span class="math-container">$\forall i$</span>. (It might be that this is possible with unique <span class="math-container">$A_i, b_i$</span> and I just haven't seen how to do so.) I have a unique set of linear constraints for each observation. An alternative to Lagrangian loss functions might be to just pass the problem context <span class="math-container">$(A_i, u_i, b_i)$</span> as the training data, but the model might return <span class="math-container">$\hat{y_i}$</span> that don't satisfy the system of equations. Is there an existing architecture that can enforce context-specific linear constraints, and possibly use the data on the constraints to learn the weights? Perhaps the constraints can be encoded in the final layer of the network architecture, but I have not found any work that seems to do that.</p> Answer:
https://ai.stackexchange.com/questions/46756/is-there-a-neural-network-architecture-that-enforces-context-specific-constraint
Question: <p>I've been experimenting with different neural network architectures and am curious about the impact of input ranges on their performance. While normalizing inputs to ranges such as [0,1] or [-1,1] is a common practice, I wonder if there's a theoretically preferable input range that neural networks tend to perform better with. Are there any studies or theoretical foundations that suggest an optimal input range for neural networks? How does input range in general impact the convergence and overall accuracy of the models?</p> Answer: <p>Unfortunately, there is no <em>theoretically</em> optimal parameter for a neural network. However, they can be roughly defined when talking about a specific topic or application domain. <em>Normalization</em> is a very important procedure in the operation of neural networks. Normalization makes it easier for the network to recognize different <em>patterns</em>. By scaling all inputs between two numbers, the network will be able to recognize and generalize many different patterns.</p> <p>Let's take a look at these two input arrays:</p> <pre><code>[89, 90, 27, 0, 29, 42, 78, 33, 78, 12] [1.186667, 1.2, 0.36, 0, 0.386667, 0.56, 1.04, 0.44, 1.04, 0.16] </code></pre> <p>At first glance, these seem like two completely different arrays, right? It would be very difficult to determine anything from them.</p> <p>Let's scale them between <em>0</em> and <em>1</em>:</p> <pre><code>var array1:Array = [89, 90, 27, 0, 29, 42, 78, 33, 78, 12] var array2:Array = [1.186667, 1.2, 0.36, 0, 0.386667, 0.56, 1.04, 0.44, 1.04, 0.16] print(&quot;Array1: &quot; + str(normalize(array1))) print(&quot;Array2: &quot; + str(normalize(array2))) </code></pre> <p>The output:</p> <pre><code>Array1: [0.988889, 1, 0.3, 0, 0.322222, 0.466667, 0.866667, 0.366667, 0.866667, 0.133333] Array2: [0.988889, 1, 0.3, 0, 0.322223, 0.466667, 0.866667, 0.366667, 0.866667, 0.133333] </code></pre> <p>Now we can easily see that the patterns of the two arrays are exactly the same and show the same temporal changes. Likewise, the neural network can draw conclusions much more easily from normalized values.</p> <p>But then how can we decide which are the most optimal scaling ranges?</p> <h2>Normalization between -1 and 1:</h2> <p>If you are using activation functions like <strong>tanh</strong> that return only values between -1 and 1, it is a good idea to normalize the input data to this range as well. This will help the network to converge faster, as the distribution of the input data will better match the expected range of the activation function. If the input data contains both positive and negative values, normalising to the range -1 to 1 will ensure that the data is centred around zero.</p> <h2><strong>Normalization between 0 and 1:</strong></h2> <p>If you are using activation functions like <strong>Sigmoid</strong> or <strong>ReLU</strong>, it's a good idea to normalize input values between 0 and 1. The Sigmoid function gives values between 0 and 1, while ReLU gives only non-negative values. So normalization between 0 and 1 works well with these activation functions. If the input data only has positive values, such as pixel values (between 0 and 255), normalization between 0 and 1 is a natural choice because it is simple and easy to understand.</p> <hr /> <p><em>In summary, the choice between normalising to [-1,1] or [0,1] depends on the activation functions used, and the nature of the data.</em></p>
https://ai.stackexchange.com/questions/46150/is-there-a-theoretically-optimal-input-range-for-neural-networks
Question: <p>so I'm working on a Project where I want to predict the Vehicle Position from the Vehicle Data like speed, acceleration etc.. now the data that I have comes also with a timestamp for each sample ( I mean that I have also a timestamp feature).</p> <p>at first I thought that I should get rid of that timestamp feature because it is not relevant to my Project, I mean logically, I will not need a timestamp feature to predict the vehicle position, that didn't make sense to me when I first took a look at the dataset. I thought other features like speed, acceleration, braking pressure etc.. are more important and I thought also that the solution for this Problem would be to use a normal Deep NN or RBFNN for making this Prediction. recently, I read some papers that shows how a Convolutional NN can be also used for regression and that confused me to choose the Architecture needed for my Project. this Week I also watched a Tutorial where a RNN/ LSTM was implemented for regression Tasks. </p> <p>Now I'm very confused which architecture should I use for my Project. I also noticed that maybe if I used that timestamp feature, I can maybe use an RNN/LSTM Network for this Task but I don't know if my dataset can be seen as time-series dataset, actually the vehicle position doesn't depend on the time as far as I can tell.</p> <p>Hopefully can someone answer me based on Experience. It would be also great to have some Papers or references where I can look for more. </p> Answer:
https://ai.stackexchange.com/questions/15816/how-to-choose-the-suitable-neural-network-architecture-for-regression-tasks
Question: <p>Convolution Neural Network (CNNs) operate over strict grid-like structures (<span class="math-container">$M \times N \times C$</span> images), whereas Graph Neural Networks (GNNs) can operate over all-flexible graphs, with an undefined number of neighbors and edges.</p> <p>On the face of it, GNNs appear to be neural architectures that can subsume CNNs. Are GNNs really generalized architectures that can operate arbitrary functions over arbitrary graph structures?</p> <p>An obvious follow-up - <strong>How can we derive a CNN out of a GNN</strong>?</p> <p>Since non-spectral GNNs are based on message-passing that employ <em>permutation-invariant</em> functions, is it possible to derive a CNN from a base-architecture of GNN?</p> Answer: <p>Yes, a CNN can be formalized as a specific kind of GNN where nodes are connected together in a 2D lattice structure and the outer edge is padded with zeros. Down-sampling techniques or pooling layers are an additional operation which remove edge nodes or low activation nodes. Convolutional layers act in the same manner as GNN weights by comparing each node with it's neighbors.</p> <p>Yes, GNNs are generalized architectures of CNNs. A CNN is derivable by treating the image as a lattice graph and augmenting pooling and/or down-sampling layers. <code>N</code> <code>w x w</code> convolutional kernels has a node with feature of length <code>N</code> interacting with a <code>w</code>-hop neighborhood. Any node of distance <code>w</code> is considered adjacent.</p> <p>I am an expert on convolutional networks and not graph neural networks. Maybe these two articles would also be helpful. <a href="https://towardsdatascience.com/understanding-graph-convolutional-networks-for-node-classification-a2bfdb7aba7b?gi=4c06cb6c8e30" rel="nofollow noreferrer">https://towardsdatascience.com/understanding-graph-convolutional-networks-for-node-classification-a2bfdb7aba7b?gi=4c06cb6c8e30</a></p> <p><a href="https://medium.com/@rmwkwok/gnn-notes-series-explain-graph-convolutional-networks-gcn-with-knowledge-in-cnn-b827be1c872b" rel="nofollow noreferrer">https://medium.com/@rmwkwok/gnn-notes-series-explain-graph-convolutional-networks-gcn-with-knowledge-in-cnn-b827be1c872b</a></p> <p>My goal in writing this was to provide a more novice accessible answer than the others on this post.</p>
https://ai.stackexchange.com/questions/24891/how-can-we-derive-a-convolution-neural-network-from-a-more-generic-graph-neural
Question: <p>I am asking this question on deep neural network architectures only. If you want to restrict the domain of tasks then you can choose computer vision for this question.</p> <p>Suppose there is an architecture that performs well on a task. Is it possible can edit or append the first or last few layers and then it performs similarly well on the other task?</p> <p>If yes, please provide me an example of such architecture that performs well on at least a couple of tasks.</p> Answer:
https://ai.stackexchange.com/questions/34019/is-it-possible-that-a-deep-neural-network-with-some-variations-can-be-used-for
Question: <p>I'm currently trying to predict 1 output value with 52 input values. The problem is that I only have around 100 rows of data that I can use. </p> <p>Will I get more accurate results when I use a small architecture than when I use multiple layers with a higher amount of neurons? </p> <p>Right now, I use 1 hidden layer with 1 neuron, because of the fact that I need to solve (in my opinion) a basic regression problem. </p> Answer: <p>I'm not aware of a direct way for finding the best NN architecture for a given task, but the recommended way, as far as I know, is to devise a network that can overfit the training data, and then apply regularization on top of it.</p> <p>That way, you can be almost sure you're not underfitting/underperforming due to network capacity.</p>
https://ai.stackexchange.com/questions/18439/is-a-basic-neural-network-architecture-better-with-small-datasets
Question: <p>I have been coming across visualizations showing that the neural nets tend to perform better as compared to the traditional machine learning algorithms (Linear regression, Log regression, etc.)</p> <p>Assuming that we have sufficient data to train deep/neural nets, can we ignore the traditional machine learning topics and concentrate more on the neural network architectures?</p> <p>Given the huge amount of data, are there any instances where traditional algorithms outperform neural nets?</p> Answer: <p>&quot;Assuming that we have sufficient data...&quot; — that's quite a big assumption. Also, traditional methods are well understood, while neural networks (and especially deep learning) is still something of a black box: you train it, and then you get a mapping from input to output. But you don't really know how that mapping is achieved.</p> <p>It's not only about performance, it's also about efficiency (speed, use of power, etc) and transparency (being able to explain why something happens).</p> <p>So there are several reasons why we don't put all our eggs into the NN basket:</p> <ul> <li><p>it is a lot easier to see what's happening and diagnose errors with 'traditional' methods which are well-understood. This is an important point in real-life applications</p> </li> <li><p>in many cases we do not have the required amount of training data available that is necessary for deep learning approaches to work</p> </li> <li><p>training a DL system is much more time- (and energy) consuming than other algorithms</p> </li> </ul> <p>I'd much rather have a nuclear power plant operated by a traditional algorithm that makes a few mistakes, but nothing drastic (and being aware that it makes these kinds of mistakes allows you to guard against them), than have a total black box doing it where I have no idea why decisions are reached and what happens in edge cases not covered by the training data.</p> <p>It's fine for toy projects where the stakes are low, but in real-world applications there are often different constraints that DL systems cannot satisfy.</p> <p><strong>UPDATE:</strong> from my own professional experience — working on a conversational AI system for a major bank. Anything they do has to go through layers upon layers of compliance regulation and vetting. Now I'd challenge anyone to explain to a corporate lawyer that your NN will never give unsound advice, and sign in blood on the dotted line that you know exactly under which conditions which advice is given. This is much easier to do with an old-fashioned rule-based system.</p>
https://ai.stackexchange.com/questions/18085/is-traditional-machine-learning-obsolete-given-that-neural-networks-typically-ou
Question: <p>Trying to understand the VGG architecture and I have these following questions.</p> <ol> <li>I understand the general understanding of increasing filter size is because we are using max pooling and so its image size gets reduced. So in order to keep information gain, we increase filter size. But the last few layers in the VGG architecture, the filter size remained same when vgg was max pooling from 14x14 to 7x7 image size, the filter size remained same at 512x512. Why wasn’t there the need to increase filter size there?</li> <li>Also few consecutive layers, in the end, was constructed with both same filter and image size, those layers were built just to increase accuracy? (experimentation?)</li> <li>And I couldn’t wrap around that visualization at final filters have the entire face as the feature as I understood through convolution visualizing (Matt Zieler video explanation). But max pooling causes us to see only a subset part of the image right? When filter size is 512x512 (face as the filter/feature) the image size as 7x7, so how does entire face as a filter will work on images when we are moving over small subset of the image pixels?</li> </ol> <p><a href="https://i.sstatic.net/rVB4S.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/rVB4S.png" alt="VGG architecture summary"></a><a href="https://i.sstatic.net/yfw43.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/yfw43.png" alt="VGG architecture final layers summary"></a></p> Answer: <p>Good questions. Let me reply one by one.</p> <p>1- Filter size can be increased. There is no limit for it. However, think two cases:</p> <ul> <li>DNN part. Shape will be 1024 x 7 x 7 and it will map to 4096 features, it will cause 204M parameters at dense_1 layer. This change will cause two possible problem. Overfitting and inference/training speed.</li> <li>Sparsity. You can implement 1024 features at 5th conv block and train the network and check the accuracy to see if increased feature count will make any impact or not.</li> </ul> <p>So, to decide the number of con layers, it is a good practice to check sparsity of feature layers. </p> <p>2- If I did not understand your question wrong, those layers are DNN classifier as a fully connected layer.</p> <p>3- Maxpooling is not causing us to see a subset of the image. It is just an algorithm to resizing. What you see in that video is the filter response to some objects exist in the image. In deeper level, do not expect to have visual shape like in shallow layers. You may even get single white pixel at deepest layer and it may be a response to an object like human face. </p>
https://ai.stackexchange.com/questions/4711/trying-to-understand-vgg-convolution-neural-networks-architecture
Question: <p>I am using <a href="https://github.com/pytorch/examples/blob/master/reinforcement_learning/actor_critic.py" rel="nofollow noreferrer">Open AI's</a> code to do a RL task on an environment that I built myself.</p> <p>I tried some network architectures, and they all converge, faster or slower on CartPole.</p> <p>On my environment, the reward seems not to converge, and keeps flickering forever.</p> <p>I suspect the neural network is too small, but I want to confirm my belief before going the route of researching the architecture.</p> <p>How can I confirm that the architecture is the problem and not anything else in a neural network reinforcement learning task?</p> Answer: <h1>Check the function loss.</h1> <p>It might be that your environment is impossible to learn. However, most likely the network simply can't handle it. By measuring the loss during the learning stage, if you find it is always very high and does not decrease, it's a strong indication this might be the issue.</p> <p>Because the network is too simple, when you optimize for some states, you ruin others. There is not formal way to find out if this is the case, but since the same algorithm works elsewhere, it's either a problem of your environment, or of the network.</p>
https://ai.stackexchange.com/questions/10210/how-to-identify-too-small-network-in-reinforcement-learning
Question: <p>I had a task to implement a neural network that would carry out multiclass classification of traffic by several parameters. On the advice of colleagues, I chose the &quot;Multilayer Perceptron&quot; architecture. One of these days I will have a defense of my work, but I absolutely do not understand how to answer the question: &quot;Why did you choose this type of architecture?&quot;. Please tell me if there are any theses why the &quot;multilayer perceptron&quot; architecture is better than other neural network architectures for solving problems of multi-class traffic classification?</p> Answer: <p>This is a very general question, so I'll just point to a reference that should be a good starting point. <a href="https://arxiv.org/abs/1810.07906" rel="nofollow noreferrer">Deep Learning for Encrypted Traffic Classification: An Overview</a> seems to contain exactly what you're looking for:</p> <blockquote> <p>Several factors affect the choice of deep learning models for network traffic classification. The most important one is the choice of features. ...</p> </blockquote> <blockquote> <p>Table II summarizes features, the corresponding models, and their properties.</p> </blockquote>
https://ai.stackexchange.com/questions/35873/how-to-justify-the-chosen-neural-architecture
Question: <p>Does anyone have any pointers to resources about the properties of randomly initialized neural networks (with no training)? I'm guessing this might depend on the network architecture and initialization scheme, but I'm most interested in properties that seem to be mostly true across architectures and initializations.</p> <p>In particular, I'm wondering what the distributions over outputs look like. Intuitively, one would expect most output distributions to be random, but I'm sure there are also &quot;adversarial examples&quot; that could be crafted which leads the NN to output highly-confident predictions.</p> Answer:
https://ai.stackexchange.com/questions/37128/distributions-over-outputs-for-randomly-initialized-neural-networks
Question: <p>Below is the loss of the same training run at different scales illustrating the plateau phenomenon. <img src="https://substackcdn.com/image/fetch/f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fbucketeer-e05bbc84-baa3-437e-9518-adb32be77984.s3.amazonaws.com%2Fpublic%2Fimages%2Fb7759d9f-88f2-4a96-a38a-82e281b7415e_1024x300.png" alt="" /> <a href="https://arxiv.org/pdf/2007.07213.pdf" rel="nofollow noreferrer">Source p3</a>.</p> <p>It seems to me that each dip adds constraints to the neural network optimization, and that neural networks must be highly over parameterized to enable the optimizer to find paths through to the next dip.</p> <p>I am trying to train timeseries features for a covariance matrix (i.e. <code>einsum('bic,bjc-&gt;bij', model(s0), model(s1))</code>). The first dip corresponds to the neural net maximizing the cosine similarities, while being linear in the magnitude i.e. <span class="math-container">$\gamma\lVert s \rVert =\lVert model(s)\rVert$</span>. The next dip corresponds to the the neural network being nonlinear in magnitude (i.e. silence, and everything else, being mapped onto the unit sphere).</p> <p>Here are a few responses to plateauing</p> <ol> <li>Regularize the architecture (an architecture that is non-linear in magnitude)</li> <li>Regularize the loss function (punish being linear in magnitude)</li> <li>Iterate on the training set to find architectures/hyperparameters that plateau less.</li> <li>Brute force it. Just leave the neural network training.</li> </ol> <p>I'm sceptical about 1 and 2 as it would only get you past the first plateau. I don't hear much about 3, although I think it might be a good idea. Does anyone do this in practice?</p> Answer: <p>I think the primary solution to plateauing is improving the dataset.</p> <p>The iteration process should be</p> <ol> <li>Train the neural network</li> <li>Identify what properties are causing the neural network to plateau.</li> <li>Gather more data, improve the targets, argument the existing dataset, to target these undesired properties.</li> <li>Find the next plateau, and repeat until the desired results are achieved.</li> </ol> <p>We are changing the <a href="https://youtu.be/78vq6kgsTa8?t=978" rel="nofollow noreferrer">loss landscape</a> using the dataset.</p>
https://ai.stackexchange.com/questions/37716/alternatives-to-brute-forcing-neural-network-plateau
Question: <p><a href="https://arxiv.org/abs/1810.04805" rel="nofollow noreferrer">BERT</a> encodes a piece of text such that each token (usually words) in the input text map to a vector in the encoding of the text. However, this makes the length of the encoding vary as a function of the input length of the text, which makes it more cumbersome to use as input to downstream neural networks that take only fixed-size inputs.</p> <p>Are there any transformer-based neural network architectures that can encode a piece of text into a fixed-size feature vector more suitable for downstream tasks?</p> <p><strong>Edit:</strong> To illustrate my question, I’m wondering whether there is some framework that allows the input to be either a sentence, a paragraph, an article, or a book, and produce an output encoding on the same, fixed-sized format for all of them.</p> Answer: <p>One way you could do it is by using <strong>SentenceTransformers</strong>.</p> <blockquote> <p>SentenceTransformers is a Python framework for state-of-the-art sentence, text and image embeddings. The initial work is described in our paper <a href="https://arxiv.org/abs/1908.10084" rel="nofollow noreferrer">Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks.</a></p> </blockquote> <p>To install it via pip</p> <pre><code>pip install -U sentence-transformers </code></pre> <p>To generate sentence embedding</p> <pre><code>from sentence_transformers import SentenceTransformer # We are using &quot;paraphrase-MiniLM-L6-v2&quot; model here, You can find list of model [here][2] model = SentenceTransformer('paraphrase-MiniLM-L6-v2') # Our sentences we like to encode sentences = ['This framework generates embeddings for each input sentence', 'Sentences are passed as a list of string.', 'The quick brown fox jumps over the lazy dog.'] # Sentences are encoded by calling model.encode() embeddings = model.encode(sentences) #Print the embeddings for sentence, embedding in zip(sentences, embeddings): print(&quot;Sentence:&quot;, sentence) print(&quot;Embedding:&quot;, embedding) print(&quot;&quot;) </code></pre> <p>But remember, SentenceTransformers models have an input limit as well, 512 tokens usually. If your text is more than that, then it might not be a suitable method.</p>
https://ai.stackexchange.com/questions/23611/are-there-transformer-based-architectures-that-can-produce-fixed-length-vector-e
Question: <p>I am working on neural networks for oceanographic data and face challenges in dealing with masked values, which I set to NaN.. I can train a neural network model with 1D vertical profiles (e.g. temperature and salinity at different depths in the ocean) and 2D ocean surface data (e.g. sea surface temperature), where</p> <ol> <li>In 1D data, values near the seafloor are masked by the ocean floor. by the ocean floor.</li> <li>In 2D data, masked values occur due to land masses.</li> </ol> <p>I would like to understand the best practices for handling NaN values in these contexts. Specifically:</p> <ol> <li>How can NaN values be handled within neural networks during training without altering the original data by filling in arbitrary values?</li> <li>Which neural network architectures or strategies are best suited to deal with for dealing with masked values, where the masked values represent important important information about the system?</li> <li>If filling in masked values is unavoidable, is there any evidence or proof that adding evidence that filling in masked values does not adversely affect the training of the the training of the neural network?</li> </ol> <p>Any technical advice or references would be greatly appreciated.</p> Answer:
https://ai.stackexchange.com/questions/47006/how-to-handle-masked-values-in-neural-networks-for-geospatial-data
Question: <p>I’ve been reading about neural network architectures. In certain cases, people say that the sigmoid "more accurately reflects real-life" and, in other cases, functions like hard limits reflect "the brain neural networks more accurately". </p> <p>What activation functions are better for what problems?</p> Answer:
https://ai.stackexchange.com/questions/17526/what-activation-functions-are-better-for-what-problems
Question: <p>We have convolutional neural networks and recurrent neural networks for analyzing, respectively, images and sequential data.</p> <p>Now, suppose I want to approximate the unknown function <span class="math-container">$f(x,y) = \sin(2\pi x)\sin(2\pi y)$</span>, with domain <span class="math-container">$\Omega = [0,1]\times [0,1]$</span>, that is, <span class="math-container">$x$</span> and <span class="math-container">$y$</span> can be between <span class="math-container">$0$</span> and <span class="math-container">$1$</span> (inclusive).</p> <p>How do I determine which neural network architecture is more appropriate to approximate this function? Which kind of activation functions would be better suited for this?</p> <p>Note that, generally, I don't know a priori which function the neural network has to learn. I am just asking for this specific <span class="math-container">$f(x, y)$</span>, as it could be a solution for a differential equation. And <span class="math-container">$\Omega$</span> is the domain, i.e., I don't care about the output of the neural network outside <span class="math-container">$\Omega$</span>.</p> Answer: <p>If the concept class specified is</p> <p><span class="math-container">$$f(x, y) = k \, \sin(2 \pi f_x x) \, sin(2 \pi f_y y) \\ \land 0 &lt; x &lt; 1 \\ \land 0 &lt; y &lt; 1 \; \text{,}$$</span></p> <p>and the optimum fit to example data is expected occur when <span class="math-container">$k \approx 1 \land f_x \approx 1 \land f_y \approx 1$</span>, then it is not an AI problem. It is a problem that can be solved with a least squares convergence, probably in conjunction with a Fourier transform.</p> <p>If nothing is known about <span class="math-container">$f(x, y)$</span> except continuity and that it is single valued with respect to <span class="math-container">$(x, y)$</span>, then few conclusions can be drawn about best approach. In such a case, the domain of <span class="math-container">$x$</span> and <span class="math-container">$y$</span> are irrelevant because they can be normalized. Furthermore, the tree of operations, such as <span class="math-container">$\sin()$</span> and multiplication, are irrelevant too, because the function could just as easily be</p> <p><span class="math-container">$$f(x, y) = \ln(x) + \Gamma(y) - k \, \text{.}$$</span></p> <p>The question indicates the design involves CNN and RNN components for analyzing images and sequential data. It is not clear whether the CNN is for the discovery of objects or waves (given the <span class="math-container">$\sin()$</span> in the function mentioned) and whether those objects move between frames so that the RNN must detect motion.</p> <p>Nothing is given about the pool of example data available or planned to be available or the expected outputs of the system. If data is sequential, where is <span class="math-container">$t$</span> in the function? What is the objective of image analysis?</p> <p>Although a deep MLP (multilayer perceptron) with SGD can learn an arbitrary function, it is hardly an architecture, the mention of images, CNN, RNN, and sequential data, MLP with SGD does not seem to match.</p> <p>Regarding activation functions, the inner layer functions would depend on the higher level design requirements. The activation functions of the last layer of a single artificial network is usually chosen to match the data type and range of desired output for each output channel (dimension).</p> <p>If the objective of this question is to take images and sequential data and produce something useful without <em>a priori</em> defining what useful means, then it is an unsolved AI problem thus far and no known topology comprised of artificial networks and other AI building blocks provide a solution. The autonomous development of internal concepts of usefulness would need to be developed mathematically and algorithmically and become practically speed optimized in hardware and software first.</p>
https://ai.stackexchange.com/questions/9319/which-neural-network-should-i-use-to-approximate-a-specific-but-unknown-function
Question: <p>I'm looking for a neural network architecture that excels in counting objects. For example, CNN that can output the number of balls (or any other object) in a given image.</p> <p>I already found articles about crowd counting. I'm looking for articles about different types of objects.</p> Answer: <p>If you want to count the number of objects using a neural network, you can use pretrained YOLO with the bottom prediction layer removed, and feed the features to a classification feed forward layer of let's say 1000 class representing 0-999 objects in the image. You can then train it and propagate the gradients through it. For example, in the pytorch code for YOLO,(source:<a href="https://github.com/eriklindernoren/PyTorch-YOLOv3" rel="nofollow noreferrer">https://github.com/eriklindernoren/PyTorch-YOLOv3</a>) You can add a <code>nn.Linear</code> and use cross entropy loss to classify the number of images. You can also change the architecture completely. Maybe you can try adding layers to reset or other classifying network to count the number of objects. Hope this can help you and have a nice day!</p>
https://ai.stackexchange.com/questions/11139/which-neural-network-can-count-the-number-of-objects-in-an-image
Question: <p>I work with neural networks for real-time image processing on embedded softwares and I tested different architectures (Googlenet, Mobilenet, Resnet, custom networks...) and different hardware solutions (boards, processors, AI accelerators...). I noticed that the performance of the system, in terms of inference time, does not depend only on the processor but also on other factors. </p> <p><em>For example</em>, I have two boards from different manifacturers, B1 (with a cheap processor) and B2 (with a better processor), and two neural networks, N1 (very light with regular convolutions and fully connected layers) and N2 (very large, with inception modules and many layers). The inference time for N1 is better on B1, while for N2 it is better on N2. Moreover, it happens that, as the software is executed, the inference time changes over time.</p> <p>So my question is: <strong>in an embedded system, what are the aspects that impact on the inference time, and how?</strong> I am interested not only in the hardware features but also in the neural network architecture (convolutional filter size, types of layers and so on).</p> Answer: <p>You can expect that the inference time will strongly depend on particular hardware and software present on your platform. First, GPU equipped devices (eg NVidia TX) will outperform non-GPU equipped devices (eg. Intel Movidius). Second, software support (eg. cudnn, TensorRT) will make dramatic further impact. </p> <p>For instance, we have measured the inference time of two convolutional models. The model A requires 250% more floating point operations than the model B. Yet, the two models take roughly the same time to evaluate on our device, since the layers of model A are better optimized in software. Conclusion: algorithmic complexity and practical execution time on a particular computing platform are not bound to be proportional any more.</p>
https://ai.stackexchange.com/questions/10418/what-are-the-aspects-that-most-impact-on-the-inference-time-for-neural-networks
Question: <p>I'm studying recurrent neural networks. Reading <a href="https://stanford.edu/%7Eshervine/teaching/cs-230/cheatsheet-recurrent-neural-networks" rel="nofollow noreferrer">this page</a> where it lists different types of recurrent network architectures, I think think of applications involving one-to-many (speech/sentence generation), many-to-one (a conventional time-series classification/prediction task) and many-to-many (machine translation). But I can't really think of an application where it's one-to-one. What is one-to-one used for?</p> <p>[Edit] Note that on the page, it says ``Traditional neural network'' for one-to-one networks. But a traditional neural network would be a feedforward network rather than RNN? [\Edit]</p> Answer:
https://ai.stackexchange.com/questions/35155/applications-of-one-to-one-recurrent-networks
Question: <p>I have become more familiar with libraries such as tensorflow for a while now, and have become interested in utilizing neural networks for solving specific problems. The big question I have is, what are some principles that you have to take into account for designing your neural networks architecture?</p> <p>Some other questions I have are:</p> <ul> <li>Do I want my network to slowly reduce the dimensionality of data (so it picks out important features), the deeper it goes? What happens when the output (lets say its one hot encoded, so the no. classes is in the 1000s while your e.g text is only of length 30) is a lot bigger than the input?</li> <li>If so, then what do I do when I have to process a single class? Do I just add layers which expand off that 1 input (isn't that wasting resources?)</li> </ul> <p>What resources do you recommend I should look into?</p> Answer: <p>Designing neural network architectures from scratch for harder tasks is work usually performed by entire research groups (whether academic or business). There are, however, some things to keep in mind:</p> <ul> <li><p>Deeper networks have more abstraction, but also higher complexity. This means they can learn more complicated relations between input and output, but can also maximally encode the noise in the dataset. You may know this as the bias/variance trade-off, but is more often called over-fitting.</p> </li> <li><p>The type of data that goes into a network and the intuitive aspects of the data help decide what type of layers to use. Linear layers are your baseline. Convolutional layers when location is important (whether 1D, 2D or 3D). Attention layers for context, such as in language models. Recurrent connections for time-series data, such as speech patterns or observations over time.</p> </li> <li><p>Determining best practices on your own is an impossible task. There is a reason research is based on previous work. You may gain intuition over time, but decisions like when to use additional operations such as pooling, batch normalization, or which hyper parameters to use, such as activation functions, optimizers and learning rate, are best borrowed from existing work. Try to find work on a similar task to what you want to do and read some papers, preferably, or blogs and tutorials if the former is too complex.</p> </li> </ul> <p>If you have a specific task in mind, by all means post it as a comment to this answer and I can help you find similar work and/or suggest some intuitive starting point from my own experience.</p> <p>In response to your second question: You do not need to reduce the dimensionality of your data from the first layers of your model. In fact, you can expand it considerably. In the end you need to boil it down to the format of your output. For example classification using a CNN will first create feature maps of your data, which will increase dimensionality (e.g. 256x256x3 image to 128x128x64 feature maps), then it will flatten the features (128x128x64 feature maps to 1048576 hidden nodes) and finally it will classify (1048576 hidden nodes to 1000 output classes).</p>
https://ai.stackexchange.com/questions/36326/principles-of-designing-a-neural-network
Question: <p>I understand that to solve multilabel classification problems, we can use the softmax activation function in the output layer of the neural network. The softmax function outputs probabilities of each label, and the label with highest probability is then predicted as the target label. However, I just saw in a research paper that the authors used regression function instead of softmax function, in output layer. The paper says:</p> <blockquote> <p>Because regression classification can automatically adjust classification thresholds based on data distribution to maximize classification performance</p> </blockquote> <p>I do not understand how can the model learn classification thresholds by itself? Are these thresholds part of the neural network architecture? Are these thresholds trained like weights of layers?</p> <p>This is the link of the paper: <a href="https://www.sciencedirect.com/science/article/abs/pii/S016816991931556X" rel="nofollow noreferrer">https://www.sciencedirect.com/science/article/abs/pii/S016816991931556X</a></p> Answer: <p>First thing to notice, is that the assumptions on the target don't match the ones of multi-classifications: in particular, in multi-class classification, it's generally assumed that any other class outside the target one, is equally bad.</p> <p>Instead here, it's clear that this is not true:<br /> <a href="https://i.sstatic.net/eWbBx.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/eWbBx.png" alt="enter image description here" /></a></p> <p>Given an input with target &quot;Healty Apple&quot;, predicting &quot;General Apple Scab&quot; is not as bad as predicting &quot;Serious Cedar Apple Rust&quot;... in other words, the class order counts.</p> <p>In order to capture this property, they decide to use classification regression.</p> <p>About the automatic threshold, they don't say anything about it on the paper, so in my opinion what they do is to adjust them to improve performance.</p> <p>On top of my head, one way is by predicting the regression score for the training set, and then fitting 6 Gaussian distributions (like a naive Bayes model), and adjusting the threshold by moving them so that they best fit the result.... or you can just plot them with different colors and check where the colors lies</p>
https://ai.stackexchange.com/questions/41461/how-can-a-regression-based-neural-network-learn-class-thresholds
Question: <p>everyone. I am working on a nested neural network architecture. For the sake of better understanding my question, simply assume the loss is</p> <p><span class="math-container">$L = G(k’) - H(k'')$</span></p> <p>where <span class="math-container">$G$</span> and <span class="math-container">$H$</span> are two functions we do not need to know but variable <span class="math-container">$k'$</span> and <span class="math-container">$k''$</span> stem from neural network NNs such that</p> <p><span class="math-container">$k’ = NNs(k),\quad k’’ = NNs(k’)$</span></p> <p>so this would make the acquirement of <span class="math-container">$k''$</span> go through a nested architecture of the same neural networks, such that</p> <p><span class="math-container">$k'' = NNs(NNs(k))$</span></p> <p>Apparently, to obtain output <span class="math-container">$k’’$</span> the same neural network gets nested once:</p> <p><span class="math-container">$k \to NNs \to k′ \to NNs \to k′′$</span></p> <p>So my question is what is the potential issue of the nested neural network? Is there any paper that I could look into? Pytorch forum told that stale forward activations are used during a backward pass could raise issue, but I cannot find any example (the same question has been asked at <a href="https://discuss.pytorch.org/t/how-does-backward-propagation-work-in-a-nested-neural-network/189962" rel="nofollow noreferrer">Pytorch forum</a>).</p> Answer: <p>Isn't this just a very short recurrent neural network? Same issues apply, although they are less severe since you aren't applying as many recurrent iterations. Once you start &quot;nesting&quot; them more, most typical issues are vanishing and exploding gradients.</p>
https://ai.stackexchange.com/questions/42777/what-is-the-potential-issue-of-nested-neural-networks
Question: <p>Just came across <a href="https://www.gwern.net/newsletter/2020/05#gpt-3" rel="nofollow noreferrer">this article on GPT-3</a>, and that lead me to the question:</p> <p>In order to make a certain kind of neural network architecture smarter all one needs to do is to make it bigger?</p> <p>Also, if that is true, how does the importance of computer power relates with the importance of fine-tuning/algorithmic improvement?</p> Answer: <p>First of all, there is no real 'intelligence' innate to artificial Neural Networks (NNs). All they do is trying to approximate a mathematical function with a certain degree of generalization (hopefully without learning a given dataset by heart, i.e. hopefully without <em>overfitting</em>).</p> <p>The more nodes (or <em>neurons</em>) you include into the network, the more complex a function can be that a network can learn to approximate. It's similar to high-school math: The higher the degree of some polynomial, the better the polynomial can be adjusted to fit some observation to be modeled; with the only difference being that NNs commonly include non-linearities and are trained via some kind of stochastic gradient descent.</p> <p>So, yes. The more nodes a model possesses, the higher the so-called <em>model capacity</em>, i.e. the higher the degree of freedom a NN-model has to fit some function. After all, NN are said to be universal function approximators - given they have enough internal nodes in their hidden layer(s) to fit some given function.</p> <p>In practice, however, you don't want to blow up a model architecture unnecessarily, since this commonly results in overfitting if it doesn't cause some instabilities of the training procedure instead.</p> <p>Generally, the larger the model to be trained, the higher the computational cost to train the network.</p> <p>A common suggestion is to reduce the number of nodes in a network at the expense of increasing a network's depth, i.e. the number of hidden layers. Often, that can help reduce the demand for excessively many nodes.</p>
https://ai.stackexchange.com/questions/22469/is-the-size-of-a-neural-network-directly-linked-with-an-increase-in-its-intelige
Question: <blockquote> <p><a href="https://medium.com/saarthi-ai/transformers-attention-based-seq2seq-machine-translation-a28940aaa4fe" rel="noreferrer">Attention</a> idea is one of the most influential ideas in deep learning. The main idea behind attention technique is that it allows the decoder to "look back” at the complete input and extracts significant information that is useful in decoding.</p> </blockquote> <p>I am really having trouble understanding the intuition behind the attention mechanism. I mean how the mechanism works and how to configure.</p> <p>In simple words (and maybe with an example), what is the intuition behind the attention mechanism?</p> <p>What are some applications, advantages &amp; disadvantages of attention mechanism?</p> Answer: <p>Simply put, the attention mechanism is loosely inspired on well, attention. Consider we are attempting machine translation on the following sentence: "The dog is a Labrador." If you were to ask someone to pick out the key words of the sentence, i.e. which ones encode the most meaning, they would likely say "dog" and "Labrador." Articles like "the" and "a" are not as relevant in translation as the previous words (though they aren't completely insignificant). Therefore, we focus our attention on the important words.</p> <p>Attention seeks to mimic this by adding attention weights to a model as trainable parameters to augment important parts of our input. Consider an encoder-decoder architecture such as the one Google Translate uses. Our encoder recurrent neural network (RNN) encodes our input sentence as a context vector in some vector space, which is then passed along to the decoder RNN which translates it into the target language. The attention mechanism scores each word in the input (via dot product with attention weights), then passes these scores through the softmax function to create a distribution. This distribution is then multiplied with the context vector to produce an attention vector, which is then passed to the decoder. In the example in the first paragraph, our attention weights for "dog" and "Labrador" would hopefully become larger in comparison to those for the other words during training. Note that all parts of the input are still considered since a distribution must sum to 1, just some elements have more effect on the output than others.</p> <p>Below is a diagram from Towards Data Science that illustrates this concept very nicely in terms of an encoder-decoder architecture.</p> <p><a href="https://i.sstatic.net/TCwv1.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/TCwv1.jpg" alt="enter image description here"></a></p> <p>The advantages of attention is its ability to identify the information in an input most pertinent to accomplishing a task, increasing performance especially in natural language processing - Google Translate is a bidirectional encoder-decoder RNN with attention mechanisms. The disadvantage is the increased computation. In humans, attention serves to reduce our workload by allowing us to ignore unimportant features, however in a neural network, attention entails overhead as we are now generating attention distributions and training our attention weights (we are not actually ignoring the unimportant features, just diminishing their importance).</p>
https://ai.stackexchange.com/questions/21389/what-is-the-intuition-behind-the-attention-mechanism
Question: <p>I am trying to understand why attention models are different than just using neural networks. Essentially the optimization of weights or using gates for protecting and controlling cell state (in recurrent networks), should eventually lead to the network focusing on certain parts of the input/source. So what is attention mechanism really adding to the network? </p> <p>A potential answer in the case of Encoder-Decoder RNNs is: </p> <blockquote> <p><a href="https://arxiv.org/pdf/1409.0473.pdf" rel="noreferrer">The most important distinguishing feature of this approach from the basic encoder–decoder is that it does not attempt to encode a whole input sentence into a single fixed-length vector. Instead, it encodes the input sentence into a sequence of vectors and chooses a subset of these vectors adaptively while decoding the translation. This frees a neural translation model from having to squash all the information of a source sentence, regardless of its length, into a fixed-length vector. We show this allows a model to cope better with long sentences.<br> - Neural Machine Translation by Jointly Learning to Align and Translate</a></p> </blockquote> <p>which made sense and the paper says that it worked better for NMT.</p> <p>A previous study indicated that breaking down the sentence into phrases could lead to better results:</p> <blockquote> <p><a href="https://arxiv.org/pdf/1409.1257.pdf" rel="noreferrer">In this paper, we propose a way to address this issue by automatically segmenting an input sentence into phrases that can be easily translated by the neural network translation model. Once each segment has been independently translated by the neural machine translation model, the translated clauses are concatenated to form a final translation. Empirical results show a significant improvement in translation quality for long sentences.<br> - Overcoming the Curse of Sentence Length for Neural Machine Translation using Automatic Segmentation</a></p> </blockquote> <p>which paved the way for further research resulting in attention models.</p> <p>I was also going through an article on <a href="https://medium.com/octavian-ai/attention-is-not-quite-all-you-need-cb605ef3aff6" rel="noreferrer">Attention is not quite all you need</a> where it said something similar: </p> <blockquote> <p>An LSTM has to learn to sequentially retain past values together in a single internal state across multiple RNN iterations, whereas attention can recall past sequence values at any point in a single forward pass.</p> </blockquote> <p>and a more curated blog on the family of attention mechanism gives insight on how different ways have been formulated for implementing the concept: <a href="https://lilianweng.github.io/lil-log/2018/06/24/attention-attention.html" rel="noreferrer">Attention? Attention!</a></p> <p>Specifically, I want to know how attention mechanism is formulated for this task (aforementioned) or in general. A detailed mathematical insight would be helpful, probably somewhat on these lines: <a href="https://srome.github.io/Understanding-Attention-in-Neural-Networks-Mathematically/" rel="noreferrer">Understanding Attention in NN mathematically</a></p> Answer: <p>There's plenty, but keep in mind that these articles do not describe the same approach. They simply have attention shifting automation as part of their approaches and therefore must detect a need for shift and execute it in a way that improves speed, accuracy, reliability or some combination of them.</p> <p>There is no one dominant attention approach and probably will not be. In fact, the earliest attention mechanism in common use in machines was likely the electromechanical fire alarm. In digital systems, it would be a vacuum tube electric eye driving an intruder alert followed by the first hardware interrupts in transistor microprocessor boards.</p> <p>The sophistication of hardware interrupts in contemporary computer systems is probably higher than attention mechanisms in neural nets as of this writing, but that may change. Currently the dictionary definition of attention is the only constraint we can place on these newer approaches in artificial networks.</p> <ul> <li>The four working links in the question (one is broken) lead to articles with some mathematical description, so the question half answers itself.</li> <li>This article, <a href="https://pdf.sciencedirectassets.com/271585/1-s2.0-S0004370200X00331/1-s2.0-S0004370297000659/main.pdf?x-amz-security-token=AgoJb3JpZ2luX2VjEOr%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEaCXVzLWVhc3QtMSJHMEUCIQCVfJlD30DAXF7w%2BJZTxVddGdAUgsgNTlP3Db8WMtDDlAIgUU7ITEmLZveMDUkKDLVV50AoHNwUQ0hqDzLJR48UKA4q4wMI4v%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FARACGgwwNTkwMDM1NDY4NjUiDOiCgCnrXcO4FYPkDCq3A9%2Bvw3GIADb%2FYrKeeImglZyeVuKDHCj5kt2lG7Zskv4scJPYJ4CH7CGL2A127Os3RvLzkHT87NUqZIUkKm%2FQPYSxJ2Cn6dmhmVgr2G44OcRT72nd84hBMN%2BYFzy3bcDcZax9AeM%2Br9fGEa1XtkDmsiMsvLfGEbByZ%2FoEZV0Kn5sxJBTBKaD5oHiKmdCDttXf9bzn0nZYEa2WA3BOzrQ8gBmtml%2BtdUa2arQXlvtsDJelhL5zjjPgJzJkOxGDLxOrEl28seWX75VNsE7010HYbpbteohQEFeAqLmmF0KLzQutYsjpfEHxeOmDuM9uzMlFYMlXdQA923o6dg%2F5YReXwon3fa84w%2FKn6cGztbDxt%2BS0n60P7FJnjNAZDqHwChSmKL3%2F61Pbie3lnfT7RAP%2B9kfKPIgfctjkjByVd2%2FB7y93X36wK%2FUwqcgnycNbfvdtY6rBGnqLXcEKG82l4bzVqTHQS8sYd791XxXa6dhw0jbAn%2Fk5aBM0ofELo4b67jfERsgj7oy4KwofjrH1WY6ExU5vMP%2FWSDPK0yPXayPWlQrOzsF0vWggkMUJ52A3jw%2FHvyU4DLotTNAwitLt5gU6tAHA%2Fy0ooqh979HVQpd5%2FGlH5eFEkiSVVRdi76GZWckrduAd1pSMPpfgKmIJfh0MDcWXUGZCx%2FR3qhq1nIzUjcgao3Iw6UYkI2smvO%2B0MyRnHxw%2BaVcWRImDeGTDhqtqfT9Y7ucVGPTDA4SYkH7nuWHxktkhSj8LtlT5Gk0iFdzMJRWIPCQx2aMf32l9qp%2FFDzpxn9gwPVickccSOHdjX9Y11MOyPVcydZ9L6ph3pntb2wd%2Fy8c%3D&amp;AWSAccessKeyId=ASIAQ3PHCVTY3MVAATUK&amp;Expires=1557889652&amp;Signature=BzzLZHNG66%2FkecI%2FtjnJCvPRF8Y%3D&amp;hash=9801a5a49f67b2342e82c00f4d9b746eb2951194644f233a0588e915f8d22bda&amp;host=68042c943591013ac2b2430a89b270f6af2c76d8dfd086a07176afe7c76c2c61&amp;pii=S0004370297000659&amp;tid=spdf-74d42e48-3195-473c-ab3e-61994c3c81c0&amp;sid=0ea5c4719d60084fe42944c4fd4f100bc2c0gxrqa&amp;type=client" rel="nofollow noreferrer"><em>Dynamic relevance: vision-based focus of attention using artificial neural networks</em></a>, Shumeet Baluja, Dean Pomerleau, 1995; revised 1996, (<a href="https://www.sciencedirect.com/science/article/pii/S0004370297000659" rel="nofollow noreferrer">abstract</a>), has only a few mathematical expressions but is filled with system theory that could be described mathematically with a little reading and thought.</li> <li>Same with <a href="http://www.diva-portal.org/smash/get/diva2:987589/FULLTEXT01.pdf" rel="nofollow noreferrer"><em>Self-Organization of an Artificial Neural Network Subjected to Attention Shift Impairments and Familiarity Preference, Characteristics Studied in Autism</em></a>, Lennart Gustafsson and Andrew P. Papliński, 2004.</li> <li>This one has clear and comprehensive mathematical treatment: <a href="https://www.degruyter.com/downloadpdf/j/amcs.2012.22.issue-2/v10006-012-0034-5/v10006-012-0034-5.pdf" rel="nofollow noreferrer"><em>Backpropagation Generalized Delta Rule for the Selective Attention Sigma-if Artificial Neural Network</em></a>, Maciej Huk, 2012</li> <li>This one too: <a href="https://doi.org/10.1371/journal.pone.0072035" rel="nofollow noreferrer"><em>Small and Dim Target Detection via Lateral Inhibition Filtering and Artificial Bee Colony Based Selective Visual Attention</em></a>, Haibin Duan, Yimin Deng, Xiaohua Wang, Chunfang Xu, 2013</li> <li>There is some here, but the visualizations and concepts are so theoretically relevant that one might not miss the more extensive mathematics: <a href="http://sprott.physics.wisc.edu/pubs/paper451.pdf" rel="nofollow noreferrer"><em>Using chaotic artificial neural networks to model memory in the brain</em></a>, Zainab Aram, Sajad Jafari, Jun Ma, Julien C. Sprott, Sareh Zendehrouh, Viet-Thanh Pham</li> <li>Solid math coverage here: <a href="https://iris.polito.it/retrieve/handle/11583/2303844/52344/cuda_v10.pdf" rel="nofollow noreferrer"><em>Parallel Implementation of Artificial Neural Network Training</em></a>, Stefano Scanzio, Sandro Cumani, Roberto Gemello, Franco Mana, P. Laface, 2010, (<a href="https://www.researchgate.net/publication/220732611_Parallel_implementation_of_artificial_neural_network_training" rel="nofollow noreferrer">abstract</a>)</li> <li>Also here: <a href="https://arxiv.org/pdf/1412.7755.pdf" rel="nofollow noreferrer"><em>Multiple Object Recognition with Visual Attention</em></a>, Jimmy Lei Ba, Volodymyr Mnih, Koray Kavukcuoglu, 2015 ICLR</li> <li>The mathematics for the very popular DiSAN is here: <a href="https://www.aaai.org/ocs/index.php/AAAI/AAAI18/paper/viewFile/16126/16099" rel="nofollow noreferrer"><em>DiSAN: Directional Self-Attention Network for RNN/CNN-Free Language Understanding</em></a>, Tao Shen, Jing Jiang, Tianyi Zhou, Shirui Pan, Guodong Long, Chengqi Zhang, 2018</li> <li>Mathematics and the algorithm is provided for this unique approach too: <a href="https://web.cs.wpi.edu/~xkong/publications/papers/kdd18b.pdf" rel="nofollow noreferrer"><em>Graph Classification using Structural Attention</em></a>, John Boaz Lee, Ryan Rossi, Xiangnan Kong, 2018</li> </ul> <p>It would be interesting to develop a taxonomy of attention approaches in AI, as that has probably not yet been done. It would take quite a study to see if any of the above bullet items match up with either of the two articles referenced in the question.</p>
https://ai.stackexchange.com/questions/12313/a-mathematical-explanation-of-attention-mechanism
Question: <p>Recurrent Neural Networks (RNN) With Attention Mechanism is generally used for Machine Translation and Natural Language Processing. In Python, implementation of RNN With Attention Mechanism is abundant in Machine Translation (For Eg. <a href="https://talbaumel.github.io/blog/attention/" rel="nofollow noreferrer">https://talbaumel.github.io/blog/attention/</a>, however what I would like to do is to use RNN With Attention Mechanism on a temporal data file (not any textual/sentence based data). I have a CSV file with of dimensions 21000 x 1936, which I have converted to a Dataframe using Pandas. The first column is of Datetime Format and last column consists of target classes like "Class1", "Class2", "Class3" etc. which I would like to identify. So in total, there are 21000 rows (instances of data in 10 minutes time-steps) and 1935 features. The last (1936th column) is the label column.</p> <p>It is predominant from existing literature that an Attention Mechanism works quite well when coupled into the RNN. I am unable to locate any such implementation of RNN with Attention Mechanism, which can also provide a visualisation as well. Any help in this regard would be highly appreciated. Cheers! </p> Answer: <p><strong>Project Definition</strong></p> <ul> <li>Labelled data set contains 21 K rows; 1,936 features; and 1 textual label</li> <li>Label can be 1 of 14 possible categories</li> <li>The first feature is a time stamp reflecting exact or approximate 10 minute sampling period</li> <li>Data content not primarily natural language</li> <li>The intention is to learn the function mapping the features to the label</li> <li>Visualization to observe training intermediate and final results</li> <li>Hoping to simplify implementation using already implemented algorithms and development support</li> </ul> <p><strong>Use of Recurrent Artificial Network Learning</strong></p> <p>It is correct that recurrent networks are designed for temporally related data. The later variants of the original RNN design are most apt to produce favorable results. One of the most effective of these variants is the GRU network cell, which is well represented in all the main machine learning libraries, and visualization hooks in those libraries are well documented.</p> <p><strong>Various Meanings of Attention Mechanisms</strong></p> <p>The belief that an attention mechanism beyond those built into the RNN design are needed to emphasize important features may be over-complicating the problem. The parameters of the GRU and the other RNN variants already focus attention on particular features during learning. Even a basic feed forward network does that, but the MLP (multilayer perceptron) does not recognize feature trends temporally, so the use of RNN variants is smart.</p> <p>There are other kinds of attention mechanisms that are not inside each cell of a network layer. Research into advanced attention based designs that involve oversight, various forms of feedback from the environment, recursion, or generative designs is ongoing. As the question indicates, those are targeted for natural language work. There is also attention based design for motion and facial recognition and automated walking, driving, and piloting systems. They are designed, tested, optimized, and evolving for the purpose of natural language processing or robotics, not 1,936 feature rows. It is unlikely that those systems can be morphed into something any more effective than a GRU network for this project without considerable further R&amp;D.</p> <p><strong>Output Layer and Class Encoding</strong></p> <p>The 14 labels should be coded as 14 of the 16 permutations of a 4 bit output prior to training. And the loss function should dissuade the two illegal permutations.</p> <hr /> <p><strong>Response to Comments</strong></p> <blockquote> <p>[Of the] 1936 features, one of them [is] date-time timestamps and [the] rest [are] numeric. ... Can you please suggest the format of the input? Should I convert each column of feature to a list and create a list of lists or some other way around?</p> </blockquote> <p>Regardless of what types the library you use expect as inputs, the theory is clear. Features with a finite set of fixed discrete values are ordinals. The magnitude of their information content is given in bits <span class="math-container">$b$</span> as follows, where <span class="math-container">$p$</span> is the total number of possible discrete values for the feature.</p> <p><span class="math-container">$$ b = \log_2 p $$</span></p> <p>This is also true of the timestamp, which has a specific possible range and time resolution, where <span class="math-container">$t_{\emptyset}$</span> is the initial timestamp where the project or its data began and <span class="math-container">$t_{res}$</span> is the time of one resolution step.</p> <p><span class="math-container">$$ b_{timestamp} = \log_2 \frac {t_{max} - t_\emptyset} {t_{res}} $$</span></p> <p>The label also has a range. If the range is a fixed set of permutations, then assign an integer to each, starting with zero, to encode them. If the range of the text is unknown, use a library or utility that converts words or phrases to numbers. One popular one is word2vec.</p> <p>Integrating the features to reduce the number of input bits actually wastes a layer, so don't do that. The total information is given as this.</p> <p><span class="math-container">$$ b_{total} = \sum_{i = 1}^{1,936} b_i $$</span></p> <p>The features, if they are real numbers, can remain so. The input layer of an artificial network expects a number entering the data flow for each cell. One can change the data type of the numbers to reduce computational complexity if no overflow or other mapping issue will occur. This is where the above information content can be useful in understanding how far one can go in collapsing the information into a smaller computational footprint.</p>
https://ai.stackexchange.com/questions/10010/how-to-use-rnn-with-attention-mechanism-on-non-textual-data
Question: <p>[LONG POST!!] I am working on a DNN model that works as an improviser to generate music sequences. The idea of generating music is based on taking a sequence of music nodes (their index representation) and generating sequences that are distinctive with more context and coherent structure as well as capturing syntactic and structural information from the original sequences. Therefore I am dealing with a time series dataset. Similar work was reported in &quot;<a href="https://arxiv.org/pdf/2002.03854.pdf" rel="nofollow noreferrer">Attentional Networks for music generation</a>&quot; but in our case, we have a different model architecture and different dataset. It has been known that Transformer (attention) suffers in multivariate time series dataset (Source: <a href="https://towardsdatascience.com/attention-for-time-series-classification-and-forecasting-261723e0006d" rel="nofollow noreferrer">Attention for time series forecasting and classification</a>). But given these problems were reported two years ago, the SOTA should be better by now. For that reason, my target is to use the attention mechanism in a way to overcome these challenges.</p> <p>Recently I have been using the <a href="https://www.tensorflow.org/addons/api_docs/python/tfa/layers/MultiHeadAttention" rel="nofollow noreferrer">multiheaded attention layer from TF</a> and testing with head size between 128 and 3074 and head number from 1 to 10 and dropout from 0.1 to 0.5. Based on the results there was no noticeable improvement in the model performance, it seems that the multi-headed attention layer didn't have contribution during training.</p> <p>Therefore and after carefully reading the literature I found that autoregressive attention is the best option for this types of problem. Basically, by making the attention autoregressive, it will compute the attention over the previous (decoder) outputs in such a way as to avoid using future information to make current predictions (to preserve the notion of causality). So the attention has to designed so that at each time step it needs to be autoregressive, for example, use previously generated sequences as extra input while generating the next symbol.</p> <p>In &quot;<a href="https://web.stanford.edu/class/archive/cs/cs224n/cs224n.1174/reports/2755456.pdf" rel="nofollow noreferrer">Autoregressive Attention for Parallel Sequence Modeling</a>&quot; paper they introduced the autoregressive attention mechanism in order to maintain the causality in the decoder. I didn't understand what they mean in Section 3.3 which describe the implementation of autoregressive attention. My problem is in the autoregressive implementation, in the paper they stated that autoregressive mechanics was implemented using the masking technique which changes all of the elements in the upper-right triangle and the diagonal to −∞ 3 to ensure that all the scores that would introduce future information into the attention calculation are equal to 0 after the softmax. I was hoping to see how it was implemented in the code to get a better idea of how it works.</p> <p>Here is how the attention is implemented in tensorflow:</p> <pre><code>def multiHeadedAttentionLayer(cell_input): cell_state = None if cell_state is None: cell_state = cell_input mha = tfa.layers.MultiHeadAttention(head_size=128, num_heads=5, dropout = 0.5) cell_output = mha([cell_input, cell_state]) cell_state = cell_input return cell_output </code></pre> <p>Then the function is recalled in the model architecture with the rest of the layers (below is a section of the model architecture only):</p> <pre><code>x = MaxPooling1D(pool_size=2)(x) # previous layer x = multiHeadedAttentionLayer(x) # attention layer x = LSTM(lstmneurons, kernel_regularizer=regularizers.l2(kreg3_rate), dropout=dropout3_rate, recurrent_dropout=dropout4_rate)(x) # following layer x = BatchNormalization()(x) # following layer </code></pre> <p>etc....</p> <p>Based on my intuition the autoregression should take the output results and feed them back to the input at every time step, so my questions are:</p> <p>Why do we need the masking technique?</p> <p>How to implement the masking technique in this case?</p> <p>Is there is a code for the autoregressive attention that I have a look at for reference?</p> <p>Is my current intuition about autoregressive attention correct as shown in the diagram?</p> <p><a href="https://i.sstatic.net/zldoC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/zldoC.png" alt="Autoregressive Attention" /></a></p> Answer:
https://ai.stackexchange.com/questions/28113/how-do-autoregressive-attention-mechanism-work-in-multi-headed-attention
Question: <p>I have ready many explanations of the seq2seq model. In my opinion, however, it is really like a robot that might say something correctly, but doesn't really understand it, just as is true with an LLM generally.</p> <p>In my opinion, the correct way to describe Seq2Seq and similar NLP models should start from a probability view.</p> <p>My probability view is very simple; the output of the encoder is a representation of the probability distribution of the next word. In each step of the Decoder, it just modifies the distribution based on each word it predicted from the distribution and outputs the modified distribution. It then does this repeatedly.</p> <p>Assuming this probability view is correct, how could we explain the attention mechanism used in Seq2seq?</p> Answer: <p>Pretty much anything can be interpreted as a distribution or some kind of energy model, that doesn't mean that everything is the same</p> <p>First of all, the softmax output of a Seq2Seq is just a formalization of the categorical distribution with which we model our problem</p> <p>Attention in other hand is more complicated: to begin with, the attention module learns a residual of the input, in other word is &quot;how should i correct the current input of the layer&quot;, so attention is actually a &quot;smart weighted sum for the residual&quot;</p> <p>At that point, how you implement the attention, is up to you, indeed there exist alternatives to softmax attention, such as linear attention, which definitely loses the notion of &quot;distribution&quot;, but somewhat keeps the notion of &quot;attention&quot; (since you put high magnitude scores to something you want, and small magnitude scores to what you don't care)</p> <p>So yeah, at most you can say that attention is &quot;a probability distribution over the tokens that allows the network to improve the current input via a residual connection&quot;... not too sure that this is a helpful interpretation whatsoever</p>
https://ai.stackexchange.com/questions/45853/probability-interpretation-of-attention-mechanism-in-seq2seq
Question: <p>I am aware that the attention mechanism can be used to deal with long sequences, where problems related to gradient vanishing and, more generally, representing effectively the whole sequence arise.</p> <p>However, I was wondering if attention, applied either to seq2seq RNN/GRU/LSTM or via Transformers, can contribute to improving the overall performance (as well as giving some sort of interpretability through the attention weights?) in the case of relatively short sequences (let's say around 20-30 elements each).</p> Answer: <p>They shouldn't have any issues with short sequences, as short dependencies are easier to learn. The only difficult cases are long dependencies which is where most of the research is geared at. However, this is assuming that by &quot;short sequence&quot; you mean a sequence of text that is fully contained within itself, i.e. there is no cross-sequence dependencies.</p> <p>For example, if you have a really long paragraph that doesn't fit in a transformer model, you would have to break that paragraph into many &quot;short sequences&quot;, but each of these sequence may have a dependency that depends on another sequence, i.e. cross-sequence dependencies. For these cross-sequence dependencies, any model with recurrence should do better than ones without (e.g. RNN, LSTM, Transformer-XL).</p> <p>If each short sequence is self-contained, then all of the models should perform pretty well.</p>
https://ai.stackexchange.com/questions/25253/can-the-attention-mechanism-improve-the-performance-in-the-case-of-short-sequenc
Question: <p>I am doing some research on the visual attention mechanism in remote sensing domain (where the features learnt from one layer are highlighted using the attention mask derived from another layer). From what I have observed, the attention mask is learnt in a similar fashion as any other branch in CNN. So, what is so special about the visual attention mask that makes it different from a regular two branch CNN? The reference papers are provided below:</p> <p><a href="https://ieeexplore.ieee.org/document/8736024" rel="nofollow noreferrer">Visual Attention-Driven Hyperspectral Image Classification (IEEE, 2019)</a></p> <p><a href="https://hal.archives-ouvertes.fr/hal-01931435/document" rel="nofollow noreferrer">A Two-Branch CNN Architecture for Land Cover Classification of PAN and MS Imagery (MDPI, 2019)</a></p> Answer:
https://ai.stackexchange.com/questions/21211/how-is-visual-attention-mechanism-different-from-a-two-branch-convolutional-neur
Question: <p>About attention: the Query, Key and Value vectors (before the linear transformations) are just the entire sequence, that is being inputted, or just each token? Chat-GPT nor Youtube didn't give me a clear answer. But, I thought. If we feed in each sequence straight into the Attention mechanism, then the linear layers, which are supposed to transform these inputs, won't be able to accept that, because sequences can be different length, and linear layers' input shape is fixed. And if we process each token independently, we have to store the other tokens somewhere, and then have loops to iterate through each token etc.</p> <p>So, I decided to find some code, where people create that Multi-Head attention, and here's what I found:</p> <pre><code>import tensorflow as tf from tensorflow.keras import layers class MultiHeadAttention(layers.Layer): def __init__(self, model_dim, n_heads, rate=0.1, initializer='glorot_uniform'): super(MultiHeadAttention, self).__init__() self.n_heads = n_heads self.model_dim = model_dim assert model_dim % self.n_heads == 0 self.head_dim = model_dim // self.n_heads self.wq = layers.Dense(model_dim, kernel_initializer=initializer) self.wk = layers.Dense(model_dim, kernel_initializer=initializer) self.wv = layers.Dense(model_dim, kernel_initializer=initializer) self.dropout1 = layers.Dropout(rate) self.dropout2 = layers.Dropout(rate) self.wo = layers.Dense(model_dim, kernel_initializer=initializer) def split_heads(self, x, batch_size): x = tf.reshape(x, (batch_size, -1, self.n_heads, self.head_dim)) return tf.transpose(x, perm=[0, 2, 1, 3]) def call(self, q, k, v, mask=None): batch_size = tf.shape(q)[0] q = self.wq(q) k = self.wk(k) v = self.wv(v) q = self.split_heads(q, batch_size) k = self.split_heads(k, batch_size) v = self.split_heads(v, batch_size) dh = tf.cast(self.head_dim, tf.float32) qk = tf.matmul(q, k, transpose_b=True) scaled_qk = qk / tf.math.sqrt(dh) if mask is not None: scaled_qk += (mask * -1e9) attn = self.dropout1(tf.nn.softmax(scaled_qk, axis=-1)) attn = tf.matmul(attn, v) attn = tf.transpose(attn, perm=[0, 2, 1, 3]) original_size_attention = tf.reshape(attn, (batch_size, -1, self.model_dim)) output = self.dropout2(self.wo(original_size_attention)) return output class TransformerBlock(layers.Layer): def __init__(self, emb_dim, n_heads, mlp_dim, rate=0.1, initializer='glorot_uniform', eps=1e-6, activation='gelu'): super(TransformerBlock, self).__init__() self.attn = MultiHeadAttention(emb_dim, n_heads, initializer=initializer) self.mlp = tf.keras.Sequential([ layers.Dense(mlp_dim, activation=activation, kernel_initializer=initializer), layers.Dense(emb_dim, kernel_initializer=initializer), layers.Dropout(rate) ]) self.ln1 = layers.LayerNormalization(epsilon=eps) self.ln2 = layers.LayerNormalization(epsilon=eps) def call(self, inputs, mask=None): x = self.ln1(inputs) x = inputs + self.attn(x, x, x, mask) x = x + self.mlp(self.ln2(x)) return x </code></pre> <p>So, here I see that they basically feed in the entire sequence into the Multi-Head attention:</p> <p>x = self.ln1(inputs) x = inputs + self.attn(x, x, x, mask)</p> <p>But again, sequences can be different length, but linear layers accept inputs of fixed length. Is it me not understanding something? I also read about Padding and Masking, that is used during training. Is it also used during inference?</p> Answer: <p>TL;DR YES.</p> <hr /> <p>If the sequence length of <span class="math-container">$Q, K, V$</span> is <span class="math-container">$L$</span>, the embedding size is <span class="math-container">$E$</span>, and the number of heads is <span class="math-container">$H$</span>, then weight matrices are of the order <span class="math-container">$E \times (E // H)$</span> to transform <span class="math-container">$E$</span>-sized embeddings to <span class="math-container">$(E // H)$</span> sized embeddings. We will have <span class="math-container">$H$</span> such embeddings; we get the same <span class="math-container">$E$</span>-sized vectors upon concatenation. The attention weights will be of size <span class="math-container">$L \times L$</span> to enforce every token is attending to every other token in self-attention mode.</p>
https://ai.stackexchange.com/questions/43820/does-transformers-self-attention-mechanism-process-tokens-independently-or-ent
Question: <p>In the <a href="https://arxiv.org/pdf/1706.03762.pdf" rel="nofollow noreferrer">original transformer paper</a>, the attention mechanism uses parameter matrices, but no bias terms. However, in more recent implementations I see people often using a bias term when computing &quot;key&quot;, &quot;query&quot;, and &quot;value&quot;. For example, in Andrej Karpathy's recent <a href="https://github.com/karpathy/nanoGPT/blob/master/model.py" rel="nofollow noreferrer">implementation of GPT</a>, whether a bias term is used can be determined in the config:</p> <pre><code>bias: bool = True # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster </code></pre> <p>This makes me wonder whether there is any evidence that the bias terms help. In particular, if, according to Karpathy, not using bias is &quot;a bit better and faster&quot;, why is he using them by default?</p> Answer: <p>I guess that bias terms have the ability to increase the expression power of the model.According to the paper:&quot;BitFit: Simple Parameter-efficient Fine-tuning for Transformer-based Masked Language-models&quot;.</p>
https://ai.stackexchange.com/questions/38983/is-there-any-evidence-that-the-bias-terms-help-in-the-attention-mechanism-of-the
Question: <p>The main advantages of the self-attention mechanism are:</p> <ul> <li>Ability to capture long-range dependencies</li> <li>Ease to parallelize on GPU or TPU</li> </ul> <p>However, I wonder why the same goals cannot be achieved by <em>global depthwise convolution</em> (with the kernel size equal to the length of the input sequence) with a comparable amount of flops.</p> <p><strong>Note</strong>:</p> <p>In the following, I am comparing against the original architecture from the paper <a href="https://arxiv.org/abs/1706.03762" rel="nofollow noreferrer">Attention Is All You Need</a>.</p> <p><strong>Idea</strong>:</p> <p>Consider the depthwise convolution of size <span class="math-container">$L$</span> with circular padding: <span class="math-container">$$ y_{t,c} = W_{t^{'},c} x_{t^{'} + t, c} $$</span> Here, <span class="math-container">$x$</span> is the input signal and <span class="math-container">$y$</span> is the output signal, <span class="math-container">$t$</span> is the position in the sequence, and <span class="math-container">$c$</span> is the channel index. Since the convolution is depthwise the given output channel depends on the unique input channel (we would like to have linear complexity in the dimension of the embedding vector).</p> <p>After a single convolution, one definitely would not have any interactions between the tokens in the sequence.</p> <p>However, a two-layer convolutional network with these tokens is able to capture long-range pair-wise interactions: <span class="math-container">$$ x_{t,c}^{(2)} = W_{t^{''},c}^{(2)} \sigma(W_{t^{'},c}^{(1)} x_{t^{'} + t, c}^{(0)}) $$</span></p> <p>And by stacking a not very large number of these layers (like 12 or 24) one can model interactions between tokens in the sequence of arbitrary complexity.</p> <p><strong>Comparison of complexity</strong>:</p> <p>The asymptotic complexity of both approaches seems to be the same.</p> <ul> <li><p>Attention: <span class="math-container">$O (L^2 d)$</span></p> </li> <li><p>Depthwise convolution: <span class="math-container">$O (L^2 d)$</span></p> </li> </ul> <p>However, dot product attention seems to be a rather intuitive and biologically motivated operation that is crucial for sequence problems.</p> <p>Has this question been studied in the literature or discussed somewhere before?</p> <p><strong>EDIT</strong></p> <p>De-facto global depthwise convolution is used in <a href="https://arxiv.org/abs/2105.01601" rel="nofollow noreferrer">MLP-Mixer</a>. One stage performs convolution with global receptive field (of the size of feature map), and other operation is pointwise convolution with <code>kernel_size=1</code>.</p> <p><a href="https://i.sstatic.net/sSE0H.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/sSE0H.png" alt="enter image description here" /></a></p> Answer:
https://ai.stackexchange.com/questions/30169/couldnt-the-self-attention-mechanism-be-replaced-with-a-global-depth-wise-convo
Question: <p>I have two questions about the structure of attention modules:</p> <p>Since I work with imagery I will be talking about using convolutions on feature maps in order to obtain attention maps.</p> <ol> <li><p>If we have a set of feature maps with dimensions [B, C, H, W] (batch, channel, height, width), why do we transform our feature maps before we calculate their affinity/correlation in attention mechanisms? What makes this better than simply taking the cosine distance between the feature vectors (e.g. resizing the maps to [B, C, HW] and [B, HW, C] and multiplying them together). Aren't the feature maps already in an appropriate feature/embedding space that we can just use them directly instead of transforming them first?</p> </li> <li><p>Most of the time, attention mechanisms will take as input some stack of feature maps (F), and will apply 3 transformations on them to essentially produce a &quot;query&quot;, &quot;key&quot; and &quot;value&quot;. The query and key will be multiplied together to get the affinity/correlation between a given feature vector and all other feature vectors. In computer vision these transformation will typically be performed by the different 1x1 convolutions. My question is, how come we use 3 different 1x1 convolutions? Wouldn't it make more sense to apply the same 1x1 convolution to the input F? My intuition tells me that since we want to transform/project the feature maps F into some embedding/feature space that it would make the most sense if the &quot;query&quot;, &quot;key&quot; and &quot;value&quot; were all obtained by using the same transformation. To illustrate what I mean lets pretend we had a 1x1 feature map and we wanted to see how well the pixel correlates with itself. Obviously it should correlate 100% because it is the same pixel. But wouldn't applying two sets of 1x1 convs to the pixel lead to the chance that the pixel would undergo a different transformation and in the end would have a lower correlation than it should?</p> </li> </ol> Answer: <p>I assume you're talking about this design: (<a href="https://lilianweng.github.io/lil-log/2018/06/24/attention-attention.html" rel="nofollow noreferrer">image source</a>) <a href="https://i.sstatic.net/U1ATS.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/U1ATS.png" alt="SAGAN attention network" /></a></p> <blockquote> <p>But wouldn't applying two sets of 1x1 convs to the pixel lead to the chance that the pixel would undergo a different transformation and in the end would have a lower correlation than it should?</p> </blockquote> <p>Yes, that's the point. We are not trying to measure a pixel's correlation with itself. Rather we are trying to allow it to query different related data. We are giving it freedom to change both the data and the queries.</p> <p>It is true that the space for the queries and the keys is the same - but we shouldn't use the same transformation for both, or else each instance of the attention layer is just trying to fetch its own value! Generally the purpose of an attention layer is to query <em>different</em> parts of the input.</p> <p>The first half of your question was essentially &quot;why do we have a convolution at all?&quot; and I think this has the same answer: you'd just be able to detect similar pixels, you wouldn't be able to pay attention to noses whenever eyes are detected.</p> <p>It is also true that you could probably skip the convolution on the h(x) input. It looks like this one is somewhat redundant because the convolutions on h(x) and v(x) apply in series - which makes it a two-layer convolution, not quite the same as a one-layer convolution, but perhaps only one layer is needed.</p> <p>It is possible that if you removed the conv layer on either the keys or the queries (but not both) the model would learn to generate the keys directly as the features, but this would hinder it because it would be unable to output any data in the values and queries that wasn't part of the keys (or vice versa). Seems silly. Don't do that.</p>
https://ai.stackexchange.com/questions/29989/attention-mechanism-why-apply-multiple-different-transformations-to-obtain-quer
Question: <p>The transformer architecture contains a cross attention mechanism which is enriching the encoder with information from the decoder. The place where this takes place is visualized in the image below:</p> <p><a href="https://i.sstatic.net/L3ifH.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/L3ifH.jpg" alt="transformer_architecture" /></a></p> <p>The cross attention mechanism within the original transformer architecture is implemented in the following way:</p> <p><a href="https://i.sstatic.net/BBwHl.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/BBwHl.jpg" alt="cross_attention_computation" /></a></p> <p>The source for the images is <a href="https://www.youtube.com/watch?v=EixI6t5oif0" rel="nofollow noreferrer">this video</a>. Why are the values in this step coming from the encoder instead of from the decoder? Is this where e.g. the actual language translation happens within a transformer?</p> Answer: <blockquote> <p>The transformer architecture contains a cross attention mechanism which is enriching the encoder with information from the decoder. The place where this takes place is visualized in the image below:</p> </blockquote> <p>I think that you got it the other way round. The encoder passes an enriched input sentence to the decoder. Cross attention helps the decoder to attend to every part of this &quot;enriched&quot; input and produce one output at a time recursively. Initially, the decoder's first prediction is fixed to (start of sentence) token. That gets self attended first, then get attended with encoder's output (the &quot;enriched&quot; input) and gives out a prediction from the word vocab list. This word gets appended to the decoder's input and we repeat the process again.</p>
https://ai.stackexchange.com/questions/38340/why-do-the-values-in-the-cross-attentional-mechanism-within-a-transformer-come-f
Question: <p>Yesterday, I found <a href="https://pubmed.ncbi.nlm.nih.gov/34150797/" rel="nofollow noreferrer">this</a> fascinating paper about predicting various clinical conditions using an attention based LSTM. I don't have any practical experience with attention mechanism or transformers, which might be the reason why I struggle to understand why this approach work. Well, let me first try to summarize what the authors accomplished</p> <p><a href="https://i.sstatic.net/vlO4C.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/vlO4C.jpg" alt="enter image description here" /></a></p> <p>As a first step, the use some sort of model to predict the future course of some important clinical variables. Their outcome is denoted by <span class="math-container">$X_0...X_t$</span>. As a second step, these features (no timeseries data!) are passed into a transformer like architecture:</p> <ul> <li>as an embedding step, the predicted clinical variables along with some static ones are passed to an LSTM that computes several hidden states: <span class="math-container">$H_0...H_t$</span></li> <li>the attention step receives <span class="math-container">$h_0...h_t$</span>. For computing the contribution of each hidden state, the author states that each hidden state <span class="math-container">$h_i$</span> is passed to a function that computes the similarity between <span class="math-container">$h_i$</span> and <span class="math-container">$h_t$</span>, that is the last hidden state of the lstm. From each resulting score <span class="math-container">$s_i$</span>, a weight is computed with the softmax function <span class="math-container">$$w_i = \frac{exp(s_i)}{\sum_{j=0}^texp(s_j)}$$</span>. The context vector cv is then calculated by computing the weighted sum of hidden states.</li> <li>the decoder receives the context vector concatenated with <span class="math-container">$h_t$</span> and computes the output using two dense layers.</li> </ul> <p>What I don't understand are two things:</p> <ol> <li>Is it legit to use a lstm as embedding, while the input is no time series data but independent features?</li> <li>In the presented approach, the weight of an hidden state <span class="math-container">$h_i$</span> depends on the similarity to the output of the lstm, i.e. <span class="math-container">$h_t$</span>. But isn't an attention-based architecture used precisely to let every input variable contribute equally to the output, and to combat lstm's problem of struggling with long dependencies? With long inputs, i guess that <span class="math-container">$h_0$</span> tends to be likely to have larger differences from <span class="math-container">$h_t$</span> than, e.g. <span class="math-container">$h_{t-1}$</span> simply because it is more in the past. If this is true, <span class="math-container">$h_t$</span> automatically would receive a smaller weight.</li> </ol> <p>Are my thoughts correct or have I missed something?</p> Answer:
https://ai.stackexchange.com/questions/36922/using-similarity-score-within-lstm-embedding-for-attention-based-mechanism
Question: <p>Excuse me if you find this question too vague and not fitting to this forum and feel free to close it. The overall goal of my question is to get a better intuition of the attention concept and mechanism.</p> <p>There is a high-level analogy between attention mechanisms (to be specific: in the transformer) and Google's PageRank algorithm: both claim and strive to calculate &quot;relative importances&quot; – of parts of a sentence or of web pages – without a thorough definition of what &quot;importance&quot; actually is. The meaning of &quot;relative importance&quot; as calculated by PageRank is intuitively clear even though it's recursive: the relative importance of a web page is the sum of the relative importances of the pages linking to it. (Graph-theoretically speaking, the relative importances are given by the eigenvector corresponding to the largest eigenvalue of the adjacency matrix.) The idea is, that when looking for web pages on a specific topic one should pay attention to the most &quot;important&quot; web pages (which PageRank helps to find).</p> <p>I wonder if the high-level analogy can be put a bit deeper: How are – for example – the mathematics of attention mechanisms related to the mathematics of PageRank – if they are? Or is the analogy too superficial and misleading and should be forgotten?</p> <p>Until now I could not develop an intuitive understanding what the relative importance of a token in a sentence is (on which attention then is focussed): important with respect to what? To other tokens or the sentence or even the &quot;full model&quot; as claimed <a href="https://aclanthology.org/P19-1282.pdf" rel="nofollow noreferrer">here</a>? Or isn't the goal of attention mechanisms better explained in terms of &quot;what kinds of relations are there between the tokens in a sentence and between the tokens and the sentence as a whole, and how strong are they?&quot; That's the background of my question.</p> <p>Once again: excuse the vagueness and possibly confusion of this question, I'm aware of it.</p> Answer: <p>Peter,</p> <p>A very interesting observation indeed.</p> <p>Let's narrow down from top to bottom into the cone of understanding (the depth of your understanding represents the narrower cross-section).</p> <p>When you are at the highest (biggest cross-section) it's easy to confuse (or understand) the concept of the transformer as a practically infinite-edged multigraph (a graph with multiple edges b/w two nodes), unlike Page Rank which is a simple graph (graph with only one--at max bi-directional--edge b/w any two nodes). However, in thinking so, you might not be completely wrong (unless you move into the cone of understanding). Each edge b/w two nodes i and j, in our case, represents a certain probability of occurrence of j after i in a given sequence, given the condition that i is preceded by a certain specific and finite sequence of words. Change a word, and you get a new edge with a newer probability.</p> <p>Let me paint a picture.</p> <p>Given two sentences, &quot;I am the King&quot; and &quot;I shall be the King&quot; and analyzing the words &quot;the&quot; and &quot;king&quot; as the ith and jth nodes. One edge b/w the two will represent the probability of occurrence if &quot;king&quot; given the previous sequence is &quot;I am the&quot;, whereas another might represent the probability given the previous preceding sequence is &quot;I shall be the&quot;. But wait, it's not as easy as that, as every two adjacent words in the preceding sequence will have a practically infinite number of edges in between them and so and so. Where PageRank can work with 100s of Billions but still finite nodes with singular edges in between any two nodes, it fails due to capturing that information for an infinitely large multigraph.</p> <p>Even if you were to implement a statistical method to delete unnecessary (more like need to be removed) edges (like stopwords, lower idf rated words, etc) it will still be a practically infinitely big multigraph.</p> <p>Now as you start moving down the cone of understanding, you start thinking what can be better? You start thinking about latent information capturing for the need to not create a monstrous multigraph. You start thinking about Neural Networks. Now, as we did with our multigraph we can use RNNs, use LSTMs for longer sequences, and feel pretty good about it. But, at the end of the day, you know something unnecessary is happening. You are trying to force understanding of the language by the model by using Windows, which is not really how humans understand. Not just that, as is the case with our multigraph, there are unnecessary words (stop words, lower idf rated words) that are being included in our already very time complex operations. So you want to find a way to focus on important words and also keep the memory longer.</p> <p>Attention was born (or basically came into grasp) given all the foundational work already matured.</p> <p>Now you have reached the nadir (the bottom of the cone) or the pinnacle (the top of the cone) depending on your pessimistic or optimistic tendency respectively. Here, you understand that PageRank is actually beautiful, but very limited in its applicability, algorithm, which was developed 26 years ago.</p> <p>You understand how a deep neural network understands latent space and is capable to recreate that individual edge b/w ith and jth node based on a preceding concept case-by-case, without any need to maintain a pre-trained multigraph. Here, based on 10s-100s of Billions of trained parameters (instead of 100s of billions of nodes), we capture the language understanding rather than independent connections themselves and based on a given sequence can predict the next word by essentially calculating the probabilities of all the connected words in the space.</p> <p>Hopefully, this helps.</p>
https://ai.stackexchange.com/questions/40425/how-are-the-intuitions-and-mathematics-of-attention-mechanisms-related-to-those
Question: <p>I’m curious about the mathematical reasoning behind the use of the softmax function as the activation function in self-attention mechanisms within neural networks. Specifically, I’m interested in understanding if there is a theoretical basis that necessitates the use of softmax over other activation functions.</p> <p>Softmax is commonly employed to convert raw attention scores into a probability distribution, ensuring that the sum of attention weights equals 1. This normalization allows the model to effectively focus on certain parts of the input sequence. However, I wonder if there are alternative activation functions that could be less constraining and still allow the optimization process to determine the best way to allocate attention, similar to how tanh or other activations work in different layers of a neural network.</p> <ol> <li>Is there a mathematical justification for the necessity of softmax in self-attention mechanisms?</li> <li>Could other activation functions, perhaps with fewer constraints, be used effectively in place of softmax, allowing the optimization process more flexibility?</li> </ol> <p>Any insights or references to relevant literature would be greatly appreciated.</p> Answer: <p>Softmax was first used for its properties, as it is differentiable, has not domain problem even though it has a division, and it's gradient is well behaved (and in conjunction with Categorical Cross Entropy it gets simplified a lot becoming linear)</p> <p>In the case of attention, many of such properties do not hold, and it's used merely for its ability to emulate a categorical distribution. However, there is not specific reason to use it instead of some other formulation, for example also the following activation will be a valid one: <span class="math-container">$$ \frac{p_i^2}{\sum_j p_j^2} $$</span> where the <span class="math-container">$p_i$</span> are the row logits from <span class="math-container">$QK^T$</span>. However, even though this formulation is valid, as the sum adds up to 1 and all probabilities are positive, it's much more unstable, as the denominator might get to 0, or close to 0, thus introducing instability during learning</p> <p>At the end of the day, any non parametric activation that maps a vector <span class="math-container">$v\in R^n$</span> to a vector <span class="math-container">$u$</span> such that <span class="math-container">$||u||_1=1$</span> and <span class="math-container">$u_i \ge 0\forall i$</span> is indeed a valid &quot;attention&quot; activation</p>
https://ai.stackexchange.com/questions/43048/is-softmax-necessary-as-the-activation-function-for-self-attention-mechanisms
Question: <p>Watching <a href="https://youtu.be/kCc8FmEb1nY?t=4767" rel="noreferrer">this video</a> implementing attention in a transformer. He set query, key, and value biases to <code>False</code> and said &quot;Typically, people don't use biases for these&quot;.</p> <p>Even in <a href="https://pytorch.org/docs/stable/_modules/torch/nn/modules/activation.html#MultiheadAttention" rel="noreferrer">official PyTorch code</a> the default bias is <code>False</code>:</p> <blockquote> <p>add_bias_kv: If specified, adds bias to the key and value sequences at dim=0. Default: <code>False</code>.</p> </blockquote> <p>What is the reason behind that?</p> Answer: <p>For certain types of layers, such as transformers and convolutional layers, including a bias term is unnecessary and adds unnecessary overhead to the model.</p> <p>The reason for this is that these layers are typically followed by a normalization layer, such as Batch Normalization or Layer Normalization. These normalization layers center the data at mean=0 (and std=1), effectively removing any bias.</p> <p>Therefore, it is common practice to omit the bias term in transformers and convolutional layers that are preceded by a normalization layer.</p>
https://ai.stackexchange.com/questions/40252/why-are-biases-typically-not-used-in-attention-mechanism
Question: <p>In the <a href="https://arxiv.org/pdf/1706.03762.pdf" rel="nofollow noreferrer">Attention is all you need</a> paper, on the 4th page, we have equation 1, which describes the self-attention mechanism of the transformer architecture</p> <p><span class="math-container">$$ \text { Attention }(Q, K, V)=\operatorname{softmax}\left(\frac{Q K^{T}}{\sqrt{d_{k}}}\right) V $$</span></p> <p>Everything is fine up to here.</p> <p>Then they introduce the multi-head attention, which is described by the following equation.</p> <p><span class="math-container">$$ \begin{aligned} \text { MultiHead }(Q, K, V) &amp;=\text { Concat}\left(\text {head}_{1}, \ldots, \text {head}_{\mathrm{h}}\right) W^{O} \\ \text { where head}_{\mathrm{i}} &amp;=\text {Attention}\left(Q W_{i}^{Q}, K W_{i}^{K}, V W_{i}^{V}\right) \end{aligned} $$</span></p> <p>Once the multi-head attention is motivated at the end of page 4, they state that for a single head (the <span class="math-container">$i$</span>th head), the query <span class="math-container">$Q$</span> and key <span class="math-container">$K$</span> inputs are first linearly projected by <span class="math-container">$W_i^Q$</span> and <span class="math-container">$W_i^K$</span>, then dot product is calculated, let's say <span class="math-container">$Q_i^p = Q W_i^Q$</span> and <span class="math-container">$K_i^p = K W_i^K$</span>.</p> <p>Therefore, the dot product of the projected query and key becomes the following from simple linear algebra.</p> <p><span class="math-container">$$Q_i^p {K_i^p}^\intercal = Q W_i^Q {W_i^K}^T K^T = Q W_i K^T,$$</span></p> <p>where</p> <p><span class="math-container">$$W_i = W_i^Q {W_i^K}^T$$</span></p> <p>Here, <span class="math-container">$W$</span> is the outer product of query projection by the key projection matrix. However, it is a matrix with shape <span class="math-container">$d_{model} \times d_{model}$</span>. Why did the authors not define only a <span class="math-container">$W_i$</span> instead of <span class="math-container">$W_i^Q$</span> and <span class="math-container">$W_i^K$</span> pair which have <span class="math-container">$2 \times d_{model} \times d_{k}$</span> elements? In deep learning applications, I think it would be very inefficient.</p> <p>Is there something that I am missing, like these 2 matrices <span class="math-container">$W_i^Q$</span> and <span class="math-container">$W_i^K$</span> should be separate because of this and that?</p> Answer: <p>I'll use notation from the paper you cited, and any other readers should refer to the paper (widely available) for definitions of notation. The utility of using <span class="math-container">$W^Q$</span> and <span class="math-container">$W^K$</span>, rather than <span class="math-container">$W$</span>, lies in the fact that they allow us to add fewer parameters to our architecture. <span class="math-container">$W$</span> has dimension <span class="math-container">$d_{model} \times d_{model}$</span>, which means that we are adding <span class="math-container">$d_{model}^2$</span> parameters to our architecture. <span class="math-container">$W^Q$</span> and <span class="math-container">$W^K$</span> each have dimension <span class="math-container">$d_{model} \times d_k$</span>, and <span class="math-container">$d_k=\frac{d_{model}}{h}$</span>. If we use these two matrices, we only add <span class="math-container">$2\frac{d_{model}^2}{h}$</span> parameters to our architecture, even though their multiplication (with the transpose) allows us to have the correct dimensions for matrix multiplication with <span class="math-container">$Q$</span> and <span class="math-container">$K$</span>.</p> <p>We do use <span class="math-container">$h$</span> attention heads, which then brings our number of parameters back up, but the multiple heads let the model attend to different pieces of information in our data.</p>
https://ai.stackexchange.com/questions/25217/in-the-multi-head-attention-mechanism-of-the-transformer-why-do-we-need-both-w
Question: <p>As this <a href="https://ai.stackexchange.com/q/21237/23811">question</a> says:</p> <blockquote> <p>In scaled dot product attention, we scale our outputs by dividing the dot product by the square root of the dimensionality of the matrix:</p> <p><a href="https://i.sstatic.net/wLI4m.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/wLI4m.png" alt="enter image description here" /></a></p> <p>The reason why is stated that this constrains the distribution of the weights of the output to have a standard deviation of 1.</p> </blockquote> <p>My question is why don't we do the same after multiplying to <span class="math-container">$V$</span>(values) for the same reason?</p> Answer: <p>Because what attention does is to control how much of the information in <span class="math-container">$V$</span> to use based on weights computed through the similarity between <span class="math-container">$Q$</span> and <span class="math-container">$K$</span>.</p> <p>When we multiply the attention weights by <span class="math-container">$V$</span>, we are doing a weighed sum of the vectors in <span class="math-container">$V$</span> to get a new matrix that better represents <span class="math-container">$Q$</span> contextually within <span class="math-container">$V$</span>. There is no need for variance normalization since its the resulting representation of the attention layer itself, rather than something that we use as a probability distribution. This is in opposition to the product <span class="math-container">$QK^T$</span>, to which we then apply a softmax to obtain dimension-wise pseudo-probabilities.</p>
https://ai.stackexchange.com/questions/40244/in-the-attention-mechanism-why-dont-we-normalize-after-multiplying-values
Question: <p>I have a difficult time understanding the &quot;multi-head&quot; notion in the original <a href="https://papers.nips.cc/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf" rel="noreferrer">transformer paper</a>. What makes the learning in each head unique? Why doesn't the neural network learn the same set of parameters for each attention head? Is it because we break <em>query, key</em> and <em>value</em> vectors into smaller dimensions and feed each portion to a different head?</p> Answer: <p>The reason each head is different is because they each learn a different set of weight matrices <span class="math-container">$\{ W_i^Q, W_i^K, W_i^V \}$</span> where <span class="math-container">$i$</span> is the index of the head. To clarify, the input to each attention head is the same. For attention head <span class="math-container">$i$</span>:</p> <p><span class="math-container">\begin{align} Q_i(x) &amp;= x W_i^Q \\ K_i(x) &amp;= x W_i^K \\ V_i(x) &amp;= x W_i^V \\ \text{attention}_i(x) &amp;= \text{softmax} \left(\frac{Q_i(x) K_i(x)^T}{\sqrt{d_k}} \right) V_i(x). \end{align}</span></p> <p>Notice that the input to each head is <span class="math-container">$x$</span> (either the semantic + positional embedding of the decoder input for the first decoder layer, or the output of the previous decoder layer). <a href="http://jalammar.github.io/illustrated-transformer/" rel="nofollow noreferrer">More info</a></p> <p>The question as to why gradient descent learns each set of weight matrices <span class="math-container">$\{ W_i^Q, W_i^K, W_i^V \}$</span> to be different across each attention head is very similar to <a href="https://ai.stackexchange.com/questions/25109/is-there-anything-that-ensures-that-convolutional-filters-end-up-the-same/25111#25111">&quot;Is there anything that ensures that convolutional filters don't end up the same?&quot;</a>, so maybe you might find the answer there helpful for you:</p> <blockquote> <p>No, nothing really prevents the weights from being different. In practice though they end up almost always different because it makes the model more expressive (i.e. more powerful), so gradient descent learns to do that. If a model has n features, but 2 of them are the same, then the model effectively has n−1 features, which is a less expressive model than that of n features, and therefore usually has a larger loss function.</p> </blockquote>
https://ai.stackexchange.com/questions/25148/what-is-different-in-each-head-of-a-multi-head-attention-mechanism
Question: <p>I am a bit confused on what cross attention mechanisms are doing. I understand that the currently decoded output is usually the query and the conditioning/input (from an encoder) is the key and value. The query is multiplied by the key to make an attention matrix that details how much each element of the currently decoded output relates to each element of the input and then this matrix is applied to the value. Isn't the output of this cross attention mechanism an enriched version of the input and not the currently decoded output since the attention matrix is being applied to values. I would think that the output of the entire mechanism should be and enriched version of the currently decoded output based on what the input is.</p> <p>A side thought of mine is that the cross attention mechanism does in fact produce an enriched version of the input which is then added back into the currently decoded output through a skip connection.</p> Answer:
https://ai.stackexchange.com/questions/45543/how-to-interpret-cross-attention
Question: <p>As far as I know, attention was first introduced in <a href="https://arxiv.org/abs/1409.0473" rel="nofollow noreferrer">Learning To Align And Translate</a>.</p> <p>There, the core mechanism which is able to disregard the sequence length, is a dynamically-built matrix, of shape output_size X input_size, in which every position <span class="math-container">$(o, i)$</span> holds the (log) probability that output <span class="math-container">$o$</span> should attend to input <span class="math-container">$i$</span>.</p> <p>That (log) probability is obtained by operating a learned function <span class="math-container">$a(h, s)$</span>, where <span class="math-container">$h$</span> is a hidden state of the input, and <span class="math-container">$s$</span> is a cell state of the output.</p> <p>Please let's disregard the fact that these inputs are RNN-based, and only look at the attention mechanism itself - a dynamic matrix of (log) probabilities is built, each slot is built by a function taking in two vectors, and outputting their &quot;correspondence&quot;.</p> <hr /> <p>Jump forward to the iconic <a href="https://arxiv.org/abs/1706.03762" rel="nofollow noreferrer">Attention Is All You Need</a>.</p> <p>Please disregard the fact that in this paper, <span class="math-container">$K$</span> was separated from <span class="math-container">$V$</span>, unlike in the previous one.<br /> I just want to look at the mechanism itself.</p> <p>Let's look only at Multi-Head Attention, and in it, let's look only at the part actually doing the attention: <span class="math-container">$ QK^T $</span></p> <p>Let's assume <span class="math-container">$Q$</span> and <span class="math-container">$K$</span> are vectors and not matrices, for simplicity. Their attention score is their dot product.</p> <hr /> <p>Let's compare the core attention mechanisms of &quot;align and translate&quot; against &quot;all you need&quot;.</p> <p>In &quot;align and translate&quot;, the function learns how two vectors correspond to one another</p> <p>In &quot;all you need, the function learns to project embeddings into a continuous space, where they can be compared against other such projections by their dot-product.</p> <p>One could easily implement multi-head-attention with the dynamic matrix method, by a function <span class="math-container">$b(k, q)$</span> yielding the (log) probability that the two correspond, and putting that into a dynamic-size matrix.</p> <hr /> <p><strong>My question is what in the &quot;all you need&quot; core attention method makes it better than the &quot;align and translate&quot; core attention method?</strong></p> <p>Are there ablation studies for this point?</p> <p>My intuition tells me it would be easier for a network to learn how to correspond vectors, rather than to learn an entire continuous space.</p> <hr /> <p>Again, please disregard the other contributions in &quot;all you need&quot;, such as self-attention, separation of key from value, normalization, Transformer, ect.</p> Answer: <p>The key difference between the attention mechanisms used in &quot;Learning To Align And Translate&quot; and &quot;Attention Is All You Need&quot; lies in the way that the similarity between the query and key vectors is calculated.</p> <h3>&quot;Learning To Align And Translate&quot;</h3> <p>The attention score is calculated by a learned function using a feed-forward neural network that takes in the query and key vectors and outputs a (log) probability of correspondence between them. This approach requires the model to learn a mapping from the input and output spaces to a joint space where the vectors can be compared against each other.</p> <h3>&quot;Attention Is All You Need&quot;</h3> <p>Here the attention is calculated as the similarity between the query and key vectors by taking their dot product and scaling it by the square root of their dimensionality. This approach does not require the model to learn a mapping to a joint space, but instead relies on the inherent structure of the vector space.</p> <h2>Pros/Cons</h2> <p>One advantage of the approach used in &quot;Attention Is All You Need&quot; is that it is computationally more efficient than the method used in &quot;Learning To Align And Translate&quot;, especially for long sequences. Specifically, the scaled dot product attention is faster compared to &quot;general/Bahdanau attention&quot; in the sense that the latter is a learnt via a usually shallow feedforward neural network. In that sense, overhead space and time complexity is added while traversing the computational graph of the model as part of training.</p> <p>That being said, there have been studies that have explored the use of different attention mechanisms in Transformers, including variants of the dot product and learned similarity functions. While the dot product attention used in &quot;Attention Is All You Need&quot; has shown to be effective in many cases, other mechanisms may be more appropriate for certain tasks or data types.</p> <p>I copy below recent studies relevant to transformer variations and its attention mechanism.</p> <ul> <li>Rewon Child, Scott Gray, Alec Radford, and Ilya Sutskever. Generating long sequences with sparse transformers. CoRR, abs/1904.10509, 2019.</li> <li>Nikita Kitaev, L. Kaiser, and Anselm Levskaya. Reformer: The efficient transformer. ArXiv, abs/2001.04451, 2020.</li> <li>Jack W. Rae, Anna Potapenko, Siddhant M. Jayakumar, and T. Lillicrap. Compressive transformers for long-range sequence modelling. ArXiv, abs/1911.05507, 2020.</li> <li>Sinong Wang, Belinda Z. Li, Madian Khabsa, Han Fang, and Hao Ma. Linformer: Self-attention with linear complexity. ArXiv, abs/2006.04768, 2020.</li> <li>A. Katharopoulos, A. Vyas, N. Pappas, and F. Fleuret. Transformers are rnns: Fast autoregressive transformers with linear attention. In Proceedings of the International Conference on Machine Learning (ICML), 2020.</li> <li>Yi Tay, Dara Bahri, Donald Metzler, Da-Cheng Juan, Zhe Zhao, and Che Zheng. Synthesizer: Rethinking self-attention in transformer models, 2020.</li> </ul>
https://ai.stackexchange.com/questions/40082/difference-between-dot-product-attention-and-matrix-attention
Question: <p>I've been reading about transformers &amp; have been having some difficulty understanding the concept of <em>alignment</em>.</p> <p>Based on this <a href="https://towardsdatascience.com/attn-illustrated-attention-5ec4ad276ee3#16cb" rel="nofollow noreferrer">article</a></p> <blockquote> <p>Alignment means matching segments of original text with their corresponding segments of the translation.</p> </blockquote> <p>Does this mean that, with transformers, we're adding the fully translated sentences as inputs too? What's the purpose of alignment? How exactly do these models figure out how to match the different segments together? I'm pretty sure there's some underlying assumption/knowledge that I'm not fully getting -- but I'm not entirely sure what.</p> Answer: <h3>Alignment:</h3> <p>We all know that a good translation cannot be done just by splitting words, converting them, and concatenating them back. Otherwise, a dictionary would be just enough. One translation problem is on the <strong>alignment</strong> of the words. For example:</p> <pre><code>Uma maçã grande e vermelha (1) (2) (3) (4) (5) | \ / ______/ | X / | / \ / | / X | / / \ (1) (3) (5) (2) A big red apple </code></pre> <h3>RNN</h3> <p>This article starts by showing how a RNN translator works and their underlying difficulties. And alignment is a huge pain for RNN because either you'd need another method* to solve it, so RNN could focus on smaller tasks each time. *And this method usually requires a labeled dataset (like the example above), which is quite tedious to create.</p> <p>What if, instead of hacking an external element to guess the alignment, we could just send the whole text and train a single neural network to both:</p> <ul> <li>Somehow solve the alignment problem.</li> <li>Use that to predict the next word.</li> </ul> <p>Wouldn't that be awesome? Introducing:</p> <h3>Transformers</h3> <p>They have a built-in self-attention component that scores all previous words according to their relevance for the next translated word!</p> <h4>TL;DR:</h4> <p>Transformers will automatically solve alignment while translating.</p>
https://ai.stackexchange.com/questions/26184/what-is-the-purpose-of-alignment-in-the-self-attention-mechanism-of-transforme
Question: <p>So while predicting the next word in autoregressive models(LLM) will the attention mechanism use queries from starting word or only previous word. Like for predicting after sentence &quot;I love&quot; attention mechanism takes query value for I and love and after predicting lets say as pizza, the next word attention mechanism does it take query value for I ,love ,pizza or only pizza.</p> Answer: <p>During inference, autoregressive models predicts text one token at a time sequentially. At each prediction step, attention mechanism takes query from only the current token and scores with all previous tokens' keys to compute a (softmax) weighted sum of the values associated with each of these previous tokens as output of the attention layer, and thus with runtime complexity of <span class="math-container">$O(T^2)$</span> for each layer where <span class="math-container">$T$</span> is the length of all the generated tokens in a sequence.</p> <p>The attention mechanism along with multiple attention heads are designed to use the entire sequence history to capture multiple aspects of dependencies, which enables it to understand and generate contextually relevant responses at both training and inference stages.</p>
https://ai.stackexchange.com/questions/47124/autoregressive-modelsllm-inference-prediction
Question: <p>From what I understand, the self-attention mechanism captures the dependency of a given token on various other tokens in a sequence. Inspired by nature, where natural laws are often expressed in terms of differential equations, I wonder: Does self-attention also capture relationships analogous to the rate of change of tokens?</p> Answer: <p>The self-attention mechanism in transformers does not explicitly compute derivatives or model rates of change in the strict mathematical sense of differential equations. However, it captures relationships between tokens analogous to a rate of change. Multiple attention layers can be interpreted as discrete steps in a dynamical system, where each layer with skip connection refines each input token's contextualized representation by propagating information through attention, akin to integrating a differential equation across layers. Instead of replacing the input representation entirely, the attention mechanism learns an <em>incremental</em> update that refines each token’s embedding based on its context. This incremental update is added to the original input, preserving information while also integrating new contextual dependencies. This is conceptually similar to the forward Euler method for numerical integration, where the hidden state is updated by adding a small change to the previous hidden state.</p> <p>The skip connection is critical for deep models because it helps preserve the flow of gradients during backpropagation, reducing issues like vanishing gradients. With attention layers wrapped in skip connections, the model can more easily learn to focus on the parts of the transformation that need changing, rather than having to relearn the entire representation at each layer.</p> <p>When you view the entire transformer as a sequence of residual updates, it can be interpreted as a discrete approximation of a <a href="https://en.wikipedia.org/wiki/Neural_differential_equation" rel="nofollow noreferrer">neural ODE</a> continuous process. In this picture, each attention layer acts like a “time step” where the hidden state as token embedding is evolved slightly by adding attended contextualization to it.</p> <blockquote> <p>Neural ODEs can be interpreted as a residual neural network with a continuum of layers rather than a discrete number of layers. Applying the Euler method with a unit time step to a neural ODE yields the forward propagation equation of a residual neural network... In physics-informed contexts where additional information is known, neural ODEs can be combined with an existing first-principles model to build a physics-informed neural network model called universal differential equations (UDE).</p> </blockquote>
https://ai.stackexchange.com/questions/48398/can-self-attention-capture-rate-of-change-of-token
Question: <p>I have a question about the context of CNN and LSTM. I have trained a CNN network for image classification. However, I would like to combine it with LSTM for visualizing the attention weights. So, I extracted the features from the CNN to put it into LSTM. However, I am stuck at the concept of combinating the CNN with LSTM.</p> <p>– Do I need to train the whole network again? Or just training the LSTM part is fine? – Can I just train the LSTM on image sequences based on classes (for e.g. 1 class has around 300 images) and do predictions later on extracted video frames? - In what way can I implement the attention mechanism with Keras? </p> <p>I hope you can help me while I struggle with the context of understanding the combination of this.</p> <p>~ EDITED ~</p> <p>I have trained a resnet50 to classify images. Although, I removed the last dense layer, to extract features from the trained CNN network. Those extracted features will be used as input in the newly created LSTM with attention mechanism to find out where the focus lies. The predictions will be on videos (extracted frames).</p> <p>Image -> extract features (CNN) -> LSTM + Attention (to check where the focus lies during the prediction) -> classify image (output class from N labels) </p> Answer:
https://ai.stackexchange.com/questions/13507/understanding-cnnlstm-concept-with-attention-and-need-help
Question: <p>I am wondering what is believed to be the reason for superiority of transformer?</p> <p>I see that some people believe because of the attention mechanism used, it’s able to capture much longer dependencies. However, as far as I know, you can use attention also with RNN architectures as in the famous paper attention is introduced(<a href="https://arxiv.org/pdf/1409.0473" rel="nofollow noreferrer">here</a>)).</p> <p>I am wondering whether the only reason for the superiority of transformers is because they can be highly parallelized and trained on much more data?</p> <p>Is there any experiment comparing transformers and RNN+attention trained on the exact same amount of data comparing the two?</p> Answer: <p>If you go through the <a href="https://arxiv.org/pdf/1706.03762.pdf" rel="nofollow noreferrer">main introductory paper of the transformer</a> (&quot;Attention is all you need&quot;), you can find the comparison of the model with other state-of-the-art machine translation method:</p> <p><a href="https://i.sstatic.net/o4SRo.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/o4SRo.png" alt="enter image description here" /></a></p> <p>For example, <a href="https://arxiv.org/pdf/1606.04199.pdf" rel="nofollow noreferrer">Deep-Att + PosUnk</a> is a method that has utilized RNN and attention for the translation task. As you can see, the training cost for the transformer with self-attention is <span class="math-container">$2.3 \cdot 10^{19}$</span> (FLOPs) and <span class="math-container">$1.0 \cdot 10^{20}$</span> (FLOPs) for the &quot;Deep-Att + PosUnk&quot; method (the transformer is 4 times faster) on &quot;WMT14 English-to-French&quot; dataset.</p> <p>Please note that the BLEU is a crucial factor here (not merely training cost). Hence, you can see the BLEU‌ value of the transformer superior to the <a href="https://arxiv.org/pdf/1610.10099.pdf" rel="nofollow noreferrer">ByteNet</a> (Neural Machine Translation in Linear Time). Although the ByteNet has not adopted the RNN, you can find the comparison of the ByteNet with other &quot;RNN + Attention&quot; methods in its original paper:</p> <p><a href="https://i.sstatic.net/abdit.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/abdit.png" alt="enter image description here" /></a></p> <p>Hence, by transitivity property of the BLEU score, you can find that the transformer has already outperformed other &quot;RNN‌ + Attention&quot; methods in terms of the BLEU score (please check their performance on &quot;WMT14&quot; dataset).</p>
https://ai.stackexchange.com/questions/23898/any-comparison-between-transformer-and-rnnattention-on-the-same-dataset
Question: <p>Are multi-head attention matrices weighted adjacency matrices?</p> <p>The job of the multi-head-attention mechanism in transformer models is to determine how likely a word is to appear after another word. In a sense this makes the resulting matrix a big graph with nodes and edges, where a node represents a word and an edge the likelihood to appear after that. So basically it is an adjacency matrix that is created.</p> Answer: <p>Short answer, yes I believe we can! One way feels more meaningful that the other. First, let's look at some nuance in the definition of attention. If <span class="math-container">$\text{score}(x_i, x_j) = \text{score}(x_j, x_i)$</span>, then the attention matrix is symmetric and naturally has the form of a weighted adjacency matrix. For example, this happens when attention is given by a simple dot product <span class="math-container">$\text{score}(x_i, x_j) = \langle x_i, x_j \rangle = x_i^Tx_j$</span>. This also happens if we have a learnable matrix <span class="math-container">$A$</span> and <span class="math-container">$\text{score}(x_i, x_j) = x_i^TAx_j$</span> if <span class="math-container">$A$</span> is symmetric. We can then view the attention matrix <span class="math-container">$\alpha_{i,j} = \text{Attn}_{i,j}(X)$</span> as a weighted adjacency matrix where the nodes represent input tokens, and edge weights correspond to similarity scores (as defined by the inner product, scaled inner product, or the symmetric matrix <span class="math-container">$A$</span>). Now, for the following definition of attention, this makes a little less sense, as the edge connecting token nodes in graph corresponding to tokens <span class="math-container">$x_i$</span> and <span class="math-container">$x_j$</span> is not the same as the weight on the edge connecting <span class="math-container">$x_j$</span> to <span class="math-container">$x_i$</span>, in general. Suppose <span class="math-container">$X \in \mathbb{R}^{d \times n}$</span> has as columns <span class="math-container">$X_i$</span> the <span class="math-container">$d$</span>-dimensional embeddings of the <span class="math-container">$n$</span>-tokens <span class="math-container">$x_1, x_2, ..., x_n$</span> from your input. Now, let</p> <p><span class="math-container">$$W_QX = Q$$</span> <span class="math-container">$$W_KX = K$$</span> <span class="math-container">$$W_VX = V$$</span></p> <p>be the learned weight matrices giving the &quot;query&quot; <span class="math-container">$q_i = W_QX_i$</span>, &quot;key&quot; <span class="math-container">$k_i = W_KX_i$</span>, and &quot;value&quot; <span class="math-container">$v_i = W_VX_i$</span> vectors. Then we can define attention as</p> <p><span class="math-container">\begin{align} \text{Attn}(X) &amp;= \text{softmax}\left( \frac{Q^TK}{\sqrt{d}} \right)V \\ &amp;= \text{softmax}_j\left(\text{score}(x_i, x_j)\right) \end{align}</span></p> <p>From this we can derive,</p> <p><span class="math-container">$$ \text{Attn}_{i,j}(X) = \frac{\exp \left( \frac{\langle q_i, k_j \rangle}{\sqrt{d}}\right)}{\sum_k \exp\left( \frac{\langle q_i, k_k \rangle}{\sqrt{d}} \right)}.$$</span></p> <p>Now, note, we have turned each column into a probability distribution by applying the softmax so we have</p> <p><span class="math-container">$$ P(X_i) = \text{softmax}\begin{pmatrix} \frac{\langle q_i, k_1 \rangle}{\sqrt{d}}\\ \frac{\langle q_i, k_2 \rangle}{\sqrt{d}}\\ \vdots \\ \frac{\langle q_i, k_n \rangle}{\sqrt{d}} \end{pmatrix}. $$</span></p> <p>Now, if we adjust for masked self attention, we can represent the attention mechanism as a directed graph (with weighted self-loops) as the entries in the attention matrix above the diagonal are zero, and so all edges are directed at token nodes that come &quot;after&quot; them.</p> <p>There is another way to understand attention using graphs when we view attention through the lens of (complete) graph attention networks as explained <a href="https://docs.dgl.ai/en/0.8.x/tutorials/models/4_old_wines/7_transformer.html" rel="nofollow noreferrer">here</a>.</p> <p>There is also a visualization you can find <a href="https://colab.research.google.com/drive/1hXIQ77A4TYS4y3UthWF-Ci7V7vVUoxmQ?usp=sharing#scrollTo=-QnRteSLP0Hm" rel="nofollow noreferrer">here</a> that shows the attention mechanism as a graph. It is equivalent to the graph attention formulation, but is more interactive and pretty.</p>
https://ai.stackexchange.com/questions/32036/is-the-multi-head-attention-in-the-transformer-a-weighted-adjacency-matrix
Question: <p>I am searching for an academic (i.e. with maths formulae) textbook which covers (at least) the following:</p> <ul> <li>GAN</li> <li>LSTM and transformers (e.g. seq2seq)</li> <li>Attention mechanism</li> </ul> <p>The closest match I got is <em>Deep Learning</em> (2016, MIT Press) but it only deals with part of the above subjects.</p> Answer: <p>There are a few more books that were published after 2016 that cover some of the topics you are interested in. I've not read any of them, so I don't really know whether they are good or not, but I try to summarise if they cover some of the topics you may be interested in.</p> <ul> <li><p><a href="http://faculty.neu.edu.cn/yury/AAI/Textbook/Deep%20Learning%20with%20Python.pdfhttp://faculty.neu.edu.cn/yury/AAI/Textbook/Deep%20Learning%20with%20Python.pdf" rel="nofollow noreferrer">Deep Learning with Python</a> (2017), by Francois Chollet (author of the initial Keras library), which covers GANs in <a href="http://faculty.neu.edu.cn/yury/AAI/Textbook/Deep%20Learning%20with%20Python.pdf#page=328" rel="nofollow noreferrer">section 8.5</a> (p. 305), but it does not seem to cover transformers and attention mechanisms, although it covers other intermediate/advanced topics (not sure to which extent), such as text generation with LSTMs, DeepDream, Neural Style Transfer and VAEs</p> </li> <li><p><a href="http://www.hdip-data-analytics.com/_media/resources/pdf/s4/grokking_deep_learning.pdf" rel="nofollow noreferrer">Grokking deep learning</a> (2019), by Andrew Trask, which seems to cover some intermediate/advanced topics (such as LSTMs and related tasks), but no transformers or GANs (unless I missed them); you can find the accompanying code <a href="https://github.com/iamtrask/Grokking-Deep-Learning" rel="nofollow noreferrer">here</a></p> </li> <li><p><a href="https://books.google.ch/books?hl=en&amp;lr=&amp;id=RKegDwAAQBAJ&amp;oi=fnd&amp;pg=PP1&amp;dq=Generative+Deep+Learning+david+foster&amp;ots=bqE76IUkF6&amp;sig=vXSbEW8S7ohXariAAhpbuckkKZs&amp;redir_esc=y#v=onepage&amp;q=Generative%20Deep%20Learning%20david%20foster&amp;f=false" rel="nofollow noreferrer">Generative Deep Learning: Teaching Machines to Paint, Write, Compose, and Play</a>, by David Foster, which covers many variants of GANs, VAEs and other stuff</p> </li> </ul> <p>The <a href="https://papers.nips.cc/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf" rel="nofollow noreferrer">first transformer was published in 2017</a>, so I guess there may not yet be a book that extensively covers it and other related models, such as the GPT models (if you're interested in CV, check <a href="https://machinelearningmastery.com/computer-vision-books/" rel="nofollow noreferrer">this blog post</a>, although it seems to list books that cover mostly traditional CV techniques). The attention mechanisms are older and can probably be found in textbooks that cover machine translation topics (such as seq2seq models with LSTMs), such as <a href="http://mt-class.org/jhu/assets/nmt-book.pdf#page=57" rel="nofollow noreferrer">this one</a>.</p>
https://ai.stackexchange.com/questions/25329/recent-deep-learning-textbook-i-e-covering-at-least-gans-lstm-and-transformer
Question: <p>I am reading the BERT paper <a href="https://arxiv.org/pdf/1810.04805.pdf" rel="nofollow noreferrer">BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding</a>.</p> <p>As I look at the attention mechanism, I don't understand why in the BERT encoder we have an intermediate layer between the attention and neural network layers with a bigger output (<span class="math-container">$4*H$</span>, where <span class="math-container">$H$</span> is the hidden size). Perhaps it is the layer normalization, but, by looking at the code, I'm not certain. </p> Answer: <p>The paper <a href="https://arxiv.org/abs/2012.11881" rel="nofollow noreferrer">Undivided Attention: Are Intermediate Layers Necessary for BERT?</a> should answer it.</p> <p>In the abstract, they write</p> <blockquote> <p>All BERT-based architectures have a self-attention block followed by a block of intermediate layers as the basic building component. However, a strong justification for the inclusion of these intermediate layers remains missing in the literature.</p> </blockquote> <p>In the conclusion, they write</p> <blockquote> <p>In this work we proposed a modification to the BERT architecture focusing on <strong>reducing the number of intermediate layers in the network.</strong> With the modified BERTBASE network <strong>we show that the network complexity can be significantly decreased while preserving accuracy on fine-tuning tasks.</strong></p> </blockquote>
https://ai.stackexchange.com/questions/11235/why-does-the-bert-encoder-have-an-intermediate-layer-between-the-attention-and-n
Question: <p>My understanding is that all tokens are passed to a transformer at once, and positional encodings help it understand their order in the sequence. And cosine type of positional encoding helps capture the short-term and long-term dependencies between the tokens (this is due to different frequencies for the cosine functions).</p> <p>First doubt: why doesn't word ordering implicitly emerge from the multi-head attention mechanism? My thought was that after training a transformer on tons of data, the mechanism would eventually be able to look at an unordered set of words and give it some order? Another thing: isn't order implicit in the way the rows of the Q, K, V and embedding matrices are ordered? i.e. 1st row is for 1st token, i-th row for i-th token, etc.</p> <p>Or is it that using positional encodings, we're able to take some of that &quot;learning load&quot; off of the attention mechanism, leaving it to focus on inter-token dependencies? This seems like a very hand-wavy explanation, hence I thought I should clarify with you all.</p> <p>Second doubt: even if positional encoding is needed, why can't we just use the normalized position of the token in the sequence? e.g. &quot;My name is Bob&quot; can become [0, 1, 2, 3] and this vector can be normalized to get the positional encoding. Multi-head self attention definitely is more than capable of capturing short, medium and long term token dependencies. So why do the effort of using cosine encodings?</p> Answer: <p>Your intuition is right when you use causal language models like GPTs which can learn sequence implicitly, positional encodings (PE) could further reduce the learning burden by injecting sequence order explicitly. However, attention mechanism itself is <a href="https://en.wikipedia.org/wiki/Attention_(machine_learning)#Flash_attention" rel="nofollow noreferrer">permutation-invariant</a>, thus for bidirectional masked language models like BERT there's no implicit position learning without PE.</p> <blockquote> <p>QKV attention is equivariant with respect to re-ordering the queries (rows of <span class="math-container">${\displaystyle \mathbf {Q} }$</span>); and invariant to re-ordering of the key-value pairs in <span class="math-container">${\displaystyle \mathbf {K} ,\mathbf {V} }$</span>... The permutation invariance and equivariance properties of standard QKV attention do not hold for the masked variant.</p> </blockquote> <p>As for the disadvantage of your normalised PE such as a simple linear function, cosine and sine functions encode positions across a range of frequencies, allowing the model to capture both short-term <em>and</em> long-term <em>periodic</em> dependencies by all the dimensions of PE. Some NLP tasks require understanding periodic or hierarchical recursive dependencies like word repetitions in proses vs poems. Finally relative position is more important than absolute position, cosine PEs directly describe relative positional information well while linear PE only provides absolute position information without more processing.</p>
https://ai.stackexchange.com/questions/47763/why-do-we-need-cosine-positional-encoding-in-multi-head-attention-based-transfor
Question: <p>Transformer architectures, based on the self-attention mechanism, have achieved outstanding performance in a variety of applications.</p> <p>The main advantage of this approach is that the given token can interact with any token in the input sequence and extract global information since the first layer, whereas CNN has to stack multiple convolutional or pooling layers in order to achieve a <em>receptive</em> field, that would involve the whole input sequence.</p> <p>By <em>receptive</em> field I mean the number of timestamps from the input signal on which does the output depend. For example, for sequence of two <code>Conv1D</code> with <code>kernel_size=3</code> receptive field is 5. And in transformer the output of the first blocks depends on the whole sequence.</p> <p>However, this comes at large computational and memory cost in the vanilla formulation: <span class="math-container">$$ O(L^2) $$</span> where <span class="math-container">$L$</span> is the length of the sequence.</p> <p>There have been proposed various mechanisms, that try to reduce this amount of computation:</p> <ul> <li>Random attention</li> <li>Window (Local attention)</li> <li>Global attention</li> </ul> <p>All these forms of attention are illustrated below:</p> <p><a href="https://i.sstatic.net/6Rf7D.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6Rf7D.png" alt="enter image description here" /></a></p> <p>And one can combine different of these approaches as in the <a href="https://arxiv.org/abs/2007.14062" rel="nofollow noreferrer">Big Bird paper</a></p> <p>My question is about local attention, attending only to the tokens in the fixed neighborhood of size <span class="math-container">$K$</span>. By doing so, one reduces the number of operations to: <span class="math-container">$$ O(L K) $$</span> However, now it is local as the ordinary convolution, and global receptive field will be achieved only via stacking many layers.</p> <p>Are there any advantages of Local self-attention against CNN, or it can be beneficial only in combination with other forms of attention?</p> Answer: <p>It is true that when using local attention with a window of size 5, the &quot;receptive field&quot; is the same as a CNN with kernel size 5 (or two CNN layers with kernel size 3). However, there is a key difference in how the learned weights are applied to the inputs.</p> <p><strong>In a CNN</strong>, the values of the many convolutional kernels are learned, but once learned, <strong>the kernels are static</strong>. In other words, at every position in the input (whether it be a 1D signal or 2D image), the dot product between the inputs within the window and the same CNN kernels is taken, and then a non-linear function applied.</p> <p><strong>With attention, the Query/Key/Value matrices additionally allow context to be taken into account</strong>. Instead of taking the dot-product of the input region with a set of fixed kernels, the additional matrices are effectively used to <strong>dynamically compute a new set of kernels</strong> for each position. &quot;Attention&quot; basically figures out for each convolution, which inputs are important (which inputs the network should &quot;pay attention&quot; to) by computing higher-valued weights using Q, K, and V.</p> <p>I highly recommend reading a breakdown of the original &quot;Attention is All You Need&quot; paper such as this blog post: <a href="https://jalammar.github.io/illustrated-transformer/" rel="nofollow noreferrer">https://jalammar.github.io/illustrated-transformer/</a></p>
https://ai.stackexchange.com/questions/28599/are-there-any-advantages-of-the-local-attention-against-convolutions
Question: <p>Suppose I have included 3 examples of an idiosyncratic sentence for training by a transformer:</p> <ul> <li>Example 1: <strong>Asdfogiug likes Zsdfoiusdhf and Zsdfoiusdhf likes Asdfogiug too.</strong></li> <li>Example 2: <strong>Bsodifhas likes Zsdfoiusdhf and Zsdfoiusdhf likes Bsodifhas too.</strong></li> <li>Example 3: <strong>Clkwjehrq likes Zsdfoiusdhf and Zsdfoiusdhf likes Clkwjehrq too.</strong></li> </ul> <hr /> <p>Now we prompt the above-trained transformer with the following:</p> <p><strong>Dlwkjerhtw likes Zsdfoiusdhf and Zsdfoiusdhf likes ______________</strong></p> <hr /> <p>Can our transformer complete the prompt correctly?</p> <p>How would the attention mechanism know to generate <strong>&quot;Dlwkjerhtw&quot;</strong> (a word which it has never seen before anywhere else) as the predicted next word in our prompt?</p> Answer: <p>To complete the pattern based on the given examples, the last statement should follow the same structure. Each example follows a clear pattern where the second person in the first part of the sentence is mirrored as the first person in the second part:</p> <ol> <li>Asdfogiug likes Zsdfoiusdhf and Zsdfoiusdhf likes Asdfogiug too.</li> <li>Bsodifhas likes Zsdfoiusdhf and Zsdfoiusdhf likes Bsodifhas too.</li> <li>Clkwjehrq likes Zsdfoiusdhf and Zsdfoiusdhf likes Clkwjehrq too.</li> </ol> <p>Following this structure:</p> <p>Dlwkjerhtw likes Zsdfoiusdhf and Zsdfoiusdhf likes Dlwkjerhtw too.</p> <h3>How the Transformer Model Completes the Prompt Correctly</h3> <ol> <li><p><strong>Understanding Patterns</strong>: Transformers are highly effective at recognizing and replicating patterns in data. From the given examples, the model identifies the pattern of names being swapped between the clauses. It knows that the first part of the sentence structure “Person1 likes Person2” must mirror as “Person2 likes Person1” based on the examples.</p> </li> <li><p><strong>Role of <a href="https://huggingface.co/docs/transformers/en/tokenizer_summary" rel="nofollow noreferrer">Tokenization</a></strong>:</p> <ul> <li><strong>Breaking Down Text</strong>: Tokenization involves breaking down the text into smaller units called tokens. For names or words it has never encountered before, the model uses subword tokenization methods like Byte Pair Encoding (BPE) or WordPiece.</li> <li><strong>Handling Unknown Words</strong>: These methods decompose unfamiliar words into smaller, more common subword units. For example, &quot;Dlwkjerhtw&quot; might be tokenized into [&quot;Dlw&quot;, &quot;kje&quot;, &quot;rht&quot;, &quot;w&quot;].</li> <li><strong>Maintaining Context</strong>: This allows the model to understand and generate text even with previously unseen names, by focusing on the subwords and their context.</li> </ul> </li> <li><p><strong>Attention Mechanism</strong>:</p> <ul> <li>The attention mechanism allows the model to weigh different parts of the input sentence when predicting the next token. It helps the model focus on the relevant part of the sentence to determine the appropriate word to generate next.</li> <li>When the model processes &quot;Dlwkjerhtw likes Zsdfoiusdhf and Zsdfoiusdhf likes ___________&quot;, it attends to the pattern that the second person in the first clause should appear as the first person in the second clause.</li> </ul> </li> <li><p><strong><a href="https://machinelearningmastery.com/a-gentle-introduction-to-positional-encoding-in-transformer-models-part-1/" rel="nofollow noreferrer">Positional Encoding</a></strong>: Transformers use positional encodings to understand the order of words in a sentence, ensuring that the mirrored relationship between the names in the two parts of the sentence is maintained. So, in simple words, it knows the position of words/sub-words in given input.</p> </li> <li><p><strong>Contextual Embeddings</strong>: Each token, including subwords, is converted into an embedding that captures its context. This helps the model understand the relationship between the names and predict the appropriate completion.</p> </li> </ol> <p>By leveraging tokenization, the attention mechanism, positional encoding, and contextual embeddings, the transformer model can correctly predict that &quot;Dlwkjerhtw&quot; should complete the sentence:</p> <p>Dlwkjerhtw likes Zsdfoiusdhf and Zsdfoiusdhf likes Dlwkjerhtw too.</p> <p>Even though &quot;Dlwkjerhtw&quot; is a name it has never seen before, the model generalizes the pattern from the provided examples and uses tokenization to handle the new name effectively.</p> <p><strong>Edit:</strong></p> <p>The ability of transformers to handle unknown words, such as &quot;Dlwkjerhtw,&quot; lies in how they create and use embeddings.</p> <p><a href="https://i.sstatic.net/DdVLUF54.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/DdVLUF54.png" alt="Simplified version of Creating Input embeddings for Transformers" /></a></p> <h2>Embeddings in Transformers</h2> <p>Transformers use embeddings, which are learnable representations of input tokens. Let's break down the process:</p> <ol> <li><p>Input Word: &quot;Dlwkjerhtw&quot;</p> </li> <li><p>Tokenization:</p> <ul> <li>The model uses a subword tokenization method (e.g., Byte Pair Encoding or WordPiece) to break down the word into <strong>known subwords</strong> from its corpus/dictionary.</li> <li>Tokenization Result: [&quot;Dlw&quot;, &quot;kje&quot;, &quot;rht&quot;, &quot;w&quot;]</li> </ul> </li> <li><p>Converting Input to Numbers:</p> <ul> <li>Each subword is mapped to a token ID based on the model's vocabulary.</li> <li>Example Token IDs: [15, 20, 30, 8]</li> </ul> </li> <li><p>Creating Embeddings:</p> <ul> <li>These token IDs are converted into embedding vectors. Suppose the length of each embedding vector <span class="math-container">$d = 512$</span>.</li> <li><strong>The embedding layer of the transformer learns to represent each input token in a meaningful way.</strong></li> <li>Embeddings Shape: 4 (subwords) x 512 (embedding dimension)</li> </ul> </li> <li><p>Adding Positional Encoding (PoE):</p> <ul> <li>Positional Encoding is added to the embeddings to provide information about the position of each token in the sentence.</li> <li>Positional Encodings Shape: 4 x 512</li> </ul> </li> <li><p>Final Context Embeddings:</p> <ul> <li>The final context embeddings are obtained by summing the embeddings and the positional encodings.</li> <li><span class="math-container">$Final Contextual Embeddings = Embeddings + PoE$</span></li> </ul> </li> </ol> <p>By combining the subword embeddings and positional encodings, the model captures both the subword information and their positions within the sentence. This allows the transformer to understand and generate text even with previously unseen words, as it can leverage the subword components and their contextual relationships.</p> <p>For detailed visuals refer to my post PDF on <a href="https://www.linkedin.com/posts/kulin-patel_llm-transformers-and-attention-mechanism-activity-7174470859124826112-VEVE?utm_source=share&amp;utm_medium=member_desktop" rel="nofollow noreferrer">LinkedIN</a></p>
https://ai.stackexchange.com/questions/45866/can-transformer-attention-make-predictions-based-on-analogy
Question: <p>Attention-scoring mechanism seems to be a commonly-used component in various seq2seq models, and I was reading about the original "Location-based Attention" in Bahadanau well-known paper at <a href="https://arxiv.org/pdf/1506.07503.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/1506.07503.pdf</a>. (it seems this attention is used in various forms of GNMT and text-to-speech sythesizers like tacotron-2 <a href="https://github.com/Rayhane-mamah/Tacotron-2" rel="nofollow noreferrer">https://github.com/Rayhane-mamah/Tacotron-2</a>).</p> <p>Even after repeated readings of this paper and other articles about Attention-mechanism, I'm confused about the dimensions of the matrices used, as the paper doesn't seem to describe it. My understanding is:</p> <ul> <li><p>If I have decoder hidden dim 1024, that means <span class="math-container">${s_{i-1}}$</span> vector is 1024 length.</p></li> <li><p>If I have encoder output dim 512, that means <span class="math-container">$h_{j}$</span> vector is 512 length.</p></li> <li><p>If total inputs to encoder is 256, then number of <span class="math-container">$j$</span> can be from 1 to 256.</p></li> <li><p>Since <span class="math-container">$W x S_{i-1}$</span> is a matrix multiply, it seems <span class="math-container">$cols(W)$</span> should match <span class="math-container">$rows(S_{i-1})$</span>, but <span class="math-container">$rows(W)$</span> still remain undefined. Same seems true for matrices <span class="math-container">$V, U, w, b$</span>.</p></li> </ul> <p>This is page-3/4 from the paper above that describes Attention-layer:</p> <p><a href="https://i.sstatic.net/xKD2U.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/xKD2U.png" alt="enter image description here"></a></p> <p>I'm unsure how to make sense of this. Am I missing something, or can someone explain this?</p> <p>What I don't understand is:</p> <ul> <li><p>What is the dimension of previous alignment (denoted by <span class="math-container">$alpha_{i-1})$</span>? Shouldn't it be total values of <span class="math-container">$j$</span> in <span class="math-container">$h_{j}$</span> (which is 256 and means total different encoder output states)?</p></li> <li><p>What is the dimension of <span class="math-container">$f_{i,j}$</span> and convolution filter <span class="math-container">$F$</span>? (the paper says <span class="math-container">$F$</span> belongs to <span class="math-container">$kxr$</span> shape but doesn't define <span class="math-container">$'r'$</span> anywhere). What is <span class="math-container">$'r'$</span> and what does <span class="math-container">$'k x r'$</span> mean here?</p></li> <li><p>How are these unknown dimensions for matrices <span class="math-container">$'V, U, w, b'$</span> described above determined in this model?</p></li> </ul> Answer:
https://ai.stackexchange.com/questions/21588/how-to-understand-the-matrices-used-in-the-attention-layer
Question: <p>In section 2.1 of the <a href="https://arxiv.org/pdf/1710.10903.pdf" rel="nofollow noreferrer">Graph attention network paper</a></p> <p>The graph attention layer is described as</p> <blockquote> <p>as an initial step, a shared linear transformation, parametrized by a weight matrix, W ∈ RF ′×F , is applied to every node. We then perform self-attention on the nodes—a shared attentional mechanism a : RF ′ × RF ′→ R computes attention coefficients eij = a(Whi, Whj ) that indicate the importance of node j’s features to node i.</p> </blockquote> <p>(forgive my amateur formatting)</p> <p>The function <code>a</code> represents a fully connected neural network that takes the concatenated vector of <code>Whi</code> and <code>Whj</code>, then outputs a single value which is pushed through a <code>softmax</code> to get the attention score <code>aij</code>. Then, the embedding vectors <code>Whj</code> (for all neighboring nodes of <code>i</code>) are weighted and summed by the attention score as normal.</p> <p>If my understanding is correct, this means that matrix W represents the query, the key and the value transformation matrices all in one. But how can it do that? I feel that the difference may lie in the way the additive attention is calculated vs the dot-product one, but I cannot comprehend how this works. Why can we use a shared matrix here and not there? Is it theoretical or technical?</p> Answer: <p>To my understanding, there isn't any theoretical reason why the query, key and values weights are absent.</p> <blockquote> <p>I feel that the difference may lie in the way the additive attention is calculated vs the dot-product one.</p> </blockquote> <p>In the equations for the Graph Attention Network (GAT), there is for sure a difference between GAT and Transformers. However, I think you might be misunderstanding the relationship between the two. The attention mechanism in GATs is not equivalent to the one in Transformers. This means that one is not simply a rearrangement of the other; they are different inductive biases.</p> <blockquote> <p>If my understanding is correct, this means that matrix W represents the query, the key and the value transformation matrices all in one. But how can it do that?</p> </blockquote> <p>The equation states:</p> <p><span class="math-container">$$ e_{ij} = a(Wh_i,Wh_j ) $$</span></p> <p>You are correct that a single weight matrix <span class="math-container">$W$</span> is used for the projection from the feature space to the feature map. However, this doesn't mean that <span class="math-container">$W$</span> represents the query, key, and value matrices, although it serves those roles if compared to the Transformer architecture.</p> <p>I feel that you understand the forward pass of the GAT but lack intuition on why it is done like that. According to Aleks Gordic's commentary in the following <a href="https://youtu.be/uFLeKkXWq2c?si=5iSh9Nlzf7WOmhgz&amp;t=952" rel="nofollow noreferrer">video</a>, he mentioned that he spoke with the authors of the paper. They said they had indeed tried using separate query, key, and value weight matrices but encountered overfitting in their experiments. They concluded that using a single weight matrix yielded more generalizable results. This makes sense when considering that the goal of GATs is not to construct a language model, which is a more complex problem. GATs most often operate on static graph data with features to learn. They are designed not to copy Transformers, but to adapt Transformer principles to graph data and objectives.</p> <blockquote> <p>Is it theoretical or technical?</p> </blockquote> <p>Based on what I understand, most inductive biases, if not all, are not theoretically grounded. If you think about it, there is no paper that says why one method theoretically performs better than another in neural networks. This is because it ultimately depends on your data and your final goal for the model. We only have experimental data to support our claims and a sense of intuition. The difficult part is to develop that intuition, which is based on previous experiments.</p> <p>What I'm trying to say is that there is no reason why you couldn't try adding three different weight matrices instead of one. For the original idea of the Transformer, it makes sense to divide the attention into queries and keys because we are trying to simulate language, and language has a semantic ordering component. This means that it is not the same to say &quot;Hello World&quot; as it is to say &quot;World Hello.&quot; Based on this, it is logical to have extra weights that can identify this difference.</p> <p>For the datasets that were tried with GAT, they were citation networks and protein predictions. Predicting classes in citations may not require using more weights because the problem statement does not seem to require it. However, this is not set in stone. In the end, the only way to know if one architecture is better than another is through experimentation.</p>
https://ai.stackexchange.com/questions/42292/why-is-there-a-shared-matrix-w-in-graph-attention-networks-instead-of-the-query
Question: <p>When we are applying a mask onto the padded values in an input sequence, it is typically done through setting the padded values as negative infinity. For example, a tensor of values <code>[1,2,3,0,0]</code> should result in a padding mask of <code>pad_mask = [True, True, True, False, False]</code> (or the opposite depending on your flavour). However, if we apply the mask i.e <code>attention_scores = attention_scores.masked_fill_(pad_mask.T == False, float('-inf')) </code>before applying softmax, won't we get the 4th and 5th row of the attention_scores as 'nan' when we softmax attempts to calculate the probability distribution along each row?</p> <p>Does that mean the step of where to apply the mask is incorrect, and we should apply a zero-ing out of the pad token rows in the attention_score matrix after applying the softmax function? or is there another key concept/step I am missing here</p> Answer: <p>You are masking at the wrong place. Masking happens before the sequence goes into the encoder/decoder layer depending on what kind of architecture you are using. It happens right after you calculate the embeddings using positional encoding + token encodings.</p> <p>This is because the masked positions are also considered in calculating the attention values, and if you simply make those masked attention values zero, the model loses the attention and can't make accurate predictions.</p>
https://ai.stackexchange.com/questions/41062/when-do-we-apply-a-mask-onto-our-padded-values-during-attention-mechanisms
Question: <p>I'm reading OpenAI's new paper &quot;<a href="https://openaipublic.blob.core.windows.net/neuron-explainer/paper/index.html" rel="nofollow noreferrer">Language models can explain neurons in language models</a>&quot; And I can't fully understand the concept of neurons here.</p> <p>Can you please explain it? Is it related to the attention mechanism?</p> Answer: <p>It seems that in this paper neuron means the perceptrons in the MLP layers of the transformer.</p>
https://ai.stackexchange.com/questions/40385/what-is-a-neuron-in-large-language-models
Question: <p>In RNNs, to avoid &quot;forgetting&quot; information encoded by earlier encoders, we can use attention. It's basically a second neural network that tells us how much we should attend at time <em>t</em> on each of the earlier hidden states (from <em>1</em> to <em>t - 1</em>). This is described here: <a href="https://i.sstatic.net/cri6k.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/cri6k.png" alt="enter image description here" /></a> (image from <a href="https://medium.com/swlh/a-simple-overview-of-rnn-lstm-and-attention-mechanism-9e844763d07b" rel="nofollow noreferrer">https://medium.com/swlh/a-simple-overview-of-rnn-lstm-and-attention-mechanism-9e844763d07b</a>)</p> <p>However, there is something I don't understand. This second neural network will output <em>t</em> values. So there will be <em>t</em> neurons on the last layer. What if my input sentence (in a seq2seq network for example) has only <em>t - 2</em> words. Or <em>t + 2</em> words. Then I can't use that same second neural network since its architecture is fixed. How is it dealt?</p> <p>EDIT: is it that the second neural network takes as input one encoder hidden state and one decoder hidden state, and we get <em>t</em> scores by doing <em>t</em> forward passes (one per each input hidden state, all with the current decoder hidden state)? And then we softmax all those <em>t</em> outputs?</p> Answer: <p>You don't need padding for attention with variable-length inputs. Looking at the formulation in the article: <a href="https://i.sstatic.net/u6VTP.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/u6VTP.png" alt="Attention description from article: https://medium.com/swlh/a-simple-overview-of-rnn-lstm-and-attention-mechanism-9e844763d07b" /></a></p> <p>A learned model (<span class="math-container">$\mathbf{a}(\cdot)$</span>) encodes the hidden state of each input token directly. This means that if you have a longer/shorter input, you would just run more forward-passes.</p> <p>During training, <span class="math-container">$\mathbf{a}(\cdot)$</span> learns to give higher values for more relevant tokens. It only depends on the hidden-dimensions of <span class="math-container">$h_j$</span> and <span class="math-container">$s_{t-1}$</span>. You might still use masking and padding, this generally is more of a efficiency thing (because GPUs like static data sizes). In fact, you'll probably have to use masking to make sure that your decoder doesn't attend to masking tokens.</p>
https://ai.stackexchange.com/questions/43660/attention-with-recurrent-neural-networks
Question: <p>Convolutions can be expressed as a matrix-multiplication (see e.g. <a href="https://ai.stackexchange.com/q/11172/2444">this post</a>) and as an element-wise multiplication using the Fourier domain (<a href="https://en.wikipedia.org/wiki/Convolution_theorem" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Convolution_theorem</a>).</p> <p>Attention utilizes matrix multiplications, and is as such <span class="math-container">$O(n^2)$</span>. So, my question is, is it possible to exploit the Fourier domain for attention mechanisms by turning the matrix multiplication of attention into a large convolution between the query and the key matrices?</p> Answer:
https://ai.stackexchange.com/questions/23699/is-it-possible-to-express-attention-as-a-fourier-convolution
Question: <p>In the paper <a href="https://arxiv.org/pdf/2008.02217.pdf" rel="nofollow noreferrer">Hopfield networks is all you need</a>, the authors mention that their modern Hopfield network layers are a good replacement for pooling, GRU, LSTM, and attention layers, and tend to outperform them in various tasks.</p> <p>I understand that they show that the layers can store an exponential amount of vectors, but that should still be worse than attention layers that can focus parts of an arbitrary length input sequence.</p> <p>Also, in their paper, they briefly allude to Neural Turing Machine and related memory augmentation architectures, but do not comment on the comparison between them.</p> <p>Has someone studied how these layers help improve the performance over pooling and attention layers, and is there any comparison between replacing layers with Hopfield layers vs augmenting networks with external memory like Neural Turing Machines?</p> <p><strong>Edit 29 Jan 2020</strong> I believe my intuition that attention mechanism should outperform hopfield layers was wrong, as I was comparing the hopfield layer that uses an input vector for query <span class="math-container">$R (\approx Q)$</span> and stored patterns <span class="math-container">$Y$</span> for both Key <span class="math-container">$K$</span> and Values <span class="math-container">$V$</span>. In this case my assumption was that hopfield layer would be limited by its storage capacity while attention mechanism does not have such constraints.</p> <p>However the authors do mention that the input <span class="math-container">$Y$</span> may be modified to ingest two extra input vectors for Key and Value. I believe in this case it would perform hopfield network mapping instead of attention and I do not know how the 2 compare. <a href="https://i.sstatic.net/CIz3W.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/CIz3W.png" alt="Hopfield Layer - Attention analogy" /></a></p> Answer: <p>Will try to formulate my understanding of the ideas in this paper, mention my own concerns that I see are relevant to your question, and see if we can identify any confusions along the way that might clarify the issue</p> <p>On eq(6) of <a href="https://ml-jku.github.io/hopfield-layers/" rel="nofollow noreferrer">the relevant blog post</a>, they identify the weight matrix of a discrete, binary Hopfield network as</p> <p><span class="math-container">$$ \boldsymbol{W} = \sum_i^N x_i x_i^T $$</span></p> <p>with N raw stored entries, that are retrieved by iterating the initial guess <span class="math-container">$\xi$</span> with the following update rule</p> <p><span class="math-container">$$ \xi_{t+1} = \text{sgn}( \boldsymbol{W} \xi_{t} - b ) $$</span></p> <p>Now to the paper in question, the update rule for the generalization they propose for continuous states that would be used is (eq 22 in OP):</p> <p><span class="math-container">$$ \xi_{t+1} = \boldsymbol{X} \text{softmax}( \beta \boldsymbol{X}^T \xi_{t} ) $$</span></p> <p>Where <span class="math-container">$\boldsymbol{X} = (x_0, x_1, \dots , x_N ) $</span></p> <p>The first substantial difference I see is that, while on the case of binary entries, all the weights of the network are encoded in the matrix <span class="math-container">$\boldsymbol{W}$</span>, hence the storage is constant regardless of how many actual patterns are stored in it. In contrast, in this continuous case generalized rule, the <span class="math-container">$\boldsymbol{X}$</span> matrix seems to grow linearly with the size of entries, in fact it keeps all the stored entries directly. By their update rule, it doesn't seem to be a way around storing and keeping around the entire entries, and the update rule seems to only find a &quot;best fit&quot; among the entries, using the scalar dot product of the attention mechanism. I still think I might be missing something important here</p>
https://ai.stackexchange.com/questions/26038/reasoning-behind-performance-improvement-with-hopfield-networks
Question: <p>There is something that i can't get it, given a prompt input to ChatGPT, this is One Hot Encoded, Embedded, Positional Encoded and so on. Anyway we have a matrix, still after attention mechanism we have a matrix, how we end with a probability vector and not with a probability matrix?</p> Answer: <p>Once the last level of the <a href="https://paperswithcode.com/method/multi-head-attention" rel="nofollow noreferrer"><em>multi-head attention</em></a> mechanism returns its output, the matrix is flattened in an array and sent as input to a <em><a href="https://pytorch.org/docs/stable/generated/torch.nn.Linear.html#torch.nn.Linear" rel="nofollow noreferrer">linear</a></em> level (a.k.a. a <em>fully-connected</em> layer).The output of this layer is activated via <a href="https://pytorch.org/docs/stable/generated/torch.nn.Softmax.html#softmax" rel="nofollow noreferrer">Softmax</a> in order to have probabilities associated to the next token. The token with the highest probability is then returned.</p>
https://ai.stackexchange.com/questions/45890/how-chatgpt-pass-from-a-prompt-to-a-predicted-word
Question: <p>So I'm trying to write PyTorch code that performs the single-head computation, so you get some input vectors, attention mechanism/linear transformations, some output vectors.</p> <p>Then I tried to re-use the same matrices by splitting them up into submatrices and get the same output vectors by using a 2-head attention approach. If I'm not mistaken, you should be able to just concatenate the outputs together.</p> <p>The dimensions were correct, so output of single head and output of multi-head had the same dimensions, making me believe that multi-head is just better for performance reasons but not really different if we talk about input and output.</p> <p>However, the output values were not the same despite both using the same matrix.</p> <p>Is multi-head now inherently different from single head or how can I have an example compute the exact same input and output using single head and multi-head? I thought it should be possible if you re-use the same matrices but I was wrong...</p> Answer: <p>Your approach of splitting the same matrices into submatrices for different heads and then concatenating together as output doesn't work as intended because each head in multi-head attention should have distinct learnable weight matrices which enable each head to focus on different aspects of the input sequence. Simply splitting the weight matrices into two submatrices for the two heads defeats the purpose of having multiple heads in the first place, essentially forcing the two heads to learn the same original aspect of self-attention and might causing the output values were not the same despite both using the same matrix.</p>
https://ai.stackexchange.com/questions/47156/are-single-head-and-multi-head-attention-equivalent-in-terms-of-input-and-output
Question: <p>I have a question about <a href="http://proceedings.mlr.press/v37/xuc15.pdf" rel="nofollow noreferrer">Show, Attend and Tell: Neural Image CaptionGeneration with Visual Attention</a> paper by Xu. The basic mechanism of stochastic hard attention is that each pixel of the input image has a corresponding parameter <span class="math-container">$\alpha_i$</span>, which describes the probability that this pixel will be chosen for further processing.</p> <p>But I don't see an explanation of how to train or define this parameter in the paper. Can someone explain how to train this <span class="math-container">$\alpha_i$</span> for each pixel?</p> Answer:
https://ai.stackexchange.com/questions/25828/how-are-the-parameters-alpha-i-of-hard-attention-trained
Question: <p>There are many articles comparing RNNs/LSTMs and the Attention mechanism. One of the disadvantages of RNNs that is often mentioned is that while Attention can be computed in parallel, RNNs are highly sequential. That is, the computation of the next tokens depends on the result of previous tokens, thus, RNNs are losing to Attention in terms of speed.</p> <p>Even though I fully agree that RNNs are sequential as stated above, I think they are still parallelizable by splitting the mini-batch into sub-batches and each of these sub-batches is processed independently by a dedicated thread. For example, a training batch of size 32 can be split into 4 sub-batches of size 8; 4 threads process 4 sub-batches independently. That way, RNNs/LSTMs are parallelizable and this is not a disadvantage compared to Attention.</p> <p>Is my thought correct?</p> Answer: <p>You are talking about model parallelism. But, that's not the reason RNNs/LSTMs are not in vogue.</p> <p>Imagine your ability to read the first line of a page and going on reading and still making connections to the first line until the end of the page.</p> <p>Can RNNs/LSTMs do that? No. Can Attention (i.e. Transformers) do it? Yes.</p> <p>The reason is simple Attention is effectively an affinity matrix between each and every input that goes into a network. So, it is able to do that. We have a huge memory overload but hey, we want the performance.</p> <p>In case of RNNs/LSTMs, the cells have to do this heavy-lifting, there is only a set amount of information that can be contained in them. That's why you have to forget gate to control information retained.</p> <p>Nevertheless, your thought is correct but that's not the reason for Attention to be in vogue. But, your thought has negative ramifications when we see how to implement it. Also, nevertheless the computation will be still sequential since you can't process input (n + 1) without input n. Local parallelization is possible but not global.</p>
https://ai.stackexchange.com/questions/27171/do-rnns-lstms-really-need-to-be-sequential
Question: <p>In the paper <a href="https://openreview.net/pdf?id=B1DmUzWAW" rel="nofollow noreferrer">A Simple Neural Attentive Meta-Learner</a>, the authors mentioned right before Section 3.1:</p> <blockquote> <p>we preserve the internal state of a SNAIL across episode boundaries, which allows it to have memory that spans multiple episodes. The observations also contain a binary input that indicates episode termination.</p> </blockquote> <p>As far as I can understand, SNAIL uses temporal convolutions to aggregate contextual information, from which causal attention learns to distill specific pieces of information. Temporal convolutions does not seems to maintain any internal state, and neither does the attention mechanism they use after <a href="https://arxiv.org/pdf/1706.03762.pdf" rel="nofollow noreferrer">this paper</a>. This makes me wonder: "What is the internal state of a SNAIL?"</p> Answer: <p>Here's what I understand, welcome to point out any mistakes.</p> <p>When starting a new episode(but still in the same task), SNAIL does not clear its batches. Instead, it makes decisions based on the current observation and observation-action pairs from the previous episode. In this way, it keeps knowledge of the previous episode whereby achieving few-shot learning in the test time.</p>
https://ai.stackexchange.com/questions/11557/what-is-the-internal-state-of-a-simple-neural-attentive-meta-learnersnail
Question: <p>I was hoping someone could explain to me why in the transformer model from the &quot;Attention is all you need&quot; paper there is no activation applied after both the multihead attention layer and to the residual connections. It seems to me that there are multiple linear layers in a row, and I have always been under the impression that you should have an activation between linear layers.</p> <p>For instance when I look at the different flavors of resnet they always apply some sort of non linearity following a linear layer. For instance a residual block might look something like...</p> <p>Input -&gt; Conv -&gt; BN -&gt; Relu -&gt; Conv -&gt; (+ Input) -&gt; BN -&gt; Relu</p> <p>or in the case of pre-activation...</p> <p>Input -&gt; BN -&gt; Relu -&gt; Conv -&gt; BN -&gt; Relu -&gt; Conv -&gt; (+ Input)</p> <p>In all the resnet flavors I have seen, they never allow two linear layers to be connected without a relu in-between.</p> <p>However in the the transformer...</p> <p>Input -&gt; Multihead-Attn -&gt; Add/Norm -&gt; Feed Forward(Dense Layer -&gt; Relu -&gt; Dense Layer) -&gt; Add/Norm</p> <p>In the multihead attention layer it performs the attention mechanism and then applies a fully connected layer to project back to the dimension of its input. However, there is no non linearity between that and feed forward network (except for maybe the softmax used in part of the attention.) A model like this would make more sense to me...</p> <p>Input -&gt; Multihead-Attn -&gt; Add/Norm -&gt; <strong>Relu</strong> -&gt; Feed Forward(Dense Layer -&gt; Relu -&gt; Dense Layer) -&gt; Add/Norm -&gt; <strong>Relu</strong></p> <p>or something like the pre-activated resnet...</p> <p>Input -&gt; Relu -&gt; Multihead-Attn -&gt; Add/Norm -&gt; Input2 -&gt; <strong>Relu</strong> -&gt; Feed Forward(Dense Layer -&gt; Relu -&gt; Dense Layer) -&gt; Add/Norm(Input2)</p> <p>Can anyone explain why the transformer is the way it is?</p> <p>I have asked a similar question when I was looking at the architecture of wavenet on another forum but I never really got a clear answer. In that case it did not make sense to me again why there was no activation applied to the residual connections. (<a href="https://www.reddit.com/r/MachineLearning/comments/njbjfb/d_is_there_a_point_to_having_layers_with_just_a/" rel="noreferrer">https://www.reddit.com/r/MachineLearning/comments/njbjfb/d_is_there_a_point_to_having_layers_with_just_a/</a>)</p> Answer: <p>This goes back to the purpose of self-attention. While the Vaswani et als Attention is All You Need paper does not explicitly define self-attention, I am using it here as being synonymous to what it refers to as scaled dot-product attention when all three inputs are identical.</p> <p>Measure between word-vectors is generally computed through cosine-similarity because in the dimensions word tokens exist, it's highly unlikely for two words to be colinear even if they are trained to be closer in value if they are similar. However, two trained tokens will have higher cosine-similarity if they are semantically closer to each other than two completely unrelated words.</p> <p>This fact is exploited by scaled dot-product attention; After several of these matrix multiplications, the dissimilar words will zero out or become negative due to the dot product between them, and the similar words will stand out in the resulting matrix.</p> <p>So, self attention can be viewed as a weighted average, where less similar words become averaged out faster (toward the zero vector, on average), thereby achieving groupings of important and unimportant words (i.e. attention). The weighting happens through the dot product. If input vectors were normalized, the weights would be exactly the cosine similarities.</p> <p>The important thing to take into consideration is that within the self-attention mechanism, there are no parameters; Those linear operations are just there to capture the relationship between the different vectors by using the properties of the vectors used to represent them.</p> <p>Read <a href="http://peterbloem.nl/blog/transformers" rel="nofollow noreferrer">this blog post by Peter Bloem</a> for a more in-depth explanation of self-attention.</p> <hr /> <h2>Edit</h2> <p>I should add that this explanation is less satisfactory considering how Transformers also seem to work for tasks without learned embeddings, like time-series forecasting. I have no idea why that is. However, the model was originally used for NLP, and they did use learned embeddings. So, I bet that's why that particular architecture looks the way it does.</p> <p>Bloem, in the blog post above, does discuss the mathematical properties of self-attention without bringing up the fact that the original architecture does have learned embeddings.</p> <p>All this shows is that having learned embeddings does not matter that much; The layers following the multi-headed attention will learn the relationships between the vectors. The general point about the properties of the dot-product being exploited does stand.</p>
https://ai.stackexchange.com/questions/30341/why-does-a-transformer-not-use-an-activation-function-following-the-multi-head-a
Question: <p>I want to understand the transformer architecture, so I start with self attention and I understand their mechanism, but when I pass to the multi-head attention I find some difficulties like how calculate Q , K and V for each head. I find many way to calculate Q , K and V but I don't know which way is correct.<br> <strong>method 1:</strong> <img src="https://jalammar.github.io/images/t/transformer_multi-headed_self-attention-recap.png" alt="this image illustrate how calcule these matrices " /> <strong>method 2:</strong> I find this method in YouTube. <a href="https://i.sstatic.net/HEZHv.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/HEZHv.png" alt="enter image description here" /></a> <strong>method 3:</strong> in this method it just for headi we have: Qi=xWqi Ki=xWki Vi=xWvi so I don't know which method is correct there is the links of my references <a href="https://jalammar.github.io/illustrated-transformer/" rel="nofollow noreferrer">The Illustrated Transformer</a> <a href="https://youtu.be/bCz4OMemCcA?si=4cJa0YojjkPgzcs0" rel="nofollow noreferrer">YouTube video</a></p> Answer: <p>As far as I understand your question, you have problems with multiple heads. Let's take the input <span class="math-container">$\mathbf{Q}$</span> (with dimension: <span class="math-container">$\textit{seq_length}$</span> x <span class="math-container">$d_{model}$</span>), which is the same for <span class="math-container">$\mathbf{Q}, \mathbf{K}$</span> and <span class="math-container">$\mathbf{V}$</span> (thus <span class="math-container">$\mathbf{Q} = \mathbf{K} = \mathbf{V}$</span>). then you need to multiply them with 3 different matrices (with dimension: <span class="math-container">$d_{model}$</span> x <span class="math-container">$d_{model}$</span>), thus: <span class="math-container">$\mathbf{Q}$</span> x <span class="math-container">$\mathbf{W}_{q}$</span>, <span class="math-container">$\mathbf{K}$</span> x <span class="math-container">$\mathbf{W}_{k}$</span>, <span class="math-container">$\mathbf{V}$</span> x <span class="math-container">$\mathbf{W}_{v}$</span>. Why this multiplication? Because those are the matrices with the learnable parameters. Now... in case of multi head attention, you need to split them by the number heads, that you want. Since the model dimension (<span class="math-container">$d_{model}$</span>) must be divisible by the number of heads (<span class="math-container">$h$</span>). At this point you do not need to create or use any complicate function, you can just reshape the three matrices in this way:</p> <pre><code># (batch, seq_len, d_model) --&gt; (batch, seq_len, h, d_k) --&gt; (batch, h, seq_len, d_k) </code></pre> <p>or in PyTorch code if you prefer:</p> <pre><code>query = query.view(query.shape[0], query.shape[1], self.h, self.d_k).transpose(1, 2) (where d_k = dim_model // h) </code></pre> <p>In case you don't &quot;see&quot; the division in chunks, open a terminal, import torch and try the line of code above (removing the batch in all the calculation) allright?</p>
https://ai.stackexchange.com/questions/45329/how-the-q-k-v-be-calculated-in-multi-head-attention
Question: <p>During trying to understand transformers by reading <a href="https://arxiv.org/abs/1706.03762" rel="nofollow noreferrer">Attention is all you need</a>, I noticed the authors constantly refer to &quot;self attention&quot; without explaining it.</p> <p>The original attention mechanism is introduced in <a href="https://arxiv.org/abs/1409.0473" rel="nofollow noreferrer">NEURAL MACHINE TRANSLATION BY JOINTLY LEARNING TO ALIGN AND TRANSLATE</a>, in which a the relationship between each output and each input is encoded into a matrix whose size is dependent on input and output sizes.</p> <p>It seems the paper which first introduced self-attention is <a href="https://arxiv.org/abs/1703.03130" rel="nofollow noreferrer">A STRUCTURED SELF-ATTENTIVE SENTENCE EMBEDDING</a>.</p> <p>I am not finding similar ideas in this paper, and would like an explanation.</p> <p>In this paper, self-attention is defined like so</p> <p>Given <span class="math-container">$H=(h_1, h_2, ... h_n)$</span>, a sequence of hidden bidirectional LSTM states, each of dimension <span class="math-container">$2u$</span>, they try to encode the sentence into a fixed length vector. They do so by weighting the hidden states according to the probabilities (weights) vector <span class="math-container">$a$</span> defined as</p> <p><span class="math-container">$a = softmax(W_{s_2}tanh(W_{s_1}H^T))$</span></p> <p>This can be read as a multi layer perceptron, <span class="math-container">$A$</span>, operating on vectors of size <span class="math-container">$2u$</span>, with a single layer of activation, with activation function <span class="math-container">$tanh$</span>, and output size of 1. <span class="math-container">$A$</span>'s output units are log probabilities, meaning &quot;how likely is timestamp <span class="math-container">$i$</span> to be important for the sentence embedding&quot;. <span class="math-container">$A$</span> is then used on the <span class="math-container">$n$</span> hidden states, <span class="math-container">$H$</span>, to obtain <span class="math-container">$n$</span> weights, one for each hidden state <span class="math-container">$h_i$</span>.</p> <p>Then they go on to extend this from dimension <span class="math-container">$1$</span> to <span class="math-container">$r$</span>.</p> <p>This is all well, but I fail to see what good this <span class="math-container">$A$</span> actually does - <strong>it does not use any relationship between two different states <span class="math-container">$h_i, h_j, i \ne j$</span> other than that already found by the LSTM, thus (in my mind,) defeating the purpose</strong>.</p> <p>I expected something like the original attention - creating a <span class="math-container">$nxn$</span> matrix, and have some MLP <span class="math-container">$a(h_i, h_j)$</span> calculate each cell, thus encoding probability of the relationship between the cells. This was not done here.</p> <hr /> <p>My questions</p> <ol> <li>Is this really the self attention mentioned throughout &quot;attention is all you need&quot;? if not, please refer me to the correct paper</li> <li>Did I understand this paper correctly, and indeed other than the LSTM, there are no relationships between the different time stamps, thus defeating the purpose of encoding the sentence better than the LSTM? [we could just add another layer into the LSTM, isn't it the same or better?]</li> <li>Please explain the point of this paper. Adding a global MLP on all LSTM states? That's it?</li> <li>Why only a single layer? why <span class="math-container">$tanh$</span>? why not just a single vector of size <span class="math-container">$1x2h$</span> and no activation at all?</li> </ol> Answer: <blockquote> <ol> <li>Is this really the self attention mentioned throughout &quot;attention is all you need&quot;?</li> </ol> </blockquote> <p>I think that the crucial point that you are missing is the difference between the Transformer architecture and recurrent neural network (RNN) architecture.</p> <p>In the RNNs the context information is stored in the hidden state <span class="math-container">$h_t$</span> which is modified and passed onto the next step of the sequence. In its basic implementation the recurrent approach suffers from the <a href="https://en.wikipedia.org/wiki/Vanishing_gradient_problem#Recurrent_network_model" rel="nofollow noreferrer">vanishing gradient problem</a>. Different approaches was first introduced to mitigate this problem: <a href="https://en.wikipedia.org/wiki/Long_short-term_memory" rel="nofollow noreferrer">LSTM</a>, <a href="https://en.wikipedia.org/wiki/Gated_recurrent_unit" rel="nofollow noreferrer">GRU</a> and other flavors of the same general idea - have a multiplicative weight that learns the relative importance of the context data and controls the flow of information between different steps. &quot;Attention&quot; was just another name given to the similar idea.</p> <p>The &quot;all you need&quot; part of the <a href="https://arxiv.org/abs/1706.03762" rel="nofollow noreferrer">Attention is all you need</a> paper is about dropping the RNN architecture altogether. Quoting the paper: &quot;<em>In this work we propose the Transformer, a model architecture eschewing recurrence and instead relying entirely on an attention mechanism to draw global dependencies between input and output.</em>&quot;</p> <blockquote> <ol start="2"> <li>Did I understand this paper correctly, and indeed other than the LSTM, there are no relationships between the different time stamps</li> </ol> </blockquote> <p>I'd say that yes, you did understand the paper correctly - most of the researchers was relying on the RNN architecture to extract the &quot;interaction&quot; information between different tokens. It looks obvious now, but at that time the transformers paper was revolutionary.</p>
https://ai.stackexchange.com/questions/39891/understanding-self-attention-how-come-there-is-no-connection-between-different
Question: <p>Considering the architecture of encoder and decoder in transformer as shown below: <a href="https://i.sstatic.net/4pAzL.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/4pAzL.png" alt="enter image description here" /></a></p> <ul> <li><strong>Does each input token after self attention mechanism (z1,z2,z3,...)is passed to it's specific separate Feed forward neural network or does all the Z's are stacked into one and then passed to single FFNN?</strong></li> <li><strong>If all the Z's are stacked into one, then how the difference in shapes of different inputs is taken care</strong></li> <li><strong>If every z has its own Feed forward neural network, how in practical it is implemented with arbitrary input length?</strong></li> </ul> Answer: <ul> <li>the z’s are stacked and then passed to a single feed forward layer</li> <li>the difference in shapes of inputs is resolved by padding to the dimension of the model</li> </ul>
https://ai.stackexchange.com/questions/40173/does-number-of-fully-connected-neural-networks-changes-in-transformer-architecht
Question: <p><a href="https://arxiv.org/pdf/1709.01507.pdf" rel="nofollow noreferrer">Squezee-and-excite networks</a> introduced SE blocks, while <a href="https://arxiv.org/pdf/1801.04381.pdf" rel="nofollow noreferrer">MobileNet v2</a> introduced linear bottlenecks.</p> <p>What is the effective difference between these two concepts?</p> <p>Is it only implementation (depth-wise convolution, vs per-channel pooling), or they serve a different purpose?</p> <p>My understanding is that both approaches are used as attention mechanism, working per-channel. In other words, both approaches are used to filter unnecessary information (information that we consider noise, not signal). Is this correct? Do bottlenecks ensure, that the same feature won't be represented multiple times in different channels, or they don't help at all in this regard?</p> Answer:
https://ai.stackexchange.com/questions/14009/what-is-the-difference-between-squeeze-and-excite-and-bottleneck-modules-from-mo
Question: <p>I am learning Computational Neuroscience. If I do reasoning in my mind, especially Classifying an object and Deducing to figure out its qualities, I have to memorize the category and the category's definition, qualities in the past.</p> <p>So what are the Essence and foundations of Memory in ANNs and the Brain? Memories can fade, so memories are not simply the parameters in the ANNs. Are there any Transformers-like parts in our brain, since the attention mechanism is quite an easy way to calculate the similarity between two items?</p> <p>Thank you very much for all your discussions and answers.</p> Answer: <p>I may not be able to fully address your question but I want to provide some comparisons between ANNs and the Brain.</p> <ol> <li><strong>Plasticity.</strong> The brain can adapt/grow/remove its connections among neurons as required. For example, learning a new skill (like playing a new instrument) causes the grow of new connections that you can see as shortcuts between the interested parts of the brain such that to maximize your performance at that task. Instead, ANNs are just static: once the training is completed, the values of the weights are fixed regardless the new experience (or data samples) they are asked to predict.</li> <li><strong>Modularity and multi-modality.</strong> The brain is made of many parts (or modules) which are often interconnected in a very complex way. Moreover, the brain can process multi-modal information like visual, audio, and, e.g., tactile stimuli. In these days, modern ANNs can also exploits multi-modal inputs although still not as good as our brain.</li> <li><strong>Distributed memory.</strong> The brain has specialized areas, like the Hippocampus if I'm not wrong, that handle memory related stuff. Moreover, some argue that the memories are also stored in many different places because the Hippocampus takes a small area within the brain. Also, memories seem to be stored in a sort of &quot;compressed&quot; way such that you retain only the vital information, which can be later &quot;reconstructed&quot; or even &quot;retrieved&quot;. Regarding this point there could be a similarity with (variational) auto-encoders (a kind of ANN), which learns to reconstruct its inputs from a compressed representation. In some applications, the goal is to learn an efficient thus compact representation of the input data.</li> <li><strong>Attention.</strong> Each fraction of second the brain experience tons of data (by its multiple senses), which, most of them, is discarded for the sake of not becoming crazy just in few seconds. In the brain we distinguish between <em>voluntary</em> (top-down) and <em>automatic</em> (bottom-up) types of attention. Basically, in the former case we decide what to attend whereas in the latter case, which is also less understood, there are things that are found to capture our attention (like a sudden movement or change in luminosity/color.) In Transformer-based ANNs you have an attention mechanism that can select which parts of the input to focus more. Also, in general, there are portion of the input that, let's say, capture the attention of (or better said, <em>mislead</em>) the ANN. Personally I find this mechanism in ANNs to be similar to bottom-up attention but, also in this case, this is very little understood.</li> </ol>
https://ai.stackexchange.com/questions/42478/what-is-the-essence-of-memory-of-anns-and-brain
Question: <p>I'm trying to understand how transformer models, such as BERT or GPT, handle negation in sentiment analysis. Specifically, I'm curious about how these models manage to correctly interpret sentences where negation changes the sentiment, such as &quot;The movie is not good.&quot;</p> <p>A simple model using word embeddings + global averaging fails to handle negation properly. Intuitively, for example, if &quot;good&quot; has a positive sentiment score and &quot;bad&quot; has a negative sentiment score, a model might misinterpret &quot;not good&quot; by simply averaging the scores of &quot;not&quot; and &quot;good&quot;.</p> <h3>Example Without Negation</h3> <p>Consider the following sentences with sentiment words:</p> <ul> <li>&quot;The movie is good.&quot;</li> <li>&quot;The movie is awesome.&quot;</li> <li>&quot;The movie is terrible.&quot;</li> </ul> <p>Suppose we have the following word embeddings representing sentiment scores:</p> <ul> <li>&quot;good&quot; = [10]</li> <li>&quot;awesome&quot; = [12]</li> <li>&quot;terrible&quot; = [-10]</li> </ul> <p>Neutral words (assuming embeddings around 0):</p> <ul> <li>&quot;the&quot; = [0]</li> <li>&quot;movie&quot; = [0]</li> <li>&quot;is&quot; = [0]</li> </ul> <p>For these sentences, a simple global average of the sentiment scores works well:</p> <ul> <li>&quot;The movie is good&quot; = average([0, 0, 0, 10]) = 10 / 4 = 2.5 (positive sentiment)</li> <li>&quot;The movie is awesome&quot; = average([0, 0, 0, 12]) = 12 / 4 = 3 (positive sentiment)</li> <li>&quot;The movie is terrible&quot; = average([0, 0, 0, -10]) = -10 / 4 = -2.5 (negative sentiment)</li> </ul> <h3>Example With Negation</h3> <p>Now, consider the sentence &quot;The movie is not good.&quot; In this case, the sentiment should be negative due to the presence of &quot;not.&quot; However, averaging the scores naively might not handle this correctly. For example:</p> <ul> <li>&quot;The movie is not good&quot; = average([0, 0, 0, -5 (for not), 10 (for good)]) = (0 + 0 + 0 - 5 + 10) / 5 = 5 / 5 = 1 (incorrectly positive)</li> <li>&quot;The movie is not bad&quot; = average([0, 0, 0, -5, -9]) = (0 + 0 + 0 - 5 - 9) / 5 = -14 / 5 = -2.8 (incorrectly negative)</li> </ul> <h3>How Transformers Handle Negation</h3> <p>Can someone explain, with a concrete example, how a transformer model like BERT or GPT can correctly understand and model negation in a sentence? Specifically, I'm interested in:</p> <ul> <li>How the self-attention mechanism captures the relationship between words like &quot;not&quot; and &quot;good&quot;.</li> <li>An example with numerical values to illustrate the process.</li> </ul> Answer: <p>To answer this question, it makes sense to go over how multi-headed self attention works. Say we have 2 heads defined as follows (I am leaving small details out for simplicity):</p> <p><span class="math-container">$$W_q^1, W_k^1, \text{ and } W_v^1$$</span></p> <p><span class="math-container">$$W_q^2, W_k^2, \text{ and } W_v^2$$</span></p> <p>where the superscript defines the head number. We also have our token embeddings <span class="math-container">$X$</span>, for our sequence.</p> <ol> <li>We multiply our embedding by each of the previously defined matrices to get our query, key, and value features for each head.</li> </ol> <p><span class="math-container">\begin{align}XW^i_q &amp;= Q^i \\ XW^i_k &amp;= K^i \\ XW^i_v &amp;= V^i\end{align}</span></p> <ol start="2"> <li>We then preform the dot product attention between the key and values of each head</li> </ol> <p><span class="math-container">$$E^i=Q^i K^{i \top}$$</span></p> <ol start="3"> <li>We then apply softmax row-wise to get our attention scores</li> </ol> <p><span class="math-container">$$A^i=softmax(E^i)$$</span></p> <ol start="4"> <li><p>Then, using each row of attention scores, we get the linear combination of the corresponding value vectors in <span class="math-container">$V^i$</span></p> </li> <li><p>Then, to combine the outputs from each head, we concatenate or average the head outputs.</p> </li> <li><p>Finally, we throw these vectors into a linear layer, so that our final representation can encapsulate all the nuance that exists in the outputs from the two heads.</p> </li> </ol> <p><span class="math-container">$\textbf{The answer to your first question specifically pertains to the fourth step.}$</span> In that the attention scores that we created encapsulate the relationships between words, our value vectors hold the meaning to the words, and our linear combination creates a representation, from these aforementioned components that encapsulates the negation of some word. The ability of any transformer-based architecture, with appropriate regularization, to do this increases as we stack these multi-headed attention blocks on top of each other.</p>
https://ai.stackexchange.com/questions/46067/how-do-transformer-models-handle-negation-in-sentiment-analysis
Question: <p>In Transformer models, token embeddings are combined with positional encodings through element-wise addition to incorporate positional information. However, this raises a concern about the potential for different tokens in different positions to end up with identical embeddings.</p> <p>For example, consider the following:</p> <ul> <li>Embedding of token <span class="math-container">$A$</span>: <span class="math-container">$[0.5, 0]$</span></li> <li>Positional encoding at position <span class="math-container">$1$</span>: <span class="math-container">$[1, 0]$</span></li> <li>Combined representation for token <span class="math-container">$A$</span> at position <span class="math-container">$1$</span>: <span class="math-container">$[0.5 + 1, 0 + 0] = [1.5, 0]$</span></li> <li>Embedding of token <span class="math-container">$B$</span>: <span class="math-container">$[1, 0]$</span></li> <li>Positional encoding at position <span class="math-container">$2$</span>: <span class="math-container">$[0.5, 0]$</span></li> <li>Combined representation for token <span class="math-container">$B$</span> at position <span class="math-container">$2$</span>: <span class="math-container">$[1 + 0.5, 0 + 0] = [1.5, 0]$</span></li> </ul> <p>In this case, the combined representations for different tokens at different positions are the same.</p> <p>Given that positional encodings are added element-wise to token embeddings, how do Transformer models ensure the uniqueness of token representations to prevent different token-position combinations from resulting in the same embedding vector? Specifically, how do they handle cases where different embeddings and positional encodings could potentially sum to the same vector?</p> Answer: <p>Positional Encoding (PE) is a broad term encompassing various techniques meant to embed positional information within a matrix <span class="math-container">$x \in \mathbb{R}^{S \times d_{\text{model}}}$</span>, where <span class="math-container">$S$</span> is the number of tokens, and <span class="math-container">$d_{\text{model}}$</span> is the size of each token. Assuming you are referring to the PE defined in &quot;Attention is all you need&quot; (<a href="https://arxiv.org/pdf/1706.03762" rel="nofollow noreferrer">Vaswani et al., 2017</a>), then you have: <span class="math-container">$$\operatorname{PE}(p,2i) = \sin\left( \frac{p}{10,000^{\frac{2i}{d_{\text{model}}}}}\right)$$</span> <span class="math-container">$$\operatorname{PE}(p,2i+1) = \cos\left( \frac{p}{10,000^{\frac{2i}{d_{\text{model}}}}}\right)$$</span> where <span class="math-container">$d_{\text{model}}$</span> is the size of the embedding vector, <span class="math-container">$p$</span> is the position of the (token) embedding in the sequence, and <span class="math-container">$i$</span> is the feature index in the embedding space. As you can see, <span class="math-container">$\operatorname{PE}$</span> <strong>is not a function of the embeddings</strong>, but rather a determinsitc function of the position <span class="math-container">$p$</span> and the feature index <span class="math-container">$i$</span>. This means that <strong>PE is the same across all input sequences</strong>.</p> <p>This is also the reason why in many practical implementation, like <a href="https://pytorch.org/tutorials/beginner/translation_transformer.html" rel="nofollow noreferrer">here</a>, PE is computed only once. Specifically, the PEs are precomputed for a fixed maximum sequence length and stored in a tensor. When an input sequence <span class="math-container">$x$</span> is processed, the corresponding PEs are sliced from this precomputed tensor (to match the dimensions) and added to <span class="math-container">$x$</span>.</p> <p>Therefore, back to your example, if your sequence is <span class="math-container">$$ \begin{bmatrix} A \\ B\\ \end{bmatrix} = \begin{bmatrix} 0.5 &amp; 0.0 \\ 1.0 &amp; 0.0 \\ \end{bmatrix} $$</span> you have <span class="math-container">$d_{\text{model}} = 2$</span> and <span class="math-container">$p, i \in \{0, 1\}$</span>. First, compute the PEs: <span class="math-container">\begin{align} \operatorname{PE}(0,0) &amp;= \sin\left( \frac{0}{10,000^{\frac{0}{2}}} \right) = \sin\left( 0 \right) = 0 \\ \operatorname{PE}(0,1) &amp;= \cos\left( \frac{0}{10,000^{\frac{0}{2}}} \right) = \cos\left( 0 \right) = 1 \\ \operatorname{PE}(1,0) &amp;= \sin\left( \frac{1}{10,000^{\frac{0}{2}}} \right) = \sin(1) \approx 0.8415 \\ \operatorname{PE}(1,1) &amp;= \cos\left( \frac{1}{10,000^{\frac{0}{2}}} \right) = \cos(1) \approx 0.5403 \end{align}</span></p> <p>This results in the PE tensor: <span class="math-container">$$ \operatorname{PE} = \begin{bmatrix} 0.0000 &amp; 1.0000\\ 0.8415 &amp; 0.5403\\ \end{bmatrix} $$</span> which will be the same for all input sequences. Your input sequence is then transformed as follows: <span class="math-container">$$ x' = x + \operatorname{PE} = \begin{bmatrix} 0.5 &amp; 0.0 \\ 1.0 &amp; 0.0 \\ \end{bmatrix} + \begin{bmatrix} 0.0000 &amp; 1.0000\\ 0.8415 &amp; 0.5403\\ \end{bmatrix} = \begin{bmatrix} 0.5000 &amp; 1.0000\\ 1.8415 &amp; 0.5403\\ \end{bmatrix} $$</span></p> <p>Notably, each PE is <strong>unique</strong> for each position within an input sequence. Consequently, if two distinct tokens within the same input sequence, denoted as <span class="math-container">$x_p$</span> and <span class="math-container">$x_q$</span>, yield identical embeddings after the application of their respective PEs: <span class="math-container">$$ x_p + \operatorname{PE}(p) = x_q + \operatorname{PE}(q)$$</span> several implications arise. First, the occurrence of such an event is highly improbable, given that <span class="math-container">$\operatorname{PE}(p) \neq \operatorname{PE}(q)$</span>. Second, even if this rare event occurs, the model is capable of distinguishing between the tokens based on their positional contexts. Since <span class="math-container">$\operatorname{PE}(p) \neq \operatorname{PE}(q)$</span>, then also <span class="math-container">$x_p \neq x_q$</span> (the embeddings are different). Thus, the information encoded by <span class="math-container">$x_p$</span> and <span class="math-container">$x_q$</span> are different, even though the final embeddings are the same.</p>
https://ai.stackexchange.com/questions/46205/how-do-transformer-models-ensure-unique-token-representations-when-combining-emb
Question: <p>Regarding the use of pre-processing techniques before using Transformers models, I read <a href="https://stackoverflow.com/a/63986348/13745968">this post</a> that apparently says that these measures are not so necessary nor interfere so much in the final result.</p> <p>The arguments raised seemed to me quite convincing, but someone would know how to explain better, perhaps with a bibliographic reference, why is it not so necessary to use these techniques?</p> Answer:
https://ai.stackexchange.com/questions/27009/why-not-using-pre-processing-before-using-transformer-models
Question: <p>I've watched the outstanding Andrej Karpathy's <a href="https://www.youtube.com/watch?v=VMj-3S1tku0&amp;list=PLAqhIrjkxbuWI23v9cThsA9GvCAUhRvKZ&amp;index=1&amp;t=0s" rel="nofollow noreferrer">From Zero to Hero course</a>. In the last lecture, he introduces Transformer decoder architecture, which is able to produce Shakespear-like text. However, there was no direct comparison of the achieved cross-entropy loss (~1.4) with simple MLP models he talked about in the first 5 lectures.</p> <p>What if one trains an MLP based model with a similar number of parameters/layers, the same context length and also including layer normalization, feed forward and dropout, would the result be substantially worse? Would the training take longer? Are there direct comparisons like that in the literature?</p> Answer: <p>I can't provide you with numbers and results, but I'd expect (for not triavial problems) the MLP-based model to be worse than a Transformer.</p> <p>The reason is that transformers are designed to handle sequences, whereas MLP are not (even if you flatten the entire sequence into a vector). Trasformers can leverage an <strong>inductive bias</strong> specifically designed for sequences (likewise CNNs for images), which should account for a better learning, at least, even in case of similar number of parameters and regularization.</p> <p>Thanks to <em>self-attention</em> transformers are able to learn to focus on relevant parts of the sequence, even far in time, whereas simple MLPs cannot do this. Moreover, <em>positional encoding</em> provides the transformer to use the sequence order information, enabling it to learn to attend even to relative positions. Instead, MLPs just combine information from all the vectors' components.</p>
https://ai.stackexchange.com/questions/40686/are-transformer-models-better-than-comparable-complexity-mlp-based-models
Question: <p>In <a href="https://proceedings.neurips.cc/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf" rel="nofollow noreferrer">Attention Is All You Need</a> paper:</p> <blockquote> <p>That is, the output of each sub-layer is <span class="math-container">$LayerNorm(x+Sublayer(x))$</span>, where <span class="math-container">$Sublayer(x)$</span> is the function implemented by the sub-layer itself. We apply dropout to the output of each sub-layer, before it is added to the sub-layer input and normalized.</p> </blockquote> <p>which makes the final formula <span class="math-container">$LayerNorm(x+Dropout(Sublayer(x)))$</span>. However, in <a href="https://github.com/tensorflow/models/blob/0effd158ae1e6403c6048410f79b779bdf344d7d/official/transformer/model/transformer.py#L278-L288" rel="nofollow noreferrer">https://github.com/tensorflow/models/blob/0effd158ae1e6403c6048410f79b779bdf344d7d/official/transformer/model/transformer.py#L278-L288</a>, I see</p> <pre><code>def __call__(self, x, *args, **kwargs): # Preprocessing: apply layer normalization y = self.layer_norm(x) # Get layer output y = self.layer(y, *args, **kwargs) # Postprocessing: apply dropout and residual connection if self.train: y = tf.nn.dropout(y, 1 - self.postprocess_dropout) return x + y </code></pre> <p>which ends up as <span class="math-container">$x+Dropout(Sublayer(LayerNorm(x)))$</span>. Plus there are extra <code>LayerNorm</code>s as final layers in both encoder and decoder stacks.</p> <p>In a quick test, the performance of this model seems to be better than if I change back to the paper's order of operations. My question is: why? And could it be predicted in advance?</p> <p>I note that <a href="https://arxiv.org/pdf/1904.10509.pdf" rel="nofollow noreferrer">Generating Long Sequences with Sparse Transformers</a> uses the <span class="math-container">$x+Dropout(Sublayer(LayerNorm(x)))$</span> order, but doesn't discuss it, unlike the other changes it makes to Transformer.</p> Answer:
https://ai.stackexchange.com/questions/16835/where-should-we-place-layer-normalization-in-a-transformer-model
Question: <p>In the transformer model, to incorporate positional information of texts, the researchers have added a positional encoding to the model. <em>How does positional encoding work? How does the positional encoding system learn the positions when varying lengths and types of text are passed at different time intervals?</em></p> <p>To be more concrete, let's take these two sentences.</p> <ol> <li>&quot;She is my queen&quot;</li> <li>&quot;Elizabeth is the queen of England&quot;</li> </ol> <p>How would these sentences be passed to the transformer? What would happen to them during the positional encoding part?</p> <p>Please explain with less math and with more intuition behind it.</p> Answer:
https://ai.stackexchange.com/questions/18437/how-does-positional-encoding-work-in-the-transformer-model
Question: <p>I am trying to make a model that uses a <em>Transformer</em> to see the relationship between several data vectors, but the order of the data is not relevant in this case, so I am not using the <em>Positional Encoding</em>.</p> <p>Since the performance of models using Transformers is quite improved with the use of this part, do you think that if I remove that part I am breaking the potential of Transformers or is it correct to do so?</p> Answer: <p>Positional Encodings in Transformers exist to give the model some information about the position of the embedding. This makes sense in fields like NLP or Time Series Data, since the position(order) matters in this case.</p> <p>However, since you say that order of the data is not relevant in your use case, positional encoding would not be necessary.</p>
https://ai.stackexchange.com/questions/32396/is-positional-encoding-always-needed-for-using-transformer-models-correctly
Question: <p>I understand that all inputs in a batch need to be of the same size. However, it seems BERT/Transformers models can accept batches with different sizes as input.</p> <p>How is that possible? I thought we needed to pad all examples in a batch to <code>model.max_input_size</code>, however, it seems HuggingFace does <code>Dynamic Padding</code> that allows sending batches of different lengths (till the time they are smaller than <code>max_input_size</code>)</p> <p><a href="https://i.sstatic.net/zC1WS.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/zC1WS.png" alt="enter image description here" /></a></p> <p>Link: <a href="https://mccormickml.com/2020/07/29/smart-batching-tutorial/" rel="nofollow noreferrer">https://mccormickml.com/2020/07/29/smart-batching-tutorial/</a><br /> Link2: <a href="https://huggingface.co/learn/nlp-course/en/chapter3/2?fw=pt#dynamic-padding" rel="nofollow noreferrer">https://huggingface.co/learn/nlp-course/en/chapter3/2?fw=pt#dynamic-padding</a></p> Answer: <p>The reason why you want to pad at all is because you want to stuff everything into giant matrix multiplies. GPUs are great at parallelizing these operations. Instead of running e.g., <span class="math-container">$Wx_i + b$</span> 32 times, you can run <span class="math-container">$W X + b$</span> a single time, where each column of <span class="math-container">$X$</span> is a single input.</p> <p>So, if you have inputs with different input lengths, you just need to add enough padding such that you can fit all your <span class="math-container">$x_i$</span>s into a single matrix <span class="math-container">$X$</span>. That is, you only need to pad to the maximum length item in your batch.</p> <p>The padding tokens are also masked, so that tokens can't attend to them and they don't contribute to the loss. Because of this, adding any additional padding tokens wouldn't really do anything.</p>
https://ai.stackexchange.com/questions/41858/how-can-bert-transformer-models-accept-input-batches-of-different-sizes
Question: <p>I'm currently studying the Transformer model (<strong>Attention is all you need</strong>) and after reading it I still have some questions for which I get conflicting answers if I google them:</p> <ul> <li>What exactly are the dimensions of the input to the encoder of a transformer, from what I've seen you can input sentences with dynamic lengths but in the paper it seems like all layers expect the K/Q/V matrices to have dimensions of <code>d_model, d_k</code> or <code>d_v/d_q</code></li> <li>Same question for the decoder, what exactly are the input dimensions and how do the attention layers handle dynamic dimensions if its possible</li> <li>Another question is is masking only used for training where you input the whole sentence as the input to the decoder or does it have another purpose than that (especially in inference)</li> </ul> Answer: <p>Transformer networks are great, because they can handle variable length inputs, but they also have limitations, concerning the input size. For example BERT (a transformer based language model) only accepts <span class="math-container">$N = 512$</span> input tokens at most. They way transformer models can accept sequences shorter than the <span class="math-container">$N$</span>, is by padding the input sequence with zeros and masking. When inputting a sequence with length <span class="math-container">$n \leq N$</span>, the mask <span class="math-container">$m$</span> is a vector of size <span class="math-container">$N$</span>, where <span class="math-container">$m_i = (i \leq n)$</span>. Say we have a transformer that should translate from English to German which accepts <span class="math-container">$N = 8$</span> tokens at most, and we input the sentence &quot;Today is Tuesday&quot;. Let the words have the following token values:</p> <p><span class="math-container">\begin{array} {|r|r|} \hline \text{[SOS]} &amp; 1 \\ \hline \text{Today} &amp; 274 \\ \hline \text{is} &amp; 12 \\ \hline \text{Tuesday} &amp; 125 \\ \hline \text{[EOS]} &amp; 2 \\ \hline \end{array}</span></p> <p>The first input will always be occupied by the [SOS] token and each sequence is followed by an [EOS] token. Now the input looks like this:</p> <p><span class="math-container">\begin{bmatrix}1\\274\\12\\125\\2\\0\\0\\0\end{bmatrix}</span></p> <p>And you also supply an attention mask (using integers representing booleans) which looks like this:</p> <p><span class="math-container">\begin{bmatrix}1\\1\\1\\1\\1\\0\\0\\0\end{bmatrix}</span></p> <p>This means, each position can only attend to positions <span class="math-container">$i$</span> where <span class="math-container">$m_i = 1$</span>. Therefore, positions where the mask is 0, do not affect the output of the model.</p> <p>The vector representation of the mask above is the simplified version of the actual attention mask, describing that position at row <span class="math-container">$i$</span> can attend to positions at column <span class="math-container">$j$</span>:</p> <p><span class="math-container">\begin{bmatrix}1&amp;1&amp;1&amp;1&amp;1&amp;0&amp;0&amp;0\\1&amp;1&amp;1&amp;1&amp;1&amp;0&amp;0&amp;0\\1&amp;1&amp;1&amp;1&amp;1&amp;0&amp;0&amp;0\\1&amp;1&amp;1&amp;1&amp;1&amp;0&amp;0&amp;0\\1&amp;1&amp;1&amp;1&amp;1&amp;0&amp;0&amp;0\\0&amp;0&amp;0&amp;0&amp;0&amp;0&amp;0&amp;0\\0&amp;0&amp;0&amp;0&amp;0&amp;0&amp;0&amp;0\\0&amp;0&amp;0&amp;0&amp;0&amp;0&amp;0&amp;0\end{bmatrix}</span></p> <p>The decoder works a bit differently during training and inference.</p> <p><strong>Training:</strong> The decoder attention mask is built, so that each position can not attend to future positions. You can describe this by using a matrix:</p> <p><span class="math-container">\begin{bmatrix}1&amp;0&amp;0&amp;0&amp;0&amp;0&amp;0&amp;0\\1&amp;1&amp;0&amp;0&amp;0&amp;0&amp;0&amp;0\\1&amp;1&amp;1&amp;0&amp;0&amp;0&amp;0&amp;0\\1&amp;1&amp;1&amp;1&amp;0&amp;0&amp;0&amp;0\\1&amp;1&amp;1&amp;1&amp;1&amp;0&amp;0&amp;0\\1&amp;1&amp;1&amp;1&amp;1&amp;1&amp;0&amp;0\\1&amp;1&amp;1&amp;1&amp;1&amp;1&amp;1&amp;0\\1&amp;1&amp;1&amp;1&amp;1&amp;1&amp;1&amp;1\end{bmatrix}</span></p> <p>When using this mask for the decoder, position <span class="math-container">$i$</span> can only attend to positions <span class="math-container">$j, j \leq i$</span>. For the task of translation from English to German (e.g. &quot;Today is Tuesday&quot; -&gt; &quot;Heute ist Dienstag&quot;), you can provide the model with the entire input sentence and the entire output sentence. The model will make a prediction for each decoder input position, what the next word will be. And by using the mask, no information leaks into earlier positions (when predicting the next token for the word &quot;ist&quot;, the model can only see &quot;[SOS] Heute ist&quot;).</p> <p><strong>Inference:</strong> For the inference stage, you would first provide the input sentence for the encoder and for the decoder only the [SOS] token. Now you sample a word from the transformer output (e.g. picking the most likely or sample from the output distribution) at the position of your last decoder input (in this case the position of the [SOS] token, e.g. position 0). Then you do the next inference step, by again providing the input sentence for the encoder, and for the decoder you provide the [SOS] token + the predicted word from the last step. If the previous prediction was &quot;Heute&quot;, your decoder input now is &quot;[SOS] Heute&quot;. You just repeat this process, each time providing the so far predicted sentence to the decoder, until the transformer predicts [EOS].</p>
https://ai.stackexchange.com/questions/34760/dimensions-of-a-transformer-model-and-purpose-of-masking
Question: <p>I am not technically familiar with AI or neural networks beyond a tech news reading level of knowledge, so I apologise if this is a dumb question.</p> <p>I was recently reading <a href="https://arstechnica.com/gadgets/2023/01/the-generative-ai-revolution-has-begun-how-did-we-get-here/3/" rel="nofollow noreferrer">this article</a> on <a href="https://www.arstechnica.com" rel="nofollow noreferrer">Ars Technica</a>. It is a high level description of the history of generative AI models (it's a very good article, highly recommended).</p> <p>When discussing large language models, the following passage appears:</p> <blockquote> <p>But there was also a surprise. The OpenAI researchers discovered that in making the models bigger, they didn’t just get better at producing text. The models could learn entirely new behaviors simply by being shown new training data. In particular, <strong>the researchers discovered that GPT3 could be trained to follow instructions in plain English without having to explicitly design the model that way.</strong> (emphasis added)</p> </blockquote> <p>I have three questions:</p> <ol> <li><p>Was this instruction-following behaviour truly emergent, as in completely unexpected and unplanned for?</p> </li> <li><p>This seems completely at odds with the usual description of transformer models as transforming text of one kind into another. Following instructions seems, at a conceptual level, to be something much higher? If this is the case, do we have any idea how this emerged, and what properties of the model it is rooted in?</p> </li> <li><p>Do we have any idea how wide the scope of this kind of &quot;instruction following&quot; is? I.e. can the models make sense and respond &quot;sensibly&quot; (not correctly - I am not concerned with the correctness of the response, but with its relation to the instruction) to <em>any</em> instruction related to text? Or are there specific kinds of instructions they are able to comprehend, and others they fail at?</p> </li> </ol> Answer:
https://ai.stackexchange.com/questions/38973/following-instructions-as-an-emergent-behaviour-in-transformer-models-isnt
Question: <p>So I was experimenting with the Llama and Mistral models, and using &quot;talk like a viking&quot; in the system prompt caused the model to resemble a viking or similar. How they know that? This was on a instruct version of these models. Here is a example output from Hugging Face spaces, when I asked about the planets being renamed into colors:</p> <pre><code>OHOHOHO! Listen up, me hearty! If we were to name the planets after colors, here's what they'd be called, savvy? 1. Earth - Green, for the lush forests and rolling hills. 2. Mars - Red, for the rusty soil and barren landscape. 3. Venus - Pink, for the thick atmosphere and swelterin' heat. 4. Mercury - Silver, for the metallic sheen and scorching temperatures. 5. Jupiter - Purple, for the swirlin' storm clouds and gaseous composition. 6. Saturn - Gold, for the shimmerin' rings and ancient wisdom. 7. Uranus - Blue, for the distant skies and mystical allure. 8. Neptune - Teal, for the deep oceans and misty atmosphere. So hoist the colors, me hearties, and let's set sail for the cosmos! YARRR! </code></pre> Answer: <p>The ability of models like Llama and Mistral to &quot;talk like a Viking&quot; when prompted with phrases like &quot;talk like a viking&quot; stems from the transformer's self-attention training process, where they <em>implicitly</em> learn patterns in the data including various styles and tones using their pretrained parameters from a diverse corpus of text including not only formal languages but also a wide variety of regional dialects, historical figures, and styles like that of Vikings.</p> <p>The &quot;instruct&quot; versions of these foundational models are further fine-tuned on task-specific instructions such as your Q&amp;A task, where they learn to follow prompts that specify a certain style or tone. This means that when you tell the model to &quot;talk like a viking,&quot; it adjusts its output to fit a tone that aligns with that style, even if it's not directly historical Viking speech. And one critical factor for a semantically-coherent and style-consistent autoregressive output of the models is your prompt input's context-aware embeddings transformation by the self-attention modules to predict the next token at each step during their inference time.</p>
https://ai.stackexchange.com/questions/47813/how-transformer-models-can-imitate-characters
Question: <p>I have some questions about using (encoder / decoder / encoder-decoder) transformer models, included (language) transformer or Vision transformer.</p> <p>The overall form of a transformer consists of an encoder and a decoder. Depending on the model, you may use only the encoder, only the decoder, or both. However, for what purpose do model designers use only encoders, only decoders, or both?</p> <p>I already knew that encoders in transformers are as known as taking in a sequence of input data and generates a fixed-length representation of it. This representation can then be fed into the decoder to generate an output sequence. In other words, the encoder can be thought of as a kind of compression that extracts features from the data. And the decoder can be thought of as playing a role in returning the compressed information in the encoder to its original state. So I'm wondering why some models work without having both an encoder and a decoder.</p> <p>Few days ago, I think use only encoders are useful to classifying classes. Because <strong>DOSOVITSKIY, Alexey, et al. An image is worth 16x16 words: Transformers for image recognition at scale. arXiv preprint arXiv:2010.11929, 2020.</strong> paper shows only encoder to classification images. Decoders are useful in generative things, because <strong>WANG, Jianfeng, et al. Git: A generative image-to-text transformer for vision and language. arXiv preprint arXiv:2205.14100, 2022.</strong> paper using encoder to encode the visual information from the input image into a representation that can be used by the text decoder to generate text. Then, to generate text, they give the 'encoder's output and the text' as the decoder's input.</p> <p>But, I am sure about that my think are wrong because of BERT and GPT. <strong>BERT</strong> using encoder and does not have a decoder. <strong>GPT</strong> uses decoder and does not have a encoder. A typical user thinks that BERT and GPT equally answer the question asked by the user. So they think BERT and GPT provide the same service. However, in terms of model structure, BERT and GPT are completely different.</p> <h1>So, I have two questions about each functional part that makes up the transformer.</h1> <ol> <li>what does encoder and decoder do in transformer? The transformer referred to here can be text or image.</li> <li>For what purpose do model designers use only encoders, only decoders, or both encoders and decoders?</li> </ol> <p>Thank you.</p> Answer: <p>The <a href="https://arxiv.org/abs/1706.03762" rel="noreferrer">original transformer paper</a> presents the transformer as a model consisting of both encoder and decoder. However, many times you will see (or hear) people describing their model as a &quot;transformer model&quot;, but it actually consists only of an encoder or only of a decoder. That's fine as long as you know what exactly is going on. (I would say that the distinctive feature of the transformer model is the <a href="https://pi-tau.github.io/posts/transformer/#attention" rel="noreferrer">attention layer</a>.)</p> <p>For example, as you mentioned, <strong>G</strong>enerative <strong>P</strong>retrained <strong>Transformer</strong> (GPT) is a decoder-only model, and <strong>Vi</strong>sion <strong>Transformer</strong> (ViT) is an encoder-only model.</p> <p>I feel like your question already contains the answer :) Yes, encoders are used exactly for that - encoding (or compressing) the input. Note that the output sequence from the encoder has the same length as the input sequence. This is why encoder-only models cannot be used for tasks where the output sequence has a different length or unknown length, e.g. machine translation, text summarization. In these cases you need the decoder.</p> <p>Encoder-only models like ViT and BERT will encode the input sequence and produce an output sequence of the same length. Then for classification they will use only the first element of the output sequence.</p> <p><a href="https://i.sstatic.net/N0vDZ.png" rel="noreferrer"><img src="https://i.sstatic.net/N0vDZ.png" alt="Vision Transformer" /></a></p> <p>As I said, encoder-only models cannot be used for generating an output sequence of different (or unknown) length, i.e. BERT cannot be used for machine translation or generative question answering. BERT can only be used for question answering on <a href="https://rajpurkar.github.io/SQuAD-explorer/" rel="noreferrer">SQuAD</a>-type datasets, i.e. your answer is a continuous segment from the input and the model only outputs <code>&lt;START_IDX&gt;</code> and <code>&lt;END_IDX&gt;</code> to mark it.</p> <p>For generation tasks you need a decoder. The decoder is actually an auto-regressive model. It will generate the elements of the output sequence one-by-one until it decides that the sequence is ready and then it generates the final <code>&lt;END&gt;</code> token. See <a href="https://pi-tau.github.io/posts/transformer/#inference" rel="noreferrer">here</a>.</p> <p>Previously people used an encoder-decoder architecture to solve these sequence-to-sequence tasks (e.g. <a href="https://arxiv.org/pdf/1910.10683.pdf" rel="noreferrer">T5</a>). You want the encoder to encode your input sequence and the decoder to decode it and produce the output sequence. However, it turns out that you can use a decoder-only model. You simply concatenate your source and target sentences and treat the task as a language modelling task. Now there are pros and cons to this approach, but the main takeaway is that you can do it if you want to.</p> <p>You can checkout these papers to read more about encoder-decoder vs decoder-only models for sequence to sequence tasks:<br /> <a href="https://arxiv.org/pdf/2304.04052.pdf" rel="noreferrer">https://arxiv.org/pdf/2304.04052.pdf</a><br /> <a href="https://aclanthology.org/2022.aacl-main.43.pdf" rel="noreferrer">https://aclanthology.org/2022.aacl-main.43.pdf</a></p>
https://ai.stackexchange.com/questions/41505/which-situation-will-helpful-using-encoder-or-decoder-or-both-in-transformer-mod