File size: 1,480 Bytes
bab6333
 
 
 
 
 
 
 
d3b61f8
bab6333
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
"""Bidirectional masks for existing full-attention layers only."""

from contextlib import contextmanager
import torch


def bidirectional_mask(config, inputs_embeds, attention_mask=None, past_key_values=None, **kwargs):
    if past_key_values is not None:
        raise ValueError('Bidirectional inference does not support autoregressive KV caches')
    if config._attn_implementation not in ('sdpa', 'eager'):
        raise ValueError('Bidirectional full layers currently require SDPA or eager attention')
    batch, length = inputs_embeds.shape[:2]
    if attention_mask is None:
        valid = torch.ones((batch, length), device=inputs_embeds.device, dtype=torch.bool)
    else:
        if attention_mask.shape != (batch, length):
            raise ValueError('Expected independent per-sample 2D padding mask')
        valid = attention_mask.to(device=inputs_embeds.device, dtype=torch.bool)
    mask = torch.zeros((batch, 1, 1, length), device=inputs_embeds.device, dtype=inputs_embeds.dtype)
    return mask.masked_fill(~valid[:, None, None, :], torch.finfo(inputs_embeds.dtype).min)


@contextmanager
def full_layer_attention(module, mode):
    if mode == 'causal':
        yield
        return
    if mode != 'bidirectional_full_layers':
        raise ValueError('Unknown attention mode: ' + mode)
    original = module.create_causal_mask
    module.create_causal_mask = bidirectional_mask
    try:
        yield
    finally:
        module.create_causal_mask = original