R/PipeOpTorchMultiheadAttention.R

nn_attention = nn_module(
  "nn_attention",
  initialize = function(embed_dim, num_heads, dropout = 0, bias = TRUE, add_bias_kv = FALSE,
    add_zero_attn = FALSE, kdim = NULL, vdim = NULL, batch_first = FALSE, need_weights = FALSE,
    avg_weights = TRUE) {
    self$need_weights = assert_flag(need_weights)
    self$avg_weights = assert_flag(avg_weights)
    self$attention = torch::nn_multihead_attention(
      embed_dim = embed_dim,
      num_heads = num_heads,
      dropout = dropout,
      bias = bias,
      add_bias_kv = add_bias_kv,
      add_zero_attn = add_zero_attn,
      kdim = kdim,
      vdim = vdim,
      batch_first = batch_first
    )
  },
  forward = function(...) {
    inputs = list(...)
    query = inputs[[1L]]
    key = if (length(inputs) >= 2L) inputs[[2L]] else query
    value = if (length(inputs) >= 3L) inputs[[3L]] else key
    out = self$attention(query = query, key = key, value = value,
      need_weights = self$need_weights, avg_weights = self$avg_weights)
    if (self$need_weights) {
      list(output = out[[1L]], weights = out[[2L]])
    } else {
      out[[1L]]
    }
  }
)

