Repository: pytorch
Issue: 'MultiHeadAttention.attention' is being compiled since it was called from 'MultiHeadAttention.forward'
Labels: oncall: jit

### 🐛 Describe the bug

```
File "/home/_/infer_0508.py", line 692, in get_audio
    scripted_model = torch.jit.script(quantized_model)
  File "/home/_/lib/python3.10/site-packages/torch/jit/_script.py", line 1338, in script
    return torch.jit._recursive.create_script_module(
  File "/home/_/lib/python3.10/site-packages/torch/jit/_recursive.py", line 558, in create_script_module
    return create_script_module_impl(nn_module, concrete_type, stubs_fn)
  File "/home/_/lib/python3.10/site-packages/torch/jit/_recursive.py", line 631, in create_script_module_impl
    script_module = torch.jit.RecursiveScriptModule._construct(cpp_module, init_fn)
  File "/home/_/lib/python3.10/site-packages/torch/jit/_script.py", line 647, in _construct
    init_fn(script_module)
  File "/home/_/lib/python3.10/site-packages/torch/jit/_recursive.py", line 607, in init_fn
    scripted = create_script_module_impl(
  File "/home/_/lib/python3.10/site-packages/torch/jit/_recursive.py", line 631, in create_script_module_impl
    script_module = torch.jit.RecursiveScriptModule._construct(cpp_module, init_fn)
  File "/home/_/lib/python3.10/site-packages/torch/jit/_script.py", line 647, in _construct
    init_fn(script_module)
  File "/home/_/lib/python3.10/site-packages/torch/jit/_recursive.py", line 607, in init_fn
    scripted = create_script_module_impl(
  File "/home/_/lib/python3.10/site-packages/torch/jit/_recursive.py", line 631, in create_script_module_impl
    script_module = torch.jit.RecursiveScriptModule._construct(cpp_module, init_fn)
  File "/home/_/lib/python3.10/site-packages/torch/jit/_script.py", line 647, in _construct
    init_fn(script_module)
  File "/home/_/lib/python3.10/site-packages/torch/jit/_recursive.py", line 607, in init_fn
    scripted = create_script_module_impl(
  File "/home/_/lib/python3.10/site-packages/torch/jit/_recursive.py", line 631, in create_script_module_impl
    script_module = torch.jit.RecursiveScriptModule._construct(cpp_module, init_fn)
  File "/home/_/lib/python3.10/site-packages/torch/jit/_script.py", line 647, in _construct
    init_fn(script_module)
  File "/home/_/lib/python3.10/site-packages/torch/jit/_recursive.py", line 607, in init_fn
    scripted = create_script_module_impl(
  File "/home/_/lib/python3.10/site-packages/torch/jit/_recursive.py", line 635, in create_script_module_impl
    create_methods_and_properties_from_stubs(
  File "/home/_/lib/python3.10/site-packages/torch/jit/_recursive.py", line 467, in create_methods_and_properties_
    concrete_type._create_methods_and_properties(
  File "/home/_/lib/python3.10/site-packages/torch/jit/_recursive.py", line 1036, in compile_unbound_method
    create_methods_and_properties_from_stubs(concrete_type, (stub,), ())
  File "/home/_/lib/python3.10/site-packages/torch/jit/_recursive.py", line 467, in create_methods_and_properties_
    concrete_type._create_methods_and_properties(
RuntimeError: 
cannot statically infer the expected size of a list in this context:
  File "/home/_/attentions.py", line 191
  def attention(self, query, key, value, mask=None):
    # reshape [b, d, t] -> [b, n_h, t, d_k]
    b, d, t_s, t_t = (*key.size(), query.size(2))
                      ~~~~~~~~~ <--- HERE
    query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
    key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
'MultiHeadAttention.attention' is being compiled since it was called from 'MultiHeadAttention.forward'
  File "/home/_/attentions.py", line 184
    v = self.conv_v(c)
    
    x, self.attn = self.attention(q, k, v, mask=attn_mask)
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <--- HERE
  
    x = self.conv_o(x)
```


### Versions

python                3.10
toolz                     0.12.1
torch                     2.2.2+cu121
torchaudio                2.2.2+cu121
torchvision               0.17.2+cu121
tqdm                      4.66.2
transformers              4.39.1

  ```
class MultiHeadAttention(nn.Module):
  def __init__(self, channels, out_channels, n_heads, p_dropout=0., window_size=None, heads_share=True, block_length=None, proximal_bias=False, proximal_init=False):
    super().__init__()
    assert channels % n_heads == 0

    self.channels = channels
    self.out_channels = out_channels
    self.n_heads = n_heads
    self.p_dropout = p_dropout
    self.window_size = window_size
    self.heads_share = heads_share
    self.block_length = block_length
    self.proximal_bias = proximal_bias
    self.proximal_init = proximal_init
    self.attn = None

    self.k_channels = channels // n_heads
    self.conv_q = nn.Conv1d(channels, channels, 1)
    self.conv_k = nn.Conv1d(channels, channels, 1)
    self.conv_v = nn.Conv1d(channels, channels, 1)
    self.conv_o = nn.Conv1d(channels, out_channels, 1)
    self.drop = nn.Dropout(p_dropout)

    if window_size is not None:
      n_heads_rel = 1 if heads_share else n_heads
      rel_stddev = self.k_channels**-0.5
      self.emb_rel_k = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
      self.emb_rel_v = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)

    nn.init.xavier_uniform_(self.conv_q.weight)
    nn.init.xavier_uniform_(self.conv_k.weight)
    nn.init.xavier_uniform_(self.conv_v.weight)
    if proximal_init:
      with torch.no_grad():
        self.conv_k.weight.copy_(self.conv_q.weight)
        self.conv_k.bias.copy_(self.conv_q.bias)

  def forward(self, x, c, attn_mask=None):
    q = self.conv_q(x)
    k = self.conv_k(c)
    v = self.conv_v(c)
    
    x, self.attn = self.attention(q, k, v, mask=attn_mask)

    x = self.conv_o(x)
    return x

  def attention(self, query, key, value, mask=None):
      # reshape [b, d, t] -> [b, n_h, t, d_k]
      b, d, t_s, t_t = (*key.size(), query.size(2))
      #  ~~~~~~~~~ <--- HERE
      query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
      key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
      value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
  
      scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
      if self.window_size is not None:
        assert t_s == t_t, "Relative attention is only available for self-attention."
        key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
        rel_logits = self._matmul_with_relative_keys(query /math.sqrt(self.k_channels), key_relative_embeddings)
        scores_local = self._relative_position_to_absolute_position(rel_logits)
        scores = scores + scores_local
      if self.proximal_bias:
        assert t_s == t_t, "Proximal bias is only available for self-attention."
        scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype)
      if mask is not None:
        scores = scores.masked_fill(mask == 0, -1e4)
        if self.block_length is not None:
          assert t_s == t_t, "Local attention is only available for self-attention."
          block_mask = torch.ones_like(scores).triu(-self.block_length).tril(self.block_length)
          scores = scores.masked_fill(block_mask == 0, -1e4)
      p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
      p_attn = self.drop(p_attn)
      output = torch.matmul(p_attn, value)
      if self.window_size is not None:
        relative_weights = self._absolute_position_to_relative_position(p_attn)
        value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s)
        output = output + self._matmul_with_relative_values(relative_weights, value_relative_embeddings)
      output = output.transpose(2, 3).contiguous().view(b, d, t_t) # [b, n_h, t_t, d_k] -> [b, d, t_t]
      return output, p_attn

```

cc @EikanWang @jgong5 @wenzhe-nrv @sanchitintel