🐛 use llama tokenizer for llama-based models

This commit is contained in:
Nate Sesti 2024-02-19 19:50:01 -08:00
parent 21981156f8
commit e8bbdc06a1
13 changed files with 70 additions and 32 deletions

View file

@ -76,7 +76,8 @@ export async function constructAutocompletePrompt(
line: number,
character: number
) => Promise<AutocompleteSnippet | undefined>,
options: TabAutocompleteOptions
options: TabAutocompleteOptions,
modelName: string
): Promise<{ prefix: string; suffix: string; useFim: boolean }> {
// Find external snippets
const snippets: AutocompleteSnippet[] = [];
@ -121,17 +122,17 @@ export async function constructAutocompletePrompt(
.join("\n");
const maxPrefixTokens =
options.maxPromptTokens * options.prefixPercentage -
countTokens(formattedSnippets, "gpt-4");
let prefix = pruneLinesFromTop(fullPrefix, maxPrefixTokens);
countTokens(formattedSnippets, modelName);
let prefix = pruneLinesFromTop(fullPrefix, maxPrefixTokens, modelName);
if (formattedSnippets.length > 0) {
prefix = formattedSnippets + "\n" + prefix;
}
const maxSuffixTokens = Math.min(
options.maxPromptTokens - countTokens(prefix, "gpt-4"),
options.maxPromptTokens - countTokens(prefix, modelName),
options.maxSuffixPercentage * options.maxPromptTokens
);
let suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens);
let suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens, modelName);
return { prefix, suffix, useFim: true };
}

View file

