///
import type { InferenceSession } from "onnxruntime-web";
import { fetchManifest, selectVariant } from "./manifest";
import { loadOrt } from "./ort";
import { fetchVerified } from "./fetch";
import { clampTemperature, confidenceFromProbabilities, padPrepared, prepareQuestion, tempBucket, type PreparedQuestion, type TokenizerLike } from "./preprocess";
import type { WorkerRequest, WorkerResponse } from "./protocol";
import type { LayaAnswer, ExecutionBackend, ModelManifest, WeightPrecision } from "./shared/types";
let manifest: ModelManifest | undefined;
let session: InferenceSession | undefined;
let tokenizer: TokenizerLike | undefined;
let backend: ExecutionBackend = "webgpu";
let precision: WeightPrecision = "fp32";
let loadMs = 0;
let stage = "worker startup";
const send = (message: WorkerResponse) => {
if (message.type === "progress") stage = message.progress.phase;
self.postMessage(message);
};
const relative = (path: string, base: string) => new URL(path, base).href;
async function hasShaderF16(): Promise {
const gpu = (navigator as Navigator & { gpu?: { requestAdapter(): Promise<{ features: Set } | null> } }).gpu;
if (!gpu) return false;
const adapter = await gpu.requestAdapter();
return adapter?.features.has("shader-f16") ?? false;
}
async function load(request: Extract) {
const started = performance.now();
send({ id: request.id, type: "progress", progress: { phase: "manifest", loaded: 0 } });
backend = request.backend;
if (backend === "webgpu") {
const gpu = (navigator as Navigator & { gpu?: { requestAdapter(): Promise } }).gpu;
if (!gpu || !(await gpu.requestAdapter())) throw new Error("WebGPU is unavailable: this browser has no usable GPU adapter. Select WASM (CPU) to run without a GPU.");
}
manifest = await fetchManifest(request.manifestUrl, request.model);
const selected = selectVariant(manifest, backend, request.precision, backend === "webgpu" && await hasShaderF16());
precision = selected.precision;
const variant = selected.variant;
send({ id: request.id, type: "progress", progress: { phase: "runtime", loaded: 0 } });
const ort = await loadOrt(backend);
send({ id: request.id, type: "progress", progress: { phase: "tokenizer", loaded: 0 } });
const tokenizerJson = new TextDecoder().decode(await fetchVerified(relative(manifest.tokenizer.path, request.manifestUrl), manifest.tokenizer.sha256));
const tokenizerConfig = manifest.tokenizer.configPath
? JSON.parse(new TextDecoder().decode(await fetchVerified(relative(manifest.tokenizer.configPath, request.manifestUrl), manifest.tokenizer.configSha256)))
: {};
const tokenizers = await import("@huggingface/tokenizers");
const tokenizerInstance = new tokenizers.Tokenizer(JSON.parse(tokenizerJson), tokenizerConfig);
tokenizer = {
encode(text, options = {}) {
const encoded = tokenizerInstance.encode(text, { add_special_tokens: options.add_special_tokens ?? false });
return { ids: encoded.ids, attention_mask: encoded.attention_mask };
},
};
const graph = await fetchVerified(relative(variant.graph, request.manifestUrl), variant.graphSha256, (progress) => send({ id: request.id, type: "progress", progress }));
const externalData = await Promise.all((variant.externalData ?? []).map(async (file) => ({
path: file.location ?? file.path,
data: new Uint8Array(await fetchVerified(relative(file.path, request.manifestUrl), file.sha256, (progress) => send({ id: request.id, type: "progress", progress }))),
})));
send({ id: request.id, type: "progress", progress: { phase: "session", loaded: 0 } });
session = await ort.InferenceSession.create(new Uint8Array(graph), { executionProviders: [backend], externalData });
loadMs = performance.now() - started;
send({ id: request.id, type: "progress", progress: { phase: "ready", loaded: 1, total: 1 } });
}
function softmax(values: number[]): number[] {
const max = Math.max(...values);
const exps = values.map((value) => Math.exp(value - max));
const total = exps.reduce((sum, value) => sum + value, 0);
return exps.map((value) => value / total);
}
async function runBatch(batch: PreparedQuestion[]): Promise {
if (!manifest || !session) throw new Error("Model is not loaded");
const ort = await loadOrt(backend);
const padded = padPrepared(batch, manifest.specialTokens.padId);
const i64 = (values: number[], dimensions: number[]) => new ort.Tensor("int64", BigInt64Array.from(values.map(BigInt)), dimensions);
const feeds = {
input_ids: i64(padded.inputIds, [padded.dimensions.batch, padded.dimensions.sequence]),
attention_mask: i64(padded.attentionMask, [padded.dimensions.batch, padded.dimensions.sequence]),
marker_pos: i64(padded.markerPositions, [padded.dimensions.batch, padded.dimensions.options]),
marker_mask: new ort.Tensor("bool", Uint8Array.from(padded.markerMask), [padded.dimensions.batch, padded.dimensions.options]),
qtype: i64(padded.questionTypes, [padded.dimensions.batch]),
};
const outputs = await session.run(feeds);
const logits = Array.from(outputs.logits.data as Float32Array);
const acts = Array.from(outputs.act_probs.data as Float32Array);
const actWidth = Number(outputs.act_probs.dims[1] ?? 1);
return batch.map((item, index) => {
const count = item.optionLabels.length;
const fallback = manifest!.calibration?.temperature?.[item.questionType] ?? 1;
const temperature = clampTemperature(manifest!.calibration?.temperatureByOptions?.[tempBucket(item.type, count)] ?? fallback);
const probabilities = softmax(logits.slice(index * padded.dimensions.options, index * padded.dimensions.options + count).map((value) => value / temperature));
const winner = probabilities.indexOf(Math.max(...probabilities));
const rounded = probabilities.map((value) => Math.round(value * 1e4) / 1e4);
const base = { distribution: rounded, probabilities: Object.fromEntries(item.optionLabels.map((key, option) => [key, rounded[option] ?? 0])), action: { act_probability: Math.round((acts[index * actWidth] ?? 0) * 1e4) / 1e4 }, usage: item.usage };
if (item.type === "choice") { const choice = item.optionLabels[winner] ?? ""; return { ...base, type: "choice" as const, answer: choice, choice, confidence: Math.round(confidenceFromProbabilities(probabilities) * 1e4) / 1e4 }; }
if (item.type === "score") { const score = Math.round(probabilities.reduce((sum, value, option) => sum + value * option, 0) * 1e4) / 1e4; return { ...base, type: "score" as const, answer: score, score, legend: Object.fromEntries((item.criteria as unknown[]).map((value, option) => [String(option), value])), confidence: Math.round(confidenceFromProbabilities(probabilities) * 1e4) / 1e4 }; }
const noul = rounded[1] ?? 0; return { ...base, type: "noul" as const, answer: noul >= 0.5, noul, confidence: Math.round(Math.max(noul, 1 - noul) * 1e4) / 1e4 };
});
}
async function infer(request: Extract) {
if (!manifest || !tokenizer) throw new Error("Model is not loaded");
const prepared = await Promise.all(request.questions.map(({ id, question }) => prepareQuestion(tokenizer!, manifest!, request.state, id, question)));
const started = performance.now();
const answers: LayaAnswer[] = [];
const size = manifest.maxQuestionsPerBatch ?? 4;
for (let offset = 0; offset < prepared.length; offset += size) answers.push(...await runBatch(prepared.slice(offset, offset + size)));
const answerMap = Object.fromEntries(answers.map((answer, index) => [prepared[index]!.id, answer]));
send({ id: request.id, type: "result", result: {
model: "laya-rl-agent", answers: answerMap,
usage: { input_tokens: prepared.reduce((sum, item) => sum + item.usage.inputTokens, 0), output_tokens: 0 },
diagnostics: { model: manifest.model, checkpoint: manifest.checkpoint, precision, backend, loadMs, inferenceMs: performance.now() - started, batches: Math.ceil(prepared.length / size) },
} });
}
// Keep load, inference, and release ordered even if the caller posts concurrently.
let requests: Promise = Promise.resolve();
self.addEventListener("message", (event: MessageEvent) => {
const request = event.data;
requests = requests.then(async () => {
try {
if (request.type === "ping") send({ id: request.id, type: "ready" });
else if (request.type === "load") {
if (session) throw new Error("Worker already owns a session; create a new worker to change models");
await load(request); send({ id: request.id, type: "loaded" });
} else if (request.type === "infer") { stage = "inference"; await infer(request); }
else {
stage = "shutdown";
await session?.release(); session = undefined; tokenizer = undefined; manifest = undefined;
send({ id: request.id, type: "closed" });
}
} catch (error) {
send({ id: request.id, type: "error", code: request.type === "load" || request.type === "ping" ? "LOAD_FAILED" : "INFERENCE_FAILED", stage,
message: error instanceof Error ? error.message : `ONNX Runtime error: ${String(error)}` });
}
});
});