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

Offline Summarization in the Browser

Generate browser-local summaries with token-bounded chunks, quantized models, progressive reduction, and explicit checks for context and output quality.

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

Mental model

Offline summarization runs a downloaded encoder-decoder model inside the browser, so document text can stay on the device after model assets are available. Long input still has to fit the model's source-token window: split by the model tokenizer, summarize pieces sequentially, then reduce those summaries through a bounded final pass.

Learning outcomes

  • Calculate the number of source windows from token count, model input budget, and overlap.
  • Implement sequential map-reduce summarization without confusing character count with tokenizer length.
  • Separate first-use model download from offline inference, and validate generated claims against the original text.

Theory

Token budgets and map-reduce

Transformers.js exposes a summarization pipeline that accepts one or more articles and returns summary text. The pipeline uses the model tokenizer, which is also available for counting and decoding token IDs. The official Xenova/distilbart-cnn-6-6 configuration sets max_position_embeddings to 1,024; this lesson uses a conservative 900-token source window to leave room for special tokens and tokenizer details. Re-check the selected model's configuration before changing that budget. Nine hundred characters is not the same limit: punctuation, code, URLs, and languages tokenize at different rates.

For a document larger than the source window, tokenize once and form windows from token IDs. A small overlap preserves some context where one piece ends and the next begins; after per-window generation, a reducer summarizes the partials into a single result. This is a map-reduce pattern over text, not an exact merge: overlapping facts may repeat, and an intermediate summary can discard a caveat needed later.

The window count is:

Nchunks=1+⌈max⁡(0,T−L)L−O⌉N_{\text{chunks}}=1+\left\lceil\frac{\max(0,T-L)}{L-O}\right\rceil

T is source length in tokenizer tokens, L is the model input budget in tokens, O is overlap in tokens, and N_chunks is the resulting number of model calls in the map pass. With T = 9,000, L = 900, and O = 64, the stride is 836 tokens and the formula yields 11 chunks. Ten seams repeat up to 640 tokens; at a 72-token generation cap, the partial summaries contain at most 792 generated tokens before the final reducer. The loop re-tokenizes the partials because their joined text can still exceed the same input budget.

Keep the pipeline bounded

Model loading has a separate cost from generation. The first use must fetch the tokenizer, ONNX weights, and runtime assets; browser caching can make later runs local, but storage eviction or an incomplete first download can break an offline session. Load the pipeline only when the user opens the local summarizer, report whether model assets are ready, and offer a clear download or fallback path before promising offline use.

The code below is intended for a dedicated worker module. It loads one quantized pipeline, caps document and generation sizes, and processes windows sequentially so temporary activations and partial outputs do not accumulate from concurrent model calls. Transformers.js defaults browser inference to WebAssembly; switching to device: "webgpu" requires testing that browser and model path. ONNX Runtime Web offers WebGPU and WASM providers, but GPU support is limited to supported operators, so a successful GPU request does not prove that all work used the GPU.

