"vscode:/vscode.git/clone" did not exist on "c6c22f16d3533c63bec6cb1b8a3a29759bbbb9c2"
preprocess.py 1.99 KB
Newer Older
1
2
import torch
import torch.nn as nn
3
4
5

from colossalai.legacy.context.parallel_mode import ParallelMode
from colossalai.legacy.core import global_context as gpc
6
7
8
9
10
11
12
13
14
15
16


class PreProcessor(nn.Module):
    def __init__(self, sub_seq_length):
        super().__init__()
        self.sub_seq_length = sub_seq_length

    def bert_position_ids(self, token_ids):
        # Create position ids
        seq_length = token_ids.size(1)
        local_rank = gpc.get_local_rank(ParallelMode.SEQUENCE)
17
18
19
        position_ids = torch.arange(
            seq_length * local_rank, seq_length * (local_rank + 1), dtype=torch.long, device=token_ids.device
        )
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
        position_ids = position_ids.unsqueeze(0).expand_as(token_ids)

        return position_ids

    def bert_extended_attention_mask(self, attention_mask):
        local_rank = gpc.get_local_rank(ParallelMode.SEQUENCE)
        start_index = local_rank * self.sub_seq_length
        end_index = (local_rank + 1) * self.sub_seq_length

        # We create a 3D attention mask from a 2D tensor mask.
        # [b, 1, s]
        attention_mask_b1s = attention_mask.unsqueeze(1)
        # [b, s, 1]
        attention_mask_bs1 = attention_mask.unsqueeze(2)
        # [b, s/D, s]
        attention_mask_bss = attention_mask_b1s * attention_mask_bs1

        attention_mask_bss = attention_mask_bss[:, start_index:end_index, :]

        # [b, 1, s/D, s]
        extended_attention_mask = attention_mask_bss.unsqueeze(1)

        # Convert attention mask to binary:
43
        extended_attention_mask = extended_attention_mask < 0.5
44
45
46
47
48
49
50
51
52
53
54
55
56
57

        return extended_attention_mask

    def forward(self, input_ids=None, attention_mask=None):
        if attention_mask is not None:
            extended_attention_mask = self.bert_extended_attention_mask(attention_mask)
        else:
            extended_attention_mask = None

        if input_ids is not None:
            position_ids = self.bert_position_ids(input_ids)
        else:
            position_ids = None
        return position_ids, extended_attention_mask