dodle commited on
Commit
d9782fd
·
verified ·
1 Parent(s): c05fba7

Upload folder using huggingface_hub

Browse files
README.md CHANGED
@@ -55,7 +55,7 @@ From this directory, train the Python model's action policy:
55
  python3 me.py --train-actions --seed 123
56
  ```
57
 
58
- The command writes `noe-action-model.dodl` and a GGUF companion. It trains on a generated policy and checks progress against a fixed set of 100 validation scenarios. It keeps the best checkpoint and stops when validation accuracy no longer improves. Use `--samples`, `--epochs`, and `--patience` to adjust training, `--output` to choose a file path, and `--seed` to make a run repeatable. The engine uses the trained policy unless a rule or eligible goal takes priority.
59
 
60
  ### Pixel controller
61
 
@@ -85,7 +85,7 @@ The files are binary, not text or JSON. The serializer and loader support files
85
 
86
  ## Use a language model for replies
87
 
88
- `LLMProvider` can request replies from OpenAI, Gemini, or an OpenAI-compatible server. It uses Python's standard library, so you do not need a provider SDK. Provider settings and API keys are read at runtime and are never saved in the model file.
89
 
90
  For OpenAI, set:
91
 
@@ -166,7 +166,7 @@ You can pass DODL models or supported model paths. ONNX loading requires `pip in
166
  - `serialize_model(model)` and `deserialize_model(data)` convert to and from DODL bytes.
167
  - `serialize_gguf_model(model)` and `create_gguf_model_file(path, model)` write GGUF data.
168
  - `AIEngine(model=None)` runs a model. `step(input_value)` performs one cycle, and `export_model()` returns the updated model as bytes.
169
- - `train_action_model(...)` trains an action policy; `evaluate_action_model(model)` reports its validation results.
170
  - `merge_models(model_a, model_b, alpha=0.5)` blends network weights.
171
  - `LLMProvider(...)` configures a text-generation service; `AIEngine.respond(...)` requests a reply and runs one local cycle.
172
  - `BiocomputationProvider(...)` configures a remote service; `AIEngine.compute_biological(...)` submits a task without changing model state.
 
55
  python3 me.py --train-actions --seed 123
