feat(qmd): switch to Qwen3 4B embedding and reranker models
Use Qwen3-Embedding-4B and Qwen3-Reranker-4B (both Q4_K_M) for QMD local search, and make the switch reach existing installations: - Rewrite the setup-owned models block on every install and update, while still recording the user's original block only once. - When the new embedding size no longer matches stored vectors, the daemon clears the old vectors and re-embeds the repository. - Delete setup-downloaded model files the current models no longer use. - Skip npm and pnpm lockfiles and minified bundles when indexing repositories, which saves embedding work and removes search noise. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3fcd7bcbfd
commit
ca4cb2a144
8 files changed
+112
-9
No files matched your search
@@ -99,7 +99,7 @@ Install and update also rebuild internally; the explicit build above lets you ch
|
|||||||
- User-level extension installation for Ponytail, i-have-adhd, Superpowers, Context7, Caveman, MCPorter,
|
- User-level extension installation for Ponytail, i-have-adhd, Superpowers, Context7, Caveman, MCPorter,
|
||||||
Humanizer, Impeccable, Anthropic Frontend Design, and REA, with an interactive extension toggle during both install and update. Only extensions
|
Humanizer, Impeccable, Anthropic Frontend Design, and REA, with an interactive extension toggle during both install and update. Only extensions
|
||||||
installed and recorded by this setup can be removed through deselection.
|
installed and recorded by this setup can be removed through deselection.
|
||||||
- Optional local search for both clients through QMD with Qwen3-Embedding-0.6B, Qwen3-Reranker-0.6B, and QMD Query Expansion 1.7B (Yes/No/Auto; Auto benchmarks GPU, then CPU).
|
- Optional local search for both clients through QMD with Qwen3-Embedding-4B, Qwen3-Reranker-4B, and QMD Query Expansion 1.7B (Yes/No/Auto; Auto benchmarks GPU, then CPU).
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
|
|||||||
@@ -79,8 +79,13 @@ Quickupdate reuses the saved choice and device; it does not rerun the benchmark.
|
|||||||
- **No:** omit the search skill and its instruction line, remove the warm-up hook registration,
|
- **No:** omit the search skill and its instruction line, remove the warm-up hook registration,
|
||||||
and disable search for the selected clients. Dry runs do not download, benchmark, or remove QMD resources.
|
and disable search for the selected clients. Dry runs do not download, benchmark, or remove QMD resources.
|
||||||
|
|
||||||
The models are Qwen3-Embedding-0.6B, Qwen3-Reranker-0.6B, and QMD Query Expansion 1.7B.
|
The models are Qwen3-Embedding-4B, Qwen3-Reranker-4B, and QMD Query Expansion 1.7B.
|
||||||
Exact model URIs live in [`shared/qmd/qmd-lib.mjs`](../shared/qmd/qmd-lib.mjs).
|
Exact model URIs live in [`shared/qmd/qmd-lib.mjs`](../shared/qmd/qmd-lib.mjs).
|
||||||
|
Install and update rewrite the setup-owned `models:` block, so changed models reach existing installations.
|
||||||
|
When a new embedding model produces vectors of another size, the daemon clears all old vectors and
|
||||||
|
re-embeds each repository on its next search; run `qmd embed` to re-embed your own QMD collections.
|
||||||
|
Install and update also delete model files the setup downloaded that the current models no longer use.
|
||||||
|
Repository indexes skip git-ignored files, npm and pnpm lockfiles, and minified `*.min.js` bundles.
|
||||||
Auto thresholds can be overridden with `QMD_BENCHMARK_MAX_QUERY_SECONDS` and
|
Auto thresholds can be overridden with `QMD_BENCHMARK_MAX_QUERY_SECONDS` and
|
||||||
`QMD_BENCHMARK_MIN_CHUNKS_PER_SECOND`. The benchmark uses a temporary database and a deterministic
|
`QMD_BENCHMARK_MIN_CHUNKS_PER_SECOND`. The benchmark uses a temporary database and a deterministic
|
||||||
100-document fixture; its measurements are not an end-to-end estimate for a user's repository.
|
100-document fixture; its measurements are not an end-to-end estimate for a user's repository.
|
||||||
|
|||||||
+33
-2
@@ -59,6 +59,14 @@ def node_version_ok(text):
|
|||||||
return bool(match) and int(match.group(1)) >= 22
|
return bool(match) and int(match.group(1)) >= 22
|
||||||
|
|
||||||
|
|
||||||
|
def model_files(text):
|
||||||
|
"""Cache file names node-llama-cpp gives the hf: model URIs in qmd-lib.mjs: hf_<owner>_<file> plus <file>.etag."""
|
||||||
|
names = set()
|
||||||
|
for owner, file in re.findall(r"'hf:([^/']+)/[^/']+/([^/']+\.gguf)'", text):
|
||||||
|
names |= {f'hf_{owner}_{file}', f'{file}.etag'}
|
||||||
|
return names
|
||||||
|
|
||||||
|
|
||||||
def digest(path):
|
def digest(path):
|
||||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||||
|
|
||||||
@@ -176,8 +184,9 @@ class Setup:
|
|||||||
state['owned_package'] = True
|
state['owned_package'] = True
|
||||||
self.install_scripts(state)
|
self.install_scripts(state)
|
||||||
atomic_json(self.state_path, state)
|
atomic_json(self.state_path, state)
|
||||||
if not state['models_block']:
|
# Rewrite the setup-owned block on every run so changed default models reach existing installs.
|
||||||
output = self.node('qmd-config.mjs', 'set-models')
|
output = self.node('qmd-config.mjs', 'set-models')
|
||||||
|
if not state['models_block']:
|
||||||
try:
|
try:
|
||||||
previous = json.loads(output.strip().splitlines()[-1])['previous']
|
previous = json.loads(output.strip().splitlines()[-1])['previous']
|
||||||
except (IndexError, KeyError, TypeError, json.JSONDecodeError):
|
except (IndexError, KeyError, TypeError, json.JSONDecodeError):
|
||||||
@@ -190,6 +199,28 @@ class Setup:
|
|||||||
after = {p.name for p in self.models.iterdir()} if self.models.is_dir() else set()
|
after = {p.name for p in self.models.iterdir()} if self.models.is_dir() else set()
|
||||||
state['owned_models'] = sorted(set(state['owned_models']) | (after - before))
|
state['owned_models'] = sorted(set(state['owned_models']) | (after - before))
|
||||||
atomic_json(self.state_path, state)
|
atomic_json(self.state_path, state)
|
||||||
|
self.prune_models(state)
|
||||||
|
|
||||||
|
def prune_models(self, state):
|
||||||
|
"""Delete setup-downloaded model files the current models no longer use; foreign files stay."""
|
||||||
|
current = model_files((self.root / 'shared' / 'qmd' / 'qmd-lib.mjs').read_text(encoding='utf-8'))
|
||||||
|
if not current: # an unparsable model list must never delete every model
|
||||||
|
return
|
||||||
|
kept = []
|
||||||
|
for name in state['owned_models']:
|
||||||
|
if name in current:
|
||||||
|
kept.append(name)
|
||||||
|
continue
|
||||||
|
path = self.models / name
|
||||||
|
if name != Path(name).name or not path.is_file() or path.is_symlink():
|
||||||
|
continue # already gone, or not a plain file the setup can safely delete
|
||||||
|
try:
|
||||||
|
path.unlink()
|
||||||
|
except OSError as error: # a running daemon may still hold it; the next update retries
|
||||||
|
print(f'QMD local search: could not delete unused model {name}: {error}', file=sys.stderr)
|
||||||
|
kept.append(name)
|
||||||
|
state['owned_models'] = sorted(kept)
|
||||||
|
atomic_json(self.state_path, state)
|
||||||
|
|
||||||
def detect_gpu(self):
|
def detect_gpu(self):
|
||||||
try:
|
try:
|
||||||
@@ -205,7 +236,7 @@ class Setup:
|
|||||||
def enable(self, clients):
|
def enable(self, clients):
|
||||||
state = self.load()
|
state = self.load()
|
||||||
if self.dry_run:
|
if self.dry_run:
|
||||||
self.say('DRYRUN enable QMD local search: Qwen3-Embedding-0.6B, Qwen3-Reranker-0.6B, QMD query expansion 1.7B')
|
self.say('DRYRUN enable QMD local search: Qwen3-Embedding-4B, Qwen3-Reranker-4B, QMD query expansion 1.7B')
|
||||||
return
|
return
|
||||||
self.install(state)
|
self.install(state)
|
||||||
if state['device'] is None:
|
if state['device'] is None:
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { execFileSync } from 'node:child_process';
|
|||||||
import { existsSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs';
|
import { existsSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs';
|
||||||
import { tmpdir } from 'node:os';
|
import { tmpdir } from 'node:os';
|
||||||
import { join, resolve } from 'node:path';
|
import { join, resolve } from 'node:path';
|
||||||
import { acquireStartLock, createServer, gitFingerprint, ignoreGlobs, keepModelsLoaded } from '../../shared/qmd/qmd-daemon.mjs';
|
import { INDEX_EXCLUDES, acquireStartLock, createServer, gitFingerprint, ignoreGlobs, indexIgnores, keepModelsLoaded } from '../../shared/qmd/qmd-daemon.mjs';
|
||||||
import { collectionName } from '../../shared/qmd/qmd-lib.mjs';
|
import { collectionName } from '../../shared/qmd/qmd-lib.mjs';
|
||||||
|
|
||||||
const defaultHits = () => [{ displayPath: `${collectionName('/r')}/src/a.ts`, body: 'x\nretry here', bestChunkPos: 2, bestChunk: 'retry here', score: 0.91 }];
|
const defaultHits = () => [{ displayPath: `${collectionName('/r')}/src/a.ts`, body: 'x\nretry here', bestChunkPos: 2, bestChunk: 'retry here', score: 0.91 }];
|
||||||
@@ -72,6 +72,19 @@ test('search adds the repo collection once, refreshes on change, and filters oth
|
|||||||
assert.equal(s.store.calls.filter((c) => c[0] === 'update').length, 1, 'unchanged fingerprint skips update');
|
assert.equal(s.store.calls.filter((c) => c[0] === 'update').length, 1, 'unchanged fingerprint skips update');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('a changed embedding size clears old vectors and embeds again', async (t) => {
|
||||||
|
const s = await start(t);
|
||||||
|
let failures = 1;
|
||||||
|
const embed = s.store.embed;
|
||||||
|
s.store.embed = async (opts) => {
|
||||||
|
if (failures-- > 0) throw new Error('Embedding dimension mismatch: existing vectors are 1024d but the current model produces 2560d.');
|
||||||
|
return embed(opts);
|
||||||
|
};
|
||||||
|
s.store.internal = { clearAllEmbeddings: () => s.store.calls.push(['clear']) };
|
||||||
|
assert.equal((await s.call('/search', { repo: '/r', query: 'q', limit: 1 })).status, 200);
|
||||||
|
assert.deepEqual(s.store.calls.filter((c) => c[0] === 'clear' || c[0] === 'embed').map((c) => c[0]), ['clear', 'embed']);
|
||||||
|
});
|
||||||
|
|
||||||
test('rejects a missing query', async (t) => {
|
test('rejects a missing query', async (t) => {
|
||||||
const s = await start(t);
|
const s = await start(t);
|
||||||
assert.equal((await s.call('/search', { repo: '/r' })).status, 400);
|
assert.equal((await s.call('/search', { repo: '/r' })).status, 400);
|
||||||
@@ -182,6 +195,13 @@ test('ignoreGlobs turns git ignored paths into escaped QMD ignore globs', () =>
|
|||||||
assert.deepEqual(ignoreGlobs('', escape), []);
|
assert.deepEqual(ignoreGlobs('', escape), []);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('index ignores add lockfiles and minified bundles to the git ignored paths', () => {
|
||||||
|
const ignores = indexIgnores('/r', (path) => path, () => ['dist/**']);
|
||||||
|
assert.deepEqual(ignores, [...INDEX_EXCLUDES, 'dist/**']);
|
||||||
|
for (const pattern of ['**/package-lock.json', '**/pnpm-lock.yaml', '**/*.min.js']) assert.ok(ignores.includes(pattern));
|
||||||
|
assert.deepEqual(indexIgnores('/r', (path) => path, () => []), INDEX_EXCLUDES, 'fixed excludes apply when git lists nothing');
|
||||||
|
});
|
||||||
|
|
||||||
test('git ignored paths reach addCollection and are persisted only when they change', async (t) => {
|
test('git ignored paths reach addCollection and are persisted only when they change', async (t) => {
|
||||||
let ignore = ['dist/**'];
|
let ignore = ['dist/**'];
|
||||||
let fingerprint = 'one';
|
let fingerprint = 'one';
|
||||||
|
|||||||
@@ -103,6 +103,29 @@ class SetupTest(unittest.TestCase):
|
|||||||
self.assertFalse(any('npm uninstall' in ' '.join(c) for c in runner.calls))
|
self.assertFalse(any('npm uninstall' in ' '.join(c) for c in runner.calls))
|
||||||
self.assertFalse((self.home / '.my-ai-configuration/qmd.json').exists())
|
self.assertFalse((self.home / '.my-ai-configuration/qmd.json').exists())
|
||||||
|
|
||||||
|
def test_model_files_follow_node_llama_cpp_cache_names(self):
|
||||||
|
names = qmd.model_files((ROOT / 'shared/qmd/qmd-lib.mjs').read_text(encoding='utf-8'))
|
||||||
|
self.assertIn('hf_Qwen_Qwen3-Embedding-4B-Q4_K_M.gguf', names)
|
||||||
|
self.assertIn('Qwen3-Embedding-4B-Q4_K_M.gguf.etag', names)
|
||||||
|
self.assertEqual(6, len(names))
|
||||||
|
|
||||||
|
def test_update_deletes_only_owned_models_no_longer_used(self):
|
||||||
|
models = self.home / '.cache/qmd/models'
|
||||||
|
current = qmd.model_files((ROOT / 'shared/qmd/qmd-lib.mjs').read_text(encoding='utf-8'))
|
||||||
|
create = lambda arguments: [(models / n).write_text('x') for n in current] if arguments[-1:] == ['pull'] else None
|
||||||
|
runner = FakeRunner(on_call=create)
|
||||||
|
self.setup(runner).enable(['claude'])
|
||||||
|
for name in ('hf_Qwen_Qwen3-Embedding-0.6B-Q8_0.gguf', 'foreign.gguf'):
|
||||||
|
(models / name).write_text('x')
|
||||||
|
state = self.state()
|
||||||
|
state['owned_models'].append('hf_Qwen_Qwen3-Embedding-0.6B-Q8_0.gguf')
|
||||||
|
(self.home / '.my-ai-configuration/qmd.json').write_text(json.dumps(state))
|
||||||
|
self.setup(runner).enable(['claude'])
|
||||||
|
self.assertFalse((models / 'hf_Qwen_Qwen3-Embedding-0.6B-Q8_0.gguf').exists())
|
||||||
|
self.assertTrue((models / 'foreign.gguf').exists())
|
||||||
|
self.assertTrue(all((models / n).exists() for n in current))
|
||||||
|
self.assertEqual(sorted(current), self.state()['owned_models'])
|
||||||
|
|
||||||
def test_disable_removes_owned_models_and_collections(self):
|
def test_disable_removes_owned_models_and_collections(self):
|
||||||
runner = FakeRunner()
|
runner = FakeRunner()
|
||||||
setup = self.setup(runner)
|
setup = self.setup(runner)
|
||||||
@@ -156,6 +179,15 @@ class SetupTest(unittest.TestCase):
|
|||||||
self.assertIn(['node', str(self.home / '.my-ai-configuration/qmd/qmd-config.mjs'), 'restore-models', '{"embed": "mine"}'], runner.calls)
|
self.assertIn(['node', str(self.home / '.my-ai-configuration/qmd/qmd-config.mjs'), 'restore-models', '{"embed": "mine"}'], runner.calls)
|
||||||
self.assertFalse(any(c[-1:] == ['unset-models'] for c in runner.calls))
|
self.assertFalse(any(c[-1:] == ['unset-models'] for c in runner.calls))
|
||||||
|
|
||||||
|
def test_update_rewrites_owned_models_block_and_keeps_user_original(self):
|
||||||
|
runner = FakeRunner(previous={'embed': 'mine'})
|
||||||
|
self.setup(runner).enable(['claude'])
|
||||||
|
# The second run sees the setup's own older block; it must refresh it without recording it as the user's.
|
||||||
|
runner.previous = {'rerank': 'older setup default'}
|
||||||
|
self.setup(runner).enable(['claude'])
|
||||||
|
self.assertEqual(2, sum(c[-1:] == ['set-models'] for c in runner.calls))
|
||||||
|
self.assertEqual(self.state()['previous_models'], {'embed': 'mine'})
|
||||||
|
|
||||||
def test_models_block_removed_when_none_existed(self):
|
def test_models_block_removed_when_none_existed(self):
|
||||||
runner = FakeRunner()
|
runner = FakeRunner()
|
||||||
setup = self.setup(runner)
|
setup = self.setup(runner)
|
||||||
|
|||||||
@@ -33,6 +33,13 @@ export function ignoreGlobs(output, escape) {
|
|||||||
return output.split('\0').filter(Boolean).map((path) => (path.endsWith('/') ? `${escape(path.slice(0, -1))}/**` : escape(path)));
|
return output.split('\0').filter(Boolean).map((path) => (path.endsWith('/') ? `${escape(path.slice(0, -1))}/**` : escape(path)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Tracked lockfiles and minified bundles are large and generated: embedding them costs time and only adds noise to results.
|
||||||
|
export const INDEX_EXCLUDES = ['**/package-lock.json', '**/npm-shrinkwrap.json', '**/pnpm-lock.yaml', '**/*.min.js'];
|
||||||
|
|
||||||
|
export function indexIgnores(repo, escape, git = gitIgnored) {
|
||||||
|
return [...INDEX_EXCLUDES, ...git(repo, escape)];
|
||||||
|
}
|
||||||
|
|
||||||
export function gitIgnored(repo, escape) {
|
export function gitIgnored(repo, escape) {
|
||||||
try {
|
try {
|
||||||
return ignoreGlobs(execFileSync('git', ['-C', repo, 'ls-files', '-z', '--others', '--ignored', '--exclude-standard', '--directory'],
|
return ignoreGlobs(execFileSync('git', ['-C', repo, 'ls-files', '-z', '--others', '--ignored', '--exclude-standard', '--directory'],
|
||||||
@@ -126,7 +133,15 @@ export function createServer({ store, token, idleMs, now = Date.now, onIdle, ext
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
await store.update({ collections: [name] });
|
await store.update({ collections: [name] });
|
||||||
|
try {
|
||||||
await store.embed({ collection: name, chunkStrategy: 'auto' });
|
await store.embed({ collection: name, chunkStrategy: 'auto' });
|
||||||
|
} catch (error) {
|
||||||
|
// QMD keeps one vector table, so a new embedding model with another size needs a full clear; other collections re-embed on their next refresh.
|
||||||
|
if (!/Embedding dimension mismatch/.test(error?.message ?? '')) throw error;
|
||||||
|
console.error('qmd-daemon: embedding model changed; clearing old vectors and re-embedding.');
|
||||||
|
store.internal.clearAllEmbeddings();
|
||||||
|
await store.embed({ collection: name, chunkStrategy: 'auto' });
|
||||||
|
}
|
||||||
fingerprints.set(name, fingerprint);
|
fingerprints.set(name, fingerprint);
|
||||||
return { collection: name, updated: true };
|
return { collection: name, updated: true };
|
||||||
}
|
}
|
||||||
@@ -223,7 +238,7 @@ async function main() {
|
|||||||
};
|
};
|
||||||
const daemon = createServer({
|
const daemon = createServer({
|
||||||
store, token, idleMs: idleMinutes() * 60_000, onIdle: stop, extractSnippet,
|
store, token, idleMs: idleMinutes() * 60_000, onIdle: stop, extractSnippet,
|
||||||
ignored: (repo) => gitIgnored(repo, fastGlob.escapePath),
|
ignored: (repo) => indexIgnores(repo, fastGlob.escapePath),
|
||||||
persistIgnore: async (name, ignore) => {
|
persistIgnore: async (name, ignore) => {
|
||||||
const path = qmdConfigPath();
|
const path = qmdConfigPath();
|
||||||
const text = existsSync(path) ? readFileSync(path, 'utf8') : '';
|
const text = existsSync(path) ? readFileSync(path, 'utf8') : '';
|
||||||
|
|||||||
@@ -8,8 +8,8 @@ import { dirname, join, resolve } from 'node:path';
|
|||||||
import { pathToFileURL } from 'node:url';
|
import { pathToFileURL } from 'node:url';
|
||||||
|
|
||||||
export const MODELS = {
|
export const MODELS = {
|
||||||
embed: 'hf:Qwen/Qwen3-Embedding-0.6B-GGUF/Qwen3-Embedding-0.6B-Q8_0.gguf',
|
embed: 'hf:Qwen/Qwen3-Embedding-4B-GGUF/Qwen3-Embedding-4B-Q4_K_M.gguf',
|
||||||
rerank: 'hf:ggml-org/Qwen3-Reranker-0.6B-Q8_0-GGUF/qwen3-reranker-0.6b-q8_0.gguf',
|
rerank: 'hf:giladgd/Qwen3-Reranker-4B-GGUF/Qwen3-Reranker-4B.Q4_K_M.gguf',
|
||||||
generate: 'hf:tobil/qmd-query-expansion-1.7B-gguf/qmd-query-expansion-1.7B-q4_k_m.gguf',
|
generate: 'hf:tobil/qmd-query-expansion-1.7B-gguf/qmd-query-expansion-1.7B-q4_k_m.gguf',
|
||||||
};
|
};
|
||||||
export const MASK = '**/*.{md,py,cs,ts,tsx,js,jsx,mjs,go,rs,java,ps1,sh,json,yml,yaml,xml,sql}';
|
export const MASK = '**/*.{md,py,cs,ts,tsx,js,jsx,mjs,go,rs,java,ps1,sh,json,yml,yaml,xml,sql}';
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ description: MUST apply before open repository searches - run semantic retrieval
|
|||||||
|
|
||||||
# Semantic Search
|
# Semantic Search
|
||||||
|
|
||||||
Search the current Git repository, plus the user's registered QMD collections, by meaning. QMD runs locally with Qwen3-Embedding-0.6B, Qwen3-Reranker-0.6B, and QMD Query Expansion 1.7B; a background daemon keeps them loaded.
|
Search the current Git repository, plus the user's registered QMD collections, by meaning. QMD runs locally with Qwen3-Embedding-4B, Qwen3-Reranker-4B, and QMD Query Expansion 1.7B; a background daemon keeps them loaded.
|
||||||
|
|
||||||
## Rule
|
## Rule
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user