File size: 6,175 Bytes
9b72f0d
 
 
 
 
 
 
 
 
832660f
db78b1a
 
9b72f0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db78b1a
9b72f0d
 
 
 
 
 
 
 
 
 
 
db78b1a
 
9b72f0d
 
 
 
 
 
 
 
 
 
ec2237a
 
 
9b72f0d
 
 
 
 
 
 
ec2237a
9b72f0d
 
ec2237a
9b72f0d
 
ec2237a
9b72f0d
 
 
ec2237a
9b72f0d
 
 
 
3624cee
 
9b72f0d
 
 
 
cc1f67c
9b72f0d
db78b1a
 
9b72f0d
 
 
 
 
ec2237a
 
 
 
 
 
 
 
 
 
 
 
9b72f0d
832660f
 
 
 
9b72f0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2847f1
832660f
9b72f0d
832660f
9b72f0d
 
 
 
b2847f1
cc1f67c
97ce2e0
9b72f0d
db78b1a
9b72f0d
 
 
 
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
import {
  AutoModelForCausalLM,
  AutoTokenizer,
  InterruptableStoppingCriteria,
  PreTrainedModel,
  PreTrainedTokenizer,
  Tensor,
  TextStreamer,
} from "@huggingface/transformers";

import { calculateDownloadProgress } from "../../utils/calculateDownloadProgress.ts";
import { MODELS } from "../../utils/models.ts";
import {
  type Request,
  RequestType,
  type Response,
  ResponseType,
} from "../types.ts";

interface Pipeline {
  tokenizer: PreTrainedTokenizer;
  model: PreTrainedModel;
}

let pipeline: Pipeline | null = null;
let initializedModelKey: keyof typeof MODELS | null = null;
let cache: { pastKeyValues: any | null; key: string } = {
  pastKeyValues: null,
  key: "",
};
let stoppingCriteria: any | null = null;

const getTextGenerationPipeline = async (
  modelKey: keyof typeof MODELS,
  onDownloadProgress: (percentage: number) => void = () => {}
): Promise<Pipeline> => {
  if (pipeline && modelKey === initializedModelKey) return pipeline;
  if (pipeline) {
    await pipeline.model.dispose();
  }

  const MODEL = MODELS[modelKey];
  const MODEL_FILES = new Map();
  for (const [key, value] of Object.entries(MODEL.files)) {
    MODEL_FILES.set(key, { loaded: 0, total: value });
  }

  try {
    const tokenizer = await AutoTokenizer.from_pretrained(MODEL.modelId);
    const model = await AutoModelForCausalLM.from_pretrained(MODEL.modelId, {
      dtype: MODEL.dtype,
      device: MODEL.device,
      progress_callback: calculateDownloadProgress(
        ({ percentage }) => onDownloadProgress(percentage),
        MODEL_FILES
      ),
    });
    pipeline = { tokenizer, model };
    initializedModelKey = modelKey;
    return pipeline;
  } catch (error) {
    console.error("Failed to initialize feature extraction pipeline:", error);
    throw error;
  }
};

const postMessage = (message: Response) => self.postMessage(message);

self.onmessage = async ({ data }: MessageEvent<Request>) => {
  if (data.type === RequestType.INITIALIZE_MODEL) {
    let lastPercentage = 0;
    await getTextGenerationPipeline(data.modelKey, (percentage) => {
      if (lastPercentage === percentage) return;
      lastPercentage = percentage;
      postMessage({
        type: ResponseType.INITIALIZE_MODEL,
        progress: percentage,
        done: false,
        requestId: data.requestId,
      });
    });
    postMessage({
      type: ResponseType.INITIALIZE_MODEL,
      progress: 100,
      done: true,
      requestId: data.requestId,
    });
  }

  if (data.type === RequestType.GENERATE_MESSAGE_ABORT) {
    stoppingCriteria.interrupt();
    postMessage({
      type: ResponseType.GENERATE_TEXT_ABORTED,
      requestId: data.requestId,
    });
  }

  if (data.type === RequestType.GENERATE_MESSAGE) {
    const MODEL = MODELS[data.modelKey];
    stoppingCriteria = new InterruptableStoppingCriteria();

    const { messages, tools, requestId } = data;
    const { tokenizer, model } = await getTextGenerationPipeline(data.modelKey);
    if (!stoppingCriteria) {
      stoppingCriteria = new InterruptableStoppingCriteria();
    }

    const input = tokenizer.apply_chat_template(messages, {
      tools,
      add_generation_prompt: true,
      return_dict: true,
      // @ts-expect-error
      enable_thinking: data.enableThinking,
    }) as {
      input_ids: Tensor;
      attention_mask: number[] | number[][] | Tensor;
    };

    const started = performance.now();
    let firstTokenTime: DOMHighResTimeStamp | null = null;
    let numTokens = 0;
    let tps: number = 0;

    const removeEosToken = (content: string): string =>
      content.replace(tokenizer.eos_token, "");

    const tokenCallbackFunction = () => {
      firstTokenTime ??= performance.now();
      if (numTokens++ > 0) {
        tps = (numTokens / (performance.now() - firstTokenTime)) * 1000;
      }
    };

    const callbackFunction = (chunk: string) => {
      postMessage({
        type: ResponseType.GENERATE_TEXT_CHUNK,
        chunk: removeEosToken(chunk),
        requestId,
      });
    };

    const streamer = new TextStreamer(tokenizer, {
      skip_prompt: true,
      skip_special_tokens: false,
      token_callback_function: tokenCallbackFunction,
      callback_function: callbackFunction,
    });

    const cacheKey = MODEL.modelId + JSON.stringify(messages.slice(0, -1));
    const useCache = cacheKey === cache.key;

    const { sequences, past_key_values } = (await model.generate({
      ...input,
      max_new_tokens: 1024,
      past_key_values: useCache ? cache.pastKeyValues : null,
      return_dict_in_generate: true,
      temperature: data.temperature,
      stopping_criteria: stoppingCriteria,
      streamer,
    })) as { sequences: Tensor; past_key_values: any };
    const ended = performance.now();

    const lengthOfInput = input.input_ids.dims[1];
    const response = removeEosToken(
      tokenizer.batch_decode(
        /**
         * First argument (null): Don't slice dimension 0 (the batch dimension) - keep all batches
         * Second argument ([lengthOfInput, Number.MAX_SAFE_INTEGER]): For dimension 1 (the sequence/token dimension), slice from index lengthOfInput to the end
         */
        sequences.slice(null, [lengthOfInput, Number.MAX_SAFE_INTEGER]),
        {
          skip_special_tokens: false,
        }
      )[0]
    );

    const template = tokenizer.batch_decode(sequences, {
      skip_special_tokens: false,
    })[0];

    cache = {
      pastKeyValues: past_key_values,
      key:
        MODEL.modelId +
        JSON.stringify([
          ...messages,
          {
            role: "assistant",
            content: response,
          },
        ]),
    };

    postMessage({
      type: ResponseType.GENERATE_TEXT_DONE,
      response,
      metadata: {
        inputDurationMs: firstTokenTime - started,
        outputTokens: numTokens,
        outputDurationMs: ended - firstTokenTime,
        outputTps: tps,
        doneMs: ended - started,
        modelKey: MODEL.modelId,
        model: MODEL.title,
        template,
        useKvCache: useCache,
        temperature: data.temperature,
      },
      interrupted: stoppingCriteria.interrupted,
      requestId,
    });
  }
};