컨테이너를 새로 만들 때마다 모델 465MB 를 다시 받았다(실측 2분 49초). 그 사이 첫 발행은 publish 60초 상한을 넘겨 키워드 없이 나간다. 4.x 는 이 변수를 읽지 않고 node_modules 아래에 받아서 ontology-model 볼륨(/app/.cache)이 비어 있었다. - config/env: embedding.cacheDir ← TRANSFORMERS_CACHE - local.provider: transformers.js env.cacheDir 로 넘김 tsc 통과. 로컬 compose: 재생성 후 /app/.cache 465M, 다시 재생성하면 모델 로딩 1.7초 Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
47 lines
1.8 KiB
TypeScript
47 lines
1.8 KiB
TypeScript
import { Injectable, Logger } from '@nestjs/common';
|
|
import { EMBEDDING_DIM, env } from '../config/env';
|
|
import { EmbedKind, EmbeddingProvider } from './types';
|
|
|
|
/** CommonJS 빌드에서 ESM 전용 패키지를 로드하기 위한 우회 (TS 가 require 로 바꾸지 못하게 한다) */
|
|
const esmImport = new Function('s', 'return import(s)') as (s: string) => Promise<any>;
|
|
|
|
/** 로컬 multilingual-e5-small (384차원, onnxruntime CPU). */
|
|
@Injectable()
|
|
export class LocalEmbeddingProvider extends EmbeddingProvider {
|
|
readonly name = 'local:multilingual-e5-small';
|
|
readonly dimensions = EMBEDDING_DIM;
|
|
private readonly logger = new Logger(LocalEmbeddingProvider.name);
|
|
private extractor: any | null = null;
|
|
private loading: Promise<any> | null = null;
|
|
|
|
private async pipe() {
|
|
if (this.extractor) return this.extractor;
|
|
if (!this.loading) {
|
|
this.loading = (async () => {
|
|
const t0 = Date.now();
|
|
const { pipeline, env: tf } = await esmImport('@huggingface/transformers');
|
|
if (env.embedding.cacheDir) tf.cacheDir = env.embedding.cacheDir;
|
|
const fe = await pipeline('feature-extraction', env.embedding.localModel);
|
|
this.logger.log(`model ready: ${env.embedding.localModel} (${Date.now() - t0}ms)`);
|
|
this.extractor = fe;
|
|
return fe;
|
|
})();
|
|
}
|
|
return this.loading;
|
|
}
|
|
|
|
async embed(texts: string[], kind: EmbedKind = 'passage'): Promise<number[][]> {
|
|
if (texts.length === 0) return [];
|
|
const fe = await this.pipe();
|
|
const prefixed = texts.map((t) => `${kind}: ${t}`);
|
|
const out: number[][] = [];
|
|
const BATCH = 64;
|
|
for (let i = 0; i < prefixed.length; i += BATCH) {
|
|
const slice = prefixed.slice(i, i + BATCH);
|
|
const res = await fe(slice, { pooling: 'mean', normalize: true });
|
|
out.push(...(res.tolist() as number[][]));
|
|
}
|
|
return out;
|
|
}
|
|
}
|