Run this notebook online:\ |Binder| or Colab: |Colab| .. |Binder| image:: https://mybinder.org/badge_logo.svg :target: https://mybinder.org/v2/gh/deepjavalibrary/d2l-java/master?filepath=chapter_attention-mechanisms/nadaraya-watson.ipynb .. |Colab| image:: https://colab.research.google.com/assets/colab-badge.svg :target: https://colab.research.google.com/github/deepjavalibrary/d2l-java/blob/colab/chapter_attention-mechanisms/nadaraya-watson.ipynb .. _sec_nadaraya-watson: Attention Pooling: Nadaraya-Watson Kernel Regression ==================================================== Now you know the major components of attention mechanisms under the framework in :numref:`fig_qkv`. To recapitulate, the interactions between queries (volitional cues) and keys (nonvolitional cues) result in *attention pooling*. The attention pooling selectively aggregates values (sensory inputs) to produce the output. In this section, we will describe attention pooling in greater detail to give you a high-level view of how attention mechanisms work in practice. Specifically, the Nadaraya-Watson kernel regression model proposed in 1964 is a simple yet complete example for demonstrating machine learning with attention mechanisms. .. code:: java %load ../utils/djl-imports %load ../utils/plot-utils %load ../utils/Functions.java %load ../utils/Animator.java %load ../utils/PlotUtils.java .. code:: java NDManager manager = NDManager.newBaseManager(); Generating the Dataset ---------------------- To keep things simple, let us consider the following regression problem: given a dataset of input-output pairs :math:`\{(x_1, y_1), \ldots, (x_n, y_n)\}`, how to learn :math:`f` to predict the output :math:`\hat{y} = f(x)` for any new input :math:`x`? Here we generate an artificial dataset according to the following nonlinear function with the noise term :math:`\epsilon`: .. math:: y_i = 2\sin(x_i) + x_i^{0.8} + \epsilon, where :math:`\epsilon` obeys a normal distribution with zero mean and standard deviation 0.5. Both 50 training examples and 50 testing examples are generated. To better visualize the pattern of attention later, the training inputs are sorted. .. code:: java int nTrain = 50; // No. of training examples NDArray xTrain = manager.randomUniform(0, 1, new Shape(nTrain)).mul(5).sort(); // Training inputs .. code:: java Function f = x -> x.sin().mul(2).add(x.pow(0.8)); NDArray yTrain = f.apply(xTrain) .add( manager.randomNormal( 0f, 0.5f, new Shape(nTrain), DataType.FLOAT32)); // Training outputs NDArray xTest = manager.arange(0f, 5f, 0.1f); // Testing examples NDArray yTruth = f.apply(xTest); // Ground-truth outputs for the testing examples int nTest = (int) xTest.getShape().get(0); // No. of testing examples System.out.println(nTest); .. parsed-literal:: :class: output 50 The following function plots all the training examples (represented by circles), the ground-truth data generation function ``f`` without the noise term (labeled by "Truth"), and the learned prediction function (labeled by "Pred"). .. code:: java public static Figure plot( NDArray yHat, String trace1Name, String trace2Name, String xLabel, String yLabel, int width, int height) { ScatterTrace trace = ScatterTrace.builder( Functions.floatToDoubleArray(xTest.toFloatArray()), Functions.floatToDoubleArray(yTruth.toFloatArray())) .mode(ScatterTrace.Mode.LINE) .name(trace1Name) .build(); ScatterTrace trace2 = ScatterTrace.builder( Functions.floatToDoubleArray(xTest.toFloatArray()), Functions.floatToDoubleArray(yHat.toFloatArray())) .mode(ScatterTrace.Mode.LINE) .name(trace2Name) .build(); ScatterTrace trace3 = ScatterTrace.builder( Functions.floatToDoubleArray(xTrain.toFloatArray()), Functions.floatToDoubleArray(yTrain.toFloatArray())) .mode(ScatterTrace.Mode.MARKERS) .marker(Marker.builder().symbol(Symbol.CIRCLE).size(15).opacity(.5).build()) .build(); Layout layout = Layout.builder() .height(height) .width(width) .showLegend(true) .xAxis(Axis.builder().title(xLabel).domain(0, 5).build()) .yAxis(Axis.builder().title(yLabel).domain(-1, 5).build()) .build(); return new Figure(layout, trace, trace2, trace3); } Average Pooling --------------- We begin with perhaps the world's "dumbest" estimator for this regression problem: using average pooling to average over all the training outputs: .. math:: f(x) = \frac{1}{n}\sum_{i=1}^n y_i, :label: eq_avg-pooling which is plotted below. As we can see, this estimator is indeed not so smart. .. code:: java NDArray yHat = yTrain.mean().tile(nTest); plot(yHat, "Truth", "Pred", "x", "y", 700, 500); .. raw:: html
Nonparametric Attention Pooling ------------------------------- Obviously, average pooling omits the inputs :math:`x_i`. A better idea was proposed by Nadaraya :cite:`Nadaraya.1964` and Watson :cite:`Watson.1964` to weigh the outputs :math:`y_i` according to their input locations: .. math:: f(x) = \sum_{i=1}^n \frac{K(x - x_i)}{\sum_{j=1}^n K(x - x_j)} y_i, :label: eq_nadaraya-watson where :math:`K` is a *kernel*. The estimator in :eq:`eq_nadaraya-watson` is called *Nadaraya-Watson kernel regression*. Here we will not dive into details of kernels. Recall the framework of attention mechanisms in :numref:`fig_qkv`. From the perspective of attention, we can rewrite :eq:`eq_nadaraya-watson` in a more generalized form of *attention pooling*: .. math:: f(x) = \sum_{i=1}^n \alpha(x, x_i) y_i, :label: eq_attn-pooling where :math:`x` is the query and :math:`(x_i, y_i)` is the key-value pair. Comparing :eq:`eq_attn-pooling` and :eq:`eq_avg-pooling`, the attention pooling here is a weighted average of values :math:`y_i`. The *attention weight* :math:`\alpha(x, x_i)` in :eq:`eq_attn-pooling` is assigned to the corresponding value :math:`y_i` based on the interaction between the query :math:`x` and the key :math:`x_i` modeled by :math:`\alpha`. For any query, its attention weights over all the key-value pairs are a valid probability distribution: they are non-negative and sum up to one. To gain intuitions of attention pooling, just consider a *Gaussian kernel* defined as .. math:: K(u) = \frac{1}{\sqrt{2\pi}} \exp(-\frac{u^2}{2}). Plugging the Gaussian kernel into :eq:`eq_attn-pooling` and :eq:`eq_nadaraya-watson` gives .. math:: \begin{aligned} f(x) &=\sum_{i=1}^n \alpha(x, x_i) y_i\\ &= \sum_{i=1}^n \frac{\exp\left(-\frac{1}{2}(x - x_i)^2\right)}{\sum_{j=1}^n \exp\left(-\frac{1}{2}(x - x_j)^2\right)} y_i \\&= \sum_{i=1}^n \mathrm{softmax}\left(-\frac{1}{2}(x - x_i)^2\right) y_i. \end{aligned} :label: eq_nadaraya-watson-gaussian In :eq:`eq_nadaraya-watson-gaussian`, a key :math:`x_i` that is closer to the given query :math:`x` will get *more attention* via a *larger attention weight* assigned to the key's corresponding value :math:`y_i`. Notably, Nadaraya-Watson kernel regression is a nonparametric model; thus :eq:`eq_nadaraya-watson-gaussian` is an example of *nonparametric attention pooling*. In the following, we plot the prediction based on this nonparametric attention model. The predicted line is smooth and closer to the ground-truth than that produced by average pooling. .. code:: java // Shape of `xRepeat`: (`nTest`, `nTrain`), where each row contains the // same testing inputs (i.e., same queries) NDArray xRepeat = xTest.repeat(nTrain).reshape(new Shape(-1, nTrain)); // Note that `xTrain` contains the keys. Shape of `attention_weights`: // (`nTest`, `nTrain`), where each row contains attention weights to be // assigned among the values (`yTrain`) given each query NDArray attentionWeights = xRepeat.sub(xTrain).pow(2).div(2).mul(-1).softmax(-1); // Each element of `yHat` is weighted average of values, where weights are // attention weights yHat = attentionWeights.dot(yTrain); plot(yHat, "Truth", "Pred", "x", "y", 700, 500); .. raw:: html
Now let us take a look at the attention weights. Here testing inputs are queries while training inputs are keys. Since both inputs are sorted, we can see that the closer the query-key pair is, the higher attention weight is in the attention pooling. .. code:: java PlotUtils.showHeatmaps( attentionWeights.expandDims(0).expandDims(0), "Sorted training inputs", "Sorted testing inputs", new String[] {""}, 500, 700); .. raw:: html
Parametric Attention Pooling ---------------------------- Nonparametric Nadaraya-Watson kernel regression enjoys the *consistency* benefit: given enough data this model converges to the optimal solution. Nonetheless, we can easily integrate learnable parameters into attention pooling. As an example, slightly different from :eq:`eq_nadaraya-watson-gaussian`, in the following the distance between the query :math:`x` and the key :math:`x_i` is multiplied a learnable parameter :math:`w`: .. math:: \begin{aligned}f(x) &= \sum_{i=1}^n \alpha(x, x_i) y_i \\&= \sum_{i=1}^n \frac{\exp\left(-\frac{1}{2}((x - x_i)w)^2\right)}{\sum_{j=1}^n \exp\left(-\frac{1}{2}((x - x_i)w)^2\right)} y_i \\&= \sum_{i=1}^n \mathrm{softmax}\left(-\frac{1}{2}((x - x_i)w)^2\right) y_i.\end{aligned} :label: eq_nadaraya-watson-gaussian-para In the rest of the section, we will train this model by learning the parameter of the attention pooling in :eq:`eq_nadaraya-watson-gaussian-para`. .. _subsec_batch_dot: Batch Matrix Multiplication ~~~~~~~~~~~~~~~~~~~~~~~~~~~ To more efficiently compute attention for minibatches, we can leverage batch matrix multiplication utilities provided by deep learning frameworks. Suppose that the first minibatch contains :math:`n` matrices :math:`\mathbf{X}_1, \ldots, \mathbf{X}_n` of shape :math:`a\times b`, and the second minibatch contains :math:`n` matrices :math:`\mathbf{Y}_1, \ldots, \mathbf{Y}_n` of shape :math:`b\times c`. Their batch matrix multiplication results in :math:`n` matrices :math:`\mathbf{X}_1\mathbf{Y}_1, \ldots, \mathbf{X}_n\mathbf{Y}_n` of shape :math:`a\times c`. Therefore, given two tensors of shape (:math:`n`, :math:`a`, :math:`b`) and (:math:`n`, :math:`b`, :math:`c`), the shape of their batch matrix multiplication output is (:math:`n`, :math:`a`, :math:`c`). .. code:: java NDArray X = manager.ones(new Shape(2, 1, 4)); NDArray Y = manager.ones(new Shape(2, 4, 6)); X.batchDot(Y).getShape() .. parsed-literal:: :class: output (2, 1, 6) In the context of attention mechanisms, we can use minibatch matrix multiplication to compute weighted averages of values in a minibatch. .. code:: java NDArray weights = manager.ones(new Shape(2, 10)).mul(0.1); NDArray values = manager.arange(20f).reshape(new Shape(2, 10)); weights.expandDims(1).batchDot(values.expandDims(-1)) .. parsed-literal:: :class: output ND: (2, 1, 1) gpu(0) float32 [[[ 4.5], ], [[14.5], ], ] Defining the Model ~~~~~~~~~~~~~~~~~~ Using minibatch matrix multiplication, below we define the parametric version of Nadaraya-Watson kernel regression based on the parametric attention pooling in :eq:`eq_nadaraya-watson-gaussian-para`. .. code:: java public class NWKernelRegression extends AbstractBlock { private Parameter w; public NDArray attentionWeights; public NWKernelRegression() { w = Parameter.builder().optShape(new Shape(1)).setName("w").optInitializer(new UniformInitializer()).build(); addParameter(w); } @Override protected NDList forwardInternal( ParameterStore parameterStore, NDList inputs, boolean training, PairList params) { // Shape of the output `queries` and `attentionWeights`: // (no. of queries, no. of key-value pairs) NDArray queries = inputs.get(0); NDArray keys = inputs.get(1); NDArray values = inputs.get(2); queries = queries.repeat(keys.getShape().get(1)) .reshape(new Shape(-1, keys.getShape().get(1))); this.attentionWeights = queries.sub(keys).mul(this.w.getArray()).pow(2).div(2).mul(-1).softmax(-1); // Shape of `values`: (no. of queries, no. of key-value pairs) return new NDList( attentionWeights.expandDims(1).batchDot(values.expandDims(-1)).reshape(-1)); } @Override public Shape[] getOutputShapes(Shape[] inputShapes) { throw new UnsupportedOperationException("Not implemented"); } } Training ~~~~~~~~ In the following, we transform the training dataset to keys and values to train the attention model. In the parametric attention pooling, any training input takes key-value pairs from all the training examples except for itself to predict its output. .. code:: java // Shape of `xTile`: (`nTrain`, `nTrain`), where each column contains the // same training inputs NDArray xTile = xTrain.tile(new long[] {nTrain, 1}); // Shape of `Y_tile`: (`nTrain`, `nTrain`), where each column contains the // same training outputs NDArray yTile = yTrain.tile(new long[] {nTrain, 1}); // Shape of `keys`: ('nTrain', 'nTrain' - 1) NDArray keys = xTile.get(new NDIndex().addBooleanIndex(manager.eye(nTrain).mul(-1).add(1))).reshape(new Shape(nTrain, -1)); // Shape of `values`: ('nTrain', 'nTrain' - 1) values = yTile.get(new NDIndex().addBooleanIndex(manager.eye(nTrain).mul(-1).add(1))).reshape(new Shape(nTrain, -1)); Using the squared loss and stochastic gradient descent, we train the parametric attention model. .. code:: java NWKernelRegression net = new NWKernelRegression(); Loss loss = Loss.l2Loss(); Tracker lrt = Tracker.fixed(0.5f * nTrain); // Since we are using sgd, to be able to put the right // scale, we need to multiply by batchSize Optimizer sgd = Optimizer.sgd().setLearningRateTracker(lrt).build(); DefaultTrainingConfig config = new DefaultTrainingConfig(loss) .optOptimizer(sgd) // Optimizer (loss function) .addTrainingListeners(TrainingListener.Defaults.logging()); // Logging Model model = Model.newInstance(""); model.setBlock(net); Trainer trainer = model.newTrainer(config); Animator animator = new Animator(); ParameterStore ps = new ParameterStore(manager, false); // Create trainer and animator for (int epoch = 0; epoch < 5; epoch++) { try (GradientCollector gc = trainer.newGradientCollector()) { NDArray result = net.forward(ps, new NDList(xTrain, keys, values), true).get(0); NDArray l = trainer.getLoss().evaluate(new NDList(yTrain), new NDList(result)); gc.backward(l); animator.add(epoch + 1, (float) l.getFloat(), "Loss"); animator.show(); } trainer.step(); } .. parsed-literal:: :class: output INFO Training on: 4 GPUs. INFO Load MXNet Engine Version 1.9.0 in 0.077 ms. .. raw:: html
After training the parametric attention model, we can plot its prediction. Trying to fit the training dataset with noise, the predicted line is less smooth than its nonparametric counterpart that was plotted earlier. .. code:: java // Shape of `keys`: (`nTest`, `nTrain`), where each column contains the same // training inputs (i.e., same keys) keys = xTrain.tile(new long[] {nTest, 1}); // Shape of `value`: (`nTest`, `nTrain`) values = yTrain.tile(new long[] {nTest, 1}); yHat = net.forward(ps, new NDList(xTest, keys, values), true).get(0); plot(yHat, "Truth", "Pred", "x", "y", 700, 500); .. raw:: html
Comparing with nonparametric attention pooling, the region with large attention weights becomes sharper in the learnable and parametric setting. .. code:: java PlotUtils.showHeatmaps( net.attentionWeights.expandDims(0).expandDims(0), "Sorted training inputs", "Sorted testing inputs", new String[] {""}, 500, 700); .. raw:: html
Summary ------- - Nadaraya-Watson kernel regression is an example of machine learning with attention mechanisms. - The attention pooling of Nadaraya-Watson kernel regression is a weighted average of the training outputs. From the attention perspective, the attention weight is assigned to a value based on a function of a query and the key that is paired with the value. - Attention pooling can be either nonparametric or parametric. Exercises --------- 1. Increase the number of training examples. Can you learn nonparametric Nadaraya-Watson kernel regression better? 2. What is the value of our learned :math:`w` in the parametric attention pooling experiment? Why does it make the weighted region sharper when visualizing the attention weights? 3. How can we add hyperparameters to nonparametric Nadaraya-Watson kernel regression to predict better? 4. Design another parametric attention pooling for the kernel regression of this section. Train this new model and visualize its attention weights.