prompt-compressor / compressor.js
CiscoR's picture
In-browser multilingual prompt compression (transformers.js, int8 ONNX)
5489dfc verified
Raw History Blame Contribute Delete
21.7 kB
/**
* LLMLingua-2 prompt compression in JavaScript (transformers.js + ONNX Runtime Web).
*
* A port of compress.py from the Cis Labs Prompt Compressor Python Space, which re-implements the
* token-level path of llmlingua 0.2.2 `compress_prompt_llmlingua2` (token_to_word="mean", no
* context-level filter) for mBERT token classifiers whose label 1 = "keep":
*
* 1. Force tokens that are not a single word piece (in practice "\n") are replaced by the
* placeholder tokens [NEW0]..[NEW99] (i = position in `forceTokens`), as llmlingua does.
* 2. The text is tokenized once and cut into chunks of ~510 word pieces, preferably right after a
* chunk-end token ("." or the newline placeholder), with llmlingua's window (a chunk may hold
* 511 pieces, in which case the 512 limit cuts off [SEP]).
* 3. Each chunk goes through the classifier; keep-prob = softmax(logits)[..., 1].
* 4. Word pieces are merged into words: "##" continues the previous word, force tokens always
* start a new word, special pieces such as [UNK] are skipped. Word prob = mean of its piece
* probs, in float32 like numpy; force tokens get 1.0.
* 5. Per chunk, every word prob is repeated once per cl100k_base token of the word, and words
* strictly above numpy.percentile(probs, int(100 * (1 - rate) + 1)) are kept. The percentile
* reproduces numpy's float32 / float64 arithmetic bit for bit.
*
* Which words are kept matches compress.py and llmlingua. The output string restores the original
* spacing between kept words ("Hello, world.") instead of llmlingua's space-joined words.
*
* Usage:
* const pc = await PromptCompressor.load("Cis-Labs/prompt-compressor-bert-base-multilingual-cased");
* const res = await pc.compress(longPrompt, { rate: 0.5 });
* console.log(res.compressed, res.originTokens, "->", res.compressedTokens);
*/
import { AutoModelForTokenClassification, AutoTokenizer, Tensor, Tiktoken, env, loadCl100k } from "./deps.js";
export const MAX_SEQ_LEN = 512;
export const NEW_TOKENS = Array.from({ length: 100 }, (_, i) => `[NEW${i}]`);
export const DEFAULT_FORCE_TOKENS = Object.freeze(["\n", "?"]);
export const CHUNK_END_TOKENS = Object.freeze([".", "\n"]);
const f32 = Math.fround;
// Python's whitespace set (str.isspace, re "\s"), used by the output joiner and the highlighter.
const PY_WS = "\\t\\n\\x0b\\x0c\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
const PY_SPACE_ONLY = new RegExp(`^[${PY_WS}]+$`);
const PY_SPACE_CHAR = new RegExp(`^[${PY_WS}]$`);
const PY_RUNS = new RegExp(`[${PY_WS}]+|[^${PY_WS}]+`, "g");
// Scripts written without spaces between words: never insert a space when gluing them.
const NO_SPACE =
/^[฀-໿က-႟ក-៿ -ヿ㐀-䶿一-鿿豈-﫿＀-￯\u{20000}-\u{3ffff}]/u;
const DIGIT = /\p{Nd}/u; // Python re "\d" on str
const PUNCT_CATEGORY = /^\p{P}/u;
// BertNormalizer + BertPreTokenizer character classes, as the transformers.js tokenizer applies
// them. Used only to recover character offsets of word pieces (transformers.js returns none).
const TOK_WS = /^\s/;
const TOK_REMOVED = /^[\p{Cc}\p{Cf}\p{Co}\p{Cs}�]/u; // dropped by clean_text (except \t \n \r)
const TOK_PUNCT = /^[\p{P}!-/:-@[-`{-~]/u;
// CJK ideographs that BertNormalizer pads with spaces (ranges of the Rust tokenizers crate).
const isCJK = (c) =>
(c >= 0x4e00 && c <= 0x9fff) ||
(c >= 0x3400 && c <= 0x4dbf) ||
(c >= 0xf900 && c <= 0xfaff) ||
(c >= 0x20000 && c <= 0x2a6df) ||
(c >= 0x2a700 && c <= 0x2b81f) ||
(c >= 0x2b920 && c <= 0x2ceaf) ||
(c >= 0x2f800 && c <= 0x2fa1f);
// transformers.js only pads BMP ideographs; pad the supplementary-plane ones as the Rust tokenizer does.
const ASTRAL_CJK = /[\u{20000}-\u{2a6df}\u{2a700}-\u{2b81f}\u{2b920}-\u{2ceaf}\u{2f800}-\u{2fa1f}]/gu;
const padAstralCJK = (s) => (s.length > 1 && /[\ud840-\ud87e]/.test(s) ? s.replace(ASTRAL_CJK, " $& ") : s);
const charAt = (s, i) => String.fromCodePoint(s.codePointAt(i));
function charBefore(s, i) {
const lo = s.charCodeAt(i - 1);
if (i >= 2 && lo >= 0xdc00 && lo <= 0xdfff) {
const hi = s.charCodeAt(i - 2);
if (hi >= 0xd800 && hi <= 0xdbff) return s.slice(i - 2, i);
}
return s[i - 1];
}
const escapeRegExp = (s) => s.replace(/[\\^$.*+?()[\]{}|/]/g, "\\$&");
function removedLen(s, i) {
const c = s[i];
if (c === "\t" || c === "\n" || c === "\r") return 0;
const ch = charAt(s, i);
return TOK_REMOVED.test(ch) ? ch.length : 0;
}
/**
* Character spans (UTF-16, end-exclusive) of `tokens` in `text`. Pieces are verbatim substrings of
* the cleaned text (mBERT cased does no lowercasing or accent stripping), so a left-to-right scan
* that skips whitespace and characters removed by the normalizer recovers the same spans as the
* Rust tokenizer's offset mapping. [UNK] covers its whole pre-token.
*/
function alignPieces(text, tokens, unk, added) {
const n = text.length;
const spans = [];
let cursor = 0;
let misses = 0;
const skip = (i) => {
while (i < n) {
if (TOK_WS.test(text[i])) i += 1;
else {
const r = removedLen(text, i);
if (!r) break;
i += r;
}
}
return i;
};
for (const tok of tokens) {
const i = skip(cursor);
if (added.has(tok) && text.startsWith(tok, i)) {
spans.push([i, i + tok.length]);
cursor = i + tok.length;
continue;
}
if (tok === unk) {
let e = i;
if (i < n) {
const ch = charAt(text, i);
if (TOK_PUNCT.test(ch) || isCJK(ch.codePointAt(0))) e = i + ch.length;
else {
for (let j = i; j < n; ) {
const r = removedLen(text, j);
if (r) {
j += r;
continue;
}
const cj = charAt(text, j);
if (TOK_WS.test(cj) || TOK_PUNCT.test(cj) || isCJK(cj.codePointAt(0))) break;
j += cj.length;
e = j;
}
}
}
spans.push([i, e]);
cursor = e;
continue;
}
const t = tok.startsWith("##") ? tok.slice(2) : tok;
let j = 0;
let e = i;
let start = -1;
while (j < t.length && e < n) {
if (text.charCodeAt(e) === t.charCodeAt(j)) {
if (start < 0) start = e;
e += 1;
j += 1;
} else {
const r = start >= 0 ? removedLen(text, e) : 0;
if (!r) break;
e += r;
}
}
if (j === t.length && start >= 0) {
spans.push([start, e]);
cursor = e;
} else {
misses += 1; // should not happen; keep going with a best guess
const k = text.indexOf(t, cursor);
if (k >= 0) {
spans.push([k, k + t.length]);
cursor = k + t.length;
} else spans.push([i, i]);
}
}
return { spans, misses };
}
/** numpy.percentile(values, q) (method="linear"), in float32 when every value is float32. */
export function percentile(values, q, isFloat32) {
const a = Float64Array.from(values).sort();
const n = a.length;
const v = (n - 1) * (q / 100);
if (v >= n - 1) return a[n - 1];
if (v < 0) return a[0];
const lo = Math.floor(v);
const g = v - lo;
const x = a[lo];
const y = a[lo + 1];
if (isFloat32) {
const d = f32(y - x);
return g >= 0.5 ? f32(y - f32(d * f32(1 - g))) : f32(x + f32(d * f32(g)));
}
const d = y - x;
return g >= 0.5 ? y - d * (1 - g) : x + d * g;
}
function tokenCounter(enc) {
const cache = new Map();
if (enc) {
return (s) => {
let c = cache.get(s);
if (c === undefined) {
c = enc.encode(s, [], []).length; // disallowed_special=(): special tokens count as text
if (s.length < 64) cache.set(s, c);
}
return c;
};
}
// Fallback when the cl100k ranks cannot be loaded: crude word / punctuation count.
return (s) => (s.match(/[\p{L}\p{N}_]+|[^\p{L}\p{N}_\s]|\n/gu) || []).length;
}
const tokenOf = (v) => (typeof v === "string" ? v : v?.content);
export class PromptCompressor {
constructor(tokenizer, model, countTokens, info) {
this.tokenizer = tokenizer;
this.model = model;
this.countTokens = countTokens;
this.info = info;
const cfg = tokenizer.config ?? {};
const pick = (key, dflt) => tokenOf(cfg[key]) ?? dflt;
this.unkToken = pick("unk_token", "[UNK]");
// Special tokens as llmlingua sees them (taken before the [NEWi] placeholders are added).
this.specialTokens = new Set([
pick("cls_token", "[CLS]"),
pick("sep_token", "[SEP]"),
pick("pad_token", "[PAD]"),
this.unkToken,
pick("mask_token", "[MASK]"),
]);
this.addedTokens = new Set(tokenizer.all_special_tokens ?? []);
const [cls, sep] = tokenizer.convert_tokens_to_ids([pick("cls_token", "[CLS]"), pick("sep_token", "[SEP]")]);
this.clsId = cls;
this.sepId = sep;
const newIds = tokenizer.convert_tokens_to_ids(NEW_TOKENS);
this.placeholderIds = new Map(NEW_TOKENS.map((t, i) => [t, newIds[i]]));
}
/**
* Load tokenizer, ONNX model and token counter.
* @param {string} modelId Hub repo id, or a same-origin path to a folder with the same layout.
* @param {object} [opts]
* @param {"auto"|"webgpu"|"wasm"} [opts.device="auto"] "auto" = WebGPU for float weights when an adapter is
* available, else WebAssembly. int8 graphs (q8) run their integer matmuls on the CPU even under WebGPU, so
* "auto" uses multi-threaded WebAssembly for them (threads need a cross-origin-isolated page).
* @param {string} [opts.dtype="q8"] "q8" loads onnx/model_quantized.onnx, "fp32" onnx/model.onnx.
* @param {(info: object) => void} [opts.progress_callback] transformers.js download progress.
*/
static async load(modelId, { device = "auto", dtype = "q8", progress_callback = null } = {}) {
if (/^(\.{0,2}\/|https?:)/.test(modelId)) {
env.allowLocalModels = true; // a folder served next to the page (testing before release)
env.allowRemoteModels = false;
}
const ranksPromise = loadCl100k().catch(() => null);
const tokenizer = await AutoTokenizer.from_pretrained(modelId, { progress_callback });
let devices = [device];
if (device === "auto") {
let adapter = null;
if (!["q8", "int8", "uint8"].includes(dtype)) {
try {
adapter = await globalThis.navigator?.gpu?.requestAdapter();
} catch {
adapter = null;
}
}
devices = adapter ? ["webgpu", "wasm"] : ["wasm"];
}
let model = null;
let used = null;
let lastError = null;
for (const d of devices) {
try {
model = await AutoModelForTokenClassification.from_pretrained(modelId, { device: d, dtype, progress_callback });
used = d;
break;
} catch (err) {
lastError = err;
}
}
if (!model) throw lastError;
const ranks = await ranksPromise;
const counter = ranks ? tokenCounter(new Tiktoken(ranks)) : tokenCounter(null);
const info = {
modelId,
device: used,
dtype,
tokenCounter: ranks ? "cl100k_base" : "approx",
threads: used === "wasm" ? (env.backends?.onnx?.wasm?.numThreads ?? null) : null,
};
const pc = new PromptCompressor(tokenizer, model, counter, info);
if (pc.placeholderIds.get(NEW_TOKENS[0]) === undefined || pc.placeholderIds.get(NEW_TOKENS[0]) === null) {
throw new Error(`${modelId}: tokenizer has no [NEW0] token (needed for the newline force token)`);
}
return pc;
}
// -- steps ------------------------------------------------------------------------------------
_pieces(text, tokenMap) {
const parts = [];
let pos = 0;
if (tokenMap.size) {
const re = new RegExp([...tokenMap.keys()].map(escapeRegExp).join("|"), "g");
for (const m of text.matchAll(re)) {
if (m.index > pos) parts.push([pos, m.index, null]);
parts.push([m.index, m.index + m[0].length, tokenMap.get(m[0])]);
pos = m.index + m[0].length;
}
}
if (pos < text.length) parts.push([pos, text.length, null]);
const pieces = [];
let misses = 0;
for (const [s, e, ph] of parts) {
if (ph !== null) {
pieces.push([ph, this.placeholderIds.get(ph), s, e]);
continue;
}
const sub = text.slice(s, e);
const toks = this.tokenizer.tokenize(padAstralCJK(sub));
const ids = this.tokenizer.convert_tokens_to_ids(toks);
const al = alignPieces(sub, toks, this.unkToken, this.addedTokens);
misses += al.misses;
for (let k = 0; k < toks.length; k++) pieces.push([toks[k], ids[k], s + al.spans[k][0], s + al.spans[k][1]]);
}
this._alignMisses = misses;
return pieces;
}
static _chunks(pieces, endTokens) {
const maxLen = MAX_SEQ_LEN - 2;
const out = [];
const n = pieces.length;
let st = 0;
while (st < n) {
if (n - st <= maxLen) {
out.push([st, n]);
break;
}
const ed = st + maxLen; // llmlingua's window: up to 511 pieces
let cut = null;
for (let j = ed; j > st; j--) {
if (endTokens.has(pieces[j][0])) {
cut = j;
break;
}
}
if (cut === null) {
// no sentence end: cut between words (llmlingua may split one)
cut = ed;
while (cut > st && cut + 1 < n && pieces[cut + 1][0].startsWith("##")) cut -= 1;
if (!(cut > st)) cut = ed;
}
out.push([st, cut + 1]);
st = cut + 1;
}
return out;
}
async _keepProbs(chunkIds, onProgress) {
const out = [];
for (let c = 0; c < chunkIds.length; c++) {
const ids = chunkIds[c];
const row = [this.clsId, ...ids, this.sepId].slice(0, MAX_SEQ_LEN);
const L = row.length;
const inputIds = new Tensor("int64", BigInt64Array.from(row, (x) => BigInt(x)), [1, L]);
const mask = new Tensor("int64", new BigInt64Array(L).fill(1n), [1, L]);
const types = new Tensor("int64", new BigInt64Array(L), [1, L]);
const { logits } = await this.model({ input_ids: inputIds, attention_mask: mask, token_type_ids: types });
const data = logits.data;
const nl = logits.dims[2];
const p = new Float64Array(ids.length);
for (let i = 0; i < ids.length; i++) {
const o = (i + 1) * nl;
let mx = -Infinity;
for (let k = 0; k < nl; k++) mx = Math.max(mx, data[o + k]);
let sum = 0;
for (let k = 0; k < nl; k++) sum += Math.exp(data[o + k] - mx);
p[i] = f32(Math.exp(data[o + 1] - mx) / sum);
}
logits.dispose?.();
out.push(p);
onProgress?.({ done: c + 1, total: chunkIds.length });
}
return out;
}
_merge(pieces, probs, forceSet, placeholders, forceDigit) {
// llmlingua __merge_token_to_word + mean __token_prob_to_word_prob. Probabilities stay float32
// like numpy's; a forced word's 1.0 is a Python float, which decides the percentile dtype.
const words = [];
const wp = [];
for (let k = 0; k < pieces.length; k++) {
const [tok, , a, b] = pieces[k];
const p = probs[k];
if (this.specialTokens.has(tok)) continue;
const pure = tok.replace(/^#+/, "");
const forced = forceSet.has(pure) || placeholders.has(pure);
if (forced || !tok.startsWith("##") || !words.length) {
const orig = placeholders.get(tok) ?? tok;
const isOne = forced || (forceDigit && DIGIT.test(orig));
words.push({ start: a, end: b, pieceText: orig, prob: 0, keep: false, f32: true });
wp.push([[isOne ? 1 : p, !isOne]]);
} else {
const w = words[words.length - 1];
w.end = b;
w.pieceText += pure;
const isOne = forceDigit && DIGIT.test(tok);
wp[wp.length - 1].push([isOne ? 1 : p, !isOne]);
}
}
for (let k = 0; k < words.length; k++) {
let s = 0;
let anyF32 = false;
for (const [v, isF32] of wp[k]) {
s = f32(s + v);
anyF32 = anyF32 || isF32;
}
const n = wp[k].length;
words[k].prob = anyF32 ? f32(s / n) : s / n;
words[k].f32 = anyF32;
}
return words;
}
_select(words, reduceRate) {
if (reduceRate <= 0) {
for (const w of words) w.keep = true;
return;
}
const weighted = [];
let allF32 = true;
for (const w of words) {
const n = this.countTokens(w.pieceText);
for (let i = 0; i < n; i++) weighted.push(w.prob);
if (n > 0 && !w.f32) allF32 = false;
}
if (!weighted.length) return;
const thr = percentile(weighted, Math.min(100, Math.trunc(100 * reduceRate + 1)), allF32);
for (const w of words) w.keep = w.prob > thr || (thr === 1 && w.prob === thr);
}
// -- public API -------------------------------------------------------------------------------
/**
* Keep roughly `rate` of the GPT tokens of `text` (llmlingua `compress_prompt` semantics).
* @returns {Promise<{text: string, compressed: string, words: object[], originTokens: number,
* compressedTokens: number, rate: number, ratio: number, nChunks: number, truncated: boolean,
* latencyMs: number}>}
*/
async compress(
text,
{
rate = 0.5,
forceTokens = DEFAULT_FORCE_TOKENS,
forceReserveDigit = false,
chunkEndTokens = CHUNK_END_TOKENS,
targetToken = -1,
maxInputTokens = null,
onProgress = null,
} = {},
) {
const t0 = performance.now();
text = text.replaceAll("\r\n", "\n");
forceTokens = [...forceTokens].filter((t) => t.length > 0);
if (forceTokens.length > NEW_TOKENS.length) throw new Error(`at most ${NEW_TOKENS.length} force tokens`);
const tokenMap = new Map();
forceTokens.forEach((t, i) => {
if (this.tokenizer.tokenize(t).length !== 1) tokenMap.set(t, NEW_TOKENS[i]); // dict semantics, as in Python
});
const placeholders = new Map([...tokenMap].map(([k, v]) => [v, k]));
const endTokens = new Set(chunkEndTokens);
for (const c of chunkEndTokens) if (tokenMap.has(c)) endTokens.add(tokenMap.get(c));
let pieces = this._pieces(text, tokenMap);
const truncated = Boolean(maxInputTokens) && pieces.length > maxInputTokens;
if (truncated) {
// cut before a word start so no word is split
let k = maxInputTokens;
while (k > 0 && pieces[k][0].startsWith("##")) k -= 1;
text = text.slice(0, pieces[k][2]);
pieces = pieces.slice(0, k);
}
const originTokens = this.countTokens(text);
if (targetToken > 0) rate = Math.min(targetToken / Math.max(1, originTokens), 1.0);
const reduceRate = Math.max(0, 1 - rate);
const chunks = PromptCompressor._chunks(pieces, endTokens);
let probs;
if (reduceRate > 0) {
probs = await this._keepProbs(
chunks.map(([s, e]) => pieces.slice(s, e).map((p) => p[1])),
onProgress,
);
} else {
probs = chunks.map(([s, e]) => new Float64Array(e - s).fill(1)); // llmlingua skips the model
}
const words = [];
const forceSet = new Set(forceTokens);
chunks.forEach(([s, e], i) => {
const cw = this._merge(pieces.slice(s, e), probs[i], forceSet, placeholders, forceReserveDigit);
this._select(cw, reduceRate);
words.push(...cw);
});
const compressed = joinKept(text, words.filter((w) => w.keep));
const compressedTokens = this.countTokens(compressed);
return {
text,
compressed,
words: words.map(({ start, end, pieceText, prob, keep }) => ({ start, end, pieceText, prob, keep })),
originTokens,
compressedTokens,
rate: compressedTokens / Math.max(1, originTokens),
ratio: originTokens / Math.max(1, compressedTokens),
nChunks: chunks.length,
nPieces: pieces.length,
truncated,
latencyMs: performance.now() - t0,
alignMisses: this._alignMisses,
};
}
}
/** Re-join kept words, reusing the original whitespace where it still applies. */
export function joinKept(text, kept) {
const out = [];
for (let i = 0; i < kept.length; i++) {
if (i > 0) out.push(separator(text, kept[i - 1], kept[i]));
out.push(text.slice(kept[i].start, kept[i].end));
}
return out.join("");
}
function separator(text, a, b) {
if (text.slice(a.start, a.end) === "\n" || text.slice(b.start, b.end) === "\n") return ""; // a kept newline carries the break
const gap = text.slice(a.end, b.start);
if (!gap) return ""; // e.g. "world" + "," or adjacent CJK characters
if (PY_SPACE_ONLY.test(gap)) return gap.includes("\n") ? " " : gap; // unforced newlines collapse, as in llmlingua
if (PY_SPACE_CHAR.test(gap[gap.length - 1])) return " ";
if (NO_SPACE.test(charBefore(text, a.end)) || NO_SPACE.test(charAt(text, b.start))) return "";
// b was glued to dropped text on its left: no space before punctuation ("Hi Anna," -> "Hi,")
return PUNCT_CATEGORY.test(charAt(text, b.start)) ? "" : " ";
}
/** [text, "kept" | "dropped" | null] runs covering the whole input, for highlighting. */
export function segments({ text, words }) {
const out = [];
const add = (s, lab) => {
if (!s) return;
if (out.length && out[out.length - 1][1] === lab) out[out.length - 1][0] += s;
else out.push([s, lab]);
};
const addGap = (gap) => {
// whitespace stays unlabelled; skipped [UNK] pieces were dropped
for (const m of gap.matchAll(PY_RUNS)) add(m[0], PY_SPACE_ONLY.test(m[0]) ? null : "dropped");
};
let pos = 0;
let prev = null;
for (const w of words) {
const lab = w.keep ? "kept" : "dropped";
const gap = text.slice(pos, w.start);
if (gap && PY_SPACE_ONLY.test(gap) && prev === lab) add(gap, lab); // one run for "word word word"
else addGap(gap);
add(text.slice(w.start, w.end), lab);
pos = w.end;
prev = lab;
}
addGap(text.slice(pos));
return out;
}