#' @title Multi-Head Attention
#'
#' @description
#' Multi-head attention as described in *Attention Is All You Need*.
#'
#' This is a thin wrapper around [`torch::nn_multihead_attention()`] that makes it usable as a
#' building block of a [`Graph`][mlr3pipelines::Graph] of tensor operations, where both
#' self-attention and cross-attention can be expressed, see section *Input and Output Channels*.
#'
#' @section Tensor Layout:
#' All inputs and outputs are `(batch, sequence, feature)`, i.e. the `batch_first` layout of
#' [`torch::nn_multihead_attention()`], which is fixed and not a hyperparameter.
#' `torch` defaults to `(sequence, batch, feature)`, but the first dimension of every shape has to
#' be the batch dimension here.
#'
#' @section nn_module:
#' Calls [`torch::nn_multihead_attention()`] when trained, where the parameters `embed_dim`, `kdim`
#' and `vdim` are inferred as the last dimension of the query, key and value tensors respectively,
#' and `batch_first` is always `TRUE`, see section *Tensor Layout*.
#' @section Parameters:
#' * `num_heads` :: `integer(1)`\cr
#'   Number of parallel attention heads. The embedding dimension must be divisible by `num_heads`.
#' * `dropout` :: `numeric(1)`\cr
#'   Dropout probability on the attention weights.
#'   Default is `0`.
#' * `bias` :: `logical(1)`\cr
#'   Whether to add a bias to the input and output projections.
#'   Default is `TRUE`.
#' * `add_bias_kv` :: `logical(1)`\cr
#'   Whether to add a bias to the key and value sequences at dimension 1.
#'   Default is `FALSE`.
#' * `add_zero_attn` :: `logical(1)`\cr
#'   Whether to add a new batch of zeros to the key and value sequences at dimension 1.
#'   Default is `FALSE`.
#' * `avg_weights` :: `logical(1)`\cr
#'   Whether the returned attention weights are averaged over the attention heads.
#'   Default is `TRUE`. Only has an effect when `"weights"` is among `$outputs`.
#'
#' Note that `embed_dim`, `kdim` and `vdim` are *not* parameters, as they are inferred from the
#' shapes of the input tensors, and that `batch_first` is *not* a parameter either, as it is fixed
#' to `TRUE`, see section *Tensor Layout*.
#'
#' @section Input and Output Channels:
#' The number of input channels is determined by the construction argument `mode`:
#' * `mode = "self"` (default): one input channel `"input"`, which is used as query, key and value,
#'   i.e. the `PipeOp` performs *self-attention*.
#' * `mode = "cross"`: input channels `"query"` and `"key_value"`, i.e. the `PipeOp` performs
#'   *cross-attention*, where the second input is used as both key and value.
#' * `mode = "general"`: input channels `"query"`, `"key"` and `"value"`, i.e. the `PipeOp` performs
#'   *cross-attention* with separate key and value inputs.
#'
#' The module has two outputs, `"output"`, containing the attention output, and `"weights"`,
#' containing the attention weights, of which only `"output"` is an output channel by default.
#' Set `$outputs` to also (or only) get the weights, e.g. `outputs = c("output", "weights")`,
#' which are only computed when they are among `$outputs`.
#'
#' For an explanation see [`PipeOpTorch`].
#'
#' @references
#' `r format_bib("vaswani2017attention")`
#'
#' @templateVar id nn_multihead_attention
#' @templateVar param_vals num_heads = 4
#' @template pipeop_torch
#' @template pipeop_torch_example
#'
#' @export
PipeOpTorchMultiheadAttention = R6Class("PipeOpTorchMultiheadAttention",
  inherit = PipeOpTorch,
  public = list(
    #' @description Creates a new instance of this [R6][R6::R6Class] class.
    #' @template params_pipelines
    #' @param mode (`character(1)`)\cr
    #'   The attention mode, which determines the input channels. One of `"self"`, `"cross"` or
    #'   `"general"`.
    #'   This is a *construction* argument (and not a hyperparameter), because it determines the
    #'   structure of the [`Graph`][mlr3pipelines::Graph].
    #'   The default is `"self"`, which means that the `PipeOp` performs self-attention.
    #'   See section *Input and Output Channels* for more information.
    initialize = function(id = "nn_multihead_attention", mode = "self", param_vals = list()) {
      private$.mode = assert_choice(mode, c("self", "cross", "general"))
      inname = switch(private$.mode,
        self = "input",
        cross = c("query", "key_value"),
        general = c("query", "key", "value")
      )
      param_set = ps(
        num_heads = p_int(lower = 1L, tags = c("train", "required")),
        dropout = p_dbl(lower = 0, upper = 1, default = 0, tags = "train"),
        bias = p_lgl(default = TRUE, tags = "train"),
        add_bias_kv = p_lgl(default = FALSE, tags = "train"),
        add_zero_attn = p_lgl(default = FALSE, tags = "train"),
        avg_weights = p_lgl(default = TRUE, tags = "train")
      )
      super$initialize(
        id = id,
        module_generator = nn_attention,
        param_set = param_set,
        param_vals = param_vals,
        inname = inname,
        outname = c("output", "weights")
      )
      # the weights are only an output channel when they are requested
      self$outputs = "output"
    }
  ),
  private = list(
    .mode = NULL,
    # index of the value input channel: query/key/value for "general", query/key_value for "cross",
    # and the single "input" channel for "self"
    .value_index = function() {
      switch(private$.mode, self = 1L, cross = 2L, general = 3L)
    },
    .additional_phash_input = function() {
      c(super$.additional_phash_input(), list(private$.mode))
    },
    # the shape of the key input, which for `mode == "self"` is the query itself
    .key_shape = function(shapes_in) {
      if (private$.mode == "self") shapes_in[[1L]] else shapes_in[[2L]]
    },
    # whether torch takes the `qkv_same_embed_dim_` branch, which is the only one that forwards
    # `avg_weights` to `nnf_multi_head_attention_forward()`
    .qkv_same_embed_dim = function(shapes_in) {
      embed_dim = tail(shapes_in[[1L]], 1L)
      kdim = tail(private$.key_shape(shapes_in), 1L)
      vdim = tail(shapes_in[[private$.value_index()]], 1L)
      isTRUE(kdim == embed_dim) && isTRUE(vdim == embed_dim)
    },
    .shapes_out = function(shapes_in, param_vals, task) {
      walk(seq_along(shapes_in), function(i) {
        if (length(shapes_in[[i]]) != 3L) {
          stopf("PipeOpTorchMultiheadAttention expects three-dimensional inputs, but input %i has %i dimensions.", i, length(shapes_in[[i]])) # nolint
        }
        # the last dimension of every input becomes embed_dim, kdim or vdim, none of which can be
        # inferred lazily, so an unknown feature dimension must be caught here for all channels
        if (is.na(tail(shapes_in[[i]], 1L))) {
          stopf("PipeOpTorchMultiheadAttention received an input shape where the last dimension is unknown (input channel '%s'). Please provide an input with a known last dimension.", self$input$name[[i]]) # nolint
        }
      })
      query_shape = shapes_in[[1L]]
      embed_dim = tail(query_shape, 1L)
      if (embed_dim %% param_vals$num_heads != 0) {
        stopf("PipeOpTorchMultiheadAttention: the embedding dimension (%i) must be divisible by 'num_heads' (%i).", embed_dim, param_vals$num_heads) # nolint
      }
      # all inputs and outputs are `(batch, sequence, feature)`, see `.shape_dependent_params()`
      key_shape = private$.key_shape(shapes_in)
      n_batch = query_shape[1L]
      tgt_len = query_shape[2L]
      src_len = key_shape[2L] + (param_vals$add_bias_kv %??% FALSE) + (param_vals$add_zero_attn %??% FALSE)

      # torch ignores `avg_weights` unless kdim and vdim both equal embed_dim
      avg_weights = (param_vals$avg_weights %??% TRUE) || !private$.qkv_same_embed_dim(shapes_in)
      weights_shape = if (avg_weights) {
        c(n_batch, tgt_len, src_len)
      } else {
        c(n_batch, param_vals$num_heads, tgt_len, src_len)
      }
      # the attention output has the same shape as the query
      list(query_shape, weights_shape)
    },
    .shape_dependent_params = function(shapes_in, param_vals, task) {
      param_vals$batch_first = TRUE
      param_vals$embed_dim = tail(shapes_in[[1L]], 1L)
      if (private$.mode != "self") {
        # for mode == "cross", the second channel provides both the keys and the values
        param_vals$kdim = tail(shapes_in[[2L]], 1L)
        param_vals$vdim = tail(shapes_in[[private$.value_index()]], 1L)
      }
      # the weights are only computed when they are among `$outputs`
      param_vals$need_weights = "weights" %in% self$output$name
      param_vals
    },
    .module_outputs = function() {
      if ("weights" %in% self$output$name) c("output", "weights") else "output"
    }
  )
)

#' @include aaa.R
register_po("nn_multihead_attention", PipeOpTorchMultiheadAttention)

Try the mlr3torch package in your browser

Any scripts or data that you put into this service are public.

mlr3torch documentation built on Oct. 30, 2026, 5:10 p.m.