@qvac/harness 1.0.1 → 1.2.0

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.
Files changed (98) hide show
  1. package/CHANGELOG.md +171 -6
  2. package/README.md +39 -0
  3. package/dist-lib/index.d.ts +32 -304
  4. package/dist-lib/index.js +16 -1147
  5. package/dist-lib/lib/agent/child-run.d.ts +33 -0
  6. package/dist-lib/lib/agent/child-run.js +58 -0
  7. package/dist-lib/lib/agent/delegate.d.ts +3 -19
  8. package/dist-lib/lib/agent/delegate.js +8 -31
  9. package/dist-lib/lib/agent/index.d.ts +7 -0
  10. package/dist-lib/lib/agent/index.js +5 -0
  11. package/dist-lib/lib/agent/read-parts.d.ts +47 -0
  12. package/dist-lib/lib/agent/read-parts.js +85 -0
  13. package/dist-lib/lib/capabilities/completion-engine/driver.js +6 -2
  14. package/dist-lib/lib/capabilities/completion-engine/engine.d.ts +4 -0
  15. package/dist-lib/lib/capabilities/completion-engine/engine.js +27 -18
  16. package/dist-lib/lib/capabilities/completion-engine/model-round.d.ts +4 -1
  17. package/dist-lib/lib/capabilities/completion-engine/round.js +5 -4
  18. package/dist-lib/lib/client/index.js +1 -3
  19. package/dist-lib/lib/connect/decode.d.ts +3 -2
  20. package/dist-lib/lib/connect/decode.js +14 -0
  21. package/dist-lib/lib/connect.d.ts +1 -0
  22. package/dist-lib/lib/connect.js +11 -5
  23. package/dist-lib/lib/context-window.d.ts +2 -0
  24. package/dist-lib/lib/context-window.js +17 -14
  25. package/dist-lib/lib/contract/models.d.ts +13 -1
  26. package/dist-lib/lib/contract-types.d.ts +9 -0
  27. package/dist-lib/lib/harness.d.ts +269 -0
  28. package/dist-lib/lib/harness.js +1154 -0
  29. package/dist-lib/lib/models/custom-model-cache.d.ts +2 -0
  30. package/dist-lib/lib/models/custom-model-cache.js +21 -0
  31. package/dist-lib/lib/models/memory-cap.d.ts +6 -0
  32. package/dist-lib/lib/models/memory-cap.js +20 -0
  33. package/dist-lib/lib/models/model-catalog.d.ts +2 -0
  34. package/dist-lib/lib/models/model-catalog.js +8 -2
  35. package/dist-lib/lib/models/model-fit.d.ts +59 -10
  36. package/dist-lib/lib/models/model-fit.js +172 -35
  37. package/dist-lib/lib/models/model-handle.d.ts +2 -1
  38. package/dist-lib/lib/models/model-pool.d.ts +3 -2
  39. package/dist-lib/lib/models/model-pool.js +30 -13
  40. package/dist-lib/lib/models/tts-model-default.d.ts +1 -1
  41. package/dist-lib/lib/models/tts-model-default.js +7 -6
  42. package/dist-lib/lib/residency/completion-runtime.d.ts +1 -1
  43. package/dist-lib/lib/residency/completion-runtime.js +1 -1
  44. package/dist-lib/lib/residency/index.d.ts +31 -9
  45. package/dist-lib/lib/residency/index.js +286 -88
  46. package/dist-lib/lib/run-log/boundary.d.ts +4 -1
  47. package/dist-lib/lib/run-log/boundary.js +2 -1
  48. package/dist-lib/lib/run-log/index.d.ts +2 -1
  49. package/dist-lib/lib/run-log/index.js +2 -1
  50. package/dist-lib/lib/run-log/persisted-actor.d.ts +10 -0
  51. package/dist-lib/lib/run-log/persisted-actor.js +15 -0
  52. package/dist-lib/lib/run-log/run-journal.d.ts +3 -0
  53. package/dist-lib/lib/run-log/run-journal.js +19 -8
  54. package/dist-lib/lib/serve/requests.d.ts +3 -0
  55. package/dist-lib/lib/serve.js +3 -0
  56. package/dist-lib/lib/spawn.d.ts +4 -1
  57. package/dist-lib/lib/tools/exec.d.ts +2 -0
  58. package/dist-lib/lib/tools/exec.js +29 -1
  59. package/dist-lib/lib/tools/files/list-dir.js +79 -32
  60. package/dist-lib/lib/tools/fs/walk.d.ts +11 -1
  61. package/dist-lib/lib/tools/fs/walk.js +64 -30
  62. package/dist-lib/lib/tools/office.js +8 -5
  63. package/dist-lib/lib/tools/pdf/pages.d.ts +1 -1
  64. package/dist-lib/lib/tools/pdf/pages.js +3 -14
  65. package/dist-lib/lib/tools/pdf/recognize.d.ts +3 -0
  66. package/dist-lib/lib/tools/pdf/recognize.js +45 -7
  67. package/dist-lib/plugins/image/generate-image.d.ts +2 -2
  68. package/dist-lib/plugins/image/generate-image.js +9 -1
  69. package/dist-lib/plugins/image/index.js +6 -2
  70. package/dist-lib/plugins/knowledge/chunk-index.d.ts +4 -0
  71. package/dist-lib/plugins/knowledge/chunk-index.js +191 -0
  72. package/dist-lib/plugins/knowledge/index.d.ts +1 -0
  73. package/dist-lib/plugins/knowledge/index.js +1 -0
  74. package/dist-lib/plugins/knowledge/manifest.d.ts +2 -1
  75. package/dist-lib/plugins/knowledge/manifest.js +2 -9
  76. package/dist-lib/plugins/knowledge/store.d.ts +5 -1
  77. package/dist-lib/plugins/knowledge/store.js +44 -16
  78. package/dist-lib/plugins/lsp/rpc.d.ts +9 -1
  79. package/dist-lib/plugins/lsp/rpc.js +81 -17
  80. package/dist-lib/plugins/music/generate-music.d.ts +2 -2
  81. package/dist-lib/plugins/music/generate-music.js +14 -1
  82. package/dist-lib/plugins/music/index.js +4 -1
  83. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  84. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  85. package/dist-lib/plugins/speech/speech-engine.d.ts +5 -2
  86. package/dist-lib/plugins/speech/speech-engine.js +28 -7
  87. package/dist-lib/schema/harness.js +28 -2
  88. package/dist-lib/spec/bind.js +3 -0
  89. package/dist-lib/spec/calls.js +1 -0
  90. package/dist-lib/spec/hrpc/hrpc.json +13 -0
  91. package/dist-lib/spec/hrpc/index.js +15 -3
  92. package/dist-lib/spec/hrpc/messages.js +87 -6
  93. package/dist-lib/spec/hyperschema/index.js +87 -6
  94. package/dist-lib/spec/hyperschema/schema.json +70 -2
  95. package/dist-lib/spec/hyperschema/types.d.ts +21 -1
  96. package/package.json +29 -28
  97. package/scripts/addon-externals.cjs +1 -0
  98. package/worker/harness-sidecar.mjs +12 -1
