"""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(['', '', ''] + 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['']] + [vocab.get(word, vocab['']) 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)