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
+113
-10
No files matched your search
+33
-2
@@ -59,6 +59,14 @@ def node_version_ok(text):
|
||||
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):
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
@@ -176,8 +184,9 @@ class Setup:
|
||||
state['owned_package'] = True
|
||||
self.install_scripts(state)
|
||||
atomic_json(self.state_path, state)
|
||||
# Rewrite the setup-owned block on every run so changed default models reach existing installs.
|
||||
output = self.node('qmd-config.mjs', 'set-models')
|
||||
if not state['models_block']:
|
||||
output = self.node('qmd-config.mjs', 'set-models')
|
||||
try:
|
||||
previous = json.loads(output.strip().splitlines()[-1])['previous']
|
||||
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()
|
||||
state['owned_models'] = sorted(set(state['owned_models']) | (after - before))
|
||||
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):
|
||||
try:
|
||||
@@ -205,7 +236,7 @@ class Setup:
|
||||
def enable(self, clients):
|
||||
state = self.load()
|
||||
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
|
||||
self.install(state)
|
||||
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 { tmpdir } from 'node:os';
|
||||
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';
|
||||
|
||||
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');
|
||||
});
|
||||
|
||||
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) => {
|
||||
const s = await start(t);
|
||||
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), []);
|
||||
});
|
||||
|
||||
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) => {
|
||||
let ignore = ['dist/**'];
|
||||
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((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):
|
||||
runner = FakeRunner()
|
||||
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.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):
|
||||
runner = FakeRunner()
|
||||
setup = self.setup(runner)
|
||||
|
||||
Reference in new issue
Block a user