Transformer's Encoder with Self-Attention layers

Thank you a lot for a prompt response @treo .
It’s actually quite difficult for me to perceive that dimension structure because in the examples of self-attention mechanism I found online I saw only the dimensions of [numberOfWordsInSequence, wordEmbeddingSize]. Seems like in the current situation, because I fetch the embedding from a lookup table and automatically get the matrix of the shape [numberOfWordsInSequence, wordEmbeddingSize] I have to use INDArray’s permute() method in order to create the shape which SelfAttentionLayer expects, am I right ?
One more thing, I’ve tried running the fit() for the model which uses a SelfAttentionLayer and noticed that it’s doesn’t use concurrency (which makes it quite slow). Is it possible to somehow configure the model to run in parallel? Or could it be that I’ve missed that configuration option?

I guess that the examples were not for DL4J.

As you can see in the javadoc for SelfAttentionLayer:

and in

It explicitly tells you what kind of input shape it expects.

Actually an expandDims to get the leading 1 and then permute to get it in the order that you want.

How concurrent exactly it runs depends on the data size you put into it. But due to the way it necessarily needs to work it is somewhat slow. There is little you can do about it other than getting more powerful hardware.

Thanks again for the quick response.

Actually I’m running the training of the model on my CPU und only 1 out of 8 CPU cores is being used for the calculations. When I used some of the reinforcement models or SkipGram in Word2vec, the CPU load was more than 50%. That’s why I was curious, if I used a wrong config for SelfAttentionLayer model. If I understand it correctly, the more batch size and sequence length I use for those calculations - the more concurrent CPU resources the calculations will take? I took a look into and but couldn’t figure out, if that’s the case

Attention on its own is mostly a series of matrix multiplications with a softmax in-between.

Because of this, all of the concurrency comes from the BLAS library deciding that it is reasonable to use more than one core. When you feed it with not enough data, then it will not do so.

Perfect. Thanks a lot for the info!
One more question - While taking a look at the gradients after fitting the model I noticed that the matrices Wo and Wv have the gradients calculated, but Wk and Wq don’t. Is it a correct behavior or a wrong configuration? Or should I use LearnedSelfAttentionLayer in order to get the back-propagation to at least Wq ?

Gradients should be propagated to all weights. However, depending on how you are looking at it, it might look like the gradient is exactly zero in cases where it is just very small.

Ok, thanks. I’ll try changing the learning rate to see if the gradients for those 2 matrices are not really zeros.

Tested it with a higher learning rate. Gradients are really there, thanks a lot for the help! Now I’ll try to adjust the labels to see if the learning itself works with my config…

Sorry @treo for disturbing again, but I tried my config out and I get really weird results. After adapting my input data and labels (which are one-hot arrays based on vocab size and are used at the same time as label masks) after feeding the network (which is a simple single Transformer’s encoder) with a sequence of words I get the Softmax output which is the same for each word. Most probably I’m doing something wrong but for now I can’t identify the cause. My network config:

