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

Upload folder using huggingface_hub

Browse files
README.md CHANGED
@@ -12,6 +12,7 @@ tags:
12
  ## Files in this folder
13
 
14
  - `me.py` implements the Python model, training commands, and DODL/GGUF file support.
 
15
  - `model_providers.py` connects to OpenAI, Gemini, OpenAI-compatible APIs, and remote biocomputation services.
16
  - `index.html` and `me.js` run the browser-based pixel demo. This demo uses its own steering model; it is separate from the Python agent.
17
  - `noe-model.dodl` and `noe-model.F32.gguf` are the default Python model files. The `noe-pixel-model` files belong to the pixel demo.
@@ -57,6 +58,8 @@ python3 me.py --train-actions --seed 123
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
 
62
  The browser demo has a separate network that steers a pixel using its position, velocity, pointer position, and excitement level. Train it with:
@@ -171,6 +174,8 @@ You can pass DODL models or supported model paths. ONNX loading requires `pip in
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.
173
 
 
 
174
  ## License and contributing
175
 
176
  Noesis is released under the [MIT License](LICENSE). Some components include their own license files.
 
12
  ## Files in this folder
13
 
14
  - `me.py` implements the Python model, training commands, and DODL/GGUF file support.
15
+ - `model_config.py` holds shared model and file-format limits; `model_formats.py` validates, serializes, and deserializes model data.
16
  - `model_providers.py` connects to OpenAI, Gemini, OpenAI-compatible APIs, and remote biocomputation services.
17
  - `index.html` and `me.js` run the browser-based pixel demo. This demo uses its own steering model; it is separate from the Python agent.
18
  - `noe-model.dodl` and `noe-model.F32.gguf` are the default Python model files. The `noe-pixel-model` files belong to the pixel demo.
 
58
 
59
  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.
60
 
61
+ Evaluation reports both a majority-class baseline and `rule_baseline_accuracy`. The generated labels are defined by the same threshold policy used by the rule baseline, so a perfect rule-baseline score is expected; compare against real task scenarios before preferring the neural policy.
62
+
63
  ### Pixel controller
64
 
65
  The browser demo has a separate network that steers a pixel using its position, velocity, pointer position, and excitement level. Train it with:
 
174
  - `LLMProvider(...)` configures a text-generation service; `AIEngine.respond(...)` requests a reply and runs one local cycle.
175
  - `BiocomputationProvider(...)` configures a remote service; `AIEngine.compute_biological(...)` submits a task without changing model state.
176
 
177
+ Model validation checks network tensors and runtime metadata used by the engine. Serialization does not mutate its input; `AIEngine.export_model()` synchronizes live state and the update timestamp before serializing.
178
+
179
  ## License and contributing
180
 
181
  Noesis is released under the [MIT License](LICENSE). Some components include their own license files.
me.py CHANGED
@@ -4,16 +4,27 @@
4
 
5
  from array import array
6
  import argparse
7
- import base64
8
  import copy
9
  import json
10
  import math
11
  import os
12
  import secrets
13
  import struct
 
14
  import time
15
 
16
  if __package__:
 
 
 
 
 
 
 
 
 
 
 
17
  from .model_providers import (
18
  BiocomputationProvider,
19
  BiocomputationProviderError,
@@ -22,6 +33,17 @@ if __package__:
22
  normalize_provider_response,
23
  )
24
  else:
 
 
 
 
 
 
 
 
 
 
 
25
  from model_providers import (
26
  BiocomputationProvider,
27
  BiocomputationProviderError,
@@ -31,25 +53,6 @@ else:
31
  )
32
 
33
 
34
- CONFIG = {
35
- "VERSION": 2,
36
- "MAX_FILE_SIZE": 1024 * 1024,
37
- "TARGET_FILE_SIZE": 950 * 1024,
38
- "INPUT_SIZE": 16,
39
- "HIDDEN_SIZE": 32,
40
- "OUTPUT_SIZE": 8,
41
- "MEMORY_LIMIT": 200,
42
- "RULE_LIMIT": 64,
43
- "BEHAVIOR_LIMIT": 128,
44
- "LEARNING_RATE": 0.02,
45
- "MIN_WEIGHT": -5,
46
- "MAX_WEIGHT": 5,
47
- "STATE_MIN": 0,
48
- "STATE_MAX": 100,
49
- }
50
-
51
- MAGIC = b"DODL"
52
- HEADER_SIZE = 16
53
  PIXEL_INPUT_SIZE = 8
54
  PIXEL_OUTPUT_SIZE = 2
55
  ACTION_LABELS = ("rest", "explore", "learn", "observe")
@@ -387,6 +390,7 @@ def _action_policy_held_out_examples():
387
 
388
  def _action_policy_metrics(network, examples):
389
  correct = 0
 
390
  squared_error = 0.0
391
  class_totals = {label: 0 for label in ACTION_LABELS}
392
  class_correct = {label: 0 for label in ACTION_LABELS}
@@ -394,9 +398,14 @@ def _action_policy_metrics(network, examples):
394
  target_index = ACTION_LABELS.index(target)
395
  outputs = network.forward(inputs)["output"]
396
  prediction = ACTION_LABELS[max(range(len(ACTION_LABELS)), key=lambda index: outputs[index])]
 
 
 
397
  if prediction == target:
398
  correct += 1
399
  class_correct[target] += 1
 
 
400
  class_totals[target] += 1
401
  for index, output in enumerate(outputs[: len(ACTION_LABELS)]):
402
  expected = 1.0 if index == target_index else 0.0
@@ -405,6 +414,7 @@ def _action_policy_metrics(network, examples):
405
  return {
406
  "accuracy": correct / sample_count,
407
  "baseline_accuracy": sum(class_totals[label] for label in ACTION_LABELS if label == "observe") / sample_count,
 
408
  "mse": squared_error / (sample_count * len(ACTION_LABELS)),
409
  "per_action_accuracy": {
410
  label: class_correct[label] / class_totals[label]
@@ -527,10 +537,11 @@ def train_action_model(
527
  "bias2": network.bias2,
528
  "policyTrained": True,
529
  }
530
- with open(path, "wb") as model_file:
531
- model_file.write(serialize_model(model))
532
  gguf_path = os.path.splitext(os.fsdecode(path))[0] + ".F32.gguf"
533
- create_gguf_model_file(gguf_path, model)
 
 
534
  return model
535
 
536
 
@@ -603,10 +614,11 @@ def train_pixel_model(
603
  "weights2": network.weights2,
604
  "bias2": network.bias2,
605
  }
606
- with open(path, "wb") as model_file:
607
- model_file.write(serialize_model(model))
608
  gguf_path = os.path.splitext(os.fsdecode(path))[0] + ".F32.gguf"
609
- create_gguf_model_file(gguf_path, model)
 
 
610
  return model
611
 
612
 
@@ -885,6 +897,8 @@ def merge_models(model_a, model_b, alpha=0.5):
885
  model_a = load_model_file(model_a)
886
  if not isinstance(model_b, dict):
887
  model_b = load_model_file(model_b)
 
 
888
  if isinstance(alpha, bool) or not isinstance(alpha, (int, float)) or not math.isfinite(alpha):
889
  raise ValueError("alpha must be a finite number between 0 and 1.")
890
  if not 0 <= alpha <= 1:
@@ -958,230 +972,42 @@ def merge_models(model_a, model_b, alpha=0.5):
958
  return merged
959
 
960
 
961
- def validate_model(model):
962
- if not isinstance(model, dict):
963
- raise ValueError("Model must be an object.")
964
- for key, limit in (
965
- ("memory", CONFIG["MEMORY_LIMIT"]),
966
- ("rules", CONFIG["RULE_LIMIT"]),
967
- ("behavior", CONFIG["BEHAVIOR_LIMIT"]),
968
- ):
969
- values = model.get(key)
970
- if not isinstance(values, list):
971
- raise ValueError(f"Model {key} must be a list.")
972
- if len(values) > limit:
973
- raise ValueError(f"{key.capitalize()} limit exceeded.")
974
-
975
- network = model.get("network")
976
- if not isinstance(network, dict):
977
- raise ValueError("Model network must be an object.")
978
- shape = tuple(network.get(key) for key in ("inputSize", "hiddenSize", "outputSize"))
979
- if any(not isinstance(size, int) or isinstance(size, bool) or size <= 0 for size in shape):
980
- raise ValueError("Invalid network shape.")
981
- input_size, hidden_size, output_size = shape
982
- if "policyTrained" in network and not isinstance(network["policyTrained"], bool):
983
- raise ValueError("Model network policyTrained must be a boolean.")
984
- expected_lengths = {
985
- "weights1": input_size * hidden_size,
986
- "bias1": hidden_size,
987
- "weights2": hidden_size * output_size,
988
- "bias2": output_size,
989
- }
990
- for key, expected_length in expected_lengths.items():
991
- values = network.get(key)
992
- if not isinstance(values, (array, list, tuple)) or len(values) != expected_length:
993
- raise ValueError(f"Model has invalid {key} array length.")
994
- for value in values:
995
  try:
996
- is_finite = math.isfinite(value)
997
- except (OverflowError, TypeError, ValueError) as error:
998
- raise ValueError(f"Model {key} values must be finite numbers.") from error
999
- if not is_finite:
1000
- raise ValueError(f"Model {key} values must be finite numbers.")
1001
- return True
1002
-
1003
-
1004
- def _float_array_bytes(values):
1005
- return struct.pack(f"<{len(values)}f", *values)
1006
-
1007
-
1008
- def serialize_model(model):
1009
- validate_model(model)
1010
- model["updatedAt"] = now()
1011
- network = model["network"]
1012
- metadata = {
1013
- "version": model["version"],
1014
- "id": list(model["id"]),
1015
- "createdAt": model["createdAt"],
1016
- "updatedAt": model["updatedAt"],
1017
- "randomSeed": model["randomSeed"],
1018
- "memory": model["memory"],
1019
- "rules": model["rules"],
1020
- "behavior": model["behavior"],
1021
- "state": model["state"],
1022
- "goals": model["goals"],
1023
- "networkShape": {
1024
- "inputSize": network["inputSize"],
1025
- "hiddenSize": network["hiddenSize"],
1026
- "outputSize": network["outputSize"],
1027
- },
1028
- "policyTrained": bool(network.get("policyTrained", False)),
1029
- }
1030
- metadata_bytes = json.dumps(metadata, separators=(",", ":"), allow_nan=False).encode("utf-8")
1031
- network_bytes = b"".join(
1032
- _float_array_bytes(network[key]) for key in ("weights1", "bias1", "weights2", "bias2")
1033
- )
1034
- total_size = HEADER_SIZE + len(metadata_bytes) + len(network_bytes)
1035
- if total_size > CONFIG["MAX_FILE_SIZE"]:
1036
- raise ValueError(f"Model exceeds 1 MB: {total_size} bytes")
1037
- header = MAGIC + struct.pack("<HHII", CONFIG["VERSION"], 0, len(metadata_bytes), len(network_bytes))
1038
- return header + metadata_bytes + network_bytes
1039
-
1040
-
1041
- def _gguf_string(value):
1042
- encoded = value.encode("utf-8")
1043
- return struct.pack("<Q", len(encoded)) + encoded
1044
-
1045
-
1046
- def serialize_gguf_model(model):
1047
- network = model["network"]
1048
- tensors = (
1049
- ("network.weights1", (network["inputSize"], network["hiddenSize"]), network["weights1"]),
1050
- ("network.bias1", (network["hiddenSize"],), network["bias1"]),
1051
- ("network.weights2", (network["hiddenSize"], network["outputSize"]), network["weights2"]),
1052
- ("network.bias2", (network["outputSize"],), network["bias2"]),
1053
- )
1054
- metadata = (
1055
- ("general.architecture", 8, "noesis"),
1056
- ("general.name", 8, "Noesis Tiny Network"),
1057
- ("general.alignment", 4, 32),
1058
- ("noesis.input_size", 4, network["inputSize"]),
1059
- ("noesis.hidden_size", 4, network["hiddenSize"]),
1060
- ("noesis.output_size", 4, network["outputSize"]),
1061
- ("noesis.workspace_version", 4, 1),
1062
- ("noesis.workspace_format", 8, "cycle_snapshot"),
1063
- )
1064
- metadata_bytes = bytearray()
1065
- for key, value_type, value in metadata:
1066
- metadata_bytes.extend(_gguf_string(key))
1067
- metadata_bytes.extend(struct.pack("<I", value_type))
1068
- metadata_bytes.extend(_gguf_string(value) if value_type == 8 else struct.pack("<I", value))
1069
-
1070
- tensor_data = bytearray()
1071
- tensor_descriptors = bytearray()
1072
- for name, dimensions, values in tensors:
1073
- tensor_data.extend(b"\0" * ((-len(tensor_data)) % 32))
1074
- offset = len(tensor_data)
1075
- tensor_data.extend(_float_array_bytes(values))
1076
- tensor_descriptors.extend(_gguf_string(name))
1077
- tensor_descriptors.extend(struct.pack("<I", len(dimensions)))
1078
- tensor_descriptors.extend(struct.pack(f"<{len(dimensions)}Q", *dimensions))
1079
- tensor_descriptors.extend(struct.pack("<IQ", 0, offset))
1080
-
1081
- header = b"GGUF" + struct.pack("<IQQ", 3, len(tensors), len(metadata))
1082
- content = header + metadata_bytes + tensor_descriptors
1083
- content += b"\0" * ((-len(content)) % 32)
1084
- return content + tensor_data
1085
 
1086
 
1087
  def create_model_file(path):
1088
  model = create_model()
1089
- with open(path, "wb") as model_file:
1090
- model_file.write(serialize_model(model))
1091
  return model
1092
 
1093
 
1094
  def create_gguf_model_file(path, model):
1095
- with open(path, "wb") as model_file:
1096
- model_file.write(serialize_gguf_model(model))
1097
-
1098
-
1099
- def deserialize_model(buffer):
1100
- buffer = bytes(buffer)
1101
- if len(buffer) < HEADER_SIZE or len(buffer) > CONFIG["MAX_FILE_SIZE"] or buffer[:4] != MAGIC:
1102
- raise ValueError("Invalid DODL model file.")
1103
- version, _, metadata_size, network_size = struct.unpack_from("<HHII", buffer, 4)
1104
- if version != CONFIG["VERSION"]:
1105
- raise ValueError("Unsupported model version.")
1106
- if HEADER_SIZE + metadata_size + network_size != len(buffer):
1107
- raise ValueError("Corrupt model size.")
1108
- metadata_start = HEADER_SIZE
1109
- try:
1110
- metadata = json.loads(buffer[metadata_start : metadata_start + metadata_size].decode("utf-8"))
1111
- if not isinstance(metadata, dict) or metadata.get("version") != version:
1112
- raise ValueError("Invalid model metadata.")
1113
- shape = metadata["networkShape"]
1114
- input_size = shape["inputSize"]
1115
- hidden_size = shape["hiddenSize"]
1116
- output_size = shape["outputSize"]
1117
- except (UnicodeDecodeError, json.JSONDecodeError, KeyError, TypeError) as error:
1118
- raise ValueError("Invalid DODL model metadata.") from error
1119
- if any(
1120
- not isinstance(size, int) or isinstance(size, bool) or size <= 0
1121
- for size in (input_size, hidden_size, output_size)
1122
- ):
1123
- raise ValueError("Invalid network shape.")
1124
- lengths = (
1125
- input_size * hidden_size,
1126
- hidden_size,
1127
- hidden_size * output_size,
1128
- output_size,
1129
- )
1130
- if network_size != sum(lengths) * 4:
1131
- raise ValueError("Corrupt model size.")
1132
- offset = metadata_start + metadata_size
1133
- arrays = []
1134
- for length in lengths:
1135
- values = array("f")
1136
- values.frombytes(buffer[offset : offset + length * 4])
1137
- if struct.pack("=I", 1) != struct.pack("<I", 1):
1138
- values.byteswap()
1139
- arrays.append(values)
1140
- offset += length * 4
1141
- model = {
1142
- "version": metadata["version"],
1143
- "id": bytearray(metadata["id"]),
1144
- "createdAt": metadata["createdAt"],
1145
- "updatedAt": metadata["updatedAt"],
1146
- "randomSeed": metadata["randomSeed"],
1147
- "network": {
1148
- "inputSize": input_size,
1149
- "hiddenSize": hidden_size,
1150
- "outputSize": output_size,
1151
- "weights1": arrays[0],
1152
- "bias1": arrays[1],
1153
- "weights2": arrays[2],
1154
- "bias2": arrays[3],
1155
- "policyTrained": metadata.get("policyTrained", False),
1156
- },
1157
- "memory": metadata["memory"],
1158
- "rules": metadata["rules"],
1159
- "behavior": metadata["behavior"],
1160
- "state": metadata["state"],
1161
- "goals": metadata["goals"],
1162
- }
1163
- validate_model(model)
1164
- return model
1165
-
1166
-
1167
- def load_stored_model(storage, key):
1168
- stored_model = storage.getItem(key) if hasattr(storage, "getItem") else storage.get(key)
1169
- if not stored_model:
1170
- return None
1171
- return deserialize_model(decode_model_from_storage(stored_model))
1172
-
1173
-
1174
- def save_stored_model(storage, key, model):
1175
- encoded = encode_model_for_storage(serialize_model(model))
1176
- if hasattr(storage, "setItem"):
1177
- storage.setItem(key, encoded)
1178
- else:
1179
- storage[key] = encoded
1180
 
1181
 
1182
  class AIEngine:
1183
  def __init__(self, model=None, provider=None):
1184
  self.model = model if model is not None else create_model()
 
1185
  self.provider = provider
1186
  self.random = Random(self.model["randomSeed"])
1187
  stored_network = self.model["network"]
 
4
 
5
  from array import array
6
  import argparse
 
7
  import copy
8
  import json
9
  import math
10
  import os
11
  import secrets
12
  import struct
13
+ import tempfile
14
  import time
15
 
16
  if __package__:
17
+ from .model_config import CONFIG, HEADER_SIZE, MAGIC
18
+ from .model_formats import (
19
+ decode_model_from_storage,
20
+ deserialize_model,
21
+ encode_model_for_storage,
22
+ load_stored_model,
23
+ save_stored_model,
24
+ serialize_gguf_model,
25
+ serialize_model,
26
+ validate_model,
27
+ )
28
  from .model_providers import (
29
  BiocomputationProvider,
30
  BiocomputationProviderError,
 
33
  normalize_provider_response,
34
  )
35
  else:
36
+ from model_config import CONFIG, HEADER_SIZE, MAGIC
37
+ from model_formats import (
38
+ decode_model_from_storage,
39
+ deserialize_model,
40
+ encode_model_for_storage,
41
+ load_stored_model,
42
+ save_stored_model,
43
+ serialize_gguf_model,
44
+ serialize_model,
45
+ validate_model,
46
+ )
47
  from model_providers import (
48
  BiocomputationProvider,
49
  BiocomputationProviderError,
 
53
  )
54
 
55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  PIXEL_INPUT_SIZE = 8
57
  PIXEL_OUTPUT_SIZE = 2
58
  ACTION_LABELS = ("rest", "explore", "learn", "observe")
 
390
 
391
  def _action_policy_metrics(network, examples):
392
  correct = 0
393
+ rule_baseline_correct = 0
394
  squared_error = 0.0
395
  class_totals = {label: 0 for label in ACTION_LABELS}
396
  class_correct = {label: 0 for label in ACTION_LABELS}
 
398
  target_index = ACTION_LABELS.index(target)
399
  outputs = network.forward(inputs)["output"]
400
  prediction = ACTION_LABELS[max(range(len(ACTION_LABELS)), key=lambda index: outputs[index])]
401
+ rule_prediction = _action_policy_target(
402
+ inputs[0] * 100, inputs[1] * 100, inputs[2] * 100
403
+ )
404
  if prediction == target:
405
  correct += 1
406
  class_correct[target] += 1
407
+ if rule_prediction == target:
408
+ rule_baseline_correct += 1
409
  class_totals[target] += 1
410
  for index, output in enumerate(outputs[: len(ACTION_LABELS)]):
411
  expected = 1.0 if index == target_index else 0.0
 
414
  return {
415
  "accuracy": correct / sample_count,
416
  "baseline_accuracy": sum(class_totals[label] for label in ACTION_LABELS if label == "observe") / sample_count,
417
+ "rule_baseline_accuracy": rule_baseline_correct / sample_count,
418
  "mse": squared_error / (sample_count * len(ACTION_LABELS)),
419
  "per_action_accuracy": {
420
  label: class_correct[label] / class_totals[label]
 
537
  "bias2": network.bias2,
538
  "policyTrained": True,
539
  }
540
+ model["updatedAt"] = now()
 
541
  gguf_path = os.path.splitext(os.fsdecode(path))[0] + ".F32.gguf"
542
+ _write_model_artifacts(
543
+ ((path, serialize_model(model)), (gguf_path, serialize_gguf_model(model)))
544
+ )
545
  return model
546
 
547
 
 
614
  "weights2": network.weights2,
615
  "bias2": network.bias2,
616
  }
617
+ model["updatedAt"] = now()
 
618
  gguf_path = os.path.splitext(os.fsdecode(path))[0] + ".F32.gguf"
619
+ _write_model_artifacts(
620
+ ((path, serialize_model(model)), (gguf_path, serialize_gguf_model(model)))
621
+ )
622
  return model
623
 
624
 
 
897
  model_a = load_model_file(model_a)
898
  if not isinstance(model_b, dict):
899
  model_b = load_model_file(model_b)
900
+ validate_model(model_a)
901
+ validate_model(model_b)
902
  if isinstance(alpha, bool) or not isinstance(alpha, (int, float)) or not math.isfinite(alpha):
903
  raise ValueError("alpha must be a finite number between 0 and 1.")
904
  if not 0 <= alpha <= 1:
 
972
  return merged
973
 
974
 
975
+ def _write_model_artifacts(artifacts):
976
+ staged = []
977
+ try:
978
+ for path, data in artifacts:
979
+ path = os.fsdecode(os.fspath(path))
980
+ directory = os.path.dirname(os.path.abspath(path))
981
+ prefix = f".{os.path.basename(path)}."
982
+ with tempfile.NamedTemporaryFile(
983
+ mode="wb", dir=directory, prefix=prefix, suffix=".tmp", delete=False
984
+ ) as temporary_file:
985
+ staged.append((temporary_file.name, path))
986
+ temporary_file.write(data)
987
+ for temporary_path, path in staged:
988
+ os.replace(temporary_path, path)
989
+ finally:
990
+ for temporary_path, _ in staged:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
991
  try:
992
+ os.unlink(temporary_path)
993
+ except FileNotFoundError:
994
+ pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
995
 
996
 
997
  def create_model_file(path):
998
  model = create_model()
999
+ _write_model_artifacts(((path, serialize_model(model)),))
 
1000
  return model
1001
 
1002
 
1003
  def create_gguf_model_file(path, model):
1004
+ _write_model_artifacts(((path, serialize_gguf_model(model)),))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1005
 
1006
 
1007
  class AIEngine:
1008
  def __init__(self, model=None, provider=None):
1009
  self.model = model if model is not None else create_model()
1010
+ validate_model(self.model)
1011
  self.provider = provider
1012
  self.random = Random(self.model["randomSeed"])
1013
  stored_network = self.model["network"]
model_config.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CONFIG = {
2
+ "VERSION": 2,
3
+ "MAX_FILE_SIZE": 1024 * 1024,
4
+ "TARGET_FILE_SIZE": 950 * 1024,
5
+ "INPUT_SIZE": 16,
6
+ "HIDDEN_SIZE": 32,
7
+ "OUTPUT_SIZE": 8,
8
+ "MEMORY_LIMIT": 200,
9
+ "RULE_LIMIT": 64,
10
+ "BEHAVIOR_LIMIT": 128,
11
+ "LEARNING_RATE": 0.02,
12
+ "MIN_WEIGHT": -5,
13
+ "MAX_WEIGHT": 5,
14
+ "STATE_MIN": 0,
15
+ "STATE_MAX": 100,
16
+ }
17
+
18
+ MAGIC = b"DODL"
19
+ HEADER_SIZE = 16
model_formats.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from array import array
2
+ import base64
3
+ import json
4
+ import math
5
+ import struct
6
+
7
+ if __package__:
8
+ from .model_config import CONFIG, HEADER_SIZE, MAGIC
9
+ else:
10
+ from model_config import CONFIG, HEADER_SIZE, MAGIC
11
+
12
+
13
+ def encode_model_for_storage(buffer):
14
+ return base64.b64encode(buffer).decode("ascii")
15
+
16
+
17
+ def decode_model_from_storage(encoded):
18
+ return base64.b64decode(encoded, validate=True)
19
+
20
+
21
+ def _reject_json_constant(value):
22
+ raise ValueError(f"Invalid JSON constant '{value}'.")
23
+
24
+
25
+ def _validate_json_value(value, path):
26
+ if value is None or isinstance(value, (bool, str, int)):
27
+ return
28
+ if isinstance(value, float):
29
+ if not math.isfinite(value):
30
+ raise ValueError(f"Model {path} values must be finite JSON values.")
31
+ return
32
+ if isinstance(value, list):
33
+ for index, item in enumerate(value):
34
+ _validate_json_value(item, f"{path}[{index}]")
35
+ return
36
+ if isinstance(value, dict):
37
+ for key, item in value.items():
38
+ if not isinstance(key, str):
39
+ raise ValueError(f"Model {path} object keys must be strings.")
40
+ _validate_json_value(item, f"{path}.{key}")
41
+ return
42
+ raise ValueError(f"Model {path} contains a non-JSON value.")
43
+
44
+
45
+ def _finite_number(value):
46
+ return (
47
+ isinstance(value, (int, float))
48
+ and not isinstance(value, bool)
49
+ and math.isfinite(value)
50
+ )
51
+
52
+
53
+ def validate_model(model):
54
+ if not isinstance(model, dict):
55
+ raise ValueError("Model must be an object.")
56
+ if model.get("version") != CONFIG["VERSION"]:
57
+ raise ValueError("Unsupported model version.")
58
+ model_id = model.get("id")
59
+ if not isinstance(model_id, (list, tuple, bytes, bytearray)) or len(model_id) != 16:
60
+ raise ValueError("Model id must contain 16 bytes.")
61
+ if any(not isinstance(value, int) or isinstance(value, bool) or not 0 <= value <= 255 for value in model_id):
62
+ raise ValueError("Model id must contain 16 bytes.")
63
+ for key in ("createdAt", "updatedAt", "randomSeed"):
64
+ value = model.get(key)
65
+ if not isinstance(value, int) or isinstance(value, bool):
66
+ raise ValueError(f"Model {key} must be an integer.")
67
+
68
+ for key, limit in (("memory", CONFIG["MEMORY_LIMIT"]), ("rules", CONFIG["RULE_LIMIT"])):
69
+ values = model.get(key)
70
+ if not isinstance(values, list):
71
+ raise ValueError(f"Model {key} must be a list.")
72
+ if len(values) > limit:
73
+ raise ValueError(f"{key.capitalize()} limit exceeded.")
74
+ for index, item in enumerate(values):
75
+ if not isinstance(item, dict):
76
+ raise ValueError(f"Model {key}[{index}] must be an object.")
77
+ _validate_json_value(item, f"{key}[{index}]")
78
+
79
+ behavior = model.get("behavior")
80
+ if not isinstance(behavior, list):
81
+ raise ValueError("Model behavior must be a list.")
82
+ if len(behavior) > CONFIG["BEHAVIOR_LIMIT"]:
83
+ raise ValueError("Behavior limit exceeded.")
84
+ _validate_json_value(behavior, "behavior")
85
+
86
+ for rule in model["rules"]:
87
+ condition = rule.get("condition")
88
+ action = rule.get("action")
89
+ if (
90
+ not isinstance(rule.get("id"), str)
91
+ or not isinstance(condition, dict)
92
+ or not isinstance(action, dict)
93
+ or not isinstance(action.get("type"), str)
94
+ or not action["type"]
95
+ or not isinstance(rule.get("enabled"), bool)
96
+ or not _finite_number(rule.get("priority"))
97
+ or any(
98
+ not isinstance(rule.get(key), int)
99
+ or isinstance(rule.get(key), bool)
100
+ or rule[key] < 0
101
+ for key in ("success", "failure")
102
+ )
103
+ ):
104
+ raise ValueError("Model rules contain an invalid rule.")
105
+ condition_type = condition.get("type")
106
+ if condition_type not in ("always", "less-than", "greater-than", "equals"):
107
+ raise ValueError("Model rules contain an unsupported condition.")
108
+ if condition_type != "always" and not isinstance(condition.get("variable"), str):
109
+ raise ValueError("Model rule conditions must name a variable.")
110
+ if condition_type in ("less-than", "greater-than") and not _finite_number(
111
+ condition.get("value")
112
+ ):
113
+ raise ValueError("Model rule threshold must be a finite number.")
114
+
115
+ behavior_ops = {"READ", "LESS_THAN", "GREATER_THAN", "IF", "ELSE", "ACTION", "END"}
116
+ for instruction in behavior:
117
+ if (
118
+ not isinstance(instruction, list)
119
+ or not instruction
120
+ or not isinstance(instruction[0], str)
121
+ or instruction[0] not in behavior_ops
122
+ ):
123
+ raise ValueError("Model behavior contains an invalid instruction.")
124
+ op = instruction[0]
125
+ if op in ("READ", "ACTION"):
126
+ if len(instruction) != 2 or not isinstance(instruction[1], str):
127
+ raise ValueError(f"Model behavior {op} requires a string operand.")
128
+ elif op in ("LESS_THAN", "GREATER_THAN"):
129
+ if len(instruction) != 2 or not _finite_number(instruction[1]):
130
+ raise ValueError(f"Model behavior {op} requires a numeric operand.")
131
+ elif len(instruction) != 1:
132
+ raise ValueError(f"Model behavior {op} does not accept an operand.")
133
+
134
+ goals = model.get("goals")
135
+ if not isinstance(goals, list):
136
+ raise ValueError("Model goals must be a list.")
137
+ _validate_json_value(goals, "goals")
138
+ for goal in goals:
139
+ if (
140
+ not isinstance(goal, dict)
141
+ or not isinstance(goal.get("id"), str)
142
+ or not _finite_number(goal.get("priority"))
143
+ or not isinstance(goal.get("target"), dict)
144
+ or any(not _finite_number(value) for value in goal["target"].values())
145
+ ):
146
+ raise ValueError("Model goals contain an invalid goal.")
147
+
148
+ state = model.get("state")
149
+ if not isinstance(state, dict):
150
+ raise ValueError("Model state must be an object.")
151
+ for key in ("energy", "curiosity", "confidence", "stability", "lastReward"):
152
+ if not _finite_number(state.get(key)):
153
+ raise ValueError(f"Model state field '{key}' must be a finite number.")
154
+ if not isinstance(state.get("cycle"), int) or isinstance(state.get("cycle"), bool):
155
+ raise ValueError("Model state cycle must be an integer.")
156
+ if state.get("lastAction") is not None and not isinstance(state.get("lastAction"), str):
157
+ raise ValueError("Model state lastAction must be a string or null.")
158
+ if "bioSignals" in state and not isinstance(state["bioSignals"], dict):
159
+ raise ValueError("Model state bioSignals must be an object.")
160
+ if "selfModel" in state and not isinstance(state["selfModel"], dict):
161
+ raise ValueError("Model state selfModel must be an object.")
162
+ if "workspace" in state and not isinstance(state["workspace"], dict):
163
+ raise ValueError("Model state workspace must be an object.")
164
+ _validate_json_value(state, "state")
165
+
166
+ network = model.get("network")
167
+ if not isinstance(network, dict):
168
+ raise ValueError("Model network must be an object.")
169
+ shape = tuple(network.get(key) for key in ("inputSize", "hiddenSize", "outputSize"))
170
+ if any(not isinstance(size, int) or isinstance(size, bool) or size <= 0 for size in shape):
171
+ raise ValueError("Invalid network shape.")
172
+ input_size, hidden_size, output_size = shape
173
+ if "policyTrained" in network and not isinstance(network["policyTrained"], bool):
174
+ raise ValueError("Model network policyTrained must be a boolean.")
175
+ expected_lengths = {
176
+ "weights1": input_size * hidden_size,
177
+ "bias1": hidden_size,
178
+ "weights2": hidden_size * output_size,
179
+ "bias2": output_size,
180
+ }
181
+ for key, expected_length in expected_lengths.items():
182
+ values = network.get(key)
183
+ if not isinstance(values, (array, list, tuple)) or len(values) != expected_length:
184
+ raise ValueError(f"Model has invalid {key} array lengths.")
185
+ for value in values:
186
+ if not _finite_number(value):
187
+ raise ValueError(f"Model {key} values must be finite numbers.")
188
+ return True
189
+
190
+
191
+ def _float_array_bytes(values):
192
+ return struct.pack(f"<{len(values)}f", *values)
193
+
194
+
195
+ def serialize_model(model):
196
+ validate_model(model)
197
+ network = model["network"]
198
+ metadata = {
199
+ "version": model["version"],
200
+ "id": list(model["id"]),
201
+ "createdAt": model["createdAt"],
202
+ "updatedAt": model["updatedAt"],
203
+ "randomSeed": model["randomSeed"],
204
+ "memory": model["memory"],
205
+ "rules": model["rules"],
206
+ "behavior": model["behavior"],
207
+ "state": model["state"],
208
+ "goals": model["goals"],
209
+ "networkShape": {
210
+ "inputSize": network["inputSize"],
211
+ "hiddenSize": network["hiddenSize"],
212
+ "outputSize": network["outputSize"],
213
+ },
214
+ "policyTrained": bool(network.get("policyTrained", False)),
215
+ }
216
+ metadata_bytes = json.dumps(metadata, separators=(",", ":"), allow_nan=False).encode("utf-8")
217
+ network_bytes = b"".join(
218
+ _float_array_bytes(network[key]) for key in ("weights1", "bias1", "weights2", "bias2")
219
+ )
220
+ total_size = HEADER_SIZE + len(metadata_bytes) + len(network_bytes)
221
+ if total_size > CONFIG["MAX_FILE_SIZE"]:
222
+ raise ValueError(f"Model exceeds 1 MB: {total_size} bytes")
223
+ header = MAGIC + struct.pack("<HHII", CONFIG["VERSION"], 0, len(metadata_bytes), len(network_bytes))
224
+ return header + metadata_bytes + network_bytes
225
+
226
+
227
+ def _gguf_string(value):
228
+ encoded = value.encode("utf-8")
229
+ return struct.pack("<Q", len(encoded)) + encoded
230
+
231
+
232
+ def serialize_gguf_model(model):
233
+ validate_model(model)
234
+ network = model["network"]
235
+ tensors = (
236
+ ("network.weights1", (network["inputSize"], network["hiddenSize"]), network["weights1"]),
237
+ ("network.bias1", (network["hiddenSize"],), network["bias1"]),
238
+ ("network.weights2", (network["hiddenSize"], network["outputSize"]), network["weights2"]),
239
+ ("network.bias2", (network["outputSize"],), network["bias2"]),
240
+ )
241
+ metadata = (
242
+ ("general.architecture", 8, "noesis"),
243
+ ("general.name", 8, "Noesis Tiny Network"),
244
+ ("general.alignment", 4, 32),
245
+ ("noesis.input_size", 4, network["inputSize"]),
246
+ ("noesis.hidden_size", 4, network["hiddenSize"]),
247
+ ("noesis.output_size", 4, network["outputSize"]),
248
+ ("noesis.workspace_version", 4, 1),
249
+ ("noesis.workspace_format", 8, "cycle_snapshot"),
250
+ )
251
+ metadata_bytes = bytearray()
252
+ for key, value_type, value in metadata:
253
+ metadata_bytes.extend(_gguf_string(key))
254
+ metadata_bytes.extend(struct.pack("<I", value_type))
255
+ metadata_bytes.extend(_gguf_string(value) if value_type == 8 else struct.pack("<I", value))
256
+
257
+ tensor_data = bytearray()
258
+ tensor_descriptors = bytearray()
259
+ for name, dimensions, values in tensors:
260
+ tensor_data.extend(b"\0" * ((-len(tensor_data)) % 32))
261
+ offset = len(tensor_data)
262
+ tensor_data.extend(_float_array_bytes(values))
263
+ tensor_descriptors.extend(_gguf_string(name))
264
+ tensor_descriptors.extend(struct.pack("<I", len(dimensions)))
265
+ tensor_descriptors.extend(struct.pack(f"<{len(dimensions)}Q", *dimensions))
266
+ tensor_descriptors.extend(struct.pack("<IQ", 0, offset))
267
+
268
+ header = b"GGUF" + struct.pack("<IQQ", 3, len(tensors), len(metadata))
269
+ content = header + metadata_bytes + tensor_descriptors
270
+ content += b"\0" * ((-len(content)) % 32)
271
+ return content + tensor_data
272
+
273
+
274
+ def deserialize_model(buffer):
275
+ buffer = bytes(buffer)
276
+ if len(buffer) < HEADER_SIZE or len(buffer) > CONFIG["MAX_FILE_SIZE"] or buffer[:4] != MAGIC:
277
+ raise ValueError("Invalid DODL model file.")
278
+ version, _, metadata_size, network_size = struct.unpack_from("<HHII", buffer, 4)
279
+ if version != CONFIG["VERSION"]:
280
+ raise ValueError("Unsupported model version.")
281
+ if HEADER_SIZE + metadata_size + network_size != len(buffer):
282
+ raise ValueError("Corrupt model size.")
283
+ metadata_start = HEADER_SIZE
284
+ try:
285
+ metadata = json.loads(
286
+ buffer[metadata_start : metadata_start + metadata_size].decode("utf-8"),
287
+ parse_constant=_reject_json_constant,
288
+ )
289
+ if not isinstance(metadata, dict) or metadata.get("version") != version:
290
+ raise ValueError("Invalid model metadata.")
291
+ shape = metadata["networkShape"]
292
+ input_size = shape["inputSize"]
293
+ hidden_size = shape["hiddenSize"]
294
+ output_size = shape["outputSize"]
295
+ except (UnicodeDecodeError, json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
296
+ raise ValueError("Invalid DODL model metadata.") from error
297
+ if any(
298
+ not isinstance(size, int) or isinstance(size, bool) or size <= 0
299
+ for size in (input_size, hidden_size, output_size)
300
+ ):
301
+ raise ValueError("Invalid network shape.")
302
+ lengths = (
303
+ input_size * hidden_size,
304
+ hidden_size,
305
+ hidden_size * output_size,
306
+ output_size,
307
+ )
308
+ if network_size != sum(lengths) * 4:
309
+ raise ValueError("Corrupt model size.")
310
+ offset = metadata_start + metadata_size
311
+ arrays = []
312
+ for length in lengths:
313
+ values = array("f")
314
+ values.frombytes(buffer[offset : offset + length * 4])
315
+ if struct.pack("=I", 1) != struct.pack("<I", 1):
316
+ values.byteswap()
317
+ arrays.append(values)
318
+ offset += length * 4
319
+ model = {
320
+ "version": metadata["version"],
321
+ "id": bytearray(metadata["id"]),
322
+ "createdAt": metadata["createdAt"],
323
+ "updatedAt": metadata["updatedAt"],
324
+ "randomSeed": metadata["randomSeed"],
325
+ "network": {
326
+ "inputSize": input_size,
327
+ "hiddenSize": hidden_size,
328
+ "outputSize": output_size,
329
+ "weights1": arrays[0],
330
+ "bias1": arrays[1],
331
+ "weights2": arrays[2],
332
+ "bias2": arrays[3],
333
+ "policyTrained": metadata.get("policyTrained", False),
334
+ },
335
+ "memory": metadata["memory"],
336
+ "rules": metadata["rules"],
337
+ "behavior": metadata["behavior"],
338
+ "state": metadata["state"],
339
+ "goals": metadata["goals"],
340
+ }
341
+ validate_model(model)
342
+ return model
343
+
344
+
345
+ def load_stored_model(storage, key):
346
+ stored_model = storage.getItem(key) if hasattr(storage, "getItem") else storage.get(key)
347
+ if not stored_model:
348
+ return None
349
+ return deserialize_model(decode_model_from_storage(stored_model))
350
+
351
+
352
+ def save_stored_model(storage, key, model):
353
+ encoded = encode_model_for_storage(serialize_model(model))
354
+ if hasattr(storage, "setItem"):
355
+ storage.setItem(key, encoded)
356
+ else:
357
+ storage[key] = encoded
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