Skip to content

Language models, retrieval, prompting, and language adaptation · Contextual and sentence encoders · LNG016 · Model

DistilBERT

Compresses a pretrained bidirectional encoder using knowledge distillation during pretraining. It targets lower latency and smaller storage while retaining transferable language representations;

Runs in CodeSplash Component demo, not a trained model CodeSplash's own run

In CodeSplash

A CodeSplash method runs this entry in Python and R. Set it up from the method's page.

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

Compresses a pretrained bidirectional encoder using knowledge distillation during pretraining. It targets lower latency and smaller storage while retaining transferable language representations; it is not simply a smaller randomly trained BERT.

Question / objective

Can a smaller encoder imitate a larger teacher while retaining useful representations?

Architecture / computational structure

A reduced-depth student is trained using teacher-distribution and representation-related losses together with language modeling. Learned student weights are parameters; teacher choice, temperature, and loss weights are hyperparameters.

Assumptions

The student inherits teacher biases and mistakes.

Formula / computational definition

LKD=T2KL⁡ ⁣(softmax⁡(zteacher/T) ∥ softmax⁡(zstudent/T)).\mathcal L_{\mathrm{KD}}=T^2\operatorname{KL}\!\left(\operatorname{softmax}(z_{\mathrm{teacher}}/T)\,\|\,\operatorname{softmax}(z_{\mathrm{student}}/T)\right).

Combine a teacher–student softened-probability loss with masked-language and representation-alignment terms. A representative distillation term is T^2 KL(p_teacher^T || p_student^T), where temperature T softens output distributions.

Parameters and notation

Learned parameters: identified in the architecture subsection. Hyperparameters, design and inference choices: Student depth, initialization, loss weights, distillation temperature, masking, tokenizer, and deployment precision.

Fitting, fine-tuning, and adaptation

Use a pretrained student or distill from a fixed teacher on suitable text. Fine-tune a task head, selectively unfreeze, or add supported adapters. Evaluate student accuracy and calibration against latency/memory targets; teacher errors and domain mismatch can be inherited.

How to use and calibrate

Measure downstream quality and calibrated confidence alongside batch-specific latency, memory, and energy when relevant. 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

Deploy contextual text classification on a device with limited inference resources.

Interpretation / pitfalls

Watch out

Relative accuracy retention is task-dependent; parameter reduction does not guarantee the same speedup on every hardware platform. 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 supports DistilBERT for inference and fine-tuning. R can use reticulate; a native distillation experiment needs a teacher, student, aligned token positions, and clearly specified loss coefficients.

Example scope: Temperature-scaled teacher/student KL component; omits other DistilBERT losses.

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.

Python

Component demo, not a trained model — Temperature-scaled teacher/student KL component; omits other DistilBERT losses.

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)
temperature = 2.0
teacher = softmax([x/temperature for x in [2,0,-1]])
student = softmax([x/temperature for x in [1,0.2,-0.5]])
loss = temperature**2 * sum(p * math.log(p/q) for p,q in zip(teacher,student))
print(loss)
R

Component demo, not a trained model — Temperature-scaled teacher/student KL component; omits other DistilBERT losses.

Shared setup for this chapter
softmax <- function(x) {
  shifted <- exp(x-max(x))
  shifted/sum(shifted)
}
temperature <- 2
teacher <- softmax(c(2,0,-1)/temperature)
student <- softmax(c(1,0.2,-0.5)/temperature)
print(temperature^2 * sum(teacher * log(teacher/student)))

Sources

From the CodeSplash reference, entry LNG016.