FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Client-Side Sentiment Classification with DistilBERT

Run a bounded text classifier in the browser, then use consent, uncertainty gates, and subgroup checks before showing a sentiment label.

Freshness: current•9 min read•Deep Learning and Specialized AI
Full Technical Reference Document

Mental model

Client-side sentiment classification runs a text model on the user’s device and returns a label such as positive or negative for a specific text and training domain. The output is a task estimate, not a reading of someone’s emotions. A safe feature requests the text explicitly, keeps inference local, exposes uncertainty, and never lets the label silently determine access or treatment.

Theory

A text classifier transforms a string into a fixed sequence of token IDs, adds an attention mask, and feeds those tensors through an encoder and a small classification head. The head emits one logit per label. A post-processing step converts the logits into normalized scores; the largest score selects the predicted class, but it does not prove that the label is correct or that it describes the author’s inner state.

A browser pipeline still has a deployment boundary. The JavaScript runtime and model weights may be downloaded from a host when the application first loads them. Once those assets are present, a local ONNX Runtime Web or Transformers.js pipeline can process the submitted text in the page or a worker without sending the inference input to a hosted model endpoint. That is a narrower privacy claim than “the feature is offline”: telemetry, analytics, crash reports, and the model download itself may still use the network. Verify the actual request path and keep raw text out of logs.

A reference checkpoint such as DistilBERT fine-tuned on SST-2 is an English binary classifier trained on movie-review text. Its model card reports task-specific evaluation and also shows that apparently neutral country-name substitutions can change its positive score substantially. That evidence is a warning about domain transfer and bias, not a measurement of how well the model reads a support message, employee comment, or an individual’s feelings. The model should label text for a bounded purpose, such as optional feedback triage, rather than decide how a person should be treated.

From logits to a reviewable result

For logits zkz_k and temperature TT, the softmax score for class kk is:

pk=exp⁡(zk/T)∑jexp⁡(zj/T)p_k=\frac{\exp(z_k/T)}{\sum_j \exp(z_j/T)}

Let p(1)p_{(1)} and p(2)p_{(2)} be the largest and second-largest scores. Their margin is Δ=p(1)−p(2)\Delta=p_{(1)}-p_{(2)}. Entropy H(p)=−∑kpkln⁡(pk)H(p)=-\sum_k p_k\ln(p_k) summarizes how spread out the scores are, in nats. Temperature scaling can improve calibration on a held-out set, but it cannot repair a dataset that does not represent the text being classified. A product can abstain unless the largest score exceeds a validated threshold τ\tau and the margin exceeds a separate threshold δ\delta.

For an illustrative two-class output with positive logit 1.4, negative logit 0.7, and T=1T=1, softmax gives approximately ppositive=0.668p_{positive}=0.668 and pnegative=0.332p_{negative}=0.332. The top-class margin is 0.336. If a feedback queue requires τ=0.80\tau=0.80 and δ=0.35\delta=0.35, this item is marked “uncertain” rather than sent to a positive or negative bucket. The numbers demonstrate the policy calculation; they are not a measured prediction for a particular sentence. Teams must choose thresholds from representative, consented data and assess the cost of both missed feedback and wrongly assigned labels.

Browser execution and privacy boundary

An explicit interaction should identify the text that will be analyzed, the purpose, and whether the result is stored. Keep the operation narrow: text typed into an optional feedback form is different from inferring tone from every message, keystroke, camera frame, or browsing event. Do not adapt themes, pricing, or access based on a passive sentiment estimate. If results are retained, record only the minimum data needed, define a deletion period, and make the user-facing action reversible.

Run the pipeline away from the main UI thread when model execution could delay typing or scrolling. Measure cold model download, first inference, warm latency, resident memory, and energy on representative devices. WebGPU can accelerate supported model operations, while WebAssembly may be more compatible for a small classifier; the runtime and model must actually support the selected backend. A compact quantized checkpoint reduces transfer and weight memory, but calibration and decision thresholds still require validation after quantization.

Explicit text and purpose
Tokenizer builds model inputs
Local encoder emits class logits
Softmax and uncertainty gate
Show, abstain, or discard result
Conceptual teaching model synthesized from:hf-transformers-js-docs,onnx-runtime-web-docs,hf-distilbert-sst2-model-card