@@ -12,3 +12,5 @@ export declare function customShardCache(src: string, modelsDir: string | undefi
12
12
  export declare function localWeightFile(src: string, modelsDir: string | undefined): string | null;
13
13
  export declare function customDownloads(entry: CustomModelEntry, modelsDir: string | undefined): Promise<CustomDownloads>;
14
14
  export declare function isCustomModelCached(entry: CustomModelEntry, modelsDir: string | undefined): Promise<boolean>;
15
+ export declare function retiredWeightFiles(modelsDir: string): string[];
16
+ export declare function sweepRetiredWeights(modelsDir: string): Promise<string[]>;
@@ -3,6 +3,7 @@ import fs from 'fs';
3
3
  import path from 'path';
4
4
  import { isRemoteSource, localSourcePath } from './gguf-header.js';
5
5
  import { shardSet } from './shards.js';
6
+ import { HarnessLog } from '../log.js';
6
7
  const ARCHIVE = /\.(tar|tgz|zip)(\.\w+)?$/i;
7
8
  export function customFileCachePath(src, modelsDir) {
8
9
  if (!isRemoteSource(src)) {
@@ -45,6 +46,26 @@ export async function isCustomModelCached(entry, modelsDir) {
45
46
  function sourcesOf(entry) {
46
47
  return entry.projectionSrc ? [entry.src, entry.projectionSrc] : [entry.src];
47
48
  }
49
+ const RETIRED_WEIGHTS = [
50
+ 'unsloth/embeddinggemma-300m-GGUF/resolve/6661a6504c30d8304af13455cb4a5d4f5bc6011f/embeddinggemma-300M-BF16.gguf',
51
+ 'unsloth/embeddinggemma-300m-GGUF/resolve/6661a6504c30d8304af13455cb4a5d4f5bc6011f/embeddinggemma-300M-F32.gguf',
52
+ 'unsloth/embeddinggemma-300m-GGUF/resolve/6661a6504c30d8304af13455cb4a5d4f5bc6011f/embeddinggemma-300M-Q8_0.gguf',
53
+ 'unsloth/embeddinggemma-300m-GGUF/resolve/6661a6504c30d8304af13455cb4a5d4f5bc6011f/embeddinggemma-300m-Q4_0.gguf'
54
+ ];
55
+ export function retiredWeightFiles(modelsDir) {
56
+ return RETIRED_WEIGHTS.map((registryPath) => path.join(modelsDir, `${shortHash(registryPath)}_${filenameOf(registryPath)}`));
57
+ }
58
+ export async function sweepRetiredWeights(modelsDir) {
59
+ const removed = [];
60
+ for (const file of retiredWeightFiles(modelsDir)) {
61
+ const gone = await fs.promises.unlink(file).then(() => true, () => false);
62
+ if (gone) {
63
+ HarnessLog.info('removed retired model weights', { file });
64
+ removed.push(file);
65
+ }
66
+ }
67
+ return removed;
68
+ }
48
69
  function filenameOf(src) {
49
70
  return src.split('/').pop()?.split('?')[0] || 'model.gguf';
50
71
  }
@@ -1,3 +1,9 @@
1
+ export declare const HOST_POOL = "host";
2
+ export declare const BUDGET_POOL = "budget";
3
+ export type PoolBytes = Readonly<Record<string, number>>;
4
+ export declare function sumPools(uses: Iterable<PoolBytes>): PoolBytes;
5
+ export declare function totalBytes(use: PoolBytes): number;
6
+ export declare function poolsOver(used: PoolBytes, need: PoolBytes, capOf: (pool: string) => number | null): string[];
1
7
  export declare const VictimRank: {
2
8
  readonly generator: 0;
3
9
  readonly companion: 1;
@@ -1,3 +1,23 @@
1
+ export const HOST_POOL = 'host';
2
+ export const BUDGET_POOL = 'budget';
3
+ export function sumPools(uses) {
4
+ const sum = {};
5
+ for (const use of uses) {
6
+ for (const [pool, bytes] of Object.entries(use)) {
7
+ sum[pool] = (sum[pool] ?? 0) + bytes;
8
+ }
9
+ }
10
+ return sum;
11
+ }
12
+ export function totalBytes(use) {
13
+ return Object.values(use).reduce((sum, bytes) => sum + bytes, 0);
14
+ }
15
+ export function poolsOver(used, need, capOf) {
16
+ return Object.keys({ ...used, ...need }).filter((pool) => {
17
+ const cap = capOf(pool);
18
+ return cap !== null && (used[pool] ?? 0) + (need[pool] ?? 0) > cap;
19
+ });
20
+ }
1
21
  export const VictimRank = {
2
22
  generator: 0,
3
23
  companion: 1,
@@ -32,6 +32,7 @@ export interface CategoryDefault {
32
32
  readonly companions?: ReadonlyArray<SdkModelAsset>;
33
33
  }
34
34
  export declare const AUDIO8_TTS: CategoryDefault;
35
+ export declare const AUDIO8_CODEC_ENCODER_SRC: "registry://s3/qvac_models_compiled/ggml/audio-8/2026-08-12/audio8-codec-encoder-q8_0.gguf";
35
36
  export declare const MOSS_TTS: CategoryDefault;
36
37
  export declare const MOSS_CODEC_ENCODER_SRC: "registry://s3/qvac_models_compiled/ggml/openmoss/2026-09-25/moss-codec-encoder-f16.gguf";
37
38
  export declare const CATEGORY_DEFAULTS: ReadonlyArray<CategoryDefault>;
@@ -141,6 +142,7 @@ export declare function curatedListables(): CuratedListable[];
141
142
  export declare function curatedModelAsset(name: string, addon: ModelRegistryEntry['addon']): SdkModelAsset | undefined;
142
143
  export declare function modelAddonOf(model: string): ModelRegistryEntry['addon'];
143
144
  export declare function residentSrc(model: string, addon: ModelRegistryEntry['addon']): string;
145
+ export declare function generatorRowName(src: string): string;
144
146
  export declare function catalogModelName(model: string, addon: ModelRegistryEntry['addon']): string;
145
147
  export declare const CUSTOM_TASK_TYPES: readonly ['llm'];
146
148
  export type CustomTaskType = (typeof CUSTOM_TASK_TYPES)[number];
@@ -1,4 +1,4 @@
1
- import { AUDIOGEN_ACESTEP_5HZ_LM_0_6B_Q8_0, AUDIOGEN_ACESTEP_V15_BASE_Q4_K_M, AUDIOGEN_ACESTEP_V15_SFT_Q8_0, AUDIOGEN_ACESTEP_V15_TURBO_Q4_K_M, AUDIOGEN_ACESTEP_V15_TURBO_Q8_0, AUDIOGEN_QWEN3_EMBEDDING_0_6B_Q8_0, AUDIOGEN_VAE_BF16, EMBEDDINGGEMMA_300M_Q4_0, FLUX_2_KLEIN_4B_Q4_0, FLUX_2_KLEIN_4B_VAE, HEALTHCARE_1_7B_MEDICAL_Q4_K_M, HEALTHCARE_4B_MEDICAL_Q4_K_M, MOE_35B_INST_Q4_K_M, MMPROJ_QWEN3_5_2B_MULTIMODAL_Q8_0, MMPROJ_QWEN3_5_4B_MULTIMODAL_Q8_0, MMPROJ_QWEN3_5_9B_MULTIMODAL_F16, MMPROJ_QWEN3_6_35B_A3B_MULTIMODAL_F16, MMPROJ_QWEN3_8_27B_MULTIMODAL_F16, MMPROJ_TERNARY_BONSAI_2_27B_MULTIMODAL_Q8_0, QWEN3_5_2B_MULTIMODAL_Q4_K_M, QWEN3_5_4B_MULTIMODAL_Q4_K_M, QWEN3_5_9B_MULTIMODAL_Q4_K_M, PARAKEET_TDT_0_6B_V3_Q8_0, PARAKEET_TDT_1_1B_Q8_0, QWEN3_4B_Q4_K_M, QWEN3_6_35B_A3B_MULTIMODAL_Q4_K_M, QWEN3_8_27B_DFLASH2_Q8_0, QWEN3_8_27B_MULTIMODAL_UD_Q4_K_XL, SD_V2_1_1B_Q8_0, SDXL_BASE_1_0_3B_Q4_0, TERNARY_BONSAI_2_27B_MULTIMODAL_PQ2_0, TERNARY_BONSAI_2_27B_MULTIMODAL_PTQ1_0, TTS_CODEC_DECODER_AUDIO8_Q8_0, TTS_CODEC_DECODER_MOSS_TTS_F16, TTS_CODEC_ENCODER_MOSS_TTS_F16, TTS_DELAY_LLM_MOSS_TTS_F16, TTS_LM_MULTILINGUAL_AUDIO8_Q8_0, TTS_MULTILINGUAL_SUPERTONIC3_FP16, TTS_MULTILINGUAL_SUPERTONIC3_Q4_0, TTS_MULTILINGUAL_SUPERTONIC3_Q8_0 } from '@qvac/inference/models';
1
+ import { AUDIOGEN_ACESTEP_5HZ_LM_0_6B_Q8_0, AUDIOGEN_ACESTEP_V15_BASE_Q4_K_M, AUDIOGEN_ACESTEP_V15_SFT_Q8_0, AUDIOGEN_ACESTEP_V15_TURBO_Q4_K_M, AUDIOGEN_ACESTEP_V15_TURBO_Q8_0, AUDIOGEN_QWEN3_EMBEDDING_0_6B_Q8_0, AUDIOGEN_VAE_BF16, EMBEDDINGGEMMA_300M_Q4_0, FLUX_2_KLEIN_4B_Q4_0, FLUX_2_KLEIN_4B_VAE, HEALTHCARE_1_7B_MEDICAL_Q4_K_M, HEALTHCARE_4B_MEDICAL_Q4_K_M, MOE_35B_INST_Q4_K_M, MMPROJ_QWEN3_5_2B_MULTIMODAL_Q8_0, MMPROJ_QWEN3_5_4B_MULTIMODAL_Q8_0, MMPROJ_QWEN3_5_9B_MULTIMODAL_F16, MMPROJ_QWEN3_6_35B_A3B_MULTIMODAL_F16, MMPROJ_QWEN3_8_27B_MULTIMODAL_F16, MMPROJ_TERNARY_BONSAI_2_27B_MULTIMODAL_Q8_0, QWEN3_5_2B_MULTIMODAL_Q4_K_M, QWEN3_5_4B_MULTIMODAL_Q4_K_M, QWEN3_5_9B_MULTIMODAL_Q4_K_M, PARAKEET_TDT_0_6B_V3_Q8_0, PARAKEET_TDT_1_1B_Q8_0, QWEN3_4B_Q4_K_M, QWEN3_6_35B_A3B_MULTIMODAL_Q4_K_M, QWEN3_8_27B_DFLASH2_Q8_0, QWEN3_8_27B_MULTIMODAL_UD_Q4_K_XL, SD_V2_1_1B_Q8_0, SDXL_BASE_1_0_3B_Q4_0, TERNARY_BONSAI_2_27B_MULTIMODAL_PQ2_0, TERNARY_BONSAI_2_27B_MULTIMODAL_PTQ1_0, TTS_CODEC_DECODER_AUDIO8_Q8_0, TTS_CODEC_DECODER_MOSS_TTS_F16, TTS_CODEC_ENCODER_AUDIO8_Q8_0, TTS_CODEC_ENCODER_MOSS_TTS_F16, TTS_DELAY_LLM_MOSS_TTS_F16, TTS_LM_MULTILINGUAL_AUDIO8_Q8_0, TTS_MULTILINGUAL_SUPERTONIC3_FP16, TTS_MULTILINGUAL_SUPERTONIC3_Q4_0, TTS_MULTILINGUAL_SUPERTONIC3_Q8_0 } from '@qvac/inference/models';
2
2
  import { detectToolDialect } from './tool-dialect.js';
3
3
  import { defaultTtsModelName, supertonicModelName } from './tts-model-default.js';
4
4
  import { CAPABILITY_PROFILE_ORDER, QWEN_35_2B, QWEN_35_4B, QWEN_35_9B, QWEN_36_35B_A3B, QWEN_38_27B, KAT_CODER_25_35B, BONSAI_2_27B_PQ2, BONSAI_2_27B_PTQ1, MEDPSY_1_7B, MEDPSY_4B, isCapabilityProfile, meetsMinCapabilityProfile, modelNameToCapabilityProfile, capabilityProfileToModelName, isMultimodalLlm, AGENT_MODEL_NAMES, modelDisplayName, capabilityProfileModelLabel, DEFAULT_IMAGE_MODEL_CHOICE, defaultImageModelChoice, IMAGE_CHOICE_CATALOG, isMobilePlatform, runnableModelName } from './model-catalog-constants.js';
@@ -93,6 +93,7 @@ export const AUDIO8_TTS = {
93
93
  useGPU: true
94
94
  }
95
95
  };
96
+ export const AUDIO8_CODEC_ENCODER_SRC = TTS_CODEC_ENCODER_AUDIO8_Q8_0.src;
96
97
  export const MOSS_TTS = {
97
98
  name: 'MOSS-TTS-8B-F16',
98
99
  category: 'tts',
@@ -108,7 +109,6 @@ export const MOSS_TTS = {
108
109
  };
109
110
  export const MOSS_CODEC_ENCODER_SRC = TTS_CODEC_ENCODER_MOSS_TTS_F16.src;
110
111
  export const CATEGORY_DEFAULTS = [
111
- AUDIO8_TTS,
112
112
  { name: 'Supertonic3-Q4_0', category: 'tts', asset: TTS_MULTILINGUAL_SUPERTONIC3_Q4_0 },
113
113
  {
114
114
  name: 'Supertonic3-Q8_0',
@@ -122,6 +122,7 @@ export const CATEGORY_DEFAULTS = [
122
122
  asset: TTS_MULTILINGUAL_SUPERTONIC3_FP16,
123
123
  modelConfig: TTS_FULL_STEPS
124
124
  },
125
+ AUDIO8_TTS,
125
126
  MOSS_TTS,
126
127
  {
127
128
  name: 'Parakeet-TDT-0.6B-v3-Q8_0',
@@ -454,6 +455,11 @@ export function modelAddonOf(model) {
454
455
  export function residentSrc(model, addon) {
455
456
  return curatedModelAsset(model, addon)?.src ?? model;
456
457
  }
458
+ export function generatorRowName(src) {
459
+ const image = DIFFUSION_CATALOG.find((entry) => entry.model.src === src);
460
+ const music = AUDIOGEN_CATALOG.find((entry) => entry.dit.src === src || entry.dit.name === src);
461
+ return image?.name ?? music?.name ?? src;
462
+ }
457
463
  export function catalogModelName(model, addon) {
458
464
  const known = curatedListables().find((entry) => entry.asset.addon === addon &&
459
465
  (entry.name === model || entry.asset.name === model || entry.asset.src === model));
@@ -1,7 +1,15 @@
1
- import type { AssessModelFitInput, AssessModelFitResult } from '@qvac/inference';
2
- export type ModelFitVerdict = AssessModelFitResult['verdict'];
3
- export type ModelFitBasis = AssessModelFitResult['basis'];
4
- export type ModelFitEvidence = NonNullable<AssessModelFitResult['evidence']>;
1
+ import type { AssessModelFitInput, AssessModelFitResult, getModelInfo } from '@qvac/inference';
2
+ import { type PoolBytes } from './memory-cap.ts';
3
+ type SdkModelFit = AssessModelFitResult['models'][number];
4
+ type SdkPool = AssessModelFitResult['pools'][number];
5
+ declare const VERDICTS: {
6
+ readonly fits: 'likely-fits';
7
+ readonly 'does-not-fit': 'likely-too-large';
8
+ readonly unknown: 'unknown';
9
+ };
10
+ export type ModelFitVerdict = (typeof VERDICTS)[keyof typeof VERDICTS];
11
+ export type ModelFitBasis = string;
12
+ export type ModelFitEvidence = string;
5
13
  export type FitModelType = 'llm' | 'embeddings';
6
14
  export interface FitQuery {
7
15
  src: string;
@@ -11,11 +19,18 @@ export interface FitQuery {
11
19
  registrySource?: string;
12
20
  modelType?: FitModelType;
13
21
  contextTokens: number;
22
+ slots?: number;
23
+ kvCacheK?: string;
24
+ kvCacheV?: string;
25
+ device?: 'cpu' | 'gpu';
26
+ gpuLayers?: number;
27
+ onDisk?: boolean;
14
28
  }
15
29
  export interface FitAssessment {
16
30
  verdict: ModelFitVerdict;
17
- basis: ModelFitBasis;
18
- evidence?: ModelFitEvidence | undefined;
31
+ bytes: number | undefined;
32
+ pools: PoolBytes;
33
+ free?: PoolBytes;
19
34
  reasons: string[];
20
35
  }
21
36
  export interface FitAsset {
@@ -30,26 +45,60 @@ export interface ContextChoice {
30
45
  slots: number;
31
46
  fits: boolean;
32
47
  }
33
- export interface FitQueryOptions {
48
+ export interface FitLoad {
49
+ readonly slots?: number;
50
+ readonly kvCacheK?: string;
51
+ readonly kvCacheV?: string;
52
+ readonly device?: 'cpu' | 'gpu';
53
+ readonly gpuLayers?: number;
54
+ }
55
+ export interface FitQueryOptions extends FitLoad {
34
56
  readonly native?: boolean;
35
57
  readonly modelType?: FitModelType;
36
58
  }
59
+ export interface LadderOptions extends FitLoad {
60
+ readonly rungs?: boolean;
61
+ }
37
62
  export type AssessModelFit = (input: AssessModelFitInput) => Promise<AssessModelFitResult>;
63
+ export type LocateWeight = (query: FitQuery) => Promise<string | undefined>;
64
+ export interface DownloadedWeightSdk {
65
+ getModelInfo: typeof getModelInfo;
66
+ }
38
67
  export declare class ModelFit {
68
+ static readonly ALL_LAYERS = 999;
39
69
  private readonly _assess;
70
+ private readonly _locate;
40
71
  private readonly _chosen;
41
72
  private _rows;
42
- constructor(assess: AssessModelFit);
43
- static query(asset: FitAsset, contextTokens: number, { native, modelType }?: FitQueryOptions): FitQuery;
73
+ private readonly _described;
74
+ private readonly _describing;
75
+ private _background;
76
+ private _closed;
77
+ private _generation;
78
+ private readonly _capacity;
79
+ constructor(assess: AssessModelFit, locate?: LocateWeight);
80
+ static need(label: string, usedBytes: number, freeBytes: number | undefined): string;
81
+ static downloaded(sdk: DownloadedWeightSdk, name: string, sha256Checksum: string): Promise<string | undefined>;
82
+ static query(asset: FitAsset, contextTokens: number, { native, ...load }?: FitQueryOptions): FitQuery;
44
83
  static confirms(assessed: FitAssessment | null): boolean;
84
+ static judge(model: SdkModelFit | undefined): FitAssessment;
85
+ observe(pools: ReadonlyArray<SdkPool>): void;
86
+ capacity(): ReadonlyMap<string, number | undefined>;
45
87
  assess(query: FitQuery): Promise<FitAssessment>;
46
88
  rows(queries: () => ReadonlyMap<string, FitQuery>): Promise<ReadonlyMap<string, FitAssessment>>;
89
+ described(): Promise<void>;
90
+ close(): void;
47
91
  clearRows(): void;
48
92
  chosen(key: string): number | undefined;
49
93
  chosenSlots(key: string): number | undefined;
50
94
  keep(key: string, { ctxSize, slots }: ContextChoice): void;
51
- ladder(asset: FitAsset, tier: number, slots?: number): Promise<ContextChoice>;
95
+ ladder(asset: FitAsset, tier: number, { slots, rungs, gpuLayers, ...load }?: LadderOptions): Promise<ContextChoice>;
52
96
  private _steps;
53
97
  private _ask;
98
+ private _files;
99
+ private _rowsNow;
100
+ private _describeLater;
101
+ private _fit;
54
102
  settle(query: FitQuery): Promise<FitAssessment | null>;
55
103
  }
104
+ export {};
@@ -1,21 +1,79 @@
1
1
  import { errorMessage } from '../guards.js';
2
2
  import { HarnessLog } from '../log.js';
3
+ import { HOST_POOL, totalBytes } from './memory-cap.js';
4
+ const VERDICTS = {
5
+ fits: 'likely-fits',
6
+ 'does-not-fit': 'likely-too-large',
7
+ unknown: 'unknown'
8
+ };
3
9
  const CONTEXT_RUNGS = [32_768, 16_384, 8_192];
4
10
  export class ModelFit {
11
+ static ALL_LAYERS = 999;
5
12
  _assess;
13
+ _locate;
6
14
  _chosen = new Map();
7
15
  _rows = null;
8
- constructor(assess) {
16
+ _described = new Map();
17
+ _describing = new Set();
18
+ _background = Promise.resolve();
19
+ _closed = false;
20
+ _generation = 0;
21
+ _capacity = new Map();
22
+ constructor(assess, locate = async () => undefined) {
9
23
  this._assess = assess;
24
+ this._locate = locate;
10
25
  }
11
- static query(asset, contextTokens, { native = false, modelType } = {}) {
26
+ static need(label, usedBytes, freeBytes) {
27
+ const free = freeBytes === undefined ? '' : ` of ${mib(freeBytes)} free`;
28
+ return `${label} needs ${mib(usedBytes)}${free}`;
29
+ }
30
+ static async downloaded(sdk, name, sha256Checksum) {
31
+ const info = await sdk.getModelInfo({ name }).catch(() => null);
32
+ const files = info?.cacheFiles ?? [];
33
+ if (files.some((file) => !file.isCached)) {
34
+ return undefined;
35
+ }
36
+ return files.find((file) => file.sha256Checksum === sha256Checksum)?.path;
37
+ }
38
+ static query(asset, contextTokens, { native = false, ...load } = {}) {
12
39
  const { src, sha256Checksum, name, registryPath, registrySource } = asset;
13
- return native
14
- ? { src, sha256Checksum, name, registryPath, registrySource, modelType, contextTokens }
15
- : { src, sha256Checksum, name, modelType, contextTokens };
40
+ const query = { src, sha256Checksum, name, contextTokens, ...load };
41
+ return native ? { ...query, registryPath, registrySource } : query;
16
42
  }
17
43
  static confirms(assessed) {
18
- return assessed?.verdict === 'likely-fits' && assessed.evidence === 'native-fit';
44
+ return assessed?.verdict === 'likely-fits';
45
+ }
46
+ static judge(model) {
47
+ if (!model) {
48
+ return { verdict: 'unknown', bytes: undefined, pools: {}, reasons: [] };
49
+ }
50
+ const { status, devices } = model;
51
+ const pools = {};
52
+ const free = {};
53
+ for (const { id, unified, usedBytes, freeBytes } of devices) {
54
+ const pool = unified ? HOST_POOL : id;
55
+ pools[pool] = (pools[pool] ?? 0) + usedBytes;
56
+ if (freeBytes !== undefined) {
57
+ free[pool] = Math.min(free[pool] ?? freeBytes, freeBytes);
58
+ }
59
+ }
60
+ return {
61
+ verdict: VERDICTS[status],
62
+ bytes: devices.length ? totalBytes(pools) : undefined,
63
+ pools,
64
+ free,
65
+ reasons: devices.map(deviceReason)
66
+ };
67
+ }
68
+ observe(pools) {
69
+ for (const { id, totalBytes: total } of pools) {
70
+ const named = this._capacity.get(id);
71
+ const least = total === undefined || named === undefined ? (total ?? named) : Math.min(total, named);
72
+ this._capacity.set(id, least);
73
+ }
74
+ }
75
+ capacity() {
76
+ return this._capacity;
19
77
  }
20
78
  async assess(query) {
21
79
  const [assessed] = await this._ask([query]);
@@ -25,8 +83,7 @@ export class ModelFit {
25
83
  if (this._rows) {
26
84
  return this._rows;
27
85
  }
28
- const keyed = [...queries()];
29
- const pending = this._ask(keyed.map(([, query]) => query)).then((assessed) => new Map(keyed.map(([key], i) => [key, assessed[i]])));
86
+ const pending = this._rowsNow([...queries()]);
30
87
  this._rows = pending;
31
88
  pending.catch(() => {
32
89
  if (this._rows === pending) {
@@ -35,8 +92,17 @@ export class ModelFit {
35
92
  });
36
93
  return pending;
37
94
  }
95
+ described() {
96
+ return this._background;
97
+ }
98
+ close() {
99
+ this._closed = true;
100
+ }
38
101
  clearRows() {
39
102
  this._rows = null;
103
+ this._described.clear();
104
+ this._describing.clear();
105
+ this._generation++;
40
106
  }
41
107
  chosen(key) {
42
108
  return this._chosen.get(key)?.ctxSize;
@@ -49,48 +115,107 @@ export class ModelFit {
49
115
  this._chosen.set(key, { ctxSize, slots });
50
116
  }
51
117
  }
52
- async ladder(asset, tier, slots = 1) {
53
- const choice = await this._steps(asset, tier, { slots, native: true });
54
- if (choice.fits || slots === 1) {
55
- return choice;
118
+ async ladder(asset, tier, { slots = 1, rungs = true, gpuLayers, ...load } = {}) {
119
+ for (let count = slots; count > 1; count = Math.ceil(count / 2)) {
120
+ const query = ModelFit.query(asset, tier * count, {
121
+ ...load,
122
+ native: true,
123
+ slots: count,
124
+ gpuLayers: gpuLayers ?? ModelFit.ALL_LAYERS
125
+ });
126
+ if (ModelFit.confirms(await this.settle(query))) {
127
+ return { ctxSize: tier, slots: count, fits: true };
128
+ }
56
129
  }
57
- return this._steps(asset, tier, { slots: 1, native: false });
130
+ return this._steps(asset, tier, { ...load, gpuLayers, rungs, native: slots === 1 });
58
131
  }
59
- async _steps(asset, tier, { slots, native }) {
60
- const top = await this.settle(ModelFit.query(asset, tier * slots, { native }));
132
+ async _steps(asset, tier, { native, rungs, ...load }) {
133
+ const top = await this.settle(ModelFit.query(asset, tier, { ...load, native }));
61
134
  if (top?.verdict !== 'likely-too-large') {
62
- return { ctxSize: tier, slots, fits: true };
135
+ return { ctxSize: tier, slots: 1, fits: true };
63
136
  }
64
- for (const rung of CONTEXT_RUNGS.filter((size) => size < tier)) {
65
- const assessed = await this.settle(ModelFit.query(asset, rung * slots));
137
+ for (const rung of rungs ? CONTEXT_RUNGS.filter((size) => size < tier) : []) {
138
+ const assessed = await this.settle(ModelFit.query(asset, rung, load));
66
139
  if (ModelFit.confirms(assessed)) {
67
- return { ctxSize: rung, slots, fits: true };
140
+ return { ctxSize: rung, slots: 1, fits: true };
68
141
  }
69
142
  if (assessed?.verdict !== 'likely-too-large') {
70
143
  break;
71
144
  }
72
145
  }
73
- return { ctxSize: tier, slots, fits: false };
146
+ return { ctxSize: tier, slots: 1, fits: false };
74
147
  }
75
148
  async _ask(queries) {
149
+ return this._fit(queries, await this._files(queries));
150
+ }
151
+ _files(queries) {
152
+ return Promise.all(queries.map((query) => (query.onDisk === false ? undefined : this._locate(query))));
153
+ }
154
+ async _rowsNow(keyed) {
155
+ const files = await this._files(keyed.map(([, query]) => query));
156
+ const local = keyed.filter((_, i) => files[i] !== undefined);
157
+ const fitted = local.length
158
+ ? await this._fit(local.map(([, query]) => query), files.filter((file) => file !== undefined))
159
+ : [];
160
+ const rows = new Map(local.map(([key], i) => [key, fitted[i]]));
161
+ for (const [key, query] of keyed.filter((_, i) => files[i] === undefined)) {
162
+ rows.set(key, this._described.get(describedKey(query)) ?? ModelFit.judge(undefined));
163
+ this._describeLater(key, query);
164
+ }
165
+ return rows;
166
+ }
167
+ _describeLater(key, query) {
168
+ const described = describedKey(query);
169
+ if (this._closed ||
170
+ !query.registryPath ||
171
+ this._described.has(described) ||
172
+ this._describing.has(described)) {
173
+ return;
174
+ }
175
+ const generation = this._generation;
176
+ const current = () => !this._closed && generation === this._generation;
177
+ this._describing.add(described);
178
+ this._background = this._background
179
+ .then(async () => {
180
+ if (!current()) {
181
+ return;
182
+ }
183
+ const [assessed] = await this._fit([query], [undefined]);
184
+ if (!current() || assessed.verdict === 'unknown') {
185
+ return;
186
+ }
187
+ this._described.set(described, assessed);
188
+ const rows = await this._rows;
189
+ if (rows?.get(key)?.verdict === 'unknown') {
190
+ rows.set(key, assessed);
191
+ }
192
+ })
193
+ .catch((err) => {
194
+ HarnessLog.debug('fit description failed', { model: query.name, err: errorMessage(err) });
195
+ })
196
+ .finally(() => {
197
+ if (generation === this._generation) {
198
+ this._describing.delete(described);
199
+ }
200
+ });
201
+ }
202
+ async _fit(queries, files) {
76
203
  const result = await this._assess({
77
- models: queries.map(({ contextTokens, modelType = 'llm', sha256Checksum, ...source }) => ({
78
- modelSrc: sha256Checksum ? { ...source, sha256Checksum } : source.src,
204
+ models: queries.map(({ contextTokens, slots = 1, kvCacheK, kvCacheV, device, gpuLayers, modelType = 'llm', sha256Checksum, onDisk, ...source }, i) => ({
205
+ modelSrc: files[i] ?? (sha256Checksum ? { ...source, sha256Checksum } : source.src),
79
206
  modelType,
80
- modelConfig: { ctx_size: contextTokens }
81
- })),
82
- execution: 'sequential',
83
- policy: 'interactive-v1'
84
- });
85
- return queries.map((_, i) => {
86
- const model = result.models[i];
87
- return {
88
- verdict: model?.verdict ?? result.verdict,
89
- basis: result.basis,
90
- evidence: model ? model.evidence : result.evidence,
91
- reasons: [...(model?.reasons ?? result.reasons)]
92
- };
207
+ modelConfig: defined({
208
+ ctx_size: contextTokens,
209
+ parallel: slots > 1 ? slots : undefined,
210
+ 'cache-type-k': kvCacheK,
211
+ 'cache-type-v': kvCacheV,
212
+ device,
213
+ gpu_layers: gpuLayers
214
+ })
215
+ }))
93
216
  });
217
+ this.observe(result.pools);
218
+ return queries.map((_, i) => ModelFit.judge(result.models[i]));
94
219
  }
95
220
  settle(query) {
96
221
  return this.assess(query).catch((err) => {
@@ -99,3 +224,15 @@ export class ModelFit {
99
224
  });
100
225
  }
101
226
  }
227
+ function describedKey({ sha256Checksum, src, contextTokens }) {
228
+ return `${sha256Checksum ?? src}:${contextTokens}`;
229
+ }
230
+ function deviceReason({ name, usedBytes, freeBytes }) {
231
+ return ModelFit.need(name, usedBytes, freeBytes);
232
+ }
233
+ function defined(config) {
234
+ return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== undefined));
235
+ }
236
+ function mib(bytes) {
237
+ return `${Math.round(bytes / 1_048_576)} MiB`;
238
+ }
@@ -1,12 +1,13 @@
1
1
  import { type AbortSignal } from 'bare-abort-controller';
2
2
  import type { LoadFit } from '../contract-types.ts';
3
+ import type { PoolBytes } from './memory-cap.ts';
3
4
  export interface ModelResource {
4
5
  model: string;
5
6
  modelId: string;
6
7
  ctxSize?: number;
7
8
  slots?: number;
8
9
  fit?: LoadFit | undefined;
9
- bytes?: number;
10
+ pools?: PoolBytes | undefined;
10
11
  canThink?: boolean | undefined;
11
12
  }
12
13
  export interface ModelHandleOptions {
@@ -3,6 +3,7 @@ import { ModelHandle } from './model-handle.ts';
3
3
  import { type ModelSrc } from './context.ts';
4
4
  import { type SpeculativeDraft } from './model-catalog.ts';
5
5
  import type { CpuPlacement } from '../hardware/cpu-placement.ts';
6
+ import type { PoolBytes } from './memory-cap.ts';
6
7
  import { type ModelAddon } from './model-source.ts';
7
8
  import type { GpuFaultState } from './sdk-faults.ts';
8
9
  import type { LoadedModelInfo } from '@qvac/inference';
@@ -42,7 +43,7 @@ export interface PendingLoad {
42
43
  readonly modelConfig?: Record<string, unknown> | undefined;
43
44
  }
44
45
  export interface Admission {
45
- readonly bytes: number | undefined;
46
+ readonly pools: PoolBytes | undefined;
46
47
  release(): void;
47
48
  }
48
49
  export type BeforeLoad = (load: PendingLoad) => Promise<Admission | undefined>;
@@ -128,7 +129,7 @@ export declare function settledModels(pool: PoolLike): string[];
128
129
  export interface SettledEntry {
129
130
  readonly key: string;
130
131
  readonly refs: number;
131
- readonly bytes: number | undefined;
132
+ readonly pools: PoolBytes | undefined;
132
133
  readonly lastUsed: number;
133
134
  }
134
135
  export declare function settledEntries(pool: PoolLike): SettledEntry[];
@@ -6,6 +6,7 @@ import { ModelHandle } from './model-handle.js';
6
6
  import { defaultContextSize } from './context.js';
7
7
  import { customContextLength, speculativeDraft } from './model-catalog.js';
8
8
  import { localWeightFile } from './custom-model-cache.js';
9
+ import { ModelFit } from './model-fit.js';
9
10
  import { GGUF_STUB_MAX_BYTES, parseGgufHeader, readGgufHeaderBytes } from './gguf-header.js';
10
11
  import { adrenoSafeKvCache, headSafeKvCache } from './kv-cache.js';
11
12
  import { DEFAULT_EMBED_BATCH_SIZE } from './embed-config.js';
@@ -170,7 +171,7 @@ export function settledEntries(pool) {
170
171
  out.push({
171
172
  key: entry.id,
172
173
  refs: entry.refs,
173
- bytes: resource.bytes,
174
+ pools: resource.pools,
174
175
  lastUsed: entry.value.lastUsed
175
176
  });
176
177
  }
@@ -476,8 +477,7 @@ export function createModelPool(loadSdk, notify, { deviceConfig = {}, loads = cr
476
477
  modelId,
477
478
  ctxSize,
478
479
  slots,
479
- bytes: admission?.bytes,
480
- fit: await loadFit(sdk, model, modelId),
480
+ ...(await settled(sdk, { model, modelId, admission })),
481
481
  canThink: canThink(header)
482
482
  };
483
483
  };
@@ -522,7 +522,7 @@ export function createEmbedPool(loadSdk, notify, { faults, batchSize = DEFAULT_E
522
522
  onProgress: (progress) => notify(progressState(model, progress))
523
523
  }), sdk))
524
524
  .finally(() => admission?.release());
525
- return { model, modelId, bytes: admission?.bytes, fit: await loadFit(sdk, model, modelId) };
525
+ return { model, modelId, ...(await settled(sdk, { model, modelId, admission })) };
526
526
  };
527
527
  return new ModelPuddle({
528
528
  open: (key, model = key) => reportedHandle({ notify, model, addon: 'embeddings', hold, load: () => load(key, model) }),
@@ -568,7 +568,7 @@ export function createVoicePool(loadSdk, notify, { modelType, addon, modelConfig
568
568
  return attempt();
569
569
  }))
570
570
  .finally(() => admission?.release());
571
- return { model, modelId, bytes: admission?.bytes, fit: await loadFit(sdk, model, modelId) };
571
+ return { model, modelId, ...(await settled(sdk, { model, modelId, admission })) };
572
572
  };
573
573
  return new ModelPuddle({
574
574
  open: (key, model = key) => reportedHandle({ notify, model, addon, hold, load: () => load(key, model) }),
@@ -576,7 +576,11 @@ export function createVoicePool(loadSdk, notify, { modelType, addon, modelConfig
576
576
  ...NO_IDLE_GC
577
577
  });
578
578
  }
579
- async function loadFit(sdk, model, modelId) {
579
+ async function settled(sdk, { model, modelId, admission }) {
580
+ const probe = await loadProbe(sdk, model, modelId);
581
+ return { pools: admission && (probe?.pools ?? admission.pools), fit: probe?.fit };
582
+ }
583
+ async function loadProbe(sdk, model, modelId) {
580
584
  let probe;
581
585
  try {
582
586
  probe = (await sdk.getLoadedModelInfo?.({ modelId }))?.fitProbe;
@@ -588,18 +592,31 @@ async function loadFit(sdk, model, modelId) {
588
592
  if (!probe) {
589
593
  return undefined;
590
594
  }
591
- const { verdict, reason, plan, projection } = probe;
595
+ const { verdict, pools, models } = probe;
596
+ const [own] = models;
597
+ const devicePools = pools.filter((pool) => !pool.unified);
592
598
  const fit = {
593
- verdict,
594
- reason,
595
- plan: plan && { nCtx: plan.nCtx, nGpuLayers: plan.nGpuLayers, nGpuDevices: plan.nGpuDevices },
596
- deviceBytes: projection?.deviceBytes,
597
- hostBytes: projection?.hostBytes
599
+ verdict: verdict === 'fits' ? 'fit' : verdict,
600
+ reason: pools
601
+ .map(({ id, usedBytes, freeBytes }) => ModelFit.need(id, usedBytes, freeBytes))
602
+ .join('; '),
603
+ plan: own && 'ctxSize' in own.stats
604
+ ? {
605
+ nCtx: own.stats.ctxSize,
606
+ nGpuLayers: own.stats.gpuLayers,
607
+ nGpuDevices: Math.max(own.devices.length - 1, 0)
608
+ }
609
+ : undefined,
610
+ deviceBytes: devicePools.length
611
+ ? devicePools.reduce((sum, { usedBytes }) => sum + usedBytes, 0)
612
+ : undefined,
613
+ hostBytes: pools.find((pool) => pool.unified)?.usedBytes
598
614
  };
599
615
  if (verdict === 'does-not-fit') {
600
616
  HarnessLog.info('loaded past a does-not-fit probe', { model, ...fit });
601
617
  }
602
- return fit;
618
+ const judged = ModelFit.judge(own);
619
+ return { fit, pools: judged.bytes === undefined ? undefined : judged.pools };
603
620
  }
604
621
  function unloadOnGc(loadSdk, notify, onUnloadFailure) {
605
622
  return async (handles) => {
@@ -1,4 +1,4 @@
1
1
  export type TtsCapabilityProfile = 'tiny' | 'low' | 'mid' | 'high' | 'xhigh';
2
2
  export declare const TTS_MODEL_NAMES: ReadonlyArray<string>;
3
- export declare function defaultTtsModelName(_profile: TtsCapabilityProfile): string;
3
+ export declare function defaultTtsModelName(profile: TtsCapabilityProfile): string;
4
4
  export declare function supertonicModelName(profile: TtsCapabilityProfile): string;