macro-memory 0.9.0 → 0.26.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +157 -266
- package/bin/macro-memory.mjs +526 -4
- package/docs/CHANGELOG.md +1120 -1
- package/docs/MAC.md +44 -6
- package/lib/core/client.js +56 -22
- package/lib/core/config.js +15 -2
- package/lib/core/daemon.js +336 -0
- package/lib/core/engine.js +7 -6
- package/lib/core/fence.js +1 -1
- package/lib/core/serve.js +37 -14
- package/lib/core/trust.js +6 -2
- package/lib/index.js +209 -3
- package/lib/macro/contract.js +31 -1
- package/lib/macro/defs/admin.js +4 -4
- package/lib/macro/defs/link.js +96 -9
- package/lib/macro/defs/read.js +11 -1
- package/lib/macro/defs/remember.js +89 -1
- package/lib/macro/defs/search.js +157 -6
- package/lib/macro/dreamledger.js +6 -1
- package/lib/macro/evidence.js +84 -0
- package/lib/macro/fakesites.js +93 -0
- package/lib/macro/fusion.js +16 -2
- package/lib/macro/linkflow.js +130 -5
- package/lib/macro/links.js +69 -0
- package/lib/macro/platform.js +74 -0
- package/lib/macro/portability.js +737 -0
- package/lib/macro/prompt.js +6 -6
- package/lib/macro/revisions.js +3 -13
- package/lib/macro/slots.js +252 -0
- package/lib/macro/snapshot.js +309 -1
- package/lib/macro/tools.js +49 -4
- package/lib/macro/topicpages.js +300 -0
- package/lib/mcp/server.js +6 -1
- package/lib/rerank/download.js +68 -0
- package/lib/rerank/provider.js +507 -0
- package/lib/rerank/runtime.js +246 -0
- package/lib/rerank/tokenizer.js +183 -0
- package/lib/semantic/download.js +68 -0
- package/lib/semantic/provider.js +205 -0
- package/lib/semantic/runtime.js +175 -0
- package/lib/semantic/tokenizer.js +169 -0
- package/package.json +1 -1
- package/vendor/VENDOR.json +4 -4
- package/vendor/dsh-memory-nebula/lib/host/adapters/meow.js +7 -1
- package/vendor/dsh-memory-nebula/lib/host/graph.js +183 -3
- package/vendor/dsh-memory-nebula/lib/index.js +75 -3
- package/vendor/dsh-memory-nebula/lib/web/app.js +5 -0
- package/vendor/dsh-memory-nebula/lib/web/i18n.js +1 -0
- package/vendor/meow-memory/lib/index.js +3205 -167
- package/vendor/meow-memory/lib/prompts/en/labels.md +2 -0
- package/vendor/meow-memory/lib/prompts/en/tools.md +1 -0
- package/vendor/meow-memory/lib/prompts/pt-br/labels.md +2 -0
- package/vendor/meow-memory/lib/prompts/pt-br/tools.md +1 -0
- package/vendor/meow-memory/lib/prompts/zh/labels.md +2 -0
- package/vendor/meow-memory/lib/prompts/zh/tools.md +1 -0
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 最小 cross-encoder 运行时:onnxruntime-node + 自写 WordPiece + 单标量打分。
|
|
3
|
+
*
|
|
4
|
+
* 模型:`Xenova/ms-marco-MiniLM-L-12-v2` 的 int8 量化 onnx(33MB)。
|
|
5
|
+
* 输入 `[CLS] query [SEP] doc [SEP]`,输出一个 logit(越大越相关);这里不做 sigmoid——
|
|
6
|
+
* 引擎侧只按**批内 min-max** 归一后加 `w·top`,绝对水平跨批不可比,sigmooid 会把不同问句的
|
|
7
|
+
* 难度压成同一档(F56 离线实测:prob 融合在 0.1~2.0 权重下读数几乎不动,minmax 才拉得开)。
|
|
8
|
+
*
|
|
9
|
+
* 依赖是**可选**的:`onnxruntime-node` 只是 optionalDependencies,缺了这里返回
|
|
10
|
+
* `{ ok:false, reason }`,检索照旧走词法——「缺失降级」不许变成「装了才不崩」。
|
|
11
|
+
*/
|
|
12
|
+
import { createRequire } from 'node:module'
|
|
13
|
+
import fs from 'node:fs'
|
|
14
|
+
import path from 'node:path'
|
|
15
|
+
import { pathToFileURL } from 'node:url'
|
|
16
|
+
|
|
17
|
+
/** 模型文件名 → 期望的最小字节数(防半截文件当成可用模型)。 */
|
|
18
|
+
export const MODEL_FILES = {
|
|
19
|
+
'model_quantized.onnx': 30 * 1024 * 1024,
|
|
20
|
+
'vocab.txt': 200 * 1024,
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** 多语种 CE(`bge-reranker-base` 的 XLM-R 量化导出):分词器是 SentencePiece,
|
|
24
|
+
* 目录里给的是 `tokenizer.json`(17MB)而不是 `vocab.txt`,权重也大一个量级。
|
|
25
|
+
* 为什么值得多背一份:中文问句在 0.24.8 之前一次都进不了 CE(语言门),而 zh-sem 上
|
|
26
|
+
* 单是这一个模型就把 hit@1 从 0.5625 拉到 0.8750(详见 docs/EVAL-CLAIMS.md)。 */
|
|
27
|
+
export const SP_MODEL_FILES = {
|
|
28
|
+
'model_quantized.onnx': 250 * 1024 * 1024,
|
|
29
|
+
'tokenizer.json': 8 * 1024 * 1024,
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** 目录用哪种分词器:有 tokenizer.json 就是 SentencePiece(XLM-R 系),否则按 WordPiece。
|
|
33
|
+
* 用**文件存在**判而不是目录名判——用户可以把模型放任何地方、叫任何名字。 */
|
|
34
|
+
export const tokenizerKindOf = (modelDir) => {
|
|
35
|
+
try {
|
|
36
|
+
return fs.existsSync(path.join(modelDir, 'tokenizer.json')) ? 'sentencepiece' : 'wordpiece'
|
|
37
|
+
} catch {
|
|
38
|
+
return 'wordpiece'
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** 这个文件的真实位置:优先目录根,其次 HF 仓库原样的 `onnx/` 子目录。
|
|
43
|
+
* 为什么要两处都认:我们自己下的老模型落平铺(下载器写的是文件名),而从 HF 仓库整包拷来的
|
|
44
|
+
* 多语种模型保留 `onnx/model_quantized.onnx`——同一个目录结构不该因为来源不同就判「没装好」。 */
|
|
45
|
+
export const modelFilePathOf = (modelDir, name) => {
|
|
46
|
+
const flat = path.join(modelDir, name)
|
|
47
|
+
try {
|
|
48
|
+
if (fs.existsSync(flat)) return flat
|
|
49
|
+
} catch { /* 落到下面的候选 */ }
|
|
50
|
+
const nested = path.join(modelDir, 'onnx', name)
|
|
51
|
+
try {
|
|
52
|
+
if (fs.existsSync(nested)) return nested
|
|
53
|
+
} catch { /* 回平铺路径,交给调用方报那一条 */ }
|
|
54
|
+
return flat
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 这套目录该验哪几个文件。 */
|
|
58
|
+
export const modelFilesOf = (modelDir) =>
|
|
59
|
+
tokenizerKindOf(modelDir) === 'sentencepiece' ? SP_MODEL_FILES : MODEL_FILES
|
|
60
|
+
|
|
61
|
+
export function modelReady(modelDir) {
|
|
62
|
+
if (!modelDir || !fs.existsSync(modelDir)) return false
|
|
63
|
+
for (const [name, minBytes] of Object.entries(modelFilesOf(modelDir))) {
|
|
64
|
+
const file = modelFilePathOf(modelDir, name)
|
|
65
|
+
try {
|
|
66
|
+
const st = fs.statSync(file)
|
|
67
|
+
if (!st.isFile() || st.size < minBytes) return false
|
|
68
|
+
} catch {
|
|
69
|
+
return false
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return true
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function requireFrom(base) {
|
|
76
|
+
// 生产环境 base 是插件包自己的目录;探针可以借一个装着 ORT 的目录来跑对齐。
|
|
77
|
+
return createRequire(base)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 只有在**目录用的是 SentencePiece 分词器**时才需要 `@huggingface/transformers`:
|
|
82
|
+
* 它是可选依赖,找不到就返回 null,调用方退回 `{ok:false, reason:'tokenizer-module-missing'}`,
|
|
83
|
+
* 检索照旧走词法。查找顺序与稠密侧同源:显式 opts > 两个环境变量 > 从 ORT 基座 resolve。
|
|
84
|
+
*/
|
|
85
|
+
async function loadTransformers(opts) {
|
|
86
|
+
const seen = new Set()
|
|
87
|
+
const tryPath = async (raw) => {
|
|
88
|
+
const p = String(raw ?? '').trim()
|
|
89
|
+
if (p.length === 0 || seen.has(p)) return null
|
|
90
|
+
seen.add(p)
|
|
91
|
+
try {
|
|
92
|
+
const href = p.startsWith('file:') ? p : pathToFileURL(p).href
|
|
93
|
+
return await import(href)
|
|
94
|
+
} catch {
|
|
95
|
+
return null
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
for (const cand of [opts.tokenizerModule, process.env.DSH_RERANK_TOKENIZER_MODULE, process.env.MEOW_VEC_MODULE]) {
|
|
99
|
+
const got = await tryPath(cand)
|
|
100
|
+
if (got !== null) return got
|
|
101
|
+
}
|
|
102
|
+
try {
|
|
103
|
+
const req = requireFrom(opts.requireFrom ?? import.meta.url)
|
|
104
|
+
const resolved = req.resolve('@huggingface/transformers')
|
|
105
|
+
return await import(pathToFileURL(resolved).href)
|
|
106
|
+
} catch {
|
|
107
|
+
return null
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* @param {{modelDir: string, requireFrom?: string|URL, intraOpThreads?: number, batch?: number,
|
|
113
|
+
* maxLen?: number, tokenizerModule?: string}} opts
|
|
114
|
+
* @returns {Promise<{ok: true, score(pairs: [string, string][]): Promise<number[]>,
|
|
115
|
+
* count: number, dispose(): Promise<void>} | {ok: false, reason: string}>}
|
|
116
|
+
*/
|
|
117
|
+
export async function openRuntime(opts = {}) {
|
|
118
|
+
const modelDir = opts.modelDir
|
|
119
|
+
if (!modelReady(modelDir)) return { ok: false, reason: 'model-missing' }
|
|
120
|
+
|
|
121
|
+
let ort
|
|
122
|
+
try {
|
|
123
|
+
const req = requireFrom(opts.requireFrom ?? import.meta.url)
|
|
124
|
+
ort = req('onnxruntime-node')
|
|
125
|
+
} catch (err) {
|
|
126
|
+
return { ok: false, reason: `onnxruntime-node-missing: ${err && err.message ? err.message : err}` }
|
|
127
|
+
}
|
|
128
|
+
// 有些版本把 API 挂在 default 上(CJS 互操作差异),两种都认。
|
|
129
|
+
const ortApi = ort && ort.InferenceSession ? ort : ort && ort.default ? ort.default : null
|
|
130
|
+
if (!ortApi || typeof ortApi.InferenceSession?.create !== 'function') {
|
|
131
|
+
return { ok: false, reason: 'onnxruntime-node-broken' }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
let session
|
|
135
|
+
try {
|
|
136
|
+
session = await ortApi.InferenceSession.create(modelFilePathOf(modelDir, 'model_quantized.onnx'), {
|
|
137
|
+
executionProviders: ['cpu'],
|
|
138
|
+
graphOptimizationLevel: 'all',
|
|
139
|
+
intraOpNumThreads: Number.isFinite(opts.intraOpThreads) ? opts.intraOpThreads : 2,
|
|
140
|
+
})
|
|
141
|
+
} catch (err) {
|
|
142
|
+
return { ok: false, reason: `session: ${err && err.message ? err.message : err}` }
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const kind = tokenizerKindOf(modelDir)
|
|
146
|
+
/** 把一批 pair 编码成 {ids, mask, rows, width}:两种分词器共用这一张形状,后面的张量代码只有一份。 */
|
|
147
|
+
let encodeBatch
|
|
148
|
+
try {
|
|
149
|
+
const defaultLen = kind === 'sentencepiece' ? 256 : 192
|
|
150
|
+
const maxLen = Number.isFinite(opts.maxLen) ? opts.maxLen : defaultLen
|
|
151
|
+
if (kind === 'sentencepiece') {
|
|
152
|
+
const mod = await loadTransformers(opts)
|
|
153
|
+
if (mod === null) {
|
|
154
|
+
await session.release?.()
|
|
155
|
+
return { ok: false, reason: 'tokenizer-module-missing' }
|
|
156
|
+
}
|
|
157
|
+
const tok = await mod.AutoTokenizer.from_pretrained(modelDir, { local_files_only: true })
|
|
158
|
+
encodeBatch = async (pairs) => {
|
|
159
|
+
const enc = await tok(pairs.map((p) => p[0]), {
|
|
160
|
+
text_pair: pairs.map((p) => p[1]),
|
|
161
|
+
padding: true,
|
|
162
|
+
truncation: true,
|
|
163
|
+
max_length: maxLen,
|
|
164
|
+
})
|
|
165
|
+
const ids = enc.input_ids
|
|
166
|
+
const [rows, width] = ids.dims
|
|
167
|
+
return {
|
|
168
|
+
ids: BigInt64Array.from(ids.data),
|
|
169
|
+
mask: BigInt64Array.from(enc.attention_mask.data),
|
|
170
|
+
rows,
|
|
171
|
+
width,
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
} else {
|
|
175
|
+
const vocabText = fs.readFileSync(path.join(modelDir, 'vocab.txt'), 'utf8')
|
|
176
|
+
const { WordPieceTokenizer } = await import('./tokenizer.js')
|
|
177
|
+
const tokenizer = WordPieceTokenizer.fromVocabText(vocabText, { maxLen })
|
|
178
|
+
encodeBatch = async (pairs) => {
|
|
179
|
+
const encoded = pairs.map(([q, d]) => tokenizer.encodePair(q, d))
|
|
180
|
+
const width = encoded.reduce((m, e) => Math.max(m, e.inputIds.length), 1)
|
|
181
|
+
const rows = encoded.length
|
|
182
|
+
const ids = new BigInt64Array(rows * width)
|
|
183
|
+
const mask = new BigInt64Array(rows * width)
|
|
184
|
+
for (let r = 0; r < rows; r += 1) {
|
|
185
|
+
const { inputIds, attentionMask } = encoded[r]
|
|
186
|
+
for (let c = 0; c < width; c += 1) {
|
|
187
|
+
const at = r * width + c
|
|
188
|
+
ids[at] = BigInt(inputIds[c] ?? tokenizer.padId)
|
|
189
|
+
mask[at] = BigInt(attentionMask[c] ?? 0)
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return { ids, mask, rows, width }
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
} catch (err) {
|
|
196
|
+
await session.release?.()
|
|
197
|
+
return { ok: false, reason: `tokenizer: ${err && err.message ? err.message : err}` }
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const Tensor = ortApi.Tensor
|
|
201
|
+
const inputNames = new Set(session.inputNames ?? [])
|
|
202
|
+
const wantsTokenTypes = inputNames.has('token_type_ids')
|
|
203
|
+
const batchSize = Math.max(1, Number.isFinite(opts.batch) ? opts.batch : 16)
|
|
204
|
+
let count = 0
|
|
205
|
+
|
|
206
|
+
/** 一批(≤ batchSize 对)编码成一个 int64 张量,长度按批内最长补齐。 */
|
|
207
|
+
async function batchTensor(pairs) {
|
|
208
|
+
const { ids, mask, rows, width } = await encodeBatch(pairs)
|
|
209
|
+
const feeds = {
|
|
210
|
+
input_ids: new Tensor('int64', ids, [rows, width]),
|
|
211
|
+
attention_mask: new Tensor('int64', mask, [rows, width]),
|
|
212
|
+
}
|
|
213
|
+
if (wantsTokenTypes) feeds.token_type_ids = new Tensor('int64', new BigInt64Array(rows * width), [rows, width])
|
|
214
|
+
return { feeds, rows }
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async function score(pairs) {
|
|
218
|
+
const list = Array.isArray(pairs) ? pairs : []
|
|
219
|
+
const out = new Array(list.length)
|
|
220
|
+
for (let start = 0; start < list.length; start += batchSize) {
|
|
221
|
+
const chunk = list.slice(start, start + batchSize).map((p) => [
|
|
222
|
+
typeof p?.[0] === 'string' ? p[0] : String(p?.[0] ?? ''),
|
|
223
|
+
typeof p?.[1] === 'string' ? p[1] : String(p?.[1] ?? ''),
|
|
224
|
+
])
|
|
225
|
+
const { feeds, rows } = await batchTensor(chunk)
|
|
226
|
+
const result = await session.run(feeds)
|
|
227
|
+
const first = result[session.outputNames?.[0]] ?? Object.values(result)[0]
|
|
228
|
+
const data = first?.data
|
|
229
|
+
if (!data || typeof data.length !== 'number') throw new Error('unexpected model output')
|
|
230
|
+
for (let i = 0; i < rows; i += 1) out[start + i] = Number(data[i])
|
|
231
|
+
count += rows
|
|
232
|
+
}
|
|
233
|
+
return out
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
return {
|
|
237
|
+
ok: true,
|
|
238
|
+
score,
|
|
239
|
+
get count() {
|
|
240
|
+
return count
|
|
241
|
+
},
|
|
242
|
+
async dispose() {
|
|
243
|
+
await session.release?.()
|
|
244
|
+
},
|
|
245
|
+
}
|
|
246
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 最小 BERT WordPiece 分词器(只为 bge-* 这类英文 BertModel 服务)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么自己写:`@huggingface/transformers` 全家桶一次装 376MB / 3000+ 文件,
|
|
5
|
+
* 我们要的只是「一段文字 → input_ids」,tokenizer.json 里那套图灵完备的
|
|
6
|
+
* pipeline 用不上。这里按 HuggingFace `BertTokenizer` 的语义逐条照搬:
|
|
7
|
+
* basic tokenize(小写、NFC、按空白与标点切、CJK 逐字) → wordpiece(贪心最长匹配,`##` 续接)。
|
|
8
|
+
* 与 Python 侧逐字对齐由 `tools/probe-semantic-align.mjs` 守着(余弦 ≥0.999)。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const PAD = '[PAD]'
|
|
12
|
+
const UNK = '[UNK]'
|
|
13
|
+
const CLS = '[CLS]'
|
|
14
|
+
const SEP = '[SEP]'
|
|
15
|
+
|
|
16
|
+
// HuggingFace 的 `is_whitespace` 看的是 Unicode 空白类,`is_punctuation` 看的是 Unicode 标点类
|
|
17
|
+
// (`P*`)——只判 ASCII 会把 `’` `—` `…` 这类符号粘进单词,实测余弦掉到 0.992(对齐探针里那条
|
|
18
|
+
// `LOW 0|D8:13`)。这里直接用 Unicode 属性类,和 Python 侧逐字一致。
|
|
19
|
+
const RE_WS = /[\s\p{Zs}]/u
|
|
20
|
+
const RE_PUNCT = /\p{P}/u
|
|
21
|
+
|
|
22
|
+
function isWhitespace(ch) {
|
|
23
|
+
return RE_WS.test(ch)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function isPunctuation(ch) {
|
|
27
|
+
// 先判 ASCII 区间再判 Unicode 标点类——`+` `=` `$` 这些属于 Symbol 类(`\p{S}`),不是 `\p{P}`,
|
|
28
|
+
// 但 Java 的 isPunctuation 对 ASCII 33-47/58-64/91-96/123-126 一律算标点(`LGBTQ+` 必须切成
|
|
29
|
+
// `lgbt`,`##q`,`+`)。只判 `\p{P}` 会切出 `##+`,200 条里有 4 条踩到。
|
|
30
|
+
const code = ch.codePointAt(0)
|
|
31
|
+
if (code >= 33 && code <= 47) return true
|
|
32
|
+
if (code >= 58 && code <= 64) return true
|
|
33
|
+
if (code >= 91 && code <= 96) return true
|
|
34
|
+
if (code >= 123 && code <= 126) return true
|
|
35
|
+
return RE_PUNCT.test(ch)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function isControl(ch) {
|
|
39
|
+
const code = ch.codePointAt(0)
|
|
40
|
+
if (code === 0x09 || code === 0x0a || code === 0x0d) return false
|
|
41
|
+
if (code < 0x20) return true
|
|
42
|
+
if (code >= 0x7f && code <= 0x9f) return true
|
|
43
|
+
return false
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function isChinese(ch) {
|
|
47
|
+
const c = ch.codePointAt(0)
|
|
48
|
+
return (
|
|
49
|
+
(c >= 0x4e00 && c <= 0x9fff) ||
|
|
50
|
+
(c >= 0x3400 && c <= 0x4dbf) ||
|
|
51
|
+
(c >= 0x20000 && c <= 0x2a6df) ||
|
|
52
|
+
(c >= 0x2a700 && c <= 0x2b73f) ||
|
|
53
|
+
(c >= 0x2b740 && c <= 0x2b81f) ||
|
|
54
|
+
(c >= 0x2b820 && c <= 0x2ceaf) ||
|
|
55
|
+
(c >= 0xf900 && c <= 0xfaff) ||
|
|
56
|
+
(c >= 0x2f800 && c <= 0x2fa1f)
|
|
57
|
+
)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** 归一化:去控制字符 → 小写 → 去重音(NFD 后删 Mn)。这三步对应 BertNormalizer 的
|
|
61
|
+
* `clean_text` / `lowercase` / `strip_accents`(bert-uncased 里 strip_accents 缺省跟随小写=开)。 */
|
|
62
|
+
function normalize(text) {
|
|
63
|
+
let out = ''
|
|
64
|
+
for (const ch of text) {
|
|
65
|
+
if (isWhitespace(ch)) {
|
|
66
|
+
// clean_text 把任何空白换成普通空格,保证后面按空白切分时口径一致。
|
|
67
|
+
out += ' '
|
|
68
|
+
continue
|
|
69
|
+
}
|
|
70
|
+
if (isControl(ch)) continue
|
|
71
|
+
if (ch === '\u0000' || ch === '\ufffd') continue
|
|
72
|
+
out += ch
|
|
73
|
+
}
|
|
74
|
+
return out.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '')
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** basic tokenize:空白切开,再把标点单独切成一个 token,CJK 每字一个 token。 */
|
|
78
|
+
function basicTokenize(text) {
|
|
79
|
+
const pieces = []
|
|
80
|
+
let buf = ''
|
|
81
|
+
const flush = () => {
|
|
82
|
+
if (buf.length > 0) {
|
|
83
|
+
pieces.push(buf)
|
|
84
|
+
buf = ''
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
for (const ch of text) {
|
|
88
|
+
if (isWhitespace(ch)) {
|
|
89
|
+
flush()
|
|
90
|
+
continue
|
|
91
|
+
}
|
|
92
|
+
if (isPunctuation(ch) || isChinese(ch)) {
|
|
93
|
+
flush()
|
|
94
|
+
pieces.push(ch)
|
|
95
|
+
continue
|
|
96
|
+
}
|
|
97
|
+
buf += ch
|
|
98
|
+
}
|
|
99
|
+
flush()
|
|
100
|
+
return pieces
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export class WordPieceTokenizer {
|
|
104
|
+
/**
|
|
105
|
+
* @param {{vocab: string[], maxLen?: number, maxCharsPerWord?: number}} opts
|
|
106
|
+
* `vocab` 是 vocab.txt 的行序(下标即 id)。
|
|
107
|
+
*/
|
|
108
|
+
constructor({ vocab, maxLen = 256, maxCharsPerWord = 100 }) {
|
|
109
|
+
this.ids = new Map()
|
|
110
|
+
vocab.forEach((tok, i) => {
|
|
111
|
+
if (!this.ids.has(tok)) this.ids.set(tok, i)
|
|
112
|
+
})
|
|
113
|
+
this.unkId = this.ids.get(UNK) ?? 100
|
|
114
|
+
this.clsId = this.ids.get(CLS) ?? 101
|
|
115
|
+
this.sepId = this.ids.get(SEP) ?? 102
|
|
116
|
+
this.padId = this.ids.get(PAD) ?? 0
|
|
117
|
+
this.maxLen = maxLen
|
|
118
|
+
this.maxCharsPerWord = maxCharsPerWord
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
static fromVocabText(text, opts = {}) {
|
|
122
|
+
// vocab.txt 一行一个 token;末尾可能有空行,统一去掉(去重仍按下标,见构造函数)。
|
|
123
|
+
const vocab = String(text).split(/\r?\n/)
|
|
124
|
+
while (vocab.length > 0 && vocab[vocab.length - 1] === '') vocab.pop()
|
|
125
|
+
return new WordPieceTokenizer({ ...opts, vocab })
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
#wordpiece(piece) {
|
|
129
|
+
if (piece.length > this.maxCharsPerWord) return [this.unkId]
|
|
130
|
+
const ids = []
|
|
131
|
+
let start = 0
|
|
132
|
+
while (start < piece.length) {
|
|
133
|
+
let end = piece.length
|
|
134
|
+
let cur = -1
|
|
135
|
+
while (start < end) {
|
|
136
|
+
let sub = piece.slice(start, end)
|
|
137
|
+
if (start > 0) sub = `##${sub}`
|
|
138
|
+
const hit = this.ids.get(sub)
|
|
139
|
+
if (hit !== undefined) {
|
|
140
|
+
cur = hit
|
|
141
|
+
break
|
|
142
|
+
}
|
|
143
|
+
end -= 1
|
|
144
|
+
}
|
|
145
|
+
if (cur < 0) return [this.unkId]
|
|
146
|
+
ids.push(cur)
|
|
147
|
+
start = end
|
|
148
|
+
}
|
|
149
|
+
return ids
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** @returns {number[]} 不含特殊 token 的正文 id 串。 */
|
|
153
|
+
encode(text) {
|
|
154
|
+
const out = []
|
|
155
|
+
for (const piece of basicTokenize(normalize(text))) {
|
|
156
|
+
for (const id of this.#wordpiece(piece)) out.push(id)
|
|
157
|
+
}
|
|
158
|
+
return out
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** @returns {{inputIds: number[], attentionMask: number[]}} 含 [CLS]/[SEP],已按 maxLen 截断。 */
|
|
162
|
+
encodeForModel(text) {
|
|
163
|
+
const body = this.encode(text)
|
|
164
|
+
const room = Math.max(1, this.maxLen - 2)
|
|
165
|
+
const trimmed = body.length > room ? body.slice(0, room) : body
|
|
166
|
+
const inputIds = [this.clsId, ...trimmed, this.sepId]
|
|
167
|
+
return { inputIds, attentionMask: new Array(inputIds.length).fill(1) }
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** [rerank 0.21.0 · F56] cross-encoder 的成对编码:`[CLS] q [SEP] d [SEP]`。
|
|
171
|
+
* 截断只从**文档侧**尾巴切:问句是被评的对象,切掉它等于换了问题;文档本来就是长文,
|
|
172
|
+
* 尾巴进不了模型也只是少一点上下文(CE 只看前 192 token 够用,见 F56 的 maxLen 读数)。 */
|
|
173
|
+
encodePair(query, doc) {
|
|
174
|
+
const q = this.encode(query)
|
|
175
|
+
const room = Math.max(1, this.maxLen - 3)
|
|
176
|
+
const qTrim = q.length > room ? q.slice(0, room) : q
|
|
177
|
+
const left = Math.max(0, room - qTrim.length)
|
|
178
|
+
const d = this.encode(doc)
|
|
179
|
+
const dTrim = d.length > left ? d.slice(0, left) : d
|
|
180
|
+
const inputIds = [this.clsId, ...qTrim, this.sepId, ...dTrim, this.sepId]
|
|
181
|
+
return { inputIds, attentionMask: new Array(inputIds.length).fill(1) }
|
|
182
|
+
}
|
|
183
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 模型文件按需下载:只拉「量化 onnx + vocab.txt」这两个,合计约 34MB。
|
|
3
|
+
*
|
|
4
|
+
* 规则(对应主人定的口径「33MB 模型按需下载不算太大代价」):
|
|
5
|
+
* - 默认不预装、不打包进 npm 包;第一次真正用到语义通道时才在后台下。
|
|
6
|
+
* - 先写 `.part` 再原子改名:下到一半断电/断网,下次不会把半截文件当模型用。
|
|
7
|
+
* - 只认 hf-mirror(`HF_ENDPOINT` 可改),一条 URL 失败不再试第二条同义源——
|
|
8
|
+
* 下载失败就是失败,检索退回词法,不阻塞用户。
|
|
9
|
+
* - 全程不抛:返回 `{ ok, reason }`,由调用方记一条日志。
|
|
10
|
+
*/
|
|
11
|
+
import fs from 'node:fs'
|
|
12
|
+
import fsp from 'node:fs/promises'
|
|
13
|
+
import path from 'node:path'
|
|
14
|
+
|
|
15
|
+
const HF_BASE = () => (process.env.HF_ENDPOINT || 'https://hf-mirror.com').replace(/\/+$/, '')
|
|
16
|
+
const REPO = 'Xenova/bge-small-en-v1.5'
|
|
17
|
+
|
|
18
|
+
/** 文件名 → 仓库内相对路径。`model_quantized.onnx` 在 `onnx/` 子目录下。 */
|
|
19
|
+
export const FILES = {
|
|
20
|
+
'model_quantized.onnx': 'onnx/model_quantized.onnx',
|
|
21
|
+
'vocab.txt': 'vocab.txt',
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async function fetchTo(url, dest) {
|
|
25
|
+
const res = await fetch(url, { redirect: 'follow' })
|
|
26
|
+
if (!res.ok || !res.body) throw new Error(`HTTP ${res.status} ${url}`)
|
|
27
|
+
const part = `${dest}.part`
|
|
28
|
+
await fsp.mkdir(path.dirname(dest), { recursive: true })
|
|
29
|
+
const out = fs.createWriteStream(part)
|
|
30
|
+
try {
|
|
31
|
+
for await (const chunk of res.body) {
|
|
32
|
+
if (!out.write(chunk)) await new Promise((r) => out.once('drain', r))
|
|
33
|
+
}
|
|
34
|
+
} finally {
|
|
35
|
+
await new Promise((r) => out.end(r))
|
|
36
|
+
}
|
|
37
|
+
const size = (await fsp.stat(part)).size
|
|
38
|
+
if (size === 0) throw new Error(`empty body ${url}`)
|
|
39
|
+
await fsp.rename(part, dest)
|
|
40
|
+
return size
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* @param {{dir: string, log?: (m: string) => void, signal?: AbortSignal}} opts
|
|
45
|
+
* @returns {Promise<{ok: true, bytes: number} | {ok: false, reason: string}>}
|
|
46
|
+
*/
|
|
47
|
+
export async function downloadModel({ dir, log } = {}) {
|
|
48
|
+
const say = typeof log === 'function' ? log : () => {}
|
|
49
|
+
if (!dir) return { ok: false, reason: 'no-model-dir' }
|
|
50
|
+
let bytes = 0
|
|
51
|
+
try {
|
|
52
|
+
for (const [name, rel] of Object.entries(FILES)) {
|
|
53
|
+
const dest = path.join(dir, name)
|
|
54
|
+
if (fs.existsSync(dest)) {
|
|
55
|
+
bytes += fs.statSync(dest).size
|
|
56
|
+
continue
|
|
57
|
+
}
|
|
58
|
+
const url = `${HF_BASE()}/${REPO}/resolve/main/${rel}`
|
|
59
|
+
say(`[semantic] 下载 ${name} ← ${url}`)
|
|
60
|
+
const size = await fetchTo(url, dest)
|
|
61
|
+
bytes += size
|
|
62
|
+
say(`[semantic] ${name} ${(size / 1048576).toFixed(1)}MB 就绪`)
|
|
63
|
+
}
|
|
64
|
+
return { ok: true, bytes }
|
|
65
|
+
} catch (err) {
|
|
66
|
+
return { ok: false, reason: String(err && err.message ? err.message : err) }
|
|
67
|
+
}
|
|
68
|
+
}
|