Upload folder using huggingface_hub
Browse files- README.md +15 -3
- me.py +243 -5
- model_providers.py +98 -11
README.md
CHANGED
|
@@ -34,12 +34,22 @@ print(result["action"])
|
|
| 34 |
|
| 35 |
## How the model works
|
| 36 |
|
| 37 |
-
|
| 38 |
|
| 39 |
Each step saves a workspace snapshot with the input focus, active goal, intention, predicted state, observed outcome, and prediction error. This is a practical self-monitoring trace, not evidence that the model has subjective experience. When the default `observe` action would otherwise be chosen, an active `learn` goal can guide the model to learn instead.
|
| 40 |
|
| 41 |
The model tracks `bioSignals` named `novelty`, `stress`, `recovery`, and `arousal`. These bounded software variables can influence exploration and learning. They are biological analogies, not chemical measurements or biological computation. The model also does not simulate quantum effects or establish consciousness.
|
| 42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
Live Preview: [noesis.dodle.link/model](https://noesis.dodle.link/model/)
|
| 44 |
|
| 45 |
## Create a model file
|
|
@@ -162,7 +172,7 @@ The provider sends a JSON `POST` request in this format:
|
|
| 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
|
|
@@ -192,12 +202,14 @@ The file starts with the `DODL` magic signature and a versioned header. It store
|
|
| 192 |
- `deserialize_model(data)` converts DODL bytes back to a model.
|
| 193 |
- `serialize_gguf_model(model)` converts the network tensors to GGUF v3 bytes.
|
| 194 |
- `create_gguf_model_file(path, model)` writes those GGUF bytes to `path`.
|
|
|
|
|
|
|
| 195 |
- `merge_models(model_a, model_b, alpha=0.5)` blends compatible models' network parameters.
|
| 196 |
- `AIEngine(model=None)` runs and updates a model; without an argument it creates a fresh one.
|
| 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 |
|
|
|
|
| 34 |
|
| 35 |
## How the model works
|
| 36 |
|
| 37 |
+
Explicit rest/explore rules and eligible workspace-guided goals take priority. Ordinary models retain the existing rule and behavior-program policy. An action-trained model uses four neural outputs (`rest`, `explore`, `learn`, and `observe`) to choose an action when those higher-priority rules do not decide it. Older model files remain untrained and keep their existing behavior.
|
| 38 |
|
| 39 |
Each step saves a workspace snapshot with the input focus, active goal, intention, predicted state, observed outcome, and prediction error. This is a practical self-monitoring trace, not evidence that the model has subjective experience. When the default `observe` action would otherwise be chosen, an active `learn` goal can guide the model to learn instead.
|
| 40 |
|
| 41 |
The model tracks `bioSignals` named `novelty`, `stress`, `recovery`, and `arousal`. These bounded software variables can influence exploration and learning. They are biological analogies, not chemical measurements or biological computation. The model also does not simulate quantum effects or establish consciousness.
|
| 42 |
|
| 43 |
+
## Train the action policy
|
| 44 |
+
|
| 45 |
+
Train the Python engine's action policy from `core/model/`:
|
| 46 |
+
|
| 47 |
+
```bash
|
| 48 |
+
python3 me.py --train-actions --seed 123
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
This writes `noe-action-model.dodl` and its GGUF companion. Training uses a deterministic synthetic policy and a separate, fixed 100-scenario validation set. Each epoch reports validation accuracy, the always-`observe` baseline, and mean squared error; the best checkpoint is kept and training stops after `--patience` epochs without improvement. Use `--samples`, `--epochs`, and `--patience` to adjust the run, or `--output` to choose another path. Reusing the same seed and options produces the same trained weights and metrics. The DODL file marks the policy as trained; the engine then uses its action scores while preserving explicit rule and goal overrides.
|
| 52 |
+
|
| 53 |
Live Preview: [noesis.dodle.link/model](https://noesis.dodle.link/model/)
|
| 54 |
|
| 55 |
## Create a model file
|
|
|
|
| 172 |
}
|
| 173 |
```
|
| 174 |
|
| 175 |
+
`operation` must be a non-empty string, and `inputs`, when provided, must be an object. The service must return standard JSON with the same `protocol` and a `result` field; `result` may be any JSON value. If supplied, the response content type must be `application/json` or use a `+json` media type. 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. Redirects are followed only when they remain on the same origin. Requests are not retried automatically because a repeated task could cause duplicate computation. The request timeout defaults to 30 seconds and must be a positive finite number. The API key is sent as a bearer token and is never saved in the model file.
|
| 176 |
|
| 177 |
```python
|
| 178 |
from me import AIEngine, BiocomputationProvider
|
|
|
|
| 202 |
- `deserialize_model(data)` converts DODL bytes back to a model.
|
| 203 |
- `serialize_gguf_model(model)` converts the network tensors to GGUF v3 bytes.
|
| 204 |
- `create_gguf_model_file(path, model)` writes those GGUF bytes to `path`.
|
| 205 |
+
- `train_action_model(path, sample_count, epochs, seed, patience)` trains and saves a four-action policy.
|
| 206 |
+
- `evaluate_action_model(model)` reports fixed-set accuracy, per-action accuracy, baseline accuracy, and MSE.
|
| 207 |
- `merge_models(model_a, model_b, alpha=0.5)` blends compatible models' network parameters.
|
| 208 |
- `AIEngine(model=None)` runs and updates a model; without an argument it creates a fresh one.
|
| 209 |
- `AIEngine.step(input_value)` observes input, chooses and executes an action, evaluates it, learns, updates state, and returns the cycle result.
|
| 210 |
- `LLMProvider(provider=None)` configures an OpenAI, Gemini, or OpenAI-compatible text-generation adapter from environment variables.
|
| 211 |
- `AIEngine.respond(input_value, provider=None)` generates a provider reply and runs one local engine step.
|
| 212 |
+
- `BiocomputationProvider(endpoint=None, api_key=None, timeout=30)` submits explicit tasks to a remote biocomputation service.
|
| 213 |
- `AIEngine.compute_biological(task, provider=None)` submits a task without changing model state.
|
| 214 |
- `AIEngine.export_model()` serializes the engine's current model.
|
| 215 |
|
me.py
CHANGED
|
@@ -52,6 +52,7 @@ MAGIC = b"DODL"
|
|
| 52 |
HEADER_SIZE = 16
|
| 53 |
PIXEL_INPUT_SIZE = 8
|
| 54 |
PIXEL_OUTPUT_SIZE = 2
|
|
|
|
| 55 |
|
| 56 |
|
| 57 |
def clamp(value, minimum, maximum):
|
|
@@ -347,6 +348,179 @@ def _pixel_validation_metrics(network, examples):
|
|
| 347 |
}
|
| 348 |
|
| 349 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 350 |
def train_pixel_model(
|
| 351 |
path="noe-pixel-model.dodl",
|
| 352 |
sample_count=1200,
|
|
@@ -604,6 +778,7 @@ def create_model():
|
|
| 604 |
"bias1": network.bias1,
|
| 605 |
"weights2": network.weights2,
|
| 606 |
"bias2": network.bias2,
|
|
|
|
| 607 |
},
|
| 608 |
"memory": [],
|
| 609 |
"rules": create_initial_rules(),
|
|
@@ -762,6 +937,10 @@ def merge_models(model_a, model_b, alpha=0.5):
|
|
| 762 |
"f",
|
| 763 |
((1 - alpha) * value_a + alpha * value_b for value_a, value_b in zip(values_a, values_b)),
|
| 764 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 765 |
|
| 766 |
return merged
|
| 767 |
|
|
@@ -787,6 +966,8 @@ def validate_model(model):
|
|
| 787 |
if any(not isinstance(size, int) or isinstance(size, bool) or size <= 0 for size in shape):
|
| 788 |
raise ValueError("Invalid network shape.")
|
| 789 |
input_size, hidden_size, output_size = shape
|
|
|
|
|
|
|
| 790 |
expected_lengths = {
|
| 791 |
"weights1": input_size * hidden_size,
|
| 792 |
"bias1": hidden_size,
|
|
@@ -831,6 +1012,7 @@ def serialize_model(model):
|
|
| 831 |
"hiddenSize": network["hiddenSize"],
|
| 832 |
"outputSize": network["outputSize"],
|
| 833 |
},
|
|
|
|
| 834 |
}
|
| 835 |
metadata_bytes = json.dumps(metadata, separators=(",", ":"), allow_nan=False).encode("utf-8")
|
| 836 |
network_bytes = b"".join(
|
|
@@ -957,6 +1139,7 @@ def deserialize_model(buffer):
|
|
| 957 |
"bias1": arrays[1],
|
| 958 |
"weights2": arrays[2],
|
| 959 |
"bias2": arrays[3],
|
|
|
|
| 960 |
},
|
| 961 |
"memory": metadata["memory"],
|
| 962 |
"rules": metadata["rules"],
|
|
@@ -997,6 +1180,7 @@ class AIEngine:
|
|
| 997 |
self.network.bias1 = stored_network["bias1"]
|
| 998 |
self.network.weights2 = stored_network["weights2"]
|
| 999 |
self.network.bias2 = stored_network["bias2"]
|
|
|
|
| 1000 |
self.memory = MemoryStore(self.model["memory"])
|
| 1001 |
self.rules = RuleEngine(self.model["rules"])
|
| 1002 |
self.behavior = BehaviorEngine(self.model["behavior"])
|
|
@@ -1022,6 +1206,21 @@ class AIEngine:
|
|
| 1022 |
value = input_value.get("value")
|
| 1023 |
if isinstance(value, str) and len(vector) > 4:
|
| 1024 |
vector[4] = min(len(value) / 100, 1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1025 |
if input_value.get("type") == "user_input" and len(vector) > 5:
|
| 1026 |
vector[5] = 1
|
| 1027 |
if len(vector) > 6:
|
|
@@ -1121,6 +1320,15 @@ class AIEngine:
|
|
| 1121 |
return {"type": "learn", "ruleId": None}
|
| 1122 |
if workspace.get("goal") == "explore" and signals["novelty"] >= 0.7:
|
| 1123 |
return {"type": "explore", "ruleId": None}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1124 |
if rule:
|
| 1125 |
return {"type": rule["action"]["type"], "ruleId": rule["id"]}
|
| 1126 |
return {"type": self.behavior.run(self.state), "ruleId": None}
|
|
@@ -1184,8 +1392,9 @@ class AIEngine:
|
|
| 1184 |
def learn(self, evaluation, input_vector=None):
|
| 1185 |
if input_vector is None:
|
| 1186 |
input_vector = self.encode_input(evaluation["perception"]["input"])
|
| 1187 |
-
|
| 1188 |
-
|
|
|
|
| 1189 |
action = evaluation["action"]
|
| 1190 |
if action["ruleId"]:
|
| 1191 |
self.rules.reward(action["ruleId"], evaluation["reward"])
|
|
@@ -1311,20 +1520,49 @@ class AIEngine:
|
|
| 1311 |
|
| 1312 |
if __name__ == "__main__":
|
| 1313 |
parser = argparse.ArgumentParser(description="Create or train a Noesis model.")
|
| 1314 |
-
parser.
|
|
|
|
| 1315 |
"--train-pixel",
|
| 1316 |
action="store_true",
|
| 1317 |
help="Train a pixel steering model and write noe-pixel-model.dodl.",
|
| 1318 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1319 |
parser.add_argument("--samples", type=int, default=1200)
|
| 1320 |
parser.add_argument("--epochs", type=int, default=12)
|
| 1321 |
parser.add_argument("--patience", type=int, default=4)
|
| 1322 |
parser.add_argument("--seed", type=int)
|
| 1323 |
-
parser.add_argument("--output"
|
| 1324 |
arguments = parser.parse_args()
|
| 1325 |
|
| 1326 |
output_path = "noe-model.dodl"
|
| 1327 |
-
if arguments.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1328 |
def report_metrics(epoch, metrics):
|
| 1329 |
print(
|
| 1330 |
f"epoch {epoch}: validation_mse={metrics['mse']:.6f} "
|
|
|
|
| 52 |
HEADER_SIZE = 16
|
| 53 |
PIXEL_INPUT_SIZE = 8
|
| 54 |
PIXEL_OUTPUT_SIZE = 2
|
| 55 |
+
ACTION_LABELS = ("rest", "explore", "learn", "observe")
|
| 56 |
|
| 57 |
|
| 58 |
def clamp(value, minimum, maximum):
|
|
|
|
| 348 |
}
|
| 349 |
|
| 350 |
|
| 351 |
+
def _action_policy_target(energy, curiosity, confidence):
|
| 352 |
+
if energy < 20:
|
| 353 |
+
return "rest"
|
| 354 |
+
if curiosity > 70:
|
| 355 |
+
return "explore"
|
| 356 |
+
if confidence < 40:
|
| 357 |
+
return "learn"
|
| 358 |
+
return "observe"
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def _action_policy_example(energy, curiosity, confidence, stability=80):
|
| 362 |
+
inputs = array("f", [0]) * CONFIG["INPUT_SIZE"]
|
| 363 |
+
inputs[0] = energy / 100
|
| 364 |
+
inputs[1] = curiosity / 100
|
| 365 |
+
inputs[2] = confidence / 100
|
| 366 |
+
inputs[3] = stability / 100
|
| 367 |
+
return inputs, _action_policy_target(energy, curiosity, confidence)
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def _action_policy_validation_examples():
|
| 371 |
+
return [
|
| 372 |
+
_action_policy_example(energy, curiosity, confidence)
|
| 373 |
+
for energy in (0, 19, 20, 50, 100)
|
| 374 |
+
for curiosity in (0, 70, 71, 100)
|
| 375 |
+
for confidence in (0, 39, 40, 60, 100)
|
| 376 |
+
]
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def _action_policy_metrics(network, examples):
|
| 380 |
+
correct = 0
|
| 381 |
+
squared_error = 0.0
|
| 382 |
+
class_totals = {label: 0 for label in ACTION_LABELS}
|
| 383 |
+
class_correct = {label: 0 for label in ACTION_LABELS}
|
| 384 |
+
for inputs, target in examples:
|
| 385 |
+
target_index = ACTION_LABELS.index(target)
|
| 386 |
+
outputs = network.forward(inputs)["output"]
|
| 387 |
+
prediction = ACTION_LABELS[max(range(len(ACTION_LABELS)), key=lambda index: outputs[index])]
|
| 388 |
+
if prediction == target:
|
| 389 |
+
correct += 1
|
| 390 |
+
class_correct[target] += 1
|
| 391 |
+
class_totals[target] += 1
|
| 392 |
+
for index, output in enumerate(outputs[: len(ACTION_LABELS)]):
|
| 393 |
+
expected = 1.0 if index == target_index else 0.0
|
| 394 |
+
squared_error += (output - expected) ** 2
|
| 395 |
+
sample_count = len(examples)
|
| 396 |
+
return {
|
| 397 |
+
"accuracy": correct / sample_count,
|
| 398 |
+
"baseline_accuracy": sum(class_totals[label] for label in ACTION_LABELS if label == "observe") / sample_count,
|
| 399 |
+
"mse": squared_error / (sample_count * len(ACTION_LABELS)),
|
| 400 |
+
"per_action_accuracy": {
|
| 401 |
+
label: class_correct[label] / class_totals[label]
|
| 402 |
+
if class_totals[label]
|
| 403 |
+
else 0.0
|
| 404 |
+
for label in ACTION_LABELS
|
| 405 |
+
},
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def _network_from_model(model):
|
| 410 |
+
stored = model["network"]
|
| 411 |
+
network = TinyNetwork(Random(1))
|
| 412 |
+
network.input_size = stored["inputSize"]
|
| 413 |
+
network.hidden_size = stored["hiddenSize"]
|
| 414 |
+
network.output_size = stored["outputSize"]
|
| 415 |
+
network.weights1 = stored["weights1"]
|
| 416 |
+
network.bias1 = stored["bias1"]
|
| 417 |
+
network.weights2 = stored["weights2"]
|
| 418 |
+
network.bias2 = stored["bias2"]
|
| 419 |
+
return network
|
| 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 |
+
|
| 433 |
+
|
| 434 |
+
def train_action_model(
|
| 435 |
+
path="noe-action-model.dodl",
|
| 436 |
+
sample_count=1200,
|
| 437 |
+
epochs=20,
|
| 438 |
+
seed=None,
|
| 439 |
+
patience=5,
|
| 440 |
+
metrics_callback=None,
|
| 441 |
+
):
|
| 442 |
+
if not isinstance(sample_count, int) or isinstance(sample_count, bool) or sample_count < 1:
|
| 443 |
+
raise ValueError("sample_count must be a positive integer.")
|
| 444 |
+
if not isinstance(epochs, int) or isinstance(epochs, bool) or epochs < 1:
|
| 445 |
+
raise ValueError("epochs must be a positive integer.")
|
| 446 |
+
if not isinstance(patience, int) or isinstance(patience, bool) or patience < 1:
|
| 447 |
+
raise ValueError("patience must be a positive integer.")
|
| 448 |
+
if metrics_callback is not None and not callable(metrics_callback):
|
| 449 |
+
raise ValueError("metrics_callback must be callable.")
|
| 450 |
+
|
| 451 |
+
random = Random(seed if seed is not None else random_int(1, 0xFFFFFFFF))
|
| 452 |
+
model = create_model()
|
| 453 |
+
network = TinyNetwork(random)
|
| 454 |
+
network.input_size = CONFIG["INPUT_SIZE"]
|
| 455 |
+
network.hidden_size = CONFIG["HIDDEN_SIZE"]
|
| 456 |
+
network.output_size = len(ACTION_LABELS)
|
| 457 |
+
network.weights1 = array("f", [0]) * (network.input_size * network.hidden_size)
|
| 458 |
+
network.bias1 = array("f", [0]) * network.hidden_size
|
| 459 |
+
network.weights2 = array("f", [0]) * (network.hidden_size * network.output_size)
|
| 460 |
+
network.bias2 = array("f", [0]) * network.output_size
|
| 461 |
+
network.initialize(random)
|
| 462 |
+
for hidden_index in range(network.hidden_size):
|
| 463 |
+
start = hidden_index * network.input_size
|
| 464 |
+
for input_index in range(4, network.input_size):
|
| 465 |
+
network.weights1[start + input_index] = 0
|
| 466 |
+
|
| 467 |
+
examples = [
|
| 468 |
+
_action_policy_example(
|
| 469 |
+
random.float(0, 100),
|
| 470 |
+
random.float(0, 100),
|
| 471 |
+
random.float(0, 100),
|
| 472 |
+
)
|
| 473 |
+
for _ in range(sample_count)
|
| 474 |
+
]
|
| 475 |
+
validation_examples = _action_policy_validation_examples()
|
| 476 |
+
best_score = (-1.0, float("inf"))
|
| 477 |
+
best_weights = None
|
| 478 |
+
stale_epochs = 0
|
| 479 |
+
for epoch in range(1, epochs + 1):
|
| 480 |
+
for index in range(sample_count - 1, 0, -1):
|
| 481 |
+
swap_index = int(random.next() * (index + 1))
|
| 482 |
+
examples[index], examples[swap_index] = examples[swap_index], examples[index]
|
| 483 |
+
for inputs, label in examples:
|
| 484 |
+
targets = array("f", [0]) * len(ACTION_LABELS)
|
| 485 |
+
targets[ACTION_LABELS.index(label)] = 1
|
| 486 |
+
network.learn(inputs, targets, 0.03)
|
| 487 |
+
metrics = _action_policy_metrics(network, validation_examples)
|
| 488 |
+
if metrics_callback is not None:
|
| 489 |
+
metrics_callback(epoch, metrics)
|
| 490 |
+
score = (metrics["accuracy"], -metrics["mse"])
|
| 491 |
+
if score > best_score:
|
| 492 |
+
best_score = score
|
| 493 |
+
best_weights = {
|
| 494 |
+
key: array("f", getattr(network, key))
|
| 495 |
+
for key in ("weights1", "bias1", "weights2", "bias2")
|
| 496 |
+
}
|
| 497 |
+
stale_epochs = 0
|
| 498 |
+
else:
|
| 499 |
+
stale_epochs += 1
|
| 500 |
+
if stale_epochs >= patience:
|
| 501 |
+
break
|
| 502 |
+
|
| 503 |
+
for key, values in best_weights.items():
|
| 504 |
+
setattr(network, key, values)
|
| 505 |
+
|
| 506 |
+
model["randomSeed"] = random.seed
|
| 507 |
+
model["network"] = {
|
| 508 |
+
"inputSize": network.input_size,
|
| 509 |
+
"hiddenSize": network.hidden_size,
|
| 510 |
+
"outputSize": network.output_size,
|
| 511 |
+
"weights1": network.weights1,
|
| 512 |
+
"bias1": network.bias1,
|
| 513 |
+
"weights2": network.weights2,
|
| 514 |
+
"bias2": network.bias2,
|
| 515 |
+
"policyTrained": True,
|
| 516 |
+
}
|
| 517 |
+
with open(path, "wb") as model_file:
|
| 518 |
+
model_file.write(serialize_model(model))
|
| 519 |
+
gguf_path = os.path.splitext(os.fsdecode(path))[0] + ".F32.gguf"
|
| 520 |
+
create_gguf_model_file(gguf_path, model)
|
| 521 |
+
return model
|
| 522 |
+
|
| 523 |
+
|
| 524 |
def train_pixel_model(
|
| 525 |
path="noe-pixel-model.dodl",
|
| 526 |
sample_count=1200,
|
|
|
|
| 778 |
"bias1": network.bias1,
|
| 779 |
"weights2": network.weights2,
|
| 780 |
"bias2": network.bias2,
|
| 781 |
+
"policyTrained": False,
|
| 782 |
},
|
| 783 |
"memory": [],
|
| 784 |
"rules": create_initial_rules(),
|
|
|
|
| 937 |
"f",
|
| 938 |
((1 - alpha) * value_a + alpha * value_b for value_a, value_b in zip(values_a, values_b)),
|
| 939 |
)
|
| 940 |
+
merged["network"]["policyTrained"] = bool(
|
| 941 |
+
network_a.get("policyTrained", False)
|
| 942 |
+
and network_b.get("policyTrained", False)
|
| 943 |
+
)
|
| 944 |
|
| 945 |
return merged
|
| 946 |
|
|
|
|
| 966 |
if any(not isinstance(size, int) or isinstance(size, bool) or size <= 0 for size in shape):
|
| 967 |
raise ValueError("Invalid network shape.")
|
| 968 |
input_size, hidden_size, output_size = shape
|
| 969 |
+
if "policyTrained" in network and not isinstance(network["policyTrained"], bool):
|
| 970 |
+
raise ValueError("Model network policyTrained must be a boolean.")
|
| 971 |
expected_lengths = {
|
| 972 |
"weights1": input_size * hidden_size,
|
| 973 |
"bias1": hidden_size,
|
|
|
|
| 1012 |
"hiddenSize": network["hiddenSize"],
|
| 1013 |
"outputSize": network["outputSize"],
|
| 1014 |
},
|
| 1015 |
+
"policyTrained": bool(network.get("policyTrained", False)),
|
| 1016 |
}
|
| 1017 |
metadata_bytes = json.dumps(metadata, separators=(",", ":"), allow_nan=False).encode("utf-8")
|
| 1018 |
network_bytes = b"".join(
|
|
|
|
| 1139 |
"bias1": arrays[1],
|
| 1140 |
"weights2": arrays[2],
|
| 1141 |
"bias2": arrays[3],
|
| 1142 |
+
"policyTrained": metadata.get("policyTrained", False),
|
| 1143 |
},
|
| 1144 |
"memory": metadata["memory"],
|
| 1145 |
"rules": metadata["rules"],
|
|
|
|
| 1180 |
self.network.bias1 = stored_network["bias1"]
|
| 1181 |
self.network.weights2 = stored_network["weights2"]
|
| 1182 |
self.network.bias2 = stored_network["bias2"]
|
| 1183 |
+
self.policy_trained = bool(stored_network.get("policyTrained", False))
|
| 1184 |
self.memory = MemoryStore(self.model["memory"])
|
| 1185 |
self.rules = RuleEngine(self.model["rules"])
|
| 1186 |
self.behavior = BehaviorEngine(self.model["behavior"])
|
|
|
|
| 1206 |
value = input_value.get("value")
|
| 1207 |
if isinstance(value, str) and len(vector) > 4:
|
| 1208 |
vector[4] = min(len(value) / 100, 1)
|
| 1209 |
+
feature_start = 7
|
| 1210 |
+
feature_count = len(vector) - feature_start
|
| 1211 |
+
if feature_count > 0:
|
| 1212 |
+
for token in value.lower().split():
|
| 1213 |
+
token_hash = 2166136261
|
| 1214 |
+
for byte in token.encode("utf-8"):
|
| 1215 |
+
token_hash = ((token_hash ^ byte) * 16777619) & 0xFFFFFFFF
|
| 1216 |
+
bucket = token_hash % feature_count
|
| 1217 |
+
sign = 1 if token_hash & 0x80000000 else -1
|
| 1218 |
+
vector[feature_start + bucket] += sign
|
| 1219 |
+
feature_values = vector[feature_start:]
|
| 1220 |
+
magnitude = max((abs(value) for value in feature_values), default=0)
|
| 1221 |
+
if magnitude > 1:
|
| 1222 |
+
for index in range(feature_start, len(vector)):
|
| 1223 |
+
vector[index] /= magnitude
|
| 1224 |
if input_value.get("type") == "user_input" and len(vector) > 5:
|
| 1225 |
vector[5] = 1
|
| 1226 |
if len(vector) > 6:
|
|
|
|
| 1320 |
return {"type": "learn", "ruleId": None}
|
| 1321 |
if workspace.get("goal") == "explore" and signals["novelty"] >= 0.7:
|
| 1322 |
return {"type": "explore", "ruleId": None}
|
| 1323 |
+
if rule and rule["action"]["type"] != "observe":
|
| 1324 |
+
return {"type": rule["action"]["type"], "ruleId": rule["id"]}
|
| 1325 |
+
if self.policy_trained and self.network.output_size >= len(ACTION_LABELS):
|
| 1326 |
+
inputs = self.encode_input(perception["input"])
|
| 1327 |
+
outputs = self.network.forward(inputs)["output"]
|
| 1328 |
+
action_index = max(
|
| 1329 |
+
range(len(ACTION_LABELS)), key=lambda index: outputs[index]
|
| 1330 |
+
)
|
| 1331 |
+
return {"type": ACTION_LABELS[action_index], "ruleId": None}
|
| 1332 |
if rule:
|
| 1333 |
return {"type": rule["action"]["type"], "ruleId": rule["id"]}
|
| 1334 |
return {"type": self.behavior.run(self.state), "ruleId": None}
|
|
|
|
| 1392 |
def learn(self, evaluation, input_vector=None):
|
| 1393 |
if input_vector is None:
|
| 1394 |
input_vector = self.encode_input(evaluation["perception"]["input"])
|
| 1395 |
+
if not self.policy_trained:
|
| 1396 |
+
target = array("f", [evaluation["reward"]]) * self.network.output_size
|
| 1397 |
+
self.network.learn(input_vector, target, CONFIG["LEARNING_RATE"])
|
| 1398 |
action = evaluation["action"]
|
| 1399 |
if action["ruleId"]:
|
| 1400 |
self.rules.reward(action["ruleId"], evaluation["reward"])
|
|
|
|
| 1520 |
|
| 1521 |
if __name__ == "__main__":
|
| 1522 |
parser = argparse.ArgumentParser(description="Create or train a Noesis model.")
|
| 1523 |
+
training_modes = parser.add_mutually_exclusive_group()
|
| 1524 |
+
training_modes.add_argument(
|
| 1525 |
"--train-pixel",
|
| 1526 |
action="store_true",
|
| 1527 |
help="Train a pixel steering model and write noe-pixel-model.dodl.",
|
| 1528 |
)
|
| 1529 |
+
training_modes.add_argument(
|
| 1530 |
+
"--train-actions",
|
| 1531 |
+
action="store_true",
|
| 1532 |
+
help="Train an action-selection model and write noe-action-model.dodl.",
|
| 1533 |
+
)
|
| 1534 |
parser.add_argument("--samples", type=int, default=1200)
|
| 1535 |
parser.add_argument("--epochs", type=int, default=12)
|
| 1536 |
parser.add_argument("--patience", type=int, default=4)
|
| 1537 |
parser.add_argument("--seed", type=int)
|
| 1538 |
+
parser.add_argument("--output")
|
| 1539 |
arguments = parser.parse_args()
|
| 1540 |
|
| 1541 |
output_path = "noe-model.dodl"
|
| 1542 |
+
if arguments.train_actions:
|
| 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,
|
| 1556 |
+
seed=arguments.seed,
|
| 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}")
|
| 1563 |
+
elif arguments.train_pixel:
|
| 1564 |
+
output_path = arguments.output or "noe-pixel-model.dodl"
|
| 1565 |
+
|
| 1566 |
def report_metrics(epoch, metrics):
|
| 1567 |
print(
|
| 1568 |
f"epoch {epoch}: validation_mse={metrics['mse']:.6f} "
|
model_providers.py
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
|
|
| 1 |
import json
|
| 2 |
import math
|
| 3 |
import os
|
|
@@ -10,6 +11,38 @@ def _clamp(value, minimum, maximum):
|
|
| 10 |
return max(minimum, min(maximum, value))
|
| 11 |
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
class LLMProviderError(RuntimeError):
|
| 14 |
pass
|
| 15 |
|
|
@@ -28,15 +61,40 @@ class BiocomputationProvider:
|
|
| 28 |
self.endpoint = endpoint or os.environ.get("NOESIS_BIOCOMPUTE_URL")
|
| 29 |
if not self.endpoint:
|
| 30 |
raise ValueError("Set NOESIS_BIOCOMPUTE_URL or pass endpoint.")
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
local_hosts = {"localhost", "127.0.0.1", "::1"}
|
| 33 |
if parsed_endpoint.scheme != "https" and not (
|
| 34 |
-
parsed_endpoint.scheme == "http" and
|
| 35 |
):
|
| 36 |
raise ValueError("Biocomputation endpoint must use HTTPS (HTTP is allowed for localhost).")
|
| 37 |
-
if not
|
| 38 |
raise ValueError("Biocomputation endpoint must include a hostname.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
self.api_key = api_key or os.environ.get("NOESIS_BIOCOMPUTE_API_KEY")
|
|
|
|
|
|
|
| 40 |
self.timeout = timeout
|
| 41 |
|
| 42 |
def compute(self, task):
|
|
@@ -62,25 +120,54 @@ class BiocomputationProvider:
|
|
| 62 |
headers = {"Content-Type": "application/json"}
|
| 63 |
if self.api_key:
|
| 64 |
headers["Authorization"] = f"Bearer {self.api_key}"
|
| 65 |
-
request = urllib.request.Request(
|
| 66 |
-
self.endpoint, data=payload, headers=headers, method="POST"
|
| 67 |
-
)
|
| 68 |
try:
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
response_data = response.read(self.MAX_PAYLOAD_SIZE + 1)
|
| 71 |
except urllib.error.HTTPError as error:
|
| 72 |
raise BiocomputationProviderError(
|
| 73 |
f"Biocomputation service returned HTTP {error.code}."
|
| 74 |
) from error
|
| 75 |
-
except
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
raise BiocomputationProviderError(
|
| 77 |
-
f"Biocomputation service request failed
|
| 78 |
) from error
|
| 79 |
if len(response_data) > self.MAX_PAYLOAD_SIZE:
|
| 80 |
raise BiocomputationProviderError("Biocomputation response exceeds the 1 MiB limit.")
|
| 81 |
try:
|
| 82 |
-
result = json.loads(
|
| 83 |
-
|
|
|
|
|
|
|
| 84 |
raise BiocomputationProviderError(
|
| 85 |
"Biocomputation service returned invalid JSON."
|
| 86 |
) from error
|
|
|
|
| 1 |
+
import http.client
|
| 2 |
import json
|
| 3 |
import math
|
| 4 |
import os
|
|
|
|
| 11 |
return max(minimum, min(maximum, value))
|
| 12 |
|
| 13 |
|
| 14 |
+
def _reject_json_constant(value):
|
| 15 |
+
raise ValueError(f"Invalid JSON constant '{value}'.")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class _SameOriginRedirectHandler(urllib.request.HTTPRedirectHandler):
|
| 19 |
+
def __init__(self, endpoint):
|
| 20 |
+
super().__init__()
|
| 21 |
+
parsed_endpoint = urllib.parse.urlsplit(endpoint)
|
| 22 |
+
self.origin = (
|
| 23 |
+
parsed_endpoint.scheme,
|
| 24 |
+
parsed_endpoint.hostname,
|
| 25 |
+
parsed_endpoint.port,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
def redirect_request(self, request, file_pointer, code, message, headers, new_url):
|
| 29 |
+
try:
|
| 30 |
+
parsed_url = urllib.parse.urlsplit(new_url)
|
| 31 |
+
origin = (parsed_url.scheme, parsed_url.hostname, parsed_url.port)
|
| 32 |
+
except ValueError:
|
| 33 |
+
return None
|
| 34 |
+
if (
|
| 35 |
+
origin != self.origin
|
| 36 |
+
or parsed_url.username is not None
|
| 37 |
+
or parsed_url.password is not None
|
| 38 |
+
or "#" in new_url
|
| 39 |
+
):
|
| 40 |
+
return None
|
| 41 |
+
return super().redirect_request(
|
| 42 |
+
request, file_pointer, code, message, headers, new_url
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
class LLMProviderError(RuntimeError):
|
| 47 |
pass
|
| 48 |
|
|
|
|
| 61 |
self.endpoint = endpoint or os.environ.get("NOESIS_BIOCOMPUTE_URL")
|
| 62 |
if not self.endpoint:
|
| 63 |
raise ValueError("Set NOESIS_BIOCOMPUTE_URL or pass endpoint.")
|
| 64 |
+
if not isinstance(self.endpoint, str):
|
| 65 |
+
raise ValueError("Biocomputation endpoint must be a URL string.")
|
| 66 |
+
try:
|
| 67 |
+
parsed_endpoint = urllib.parse.urlsplit(self.endpoint)
|
| 68 |
+
hostname = parsed_endpoint.hostname
|
| 69 |
+
parsed_endpoint.port
|
| 70 |
+
except ValueError as error:
|
| 71 |
+
raise ValueError("Biocomputation endpoint is malformed.") from error
|
| 72 |
local_hosts = {"localhost", "127.0.0.1", "::1"}
|
| 73 |
if parsed_endpoint.scheme != "https" and not (
|
| 74 |
+
parsed_endpoint.scheme == "http" and hostname in local_hosts
|
| 75 |
):
|
| 76 |
raise ValueError("Biocomputation endpoint must use HTTPS (HTTP is allowed for localhost).")
|
| 77 |
+
if not hostname:
|
| 78 |
raise ValueError("Biocomputation endpoint must include a hostname.")
|
| 79 |
+
if any(character.isspace() for character in hostname):
|
| 80 |
+
raise ValueError("Biocomputation endpoint hostname is malformed.")
|
| 81 |
+
if parsed_endpoint.username is not None or parsed_endpoint.password is not None:
|
| 82 |
+
raise ValueError("Biocomputation endpoint must not contain credentials.")
|
| 83 |
+
if "#" in self.endpoint:
|
| 84 |
+
raise ValueError("Biocomputation endpoint must not contain a fragment.")
|
| 85 |
+
if isinstance(timeout, bool) or not isinstance(timeout, (int, float)):
|
| 86 |
+
raise ValueError("Biocomputation timeout must be a positive finite number.")
|
| 87 |
+
try:
|
| 88 |
+
timeout = float(timeout)
|
| 89 |
+
except (OverflowError, ValueError) as error:
|
| 90 |
+
raise ValueError(
|
| 91 |
+
"Biocomputation timeout must be a positive finite number."
|
| 92 |
+
) from error
|
| 93 |
+
if not math.isfinite(timeout) or timeout <= 0:
|
| 94 |
+
raise ValueError("Biocomputation timeout must be a positive finite number.")
|
| 95 |
self.api_key = api_key or os.environ.get("NOESIS_BIOCOMPUTE_API_KEY")
|
| 96 |
+
if self.api_key is not None and not isinstance(self.api_key, str):
|
| 97 |
+
raise ValueError("Biocomputation API key must be a string.")
|
| 98 |
self.timeout = timeout
|
| 99 |
|
| 100 |
def compute(self, task):
|
|
|
|
| 120 |
headers = {"Content-Type": "application/json"}
|
| 121 |
if self.api_key:
|
| 122 |
headers["Authorization"] = f"Bearer {self.api_key}"
|
|
|
|
|
|
|
|
|
|
| 123 |
try:
|
| 124 |
+
request = urllib.request.Request(
|
| 125 |
+
self.endpoint, data=payload, headers=headers, method="POST"
|
| 126 |
+
)
|
| 127 |
+
opener = urllib.request.build_opener(
|
| 128 |
+
_SameOriginRedirectHandler(self.endpoint)
|
| 129 |
+
)
|
| 130 |
+
with opener.open(request, timeout=self.timeout) as response:
|
| 131 |
+
response_headers = getattr(response, "headers", None)
|
| 132 |
+
content_type = (
|
| 133 |
+
response_headers.get("Content-Type")
|
| 134 |
+
if response_headers is not None
|
| 135 |
+
else None
|
| 136 |
+
)
|
| 137 |
+
if content_type is None and hasattr(response, "getheader"):
|
| 138 |
+
content_type = response.getheader("Content-Type")
|
| 139 |
+
if content_type is not None:
|
| 140 |
+
media_type = content_type.split(";", 1)[0].strip().lower()
|
| 141 |
+
if media_type != "application/json" and not media_type.endswith(
|
| 142 |
+
"+json"
|
| 143 |
+
):
|
| 144 |
+
raise BiocomputationProviderError(
|
| 145 |
+
"Biocomputation service response must use a JSON content type."
|
| 146 |
+
)
|
| 147 |
response_data = response.read(self.MAX_PAYLOAD_SIZE + 1)
|
| 148 |
except urllib.error.HTTPError as error:
|
| 149 |
raise BiocomputationProviderError(
|
| 150 |
f"Biocomputation service returned HTTP {error.code}."
|
| 151 |
) from error
|
| 152 |
+
except BiocomputationProviderError:
|
| 153 |
+
raise
|
| 154 |
+
except (
|
| 155 |
+
urllib.error.URLError,
|
| 156 |
+
TimeoutError,
|
| 157 |
+
OSError,
|
| 158 |
+
http.client.HTTPException,
|
| 159 |
+
ValueError,
|
| 160 |
+
) as error:
|
| 161 |
raise BiocomputationProviderError(
|
| 162 |
+
f"Biocomputation service request failed ({type(error).__name__})."
|
| 163 |
) from error
|
| 164 |
if len(response_data) > self.MAX_PAYLOAD_SIZE:
|
| 165 |
raise BiocomputationProviderError("Biocomputation response exceeds the 1 MiB limit.")
|
| 166 |
try:
|
| 167 |
+
result = json.loads(
|
| 168 |
+
response_data.decode("utf-8"), parse_constant=_reject_json_constant
|
| 169 |
+
)
|
| 170 |
+
except (UnicodeDecodeError, ValueError) as error:
|
| 171 |
raise BiocomputationProviderError(
|
| 172 |
"Biocomputation service returned invalid JSON."
|
| 173 |
) from error
|