typescript
import { pipeline } from "@huggingface/transformers";
​
const MODEL_ID = "Xenova/distilbart-cnn-6-6";
const MAX_SOURCE_TOKENS = 900;
const OVERLAP_TOKENS = 64;
const MAX_DOCUMENT_TOKENS = 12_000;
let summarizerPromise: ReturnType<typeof pipeline> | undefined;
​
function getSummarizer() {
return (summarizerPromise ??= pipeline("summarization", MODEL_ID, { dtype: "q8" }));
}
​
function tokenWindows(ids: number[]): number[][] {
const stride = MAX_SOURCE_TOKENS - OVERLAP_TOKENS;
const windows: number[][] = [];
for (let start = 0; start < ids.length; start += stride) {
windows.push(ids.slice(start, start + MAX_SOURCE_TOKENS));
}
return windows;
}
​
export async function summarizeLocal(document: string) {
if (!document.trim()) throw new Error("document is empty");
const summarizer = await getSummarizer();
let current = document;
let passes = 0;
​
while (summarizer.tokenizer.encode(current, { add_special_tokens: false }).length >
MAX_SOURCE_TOKENS) {
const ids = summarizer.tokenizer.encode(current, { add_special_tokens: false });
if (ids.length > MAX_DOCUMENT_TOKENS || passes === 3) {
throw new RangeError("document exceeds the local summarization budget");
}
const partials: string[] = [];
for (const window of tokenWindows(ids)) {
const text = summarizer.tokenizer.decode(window, { skip_special_tokens: true });
const result = await summarizer(text, { max_new_tokens: 72, do_sample: false });
partials.push(result[0].summary_text);
}
current = partials.join("\n");
passes += 1;
}
​
const finalResult = await summarizer(current, { max_new_tokens: 128, do_sample: false });
return { summary: finalResult[0].summary_text, passes, modelId: MODEL_ID };
}
​
export async function releaseSummarizer() {
const current = summarizerPromise;
if (current) await (await current).dispose();
if (summarizerPromise === current) summarizerPromise = undefined;
}

The pipeline is initialized lazily when the first summarization request arrives; a worker should serialize requests and call releaseSummarizer() only after in-flight work finishes. Clearing the cached promise allows a later request in the same worker to create a fresh pipeline after disposal. The source text is processed locally by this worker, but the initial model fetch still contacts the model host unless the assets are already cached or bundled. A local inference path should not post the input to application APIs or analytics. Keep the original passage and source location alongside the summary: generated text is a lossy view, not a new authority.

Trade-offs

An 8-bit model variant can reduce weight transfer and memory relative to a full-precision variant, at the cost of possible quality drift that must be measured on representative summaries. A smaller model can be usable on more devices but may omit numbers or qualifiers more often. WebGPU can help some workloads; WASM is the broad browser baseline and may be preferable on unsupported devices or for small inputs.

Sequential windows bound active inference work and make progress reporting straightforward, but they increase wall-clock time compared with unconstrained parallel calls. More overlap preserves boundary context while repeating tokens and computation. A worker protects the UI thread but does not eliminate memory pressure: model weights remain resident, and the tokenizer, partial summaries, and generated output also occupy memory.

Failure modes and misconceptions

FailureWhy it happensHandling
Input overflows the encoder windowCharacter slicing does not predict model-token lengthTokenize, window below the configured input limit, and re-check reducer text
The app claims offline support before the first model download completesWeight, tokenizer, or runtime assets are still missingPreload and verify assets while online; expose a no-model fallback
All chunks run concurrently on a phoneEach call can allocate activations while weights stay residentUse sequential or small bounded concurrency and enforce an input-token cap
The summary invents or drops a conditionAbstractive generation is not a source-preserving transformKeep the source, validate key facts, and label summaries as derived text
WebGPU initialization fails or falls backBrowser/device support and operator coverage varyKeep a tested WASM path and record the backend actually used

Chunk overlap is not a factual guarantee, and quantization is not quality-neutral. If the output is used for medical, legal, or policy decisions, this pipeline needs domain evaluation and review; a fluent summary alone cannot pass that gate. For general notes, compare extracted names, dates, quantities, and negations against the original, and preserve citations at the chunk level rather than attaching one citation to a summary that combines several passages.

Decision scenario

A user pastes a 9,000-token field report and expects to summarize it during a later train ride with no network. With the example's 900-token source budget and 64-token overlap, process 11 map windows sequentially; each emits at most 72 new tokens, then a re-tokenized reducer produces the final summary. The device has not downloaded the model yet, so the app must offer the download while online and verify all required files before the trip. If the model is unavailable offline, preserve the report and show a local-only unavailable state rather than uploading it silently.

Cache model and tokenizer
Count source tokens
Summarize bounded windows
Reduce partial summaries
Validate output against source
Conceptual teaching model synthesized from:transformers-js-pipelines-docs,hf-transformers-js-docs,onnx-runtime-web-docs,xenova-distilbart-cnn-config
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