Language models, retrieval, prompting, and language adaptation · Contextual and sentence encoders · LNG010 · Model
BERT
A bidirectional transformer encoder pretrained to recover masked tokens and originally classify sentence relationships.
In CodeSplash
A CodeSplash method runs this entry in Python and R. Set it up from the method's page.
- Text encoder (MiniLM + linear head) Not verified yet
Do it in CodeSplash Run it on your own data, in Python or R.
- Availability
- Runs in CodeSplash
- Code example
- Component demo, not a trained model
- Who ran it
- CodeSplash's own run
- CodeSplash's run
- The reference's example ran in Python and R here, and they agree.
- The reference's record
- Python: The chapter's authors report running it; there is no record for this entry alone. R: Reviewed but not run: R wasn't available to the reference's authors.
Purpose
A bidirectional transformer encoder pretrained to recover masked tokens and originally classify sentence relationships. It supports tagging, extraction, classification, and representation learning from text where the complete input is available.
Question / objective
Which contextual representations support masked-token prediction and downstream understanding tasks?
Architecture / computational structure
A bidirectional Transformer encoder plus masked-token and pretraining/task heads learns token, position, attention, and feed-forward weights. Masking rates, layer dimensions, and task-head type are hyperparameters.
Assumptions
Masked-token recovery is not ordinary sentence likelihood, and pooled features are not automatically good semantic embeddings.
Formula / computational definition
Masked-language loss is -sum_{t in M} log p_theta(x_t|x_corrupted), with mask positions M. Original training adds a next-sentence classification loss. Attention sees both left and right context; this differs from a causal decoder's factorization.
Parameters and notation
Learned parameters: identified in the architecture subsection. Hyperparameters, design and inference choices: Layer count, hidden width, heads, tokenization, maximum length, corruption rate, fine-tuning learning rate, and task head.
Fitting, fine-tuning, and adaptation
Continue masked-language pretraining on domain text if justified, then train a task head. Start frozen or with a low encoder learning rate; selectively unfreeze or add compatible LoRA/adapters. Validate on document-separated labels and monitor domain overfitting and lost general-language performance.
How to use and calibrate
Use task-specific held-out metrics, calibration, subgroup/domain checks, and length-stratified analysis. Use development data for settings and an independent test set for the final estimate. Report uncertainty across examples or seeds when the evaluation design supports it; model scores and self-assessments are not automatically calibrated probabilities of correctness.
Example application
Extract entities or classify policy documents using context-sensitive token representations.
Interpretation / pitfalls
Watch out
Truncation and domain shift can dominate performance; input text may contain future information unavailable at prediction time. The code below isolates one stated component; successful execution does not validate model quality or reproduce the cited experiment.
Python and R code examples
Full implementation route: Transformers supplies encoder and task-specific BERT classes. R can call the identical Python model through reticulate; native R torch reimplementation is possible but requires architecture and tokenizer fidelity.
Example scope: Masked-token cross-entropy on two supplied target-token probabilities.
Dependencies: Python 3 standard library; base R; shared setup above. No model downloads or external services.
Validation: Python component executed in the combined example script; R counterpart supplied but not runtime-tested here. All numbers are synthetic.
Python and R
The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.
Component demo, not a trained model — Masked-token cross-entropy on two supplied target-token probabilities.
Shared setup for this chapter
import math
def softmax(xs):
m = max(xs)
es = [math.exp(x-m) for x in xs]
return [e/sum(es) for e in es]
def dot(a, b):
return sum(x*y for x, y in zip(a, b))
def matvec(matrix, vector):
return [dot(row, vector) for row in matrix]
def meanvec(rows):
return [sum(row[j] for row in rows)/len(rows) for j in range(len(rows[0]))]
def sigmoid(x):
return 1/(1+math.exp(-x))
def nll(probabilities):
return -sum(math.log(p) for p in probabilities)
target_probabilities = [0.7, 0.4]
loss = nll(target_probabilities) / len(target_probabilities)
print(loss)
Component demo, not a trained model — Masked-token cross-entropy on two supplied target-token probabilities.
Shared setup for this chapter
softmax <- function(x) {
shifted <- exp(x-max(x))
shifted/sum(shifted)
}
target_probabilities <- c(0.7,0.4)
loss <- -mean(log(target_probabilities))
print(loss)
Sources
- Source 1arxiv.org
From the CodeSplash reference, entry LNG010.