dodle commited on
Commit
353c034
·
verified ·
1 Parent(s): c83aaf5

Upload folder using huggingface_hub

Browse files
README.md CHANGED
@@ -22,7 +22,7 @@ python3 me.py
22
  This writes `noe-model.dodl` and `noe-model.F32.gguf` in the current directory. Load the DODL file and run one model step like this:
23
 
24
  ```python
25
- from model.me import AIEngine, deserialize_model
26
 
27
  with open("noe-model.dodl", "rb") as model_file:
28
  model = deserialize_model(model_file.read())
@@ -64,7 +64,7 @@ The pixel demo also uses DODL, but has a network specialized for steering. It ta
64
  python3 me.py --train-pixel
65
  ```
66
 
67
- This writes `noe-pixel-model.dodl` and leaves `noe-model.dodl` untouched. Training uses a built-in steering policy that moves away from a nearby pointer and screen edges. Use `--samples` and `--epochs` to adjust training, `--seed` to make it repeatable, or `--output` to choose another path. The browser only runs the trained model; it does not train it.
68
 
69
  Serve `core/model/` over HTTP so the browser can load the model:
70
 
@@ -79,7 +79,7 @@ Open `http://localhost:8000/`. The page loads `me.js`, which fetches `noe-pixel-
79
  Load the saved model into `AIEngine`:
80
 
81
  ```python
82
- from model.me import AIEngine, deserialize_model
83
 
84
  with open("noe-model.dodl", "rb") as model_file:
85
  model = deserialize_model(model_file.read())
@@ -103,7 +103,7 @@ with open("noe-model.dodl", "wb") as model_file:
103
  Pass DODL model dictionaries or supported model-file paths, merge them, then serialize the result:
104
 
105
  ```python
106
- from model.me import merge_models, serialize_model
107
 
108
  merged = merge_models("model-a.dodl", "model-b.onnx", alpha=0.5)
109
  with open("merged-model.dodl", "wb") as model_file:
@@ -134,7 +134,7 @@ export NOESIS_MODEL=llama3.2
134
  `NOESIS_API_KEY` is optional for local servers and can be set when the endpoint requires a key. Pass `base_url` directly to `LLMProvider` to override the environment setting.
135
 
136
  ```python
137
- from model.me import AIEngine, LLMProvider
138
 
139
  with open("noe-model.dodl", "rb") as model_file:
140
  engine = AIEngine.import_model(model_file.read())
@@ -162,10 +162,10 @@ The provider sends a JSON `POST` request in this format:
162
  }
163
  ```
164
 
165
- The service must return JSON with the same `protocol` and a `result` field. It can also include `provider` and `run_id` to identify the service and run. Set `NOESIS_BIOCOMPUTE_URL` and, if needed, `NOESIS_BIOCOMPUTE_API_KEY`. Remote endpoints must use HTTPS; HTTP is allowed for localhost development. The API key is sent as a bearer token and is never saved in the model file.
166
 
167
  ```python
168
- from model.me import AIEngine, BiocomputationProvider
169
 
170
  engine = AIEngine()
171
  provider = BiocomputationProvider() # Reads the URL and optional API key from the environment
@@ -197,6 +197,8 @@ The file starts with the `DODL` magic signature and a versioned header. It store
197
  - `AIEngine.step(input_value)` observes input, chooses and executes an action, evaluates it, learns, updates state, and returns the cycle result.
198
  - `LLMProvider(provider=None)` configures an OpenAI, Gemini, or OpenAI-compatible text-generation adapter from environment variables.
199
  - `AIEngine.respond(input_value, provider=None)` generates a provider reply and runs one local engine step.
 
 
200
  - `AIEngine.export_model()` serializes the engine's current model.
201
 
202
  ## License
 
22
  This writes `noe-model.dodl` and `noe-model.F32.gguf` in the current directory. Load the DODL file and run one model step like this:
23
 
