BERT is pre-trained on sentence pairs packed as
and its input embedding is the sum of a token, a segment and a position embedding (Fig 15.34). The masked-LM loss scores each masked position with the tied token embeddings: .
Implement:
pack_pair(a_ids, b_ids, cls_id, sep_id) returning (ids, segment_ids, positions) as Python lists: segment 0 for [CLS], the A tokens and the first [SEP]; segment 1 for the B tokens and the final [SEP]; positions . If b_ids is empty, return the single-sentence form [CLS] A [SEP] (all segment 0).bert_embed(ids, segment_ids, positions, E_tok, E_seg, E_pos): the (L, d) array .mlm_loss(H, E_tok, targets, mask): H is (L, d) final hidden vectors, targets the (L,) original token ids, mask a boolean (L,) array of masked positions. Return (loss, accuracy): the mean of over masked positions only, and the fraction of masked positions whose highest-scoring token equals the target (lowest id on ties). With no masked positions return (0.0, 0.0). Use a stable log-softmax.