-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Add embedding models configurable, from both transformers.js and TEI #646
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
32 commits
Select commit
Hold shift + click to select a range
491131c
Add embedding models configurable, from both Xenova and TEI
mikelfried 3473fc2
fix lint and format
mikelfried aebf653
Fix bug in sentenceSimilarity
mikelfried c065045
Batches for TEI using /info route
mikelfried 8df8fd2
Fix web search disapear when finish searching
mikelfried cc02b4c
Fix lint and format
mikelfried 53fa58a
Add more options for better embedding model usage
mikelfried 9a867aa
Fixing CR issues
mikelfried 6c6e290
Fix websearch disapear in later PR
mikelfried dc8d4e9
Fix lint
mikelfried aacbfeb
Fix more minor code CR
mikelfried 7a9950d
Valiadate embeddingModelName field in model config
mikelfried bce01d4
Add embeddingModel into shared conversation
mikelfried f822ced
Fix lint and format
mikelfried 421ecca
Add default embedding model, and more readme explanation
mikelfried e85faee
Fix minor embedding model readme detailed
mikelfried 00a970e
Merge branch 'main' into embedding_models
mikelfried a36c521
Update settings.json
mikelfried d132375
Update README.md
mikelfried e105225
Update README.md
mikelfried f615fef
Apply suggestions from code review
mikelfried 9ef62b9
Resolved more issues
mikelfried 7c79582
lint
nsarrazin 60d9b23
Fix more issues
mikelfried 65760bc
Fix format
mikelfried 3eb93ba
fix small typo
mikelfried 5914529
lint
nsarrazin 25d9600
fix default model
mishig25 fafecb7
Rn `maxSequenceLength` -> `chunkCharLength`
mishig25 ed3688c
format
mishig25 4ed0066
add "authorization" example
mishig25 669e86d
format
mishig25 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
import { embeddingEndpointTei, embeddingEndpointTeiParametersSchema } from "./tei/embeddingEndpoints"; | ||
import { z } from "zod"; | ||
import embeddingEndpointXenova, { embeddingEndpointXenovaParametersSchema } from "./xenova/embeddingEndpoints"; | ||
|
||
// parameters passed when generating text | ||
interface EmbeddingEndpointParameters { | ||
inputs: string[] | ||
} | ||
|
||
interface CommonEmbeddingEndpoint { | ||
weight: number; | ||
} | ||
|
||
// type signature for the endpoint | ||
export type EmbeddingEndpoint = ( | ||
params: EmbeddingEndpointParameters | ||
) => Promise<any>; // TODO: type | ||
|
||
// generator function that takes in parameters for defining the endpoint and return the endpoint | ||
export type EmbeddingEndpointGenerator<T extends CommonEmbeddingEndpoint> = (parameters: T) => EmbeddingEndpoint; | ||
|
||
// list of all endpoint generators | ||
export const embeddingEndpoints = { | ||
tei: embeddingEndpointTei, | ||
xenova: embeddingEndpointXenova | ||
}; | ||
|
||
export const embeddingEndpointSchema = z.discriminatedUnion("type", [ | ||
embeddingEndpointTeiParametersSchema, | ||
embeddingEndpointXenovaParametersSchema | ||
]); | ||
|
||
export default embeddingEndpoints; |
31 changes: 31 additions & 0 deletions
31
src/lib/server/embeddingEndpoints/tei/embeddingEndpoints.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
import { HF_ACCESS_TOKEN, HF_TOKEN } from "$env/static/private"; | ||
import { featureExtraction } from "@huggingface/inference"; | ||
import { z } from "zod"; | ||
import type { EmbeddingEndpoint } from "../embeddingEndpoints"; | ||
|
||
export const embeddingEndpointTeiParametersSchema = z.object({ | ||
weight: z.number().int().positive().default(1), | ||
mikelfried marked this conversation as resolved.
Show resolved
Hide resolved
|
||
model: z.any(), | ||
type: z.literal("tei"), | ||
url: z.string().url(), | ||
}); | ||
|
||
export function embeddingEndpointTei(input: z.input<typeof embeddingEndpointTeiParametersSchema>): EmbeddingEndpoint { | ||
const { url } = embeddingEndpointTeiParametersSchema.parse(input); | ||
return async ({ inputs }) => { | ||
const { origin } = new URL(url) | ||
|
||
const response = await fetch(`${origin}/embed`, { | ||
method: 'POST', | ||
headers: { | ||
'Accept': 'application/json', | ||
'Content-Type': 'application/json' | ||
}, | ||
body: JSON.stringify({ inputs, normalize: true, truncate: true }) | ||
}); | ||
|
||
return response.json(); | ||
}; | ||
} | ||
|
||
export default embeddingEndpointTei; |
51 changes: 51 additions & 0 deletions
51
src/lib/server/embeddingEndpoints/xenova/embeddingEndpoints.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
import { z } from "zod"; | ||
import type { EmbeddingEndpoint } from "../embeddingEndpoints"; | ||
import type { Tensor, Pipeline } from "@xenova/transformers"; | ||
import { pipeline } from "@xenova/transformers"; | ||
|
||
export const embeddingEndpointXenovaParametersSchema = z.object({ | ||
weight: z.number().int().positive().default(1), | ||
model: z.any(), | ||
type: z.literal("xenova"), | ||
}); | ||
|
||
|
||
// Use the Singleton pattern to enable lazy construction of the pipeline. | ||
class XenovaModelsSingleton { | ||
static instances: Array<[string, Promise<Pipeline>]> = []; | ||
|
||
static async getInstance(modelName: string): Promise<Pipeline> { | ||
const modelPipeline = this.instances.find(([name]) => name === modelName) | ||
|
||
if (modelPipeline) { | ||
return modelPipeline[1]; | ||
} | ||
|
||
const newModelPipeline = pipeline("feature-extraction", modelName) | ||
this.instances.push([modelName, newModelPipeline]) | ||
|
||
return newModelPipeline; | ||
} | ||
} | ||
|
||
|
||
export async function calculateEmbedding( | ||
modelName: string, | ||
inputs: string[] | ||
) { | ||
const extractor = await XenovaModelsSingleton.getInstance(modelName); | ||
const output: Tensor = await extractor(inputs, { pooling: "mean", normalize: true }); | ||
|
||
return output.tolist(); | ||
} | ||
|
||
|
||
export function embeddingEndpointXenova(input: z.input<typeof embeddingEndpointXenovaParametersSchema>): EmbeddingEndpoint { | ||
const { model } = embeddingEndpointXenovaParametersSchema.parse(input); | ||
|
||
return async ({ inputs }) => { | ||
return calculateEmbedding(model.name, inputs); | ||
}; | ||
} | ||
|
||
export default embeddingEndpointXenova; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
import { | ||
TEXT_EMBEDDING_MODELS, | ||
} from "$env/static/private"; | ||
|
||
import { z } from "zod"; | ||
import { sum } from "$lib/utils/sum"; | ||
import embeddingEndpoints, { embeddingEndpointSchema, type EmbeddingEndpoint } from "./embeddingEndpoints/embeddingEndpoints"; | ||
import embeddingEndpointXenova from "./embeddingEndpoints/xenova/embeddingEndpoints"; | ||
|
||
const modelConfig = z.object({ | ||
/** Used as an identifier in DB */ | ||
id: z.string().optional(), | ||
/** Used to link to the model page, and for inference */ | ||
name: z.string().min(1), | ||
displayName: z.string().min(1).optional(), | ||
description: z.string().min(1).optional(), | ||
websiteUrl: z.string().url().optional(), | ||
modelUrl: z.string().url().optional(), | ||
endpoints: z.array(embeddingEndpointSchema).optional(), | ||
maxSequenceLength: z.number().positive(), | ||
}); | ||
|
||
const embeddingModelsRaw = z.array(modelConfig).parse(JSON.parse(TEXT_EMBEDDING_MODELS)); | ||
|
||
const processEmbeddingModel = async (m: z.infer<typeof modelConfig>) => ({ | ||
...m, | ||
id: m.id || m.name, | ||
}); | ||
|
||
const addEndpoint = (m: Awaited<ReturnType<typeof processEmbeddingModel>>) => ({ | ||
...m, | ||
getEndpoint: async (): Promise<EmbeddingEndpoint> => { | ||
if (!m.endpoints) { | ||
return embeddingEndpointXenova({ | ||
type: "xenova", | ||
weight: 1, | ||
model: m, | ||
}); | ||
} | ||
|
||
const totalWeight = sum(m.endpoints.map((e) => e.weight)); | ||
|
||
let random = Math.random() * totalWeight; | ||
|
||
for (const endpoint of m.endpoints) { | ||
if (random < endpoint.weight) { | ||
const args = { ...endpoint, model: m }; | ||
|
||
switch (args.type) { | ||
case "tei": | ||
return embeddingEndpoints.tei(args); | ||
case "xenova": | ||
return embeddingEndpoints.xenova(args); | ||
} | ||
} | ||
|
||
random -= endpoint.weight; | ||
} | ||
|
||
throw new Error(`Failed to select endpoint`); | ||
}, | ||
}); | ||
|
||
export const embeddingModels = await Promise.all(embeddingModelsRaw.map((e) => processEmbeddingModel(e).then(addEndpoint))); | ||
|
||
export const defaultEmbeddingModel = embeddingModels[0]; | ||
|
||
export const validateEmbeddingModel = (_models: EmbeddingBackendModel[]) => { | ||
// Zod enum function requires 2 parameters | ||
return z.enum([_models[0].id, ..._models.slice(1).map((m) => m.id)]); | ||
}; | ||
|
||
|
||
export type EmbeddingBackendModel = typeof defaultEmbeddingModel; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import { dot } from "@xenova/transformers"; | ||
import type { EmbeddingBackendModel } from "./embeddingModels"; | ||
|
||
// see here: https://github.com/nmslib/hnswlib/blob/359b2ba87358224963986f709e593d799064ace6/README.md?plain=1#L34 | ||
function innerProduct(embeddingA: number[], embeddingB: number[]) { | ||
return 1.0 - dot(embeddingA, embeddingB); | ||
} | ||
|
||
export async function findSimilarSentences( | ||
embeddingModel: EmbeddingBackendModel, | ||
query: string, | ||
sentences: string[], | ||
{ topK = 5 }: { topK: number } | ||
): Promise<number[]> { | ||
const inputs = [query, ...sentences]; | ||
|
||
const embeddingEndpoint = await embeddingModel.getEndpoint(); | ||
const output = await embeddingEndpoint({ inputs }) | ||
|
||
const queryEmbedding: number[] = output[0]; | ||
const sentencesEmbeddings: number[][] = output.slice([1, inputs.length - 1]); | ||
|
||
const distancesFromQuery: { distance: number; index: number }[] = [...sentencesEmbeddings].map( | ||
(sentenceEmbedding: number[], index: number) => { | ||
return { | ||
distance: innerProduct(queryEmbedding, sentenceEmbedding), | ||
index: index, | ||
}; | ||
} | ||
); | ||
|
||
distancesFromQuery.sort((a, b) => { | ||
return a.distance - b.distance; | ||
}); | ||
|
||
// Return the indexes of the closest topK sentences | ||
return distancesFromQuery.slice(0, topK).map((item) => item.index); | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.