24
  ```python
25
+ from me import AIEngine, deserialize_model
26
 
27
  with open("noe-model.dodl", "rb") as model_file:
28
  model = deserialize_model(model_file.read())
 
64
  python3 me.py --train-pixel
65
  ```
66
 
67
+ This writes `noe-pixel-model.dodl` and leaves `noe-model.dodl` untouched. Training uses a built-in steering policy that moves away from a nearby pointer and screen edges. Each epoch is scored on separate synthetic validation examples; the command reports validation MSE and per-axis MAE, keeps the best weights, and stops after `--patience` epochs without improvement. Use `--samples`, `--epochs`, and `--patience` to adjust training, `--seed` to make it repeatable, or `--output` to choose another path. The browser only runs the trained model; it does not train it.
68
 
69
  Serve `core/model/` over HTTP so the browser can load the model:
70
 
 
79
  Load the saved model into `AIEngine`:
80
 
81
  ```python
82
+ from me import AIEngine, deserialize_model
83
 
84
  with open("noe-model.dodl", "rb") as model_file:
85
  model = deserialize_model(model_file.read())
 
103
  Pass DODL model dictionaries or supported model-file paths, merge them, then serialize the result:
104
 
105
  ```python
106
+ from me import merge_models, serialize_model
107
 
108
  merged = merge_models("model-a.dodl", "model-b.onnx", alpha=0.5)
109
  with open("merged-model.dodl", "wb") as model_file:
 
134
  `NOESIS_API_KEY` is optional for local servers and can be set when the endpoint requires a key. Pass `base_url` directly to `LLMProvider` to override the environment setting.
135
 
136
  ```python
137
+ from me import AIEngine, LLMProvider
138
 
139
  with open("noe-model.dodl", "rb") as model_file:
140
  engine = AIEngine.import_model(model_file.read())
 
162
  }
163
  ```
164
 
165
+ `operation` must be a non-empty string, and `inputs`, when provided, must be an object. The service must return JSON with the same `protocol` and a `result` field. It can also include string-valued `provider` and `run_id` fields to identify the service and run. Set `NOESIS_BIOCOMPUTE_URL` and, if needed, `NOESIS_BIOCOMPUTE_API_KEY`. Remote endpoints must use HTTPS; HTTP is allowed for localhost development. The API key is sent as a bearer token and is never saved in the model file.
166
 