new NeuralNetConfiguration.Builder()
                .updater(new Adam(1e-3))
                .layer(new SelfAttentionLayer.Builder().nOut(embeddingSize).nHeads(5).nIn(embeddingSize)
                .layer(new DenseLayer.Builder().nIn(embeddingSize).nOut(embeddingSize).activation(Activation.RELU)
                .layer(new OutputLayer.Builder().nOut(vocab.size()).activation(Activation.SOFTMAX)

As the output I expect the shape [batchSize * sequenceLength, vocab.size()]. So if I input only one sentence (sequence), I expect to get the Softmax distribution for each word within a vocabulary. But when I take a look at this distribution for each word in the sequence - it’s always the same, e.g. second word in the vocab - which is not expected because embeddings for each word are unique. Would be great to know what I’m missing here.

I’m wondering how your config even works.

The SelfAttentionLayer takes input of the shape [batchSize, nIn, timesteps] and produces an output in the shape of [batchSize, nOut, timesteps].

If I remember correctly, feeding a timeseries type input into a Dense Layer then uses just its last timestep.

So your total network output has the shape [batchSize, outputSize].

And then you have a mean square error loss function, which doesn’t make a lot of sense together with a softmax activation.

I’m confused how exactly you are even getting to your result.

If you had used an RNN output layer without the DenseLayer in the middle, that would have made some more sense, and you would have gotten a result with the proper shape of [batchSize, outputSize, timesteps].

That was my guess as well. Because there’s no explicit Transformer’s example in DL4J, I tried to do something resembling based on existing unit tests but seems like I failed.

Actually there’s a RnnToFeedForwardPreProcessor which reshapes the output without any loss. But today I realized it makes no sense to use that workflow because the prediction needs to be based on the whole sequence, not separate words. So I replaced the last dense layer with a GlobalPoolingLayer and PoolingType.AVG. I need to use Dense layers because they are the part of a standard transformer’s encoder (I’m still struggling to add the residual connections and layer normalization).

Thanks a lot for pointing that. I did use it primarily but because I misinterpreted the core meaning of having a pooling layer, I decided to use label masks and LossFunction.MCXENT doesn’t allow them to be used.

As far as I understand, Pooling layer does the job of generalizing the timeSteps output, thus in my case catching the representation of the whole sentence (sequence). Adding additional positional encoding should take care of bidirectional context relationships.

After applying the pooling layer and MCXENT loss function I finally started getting at least partially acceptable predictions. Thanks a lot @treo !!!

Now I plan to shape this model based on the architecture, similar to BERT, use BertWordPieceTokenizer in order to get the vocab with an acceptable size and start training this model on the real world data. Hopefully I get no blockers while trying to build the final model.

You might want to create your own SameDiffLayer and build the transformer units that way. I guess, it will be easier that way.

See for an example of how it can be used.

Ok. Thanks for an advice!

I decided to stick to your advice @treo and implemented my own SameDiffLayer which would basically represent a single transformer’s encoder (attention layer + dense layer + normalization). Unfortunately I got stuck with 2 issues:

  1. In order to feed forward the attention layer results into the dense layer (in my case I wanted to use sameDiff.nn.reluLayer() ) I need to reshape the RNN format into FFN, but using directly a RnnToFeedForwardPreProcessor is not an option because the latter works with INDArrays, not SDVariables. Also direct reshaping didn’t work because in public SDVariable defineLayer() method, where my new logic resides, it’s impossible to get the access to the batchSize in SDVariable layerInput (makes sense, because it’s not yet there) and I couldn’t find any workarounds (e.g. some lazy-like retrieval of batchSize from layerInput )
  2. At some point I’m gonna need the second optional output of MultiHeadDotProductAttention - attention weights. I tried to retrieve them as INDArray inside my SameDiffLayer implementation but because it’s an ARRAY - I can’t fetch it directly from outside. Thought of using SameDiffLayer.getLayerParams() but I’m not sure it’s gonna give me exactly the weights which I need (I wanted the info structure which is described on the page 13 of original paper: )

I can workaround the first issue by using existing SelfAttentionLayer and adding after it the DenseLayer and then normalization into the model’s layer ListBuilder (it will be most probably less efficient than having own SameDiffLayer combining it all at once) but it won’t help me anyway in resolving the issue #2 (I need those attention weights for the further linguistical analysis)

A dense layer is just y=f(Wx+b), so you can also just apply that calculation instead of using a predefined layer that expects a specific input shape.

And while you can’t reshape because you don’t have access to the actual shape, you can still permute, expandDims and squeeze.

In that case your best bet is to define your entire network with just SameDiff. That gives you more options of recovering any optional output.

The DL4J Layer system is a bit of a straight jacket as it forces you into a certain way of working, and optional outputs aren’t a part of that.

I guess you man an element-wise multiplication in this case? I also though of that at some time but wasn’t sure if that’s the right solution so I decided it would be efficient to reuse already existing one.

I actually tried to do that - like e.g. using for each encoder layer a unique set of params (all self-attention layer params + dense layer weights) and packing that all into one custom SameDiffLayer. I thought that would automatically eliminate the problem of the vanishing gradient (it’s basically the same layer) plus increase the performance due to the fact that all the feed-forward and back-propagation operations would then be executed inside the same graph (SameDiffLayer). But the resulting performance of that layer was almost 10 times slower than in case of simply using separate layers one by one inside the model. Seems like I lack some important knowledge of the internals of SameDiff workflow and memory management in order to resolve that issue.

That it is still a matrix multiplication, but you are using the same matrix for each timestep and no recurrence.

That I suggested and what you’re suggesting here are two different things.

What I’m talking about looks like this in practice:

The gradient doesn’t necessarily care about layers. It “vanishes” when it needs to go through too many steps (i.e. it is multiplied with a value <1.0 at each step, and if you do that often enough it is effectively gone; that’s why RNN’s don’t work that well beyond a certain length).

This too doesn’t quite work that way.

It depends on what you are actually doing, in principle you should have the exactly same speed – that is if you are using the most recent version. In previous versions, not all of SameDiff was GPU accelerated.

Thanks a lot for these tips @treo ! I’ll take a look at that example you provided to figure out how I could implement what I need. Hopefully I also get some more knowledge regarding SameDiffLayers workflow from there. Regarding the performance stuff - I’m currently using only CPU and both options were tested directly on it. So I guess the problem is the wrong SameDiffLayer implementation from my side.

One more question @treo. I’ve put it already in the SameDiff section but maybe you know the answer. After implementing the mentioned in this chat encoder’s layer model with SameDiff I’ve made it to have all the basic transformations I need but got the problem of applying feature masks to the transformations other than MultiHeadDotProductAttention. Because each transformer encoder’s layer has one dense layer after each SelfAttentionLayer, I need to apply feature masks to each such layer (if not on the input then on the activations). Also I have a first hidden layer which takes token and positional embeddings as the input. It also needs to apply feature masks. I was looking into MultiLayerNetwork and saw there that practically feature masks are applied by doing a broadcast multiplication of pre-outputs and activations plus back propagation. The first two I can easily implement. But BP is my problem. I haven’t found any available solution to force the BP in SameDiff into using the feature masks. Do you have any suggestions how I could workaround this issue?
I thought of using ArgumentInterceptor but it’s an internal stuff, not a flexible option.

I’ve answered the question on when and how to apply a mask in SameDiff over at your other thread: Feature Mask application in custom SameDiff model

It isn’t necessary for you to do that. They will be automatically applied during backprop with SameDiff when you apply it in the forward pass. The entire point of SameDiff is that it does the entire backprop for you so you don’t have to define it manually.

1 Like