Spaces:
Running
Running
File size: 6,409 Bytes
01488bc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 | import {
AutoModelForImageTextToText,
AutoProcessor,
RawImage,
TextStreamer,
type ProgressInfo,
type Tensor,
} from "@huggingface/transformers";
import { useCallback, useRef, useState, type PropsWithChildren } from "react";
import { VLMContext, type LoadState } from "./VLMContext";
const MODEL_ID = "onnx-community/LFM2-VL-450M-ONNX";
const MODEL_FILE_COUNT = 3;
const MAX_NEW_TOKENS = 128;
type CaptionRequest = {
frame: ImageData;
onStream?: (text: string) => void;
prompt: string;
};
type ProcessorType = Awaited<ReturnType<typeof AutoProcessor.from_pretrained>>;
type ModelType = Awaited<
ReturnType<typeof AutoModelForImageTextToText.from_pretrained>
>;
const initialLoadState: LoadState = {
error: null,
message: "Downloading...",
progress: 0,
status: "idle",
};
function normalizeText(text: string) {
return text.replace(/\s+/g, " ").trim();
}
function getErrorMessage(error: unknown) {
if (error instanceof Error) {
return error.message;
}
return "The model could not be loaded.";
}
export function VLMProvider({ children }: PropsWithChildren) {
const [loadState, setLoadState] = useState(initialLoadState);
const processorRef = useRef<ProcessorType | null>(null);
const modelRef = useRef<ModelType | null>(null);
const loadPromiseRef = useRef<Promise<void> | null>(null);
const generationInFlightRef = useRef(false);
const setLoadProgress = useCallback((state: Partial<LoadState>) => {
setLoadState((current) => ({
...current,
...state,
}));
}, []);
const loadModel = useCallback(async () => {
if (processorRef.current && modelRef.current) {
setLoadProgress({
error: null,
message: "Model ready",
progress: 100,
status: "ready",
});
return;
}
if (loadPromiseRef.current) {
return loadPromiseRef.current;
}
if (!("gpu" in navigator)) {
const message = "WebGPU is not available in this browser.";
setLoadProgress({
error: message,
message: "WebGPU unavailable",
progress: 0,
status: "error",
});
throw new Error(message);
}
loadPromiseRef.current = (async () => {
try {
const processor = await AutoProcessor.from_pretrained(MODEL_ID);
processorRef.current = processor;
setLoadProgress({
message: "Downloading...",
progress: 0,
status: "loading",
});
const progressMap = new Map<string, number>();
const progressCallback = (info: ProgressInfo) => {
if (
info.status !== "progress" ||
!info.file.endsWith(".onnx_data") ||
info.total === 0
) {
return;
}
progressMap.set(info.file, info.loaded / info.total);
const totalProgress =
(Array.from(progressMap.values()).reduce(
(sum, value) => sum + value,
0,
) /
MODEL_FILE_COUNT) *
100;
setLoadProgress({
message: "Downloading...",
progress: totalProgress,
status: "loading",
});
};
modelRef.current = await AutoModelForImageTextToText.from_pretrained(
MODEL_ID,
{
device: "webgpu",
dtype: {
vision_encoder: "fp16",
embed_tokens: "fp16",
decoder_model_merged: "q4f16",
},
progress_callback: progressCallback,
},
);
setLoadProgress({
error: null,
message: "Model ready",
progress: 100,
status: "ready",
});
} catch (error) {
const message = getErrorMessage(error);
setLoadProgress({
error: message,
message: "Unable to load model",
progress: 0,
status: "error",
});
throw error;
} finally {
loadPromiseRef.current = null;
}
})();
return loadPromiseRef.current;
}, [setLoadProgress]);
const generateCaption = useCallback(
async ({ frame, onStream, prompt }: CaptionRequest) => {
const processor = processorRef.current;
const model = modelRef.current;
if (!processor || !model || !processor.tokenizer) {
throw new Error("The model is not ready yet.");
}
if (generationInFlightRef.current) {
return "";
}
generationInFlightRef.current = true;
try {
const messages = [
{
content: [
{ type: "image" },
{ text: normalizeText(prompt), type: "text" },
],
role: "user",
},
];
const chatPrompt = processor.apply_chat_template(messages, {
add_generation_prompt: true,
});
const rawFrame = new RawImage(frame.data, frame.width, frame.height, 4);
const inputs = await processor(rawFrame, chatPrompt, {
add_special_tokens: false,
});
let streamedText = "";
const streamer = new TextStreamer(processor.tokenizer, {
callback_function: (text) => {
streamedText += text;
const normalized = normalizeText(streamedText);
if (normalized.length > 0) {
onStream?.(normalized);
}
},
skip_prompt: true,
skip_special_tokens: true,
});
const outputs = (await model.generate({
...inputs,
do_sample: false,
max_new_tokens: MAX_NEW_TOKENS,
repetition_penalty: 1.08,
streamer,
})) as Tensor;
const inputLength = inputs.input_ids.dims.at(-1) ?? 0;
const generated = outputs.slice(null, [inputLength, null]);
const [decoded] = processor.batch_decode(generated, {
skip_special_tokens: true,
});
const finalCaption = normalizeText(decoded ?? streamedText);
if (finalCaption.length > 0) {
onStream?.(finalCaption);
}
return finalCaption;
} finally {
generationInFlightRef.current = false;
}
},
[],
);
return (
<VLMContext.Provider
value={{
...loadState,
generateCaption,
loadModel,
}}
>
{children}
</VLMContext.Provider>
);
}
|