Spaces:
Running
Running
File size: 6,231 Bytes
68185ce |
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 |
import { useState, useEffect, useRef, useCallback } from "react";
import {
AutoModelForCausalLM,
AutoTokenizer,
TextStreamer,
} from "@huggingface/transformers";
interface LLMState {
isLoading: boolean;
isReady: boolean;
error: string | null;
progress: number;
}
interface LLMInstance {
model: any;
tokenizer: any;
}
let moduleCache: {
[modelId: string]: {
instance: LLMInstance | null;
loadingPromise: Promise<LLMInstance> | null;
};
} = {};
export const useLLM = (modelId?: string) => {
const [state, setState] = useState<LLMState>({
isLoading: false,
isReady: false,
error: null,
progress: 0,
});
const instanceRef = useRef<LLMInstance | null>(null);
const loadingPromiseRef = useRef<Promise<LLMInstance> | null>(null);
const abortControllerRef = useRef<AbortController | null>(null);
const pastKeyValuesRef = useRef<any>(null);
const loadModel = useCallback(async () => {
if (!modelId) {
throw new Error("Model ID is required");
}
const MODEL_ID = `onnx-community/LFM2-${modelId}-ONNX`;
if (!moduleCache[modelId]) {
moduleCache[modelId] = {
instance: null,
loadingPromise: null,
};
}
const cache = moduleCache[modelId];
const existingInstance = instanceRef.current || cache.instance;
if (existingInstance) {
instanceRef.current = existingInstance;
cache.instance = existingInstance;
setState((prev) => ({ ...prev, isReady: true, isLoading: false }));
return existingInstance;
}
const existingPromise = loadingPromiseRef.current || cache.loadingPromise;
if (existingPromise) {
try {
const instance = await existingPromise;
instanceRef.current = instance;
cache.instance = instance;
setState((prev) => ({ ...prev, isReady: true, isLoading: false }));
return instance;
} catch (error) {
setState((prev) => ({
...prev,
isLoading: false,
error:
error instanceof Error ? error.message : "Failed to load model",
}));
throw error;
}
}
setState((prev) => ({
...prev,
isLoading: true,
error: null,
progress: 0,
}));
abortControllerRef.current = new AbortController();
const loadingPromise = (async () => {
try {
const progressCallback = (progress: any) => {
// Only update progress for weights
if (
progress.status === "progress" &&
progress.file.endsWith(".onnx_data")
) {
const percentage = Math.round(
(progress.loaded / progress.total) * 100,
);
setState((prev) => ({ ...prev, progress: percentage }));
}
};
const tokenizer = await AutoTokenizer.from_pretrained(MODEL_ID, {
progress_callback: progressCallback,
});
const model = await AutoModelForCausalLM.from_pretrained(MODEL_ID, {
dtype: "q4f16",
device: "webgpu",
progress_callback: progressCallback,
});
const instance = { model, tokenizer };
instanceRef.current = instance;
cache.instance = instance;
loadingPromiseRef.current = null;
cache.loadingPromise = null;
setState((prev) => ({
...prev,
isLoading: false,
isReady: true,
progress: 100,
}));
return instance;
} catch (error) {
loadingPromiseRef.current = null;
cache.loadingPromise = null;
setState((prev) => ({
...prev,
isLoading: false,
error:
error instanceof Error ? error.message : "Failed to load model",
}));
throw error;
}
})();
loadingPromiseRef.current = loadingPromise;
cache.loadingPromise = loadingPromise;
return loadingPromise;
}, [modelId]);
const generateResponse = useCallback(
async (
messages: Array<{ role: string; content: string }>,
tools: Array<any>,
onToken?: (token: string) => void,
): Promise<string> => {
const instance = instanceRef.current;
if (!instance) {
throw new Error("Model not loaded. Call loadModel() first.");
}
const { model, tokenizer } = instance;
// Apply chat template with tools
const input = tokenizer.apply_chat_template(messages, {
tools,
add_generation_prompt: true,
return_dict: true,
});
const streamer = onToken
? new TextStreamer(tokenizer, {
skip_prompt: true,
skip_special_tokens: false,
callback_function: (token: string) => {
onToken(token);
},
})
: undefined;
// Generate the response
const { sequences, past_key_values } = await model.generate({
...input,
past_key_values: pastKeyValuesRef.current,
max_new_tokens: 512,
do_sample: false,
streamer,
return_dict_in_generate: true,
});
pastKeyValuesRef.current = past_key_values;
// Decode the generated text with special tokens preserved (except final <|im_end|>) for tool call detection
const response = tokenizer
.batch_decode(sequences.slice(null, [input.input_ids.dims[1], null]), {
skip_special_tokens: false,
})[0]
.replace(/<\|im_end\|>$/, "");
return response;
},
[],
);
const clearPastKeyValues = useCallback(() => {
pastKeyValuesRef.current = null;
}, []);
const cleanup = useCallback(() => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
}
}, []);
useEffect(() => {
return cleanup;
}, [cleanup]);
useEffect(() => {
if (modelId && moduleCache[modelId]) {
const existingInstance =
instanceRef.current || moduleCache[modelId].instance;
if (existingInstance) {
instanceRef.current = existingInstance;
setState((prev) => ({ ...prev, isReady: true }));
}
}
}, [modelId]);
return {
...state,
loadModel,
generateResponse,
clearPastKeyValues,
cleanup,
};
};
|