Spaces:
Configuration error
Configuration error
Update src/worker.js
Browse files7 unmodified lines891011121314151617181920213 unmodified lines2526272829303114 unmodified lines464748495051525354555657583 unmodified lines626364656667686970717210 unmodified lines83848586878889909192939495969798991005 unmodified lines1061071081091101111123 unmodified lines1161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651667 unmodified lines/*** Helper function to perform feature detection for WebGPU*/// let fp16_supported = false;async function check() {try {const adapter = await navigator.gpu.requestAdapter();if (!adapter) {throw new Error("WebGPU is not supported (no adapter found)");}// fp16_supported = adapter.features.has("shader-f16")} catch (e) {self.postMessage({status: "error",3 unmodified lines}/*** This class uses the Singleton pattern to enable lazy-loading of the pipeline*/class TextGenerationPipeline {static model_id = "HuggingFaceTB/SmolLM2-1.7B-Instruct";14 unmodified lines}const stopping_criteria = new InterruptableStoppingCriteria();let past_key_values_cache = null;async function generate(messages) {// Retrieve the text-generation pipeline.const [tokenizer, model] = await TextGenerationPipeline.getInstance();const inputs = tokenizer.apply_chat_template(messages, {add_generation_prompt: true,return_dict: true,});3 unmodified lineslet tps;const token_callback_function = () => {startTime ??= performance.now();if (numTokens++ > 0) {tps = (numTokens / (performance.now() - startTime)) * 1000;}};const callback_function = (output) => {self.postMessage({status: "update",10 unmodified linestoken_callback_function,});// Tell the main thread we are startingself.postMessage({ status: "start" });const { past_key_values, sequences } = await model.generate({...inputs,past_key_values: past_key_values_cache,// Sampling// do_sample: true,// top_k: 3,// temperature: 0.2,max_new_tokens: 1024,streamer,stopping_criteria,5 unmodified linesskip_special_tokens: true,});// Send the output back to the main threadself.postMessage({status: "complete",output: decoded,3 unmodified linesasync function load() {self.postMessage({status: "loading",data: "Loading model...",});// Load the pipeline and save it for future use.const [tokenizer, model] = await TextGenerationPipeline.getInstance((x) => {// We also add a progress callback to the pipeline so that we can// track model loading.self.postMessage(x);});self.postMessage({status: "loading",data: "Compiling shaders and warming up model...",});// Run model with dummy input to compile shadersconst inputs = tokenizer("a");await model.generate({ ...inputs, max_new_tokens: 1 });self.postMessage({ status: "ready" });}// Listen for messages from the main threadself.addEventListener("message", async (e) => {const { type, data } = e.data;switch (type) {case "check":check();break;case "load":load();break;case "generate":stopping_criteria.reset();generate(data);break;case "interrupt":stopping_criteria.interrupt();break;case "reset":past_key_values_cache = null;stopping_criteria.reset();break;}});7 unmodified lines89101112131415161718193 unmodified lines2324252627282914 unmodified lines444546474849505152535455565758596061626364653 unmodified lines697071727374757677787910 unmodified lines909192939495969798991005 unmodified lines1061071081091101113 unmodified lines1151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551567 unmodified lines/*** Helper function to perform feature detection for WebGPU*/async function check() {try {const adapter = await navigator.gpu.requestAdapter();if (!adapter) {throw new Error("WebGPU is not supported (no adapter found)");}} catch (e) {self.postMessage({status: "error",3 unmodified lines}/*** Singleton class for model loading*/class TextGenerationPipeline {static model_id = "HuggingFaceTB/SmolLM2-1.7B-Instruct";14 unmodified lines}const stopping_criteria = new InterruptableStoppingCriteria();let past_key_values_cache = null;async function generate(messages) {// --- MEDICAL ASSISTANT CONFIGURATION ---const systemPrompt = {role: "system",content: "You are a professional Emergency Room (ER) Medical Assistant. Your role is to assist physicians by providing triage classifications, suggesting immediate clinical actions based on ABCDE/ACLS protocols, and summarizing patient history using medical terminology. Be concise, objective, and prioritize life-threatening conditions. Always maintain a clinical tone."};// Inject the system prompt at the beginning of the conversationconst messagesWithSystem = [systemPrompt, ...messages];// ---------------------------------------const [tokenizer, model] = await TextGenerationPipeline.getInstance();const inputs = tokenizer.apply_chat_template(messagesWithSystem, {add_generation_prompt: true,return_dict: true,});3 unmodified lineslet tps;const token_callback_function = () => {startTime ??= performance.now();if (numTokens++ > 0) {tps = (numTokens / (performance.now() - startTime)) * 1000;}};const callback_function = (output) => {self.postMessage({status: "update",10 unmodified linestoken_callback_function,});self.postMessage({ status: "start" });const { past_key_values, sequences } = await model.generate({...inputs,past_key_values: past_key_values_cache,max_new_tokens: 1024,streamer,stopping_criteria,5 unmodified linesskip_special_tokens: true,});self.postMessage({status: "complete",output: decoded,3 unmodified linesasync function load() {self.postMessage({status: "loading",data: "Loading medical assistant model...",});const [tokenizer, model] = await TextGenerationPipeline.getInstance((x) => {self.postMessage(x);});self.postMessage({status: "loading",data: "Compiling shaders and warming up...",});const inputs = tokenizer("a");await model.generate({ ...inputs, max_new_tokens: 1 });self.postMessage({ status: "ready" });}self.addEventListener("message", async (e) => {const { type, data } = e.data;switch (type) {case "check":check();break;case "load":load();break;case "generate":stopping_criteria.reset();generate(data);break;case "interrupt":stopping_criteria.interrupt();break;case "reset":past_key_values_cache = null;stopping_criteria.reset();break;}});
src/worker.js+18-28