-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathsqlite_vector_cli_options.dart
More file actions
359 lines (322 loc) · 10.5 KB
/
Copy pathsqlite_vector_cli_options.dart
File metadata and controls
359 lines (322 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
import 'package:args/args.dart';
import 'sqlite_vector_search_service.dart';
/// COSINE metric used when vectors are normalized.
const String cosineMetric = 'COSINE';
/// L2 metric used when vectors are not normalized.
const String l2Metric = 'L2';
/// Parsed and validated command-line options for the SQLite vector example.
final class SqliteVectorCliOptions {
/// Path or URL to the GGUF model.
final String modelUrlOrPath;
/// Query string used for retrieval.
final String query;
/// Input corpus documents.
final List<String> documents;
/// Number of nearest neighbors to return.
final int topK;
/// Whether quantized ANN search is enabled.
final bool useQuantizedSearch;
/// Whether quantized vectors are preloaded.
final bool preloadQuantized;
/// Quantization type (UINT8, INT8, 1BIT).
final String quantizedQtype;
/// Optional quantization memory budget string.
final String? quantizedMaxMemory;
/// Whether exact-vs-quantized comparison is enabled.
final bool compareExact;
/// Optional minimum similarity threshold.
final double? minSimilarity;
/// Whether embedding vectors are normalized.
final bool normalize;
/// Distance metric string consumed by sqlite-vector.
final String distanceMetric;
/// SQLite database path.
final String databasePath;
/// Whether to force CPU backend.
final bool forceCpu;
/// Model context size.
final int contextSize;
/// Number of generation threads.
final int threads;
/// Number of batch threads.
final int threadsBatch;
/// Logical batch size.
final int batchSize;
/// Micro batch size.
final int microBatchSize;
/// Maximum parallel sequence slots.
final int maxParallelSequences;
/// Creates immutable CLI options.
const SqliteVectorCliOptions({
required this.modelUrlOrPath,
required this.query,
required this.documents,
required this.topK,
required this.useQuantizedSearch,
required this.preloadQuantized,
required this.quantizedQtype,
required this.quantizedMaxMemory,
required this.compareExact,
required this.minSimilarity,
required this.normalize,
required this.distanceMetric,
required this.databasePath,
required this.forceCpu,
required this.contextSize,
required this.threads,
required this.threadsBatch,
required this.batchSize,
required this.microBatchSize,
required this.maxParallelSequences,
});
}
/// Creates the CLI parser for the SQLite vector example.
ArgParser createSqliteVectorArgParser({required String defaultModelUrl}) {
return ArgParser()
..addOption(
'model',
abbr: 'm',
help: 'Path or URL to a GGUF embedding model.',
defaultsTo: defaultModelUrl,
)
..addOption(
'query',
abbr: 'q',
help: 'Query text to search against embedded documents.',
defaultsTo: 'How do I improve embedding throughput?',
)
..addMultiOption(
'doc',
abbr: 'd',
help: 'Corpus document text. Repeat to add more documents.',
)
..addOption(
'top-k',
abbr: 'k',
help: 'Number of nearest matches to return.',
defaultsTo: '3',
)
..addFlag(
'quantized',
help: 'Use quantized ANN search with vector_quantize_scan(...).',
defaultsTo: false,
)
..addFlag(
'quantized-preload',
help: 'Preload quantized vectors into memory before searching.',
defaultsTo: true,
)
..addOption(
'quantized-qtype',
help: 'Quantization type: UINT8, INT8, or 1BIT.',
defaultsTo: 'UINT8',
)
..addOption(
'quantized-max-memory',
help: 'Quantization memory budget (for example: 30MB, 64MB).',
)
..addFlag(
'compare-exact',
help: 'Run exact full-scan and print recall metrics for quantized mode.',
defaultsTo: false,
)
..addOption(
'min-similarity',
help: 'Minimum similarity threshold to display a result (-1.0..1.0).',
)
..addFlag(
'normalize',
help: 'L2 normalize vectors before storing/searching.',
defaultsTo: true,
)
..addOption(
'db',
help: 'SQLite path (use :memory: for in-memory DB).',
defaultsTo: ':memory:',
)
..addFlag(
'cpu',
help: 'Force CPU backend for reproducible parity runs.',
defaultsTo: false,
)
..addOption(
'ctx-size',
help: 'Context size (0 uses model default).',
defaultsTo: '0',
)
..addOption(
'threads',
help: 'Generation threads (0 auto).',
defaultsTo: '0',
)
..addOption(
'threads-batch',
help: 'Batch threads (defaults to --threads when omitted).',
defaultsTo: '0',
)
..addOption(
'batch-size',
help: 'Logical batch size (0 uses the model-aware default).',
defaultsTo: '0',
)
..addOption(
'ubatch-size',
help: 'Micro-batch size (0 uses the model-aware default).',
defaultsTo: '0',
)
..addOption(
'max-seq',
help: 'Max parallel sequence slots (0 uses corpus size).',
defaultsTo: '0',
)
..addFlag('help', abbr: 'h', help: 'Show help message.', negatable: false);
}
/// Parses [results] and returns strongly typed options for the CLI workflow.
SqliteVectorCliOptions parseSqliteVectorCliOptions(
ArgResults results, {
required List<String> defaultCorpus,
}) {
final String modelUrlOrPath = results['model'] as String;
final String query = results['query'] as String;
final List<String> docsOption = List<String>.from(
results['doc'] as List<String>,
);
final List<String> documents = docsOption.isEmpty
? List<String>.from(defaultCorpus)
: docsOption;
final int topK = _parsePositiveIntOption(results, 'top-k');
final bool useQuantizedSearch = results['quantized'] as bool;
final bool preloadQuantized = results['quantized-preload'] as bool;
final String quantizedQtype = _parseQuantizedTypeOption(
results,
'quantized-qtype',
);
final String? quantizedMaxMemory = _parseOptionalStringOption(
results,
'quantized-max-memory',
);
final bool compareExact = results['compare-exact'] as bool;
final double? minSimilarity = results.wasParsed('min-similarity')
? _parseDoubleRangeOption(results, 'min-similarity', min: -1.0, max: 1.0)
: null;
final bool normalize = results['normalize'] as bool;
final String distanceMetric = normalize ? cosineMetric : l2Metric;
final String databasePath = results['db'] as String;
final bool forceCpu = results['cpu'] as bool;
final int contextSize = _parseNonNegativeIntOption(results, 'ctx-size');
final int threads = _parseNonNegativeIntOption(results, 'threads');
final int threadsBatch = results.wasParsed('threads-batch')
? _parseNonNegativeIntOption(results, 'threads-batch')
: threads;
final int batchSize = _parseNonNegativeIntOption(results, 'batch-size');
final int microBatchSize = _parseNonNegativeIntOption(results, 'ubatch-size');
final int requestedMaxSeq = _parseNonNegativeIntOption(results, 'max-seq');
final int maxParallelSequences = requestedMaxSeq > 0
? requestedMaxSeq
: documents.length;
return SqliteVectorCliOptions(
modelUrlOrPath: modelUrlOrPath,
query: query,
documents: documents,
topK: topK,
useQuantizedSearch: useQuantizedSearch,
preloadQuantized: preloadQuantized,
quantizedQtype: quantizedQtype,
quantizedMaxMemory: quantizedMaxMemory,
compareExact: compareExact,
minSimilarity: minSimilarity,
normalize: normalize,
distanceMetric: distanceMetric,
databasePath: databasePath,
forceCpu: forceCpu,
contextSize: contextSize,
threads: threads,
threadsBatch: threadsBatch,
batchSize: batchSize,
microBatchSize: microBatchSize,
maxParallelSequences: maxParallelSequences,
);
}
/// Builds user-facing help text with parser usage and common examples.
String buildSqliteVectorHelpText(ArgParser parser) {
final StringBuffer buffer = StringBuffer();
buffer.writeln('llamadart SQLite Vector Example');
buffer.writeln();
buffer.writeln(parser.usage);
buffer.writeln('Example:');
buffer.writeln(
' dart run bin/llamadart_sqlite_vector_example.dart '
'-q "How do I improve embedding throughput?" '
'-d "Increase maxParallelSequences for wider embedding batches." '
'-d "Tune batchSize and ubatchSize together."',
);
buffer.writeln(
' dart run bin/llamadart_sqlite_vector_example.dart '
'--quantized --top-k 5 '
'-q "How do I improve embedding throughput?" '
'-d "Increase maxParallelSequences for wider embedding batches." '
'-d "Tune batchSize and ubatchSize together."',
);
buffer.writeln(
' dart run bin/llamadart_sqlite_vector_example.dart '
'--quantized --compare-exact --quantized-qtype INT8 --top-k 5 '
'--min-similarity 0.45 '
'-q "How do I improve embedding throughput?" '
'-d "Increase maxParallelSequences for wider embedding batches." '
'-d "Tune batchSize and ubatchSize together."',
);
return buffer.toString();
}
int _parseIntOption(ArgResults results, String name) {
final int? value = int.tryParse(results[name] as String);
if (value == null) {
throw FormatException('Invalid integer for --$name: ${results[name]}');
}
return value;
}
int _parsePositiveIntOption(ArgResults results, String name) {
final int value = _parseIntOption(results, name);
if (value <= 0) {
throw FormatException('--$name must be greater than 0.');
}
return value;
}
int _parseNonNegativeIntOption(ArgResults results, String name) {
final int value = _parseIntOption(results, name);
if (value < 0) {
throw FormatException('--$name must be 0 or greater.');
}
return value;
}
String _parseQuantizedTypeOption(ArgResults results, String name) {
final String value = (results[name] as String).trim().toUpperCase();
if (!supportedQuantizeTypes.contains(value)) {
throw FormatException(
'--$name must be one of: ${supportedQuantizeTypes.join(', ')}.',
);
}
return value;
}
String? _parseOptionalStringOption(ArgResults results, String name) {
if (!results.wasParsed(name)) {
return null;
}
final String value = (results[name] as String).trim();
return value.isEmpty ? null : value;
}
double _parseDoubleRangeOption(
ArgResults results,
String name, {
required double min,
required double max,
}) {
final String raw = results[name] as String;
final double? value = double.tryParse(raw);
if (value == null) {
throw FormatException('Invalid number for --$name: $raw');
}
if (value < min || value > max) {
throw FormatException('--$name must be in [$min, $max].');
}
return value;
}