@qvac/translation-nmtcpp 0.23.1 → 0.24.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.
package/README.md CHANGED
@@ -566,16 +566,29 @@ Call `TranslationNmtcpp.assessFit({ files, config, marginBytes? })` before
566
566
  constructing a model to estimate whether its weights can load with the memory
567
567
  free right now. `files` and `config` match the constructor; `files.model` must
568
568
  be an absolute path. It returns a Promise, and concurrent calls run one at a
569
- time within the addon. The result contains `status` (`fits`,
570
- `does-not-fit`, or `error`), `reason`, `backend`, `modelBytes`, `requiredBytes`,
571
- `freeBytes`, and a readable `report`. An unreadable model resolves with
572
- `status: 'error'`; a malformed request rejects. No model instance or weights are
573
- loaded.
569
+ time within the addon. The result is `{ status, devices, stats }`: `status` is
570
+ `fits`, `does-not-fit`, or `unknown`, and `devices` is
571
+ `[{ id, name, unified, usedBytes, freeBytes, totalBytes }]`: the selected device,
572
+ charged the allowance, then the host CPU. A discrete GPU's host row carries the
573
+ model's source bytes, which the host stages while the weights load; a GPU that
574
+ shares host memory has a host row carrying 0. A load on the CPU, which every
575
+ Bergamot load is, is one row. `id` is the PCI bus ID when the backend reports
576
+ one, and the device name otherwise. `unified` is true for memory the host owns:
577
+ the CPU, an integrated GPU, a GPU that shares the host's memory, Android's
578
+ OpenCL GPU, and a device that reports no memory of its own, which takes the
579
+ host's figures. No model instance or weights are loaded.
574
580
  The estimate budgets four times the model file size plus 512 MiB for copies,
575
- tokenizers, and inference buffers; actual use varies by model. An indeterminate placement reports `error`
576
- with `reason: 'insufficient-evidence'`. IndicTrans `main-gpu` selection currently
577
- reports `unsupported-config`. Fit is a point-in-time estimate, so
578
- another load can consume memory before `load()` runs.
581
+ tokenizers, and inference buffers; actual use varies by model. `fits` means
582
+ every row's charge fits with `marginBytes` left free. `does-not-fit` means a CPU
583
+ load whose source bytes alone do not fit. A placement between the two, memory
584
+ that cannot be read, no CPU device for the host row, and IndicTrans `main-gpu`
585
+ selection are `unknown`, with no rows. On an iOS device every unified row's free
586
+ memory is capped at the app's own memory limit, `os_proc_available_memory()`,
587
+ before the verdict, and a limit of 0 means the app has none left. A model or
588
+ vocabulary that cannot be read, a requested GPU that is unavailable, or a
589
+ malformed request rejects with an `InvalidArgument` error, and a CPU load on a
590
+ host with no CPU device with an `InternalError`. Fit is a point-in-time estimate, so another
591
+ load can consume memory before `load()` runs.
579
592
 
580
593
  ```js
581
594
  const fit = await TranslationNmtcpp.assessFit({
@@ -583,7 +596,10 @@ const fit = await TranslationNmtcpp.assessFit({
583
596
  config: { modelType: TranslationNmtcpp.ModelTypes.IndicTrans },
584
597
  marginBytes: 256 * 1024 * 1024
585
598
  })
586
- if (fit.status !== 'fits') console.log(fit.report)
599
+
600
+ fit.status // 'fits' | 'does-not-fit' | 'unknown'
601
+ fit.devices // [{ id, name, unified, usedBytes, freeBytes, totalBytes }]
602
+ fit.stats // {}
587
603
  ```
588
604
 
589
605
  - `load(): Promise<void>` — loads the model (both stages for pivot setups);
