Offload all token counting to worker processes as well as some optimizations to do more token counting in parallel

Adding the workerpool logic broke gui as vite does not support __dirname
or path.join(...). To work around this, moved the gui dependency of
stripImages out of countTokens.ts
This commit is contained in:
Rob Leidle 2024-06-17 15:08:33 -07:00
parent 3e0fae35a7
commit 78a4025414
36 changed files with 700 additions and 94 deletions

View file

@ -3,7 +3,7 @@ import {
SlashCommand,
SlashCommandDescription,
} from "../index.js";
import { stripImages } from "../llm/countTokens.js";
import { stripImages } from "../llm/images.js";
import { renderTemplatedString } from "../llm/llms/index.js";
import SlashCommands from "./slash/index.js";

View file

@ -1,5 +1,5 @@
import { SlashCommand } from "../../index.js";
import { stripImages } from "../../llm/countTokens.js";
import { stripImages } from "../../llm/images.js";
const CommitMessageCommand: SlashCommand = {
name: "commit",

View file

@ -1,5 +1,5 @@
import { ChatMessage, SlashCommand } from "../../index.js";
import { stripImages } from "../../llm/countTokens.js";
import { stripImages } from "../../llm/images.js";
import { removeQuotesAndEscapes } from "../../util/index.js";
const PROMPT = (

View file

@ -8,7 +8,7 @@ import {
} from "../../autocomplete/lineStream.js";
import { streamLines } from "../../diff/util.js";
import { ContextItemWithId, ILLM, SlashCommand } from "../../index.js";
import { stripImages } from "../../llm/countTokens.js";
import { stripImages } from "../../llm/images.js";
import {
dedentAndGetCommonWhitespace,
getMarkdownLanguageTagForFile,

View file

@ -1,5 +1,5 @@
import { ChatMessage, SlashCommand } from "../../index.js";
import { stripImages } from "../../llm/countTokens.js";
import { stripImages } from "../../llm/images.js";
const prompt = `
Review the following code, focusing on Readability, Maintainability, Code Smells, Speed, and Memory Performance. Provide feedback with these guidelines:

View file

@ -3,7 +3,7 @@ import { homedir } from "node:os";
import path from "path";
import { languageForFilepath } from "../../autocomplete/constructPrompt.js";
import { SlashCommand } from "../../index.js";
import { stripImages } from "../../llm/countTokens.js";
import { stripImages } from "../../llm/images.js";
// If useful elsewhere, helper funcs should move to core/util/index.ts or similar
function getOffsetDatetime(date: Date): Date {

View file

@ -1,6 +1,7 @@
import { constants } from "../../deploy/constants.js";
import { ChatMessageRole, FetchFunction, SlashCommand } from "../../index.js";
import { pruneStringFromBottom, stripImages } from "../../llm/countTokens.js";
import { pruneStringFromBottom } from "../../llm/countTokens.js";
import { stripImages } from "../../llm/images.js";
const PROMPT = (
input: string,

View file

@ -3,7 +3,7 @@ import path from "path";
import * as YAML from "yaml";
import type { IDE, SlashCommand } from "..";
import { walkDir } from "../indexing/walkDir";
import { stripImages } from "../llm/countTokens.js";
import { stripImages } from "../llm/images";
import { renderTemplatedString } from "../llm/llms/index.js";
import { getBasename } from "../util/index.js";

View file

@ -1,6 +1,6 @@
import { distance } from "fastest-levenshtein";
import { ChatMessage } from "../index.js";
import { stripImages } from "../llm/countTokens.js";
import { stripImages } from "../llm/images.js";
export type LineStream = AsyncGenerator<string>;

View file

@ -111,7 +111,7 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
maxChunkSize: this.maxChunkSize,
digest: item.cacheKey,
})) {
handleChunk(chunk);
await handleChunk(chunk);
}
accumulatedProgress =

View file

@ -1,10 +1,10 @@
import { ChunkWithoutID } from "../../index.js";
import { countTokens } from "../../llm/countTokens.js";
import { countTokensAsync } from "../../llm/countTokens.js";
export function* basicChunker(
export async function* basicChunker(
contents: string,
maxChunkSize: number,
): Generator<ChunkWithoutID> {
): AsyncGenerator<ChunkWithoutID> {
if (contents.trim().length === 0) {
return;
}
@ -14,18 +14,24 @@ export function* basicChunker(
let startLine = 0;
let currLine = 0;
for (const line of contents.split("\n")) {
const lineTokens = countTokens(line);
if (chunkTokens + lineTokens > maxChunkSize - 5) {
const lineTokens = await Promise.all(contents.split("\n").map(async l => {
return {
line: l,
tokenCount: await countTokensAsync(l),
};
}));
for (const lt of lineTokens) {
if (chunkTokens + lt.tokenCount > maxChunkSize - 5) {
yield { content: chunkContent, startLine, endLine: currLine - 1 };
chunkContent = "";
chunkTokens = 0;
startLine = currLine;
}
if (lineTokens < maxChunkSize) {
chunkContent += `${line}\n`;
chunkTokens += lineTokens + 1;
if (lt.tokenCount < maxChunkSize) {
chunkContent += `${lt.line}\n`;
chunkTokens += lt.tokenCount + 1;
}
currLine++;

View file

@ -1,5 +1,5 @@
import { Chunk, ChunkWithoutID } from "../../index.js";
import { countTokens } from "../../llm/countTokens.js";
import { countTokens, countTokensAsync } from "../../llm/countTokens.js";
import { supportedLanguages } from "../../util/treeSitter.js";
import { basicChunker } from "./basic.js";
import { codeChunker } from "./code.js";
@ -44,25 +44,34 @@ export async function* chunkDocument({
digest,
}: ChunkDocumentParam): AsyncGenerator<Chunk> {
let index = 0;
const chunkPromises: Promise<Chunk | undefined>[] = [];
for await (const chunkWithoutId of chunkDocumentWithoutId(
filepath,
contents,
maxChunkSize,
)) {
if (countTokens(chunkWithoutId.content) > maxChunkSize) {
console.warn(
`Chunk with more than ${maxChunkSize} tokens constructed: `,
chunkPromises.push(new Promise(async (resolve) => {
if (await countTokensAsync(chunkWithoutId.content) > maxChunkSize) {
console.warn(
`Chunk with more than ${maxChunkSize} tokens constructed: `,
filepath,
countTokens(chunkWithoutId.content),
);
return resolve(undefined);
}
resolve({
...chunkWithoutId,
digest,
index,
filepath,
countTokens(chunkWithoutId.content),
);
continue;
}
yield {
...chunkWithoutId,
digest,
index,
filepath,
};
});
}));
index++;
}
for await (const chunk of chunkPromises) {
if (!chunk) {
continue;
}
yield chunk;
}
}

View file

@ -1,6 +1,6 @@
import { SyntaxNode } from "web-tree-sitter";
import { ChunkWithoutID } from "../../index.js";
import { countTokens } from "../../llm/countTokens.js";
import { countTokens, countTokensAsync } from "../../llm/countTokens.js";
import { getParserForFile } from "../../util/treeSitter.js";
function collapsedReplacement(node: SyntaxNode): string {
@ -22,14 +22,14 @@ function firstChild(
return node.children.find((child) => child.type === grammarName) || null;
}
function collapseChildren(
async function collapseChildren(
node: SyntaxNode,
code: string,
blockTypes: string[],
collapseTypes: string[],
collapseBlockTypes: string[],
maxChunkSize: number,
): string {
): Promise<string> {
code = code.slice(0, node.endIndex);
const block = firstChild(node, blockTypes);
const collapsedChildren = [];
@ -58,7 +58,7 @@ function collapseChildren(
code = code.slice(node.startIndex);
let removedChild = false;
while (
countTokens(code.trim()) > maxChunkSize &&
(await countTokensAsync(code.trim())) > maxChunkSize &&
collapsedChildren.length > 0
) {
removedChild = true;
@ -106,11 +106,11 @@ export const FUNCTION_DECLARATION_NODE_TYPEs = [
"method_declaration",
];
function constructClassDefinitionChunk(
async function constructClassDefinitionChunk(
node: SyntaxNode,
code: string,
maxChunkSize: number,
): string {
): Promise<string> {
return collapseChildren(
node,
code,
@ -121,11 +121,11 @@ function constructClassDefinitionChunk(
);
}
function constructFunctionDefinitionChunk(
async function constructFunctionDefinitionChunk(
node: SyntaxNode,
code: string,
maxChunkSize: number,
): string {
): Promise<string> {
const bodyNode = node.children[node.children.length - 1];
const funcText =
code.slice(node.startIndex, bodyNode.startIndex) +
@ -153,7 +153,7 @@ const collapsedNodeConstructors: {
node: SyntaxNode,
code: string,
maxChunkSize: number,
) => string;
) => Promise<string>;
} = {
// Classes, structs, etc
class_definition: constructClassDefinitionChunk,
@ -165,37 +165,50 @@ const collapsedNodeConstructors: {
function_item: constructFunctionDefinitionChunk,
};
function* getSmartCollapsedChunks(
async function maybeYieldChunk(
node: SyntaxNode,
code: string,
maxChunkSize: number,
root = true,
): Generator<ChunkWithoutID> {
): Promise<ChunkWithoutID | undefined> {
// Keep entire text if not over size
if (
(root || node.type in collapsedNodeConstructors) &&
countTokens(node.text) < maxChunkSize
) {
yield {
content: node.text,
startLine: node.startPosition.row,
endLine: node.endPosition.row,
};
if (root || node.type in collapsedNodeConstructors) {
const tokenCount = await countTokensAsync(node.text);
if (tokenCount < maxChunkSize) {
return {
content: node.text,
startLine: node.startPosition.row,
endLine: node.endPosition.row,
};
}
}
return undefined;
}
async function* getSmartCollapsedChunks(
node: SyntaxNode,
code: string,
maxChunkSize: number,
root = true,
): AsyncGenerator<ChunkWithoutID> {
const chunk = await maybeYieldChunk(node, code, maxChunkSize, root);
if (chunk) {
yield chunk;
return;
}
// If a collapsed form is defined, use that
if (node.type in collapsedNodeConstructors) {
yield {
content: collapsedNodeConstructors[node.type](node, code, maxChunkSize),
content: await collapsedNodeConstructors[node.type](node, code, maxChunkSize),
startLine: node.startPosition.row,
endLine: node.endPosition.row,
};
}
// Recurse (because even if collapsed version was shown, want to show the children in full somewhere)
for (const child of node.children) {
yield* getSmartCollapsedChunks(child, code, maxChunkSize, false);
const generators = node.children.map((child) => getSmartCollapsedChunks(child, code, maxChunkSize, false));
for (const generator of generators) {
yield* generator;
}
}

View file

@ -78,7 +78,7 @@ export async function* markdownChunker(
if (hLevel > 4) {
const header = findHeader(content.split("\n"));
for (const chunk of basicChunker(content, maxChunkSize)) {
for await (const chunk of basicChunker(content, maxChunkSize)) {
yield {
...chunk,
otherMetadata: {

47
core/llm/asyncEncoder.ts Normal file
View file

@ -0,0 +1,47 @@
import llamaTokenizer from "./llamaTokenizer.js";
import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken";
import workerpool from "workerpool";
import * as path from "path";
export interface AsyncEncoder {
encode(text: string): Promise<number[]>;
decode(tokens: number[]): string;
}
export class LlamaAsyncEncoder implements AsyncEncoder {
private workerPool: workerpool.Pool;
constructor() {
this.workerPool = workerpool.pool(path.join(__dirname, "/llamaTokenizerWorkerPool.mjs"));
}
async encode(text: string): Promise<number[]> {
return this.workerPool.exec("encode", [text]);
}
decode(tokens: number[]): string {
return llamaTokenizer.decode(tokens);
}
// TODO: this should be called somewhere before exit or potentially with a shutdown hook
public async close(): Promise<void> {
await this.workerPool.terminate();
}
}
// this class does not yet do anything asynchronous
export class GPTAsyncEncoder implements AsyncEncoder {
private tiktokenEncoding: Tiktoken;
constructor() {
this.tiktokenEncoding = _encodingForModel("gpt-4");
}
async encode(text: string): Promise<number[]> {
return this.tiktokenEncoding.encode(text, "all", []);
}
decode(tokens: number[]): string {
return this.tiktokenEncoding.decode(tokens);
}
}

View file

@ -3,27 +3,35 @@ import { ChatMessage, MessageContent, MessagePart } from "../index.js";
import { autodetectTemplateType } from "./autodetect.js";
import { TOKEN_BUFFER_FOR_SAFETY } from "./constants.js";
import llamaTokenizer from "./llamaTokenizer.js";
import { AsyncEncoder, GPTAsyncEncoder, LlamaAsyncEncoder } from "./asyncEncoder.js";
import { stripImages } from "./images.js";
interface Encoding {
encode: Tiktoken["encode"];
decode: Tiktoken["decode"];
}
class LlamaEncoding implements Encoding {
encode(
text: string,
allowedSpecial?: string[] | "all" | undefined,
disallowedSpecial?: string[] | "all" | undefined,
): number[] {
encode(text: string): number[] {
return llamaTokenizer.encode(text);
}
decode(tokens: number[]): string {
return llamaTokenizer.decode(tokens);
}
}
let gptEncoding: Encoding | null = null;
const gptAsyncEncoder = new GPTAsyncEncoder();
const llamaEncoding = new LlamaEncoding();
const llamaAsyncEncoder = new LlamaAsyncEncoder();
function asyncEncoderForModel(modelName: string): AsyncEncoder {
const modelType = autodetectTemplateType(modelName);
if (!modelType || modelType === "none") {
return gptAsyncEncoder;
}
return llamaAsyncEncoder;
}
function encodingForModel(modelName: string): Encoding {
const modelType = autodetectTemplateType(modelName);
@ -46,6 +54,24 @@ function countImageTokens(content: MessagePart): number {
throw new Error("Non-image content type");
}
async function countTokensAsync(
content: MessageContent,
// defaults to llama2 because the tokenizer tends to produce more tokens
modelName = "llama2",
): Promise<number> {
const encoding = asyncEncoderForModel(modelName);
if (Array.isArray(content)) {
const promises = content.map(async part => {
if (part.type === "imageUrl") {
return countImageTokens(part);
}
return (await encoding.encode(part.text ?? "")).length;
});
return (await Promise.all(promises)).reduce((sum, val) => sum + val, 0);
}
return (await encoding.encode(content ?? "")).length;
}
function countTokens(
content: MessageContent,
// defaults to llama2 because the tokenizer tends to produce more tokens
@ -79,16 +105,6 @@ function flattenMessages(msgs: ChatMessage[]): ChatMessage[] {
return flattened;
}
export function stripImages(content: MessageContent): string {
if (Array.isArray(content)) {
return content
.filter((part) => part.type === "text")
.map((part) => part.text)
.join("\n");
}
return content;
}
function countChatMessageTokens(
modelName: string,
chatMessage: ChatMessage,
@ -360,6 +376,7 @@ function compileChatMessages(
export {
compileChatMessages,
countTokens,
countTokensAsync,
pruneLinesFromBottom,
pruneLinesFromTop,
pruneRawPromptFromTop,

11
core/llm/images.ts Normal file
View file

@ -0,0 +1,11 @@
import { MessageContent } from "../index.js";
export function stripImages(content: MessageContent): string {
if (Array.isArray(content)) {
return content
.filter((part) => part.type === "text")
.map((part) => part.text)
.join("\n");
}
return content;
}

View file

@ -36,9 +36,9 @@ import {
compileChatMessages,
countTokens,
pruneRawPromptFromTop,
stripImages,
} from "./countTokens.js";
import CompletionOptionsForModels from "./templates/options.js";
import { stripImages } from "./images.js";
export abstract class BaseLLM implements ILLM {
static providerName: ModelProvider;

486
core/llm/llamaTokenizer.mjs Normal file

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,10 @@
import workerpool from "workerpool";
import llamaTokenizer from "./llamaTokenizer.mjs";
function encode(segment) {
return llamaTokenizer.encode(segment);
}
workerpool.worker({
encode,
});

View file

@ -4,7 +4,7 @@ import {
LLMOptions,
ModelProvider,
} from "../../index.js";
import { stripImages } from "../countTokens.js";
import { stripImages } from "../images.js";
import { BaseLLM } from "../index.js";
import { streamSse } from "../stream.js";

View file

@ -10,7 +10,7 @@ import {
MessageContent,
ModelProvider,
} from "../../index.js";
import { stripImages } from "../countTokens.js";
import { stripImages } from "../images.js";
import { BaseLLM } from "../index.js";
class Bedrock extends BaseLLM {

View file

@ -1,6 +1,6 @@
import { BaseLLM } from "../index.js";
import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js";
import { stripImages } from "../countTokens.js";
import { stripImages } from "../images.js";
import { streamSse } from "../stream.js";
export default class Cloudflare extends BaseLLM {

View file

@ -5,7 +5,7 @@ import {
LLMOptions,
ModelProvider,
} from "../../index.js";
import { stripImages } from "../countTokens.js";
import { stripImages } from "../images.js";
import { streamJSON } from "../stream.js";
class Cohere extends BaseLLM {

View file

@ -5,7 +5,7 @@ import {
LLMOptions,
ModelProvider,
} from "../../index.js";
import { stripImages } from "../countTokens.js";
import { stripImages } from "../images.js";
import { BaseLLM } from "../index.js";
interface IFlowiseApiOptions {

View file

@ -5,7 +5,7 @@ import {
MessagePart,
ModelProvider,
} from "../../index.js";
import { stripImages } from "../countTokens.js";
import { stripImages } from "../images.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";

View file

@ -4,7 +4,7 @@ import {
LLMOptions,
ModelProvider,
} from "../../index.js";
import { stripImages } from "../countTokens.js";
import { stripImages } from "../images.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";

View file

@ -4,7 +4,7 @@ import {
LLMOptions,
ModelProvider,
} from "../../index.js";
import { stripImages } from "../countTokens.js";
import { stripImages } from "../images.js";
import { BaseLLM } from "../index.js";
import { streamSse } from "../stream.js";

View file

@ -1,5 +1,5 @@
import { ChatMessage } from "../../index.js";
import { stripImages } from "../countTokens.js";
import { stripImages } from "../images.js";
function templateFactory(
systemMessage: (msg: ChatMessage) => string,

View file

@ -80,6 +80,7 @@
"vectordb": "^0.4.20",
"web-tree-sitter": "^0.21.0",
"win-ca": "^3.5.1",
"workerpool": "^9.1.3",
"yaml": "^2.4.2",
"zod": "^3.23.8"
},

View file

@ -241,11 +241,15 @@ const exe = os === "win32" ? ".exe" : "";
);
});
fs.copyFileSync(
path.join(__dirname, "../../../core/vendor/tree-sitter.wasm"),
path.join(__dirname, "../out/tree-sitter.wasm"),
);
console.log("[info] Copied tree-sitter wasms");
const filesToCopy = [
"../../../core/vendor/tree-sitter.wasm",
"../../../core/llm/llamaTokenizerWorkerPool.mjs",
"../../../core/llm/llamaTokenizer.mjs",
];
for (const f of filesToCopy) {
fs.copyFileSync(path.join(__dirname, f), path.join(__dirname, "..", "out", path.basename(f)));
console.log(`[info] Copied ${path.basename(f)}`);
}
// tree-sitter tag query files
// ncp(
@ -450,6 +454,7 @@ const exe = os === "win32" ? ".exe" : "";
"@esbuild",
"@lancedb",
"@vscode/ripgrep",
"workerpool",
];
fs.mkdirSync("out/node_modules", { recursive: true });

View file

@ -6,7 +6,7 @@ import {
TrashIcon,
} from "@heroicons/react/24/outline";
import { ChatHistoryItem } from "core";
import { stripImages } from "core/llm/countTokens";
import { stripImages } from "core/llm/images";
import { useContext, useEffect, useState } from "react";
import { useSelector } from "react-redux";
import styled from "styled-components";

View file

@ -6,7 +6,7 @@ import {
MessagePart,
RangeInFile,
} from "core";
import { stripImages } from "core/llm/countTokens";
import { stripImages } from "core/llm/images";
import { IIdeMessenger } from "../../context/IdeMessenger";
interface MentionAttrs {

View file

@ -12,7 +12,7 @@ import {
SlashCommandDescription,
} from "core";
import { constructMessages } from "core/llm/constructMessages";
import { stripImages } from "core/llm/countTokens";
import { stripImages } from "core/llm/images";
import { getBasename, getRelativePath } from "core/util";
import { usePostHog } from "posthog-js/react";
import { useEffect, useRef } from "react";

View file

@ -2,7 +2,7 @@ import { Dispatch } from "@reduxjs/toolkit";
import { PersistedSessionInfo, SessionInfo } from "core";
import { llmCanGenerateInParallel } from "core/llm/autodetect";
import { stripImages } from "core/llm/countTokens";
import { stripImages } from "core/llm/images";
import { useContext } from "react";
import { useSelector } from "react-redux";
import { IdeMessengerContext } from "../context/IdeMessenger";

View file

@ -10,7 +10,7 @@ import {
PromptLog,
} from "core";
import { BrowserSerializedContinueConfig } from "core/config/load";
import { stripImages } from "core/llm/countTokens";
import { stripImages } from "core/llm/images";
import { createSelector } from "reselect";
import { v4 } from "uuid";
import { RootState } from "../store";