Upload folder using huggingface_hub
Browse files- README.md +55 -4
- me.py +344 -41
- model_formats.py +12 -1
- noe-model.F32.gguf +0 -0
- noe-model.dodl +0 -0
- noe-pixel-model.F32.gguf +0 -0
- noe-pixel-model.dodl +0 -0
README.md
CHANGED
|
@@ -38,13 +38,15 @@ result = engine.step({"type": "user_input", "value": "hello"})
|
|
| 38 |
print(result["action"])
|
| 39 |
```
|
| 40 |
|
| 41 |
-
The engine updates its state as it runs. Save the latest state with `engine.export_model()` when you want to keep those updates.
|
| 42 |
|
| 43 |
## How it works
|
| 44 |
|
| 45 |
-
Each step reads the input and current state, chooses an action, runs it, and updates the model. Rules and eligible goals can take priority. A model trained with `--train-actions` can use its network to choose among `rest`, `explore`, `learn`, and `observe`. Untrained models keep their existing rules and behavior.
|
| 46 |
|
| 47 |
-
The engine also records a workspace snapshot: what it focused on, which goal was active, what it expected, and what happened.
|
|
|
|
|
|
|
| 48 |
|
| 49 |
## Training
|
| 50 |
|
|
@@ -60,6 +62,54 @@ The command writes `noe-action-model.dodl` and a GGUF companion. It trains on a
|
|
| 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:
|
|
@@ -82,7 +132,7 @@ You can also try the [live demo](https://noesis.dodle.link/model/).
|
|
| 82 |
|
| 83 |
## Model files
|
| 84 |
|
| 85 |
-
DODL stores the full model: its state, memory, rules, behavior, and network. GGUF stores the network tensors and
|
| 86 |
|
| 87 |
The files are binary, not text or JSON. The serializer and loader support files up to 1 MiB and check the file version, dimensions, tensor lengths, and values. Use `create_model_file(path)` to write a DODL model, or pass its returned model to `create_gguf_model_file(path, model)` to write the matching GGUF file. The destination folder must already exist.
|
| 88 |
|
|
@@ -197,6 +247,7 @@ You can pass DODL models or supported model paths. ONNX loading requires `pip in
|
|
| 197 |
- `serialize_gguf_model(model)` and `create_gguf_model_file(path, model)` write GGUF data.
|
| 198 |
- `AIEngine(model=None)` runs a model. `step(input_value)` performs one cycle, and `export_model()` returns the updated model as bytes.
|
| 199 |
- `train_action_model(...)` trains an action policy; `evaluate_action_model(model)` reports validation and held-out results, including per-action accuracy and support.
|
|
|
|
| 200 |
- `merge_models(model_a, model_b, alpha=0.5)` blends network weights.
|
| 201 |
- `LLMProvider(...)` configures a text-generation service; `AIEngine.respond(...)` requests a reply and runs one local cycle.
|
| 202 |
- `BiocomputationProvider(...)` configures an allowlisted gateway client; `AIEngine.compute_biological(...)` submits an approved task without changing model state. `submit_task()`, `get_job()`, and `cancel_job()` provide asynchronous job handling.
|
|
|
|
| 38 |
print(result["action"])
|
| 39 |
```
|
| 40 |
|
| 41 |
+
The engine updates its state as it runs. Each `step()` result is an independent snapshot. Save the latest state with `engine.export_model()` when you want to keep those updates.
|
| 42 |
|
| 43 |
## How it works
|
| 44 |
|
| 45 |
+
Each step reads the input and current state, chooses an action, runs it, and updates the model. Rules and eligible goals can take priority. A model trained with `--train-actions` can use its network to choose among `rest`, `explore`, `learn`, and `observe`. Untrained models keep their existing rules and behavior. Steps update memory, rules, and the outcome self-model, but do not train network weights online.
|
| 46 |
|
| 47 |
+
The engine also records a workspace snapshot: what it focused on, which goal was active, recalled episodes, candidate predictions, what it expected, and what happened. Episodes are selected by word overlap and recency, not semantic understanding. When a goal is unmet, learned action effects can guide a choice; explicit non-observe rules still override it, and unknown actions fall back to the existing policy. Matching episodes supply context-specific outcome estimates. The candidate uncertainty and memory uncertainty fields are simple observation-count and lexical-overlap heuristics, not calibrated probabilities. Reply providers receive the selected episodes and the same pre-action workspace; provider analysis does not control actions.
|
| 48 |
+
|
| 49 |
+
These are software traces and decision heuristics, not evidence of subjective experience. Values such as `novelty`, `stress`, `recovery`, and `arousal` are bounded software signals. They are not biological measurements, and the model does not simulate quantum effects or establish consciousness.
|
| 50 |
|
| 51 |
## Training
|
| 52 |
|
|
|
|
| 62 |
|
| 63 |
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.
|
| 64 |
|
| 65 |
+
Use `evaluate_action_scenarios` to compare prediction-informed decisions (`prediction`), the policy without prediction-based selection (`policy`), and the threshold baseline (`rule_baseline`) on multi-step tasks. All run through the same engine, including rule and goal overrides. Supply representative task inputs, starting state values, optional `goals`, and measurable final-state objectives. For example, this is a synthetic illustration, not evidence of real-world performance:
|
| 66 |
+
|
| 67 |
+
```python
|
| 68 |
+
from me import evaluate_action_scenarios, load_model_file
|
| 69 |
+
|
| 70 |
+
model = load_model_file("noe-action-model.dodl")
|
| 71 |
+
scenarios = [{
|
| 72 |
+
"initial_state": {"energy": 80, "curiosity": 50, "confidence": 50},
|
| 73 |
+
"inputs": [{"type": "user_input", "value": "first"},
|
| 74 |
+
{"type": "user_input", "value": "second"}],
|
| 75 |
+
"objectives": {"confidence": {"min": 55}, "energy": {"min": 20}},
|
| 76 |
+
}]
|
| 77 |
+
results = evaluate_action_scenarios(model, scenarios)
|
| 78 |
+
print(results["prediction"]["success_rate"], results["policy"]["success_rate"],
|
| 79 |
+
results["rule_baseline"]["success_rate"])
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
Objectives support `min` and `max` bounds on final `energy`, `curiosity`, `confidence`, and `stability`. Results include success rates, mean total reward, mean prediction error, and each scenario's actions, minimum energy, final state, and success. The evaluator copies the model for each run. Its reward and state objectives measure this simulation only; representative tasks and independent outcome criteria are still needed to assess usefulness.
|
| 83 |
+
|
| 84 |
+
### Train from task demonstrations
|
| 85 |
+
|
| 86 |
+
`train_action_model_from_episodes` trains on caller-supplied multi-step demonstrations instead of threshold labels. Each episode supplies `initial_state`, `inputs`, `actions`, and final-state `objectives`; `goals` is optional. The trainer replays each demonstration, rejects rule conflicts and failed objectives, selects weights using separate validation demonstrations, and can evaluate a separate test set after selection. For example:
|
| 87 |
+
|
| 88 |
+
```python
|
| 89 |
+
from me import train_action_model_from_episodes
|
| 90 |
+
|
| 91 |
+
def episode(energy, text):
|
| 92 |
+
return {
|
| 93 |
+
"initial_state": {"energy": energy, "confidence": 50},
|
| 94 |
+
"inputs": [{"type": "user_input", "value": text}, None],
|
| 95 |
+
"actions": ["learn", "learn"],
|
| 96 |
+
"objectives": {"confidence": {"min": 60}, "energy": {"min": 20}},
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
training = [episode(80, "training task")]
|
| 100 |
+
validation = [episode(75, "validation task")]
|
| 101 |
+
test = episode(70, "held out task")
|
| 102 |
+
del test["actions"]
|
| 103 |
+
model, report = train_action_model_from_episodes(
|
| 104 |
+
"noe-demonstration-model.dodl", training, validation,
|
| 105 |
+
test_scenarios=[test], epochs=20, seed=7,
|
| 106 |
+
)
|
| 107 |
+
print(report["validation"]["accuracy"])
|
| 108 |
+
print(report["test_scenarios"]["prediction"]["success_rate"])
|
| 109 |
+
```
|
| 110 |
+
|
| 111 |
+
This example is intentionally small and synthetic; it does not establish generalization. Supply larger, representative demonstrations and independently designed validation and held-out tasks, including conflicting goals. The trainer rejects exact duplicate scenarios across the sets, but cannot detect subtler data leakage. The network still sees only its encoded state and input, not a full workspace; the runtime handles workspace-based planning separately.
|
| 112 |
+
|
| 113 |
### Pixel controller
|
| 114 |
|
| 115 |
The browser demo has a separate network that steers a pixel using its position, velocity, pointer position, and excitement level. Train it with:
|
|
|
|
| 132 |
|
| 133 |
## Model files
|
| 134 |
|
| 135 |
+
DODL stores the full model: its state, memory, rules, behavior, and network. New workspace fields and training metadata have defaults for older version-2 DODL files. GGUF stores the network tensors, dimensions, training method, feature schema, and tensor-layout metadata, but not the live model state. The `F32` suffix means the GGUF tensors use 32-bit floating-point values. The GGUF file uses Noesis' custom `noesis` architecture and needs a compatible runtime; it is not a general-purpose language model. Older files without provenance are marked `unspecified` when loaded and exported.
|
| 136 |
|
| 137 |
The files are binary, not text or JSON. The serializer and loader support files up to 1 MiB and check the file version, dimensions, tensor lengths, and values. Use `create_model_file(path)` to write a DODL model, or pass its returned model to `create_gguf_model_file(path, model)` to write the matching GGUF file. The destination folder must already exist.
|
| 138 |
|
|
|
|
| 247 |
- `serialize_gguf_model(model)` and `create_gguf_model_file(path, model)` write GGUF data.
|
| 248 |
- `AIEngine(model=None)` runs a model. `step(input_value)` performs one cycle, and `export_model()` returns the updated model as bytes.
|
| 249 |
- `train_action_model(...)` trains an action policy; `evaluate_action_model(model)` reports validation and held-out results, including per-action accuracy and support.
|
| 250 |
+
- `evaluate_action_scenarios(model, scenarios)` compares multi-step task outcomes against the threshold rule baseline.
|
| 251 |
- `merge_models(model_a, model_b, alpha=0.5)` blends network weights.
|
| 252 |
- `LLMProvider(...)` configures a text-generation service; `AIEngine.respond(...)` requests a reply and runs one local cycle.
|
| 253 |
- `BiocomputationProvider(...)` configures an allowlisted gateway client; `AIEngine.compute_biological(...)` submits an approved task without changing model state. `submit_task()`, `get_job()`, and `cancel_job()` provide asynchronous job handling.
|
me.py
CHANGED
|
@@ -96,14 +96,6 @@ class Random:
|
|
| 96 |
return minimum + self.next() * (maximum - minimum)
|
| 97 |
|
| 98 |
|
| 99 |
-
def encode_model_for_storage(buffer):
|
| 100 |
-
return base64.b64encode(buffer).decode("ascii")
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
def decode_model_from_storage(encoded):
|
| 104 |
-
return base64.b64decode(encoded, validate=True)
|
| 105 |
-
|
| 106 |
-
|
| 107 |
def create_initial_self_model():
|
| 108 |
return {
|
| 109 |
"actions": {},
|
|
@@ -121,6 +113,7 @@ def create_initial_bio_signals():
|
|
| 121 |
|
| 122 |
def create_initial_workspace():
|
| 123 |
return {
|
|
|
|
| 124 |
"cycle": 0,
|
| 125 |
"focus": "idle",
|
| 126 |
"externalInput": None,
|
|
@@ -131,6 +124,7 @@ def create_initial_workspace():
|
|
| 131 |
"prediction": None,
|
| 132 |
"outcome": None,
|
| 133 |
"predictionError": 0.0,
|
|
|
|
| 134 |
"broadcast": {},
|
| 135 |
}
|
| 136 |
|
|
@@ -413,7 +407,7 @@ def _action_policy_metrics(network, examples):
|
|
| 413 |
sample_count = len(examples)
|
| 414 |
return {
|
| 415 |
"accuracy": correct / sample_count,
|
| 416 |
-
"baseline_accuracy":
|
| 417 |
"rule_baseline_accuracy": rule_baseline_correct / sample_count,
|
| 418 |
"mse": squared_error / (sample_count * len(ACTION_LABELS)),
|
| 419 |
"per_action_accuracy": {
|
|
@@ -536,6 +530,8 @@ def train_action_model(
|
|
| 536 |
"weights2": network.weights2,
|
| 537 |
"bias2": network.bias2,
|
| 538 |
"policyTrained": True,
|
|
|
|
|
|
|
| 539 |
}
|
| 540 |
model["updatedAt"] = now()
|
| 541 |
gguf_path = os.path.splitext(os.fsdecode(path))[0] + ".F32.gguf"
|
|
@@ -613,6 +609,8 @@ def train_pixel_model(
|
|
| 613 |
"bias1": network.bias1,
|
| 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"
|
|
@@ -627,8 +625,7 @@ class MemoryStore:
|
|
| 627 |
self.items = memory if memory is not None else []
|
| 628 |
|
| 629 |
def add(self, memory):
|
| 630 |
-
|
| 631 |
-
{
|
| 632 |
"id": uuid_bytes(),
|
| 633 |
"timestamp": now(),
|
| 634 |
"input": memory.get("input"),
|
|
@@ -637,7 +634,10 @@ class MemoryStore:
|
|
| 637 |
"reward": memory.get("reward"),
|
| 638 |
"importance": clamp(memory.get("importance", 50), 0, 100),
|
| 639 |
}
|
| 640 |
-
)
|
|
|
|
|
|
|
|
|
|
| 641 |
self.limit()
|
| 642 |
|
| 643 |
def limit(self):
|
|
@@ -650,6 +650,31 @@ class MemoryStore:
|
|
| 650 |
def get_recent(self, count=10):
|
| 651 |
return self.items[-count:]
|
| 652 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 653 |
def clear(self):
|
| 654 |
self.items.clear()
|
| 655 |
|
|
@@ -804,6 +829,8 @@ def create_model():
|
|
| 804 |
"weights2": network.weights2,
|
| 805 |
"bias2": network.bias2,
|
| 806 |
"policyTrained": False,
|
|
|
|
|
|
|
| 807 |
},
|
| 808 |
"memory": [],
|
| 809 |
"rules": create_initial_rules(),
|
|
@@ -968,6 +995,12 @@ def merge_models(model_a, model_b, alpha=0.5):
|
|
| 968 |
network_a.get("policyTrained", False)
|
| 969 |
and network_b.get("policyTrained", False)
|
| 970 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 971 |
|
| 972 |
return merged
|
| 973 |
|
|
@@ -1027,7 +1060,9 @@ class AIEngine:
|
|
| 1027 |
bio_signals = self.state.setdefault("bioSignals", create_initial_bio_signals())
|
| 1028 |
for key, value in create_initial_bio_signals().items():
|
| 1029 |
bio_signals.setdefault(key, value)
|
| 1030 |
-
self.state.setdefault("selfModel", create_initial_self_model())
|
|
|
|
|
|
|
| 1031 |
self.workspace = self.state.setdefault("workspace", create_initial_workspace())
|
| 1032 |
self.goals = self.model["goals"]
|
| 1033 |
|
|
@@ -1067,7 +1102,7 @@ class AIEngine:
|
|
| 1067 |
return vector
|
| 1068 |
|
| 1069 |
def observe(self, input_value):
|
| 1070 |
-
return {"input": input_value, "timestamp": now(), "state":
|
| 1071 |
|
| 1072 |
def interpret(self, perception, input_vector=None):
|
| 1073 |
if input_vector is None:
|
|
@@ -1112,7 +1147,7 @@ class AIEngine:
|
|
| 1112 |
signals["novelty"] * 0.6 + signals["stress"] * 0.4, 0, 1
|
| 1113 |
)
|
| 1114 |
|
| 1115 |
-
def open_workspace(self, perception):
|
| 1116 |
input_value = perception["input"]
|
| 1117 |
focus = input_value.get("type", "input") if isinstance(input_value, dict) else "input"
|
| 1118 |
salient_goal = None
|
|
@@ -1131,7 +1166,8 @@ class AIEngine:
|
|
| 1131 |
if score > highest_score:
|
| 1132 |
highest_score = score
|
| 1133 |
salient_goal = goal.get("id")
|
| 1134 |
-
|
|
|
|
| 1135 |
"cycle": self.state["cycle"] + 1,
|
| 1136 |
"focus": focus,
|
| 1137 |
"externalInput": copy.deepcopy(input_value),
|
|
@@ -1145,16 +1181,22 @@ class AIEngine:
|
|
| 1145 |
"prediction": None,
|
| 1146 |
"outcome": None,
|
| 1147 |
"predictionError": 0.0,
|
|
|
|
| 1148 |
"broadcast": {},
|
| 1149 |
}
|
| 1150 |
-
|
| 1151 |
-
|
|
|
|
|
|
|
| 1152 |
|
| 1153 |
def decide(self, perception, workspace=None):
|
| 1154 |
rule = self.rules.select(self.state)
|
| 1155 |
default_action = rule is None or rule["action"]["type"] == "observe"
|
| 1156 |
signals = self.state["bioSignals"]
|
| 1157 |
if workspace and default_action and signals["stress"] < 0.75 and signals["recovery"] > 0.1:
|
|
|
|
|
|
|
|
|
|
| 1158 |
if workspace.get("goal") == "learn":
|
| 1159 |
return {"type": "learn", "ruleId": None}
|
| 1160 |
if workspace.get("goal") == "explore" and signals["novelty"] >= 0.7:
|
|
@@ -1162,22 +1204,76 @@ class AIEngine:
|
|
| 1162 |
if rule and rule["action"]["type"] != "observe":
|
| 1163 |
return {"type": rule["action"]["type"], "ruleId": rule["id"]}
|
| 1164 |
if self.policy_trained and self.network.output_size >= len(ACTION_LABELS):
|
| 1165 |
-
|
| 1166 |
-
outputs = self.network.forward(inputs)["output"]
|
| 1167 |
-
action_index = max(
|
| 1168 |
-
range(len(ACTION_LABELS)), key=lambda index: outputs[index]
|
| 1169 |
-
)
|
| 1170 |
-
return {"type": ACTION_LABELS[action_index], "ruleId": None}
|
| 1171 |
if rule:
|
| 1172 |
return {"type": rule["action"]["type"], "ruleId": rule["id"]}
|
| 1173 |
return {"type": self.behavior.run(self.state), "ruleId": None}
|
| 1174 |
|
| 1175 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1176 |
action_model = self.state["selfModel"]["actions"].get(action["type"], {})
|
| 1177 |
mean_delta = action_model.get("meanDelta", {})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1178 |
return {
|
| 1179 |
key: clamp(self.state[key] + mean_delta.get(key, 0), 0, 100)
|
| 1180 |
-
for key in
|
| 1181 |
}
|
| 1182 |
|
| 1183 |
def update_self_model(self, action, previous_state, prediction):
|
|
@@ -1229,11 +1325,6 @@ class AIEngine:
|
|
| 1229 |
return {"reward": reward, "perception": perception, "action": action, "result": result}
|
| 1230 |
|
| 1231 |
def learn(self, evaluation, input_vector=None):
|
| 1232 |
-
if input_vector is None:
|
| 1233 |
-
input_vector = self.encode_input(evaluation["perception"]["input"])
|
| 1234 |
-
if not self.policy_trained:
|
| 1235 |
-
target = array("f", [evaluation["reward"]]) * self.network.output_size
|
| 1236 |
-
self.network.learn(input_vector, target, CONFIG["LEARNING_RATE"])
|
| 1237 |
action = evaluation["action"]
|
| 1238 |
if action["ruleId"]:
|
| 1239 |
self.rules.reward(action["ruleId"], evaluation["reward"])
|
|
@@ -1244,6 +1335,12 @@ class AIEngine:
|
|
| 1244 |
"result": evaluation["result"],
|
| 1245 |
"reward": evaluation["reward"],
|
| 1246 |
"importance": abs(evaluation["reward"]) * 50 + 50,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1247 |
}
|
| 1248 |
)
|
| 1249 |
if self.random.next() < 0.05:
|
|
@@ -1258,20 +1355,27 @@ class AIEngine:
|
|
| 1258 |
self.state["curiosity"] += 1 if evaluation["reward"] > 0 else -1
|
| 1259 |
self.state["curiosity"] = clamp(self.state["curiosity"], 0, 100)
|
| 1260 |
|
| 1261 |
-
def step(self, input_value, provider_analysis=None):
|
| 1262 |
perception = self.observe(input_value)
|
| 1263 |
self.sense_bio_signals(input_value)
|
| 1264 |
input_vector = self.encode_input(perception["input"])
|
| 1265 |
interpretation = self.interpret(perception, input_vector)
|
| 1266 |
-
workspace
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1267 |
workspace["providerAnalysis"] = copy.deepcopy(provider_analysis)
|
| 1268 |
workspace["internalState"]["bioSignals"] = copy.deepcopy(self.state["bioSignals"])
|
| 1269 |
action = self.decide(perception, workspace)
|
| 1270 |
-
prediction = self.predict_action(action)
|
| 1271 |
workspace["intention"] = action["type"]
|
| 1272 |
workspace["prediction"] = prediction
|
| 1273 |
result = self.execute(action)
|
| 1274 |
self.apply_action_to_bio_signals(action)
|
|
|
|
|
|
|
| 1275 |
prediction_result = self.update_self_model(action, perception["state"], prediction)
|
| 1276 |
workspace["outcome"] = prediction_result["observed"]
|
| 1277 |
workspace["predictionError"] = prediction_result["absoluteError"]
|
|
@@ -1284,13 +1388,13 @@ class AIEngine:
|
|
| 1284 |
"prediction": workspace["prediction"],
|
| 1285 |
"outcome": workspace["outcome"],
|
| 1286 |
"predictionError": workspace["predictionError"],
|
|
|
|
|
|
|
| 1287 |
"bioSignals": copy.deepcopy(self.state["bioSignals"]),
|
| 1288 |
}
|
| 1289 |
-
evaluation = self.evaluate(perception, action, result)
|
| 1290 |
self.learn(evaluation, input_vector)
|
| 1291 |
-
self.update_state(evaluation)
|
| 1292 |
self.sync_model()
|
| 1293 |
-
return {
|
| 1294 |
"perception": perception,
|
| 1295 |
"interpretation": interpretation,
|
| 1296 |
"action": action,
|
|
@@ -1299,22 +1403,25 @@ class AIEngine:
|
|
| 1299 |
"result": result,
|
| 1300 |
"evaluation": evaluation,
|
| 1301 |
"state": self.state,
|
| 1302 |
-
}
|
| 1303 |
|
| 1304 |
def respond(self, input_value, provider=None):
|
| 1305 |
"""Generate a provider reply, then run one local engine step."""
|
| 1306 |
active_provider = provider or self.provider or LLMProvider()
|
|
|
|
|
|
|
|
|
|
| 1307 |
provider_context = {
|
| 1308 |
"user_input": input_value,
|
| 1309 |
-
"state":
|
| 1310 |
-
"memories":
|
| 1311 |
}
|
| 1312 |
if hasattr(active_provider, "generate_with_analysis"):
|
| 1313 |
provider_response = active_provider.generate_with_analysis(**provider_context)
|
| 1314 |
else:
|
| 1315 |
provider_response = active_provider.generate(**provider_context)
|
| 1316 |
normalized = normalize_provider_response(provider_response)
|
| 1317 |
-
result = self.step(input_value, provider_analysis=normalized["analysis"])
|
| 1318 |
result["reply"] = normalized["reply"]
|
| 1319 |
return result
|
| 1320 |
|
|
@@ -1365,6 +1472,202 @@ class AIEngine:
|
|
| 1365 |
return self.behavior.program
|
| 1366 |
|
| 1367 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1368 |
if __name__ == "__main__":
|
| 1369 |
parser = argparse.ArgumentParser(description="Create or train a Noesis model.")
|
| 1370 |
training_modes = parser.add_mutually_exclusive_group()
|
|
|
|
| 96 |
return minimum + self.next() * (maximum - minimum)
|
| 97 |
|
| 98 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
def create_initial_self_model():
|
| 100 |
return {
|
| 101 |
"actions": {},
|
|
|
|
| 113 |
|
| 114 |
def create_initial_workspace():
|
| 115 |
return {
|
| 116 |
+
"version": 2,
|
| 117 |
"cycle": 0,
|
| 118 |
"focus": "idle",
|
| 119 |
"externalInput": None,
|
|
|
|
| 124 |
"prediction": None,
|
| 125 |
"outcome": None,
|
| 126 |
"predictionError": 0.0,
|
| 127 |
+
"memories": [],
|
| 128 |
"broadcast": {},
|
| 129 |
}
|
| 130 |
|
|
|
|
| 407 |
sample_count = len(examples)
|
| 408 |
return {
|
| 409 |
"accuracy": correct / sample_count,
|
| 410 |
+
"baseline_accuracy": max(class_totals.values()) / sample_count,
|
| 411 |
"rule_baseline_accuracy": rule_baseline_correct / sample_count,
|
| 412 |
"mse": squared_error / (sample_count * len(ACTION_LABELS)),
|
| 413 |
"per_action_accuracy": {
|
|
|
|
| 530 |
"weights2": network.weights2,
|
| 531 |
"bias2": network.bias2,
|
| 532 |
"policyTrained": True,
|
| 533 |
+
"trainingMethod": "threshold-imitation-v1",
|
| 534 |
+
"featureSchema": "action-state-text-v1",
|
| 535 |
}
|
| 536 |
model["updatedAt"] = now()
|
| 537 |
gguf_path = os.path.splitext(os.fsdecode(path))[0] + ".F32.gguf"
|
|
|
|
| 609 |
"bias1": network.bias1,
|
| 610 |
"weights2": network.weights2,
|
| 611 |
"bias2": network.bias2,
|
| 612 |
+
"trainingMethod": "pixel-steering-v1",
|
| 613 |
+
"featureSchema": "pixel-steering-v1",
|
| 614 |
}
|
| 615 |
model["updatedAt"] = now()
|
| 616 |
gguf_path = os.path.splitext(os.fsdecode(path))[0] + ".F32.gguf"
|
|
|
|
| 625 |
self.items = memory if memory is not None else []
|
| 626 |
|
| 627 |
def add(self, memory):
|
| 628 |
+
item = {
|
|
|
|
| 629 |
"id": uuid_bytes(),
|
| 630 |
"timestamp": now(),
|
| 631 |
"input": memory.get("input"),
|
|
|
|
| 634 |
"reward": memory.get("reward"),
|
| 635 |
"importance": clamp(memory.get("importance", 50), 0, 100),
|
| 636 |
}
|
| 637 |
+
for key in ("previousState", "prediction", "outcome"):
|
| 638 |
+
if key in memory:
|
| 639 |
+
item[key] = copy.deepcopy(memory[key])
|
| 640 |
+
self.items.append(item)
|
| 641 |
self.limit()
|
| 642 |
|
| 643 |
def limit(self):
|
|
|
|
| 650 |
def get_recent(self, count=10):
|
| 651 |
return self.items[-count:]
|
| 652 |
|
| 653 |
+
def recall(self, input_value, count=3):
|
| 654 |
+
text = input_value.get("value") if isinstance(input_value, dict) else None
|
| 655 |
+
tokens = set(text.lower().split()) if isinstance(text, str) else set()
|
| 656 |
+
if not tokens:
|
| 657 |
+
return []
|
| 658 |
+
matches = []
|
| 659 |
+
for index, item in enumerate(self.items):
|
| 660 |
+
stored_input = item.get("input")
|
| 661 |
+
stored_text = stored_input.get("value") if isinstance(stored_input, dict) else None
|
| 662 |
+
if not isinstance(stored_text, str):
|
| 663 |
+
continue
|
| 664 |
+
stored_tokens = set(stored_text.lower().split())
|
| 665 |
+
overlap = len(tokens & stored_tokens)
|
| 666 |
+
if not overlap:
|
| 667 |
+
continue
|
| 668 |
+
relevance = overlap / len(tokens | stored_tokens)
|
| 669 |
+
recency = (index + 1) / max(len(self.items), 1)
|
| 670 |
+
matches.append((relevance, recency, item))
|
| 671 |
+
matches.sort(key=lambda match: (match[0], match[1]), reverse=True)
|
| 672 |
+
return [
|
| 673 |
+
{"episode": copy.deepcopy(item), "relevance": relevance,
|
| 674 |
+
"recency": recency, "uncertainty": 1 - relevance}
|
| 675 |
+
for relevance, recency, item in matches[:count]
|
| 676 |
+
]
|
| 677 |
+
|
| 678 |
def clear(self):
|
| 679 |
self.items.clear()
|
| 680 |
|
|
|
|
| 829 |
"weights2": network.weights2,
|
| 830 |
"bias2": network.bias2,
|
| 831 |
"policyTrained": False,
|
| 832 |
+
"trainingMethod": "untrained",
|
| 833 |
+
"featureSchema": "action-state-text-v1",
|
| 834 |
},
|
| 835 |
"memory": [],
|
| 836 |
"rules": create_initial_rules(),
|
|
|
|
| 995 |
network_a.get("policyTrained", False)
|
| 996 |
and network_b.get("policyTrained", False)
|
| 997 |
)
|
| 998 |
+
merged["network"]["trainingMethod"] = "weight-merge-v1"
|
| 999 |
+
merged["network"]["featureSchema"] = (
|
| 1000 |
+
network_a.get("featureSchema", "unspecified")
|
| 1001 |
+
if network_a.get("featureSchema") == network_b.get("featureSchema")
|
| 1002 |
+
else "unspecified"
|
| 1003 |
+
)
|
| 1004 |
|
| 1005 |
return merged
|
| 1006 |
|
|
|
|
| 1060 |
bio_signals = self.state.setdefault("bioSignals", create_initial_bio_signals())
|
| 1061 |
for key, value in create_initial_bio_signals().items():
|
| 1062 |
bio_signals.setdefault(key, value)
|
| 1063 |
+
self_model = self.state.setdefault("selfModel", create_initial_self_model())
|
| 1064 |
+
for key, value in create_initial_self_model().items():
|
| 1065 |
+
self_model.setdefault(key, value)
|
| 1066 |
self.workspace = self.state.setdefault("workspace", create_initial_workspace())
|
| 1067 |
self.goals = self.model["goals"]
|
| 1068 |
|
|
|
|
| 1102 |
return vector
|
| 1103 |
|
| 1104 |
def observe(self, input_value):
|
| 1105 |
+
return {"input": copy.deepcopy(input_value), "timestamp": now(), "state": copy.deepcopy(self.state)}
|
| 1106 |
|
| 1107 |
def interpret(self, perception, input_vector=None):
|
| 1108 |
if input_vector is None:
|
|
|
|
| 1147 |
signals["novelty"] * 0.6 + signals["stress"] * 0.4, 0, 1
|
| 1148 |
)
|
| 1149 |
|
| 1150 |
+
def open_workspace(self, perception, persist=True):
|
| 1151 |
input_value = perception["input"]
|
| 1152 |
focus = input_value.get("type", "input") if isinstance(input_value, dict) else "input"
|
| 1153 |
salient_goal = None
|
|
|
|
| 1166 |
if score > highest_score:
|
| 1167 |
highest_score = score
|
| 1168 |
salient_goal = goal.get("id")
|
| 1169 |
+
workspace = {
|
| 1170 |
+
"version": 2,
|
| 1171 |
"cycle": self.state["cycle"] + 1,
|
| 1172 |
"focus": focus,
|
| 1173 |
"externalInput": copy.deepcopy(input_value),
|
|
|
|
| 1181 |
"prediction": None,
|
| 1182 |
"outcome": None,
|
| 1183 |
"predictionError": 0.0,
|
| 1184 |
+
"memories": self.memory.recall(input_value),
|
| 1185 |
"broadcast": {},
|
| 1186 |
}
|
| 1187 |
+
if persist:
|
| 1188 |
+
self.workspace = workspace
|
| 1189 |
+
self.state["workspace"] = workspace
|
| 1190 |
+
return workspace
|
| 1191 |
|
| 1192 |
def decide(self, perception, workspace=None):
|
| 1193 |
rule = self.rules.select(self.state)
|
| 1194 |
default_action = rule is None or rule["action"]["type"] == "observe"
|
| 1195 |
signals = self.state["bioSignals"]
|
| 1196 |
if workspace and default_action and signals["stress"] < 0.75 and signals["recovery"] > 0.1:
|
| 1197 |
+
predicted_action = self.select_predicted_action(workspace)
|
| 1198 |
+
if predicted_action is not None:
|
| 1199 |
+
return {"type": predicted_action, "ruleId": None}
|
| 1200 |
if workspace.get("goal") == "learn":
|
| 1201 |
return {"type": "learn", "ruleId": None}
|
| 1202 |
if workspace.get("goal") == "explore" and signals["novelty"] >= 0.7:
|
|
|
|
| 1204 |
if rule and rule["action"]["type"] != "observe":
|
| 1205 |
return {"type": rule["action"]["type"], "ruleId": rule["id"]}
|
| 1206 |
if self.policy_trained and self.network.output_size >= len(ACTION_LABELS):
|
| 1207 |
+
return {"type": self._policy_action(perception), "ruleId": None}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1208 |
if rule:
|
| 1209 |
return {"type": rule["action"]["type"], "ruleId": rule["id"]}
|
| 1210 |
return {"type": self.behavior.run(self.state), "ruleId": None}
|
| 1211 |
|
| 1212 |
+
def select_predicted_action(self, workspace=None):
|
| 1213 |
+
best_action = None
|
| 1214 |
+
best_score = 0.0
|
| 1215 |
+
if workspace is not None:
|
| 1216 |
+
workspace["candidates"] = []
|
| 1217 |
+
for action_type in ACTION_LABELS:
|
| 1218 |
+
action_model = self.state["selfModel"]["actions"].get(action_type, {})
|
| 1219 |
+
count = action_model.get("count", 0)
|
| 1220 |
+
if count <= 0:
|
| 1221 |
+
continue
|
| 1222 |
+
prediction = self.predict_action({"type": action_type}, workspace)
|
| 1223 |
+
if prediction["energy"] < 20:
|
| 1224 |
+
continue
|
| 1225 |
+
score = 0.0
|
| 1226 |
+
for goal in self.goals:
|
| 1227 |
+
for key, target in goal.get("target", {}).items():
|
| 1228 |
+
state_key = key[:-3] if key.endswith("Min") else key
|
| 1229 |
+
if state_key not in prediction:
|
| 1230 |
+
continue
|
| 1231 |
+
before = max(0, target - self.state[state_key])
|
| 1232 |
+
after = max(0, target - prediction[state_key])
|
| 1233 |
+
score += goal.get("priority", 0) * (before - after)
|
| 1234 |
+
score *= count / (count + 1)
|
| 1235 |
+
if workspace is not None:
|
| 1236 |
+
workspace["candidates"].append({
|
| 1237 |
+
"action": action_type, "prediction": prediction,
|
| 1238 |
+
"observations": count, "uncertainty": 1 / (count + 1),
|
| 1239 |
+
"goalScore": score,
|
| 1240 |
+
})
|
| 1241 |
+
if score > best_score:
|
| 1242 |
+
best_action = action_type
|
| 1243 |
+
best_score = score
|
| 1244 |
+
return best_action
|
| 1245 |
+
|
| 1246 |
+
def _policy_action(self, perception):
|
| 1247 |
+
outputs = self.network.forward(self.encode_input(perception["input"]))["output"]
|
| 1248 |
+
return ACTION_LABELS[max(range(len(ACTION_LABELS)), key=lambda index: outputs[index])]
|
| 1249 |
+
|
| 1250 |
+
def predict_action(self, action, workspace=None):
|
| 1251 |
action_model = self.state["selfModel"]["actions"].get(action["type"], {})
|
| 1252 |
mean_delta = action_model.get("meanDelta", {})
|
| 1253 |
+
metrics = ("energy", "curiosity", "confidence")
|
| 1254 |
+
episodes = []
|
| 1255 |
+
for match in (workspace or {}).get("memories", []):
|
| 1256 |
+
episode = match["episode"]
|
| 1257 |
+
previous = episode.get("previousState")
|
| 1258 |
+
outcome = episode.get("outcome")
|
| 1259 |
+
if episode.get("action") != action["type"] or not isinstance(previous, dict) or not isinstance(outcome, dict):
|
| 1260 |
+
continue
|
| 1261 |
+
if all(
|
| 1262 |
+
isinstance(values.get(key), (int, float))
|
| 1263 |
+
and not isinstance(values[key], bool)
|
| 1264 |
+
and math.isfinite(values[key])
|
| 1265 |
+
for values in (previous, outcome) for key in metrics
|
| 1266 |
+
):
|
| 1267 |
+
episodes.append(episode)
|
| 1268 |
+
if episodes:
|
| 1269 |
+
mean_delta = {
|
| 1270 |
+
key: sum(episode["outcome"][key] - episode["previousState"][key]
|
| 1271 |
+
for episode in episodes) / len(episodes)
|
| 1272 |
+
for key in metrics
|
| 1273 |
+
}
|
| 1274 |
return {
|
| 1275 |
key: clamp(self.state[key] + mean_delta.get(key, 0), 0, 100)
|
| 1276 |
+
for key in metrics
|
| 1277 |
}
|
| 1278 |
|
| 1279 |
def update_self_model(self, action, previous_state, prediction):
|
|
|
|
| 1325 |
return {"reward": reward, "perception": perception, "action": action, "result": result}
|
| 1326 |
|
| 1327 |
def learn(self, evaluation, input_vector=None):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1328 |
action = evaluation["action"]
|
| 1329 |
if action["ruleId"]:
|
| 1330 |
self.rules.reward(action["ruleId"], evaluation["reward"])
|
|
|
|
| 1335 |
"result": evaluation["result"],
|
| 1336 |
"reward": evaluation["reward"],
|
| 1337 |
"importance": abs(evaluation["reward"]) * 50 + 50,
|
| 1338 |
+
"previousState": {
|
| 1339 |
+
key: evaluation["perception"]["state"][key]
|
| 1340 |
+
for key in ("energy", "curiosity", "confidence")
|
| 1341 |
+
},
|
| 1342 |
+
"prediction": self.workspace["prediction"],
|
| 1343 |
+
"outcome": self.workspace["outcome"],
|
| 1344 |
}
|
| 1345 |
)
|
| 1346 |
if self.random.next() < 0.05:
|
|
|
|
| 1355 |
self.state["curiosity"] += 1 if evaluation["reward"] > 0 else -1
|
| 1356 |
self.state["curiosity"] = clamp(self.state["curiosity"], 0, 100)
|
| 1357 |
|
| 1358 |
+
def step(self, input_value, provider_analysis=None, workspace=None):
|
| 1359 |
perception = self.observe(input_value)
|
| 1360 |
self.sense_bio_signals(input_value)
|
| 1361 |
input_vector = self.encode_input(perception["input"])
|
| 1362 |
interpretation = self.interpret(perception, input_vector)
|
| 1363 |
+
if workspace is None:
|
| 1364 |
+
workspace = self.open_workspace(perception)
|
| 1365 |
+
else:
|
| 1366 |
+
workspace = copy.deepcopy(workspace)
|
| 1367 |
+
self.workspace = workspace
|
| 1368 |
+
self.state["workspace"] = workspace
|
| 1369 |
workspace["providerAnalysis"] = copy.deepcopy(provider_analysis)
|
| 1370 |
workspace["internalState"]["bioSignals"] = copy.deepcopy(self.state["bioSignals"])
|
| 1371 |
action = self.decide(perception, workspace)
|
| 1372 |
+
prediction = self.predict_action(action, workspace)
|
| 1373 |
workspace["intention"] = action["type"]
|
| 1374 |
workspace["prediction"] = prediction
|
| 1375 |
result = self.execute(action)
|
| 1376 |
self.apply_action_to_bio_signals(action)
|
| 1377 |
+
evaluation = self.evaluate(perception, action, result)
|
| 1378 |
+
self.update_state(evaluation)
|
| 1379 |
prediction_result = self.update_self_model(action, perception["state"], prediction)
|
| 1380 |
workspace["outcome"] = prediction_result["observed"]
|
| 1381 |
workspace["predictionError"] = prediction_result["absoluteError"]
|
|
|
|
| 1388 |
"prediction": workspace["prediction"],
|
| 1389 |
"outcome": workspace["outcome"],
|
| 1390 |
"predictionError": workspace["predictionError"],
|
| 1391 |
+
"memories": workspace["memories"],
|
| 1392 |
+
"candidates": workspace.get("candidates", []),
|
| 1393 |
"bioSignals": copy.deepcopy(self.state["bioSignals"]),
|
| 1394 |
}
|
|
|
|
| 1395 |
self.learn(evaluation, input_vector)
|
|
|
|
| 1396 |
self.sync_model()
|
| 1397 |
+
return copy.deepcopy({
|
| 1398 |
"perception": perception,
|
| 1399 |
"interpretation": interpretation,
|
| 1400 |
"action": action,
|
|
|
|
| 1403 |
"result": result,
|
| 1404 |
"evaluation": evaluation,
|
| 1405 |
"state": self.state,
|
| 1406 |
+
})
|
| 1407 |
|
| 1408 |
def respond(self, input_value, provider=None):
|
| 1409 |
"""Generate a provider reply, then run one local engine step."""
|
| 1410 |
active_provider = provider or self.provider or LLMProvider()
|
| 1411 |
+
workspace = self.open_workspace(self.observe(input_value), persist=False)
|
| 1412 |
+
provider_state = copy.deepcopy(self.state)
|
| 1413 |
+
provider_state["workspace"] = copy.deepcopy(workspace)
|
| 1414 |
provider_context = {
|
| 1415 |
"user_input": input_value,
|
| 1416 |
+
"state": provider_state,
|
| 1417 |
+
"memories": [match["episode"] for match in workspace["memories"]],
|
| 1418 |
}
|
| 1419 |
if hasattr(active_provider, "generate_with_analysis"):
|
| 1420 |
provider_response = active_provider.generate_with_analysis(**provider_context)
|
| 1421 |
else:
|
| 1422 |
provider_response = active_provider.generate(**provider_context)
|
| 1423 |
normalized = normalize_provider_response(provider_response)
|
| 1424 |
+
result = self.step(input_value, provider_analysis=normalized["analysis"], workspace=workspace)
|
| 1425 |
result["reply"] = normalized["reply"]
|
| 1426 |
return result
|
| 1427 |
|
|
|
|
| 1472 |
return self.behavior.program
|
| 1473 |
|
| 1474 |
|
| 1475 |
+
def evaluate_action_scenarios(model, scenarios):
|
| 1476 |
+
"""Compare prediction-informed, policy-only, and threshold-baseline behavior."""
|
| 1477 |
+
if not isinstance(model, dict):
|
| 1478 |
+
model = load_model_file(model)
|
| 1479 |
+
validate_model(model)
|
| 1480 |
+
if not model["network"].get("policyTrained") or model["network"]["outputSize"] < len(ACTION_LABELS):
|
| 1481 |
+
raise ValueError("A trained action policy is required.")
|
| 1482 |
+
if not isinstance(scenarios, list) or not scenarios:
|
| 1483 |
+
raise ValueError("scenarios must be a non-empty list.")
|
| 1484 |
+
|
| 1485 |
+
class PolicyEngine(AIEngine):
|
| 1486 |
+
def select_predicted_action(self, workspace=None):
|
| 1487 |
+
return None
|
| 1488 |
+
|
| 1489 |
+
class BaselineEngine(PolicyEngine):
|
| 1490 |
+
def _policy_action(self, perception):
|
| 1491 |
+
return _action_policy_target(
|
| 1492 |
+
self.state["energy"], self.state["curiosity"], self.state["confidence"]
|
| 1493 |
+
)
|
| 1494 |
+
|
| 1495 |
+
state_keys = ("energy", "curiosity", "confidence", "stability")
|
| 1496 |
+
runs = {"prediction": [], "policy": [], "rule_baseline": []}
|
| 1497 |
+
for scenario in scenarios:
|
| 1498 |
+
if not isinstance(scenario, dict):
|
| 1499 |
+
raise ValueError("Each scenario must be an object.")
|
| 1500 |
+
initial = scenario.get("initial_state", {})
|
| 1501 |
+
inputs = scenario.get("inputs")
|
| 1502 |
+
objectives = scenario.get("objectives")
|
| 1503 |
+
if not isinstance(initial, dict) or any(key not in state_keys for key in initial):
|
| 1504 |
+
raise ValueError("initial_state must contain only supported state values.")
|
| 1505 |
+
if not isinstance(inputs, list) or not inputs:
|
| 1506 |
+
raise ValueError("Each scenario must contain a non-empty inputs list.")
|
| 1507 |
+
if not isinstance(objectives, dict) or not objectives:
|
| 1508 |
+
raise ValueError("Each scenario must contain objectives.")
|
| 1509 |
+
for key, value in initial.items():
|
| 1510 |
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not 0 <= value <= 100:
|
| 1511 |
+
raise ValueError(f"Invalid initial state value for {key}.")
|
| 1512 |
+
for key, bounds in objectives.items():
|
| 1513 |
+
if key not in state_keys or not isinstance(bounds, dict) or not bounds or any(bound not in ("min", "max") for bound in bounds):
|
| 1514 |
+
raise ValueError("Objectives must specify min or max for supported state values.")
|
| 1515 |
+
for value in bounds.values():
|
| 1516 |
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not 0 <= value <= 100:
|
| 1517 |
+
raise ValueError("Objective bounds must be finite values between 0 and 100.")
|
| 1518 |
+
if "min" in bounds and "max" in bounds and bounds["min"] > bounds["max"]:
|
| 1519 |
+
raise ValueError("Objective min cannot exceed max.")
|
| 1520 |
+
|
| 1521 |
+
scenario_model = copy.deepcopy(model)
|
| 1522 |
+
if "goals" in scenario:
|
| 1523 |
+
scenario_model["goals"] = copy.deepcopy(scenario["goals"])
|
| 1524 |
+
validate_model(scenario_model)
|
| 1525 |
+
for label, engine_type in (("prediction", AIEngine), ("policy", PolicyEngine), ("rule_baseline", BaselineEngine)):
|
| 1526 |
+
engine = engine_type(copy.deepcopy(scenario_model))
|
| 1527 |
+
engine.state.update(initial)
|
| 1528 |
+
actions = []
|
| 1529 |
+
total_reward = 0.0
|
| 1530 |
+
prediction_error = 0.0
|
| 1531 |
+
minimum_energy = engine.state["energy"]
|
| 1532 |
+
for input_value in inputs:
|
| 1533 |
+
result = engine.step(copy.deepcopy(input_value))
|
| 1534 |
+
actions.append(result["action"]["type"])
|
| 1535 |
+
total_reward += result["evaluation"]["reward"]
|
| 1536 |
+
prediction_error += result["prediction"]["absoluteError"]
|
| 1537 |
+
minimum_energy = min(minimum_energy, result["state"]["energy"])
|
| 1538 |
+
final_state = {key: engine.state[key] for key in state_keys}
|
| 1539 |
+
succeeded = all(
|
| 1540 |
+
("min" not in bounds or final_state[key] >= bounds["min"])
|
| 1541 |
+
and ("max" not in bounds or final_state[key] <= bounds["max"])
|
| 1542 |
+
for key, bounds in objectives.items()
|
| 1543 |
+
)
|
| 1544 |
+
runs[label].append({
|
| 1545 |
+
"actions": actions,
|
| 1546 |
+
"total_reward": total_reward,
|
| 1547 |
+
"mean_prediction_error": prediction_error / len(inputs),
|
| 1548 |
+
"minimum_energy": minimum_energy,
|
| 1549 |
+
"final_state": final_state,
|
| 1550 |
+
"success": succeeded,
|
| 1551 |
+
})
|
| 1552 |
+
return {
|
| 1553 |
+
label: {
|
| 1554 |
+
"success_rate": sum(run["success"] for run in results) / len(results),
|
| 1555 |
+
"mean_total_reward": sum(run["total_reward"] for run in results) / len(results),
|
| 1556 |
+
"mean_prediction_error": sum(run["mean_prediction_error"] for run in results) / len(results),
|
| 1557 |
+
"scenarios": results,
|
| 1558 |
+
}
|
| 1559 |
+
for label, results in runs.items()
|
| 1560 |
+
}
|
| 1561 |
+
|
| 1562 |
+
|
| 1563 |
+
def train_action_model_from_episodes(path, training_episodes, validation_episodes, *, test_scenarios=None, epochs=20, seed=1):
|
| 1564 |
+
"""Train on successful caller-provided demonstrations, validated on separate episodes."""
|
| 1565 |
+
if not isinstance(epochs, int) or isinstance(epochs, bool) or epochs < 1:
|
| 1566 |
+
raise ValueError("epochs must be a positive integer.")
|
| 1567 |
+
if not isinstance(seed, int) or isinstance(seed, bool):
|
| 1568 |
+
raise ValueError("seed must be an integer.")
|
| 1569 |
+
if any(not isinstance(episodes, list) or not episodes for episodes in (training_episodes, validation_episodes)):
|
| 1570 |
+
raise ValueError("Training and validation episodes must be non-empty lists.")
|
| 1571 |
+
if any(not isinstance(episode, dict) for episode in training_episodes + validation_episodes):
|
| 1572 |
+
raise ValueError("Each episode must be an object.")
|
| 1573 |
+
try:
|
| 1574 |
+
training_ids = {json.dumps(episode, sort_keys=True, allow_nan=False) for episode in training_episodes}
|
| 1575 |
+
validation_ids = {json.dumps(episode, sort_keys=True, allow_nan=False) for episode in validation_episodes}
|
| 1576 |
+
except (TypeError, ValueError) as error:
|
| 1577 |
+
raise ValueError("Episodes must contain finite JSON values.") from error
|
| 1578 |
+
if training_ids & validation_ids:
|
| 1579 |
+
raise ValueError("Training and validation episodes must be distinct.")
|
| 1580 |
+
def scenario_id(episode):
|
| 1581 |
+
return json.dumps(
|
| 1582 |
+
{key: episode.get(key, {} if key in ("initial_state", "goals") else None)
|
| 1583 |
+
for key in ("initial_state", "inputs", "objectives", "goals")},
|
| 1584 |
+
sort_keys=True, allow_nan=False,
|
| 1585 |
+
)
|
| 1586 |
+
|
| 1587 |
+
if {scenario_id(episode) for episode in training_episodes} & {scenario_id(episode) for episode in validation_episodes}:
|
| 1588 |
+
raise ValueError("Training and validation scenarios must be distinct.")
|
| 1589 |
+
if test_scenarios is not None:
|
| 1590 |
+
if not isinstance(test_scenarios, list) or not test_scenarios or any(not isinstance(item, dict) for item in test_scenarios):
|
| 1591 |
+
raise ValueError("test_scenarios must be a non-empty list of objects.")
|
| 1592 |
+
try:
|
| 1593 |
+
used = {scenario_id(episode) for episode in training_episodes + validation_episodes}
|
| 1594 |
+
if any(scenario_id(scenario) in used for scenario in test_scenarios):
|
| 1595 |
+
raise ValueError("Test scenarios must be distinct from training and validation episodes.")
|
| 1596 |
+
except (TypeError, AttributeError) as error:
|
| 1597 |
+
raise ValueError("Scenarios must contain finite JSON values.") from error
|
| 1598 |
+
|
| 1599 |
+
class DemonstrationEngine(AIEngine):
|
| 1600 |
+
def decide(self, perception, workspace=None):
|
| 1601 |
+
rule = self.rules.select(self.state)
|
| 1602 |
+
if rule and rule["action"]["type"] != "observe":
|
| 1603 |
+
if rule["action"]["type"] != self.demonstrated_action:
|
| 1604 |
+
raise ValueError("A demonstrated action conflicts with a rule override.")
|
| 1605 |
+
return {"type": self.demonstrated_action, "ruleId": rule["id"]}
|
| 1606 |
+
return {"type": self.demonstrated_action, "ruleId": None}
|
| 1607 |
+
|
| 1608 |
+
template = create_model()
|
| 1609 |
+
template["network"]["policyTrained"] = True
|
| 1610 |
+
|
| 1611 |
+
def collect(episodes):
|
| 1612 |
+
examples = []
|
| 1613 |
+
for episode in episodes:
|
| 1614 |
+
if not isinstance(episode, dict):
|
| 1615 |
+
raise ValueError("Each episode must be an object.")
|
| 1616 |
+
inputs = episode.get("inputs")
|
| 1617 |
+
actions = episode.get("actions")
|
| 1618 |
+
if not isinstance(inputs, list) or not isinstance(actions, list) or len(inputs) != len(actions) or not inputs:
|
| 1619 |
+
raise ValueError("Episode inputs and actions must be non-empty lists of equal length.")
|
| 1620 |
+
if any(action not in ACTION_LABELS for action in actions):
|
| 1621 |
+
raise ValueError("Episode contains an unsupported action.")
|
| 1622 |
+
scenario = {key: episode[key] for key in ("initial_state", "inputs", "objectives", "goals") if key in episode}
|
| 1623 |
+
evaluate_action_scenarios(template, [scenario])
|
| 1624 |
+
model = copy.deepcopy(template)
|
| 1625 |
+
if "goals" in episode:
|
| 1626 |
+
model["goals"] = copy.deepcopy(episode["goals"])
|
| 1627 |
+
engine = DemonstrationEngine(model)
|
| 1628 |
+
engine.state.update(episode.get("initial_state", {}))
|
| 1629 |
+
for input_value, action in zip(inputs, actions):
|
| 1630 |
+
examples.append((engine.encode_input(input_value), action))
|
| 1631 |
+
engine.demonstrated_action = action
|
| 1632 |
+
engine.step(copy.deepcopy(input_value))
|
| 1633 |
+
for key, bounds in episode["objectives"].items():
|
| 1634 |
+
if ("min" in bounds and engine.state[key] < bounds["min"]) or ("max" in bounds and engine.state[key] > bounds["max"]):
|
| 1635 |
+
raise ValueError("Demonstration does not satisfy its final-state objectives.")
|
| 1636 |
+
return examples
|
| 1637 |
+
|
| 1638 |
+
examples = collect(training_episodes)
|
| 1639 |
+
validation = collect(validation_episodes)
|
| 1640 |
+
random = Random(seed)
|
| 1641 |
+
network = TinyNetwork(random)
|
| 1642 |
+
best_weights = None
|
| 1643 |
+
best_score = (-1.0, float("-inf"))
|
| 1644 |
+
for _ in range(epochs):
|
| 1645 |
+
for index in range(len(examples) - 1, 0, -1):
|
| 1646 |
+
swap_index = int(random.next() * (index + 1))
|
| 1647 |
+
examples[index], examples[swap_index] = examples[swap_index], examples[index]
|
| 1648 |
+
for inputs, action in examples:
|
| 1649 |
+
targets = array("f", [0]) * network.output_size
|
| 1650 |
+
targets[ACTION_LABELS.index(action)] = 1
|
| 1651 |
+
network.learn(inputs, targets, 0.03)
|
| 1652 |
+
metrics = _action_policy_metrics(network, validation)
|
| 1653 |
+
score = (metrics["accuracy"], -metrics["mse"])
|
| 1654 |
+
if score > best_score:
|
| 1655 |
+
best_score = score
|
| 1656 |
+
best_weights = {key: array("f", getattr(network, key)) for key in ("weights1", "bias1", "weights2", "bias2")}
|
| 1657 |
+
model = create_model()
|
| 1658 |
+
model["randomSeed"] = random.seed
|
| 1659 |
+
model["network"].update(best_weights)
|
| 1660 |
+
model["network"]["policyTrained"] = True
|
| 1661 |
+
model["network"]["trainingMethod"] = "demonstrations-v1"
|
| 1662 |
+
model["network"]["featureSchema"] = "action-state-text-v1"
|
| 1663 |
+
gguf_path = os.path.splitext(os.fsdecode(path))[0] + ".F32.gguf"
|
| 1664 |
+
report = {"validation": _action_policy_metrics(_network_from_model(model), validation)}
|
| 1665 |
+
if test_scenarios is not None:
|
| 1666 |
+
report["test_scenarios"] = evaluate_action_scenarios(model, test_scenarios)
|
| 1667 |
+
_write_model_artifacts(((path, serialize_model(model)), (gguf_path, serialize_gguf_model(model))))
|
| 1668 |
+
return model, report
|
| 1669 |
+
|
| 1670 |
+
|
| 1671 |
if __name__ == "__main__":
|
| 1672 |
parser = argparse.ArgumentParser(description="Create or train a Noesis model.")
|
| 1673 |
training_modes = parser.add_mutually_exclusive_group()
|
model_formats.py
CHANGED
|
@@ -172,6 +172,9 @@ def validate_model(model):
|
|
| 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,
|
|
@@ -212,6 +215,8 @@ def serialize_model(model):
|
|
| 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(
|
|
@@ -245,8 +250,12 @@ def serialize_gguf_model(model):
|
|
| 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,
|
| 249 |
("noesis.workspace_format", 8, "cycle_snapshot"),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
)
|
| 251 |
metadata_bytes = bytearray()
|
| 252 |
for key, value_type, value in metadata:
|
|
@@ -331,6 +340,8 @@ def deserialize_model(buffer):
|
|
| 331 |
"weights2": arrays[2],
|
| 332 |
"bias2": arrays[3],
|
| 333 |
"policyTrained": metadata.get("policyTrained", False),
|
|
|
|
|
|
|
| 334 |
},
|
| 335 |
"memory": metadata["memory"],
|
| 336 |
"rules": metadata["rules"],
|
|
|
|
| 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 |
+
for key in ("trainingMethod", "featureSchema"):
|
| 176 |
+
if key in network and (not isinstance(network[key], str) or not network[key] or len(network[key]) > 128):
|
| 177 |
+
raise ValueError(f"Model network {key} must be a non-empty string of at most 128 characters.")
|
| 178 |
expected_lengths = {
|
| 179 |
"weights1": input_size * hidden_size,
|
| 180 |
"bias1": hidden_size,
|
|
|
|
| 215 |
"outputSize": network["outputSize"],
|
| 216 |
},
|
| 217 |
"policyTrained": bool(network.get("policyTrained", False)),
|
| 218 |
+
"trainingMethod": network.get("trainingMethod", "unspecified"),
|
| 219 |
+
"featureSchema": network.get("featureSchema", "unspecified"),
|
| 220 |
}
|
| 221 |
metadata_bytes = json.dumps(metadata, separators=(",", ":"), allow_nan=False).encode("utf-8")
|
| 222 |
network_bytes = b"".join(
|
|
|
|
| 250 |
("noesis.input_size", 4, network["inputSize"]),
|
| 251 |
("noesis.hidden_size", 4, network["hiddenSize"]),
|
| 252 |
("noesis.output_size", 4, network["outputSize"]),
|
| 253 |
+
("noesis.workspace_version", 4, 2),
|
| 254 |
("noesis.workspace_format", 8, "cycle_snapshot"),
|
| 255 |
+
("noesis.policy_trained", 4, int(network.get("policyTrained", False))),
|
| 256 |
+
("noesis.training_method", 8, network.get("trainingMethod", "unspecified")),
|
| 257 |
+
("noesis.feature_schema", 8, network.get("featureSchema", "unspecified")),
|
| 258 |
+
("noesis.tensor_layout", 8, "output-major-f32"),
|
| 259 |
)
|
| 260 |
metadata_bytes = bytearray()
|
| 261 |
for key, value_type, value in metadata:
|
|
|
|
| 340 |
"weights2": arrays[2],
|
| 341 |
"bias2": arrays[3],
|
| 342 |
"policyTrained": metadata.get("policyTrained", False),
|
| 343 |
+
"trainingMethod": metadata.get("trainingMethod", "unspecified"),
|
| 344 |
+
"featureSchema": metadata.get("featureSchema", "unspecified"),
|
| 345 |
},
|
| 346 |
"memory": metadata["memory"],
|
| 347 |
"rules": metadata["rules"],
|
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
|
|
|