package/index.d.ts CHANGED
@@ -61,7 +61,8 @@ interface TranslationNmtcppConstructor {
61
61
  new (args: TranslationNmtcppArgs): TranslationNmtcpp;
62
62
  /**
63
63
  * Assess a model before loading it, using current device memory. Concurrent
64
- * calls run one at a time. A malformed request rejects.
64
+ * calls run one at a time. A model or vocabulary that cannot be read, no
65
+ * usable device, or a malformed request rejects.
65
66
  */
66
67
  assessFit(request: TranslationNmtcpp.FitRequest): Promise<TranslationNmtcpp.FitResult>;
67
68
  /**
@@ -85,15 +86,32 @@ declare namespace TranslationNmtcpp {
85
86
  /** Additional free memory to reserve, in bytes. */
86
87
  marginBytes?: number;
87
88
  }
88
- interface FitResult {
89
- status: "fits" | "does-not-fit" | "error";
90
- reason: string;
91
- /** CPU or selected GGML device name. */
92
- backend: string;
93
- modelBytes: number;
94
- requiredBytes: number;
89
+ /**
90
+ * `unknown` is a load with no reliable verdict: a `main-gpu` selection,
91
+ * memory that cannot be read, no CPU device for the host row, or a load
92
+ * between the allowance and the source bytes.
93
+ */
94
+ type FitStatus = "fits" | "does-not-fit" | "unknown";
95
+ interface FitDevice {
96
+ /** The PCI bus ID when the backend reports one, the device name otherwise. */
97
+ id: string;
98
+ name: string;
99
+ /** Memory the host owns: the host CPU, and a GPU that shares the host's memory. */
100
+ unified: boolean;
101
+ /** The weight-load allowance on the selected device; the staged source bytes on the host. */
102
+ usedBytes: number;
95
103
  freeBytes: number;
96
- report: string;
104
+ totalBytes: number;
105
+ }
106
+ type FitStats = Record<string, never>;
107
+ interface FitResult {
108
+ status: FitStatus;
109
+ /**
110
+ * The selected GPU, then the host CPU, which stages a discrete GPU's source
111
+ * bytes. One CPU row for a load on the CPU, and none for `unknown`.
112
+ */
113
+ devices: FitDevice[];
114
+ stats: FitStats;
97
115
  }
98
116
  interface TranslationNmtcppFiles {
99
117
  model: string;
package/index.js CHANGED
@@ -95,15 +95,8 @@ const TranslationNmtcpp = class TranslationNmtcpp {
95
95
  if (modelType === "IndicTrans" &&
96
96
  (request.config["main-gpu"] !== undefined ||
97
97
  request.config.main_gpu !== undefined)) {
98
- return {
99
- status: "error",
100
- reason: "unsupported-config",
101
- backend: "",
102
- modelBytes: 0,
103
- requiredBytes: 0,
104
- freeBytes: 0,
105
- report: "Fit with main-gpu selection is unavailable",
106
- };
98
+ // The fitter cannot follow a main-gpu selection.
99
+ return { status: "unknown", devices: [], stats: {} };
107
100
  }
108
101
  // eslint-disable-next-line @typescript-eslint/no-require-imports -- native binding is resolved lazily.
109
102
  const binding = require("./binding");
package/lib/error.js CHANGED
@@ -10,7 +10,7 @@ class QvacErrorAddonMarian extends QvacErrorBase {
10
10
  exports.QvacErrorAddonMarian = QvacErrorAddonMarian;
11
11
  // eslint-disable-next-line @typescript-eslint/no-require-imports -- package metadata is read from the package root at runtime.
12
12
  const { name, version } = require("../package.json");
13
- // This library has error code range from 8001 to 9000
13
+ // Reservations are maintained in packages/error/code-ranges.json, excluding OCR's block.
14
14
  exports.ERR_CODES = Object.freeze({
15
15
  FAILED_TO_LOAD_WEIGHTS: 8001,
16
16
  FAILED_TO_CANCEL: 8002,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qvac/translation-nmtcpp",
3
- "version": "0.23.1",
3
+ "version": "0.24.0",
4
4
  "description": "translation addon for qvac",
5
5
  "addon": true,
6
6
  "engines": {
@@ -78,8 +78,8 @@
78
78
  "bugs": "https://github.com/tetherto/qvac/issues",
79
79
  "homepage": "https://qvac.tether.io",
80
80
  "devDependencies": {
81
- "@qvac/fabric-android-arm64": "^0.25.0",
82
- "@qvac/fabric-ios": "^0.25.0",
81
+ "@qvac/fabric-android-arm64": "^0.26.0",
82
+ "@qvac/fabric-ios": "^0.26.0",
83
83
  "@qvac/registry-client": "^0.6.1",
84
84
  "@types/node": "^24.2.1",
85
85
  "bare-fetch": "^3.0.1",
@@ -98,7 +98,7 @@
98
98
  },
99
99
  "dependencies": {
100
100
  "@qvac/error": "^0.1.0",
101
- "@qvac/fabric": "^0.25.0",
101
+ "@qvac/fabric": "^0.26.0",
102
102
  "@qvac/infer-base": "^0.8.0",
103
103
  "@qvac/logging": "^0.1.0",
104
104
  "bare-fs": "^4.5.1",
@@ -108,16 +108,16 @@
108
108
  "bare-url": "^2.1.6"
109
109
  },
110
110
  "optionalDependencies": {
111
- "@qvac/fabric-linux-x64": "^0.25.0",
112
- "@qvac/fabric-linux-arm64": "^0.25.0",
113
- "@qvac/fabric-darwin-arm64": "^0.25.0",
114
- "@qvac/fabric-darwin-x64": "^0.25.0",
115
- "@qvac/fabric-win32-x64": "^0.25.0"
111
+ "@qvac/fabric-linux-x64": "^0.26.0",
112
+ "@qvac/fabric-linux-arm64": "^0.26.0",
113
+ "@qvac/fabric-darwin-arm64": "^0.26.0",
114
+ "@qvac/fabric-darwin-x64": "^0.26.0",
115
+ "@qvac/fabric-win32-x64": "^0.26.0"
116
116
  },
117
117
  "peerDependencies": {
118
118
  "bare-fetch": "^3.0.1",
119
- "@qvac/fabric-android-arm64": "^0.25.0",
120
- "@qvac/fabric-ios": "^0.25.0"
119
+ "@qvac/fabric-android-arm64": "^0.26.0",
120
+ "@qvac/fabric-ios": "^0.26.0"
121
121
  },
122
122
  "peerDependenciesMeta": {
123
123
  "bare-fetch": {
@@ -7,7 +7,7 @@
7
7
  ],
8
8
  "current_versions": [
9
9
  {
10
- "version": "0.23.1"
10
+ "version": "0.24"
11
11
  }
12
12
  ],
13
13
  "exported_symbols": [
@@ -7,7 +7,7 @@
7
7
  ],
8
8
  "current_versions": [
9
9
  {
10
- "version": "0.23.1"
10
+ "version": "0.24"
11
11
  }
12
12
  ],
13
13
  "exported_symbols": [
@@ -7,7 +7,7 @@
7
7
  ],
8
8
  "current_versions": [
9
9
  {
10
- "version": "0.23.1"
10
+ "version": "0.24"
11
11
  }
12
12
  ],
13
13
  "exported_symbols": [
@@ -7,7 +7,7 @@
7
7
  ],
8
8
  "current_versions": [
9
9
  {
10
- "version": "0.23.1"
10
+ "version": "0.24"
11
11
  }
12
12
  ],
13
13
  "exported_symbols": [
@@ -7,7 +7,7 @@
7
7
  ],
8
8
  "current_versions": [
9
9
  {
10
- "version": "0.23.1"
10
+ "version": "0.24"
11
11
  }
12
12
  ],
13
13
  "exported_symbols": [
@@ -8,6 +8,11 @@ const process = require('bare-process')
8
8
  const TranslationNmtcpp = require('../../index.js')
9
9
  const { ensureIndicTransModel, ensureBergamotModel, TEST_TIMEOUT } = require('./utils')
10
10
 
11
+ const OVERHEAD_BYTES = 512 * 1024 * 1024
12
+ const allowance = (sourceBytes) => sourceBytes * 4 + OVERHEAD_BYTES
13
+ const isVerdict = (fit) => fit.status === 'fits' || fit.status === 'does-not-fit'
14
+ const demand = (fit) => fit.devices.map((row) => [row.id, row.usedBytes])
15
+
11
16
  test('fit rejects a relative model path before native use', async (t) => {
12
17
  let error
13
18
  try {
@@ -32,14 +37,23 @@ test('a malformed native request rejects', async (t) => {
32
37
  await t.exception(promise, /marginBytes/)
33
38
  })
34
39
 
35
- test('fit reports a missing model without loading it', async (t) => {
36
- const result = await TranslationNmtcpp.assessFit({
40
+ test('a missing model rejects without loading it', async (t) => {
41
+ await t.exception(
42
+ TranslationNmtcpp.assessFit({
43
+ files: { model: path.resolve(__dirname, 'missing-model.bin') },
44
+ config: { modelType: TranslationNmtcpp.ModelTypes.IndicTrans }
45
+ }),
46
+ /cannot read the translation model/
47
+ )
48
+ })
49
+
50
+ test('a main-gpu selection is unknown', async (t) => {
51
+ const fit = await TranslationNmtcpp.assessFit({
37
52
  files: { model: path.resolve(__dirname, 'missing-model.bin') },
38
- config: { modelType: TranslationNmtcpp.ModelTypes.IndicTrans }
53
+ config: { modelType: TranslationNmtcpp.ModelTypes.IndicTrans, 'main-gpu': 0 }
39
54
  })
40
- t.is(result.status, 'error')
41
- t.is(result.reason, 'model-unreadable')
42
- t.is(result.modelBytes, 0)
55
+ t.is(fit.status, 'unknown')
56
+ t.alike(fit.devices, [])
43
57
  })
44
58
 
45
59
  test('fit reads model, pivot, and vocab files below a Unicode directory', async (t) => {
@@ -60,8 +74,12 @@ test('fit reads model, pivot, and vocab files below a Unicode directory', async
60
74
  files,
61
75
  config: { modelType: TranslationNmtcpp.ModelTypes.Bergamot }
62
76
  })
63
- t.is(fit.modelBytes, 64 * 6)
64
- t.ok(!fit.report.includes('unreadable'), 'every UTF-8 path was inspected')
77
+ t.comment(JSON.stringify(fit))
78
+ t.ok(isVerdict(fit), 'a verdict')
79
+ t.is(fit.devices.length, 1, 'Bergamot runs on the CPU alone')
80
+ t.ok(fit.devices[0].unified, 'the CPU row is the host')
81
+ t.is(fit.devices[0].usedBytes, allowance(64 * 6), 'every UTF-8 path was inspected')
82
+ t.alike(fit.stats, {})
65
83
  } finally {
66
84
  fs.rmSync(dir, { recursive: true, force: true })
67
85
  }
@@ -86,33 +104,27 @@ test('queued fits keep their own requests and all settle', async (t) => {
86
104
  files: { model: path.join(dir, 'missing.bin') },
87
105
  config: { modelType: TranslationNmtcpp.ModelTypes.IndicTrans }
88
106
  })
89
- const [a, b, c] = await Promise.all([first, second, missing])
90
- t.is(a.modelBytes, 64 * 3, 'the first call owns its original files')
91
- t.ok(b.report.includes('dstVocab'), 'the second call owns its changed files')
92
- t.is(c.reason, 'model-unreadable', 'an error outcome does not strand queued callers')
107
+ const [a, b, c] = await Promise.allSettled([first, second, missing])
108
+ t.is(a.status, 'fulfilled', 'the first call read its files')
109
+ t.is(a.value.devices[0].usedBytes, allowance(64 * 3), 'the first call owns its original files')
110
+ t.ok(String(b.reason).includes('dstVocab'), 'the second call owns its changed files')
111
+ t.is(c.status, 'rejected', 'a rejection does not strand queued callers')
93
112
  } finally {
94
113
  fs.rmSync(dir, { recursive: true, force: true })
95
114
  }
96
115
  })
97
116
 
98
- async function checkRealModelFit(t, request) {
117
+ async function checkRealModelFit(t, request, sourceBytes) {
99
118
  const fit = await TranslationNmtcpp.assessFit(request)
100
- t.comment(`backend=${fit.backend} status=${fit.status} reason=${fit.reason}`)
101
- t.ok(fit.modelBytes > 0, 'model file bytes were inspected')
102
- if (fit.freeBytes === 0) {
103
- t.is(fit.status, 'error')
104
- t.is(fit.reason, 'device-memory-unavailable')
105
- return
119
+ t.comment(JSON.stringify(fit))
120
+ t.ok(isVerdict(fit) || fit.status === 'unknown', 'a verdict, or an explicit unknown')
121
+ if (isVerdict(fit)) {
122
+ t.is(fit.devices.length, 1, 'a CPU load is one row')
123
+ t.ok(fit.devices[0].usedBytes > sourceBytes, 'the load allowance includes overhead')
124
+ t.ok(fit.devices[0].freeBytes > 0, 'current memory was queried')
125
+ } else {
126
+ t.alike(fit.devices, [], 'an unknown carries no rows')
106
127
  }
107
- t.ok(fit.requiredBytes > fit.modelBytes, 'load allowance includes overhead')
108
- t.ok(fit.freeBytes > 0, 'current device memory was queried')
109
- t.ok(fit.report.includes('Translation load estimate:'), 'a readable report was returned')
110
- t.ok(
111
- fit.status === 'fits' ||
112
- fit.status === 'does-not-fit' ||
113
- (fit.status === 'error' && fit.reason === 'insufficient-evidence'),
114
- 'the ordinary assessment has a capacity verdict or explicitly reports uncertainty'
115
- )
116
128
 
117
129
  // The same real model cannot fit when the caller reserves every available
118
130
  // byte. This checks the capacity decision without assuming a runner's RAM.
@@ -121,8 +133,7 @@ async function checkRealModelFit(t, request) {
121
133
  marginBytes: Number.MAX_SAFE_INTEGER
122
134
  })
123
135
  t.is(reserved.status, 'does-not-fit')
124
- t.is(reserved.reason, 'does-not-fit')
125
- t.ok(reserved.modelBytes >= fit.modelBytes)
136
+ t.is(reserved.devices.length, 1)
126
137
  }
127
138
 
128
139
  test(
@@ -130,10 +141,14 @@ test(
130
141
  { timeout: TEST_TIMEOUT },
131
142
  async (t) => {
132
143
  const model = await ensureIndicTransModel()
133
- await checkRealModelFit(t, {
134
- files: { model },
135
- config: { modelType: TranslationNmtcpp.ModelTypes.IndicTrans, use_gpu: false }
136
- })
144
+ await checkRealModelFit(
145
+ t,
146
+ {
147
+ files: { model },
148
+ config: { modelType: TranslationNmtcpp.ModelTypes.IndicTrans, use_gpu: false }
149
+ },
150
+ fs.statSync(model).size
151
+ )
137
152
  }
138
153
  )
139
154
 
@@ -144,14 +159,34 @@ test(
144
159
  const model = await ensureIndicTransModel()
145
160
  const files = { model }
146
161
  const config = { modelType: TranslationNmtcpp.ModelTypes.IndicTrans, use_gpu: true }
147
- const automatic = await TranslationNmtcpp.assessFit({ files, config })
148
- const conflicting = await TranslationNmtcpp.assessFit({
149
- files,
150
- config: { ...config, gpu_backend: '', gpuBackend: 'no-such-backend' }
151
- })
162
+ const [automaticResult, conflictingResult] = await Promise.allSettled([
163
+ TranslationNmtcpp.assessFit({ files, config }),
164
+ TranslationNmtcpp.assessFit({
165
+ files,
166
+ config: { ...config, gpu_backend: '', gpuBackend: 'no-such-backend' }
167
+ })
168
+ ])
169
+ t.is(conflictingResult.status, automaticResult.status, 'backend alias keeps the same outcome')
170
+ if (automaticResult.status === 'rejected') {
171
+ t.is(automaticResult.reason.code, '[ General :: InvalidArgument ]')
172
+ t.is(automaticResult.reason.message, 'assessFit: the requested compute device is unavailable')
173
+ if (conflictingResult.status === 'rejected') {
174
+ t.is(conflictingResult.reason.code, automaticResult.reason.code)
175
+ t.is(conflictingResult.reason.message, automaticResult.reason.message)
176
+ }
177
+ return
178
+ }
179
+ if (conflictingResult.status === 'rejected') return
180
+ const automatic = automaticResult.value
181
+ const conflicting = conflictingResult.value
152
182
  t.is(conflicting.status, automatic.status)
153
- t.is(conflicting.reason, automatic.reason)
154
- t.is(conflicting.backend, automatic.backend)
183
+ t.alike(
184
+ conflicting.devices.map((row) => row.id),
185
+ automatic.devices.map((row) => row.id)
186
+ )
187
+ if (isVerdict(automatic)) {
188
+ t.is(automatic.devices.at(-1).name, 'CPU', 'the host row is last')
189
+ }
155
190
  }
156
191
  )
157
192
 
@@ -167,14 +202,19 @@ test(
167
202
  t.ok(vocabName, 'Bergamot vocabulary is available')
168
203
  if (!modelName || !vocabName) return
169
204
 
170
- await checkRealModelFit(t, {
171
- files: {
172
- model: path.join(modelDir, modelName),
173
- srcVocab: path.join(modelDir, vocabName),
174
- dstVocab: path.join(modelDir, vocabName)
205
+ const model = path.join(modelDir, modelName)
206
+ await checkRealModelFit(
207
+ t,
208
+ {
209
+ files: {
210
+ model,
211
+ srcVocab: path.join(modelDir, vocabName),
212
+ dstVocab: path.join(modelDir, vocabName)
213
+ },
214
+ config: { modelType: TranslationNmtcpp.ModelTypes.Bergamot }
175
215
  },
176
- config: { modelType: TranslationNmtcpp.ModelTypes.Bergamot }
177
- })
216
+ fs.statSync(model).size
217
+ )
178
218
  }
179
219
  )
180
220
 
@@ -186,6 +226,7 @@ test('fitting keeps the event loop responsive', { timeout: TEST_TIMEOUT }, async
186
226
  files: { model },
187
227
  config: { modelType: TranslationNmtcpp.ModelTypes.IndicTrans, use_gpu: false }
188
228
  }
229
+ const expected = await TranslationNmtcpp.assessFit(request)
189
230
  let pending = false
190
231
  let ticks = 0
191
232
  const timer = setInterval(() => {
@@ -202,7 +243,7 @@ test('fitting keeps the event loop responsive', { timeout: TEST_TIMEOUT }, async
202
243
  }
203
244
  t.ok(ticks > 0, 'timers ran before fitting settled')
204
245
  t.ok(
205
- fits.every((fit) => fit.modelBytes > 0),
246
+ fits.every((fit) => JSON.stringify(demand(fit)) === JSON.stringify(demand(expected))),
206
247
  'every queued fit measured the model'
207
248
  )
208
249
  t.comment(`${ticks} timer ticks before completion`)
@@ -228,8 +269,10 @@ test(
228
269
  const fit = TranslationNmtcpp.assessFit({ files: { model: modelPath }, config })
229
270
  await model.unload()
230
271
  const result = await fit
231
- t.ok(result.backend.length > 0, 'the backend name survives the model unloading')
232
- t.not(result.reason, 'device-unavailable', 'the fit device stayed available')
272
+ t.ok(
273
+ ['fits', 'does-not-fit', 'unknown'].includes(result.status),
274
+ 'the fit settled after the model unloaded'
275
+ )
233
276
  } finally {
234
277
  await model.destroy()
235
278
  }