Implementation example

This module-worker example loads a browser text-classification pipeline and accepts only explicitly consented text. It returns a result or abstains; it never posts the text to an inference service. The first model load may still download weights from Hugging Face, so a deployment that needs a strict network boundary should self-host and pin the model files, audit telemetry, and test offline behavior separately.

typescript
import { pipeline } from "@huggingface/transformers";
​
type Score = { label: string; score: number };
type Job = { requestId: string; text: string; consented: boolean };
​
const classify = await pipeline(
"text-classification",
"Xenova/distilbert-base-uncased-finetuned-sst-2-english",
{ dtype: "q8" },
);
​
self.addEventListener("message", async (event: MessageEvent<Job>) => {
const { requestId, text, consented } = event.data;
if (!consented) {
self.postMessage({ requestId, status: "rejected", reason: "consent_required" });
return;
}
const input = text.trim();
if (input.length < 3 || input.length > 600) {
self.postMessage({ requestId, status: "rejected", reason: "input_length" });
return;
}
​
try {
const scores = (await classify(input, { top_k: 2 })) as Score[];
const [best, second] = scores.slice().sort((a, b) => b.score - a.score);
if (!best || !second) throw new Error("classifier returned fewer than two labels");
const margin = best.score - second.score;
const status = best.score >= 0.80 && margin >= 0.35 ? "classified" : "uncertain";
self.postMessage({
requestId,
status,
label: status === "classified" ? best.label : null,
confidence: best.score,
margin,
});
} catch {
self.postMessage({ requestId, status: "unavailable", reason: "local_inference_failed" });
}
});

Failure modes and misconceptions

A score is an emotion meter. A binary text label only describes how a model ranks the input against its training labels. It cannot establish a person’s mood, intention, mental health, or sincerity. Show the label as an uncertain classification of submitted text and let the person correct or dismiss it.

High confidence means calibrated certainty. Neural classifiers can be confidently wrong on sarcasm, negation, short fragments, multilingual text, or a new product domain. A high average score on a movie-review benchmark does not establish performance on chat feedback. Measure reliability by data source and relevant groups, and tune a confidence gate on held-out examples before release.

Local inference removes all privacy risk. Local execution can prevent the message body from being sent to a model service, but it does not prevent a telemetry event from recording the text or the initial model request from revealing network metadata. Trace browser requests, disable text-bearing logs, and explain what model assets and diagnostics are fetched.

A two-label model can safely change the interface. A false negative may hide a complaint; a false positive may make a neutral message appear hostile. Never silently alter a user’s access, support priority, or interface because of the score. Keep an accessible non-AI route and allow explicit user feedback to override the classification.

Trade-offs

Quantizing weights and running locally can reduce transfer size and avoid inference charges, but available browser kernels, device memory, and operator support vary. A GPU backend may be faster for some models and slower to initialize for a short message. Benchmark the actual first-use and warm-use paths, and retain a CPU fallback only if its results and latency are separately checked.

Lower abstention thresholds classify more messages but also route more uncertain text into the wrong bucket. Higher thresholds protect against weak predictions while leaving more feedback unclassified. Choose a threshold against human review capacity and the relative cost of false positives and false negatives. Report coverage and error rates together so that an apparently accurate feature cannot hide that it declines difficult examples.

Decision scenario

A product team wants to infer whether a shopper is frustrated from every chat message and automatically switch the interface theme. A trial uses the English movie-review checkpoint, and short messages receive confident but inconsistent labels across wording changes. Do not enable passive inference or theme changes. If the team needs feedback triage, offer an explicit opt-in form, use a model evaluated on that text domain, abstain on ambiguous scores, and let users correct or skip the label. Keep message content out of analytics and review performance across language and demographic groups before any broader use.

Learning outcomes

  • Explain how tokenization, logits, softmax, and a confidence gate produce a bounded text-classification result.
  • Calculate the class margin and identify when a classifier should abstain.
  • Distinguish local inference from a fully offline or telemetry-free application.
  • Evaluate model-domain, subgroup, consent, and correction risks before using sentiment labels.
Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next