File size: 4,275 Bytes
6ae9156
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
"""A small word/subword Transformer for the closed action set and rejection."""
from dataclasses import asdict, dataclass
from functools import lru_cache
import hashlib
import re

import torch
from torch import nn

from actions import ActionKind, InputError

LABELS = tuple(kind.value for kind in ActionKind) + ('reject',)
WORDS = re.compile(r'NAME|[a-z]+(?:-[a-z]+)*')


@dataclass(frozen=True)
class ModelConfig:
    """Checkpointed architecture and tokenizer dimensions."""

    width: int = 64
    layers: int = 2
    heads: int = 4
    feedforward: int = 128
    char_buckets: int = 1024
    max_ngrams: int = 32
    max_words: int = 60
    dropout: float = 0.1


def tokenize(phrase):
    """Tokenize normalized command text; quoted names are already placeholders."""
    return WORDS.findall(phrase)


def make_vocab(rows):
    """Build only from training text; unseen words keep their character features."""
    words = sorted({word for phrase, _ in rows for word in tokenize(phrase)})
    return {word: index for index, word in enumerate(['<pad>', '<unk>', '<cls>'] + words)}


@lru_cache(maxsize=8192)
def _ngrams(word, buckets, maximum):
    padded = '<' + word + '>'
    pieces = [padded[index:index + size]
              for size in (2, 3, 4) for index in range(len(padded) - size + 1)]
    # Stable hashes make tokenization identical across Python processes.
    ids = [1 + int.from_bytes(hashlib.blake2b(piece.encode(), digest_size=8).digest(), 'little')
           % (buckets - 1) for piece in pieces[:maximum]]
    return tuple(ids + [0] * (maximum - len(ids)))


def encode(phrase, vocab, config):
    """Encode every word without discarding novel lexical information."""
    words = tokenize(phrase)
    if not words or len(words) > min(58, config.max_words - 1):
        raise InputError('Each command must contain between 1 and 58 words.')
    ids = [vocab['<cls>']] + [vocab.get(word, vocab['<unk>']) for word in words]
    chars = [(0,) * config.max_ngrams] + [
        _ngrams(word, config.char_buckets, config.max_ngrams) for word in words]
    return ids, chars


def collate(encoded, config):
    """Pad encoded clauses for a single CPU batch."""
    width = max(len(words) for words, _ in encoded)
    word_ids = torch.zeros((len(encoded), width), dtype=torch.long)
    char_ids = torch.zeros((len(encoded), width, config.max_ngrams), dtype=torch.long)
    for index, (words, chars) in enumerate(encoded):
        word_ids[index, :len(words)] = torch.tensor(words)
        char_ids[index, :len(words)] = torch.tensor(chars)
    return word_ids, char_ids


class IntentClassifier(nn.Module):
    """Bidirectional clause encoder; the only predictions are fixed intent labels."""

    def __init__(self, vocabulary_size, config=None):
        super().__init__()
        self.config = config or ModelConfig()
        self.thresholds = {'probability': 0.65, 'margin': 0.15}
        cfg = self.config
        self.words = nn.Embedding(vocabulary_size, cfg.width, padding_idx=0)
        self.characters = nn.Embedding(cfg.char_buckets, cfg.width, padding_idx=0)
        self.positions = nn.Embedding(cfg.max_words, cfg.width)
        self.norm = nn.LayerNorm(cfg.width)
        self.dropout = nn.Dropout(cfg.dropout)
        self.layers = nn.ModuleList([
            nn.TransformerEncoderLayer(cfg.width, cfg.heads, cfg.feedforward,
                                       dropout=cfg.dropout, batch_first=True)
            for _ in range(cfg.layers)])
        self.output = nn.Linear(cfg.width, len(LABELS))

    def forward(self, words, chars):
        mask = words.eq(0)
        count = chars.ne(0).sum(-1, keepdim=True).clamp_min(1)
        # Keep the subword path at a comparable scale to whole-word embeddings.
        character_features = self.characters(chars).sum(-2) / count.sqrt()
        positions = self.positions(torch.arange(words.shape[1], device=words.device))
        hidden = self.dropout(self.norm(self.words(words) + character_features + positions))
        for layer in self.layers:
            hidden = layer(hidden, src_key_padding_mask=mask)
        return self.output(hidden[:, 0])

    def architecture(self):
        """Return the portable architecture metadata stored beside the weights."""
        return asdict(self.config)