56
  ```
57
 
58
+ The command writes `noe-action-model.dodl` and a GGUF companion. It trains on a generated policy and selects checkpoints using 100 fixed validation scenarios. Evaluation also reports results on a separate 100-scenario held-out set, including accuracy and support for each action; held-out results do not affect checkpoint selection. Use `--samples`, `--epochs`, and `--patience` to adjust training, `--output` to choose a file path, and `--seed` to make a run repeatable. The engine uses the trained policy unless a rule or eligible goal takes priority.
59
 
60
  ### Pixel controller
61
 
 
85
 
86
  ## Use a language model for replies
87
 
88
+ `LLMProvider` can request replies from OpenAI, Gemini, or an OpenAI-compatible server. It uses Python's standard library, so you do not need a provider SDK. Requests and responses are limited to 1 MiB, and the timeout must be a positive finite number. Provider settings and API keys are read at runtime and are never saved in the model file.
89
 
90
  For OpenAI, set:
91
 
 
166
  - `serialize_model(model)` and `deserialize_model(data)` convert to and from DODL bytes.
167
  - `serialize_gguf_model(model)` and `create_gguf_model_file(path, model)` write GGUF data.
168
  - `AIEngine(model=None)` runs a model. `step(input_value)` performs one cycle, and `export_model()` returns the updated model as bytes.
169
+ - `train_action_model(...)` trains an action policy; `evaluate_action_model(model)` reports validation and held-out results, including per-action accuracy and support.
170
  - `merge_models(model_a, model_b, alpha=0.5)` blends network weights.
171
  - `LLMProvider(...)` configures a text-generation service; `AIEngine.respond(...)` requests a reply and runs one local cycle.
172
  - `BiocomputationProvider(...)` configures a remote service; `AIEngine.compute_biological(...)` submits a task without changing model state.
index.html CHANGED
@@ -31,6 +31,6 @@
31
  </head>
32
  <body>
33
  <div class="pixel" aria-hidden="true"></div>
34
- <script src="./me.js"></script>
35
  </body>
36
  </html>
 
31
  </head>
32
  <body>
33
  <div class="pixel" aria-hidden="true"></div>
34
+ <script type="module" src="./me.js"></script>
35
  </body>
36
  </html>
me.js CHANGED
@@ -1,12 +1,12 @@
1
  // Copyright (c) Napol Thanarangkaun
2
  // Licensed under the MIT License - See LICENSE file for details
3
 
 
 
4
  const pixel = document.querySelector(".pixel");
5
  const motionPreference = window.matchMedia("(prefers-reduced-motion: reduce)");
6
  const pixelSize = 5;
7
  const maxVelocity = 3;
8
- const maxModelSize = 1024 * 1024;
9
- const maxPixelHiddenSize = 128;
10
  const state = {
11
  x: pixelSize / 2 + Math.random() * Math.max(0, window.innerWidth - pixelSize),
12
  y: pixelSize / 2 + Math.random() * Math.max(0, window.innerHeight - pixelSize),
@@ -20,98 +20,6 @@ const state = {
20
  };
21
  let pixelModel = null;
22
 
23
- function readFloatArray(view, offset, length) {
24
- const values = new Float32Array(length);
25
- for (let index = 0; index < length; index++) {
26
- values[index] = view.getFloat32(offset + index * 4, true);
27
- if (!Number.isFinite(values[index])) {
28
- throw new Error("DODL model contains a non-finite value.");
29
- }
30
- }
31
- return values;
32
- }
33
-
34
- async function loadPixelModel() {
35
- const response = await fetch("./noe-pixel-model.dodl", { cache: "no-cache" });
36
- if (!response.ok) {
37
- throw new Error(`Model request failed: ${response.status}`);
38
- }
39
- const buffer = await response.arrayBuffer();
40
- if (buffer.byteLength > maxModelSize) {
41
- throw new Error("DODL model exceeds the 1 MiB size limit.");
42
- }
43
- const bytes = new Uint8Array(buffer);
44
- if (bytes.byteLength < 16 || String.fromCharCode(...bytes.subarray(0, 4)) !== "DODL") {
45
- throw new Error("Invalid DODL model header.");
46
- }
47
-
48
- const view = new DataView(buffer);
49
- const formatVersion = view.getUint16(4, true);
50
- const metadataSize = view.getUint32(8, true);
51
- const networkSize = view.getUint32(12, true);
52
- if (formatVersion !== 2 || 16 + metadataSize + networkSize !== buffer.byteLength) {
53
- throw new Error("Unsupported or corrupt DODL model.");
54
- }
55
-
56
- const metadata = JSON.parse(
57
- new TextDecoder().decode(new Uint8Array(buffer, 16, metadataSize)),
58
- );
59
- const { inputSize, hiddenSize, outputSize } = metadata.networkShape;
60
- if (
61
- inputSize !== 8 ||
62
- !Number.isSafeInteger(hiddenSize) ||
63
- hiddenSize < 1 ||
64
- hiddenSize > maxPixelHiddenSize ||
65
- outputSize !== 2
66
- ) {
67
- throw new Error("Expected a pixel model with 8 inputs, 2 outputs, and at most 128 hidden units.");
68
- }
69
- const lengths = [inputSize * hiddenSize, hiddenSize, hiddenSize * outputSize, outputSize];
70
- if (networkSize !== lengths.reduce((total, length) => total + length * 4, 0)) {
71
- throw new Error("DODL network dimensions do not match its data.");
72
- }
73
-
74
- let offset = 16 + metadataSize;
75
- const arrays = lengths.map((length) => {
76
- const values = readFloatArray(view, offset, length);
77
- offset += length * 4;
78
- return values;
79
- });
80
- return {
81
- inputSize,
82
- hiddenSize,
83
- outputSize,
84
- weights1: arrays[0],
85
- bias1: arrays[1],
86
- weights2: arrays[2],
87
- bias2: arrays[3],
88
- hiddenScratch: new Float32Array(hiddenSize),
89
- outputScratch: new Float32Array(outputSize),
90
- };
91
- }
92
-
93
- function runPixelModel(model, inputs) {
94
- const hidden = model.hiddenScratch;
95
- const outputs = model.outputScratch;
96
- for (let hiddenIndex = 0; hiddenIndex < model.hiddenSize; hiddenIndex++) {
97
- let total = model.bias1[hiddenIndex];
98
- const start = hiddenIndex * model.inputSize;
99
- for (let inputIndex = 0; inputIndex < model.inputSize; inputIndex++) {
100
- total += inputs[inputIndex] * model.weights1[start + inputIndex];
101
- }
102
- hidden[hiddenIndex] = Math.max(0, total);
103
- }
104
- for (let outputIndex = 0; outputIndex < model.outputSize; outputIndex++) {
105
- let total = model.bias2[outputIndex];
106
- const start = outputIndex * model.hiddenSize;
107
- for (let hiddenIndex = 0; hiddenIndex < model.hiddenSize; hiddenIndex++) {
108
- total += hidden[hiddenIndex] * model.weights2[start + hiddenIndex];
109
- }
110
- outputs[outputIndex] = total;
111
- }
112
- return outputs;
113
- }
114
-
115
  function createModelInputs() {
116
  const width = Math.max(1, window.innerWidth);
117
  const height = Math.max(1, window.innerHeight);
 
1
  // Copyright (c) Napol Thanarangkaun
2
  // Licensed under the MIT License - See LICENSE file for details
3
 
4
+ import { loadPixelModel, runPixelModel } from "./pixel_model.mjs";
5
+
6
  const pixel = document.querySelector(".pixel");
7
  const motionPreference = window.matchMedia("(prefers-reduced-motion: reduce)");
8
  const pixelSize = 5;
9
  const maxVelocity = 3;
 
 
10
  const state = {
11
  x: pixelSize / 2 + Math.random() * Math.max(0, window.innerWidth - pixelSize),
12
  y: pixelSize / 2 + Math.random() * Math.max(0, window.innerHeight - pixelSize),
 
20
  };
21
  let pixelModel = null;
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  function createModelInputs() {
24
  const width = Math.max(1, window.innerWidth);
25
  const height = Math.max(1, window.innerHeight);
me.py CHANGED
@@ -376,6 +376,15 @@ def _action_policy_validation_examples():
376
  ]
377
 
378
 
 
 
 
 
 
 
 
 
 
379
  def _action_policy_metrics(network, examples):
380
  correct = 0
381
  squared_error = 0.0
@@ -403,6 +412,7 @@ def _action_policy_metrics(network, examples):
403
  else 0.0
404
  for label in ACTION_LABELS
405
  },
 
406
  }
407
 
408
 
@@ -420,13 +430,16 @@ def _network_from_model(model):
420
 
421
 
422
  def evaluate_action_model(model):
423
- """Score a model on the fixed action-policy validation scenarios."""
424
  if not isinstance(model, dict):
425
  model = load_model_file(model)
426
  network = _network_from_model(model)
427
  if network.output_size < len(ACTION_LABELS):
428
  raise ValueError("Action models must have at least four output values.")
429
  metrics = _action_policy_metrics(network, _action_policy_validation_examples())
 
 
 
430
  metrics["policy_trained"] = bool(model["network"].get("policyTrained", False))
431
  return metrics
432
 
@@ -1543,13 +1556,18 @@ if __name__ == "__main__":
1543
  output_path = arguments.output or "noe-action-model.dodl"
1544
 
1545
  def report_action_metrics(epoch, metrics):
 
 
 
 
1546
  print(
1547
  f"epoch {epoch}: validation_accuracy={metrics['accuracy']:.3f} "
1548
  f"baseline_accuracy={metrics['baseline_accuracy']:.3f} "
1549
- f"validation_mse={metrics['mse']:.6f}"
 
1550
  )
1551
 
1552
- train_action_model(
1553
  output_path,
1554
  sample_count=arguments.samples,
1555
  epochs=arguments.epochs,
@@ -1557,6 +1575,15 @@ if __name__ == "__main__":
1557
  patience=arguments.patience,
1558
  metrics_callback=report_action_metrics,
1559
  )
 
 
 
 
 
 
 
 
 
1560
  print(f"Action model trained: {output_path}")
1561
  gguf_output_path = os.path.splitext(output_path)[0] + ".F32.gguf"
1562
  print(f"GGUF model file created: {gguf_output_path}")
 
376
  ]
377
 
378
 
379
+ def _action_policy_held_out_examples():
380
+ return [
381
+ _action_policy_example(energy, curiosity, confidence)
382
+ for energy in (5, 15, 35, 65, 90)
383
+ for curiosity in (10, 65, 75, 90)
384
+ for confidence in (10, 35, 45, 75, 95)
385
+ ]
386
+
387
+
388
  def _action_policy_metrics(network, examples):
389
  correct = 0
390
  squared_error = 0.0
 
412
  else 0.0
413
  for label in ACTION_LABELS
414
  },
415
+ "per_action_support": class_totals,
416
  }
417
 
418
 
 
430
 
431
 
432
  def evaluate_action_model(model):
433
+ """Score a model on validation and separate held-out policy scenarios."""
434
  if not isinstance(model, dict):
435
  model = load_model_file(model)
436
  network = _network_from_model(model)
437
  if network.output_size < len(ACTION_LABELS):
438
  raise ValueError("Action models must have at least four output values.")
439
  metrics = _action_policy_metrics(network, _action_policy_validation_examples())
440
+ metrics["held_out"] = _action_policy_metrics(
441
+ network, _action_policy_held_out_examples()
442
+ )
443
  metrics["policy_trained"] = bool(model["network"].get("policyTrained", False))
444
  return metrics
445
 
 
1556
  output_path = arguments.output or "noe-action-model.dodl"
1557
 
1558
  def report_action_metrics(epoch, metrics):
1559
+ action_accuracy = " ".join(
1560
+ f"{label}={accuracy:.3f}"
1561
+ for label, accuracy in metrics["per_action_accuracy"].items()
1562
+ )
1563
  print(
1564
  f"epoch {epoch}: validation_accuracy={metrics['accuracy']:.3f} "
1565
  f"baseline_accuracy={metrics['baseline_accuracy']:.3f} "
1566
+ f"validation_mse={metrics['mse']:.6f} "
1567
+ f"per_action_accuracy[{action_accuracy}]"
1568
  )
1569
 
1570
+ model = train_action_model(
1571
  output_path,
1572
  sample_count=arguments.samples,
1573
  epochs=arguments.epochs,
 
1575
  patience=arguments.patience,
1576
  metrics_callback=report_action_metrics,
1577
  )
1578
+ held_out_metrics = evaluate_action_model(model)["held_out"]
1579
+ held_out_accuracy = " ".join(
1580
+ f"{label}={accuracy:.3f}"
1581
+ for label, accuracy in held_out_metrics["per_action_accuracy"].items()
1582
+ )
1583
+ print(
1584
+ f"held_out_accuracy={held_out_metrics['accuracy']:.3f} "
1585
+ f"per_action_accuracy[{held_out_accuracy}]"
1586
+ )
1587
  print(f"Action model trained: {output_path}")
1588
  gguf_output_path = os.path.splitext(output_path)[0] + ".F32.gguf"
1589
  print(f"GGUF model file created: {gguf_output_path}")
model_providers.py CHANGED
@@ -190,6 +190,8 @@ class BiocomputationProvider:
190
  class LLMProvider:
191
  """Standard-library adapters for OpenAI-compatible APIs and Gemini."""
192
 
 
 
193
  def __init__(self, provider=None, api_key=None, model=None, timeout=30, base_url=None):
194
  self.provider = (provider or os.environ.get("NOESIS_PROVIDER", "openai")).lower()
195
  if self.provider not in ("openai", "gemini", "openai-compatible"):
@@ -215,6 +217,14 @@ class LLMProvider:
215
  "openai-compatible": "NOESIS_MODEL",
216
  }[self.provider]
217
  self.model = model or os.environ.get(provider_model_variable) or default_model
 
 
 
 
 
 
 
 
218
  self.timeout = timeout
219
  self.base_url = (
220
  base_url
@@ -281,22 +291,63 @@ class LLMProvider:
281
  return self._extract_text(response)
282
 
283
  def _post_json(self, url, payload, headers):
 
 
 
 
 
 
 
 
 
 
 
284
  request = urllib.request.Request(
285
  url,
286
- data=json.dumps(payload).encode("utf-8"),
287
  headers={"Content-Type": "application/json", **headers},
288
  method="POST",
289
  )
290
  try:
291
  with urllib.request.urlopen(request, timeout=self.timeout) as response:
292
- return json.loads(response.read().decode("utf-8"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293
  except urllib.error.HTTPError as error:
294
  raise LLMProviderError(
295
  f"{self.provider} API request failed with HTTP {error.code}."
296
  ) from error
297
- except (urllib.error.URLError, TimeoutError) as error:
298
- raise LLMProviderError(f"{self.provider} API request failed: {error}.") from error
299
- except (UnicodeDecodeError, json.JSONDecodeError) as error:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300
  raise LLMProviderError(f"{self.provider} API returned invalid JSON.") from error
301
 
302
  def _extract_text(self, response):
 
190
  class LLMProvider:
191
  """Standard-library adapters for OpenAI-compatible APIs and Gemini."""
192
 
193
+ MAX_PAYLOAD_SIZE = 1024 * 1024
194
+
195
  def __init__(self, provider=None, api_key=None, model=None, timeout=30, base_url=None):
196
  self.provider = (provider or os.environ.get("NOESIS_PROVIDER", "openai")).lower()
197
  if self.provider not in ("openai", "gemini", "openai-compatible"):
 
217
  "openai-compatible": "NOESIS_MODEL",
218
  }[self.provider]
219
  self.model = model or os.environ.get(provider_model_variable) or default_model
220
+ if isinstance(timeout, bool) or not isinstance(timeout, (int, float)):
221
+ raise ValueError("LLM timeout must be a positive finite number.")
222
+ try:
223
+ timeout = float(timeout)
224
+ except (OverflowError, ValueError) as error:
225
+ raise ValueError("LLM timeout must be a positive finite number.") from error
226
+ if not math.isfinite(timeout) or timeout <= 0:
227
+ raise ValueError("LLM timeout must be a positive finite number.")
228
  self.timeout = timeout
229
  self.base_url = (
230
  base_url
 
291
  return self._extract_text(response)
292
 
293
  def _post_json(self, url, payload, headers):
294
+ try:
295
+ request_data = json.dumps(
296
+ payload,
297
+ ensure_ascii=False,
298
+ separators=(",", ":"),
299
+ allow_nan=False,
300
+ ).encode("utf-8")
301
+ except (TypeError, ValueError) as error:
302
+ raise LLMProviderError("LLM request payload must contain finite JSON values.") from error
303
+ if len(request_data) > self.MAX_PAYLOAD_SIZE:
304
+ raise LLMProviderError("LLM request payload exceeds the 1 MiB limit.")
305
  request = urllib.request.Request(
306
  url,
307
+ data=request_data,
308
  headers={"Content-Type": "application/json", **headers},
309
  method="POST",
310
  )
311
  try:
312
  with urllib.request.urlopen(request, timeout=self.timeout) as response:
313
+ response_headers = getattr(response, "headers", None)
314
+ content_type = (
315
+ response_headers.get("Content-Type")
316
+ if response_headers is not None
317
+ else None
318
+ )
319
+ if content_type is not None:
320
+ media_type = content_type.split(";", 1)[0].strip().lower()
321
+ if media_type != "application/json" and not media_type.endswith(
322
+ "+json"
323
+ ):
324
+ raise LLMProviderError(
325
+ "LLM API response must use a JSON content type."
326
+ )
327
+ response_data = response.read(self.MAX_PAYLOAD_SIZE + 1)
328
  except urllib.error.HTTPError as error:
329
  raise LLMProviderError(
330
  f"{self.provider} API request failed with HTTP {error.code}."
331
  ) from error
332
+ except LLMProviderError:
333
+ raise
334
+ except (
335
+ urllib.error.URLError,
336
+ TimeoutError,
337
+ OSError,
338
+ http.client.HTTPException,
339
+ ValueError,
340
+ ) as error:
341
+ raise LLMProviderError(
342
+ f"{self.provider} API request failed ({type(error).__name__})."
343
+ ) from error
344
+ if len(response_data) > self.MAX_PAYLOAD_SIZE:
345
+ raise LLMProviderError("LLM API response exceeds the 1 MiB limit.")
346
+ try:
347
+ return json.loads(
348
+ response_data.decode("utf-8"), parse_constant=_reject_json_constant
349
+ )
350
+ except (UnicodeDecodeError, ValueError) as error:
351
  raise LLMProviderError(f"{self.provider} API returned invalid JSON.") from error
352
 
353
  def _extract_text(self, response):
noe-model.F32.gguf CHANGED
Binary files a/noe-model.F32.gguf and b/noe-model.F32.gguf differ
 
noe-model.dodl CHANGED
Binary files a/noe-model.dodl and b/noe-model.dodl differ
 
noe-pixel-model.F32.gguf CHANGED
Binary files a/noe-pixel-model.F32.gguf and b/noe-pixel-model.F32.gguf differ
 
noe-pixel-model.dodl CHANGED
Binary files a/noe-pixel-model.dodl and b/noe-pixel-model.dodl differ
 
pixel_model.mjs ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const maxModelSize = 1024 * 1024;
2
+ const maxPixelHiddenSize = 128;
3
+
4
+ function readFloatArray(view, offset, length) {
5
+ const values = new Float32Array(length);
6
+ for (let index = 0; index < length; index++) {
7
+ values[index] = view.getFloat32(offset + index * 4, true);
8
+ if (!Number.isFinite(values[index])) {
9
+ throw new Error("DODL model contains a non-finite value.");
10
+ }
11
+ }
12
+ return values;
13
+ }
14
+
15
+ export function parsePixelModel(buffer) {
16
+ if (buffer.byteLength > maxModelSize) {
17
+ throw new Error("DODL model exceeds the 1 MiB size limit.");
18
+ }
19
+ const bytes = new Uint8Array(buffer);
20
+ if (bytes.byteLength < 16 || String.fromCharCode(...bytes.subarray(0, 4)) !== "DODL") {
21
+ throw new Error("Invalid DODL model header.");
22
+ }
23
+
24
+ const view = new DataView(buffer);
25
+ const formatVersion = view.getUint16(4, true);
26
+ const metadataSize = view.getUint32(8, true);
27
+ const networkSize = view.getUint32(12, true);
28
+ if (formatVersion !== 2 || 16 + metadataSize + networkSize !== buffer.byteLength) {
29
+ throw new Error("Unsupported or corrupt DODL model.");
30
+ }
31
+
32
+ const metadata = JSON.parse(
33
+ new TextDecoder().decode(new Uint8Array(buffer, 16, metadataSize)),
34
+ );
35
+ const { inputSize, hiddenSize, outputSize } = metadata.networkShape;
36
+ if (
37
+ inputSize !== 8 ||
38
+ !Number.isSafeInteger(hiddenSize) ||
39
+ hiddenSize < 1 ||
40
+ hiddenSize > maxPixelHiddenSize ||
41
+ outputSize !== 2
42
+ ) {
43
+ throw new Error("Expected a pixel model with 8 inputs, 2 outputs, and at most 128 hidden units.");
44
+ }
45
+ const lengths = [inputSize * hiddenSize, hiddenSize, hiddenSize * outputSize, outputSize];
46
+ if (networkSize !== lengths.reduce((total, length) => total + length * 4, 0)) {
47
+ throw new Error("DODL network dimensions do not match its data.");
48
+ }
49
+
50
+ let offset = 16 + metadataSize;
51
+ const arrays = lengths.map((length) => {
52
+ const values = readFloatArray(view, offset, length);
53
+ offset += length * 4;
54
+ return values;
55
+ });
56
+ return {
57
+ inputSize,
58
+ hiddenSize,
59
+ outputSize,
60
+ weights1: arrays[0],
61
+ bias1: arrays[1],
62
+ weights2: arrays[2],
63
+ bias2: arrays[3],
64
+ hiddenScratch: new Float32Array(hiddenSize),
65
+ outputScratch: new Float32Array(outputSize),
66
+ };
67
+ }
68
+
69
+ export async function loadPixelModel(url = "./noe-pixel-model.dodl") {
70
+ const response = await fetch(url, { cache: "no-cache" });
71
+ if (!response.ok) {
72
+ throw new Error(`Model request failed: ${response.status}`);
73
+ }
74
+ return parsePixelModel(await response.arrayBuffer());
75
+ }
76
+
77
+ export function runPixelModel(model, inputs) {
78
+ const hidden = model.hiddenScratch;
79
+ const outputs = model.outputScratch;
80
+ for (let hiddenIndex = 0; hiddenIndex < model.hiddenSize; hiddenIndex++) {
81
+ let total = model.bias1[hiddenIndex];
82
+ const start = hiddenIndex * model.inputSize;
83
+ for (let inputIndex = 0; inputIndex < model.inputSize; inputIndex++) {
84
+ total += inputs[inputIndex] * model.weights1[start + inputIndex];
85
+ }
86
+ hidden[hiddenIndex] = Math.max(0, total);
87
+ }
88
+ for (let outputIndex = 0; outputIndex < model.outputSize; outputIndex++) {
89
+ let total = model.bias2[outputIndex];
90
+ const start = outputIndex * model.hiddenSize;
91
+ for (let hiddenIndex = 0; hiddenIndex < model.hiddenSize; hiddenIndex++) {
92
+ total += hidden[hiddenIndex] * model.weights2[start + hiddenIndex];
93
+ }
94
+ outputs[outputIndex] = total;
95
+ }
96
+ return outputs;
97
+ }