Baunsgaard commented on code in PR #1625:
URL: https://github.com/apache/systemds/pull/1625#discussion_r905131229


##########
scripts/nn/layers/attention.dml:
##########
@@ -0,0 +1,108 @@
+#-------------------------------------------------------------
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+#-------------------------------------------------------------
+
+source("nn/layers/softmax.dml") as softmax
+
+
+forward = function(matrix[double] query, matrix[double] key, matrix[double] 
value, integer K)
+    return (matrix[double] attention) {
+  /*
+   * Computes the forward pass for the attention layer.
+   *
+   * Inputs:
+   * - query: Input querys of shape (N,K*M).
+   * - key: Key(s) for value(s) of shape (N,K*M).
+   * - value: Value(s) for key(s) of shape (N,K*L).
+   * - K: Sequence length / number of timesteps.
+   * Outputs:
+   * - attention: Attention on value(s) for given query(s), of shape (N,K*L).
+   */
+  N = nrow(key)
+  M = ncol(query) / K
+  L = ncol(value) / K
+  norm = 1/M^0.5
+  key_norm = key * norm
+  attention = matrix(0, rows=N, cols=K*L)
+  for (n in 1:N)
+  {
+    query_n = matrix(query[n], rows=K, cols=M)
+    key_norm_n = matrix(key_norm[n],rows=K, cols=M)
+    value_n = matrix(value[n], rows=K, cols=L)
+    scores = query_n %*% t(key_norm_n)

Review Comment:
   okay, looking closer, this is hard because of us treating the entire input 
as one matrix. If we had it slightly different we could have solved it with 
element wise multiplications and rowSums, but this is not feasible currently i 
will think about it a bit more since the current way (and the only way i can 
tell currently) still is inefficient.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to