@ -11,7 +11,7 @@ export function* basicChunker(
let currLine = 0;
for (const line of contents.split("\n")) {
const lineTokens = countTokens(line, "gpt-4");
const lineTokens = countTokens(line);
if (chunkTokens + lineTokens > maxChunkSize - 5) {
yield { content: chunkContent, startLine, endLine: currLine - 1 };
chunkContent = "";

View file

@ -43,11 +43,11 @@ export async function* chunkDocument(
contents,
maxChunkSize
)) {
if (countTokens(chunkWithoutId.content, "gpt-4") > MAX_CHUNK_SIZE) {
if (countTokens(chunkWithoutId.content) > MAX_CHUNK_SIZE) {
console.warn(
`Chunk with more than ${maxChunkSize} tokens constructed: `,
filepath,
countTokens(chunkWithoutId.content, "gpt-4")
countTokens(chunkWithoutId.content)
);
continue;
}

View file

@ -59,10 +59,7 @@ function collapseChildren(
}
code = code.slice(node.startIndex);
let removedChild = false;
while (
countTokens(code, "gpt-4") > maxChunkSize &&
collapsedChildren.length > 0
) {
while (countTokens(code) > maxChunkSize && collapsedChildren.length > 0) {
removedChild = true;
// Remove children starting at the end - TODO: Add multiple chunks so no children are missing
const childCode = collapsedChildren.pop()!;
@ -169,7 +166,7 @@ function* getSmartCollapsedChunks(
// Keep entire text if not over size
if (
(root || node.type in collapsedNodeConstructors) &&
countTokens(node.text, "gpt-4") < maxChunkSize
countTokens(node.text) < maxChunkSize
) {
yield {
content: node.text,

View file

@ -57,7 +57,7 @@ export async function* markdownChunker(
maxChunkSize: number,
hLevel: number
): AsyncGenerator<ChunkWithoutID> {
if (countTokens(content, "gpt-4") <= maxChunkSize) {
if (countTokens(content) <= maxChunkSize) {
const header = findHeader(content.split("\n"));
yield {
content,
@ -122,8 +122,7 @@ export async function* markdownChunker(
for (const section of sections) {
for await (const chunk of markdownChunker(
section.content,
maxChunkSize -
(section.header ? countTokens(section.header, "gpt-4") : 0),
maxChunkSize - (section.header ? countTokens(section.header) : 0),
hLevel + 1
)) {
yield {

View file

@ -1,16 +1,29 @@
import { encodingForModel as _encodingForModel, Tiktoken } from "js-tiktoken";
import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken";
// @ts-expect-error
import llamaTokenizer from "llama-tokenizer-js";
import { ChatMessage, MessageContent, MessagePart } from "..";
import { autodetectTemplateType } from "./autodetect";
import { TOKEN_BUFFER_FOR_SAFETY } from "./constants";
let encoding: Tiktoken | null = null;
interface Encoding {
encode: Tiktoken["encode"];
decode: Tiktoken["decode"];
}
function encodingForModel(modelName: string): Tiktoken {
if (encoding) {
return encoding;
let gptEncoding: Encoding | null = null;
function encodingForModel(modelName: string): Encoding {
const modelType = autodetectTemplateType(modelName);
if (!modelType || modelType === "none") {
if (!gptEncoding) {
gptEncoding = _encodingForModel("gpt-4");
}
return gptEncoding;
}
encoding = _encodingForModel("gpt-4");
return encoding;
return llamaTokenizer;
}
function countImageTokens(content: MessagePart): number {
@ -21,7 +34,11 @@ function countImageTokens(content: MessagePart): number {
}
}
function countTokens(content: MessageContent, modelName: string): number {
function countTokens(
content: MessageContent,
// defaults to llama2 because the tokenizer tends to produce more tokens
modelName: string = "llama2"
): number {
const encoding = encodingForModel(modelName);
if (Array.isArray(content)) {
return content.reduce((acc, part) => {
@ -72,21 +89,29 @@ function countChatMessageTokens(
return countTokens(chatMessage.content, modelName) + TOKENS_PER_MESSAGE;
}
function pruneLinesFromTop(prompt: string, maxTokens: number): string {
let totalTokens = countTokens(prompt, "gpt-4");
function pruneLinesFromTop(
prompt: string,
maxTokens: number,
modelName: string
): string {
let totalTokens = countTokens(prompt, modelName);
const lines = prompt.split("\n");
while (totalTokens > maxTokens && lines.length > 0) {
totalTokens -= countTokens(lines.shift()!, "gpt-4");
totalTokens -= countTokens(lines.shift()!, modelName);
}
return lines.join("\n");
}
function pruneLinesFromBottom(prompt: string, maxTokens: number): string {
let totalTokens = countTokens(prompt, "gpt-4");
function pruneLinesFromBottom(
prompt: string,
maxTokens: number,
modelName: string
): string {
let totalTokens = countTokens(prompt, modelName);
const lines = prompt.split("\n");
while (totalTokens > maxTokens && lines.length > 0) {
totalTokens -= countTokens(lines.pop()!, "gpt-4");
totalTokens -= countTokens(lines.pop()!, modelName);
}
return lines.join("\n");

View file

@ -21,6 +21,7 @@
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"js-tiktoken": "^1.0.8",
"llama-tokenizer-js": "^1.1.3",
"llm-code-highlighter": "^0.0.9",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",
@ -4840,6 +4841,11 @@
"integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==",
"dev": true
},
"node_modules/llama-tokenizer-js": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/llama-tokenizer-js/-/llama-tokenizer-js-1.1.3.tgz",
"integrity": "sha512-+BUgsLCXVQJkjiD/t7PdESLn+yXJIRX/BJfwzVVYfKZ9aN3gsP9xoadBZxKnCxGz2Slby+S7x41gUr2TKNaS4Q=="
},
"node_modules/llm-code-highlighter": {
"version": "0.0.9",
"resolved": "https://registry.npmjs.org/llm-code-highlighter/-/llm-code-highlighter-0.0.9.tgz",

View file

@ -31,6 +31,7 @@
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"js-tiktoken": "^1.0.8",
"llama-tokenizer-js": "^1.1.3",
"llm-code-highlighter": "^0.0.9",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",

View file

@ -2745,6 +2745,11 @@ lines-and-columns@^1.1.6:
resolved "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz"
integrity sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==
llama-tokenizer-js@^1.1.3:
version "1.1.3"
resolved "https://registry.npmjs.org/llama-tokenizer-js/-/llama-tokenizer-js-1.1.3.tgz"
integrity sha512-+BUgsLCXVQJkjiD/t7PdESLn+yXJIRX/BJfwzVVYfKZ9aN3gsP9xoadBZxKnCxGz2Slby+S7x41gUr2TKNaS4Q==
llm-code-highlighter@^0.0.9:
version "0.0.9"
resolved "https://registry.npmjs.org/llm-code-highlighter/-/llm-code-highlighter-0.0.9.tgz"

View file

@ -97,6 +97,7 @@
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"js-tiktoken": "^1.0.8",
"llama-tokenizer-js": "^1.1.3",
"llm-code-highlighter": "^0.0.9",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",

View file

@ -275,8 +275,9 @@ export class ContinueCompletionProvider
fullSuffix,
clipboardText,
lang,
this.promptBuilder.getDefinition,
options
this.promptBuilder.getDefinition.bind(this.promptBuilder),
options,
llm.model
);
const { template, completionOptions } = options.template

View file

@ -2328,6 +2328,7 @@ core-util-is@1.0.2:
http-proxy-agent "^7.0.1"
https-proxy-agent "^7.0.3"
js-tiktoken "^1.0.8"
llama-tokenizer-js "^1.1.3"
llm-code-highlighter "^0.0.9"
node-fetch "^3.3.2"
node-html-markdown "^1.3.0"

1
gui/package-lock.json generated
View file

@ -85,6 +85,7 @@
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"js-tiktoken": "^1.0.8",
"llama-tokenizer-js": "^1.1.3",
"llm-code-highlighter": "^0.0.9",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",