167
  ```python
168
+ from me import AIEngine, BiocomputationProvider
169
 
170
  engine = AIEngine()
171
  provider = BiocomputationProvider() # Reads the URL and optional API key from the environment
 
197
  - `AIEngine.step(input_value)` observes input, chooses and executes an action, evaluates it, learns, updates state, and returns the cycle result.
198
  - `LLMProvider(provider=None)` configures an OpenAI, Gemini, or OpenAI-compatible text-generation adapter from environment variables.
199
  - `AIEngine.respond(input_value, provider=None)` generates a provider reply and runs one local engine step.
200
+ - `BiocomputationProvider(endpoint=None, api_key=None)` submits explicit tasks to a remote biocomputation service.
201
+ - `AIEngine.compute_biological(task, provider=None)` submits a task without changing model state.
202
  - `AIEngine.export_model()` serializes the engine's current model.
203
 
204
  ## License
me.py CHANGED
@@ -315,11 +315,40 @@ def _pixel_training_example(random):
315
  return inputs, targets
316
 
317
 
318
- def train_pixel_model(path="noe-pixel-model.dodl", sample_count=1200, epochs=12, seed=None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
319
  if not isinstance(sample_count, int) or sample_count < 1:
320
  raise ValueError("sample_count must be a positive integer.")
321
  if not isinstance(epochs, int) or epochs < 1:
322
  raise ValueError("epochs must be a positive integer.")
 
 
 
 
323
 
324
  random = Random(seed if seed is not None else random_int(1, 0xFFFFFFFF))
325
  model = create_model()
@@ -333,13 +362,35 @@ def train_pixel_model(path="noe-pixel-model.dodl", sample_count=1200, epochs=12,
333
  network.bias2 = array("f", [0]) * network.output_size
334
  network.initialize(random)
335
 
 
 
336
  examples = [_pixel_training_example(random) for _ in range(sample_count)]
337
- for _ in range(epochs):
 
 
 
338
  for index in range(sample_count - 1, 0, -1):
339
  swap_index = int(random.next() * (index + 1))
340
  examples[index], examples[swap_index] = examples[swap_index], examples[index]
341
  for inputs, targets in examples:
342
  network.learn(inputs, targets, 0.01)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
343
 
344
  model["randomSeed"] = random.seed
345
  model["network"] = {
@@ -950,6 +1001,11 @@ class BiocomputationProvider:
950
  def compute(self, task):
951
  if not isinstance(task, dict):
952
  raise ValueError("Biocomputation task must be a JSON object.")
 
 
 
 
 
953
  try:
954
  payload = json.dumps(
955
  {"protocol": self.PROTOCOL, "task": task},
@@ -995,6 +1051,11 @@ class BiocomputationProvider:
995
  raise BiocomputationProviderError(
996
  f"Biocomputation response must include protocol '{self.PROTOCOL}' and a result."
997
  )
 
 
 
 
 
998
  return result
999
 
1000
 
@@ -1041,8 +1102,9 @@ class LLMProvider:
1041
  return normalize_provider_response(text)
1042
 
1043
  def _generate(self, user_input, state, memories, structured):
 
1044
  context = json.dumps(
1045
- {"input": user_input, "state": state, "recent_memory": memories},
1046
  ensure_ascii=False,
1047
  separators=(",", ":"),
1048
  )
@@ -1212,8 +1274,10 @@ class AIEngine:
1212
  def observe(self, input_value):
1213
  return {"input": input_value, "timestamp": now(), "state": dict(self.state)}
1214
 
1215
- def interpret(self, perception):
1216
- return self.network.forward(self.encode_input(perception["input"]))
 
 
1217
 
1218
  def sense_bio_signals(self, input_value):
1219
  signals = self.state["bioSignals"]
@@ -1360,8 +1424,9 @@ class AIEngine:
1360
  reward += 0.5
1361
  return {"reward": reward, "perception": perception, "action": action, "result": result}
1362
 
1363
- def learn(self, evaluation):
1364
- input_vector = self.encode_input(evaluation["perception"]["input"])
 
1365
  target = array("f", [evaluation["reward"]]) * self.network.output_size
1366
  self.network.learn(input_vector, target, CONFIG["LEARNING_RATE"])
1367
  action = evaluation["action"]
@@ -1391,7 +1456,8 @@ class AIEngine:
1391
  def step(self, input_value, provider_analysis=None):
1392
  perception = self.observe(input_value)
1393
  self.sense_bio_signals(input_value)
1394
- interpretation = self.interpret(perception)
 
1395
  workspace = self.open_workspace(perception)
1396
  workspace["providerAnalysis"] = copy.deepcopy(provider_analysis)
1397
  workspace["internalState"]["bioSignals"] = copy.deepcopy(self.state["bioSignals"])
@@ -1416,7 +1482,7 @@ class AIEngine:
1416
  "bioSignals": copy.deepcopy(self.state["bioSignals"]),
1417
  }
1418
  evaluation = self.evaluate(perception, action, result)
1419
- self.learn(evaluation)
1420
  self.update_state(evaluation)
1421
  self.sync_model()
1422
  return {
@@ -1495,17 +1561,26 @@ if __name__ == "__main__":
1495
  )
1496
  parser.add_argument("--samples", type=int, default=1200)
1497
  parser.add_argument("--epochs", type=int, default=12)
 
1498
  parser.add_argument("--seed", type=int)
1499
  parser.add_argument("--output", default="noe-pixel-model.dodl")
1500
  arguments = parser.parse_args()
1501
 
1502
  output_path = "noe-model.dodl"
1503
  if arguments.train_pixel:
 
 
 
 
 
 
1504
  train_pixel_model(
1505
  arguments.output,
1506
  sample_count=arguments.samples,
1507
  epochs=arguments.epochs,
1508
  seed=arguments.seed,
 
 
1509
  )
1510
  gguf_output_path = os.path.splitext(arguments.output)[0] + ".F32.gguf"
1511
  print(f"Pixel control model trained: {arguments.output}")
 
315
  return inputs, targets
316
 
317
 
318
+ def _pixel_validation_metrics(network, examples):
319
+ squared_errors = [0.0] * network.output_size
320
+ absolute_errors = [0.0] * network.output_size
321
+ for inputs, targets in examples:
322
+ outputs = network.forward(inputs)["output"]
323
+ for index in range(network.output_size):
324
+ error = outputs[index] - targets[index]
325
+ squared_errors[index] += error * error
326
+ absolute_errors[index] += abs(error)
327
+ sample_count = len(examples)
328
+ mse = sum(squared_errors) / (sample_count * network.output_size)
329
+ return {
330
+ "mse": mse,
331
+ "mae_x": absolute_errors[0] / sample_count,
332
+ "mae_y": absolute_errors[1] / sample_count,
333
+ }
334
+
335
+
336
+ def train_pixel_model(
337
+ path="noe-pixel-model.dodl",
338
+ sample_count=1200,
339
+ epochs=12,
340
+ seed=None,
341
+ patience=4,
342
+ metrics_callback=None,
343
+ ):
344
  if not isinstance(sample_count, int) or sample_count < 1:
345
  raise ValueError("sample_count must be a positive integer.")
346
  if not isinstance(epochs, int) or epochs < 1:
347
  raise ValueError("epochs must be a positive integer.")
348
+ if not isinstance(patience, int) or patience < 1:
349
+ raise ValueError("patience must be a positive integer.")
350
+ if metrics_callback is not None and not callable(metrics_callback):
351
+ raise ValueError("metrics_callback must be callable.")
352
 
353
  random = Random(seed if seed is not None else random_int(1, 0xFFFFFFFF))
354
  model = create_model()
 
362
  network.bias2 = array("f", [0]) * network.output_size
363
  network.initialize(random)
364
 
365
+ validation_count = max(128, min(512, sample_count // 5))
366
+ validation_examples = [_pixel_training_example(random) for _ in range(validation_count)]
367
  examples = [_pixel_training_example(random) for _ in range(sample_count)]
368
+ best_loss = float("inf")
369
+ best_weights = None
370
+ stale_epochs = 0
371
+ for epoch in range(1, epochs + 1):
372
  for index in range(sample_count - 1, 0, -1):
373
  swap_index = int(random.next() * (index + 1))
374
  examples[index], examples[swap_index] = examples[swap_index], examples[index]
375
  for inputs, targets in examples:
376
  network.learn(inputs, targets, 0.01)
377
+ metrics = _pixel_validation_metrics(network, validation_examples)
378
+ if metrics_callback is not None:
379
+ metrics_callback(epoch, metrics)
380
+ if metrics["mse"] < best_loss:
381
+ best_loss = metrics["mse"]
382
+ best_weights = {
383
+ key: array("f", getattr(network, key))
384
+ for key in ("weights1", "bias1", "weights2", "bias2")
385
+ }
386
+ stale_epochs = 0
387
+ else:
388
+ stale_epochs += 1
389
+ if stale_epochs >= patience:
390
+ break
391
+
392
+ for key, values in best_weights.items():
393
+ setattr(network, key, values)
394
 
395
  model["randomSeed"] = random.seed
396
  model["network"] = {
 
1001
  def compute(self, task):
1002
  if not isinstance(task, dict):
1003
  raise ValueError("Biocomputation task must be a JSON object.")
1004
+ operation = task.get("operation")
1005
+ if not isinstance(operation, str) or not operation.strip():
1006
+ raise ValueError("Biocomputation task must include a non-empty operation.")
1007
+ if "inputs" in task and not isinstance(task["inputs"], dict):
1008
+ raise ValueError("Biocomputation task inputs must be a JSON object.")
1009
  try:
1010
  payload = json.dumps(
1011
  {"protocol": self.PROTOCOL, "task": task},
 
1051
  raise BiocomputationProviderError(
1052
  f"Biocomputation response must include protocol '{self.PROTOCOL}' and a result."
1053
  )
1054
+ for field in ("provider", "run_id"):
1055
+ if field in result and not isinstance(result[field], str):
1056
+ raise BiocomputationProviderError(
1057
+ f"Biocomputation response field '{field}' must be a string."
1058
+ )
1059
  return result
1060
 
1061
 
 
1102
  return normalize_provider_response(text)
1103
 
1104
  def _generate(self, user_input, state, memories, structured):
1105
+ recent_memories = memories[-5:] if isinstance(memories, (list, tuple)) else memories
1106
  context = json.dumps(
1107
+ {"input": user_input, "state": state, "recent_memory": recent_memories},
1108
  ensure_ascii=False,
1109
  separators=(",", ":"),
1110
  )
 
1274
  def observe(self, input_value):
1275
  return {"input": input_value, "timestamp": now(), "state": dict(self.state)}
1276
 
1277
+ def interpret(self, perception, input_vector=None):
1278
+ if input_vector is None:
1279
+ input_vector = self.encode_input(perception["input"])
1280
+ return self.network.forward(input_vector)
1281
 
1282
  def sense_bio_signals(self, input_value):
1283
  signals = self.state["bioSignals"]
 
1424
  reward += 0.5
1425
  return {"reward": reward, "perception": perception, "action": action, "result": result}
1426
 
1427
+ def learn(self, evaluation, input_vector=None):
1428
+ if input_vector is None:
1429
+ input_vector = self.encode_input(evaluation["perception"]["input"])
1430
  target = array("f", [evaluation["reward"]]) * self.network.output_size
1431
  self.network.learn(input_vector, target, CONFIG["LEARNING_RATE"])
1432
  action = evaluation["action"]
 
1456
  def step(self, input_value, provider_analysis=None):
1457
  perception = self.observe(input_value)
1458
  self.sense_bio_signals(input_value)
1459
+ input_vector = self.encode_input(perception["input"])
1460
+ interpretation = self.interpret(perception, input_vector)
1461
  workspace = self.open_workspace(perception)
1462
  workspace["providerAnalysis"] = copy.deepcopy(provider_analysis)
1463
  workspace["internalState"]["bioSignals"] = copy.deepcopy(self.state["bioSignals"])
 
1482
  "bioSignals": copy.deepcopy(self.state["bioSignals"]),
1483
  }
1484
  evaluation = self.evaluate(perception, action, result)
1485
+ self.learn(evaluation, input_vector)
1486
  self.update_state(evaluation)
1487
  self.sync_model()
1488
  return {
 
1561
  )
1562
  parser.add_argument("--samples", type=int, default=1200)
1563
  parser.add_argument("--epochs", type=int, default=12)
1564
+ parser.add_argument("--patience", type=int, default=4)
1565
  parser.add_argument("--seed", type=int)
1566
  parser.add_argument("--output", default="noe-pixel-model.dodl")
1567
  arguments = parser.parse_args()
1568
 
1569
  output_path = "noe-model.dodl"
1570
  if arguments.train_pixel:
1571
+ def report_metrics(epoch, metrics):
1572
+ print(
1573
+ f"epoch {epoch}: validation_mse={metrics['mse']:.6f} "
1574
+ f"x_mae={metrics['mae_x']:.6f} y_mae={metrics['mae_y']:.6f}"
1575
+ )
1576
+
1577
  train_pixel_model(
1578
  arguments.output,
1579
  sample_count=arguments.samples,
1580
  epochs=arguments.epochs,
1581
  seed=arguments.seed,
1582
+ patience=arguments.patience,
1583
+ metrics_callback=report_metrics,
1584
  )
1585
  gguf_output_path = os.path.splitext(arguments.output)[0] + ".F32.gguf"
1586
  print(f"Pixel control model trained: {arguments.output}")
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