simthinkd 0.5.0__tar.gz → 0.6.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. {simthinkd-0.5.0/src/simthinkd.egg-info → simthinkd-0.6.0}/PKG-INFO +5 -1
  2. {simthinkd-0.5.0 → simthinkd-0.6.0}/README.md +4 -0
  3. {simthinkd-0.5.0 → simthinkd-0.6.0}/pyproject.toml +1 -1
  4. {simthinkd-0.5.0 → simthinkd-0.6.0}/src/simthinkd/__init__.py +1 -1
  5. {simthinkd-0.5.0 → simthinkd-0.6.0}/src/simthinkd/core.py +58 -17
  6. simthinkd-0.6.0/src/simthinkd/embeddings.py +88 -0
  7. simthinkd-0.6.0/src/simthinkd/forest_head.py +341 -0
  8. {simthinkd-0.5.0 → simthinkd-0.6.0}/src/simthinkd/policy.py +87 -9
  9. simthinkd-0.6.0/src/simthinkd/relearn.py +276 -0
  10. {simthinkd-0.5.0 → simthinkd-0.6.0}/src/simthinkd/router.py +9 -4
  11. {simthinkd-0.5.0 → simthinkd-0.6.0}/src/simthinkd/train.py +109 -30
  12. {simthinkd-0.5.0 → simthinkd-0.6.0/src/simthinkd.egg-info}/PKG-INFO +5 -1
  13. {simthinkd-0.5.0 → simthinkd-0.6.0}/src/simthinkd.egg-info/SOURCES.txt +7 -0
  14. simthinkd-0.6.0/tests/test_a2.py +166 -0
  15. simthinkd-0.6.0/tests/test_baselines.py +184 -0
  16. simthinkd-0.6.0/tests/test_forest_head.py +231 -0
  17. simthinkd-0.6.0/tests/test_numeric_input.py +158 -0
  18. simthinkd-0.6.0/tests/test_relearn_safety.py +226 -0
  19. {simthinkd-0.5.0 → simthinkd-0.6.0}/tests/test_router.py +1 -1
  20. simthinkd-0.5.0/src/simthinkd/relearn.py +0 -113
  21. {simthinkd-0.5.0 → simthinkd-0.6.0}/LICENSE +0 -0
  22. {simthinkd-0.5.0 → simthinkd-0.6.0}/NOTICE +0 -0
  23. {simthinkd-0.5.0 → simthinkd-0.6.0}/setup.cfg +0 -0
  24. {simthinkd-0.5.0 → simthinkd-0.6.0}/src/simthinkd/adapters.py +0 -0
  25. {simthinkd-0.5.0 → simthinkd-0.6.0}/src/simthinkd/bench.py +0 -0
  26. {simthinkd-0.5.0 → simthinkd-0.6.0}/src/simthinkd/cli.py +0 -0
  27. {simthinkd-0.5.0 → simthinkd-0.6.0}/src/simthinkd/data/doom_defend_states.json +0 -0
  28. {simthinkd-0.5.0 → simthinkd-0.6.0}/src/simthinkd/dom_adapter.py +0 -0
  29. {simthinkd-0.5.0 → simthinkd-0.6.0}/src/simthinkd/integrations/__init__.py +0 -0
  30. {simthinkd-0.5.0 → simthinkd-0.6.0}/src/simthinkd/integrations/langchain_tool.py +0 -0
  31. {simthinkd-0.5.0 → simthinkd-0.6.0}/src/simthinkd/integrations/mcp_server.py +0 -0
  32. {simthinkd-0.5.0 → simthinkd-0.6.0}/src/simthinkd/score.py +0 -0
  33. {simthinkd-0.5.0 → simthinkd-0.6.0}/src/simthinkd/screen_actions.py +0 -0
  34. {simthinkd-0.5.0 → simthinkd-0.6.0}/src/simthinkd/server.py +0 -0
  35. {simthinkd-0.5.0 → simthinkd-0.6.0}/src/simthinkd/toy.py +0 -0
  36. {simthinkd-0.5.0 → simthinkd-0.6.0}/src/simthinkd/weights/SHA256SUMS +0 -0
  37. {simthinkd-0.5.0 → simthinkd-0.6.0}/src/simthinkd/weights/doom-corridor.npz +0 -0
  38. {simthinkd-0.5.0 → simthinkd-0.6.0}/src/simthinkd/weights/doom-defend.npz +0 -0
  39. {simthinkd-0.5.0 → simthinkd-0.6.0}/src/simthinkd.egg-info/dependency_links.txt +0 -0
  40. {simthinkd-0.5.0 → simthinkd-0.6.0}/src/simthinkd.egg-info/entry_points.txt +0 -0
  41. {simthinkd-0.5.0 → simthinkd-0.6.0}/src/simthinkd.egg-info/requires.txt +0 -0
  42. {simthinkd-0.5.0 → simthinkd-0.6.0}/src/simthinkd.egg-info/top_level.txt +0 -0
  43. {simthinkd-0.5.0 → simthinkd-0.6.0}/tests/test_dom_adapter.py +0 -0
  44. {simthinkd-0.5.0 → simthinkd-0.6.0}/tests/test_factory_twin.py +0 -0
  45. {simthinkd-0.5.0 → simthinkd-0.6.0}/tests/test_java_parity.py +0 -0
  46. {simthinkd-0.5.0 → simthinkd-0.6.0}/tests/test_notebook.py +0 -0
  47. {simthinkd-0.5.0 → simthinkd-0.6.0}/tests/test_package.py +0 -0
  48. {simthinkd-0.5.0 → simthinkd-0.6.0}/tests/test_parallel.py +0 -0
  49. {simthinkd-0.5.0 → simthinkd-0.6.0}/tests/test_router_example.py +0 -0
  50. {simthinkd-0.5.0 → simthinkd-0.6.0}/tests/test_score.py +0 -0
  51. {simthinkd-0.5.0 → simthinkd-0.6.0}/tests/test_screen_actions.py +0 -0
  52. {simthinkd-0.5.0 → simthinkd-0.6.0}/tests/test_server_concurrency.py +0 -0
  53. {simthinkd-0.5.0 → simthinkd-0.6.0}/tests/test_server_latency.py +0 -0
  54. {simthinkd-0.5.0 → simthinkd-0.6.0}/tests/test_space.py +0 -0
  55. {simthinkd-0.5.0 → simthinkd-0.6.0}/tests/test_web_page.py +0 -0
  56. {simthinkd-0.5.0 → simthinkd-0.6.0}/tests/test_web_parity.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: simthinkd
3
- Version: 0.5.0
3
+ Version: 0.6.0
4
4
  Summary: A 265k-parameter decision model that picks one action in about 2 ms on one CPU core, inside real-time loops.
5
5
  Author: Myeongseongsimjae AX Institute
6
6
  License: Apache-2.0
@@ -260,6 +260,10 @@ SimThink D in front it took 7.2 s with 0 calls (3 of 3 runs each, local headless
260
260
  `benchmarks/screen` reruns both apps; a large model is plugged in through one command. Manual:
261
261
  [docs/SCREEN.md](docs/SCREEN.md).
262
262
 
263
+ <p align="center"><a href="assets/screen_demos.mp4"><img src="assets/screen_demos_poster.jpg" alt="Screen-control demos: a large model alone and SimThink D in front, side by side" width="100%"></a></p>
264
+
265
+ Video (4 min 13 s): the same tasks with a large model alone and with SimThink D in front, including a Google Flights search on a laptop. The flight model learned only that one search. [Watch the video](assets/screen_demos.mp4).
266
+
263
267
  ## Measure your own model
264
268
 
265
269
  Does your model fit inside one tick? `simthinkd bench` replays 1,050 recorded Doom states that ship with the package. It times every decision, one request at a time.
@@ -230,6 +230,10 @@ SimThink D in front it took 7.2 s with 0 calls (3 of 3 runs each, local headless
230
230
  `benchmarks/screen` reruns both apps; a large model is plugged in through one command. Manual:
231
231
  [docs/SCREEN.md](docs/SCREEN.md).
232
232
 
233
+ <p align="center"><a href="assets/screen_demos.mp4"><img src="assets/screen_demos_poster.jpg" alt="Screen-control demos: a large model alone and SimThink D in front, side by side" width="100%"></a></p>
234
+
235
+ Video (4 min 13 s): the same tasks with a large model alone and with SimThink D in front, including a Google Flights search on a laptop. The flight model learned only that one search. [Watch the video](assets/screen_demos.mp4).
236
+
233
237
  ## Measure your own model
234
238
 
235
239
  Does your model fit inside one tick? `simthinkd bench` replays 1,050 recorded Doom states that ship with the package. It times every decision, one request at a time.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "simthinkd"
7
- version = "0.5.0"
7
+ version = "0.6.0"
8
8
  description = "A 265k-parameter decision model that picks one action in about 2 ms on one CPU core, inside real-time loops."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -16,7 +16,7 @@ from .relearn import RelearnReport, relearn
16
16
  from .router import HandoffMonitor, Route, Router, Skill, SkillTable
17
17
  from .score import Score, Scorer
18
18
 
19
- __version__ = '0.5.0'
19
+ __version__ = '0.6.0'
20
20
  __all__ = ['Decider', 'Decision', 'Score', 'Scorer', 'available', 'build_request', 'fit', 'fit_score', '__version__',
21
21
  'Router', 'Route', 'Skill', 'SkillTable', 'HandoffMonitor', 'relearn', 'RelearnReport',
22
22
  'ScreenAdapter', 'PipelineAdapter', 'VectorAdapter',
@@ -13,7 +13,7 @@ import time
13
13
  from dataclasses import dataclass, field
14
14
  from pathlib import Path
15
15
 
16
- from .policy import Policy, encode
16
+ from .policy import Policy
17
17
 
18
18
  WEIGHTS = Path(__file__).resolve().parent / 'weights'
19
19
 
@@ -56,13 +56,15 @@ PRESETS = {
56
56
  }
57
57
 
58
58
 
59
- def build_request(state, actions, goal, *, url='sim://custom', title='', model='simthinkd', recent_actions=None):
60
- """Turn (situation sentence, {action: description}, goal) into a decision request (see PROTOCOL.md)."""
59
+ def build_request(state, actions, goal, *, url='sim://custom', title='', model='simthinkd', recent_actions=None,
60
+ measures=None, ignore_enabled=False):
61
+ """Turn (situation sentence, {action: description}, goal) into a decision request (see PROTOCOL.md).
62
+ `measures` (optional) is {name: number}: the situation's numbers. Only a decider that learned measures uses them."""
61
63
  if not isinstance(state, str) or not state.strip():
62
64
  raise ValueError('state must be a non-empty sentence describing the situation')
63
- if not actions or len(actions) > 8:
65
+ if not actions or len(actions) > (9 if ignore_enabled and 'ignore' in actions else 8):
64
66
  raise ValueError('offer between 1 and 8 actions')
65
- return {
67
+ request = {
66
68
  'model': model,
67
69
  'state': {'page': {'url': url, 'title': title, 'text': state},
68
70
  'elements': [{'id': name, 'role': 'button', 'label': name} for name in actions],
@@ -72,6 +74,11 @@ def build_request(state, actions, goal, *, url='sim://custom', title='', model='
72
74
  for name, why in actions.items()},
73
75
  'instructions': {'goal': goal}}},
74
76
  }
77
+ if measures is not None:
78
+ if not isinstance(measures, dict) or not measures:
79
+ raise ValueError('measures must be a non-empty {name: number} dict')
80
+ request['state']['measures'] = {str(k): float(v) for k, v in measures.items()}
81
+ return request
75
82
 
76
83
 
77
84
  def answer(policy, body):
@@ -144,9 +151,13 @@ class Decision:
144
151
 
145
152
 
146
153
  class Decider:
147
- """A trained decider. `Decider("doom-defend")`, `Decider("path/to/folder_or.npz")`."""
154
+ """A trained decider. `Decider("doom-defend")`, `Decider("path/to/folder_or.npz")`.
148
155
 
149
- def __init__(self, name_or_path='doom-defend'):
156
+ check_sha256 (0.6.0.dev0, default True): a folder's card (decider.json) records the SHA-256 of its weights file; a
157
+ weights file that does not match is refused (RuntimeError), as the shipped presets always were. 0.5.0 did not check
158
+ folders; check_sha256=False loads as 0.5.0 did. A card without a recorded "sha256" loads unchecked, as before."""
159
+
160
+ def __init__(self, name_or_path='doom-defend', check_sha256=True, *, embedding_provider=None):
150
161
  preset = PRESETS.get(name_or_path)
151
162
  if preset:
152
163
  path = WEIGHTS / preset['weights']
@@ -160,24 +171,54 @@ class Decider:
160
171
  card = json.loads((path / 'decider.json').read_text(encoding='utf8'))
161
172
  self.preset = dict(card, name=card.get('name', path.name))
162
173
  path = path / card['weights']
174
+ recorded = card.get('sha256')
175
+ if check_sha256 and recorded is not None:
176
+ digest = hashlib.sha256(path.read_bytes()).hexdigest()
177
+ if digest != recorded:
178
+ raise RuntimeError(f'weights file {path.name} does not match the SHA-256 recorded in decider.json '
179
+ f'({digest[:12]} != {str(recorded)[:12]}); pass check_sha256=False to load it anyway')
163
180
  else:
164
181
  self.preset = {'name': path.stem, 'actions': None, 'goal': '', 'url': 'sim://custom', 'title': '',
165
182
  'model': path.stem}
166
- self.policy = Policy(path)
183
+ self.policy = Policy(path, spec=self.preset.get('measures'))
184
+ self.ignore_enabled = self.preset.get('ignore_enabled', False)
185
+ if embedding_provider is not None:
186
+ info = self.preset.get('a2')
187
+ if not info:
188
+ raise ValueError('embedding_provider needs a decider trained with A2 weights')
189
+ if not callable(embedding_provider):
190
+ raise TypeError('embedding_provider must be callable')
191
+ a2 = Policy(path.parent / info['weights'], spec=self.policy.spec)
192
+ if check_sha256 and a2.digest != info['sha256']:
193
+ raise RuntimeError('A2 weights do not match the recorded SHA-256')
194
+ from .embeddings import WIDTH
195
+ if a2.w['local.weight'].shape[1] != self.policy.w['local.weight'].shape[1] + 3 * WIDTH:
196
+ raise ValueError('A2 feature width does not match the base decider')
197
+ self.policy.a2 = a2
198
+ self.policy.embedding_provider = embedding_provider
167
199
  self.sha256 = self.policy.digest
168
200
 
169
201
  @property
170
202
  def actions(self):
171
203
  return dict(self.preset['actions'] or {})
172
204
 
173
- def request(self, state, actions=None, goal=None, tick=0, recent_actions=None):
205
+ @property
206
+ def measure_names(self):
207
+ """Names of the numbers this decider takes (empty for a decider that learned text only)."""
208
+ spec = self.policy.spec
209
+ return list(spec['names']) if spec else []
210
+
211
+ def request(self, state, actions=None, goal=None, tick=0, recent_actions=None, measures=None):
174
212
  actions = actions or self.preset['actions']
175
213
  if not actions:
176
214
  raise ValueError('this decider has no stored action set; pass actions={name: description}')
215
+ if measures is not None and self.policy.spec is None:
216
+ raise ValueError('this decider learned no measures; pass measures only to a decider trained with them')
177
217
  return build_request(state, actions, self.preset['goal'] if goal is None else goal,
178
218
  url=self.preset.get('url', 'sim://custom'),
179
219
  title=self.preset.get('title', '').format(tick=tick),
180
- model=self.preset.get('model', 'simthinkd'), recent_actions=recent_actions)
220
+ model=self.preset.get('model', 'simthinkd'), recent_actions=recent_actions,
221
+ measures=measures, ignore_enabled=self.ignore_enabled)
181
222
 
182
223
  def predict(self, body):
183
224
  """Protocol-level call: request dict in, `answers` dict out (same as the HTTP server)."""
@@ -196,24 +237,24 @@ class Decider:
196
237
  bodies = list(bodies)
197
238
  if not bodies:
198
239
  return []
199
- jobs, encoded = [], []
240
+ jobs, requests = [], []
200
241
  for i, body in enumerate(bodies):
201
242
  body_jobs = _jobs(body)
202
243
  if not body_jobs: # checked per request, so a neighbour in the batch never changes the outcome
203
244
  raise ValueError(f'request {i} has no question to answer')
204
245
  for name, kind in body_jobs:
205
246
  jobs.append((i, name, kind))
206
- encoded.append(encode(body if name is None else _question_body(body, body['questions'][name])))
247
+ requests.append(body if name is None else _question_body(body, body['questions'][name]))
207
248
  out = [{'answers': {}, 'meta': {'questions': 0}} for _ in bodies]
208
- for (i, name, kind), e, s in zip(jobs, encoded, self.policy.scores_batch([e[0] for e in encoded])):
209
- predicted = self.policy.decode(e, s)
249
+ for (i, name, kind), predicted in zip(jobs, self.policy.predict_batch(requests)):
210
250
  out[i]['answers'].update(answer_from(predicted) if name is None else {name: _general_answer(kind, predicted)})
211
251
  out[i]['meta']['questions'] += 1
212
252
  return out
213
253
 
214
- def decide(self, state, actions=None, goal=None, tick=0, recent_actions=None):
215
- """One decision for one situation sentence. Returns a Decision (choice, confidence, probabilities, ms)."""
216
- body = self.request(state, actions, goal, tick, recent_actions)
254
+ def decide(self, state, actions=None, goal=None, tick=0, recent_actions=None, measures=None):
255
+ """One decision for one situation sentence. Returns a Decision (choice, confidence, probabilities, ms).
256
+ `measures` ({name: number}) is used only by a decider that learned measures (see measure_names)."""
257
+ body = self.request(state, actions, goal, tick, recent_actions, measures=measures)
217
258
  start = time.perf_counter()
218
259
  op = answer(self.policy, body)['operation']
219
260
  ms = (time.perf_counter() - start) * 1000
@@ -0,0 +1,88 @@
1
+ """Optional sentence vectors from a local multilingual-e5-small service."""
2
+ import json
3
+ import math
4
+ import socket
5
+ import threading
6
+ import time
7
+ from typing import Protocol
8
+ from http.client import HTTPConnection
9
+
10
+ import numpy as np
11
+
12
+ WIDTH = 384
13
+
14
+
15
+ class EmbeddingProvider(Protocol):
16
+ def __call__(self, texts: list[str]):
17
+ """Return one 384-dimensional vector per text, in request order."""
18
+ ...
19
+
20
+
21
+ class LocalE5:
22
+ """Client for embedd.py, which caches up to 5,000 texts at the service."""
23
+ def __init__(self, timeout=0.8):
24
+ if not math.isfinite(timeout) or timeout <= 0:
25
+ raise ValueError('timeout must be positive and finite')
26
+ self.timeout = timeout
27
+
28
+ def __call__(self, texts):
29
+ conn = HTTPConnection('127.0.0.1', 8765, timeout=self.timeout)
30
+ deadline = time.monotonic() + self.timeout
31
+ timer = None
32
+ try:
33
+ conn.connect()
34
+ # A socket timeout alone resets after every successful read. A slowly
35
+ # streaming response must also yield control to the A0 ranker.
36
+ sock = conn.sock
37
+
38
+ def stop_reading():
39
+ try:
40
+ sock.shutdown(socket.SHUT_RDWR)
41
+ except OSError:
42
+ pass # already closed by the HTTP client
43
+
44
+ timer = threading.Timer(max(0., deadline - time.monotonic()), stop_reading)
45
+ timer.daemon = True
46
+ timer.start()
47
+ conn.request('POST', '/embed', json.dumps({'texts': texts}).encode(),
48
+ {'Content-Type': 'application/json'})
49
+ response = conn.getresponse()
50
+ if response.status != 200:
51
+ raise OSError(f'local embedding service returned HTTP {response.status}')
52
+ vectors = json.load(response)['vectors']
53
+ if time.monotonic() >= deadline:
54
+ raise TimeoutError('local embedding request exceeded its deadline')
55
+ return vectors
56
+ finally:
57
+ if timer is not None:
58
+ timer.cancel()
59
+ conn.close()
60
+
61
+
62
+ class EmbeddingUnavailable(ValueError):
63
+ """The provider could not produce a usable vector for every input."""
64
+
65
+
66
+ def embedding_rows(body, operations, groups, provider):
67
+ page = body['state'].get('page', {})
68
+ sentence = str(page.get('text', '')) if isinstance(page, dict) else str(page)
69
+ criteria = body['questions']['operation']['criteria']
70
+ texts = [sentence]
71
+ for op in operations:
72
+ criterion = criteria[op]
73
+ description = criterion.get('description', '') if isinstance(criterion, dict) else criterion
74
+ texts.append(f'{op}: {description}')
75
+ unique = list(dict.fromkeys(texts))
76
+ try:
77
+ vectors = np.asarray(provider(unique), dtype=np.float32)
78
+ if vectors.shape != (len(unique), WIDTH) or not np.isfinite(vectors).all():
79
+ raise ValueError('invalid embedding shape or value')
80
+ norms = np.linalg.norm(vectors.astype(np.float64), axis=1, keepdims=True)
81
+ if np.any(norms == 0):
82
+ raise ValueError('empty embedding')
83
+ by_text = dict(zip(unique, (vectors / norms).astype(np.float32)))
84
+ except Exception as exc:
85
+ raise EmbeddingUnavailable('sentence embeddings unavailable') from exc
86
+ candidates = np.stack([by_text[t] for t in texts[1:]])[groups]
87
+ utterance = np.broadcast_to(by_text[sentence], candidates.shape)
88
+ return np.concatenate([utterance, candidates, utterance * candidates], axis=1)
@@ -0,0 +1,341 @@
1
+ """ForestHead: a random forest on the numbers, feeding its class probabilities into SimThink D (0.6.0.dev0, off by default).
2
+
3
+ Numbers in a table are what a forest does well; choices, several questions, confidence, hand-over and relearning are
4
+ what the decider does well. A hybrid decider uses both: the forest reads the numeric measures and its probability for
5
+ each choice goes into the decider's numeric input as the measures `forest_p_<choice>`. The decider keeps its own
6
+ decision layer.
7
+
8
+ The forest's probability for a training row must come from trees that did not see that row, or the decider learns to
9
+ trust a forest that has memorised its training rows. `ForestHead.fit` therefore returns out-of-bag (OOB) probabilities:
10
+ for each training row, the average of the trees whose bootstrap sample left the row out. New rows get the whole forest.
11
+
12
+ from simthinkd.forest_head import ForestHead, fit_hybrid, HybridDecider
13
+ head = ForestHead(['PASS', 'SLOW_BELT'], ['speed', 'count'], params={'max_depth': 6}, seed=7)
14
+ oob = head.fit(rows, labels) # rows = [{'speed': 1.2, 'count': 3}, ...]; oob = (n, choices) array
15
+ head.predict_proba([{'speed': 3.8, 'count': 1}])
16
+ head.save('folder/forest'); ForestHead.load('folder/forest') # SHA-256 of forest.pkl checked on load
17
+
18
+ decider = fit_hybrid(protocol_rows, 'my_hybrid', steps=600) # forest + decider in one folder
19
+ HybridDecider('my_hybrid').decide(sentence, measures={'speed': 1.2, 'count': 3})
20
+
21
+ Nothing here changes `Decider`: a decider folder without a forest loads and answers exactly as before. Needs
22
+ scikit-learn (an optional dependency): `pip install scikit-learn`.
23
+ """
24
+ import copy
25
+ import hashlib
26
+ import json
27
+ import pickle
28
+ from pathlib import Path
29
+
30
+ import numpy as np
31
+
32
+ PREFIX = 'forest_p_'
33
+ CARD = 'forest.json'
34
+ MODEL = 'forest.pkl'
35
+ FORMAT = 'simthinkd-forest/1'
36
+
37
+
38
+ def _sklearn():
39
+ try:
40
+ import sklearn # noqa: F401
41
+ from sklearn.ensemble import RandomForestClassifier
42
+ except ImportError as error:
43
+ raise ImportError('ForestHead needs scikit-learn: pip install scikit-learn') from error
44
+ return sklearn, RandomForestClassifier
45
+
46
+
47
+ def _sha(path):
48
+ return hashlib.sha256(Path(path).read_bytes()).hexdigest()
49
+
50
+
51
+ def forest_measure_names(choices, prefix=PREFIX):
52
+ return [prefix + str(c) for c in choices]
53
+
54
+
55
+ class ForestHead:
56
+ """Random forest over named numeric inputs, with OOB probabilities for its own training rows.
57
+
58
+ choices: the label names, in the order of the probability columns.
59
+ inputs: the measure names the forest reads (column order is fixed by this list).
60
+ params: extra RandomForestClassifier arguments (for example max_depth, min_samples_leaf).
61
+ """
62
+
63
+ def __init__(self, choices, inputs, params=None, seed=0, n_estimators=300):
64
+ if not choices or len(set(choices)) != len(choices):
65
+ raise ValueError('choices must be a non-empty list of distinct names')
66
+ if not inputs or len(set(inputs)) != len(inputs):
67
+ raise ValueError('inputs must be a non-empty list of distinct measure names')
68
+ self.choices = [str(c) for c in choices]
69
+ self.inputs = [str(k) for k in inputs]
70
+ self.params = dict(params or {})
71
+ for key in ('n_estimators', 'random_state', 'bootstrap', 'n_jobs', 'oob_score'):
72
+ if key in self.params:
73
+ raise ValueError(f'{key} is set by ForestHead itself')
74
+ self.seed = int(seed)
75
+ self.n_estimators = int(n_estimators)
76
+ self.model = None
77
+ self.oob_counts = None
78
+ self.sha256 = None
79
+
80
+ # ---- input
81
+
82
+ def matrix(self, rows):
83
+ """rows: list of {name: number}. Every input name must be present and finite."""
84
+ X = np.empty((len(rows), len(self.inputs)), np.float64)
85
+ for i, row in enumerate(rows):
86
+ for j, name in enumerate(self.inputs):
87
+ if name not in row:
88
+ raise ValueError(f'row {i} has no value for forest input {name!r}')
89
+ v = float(row[name])
90
+ if not np.isfinite(v):
91
+ raise ValueError(f'row {i}: forest input {name!r} is not a finite number ({v})')
92
+ X[i, j] = v
93
+ return X
94
+
95
+ def _labels(self, labels):
96
+ index = {c: i for i, c in enumerate(self.choices)}
97
+ bad = sorted({str(y) for y in labels if str(y) not in index})
98
+ if bad:
99
+ raise ValueError(f'labels not among the choices: {bad}')
100
+ return np.asarray([index[str(y)] for y in labels], int)
101
+
102
+ # ---- fit
103
+
104
+ def fit(self, rows, labels):
105
+ """Fit the forest; return the OOB probabilities of the training rows, shape (len(rows), len(choices)).
106
+
107
+ A row's OOB probability is the mean of predict_proba of the trees whose bootstrap sample did not contain that
108
+ row. A row that every tree saw (practically never with 300 trees) gets the class shares of the training labels;
109
+ how many such rows there were is in `oob_counts` (count 0)."""
110
+ _, RandomForestClassifier = _sklearn()
111
+ X = self.matrix(rows)
112
+ y = self._labels(labels)
113
+ if len(X) < 2:
114
+ raise ValueError('need at least 2 rows to fit a forest')
115
+ model = RandomForestClassifier(n_estimators=self.n_estimators, random_state=self.seed, n_jobs=1,
116
+ bootstrap=True, **self.params)
117
+ model.fit(X, y)
118
+ self.model = model
119
+ n, k = len(X), len(self.choices)
120
+ total = np.zeros((n, k))
121
+ counts = np.zeros(n, int)
122
+ for tree, sampled in zip(model.estimators_, model.estimators_samples_):
123
+ seen = np.zeros(n, bool)
124
+ seen[sampled] = True
125
+ unseen = np.flatnonzero(~seen)
126
+ if len(unseen) == 0:
127
+ continue
128
+ total[unseen] += self._expand(tree.predict_proba(X[unseen]))
129
+ counts[unseen] += 1
130
+ prior = np.bincount(y, minlength=k) / len(y)
131
+ oob = np.where(counts[:, None] > 0, total / np.maximum(counts, 1)[:, None], prior[None, :])
132
+ self.oob_counts = counts
133
+ return oob
134
+
135
+ def _expand(self, P):
136
+ """The forest (and each of its trees, which share its columns) knows only the labels present in its training
137
+ rows; put each column in the place of its choice, zeros for choices it never saw."""
138
+ full = np.zeros((len(P), len(self.choices)))
139
+ full[:, np.asarray(self.model.classes_, int)] = P
140
+ return full
141
+
142
+ def predict_proba(self, rows):
143
+ """Whole-forest probabilities for new rows, shape (len(rows), len(choices))."""
144
+ if self.model is None:
145
+ raise RuntimeError('ForestHead is not fitted')
146
+ return self._expand(self.model.predict_proba(self.matrix(rows)))
147
+
148
+ def measures(self, probs, prefix=PREFIX):
149
+ """One probability row -> {'forest_p_<choice>': p} for the decider's numeric input."""
150
+ return {prefix + c: float(p) for c, p in zip(self.choices, probs)}
151
+
152
+ # ---- save / load
153
+
154
+ def card(self):
155
+ import sklearn
156
+ return {'format': FORMAT, 'model': MODEL, 'sha256': self.sha256, 'choices': self.choices,
157
+ 'inputs': self.inputs, 'params': self.params, 'seed': self.seed, 'n_estimators': self.n_estimators,
158
+ 'sklearn': sklearn.__version__, 'prefix': PREFIX}
159
+
160
+ def save(self, folder):
161
+ """Write forest.pkl and forest.json (the card records the SHA-256 of forest.pkl). Returns the folder."""
162
+ if self.model is None:
163
+ raise RuntimeError('ForestHead is not fitted')
164
+ folder = Path(folder)
165
+ folder.mkdir(parents=True, exist_ok=True)
166
+ with open(folder / MODEL, 'wb') as stream:
167
+ pickle.dump(self.model, stream, protocol=4)
168
+ self.sha256 = _sha(folder / MODEL)
169
+ (folder / CARD).write_text(json.dumps(self.card(), ensure_ascii=False, indent=1), encoding='utf8')
170
+ return folder
171
+
172
+ @classmethod
173
+ def load(cls, folder, check_sha256=True):
174
+ """Load a saved forest. The SHA-256 of forest.pkl must match the card (checked before unpickling, as
175
+ Decider checks its weights). A card without a sha256, or check_sha256=False, loads unchecked.
176
+ Only load forests you made or trust: forest.pkl is a pickle."""
177
+ folder = Path(folder)
178
+ card = json.loads((folder / CARD).read_text(encoding='utf8'))
179
+ if card.get('format') != FORMAT:
180
+ raise ValueError(f'not a ForestHead card: {folder / CARD}')
181
+ path = folder / card['model']
182
+ digest = _sha(path)
183
+ recorded = card.get('sha256')
184
+ if check_sha256 and recorded is not None and digest != recorded:
185
+ raise RuntimeError(f'forest file {path.name} does not match the SHA-256 recorded in {CARD} '
186
+ f'({digest[:12]} != {str(recorded)[:12]}); pass check_sha256=False to load it anyway')
187
+ head = cls(card['choices'], card['inputs'], card.get('params'), card.get('seed', 0),
188
+ card.get('n_estimators', 300))
189
+ with open(path, 'rb') as stream:
190
+ head.model = pickle.load(stream)
191
+ head.sha256 = digest
192
+ return head
193
+
194
+
195
+ # ---------------------------------------------------------------- training a hybrid decider
196
+
197
+ def _choices_of(row):
198
+ return list(row['request']['questions']['operation']['criteria'])
199
+
200
+
201
+ def _with_measures(row, extra):
202
+ out = copy.deepcopy(row)
203
+ state = out['request']['state']
204
+ state['measures'] = dict(state.get('measures') or {}, **extra)
205
+ return out
206
+
207
+
208
+ def fit_hybrid(rows, out, *, forest_params=None, forest_seed=0, forest_inputs=None, n_estimators=300,
209
+ steps=600, seed=31, card=None, quiet=False, head=None):
210
+ """Train a forest on the numbers and a decider on (sentence + numbers + forest probabilities); returns a
211
+ HybridDecider. Needs PyTorch and scikit-learn.
212
+
213
+ rows: protocol rows as for simthinkd.train.fit_rows ({"id", "request" with state.measures, "expected", "split"?}).
214
+ Which rows train the forest:
215
+ - rows with a "forest_id" (rows that share one forest_id are one forest example: the same shot repeated with a
216
+ weight, for instance; their measures and labels must agree);
217
+ - if no row has a forest_id: every row of the train split, each its own example.
218
+ The forest sees its examples in the order they first appear in rows (bootstrap draws depend on that order).
219
+ Forest training rows get the forest's OOB probability; every other row (validation, calibration, extra
220
+ synthetic rows without forest_id) gets the whole forest's probability, which is also honest because the forest
221
+ never saw them. The probabilities go in as measures forest_p_<choice>; the decider is then trained by fit_rows.
222
+ head: an already fitted ForestHead is not accepted (its OOB is unknown); pass settings instead.
223
+ """
224
+ from .train import fit_rows, split_for
225
+ if head is not None:
226
+ raise ValueError('fit_hybrid fits its own forest; pass forest_params / forest_seed instead of a head')
227
+ rows = list(rows)
228
+ if not rows:
229
+ raise ValueError('no rows')
230
+ choices = _choices_of(rows[0])
231
+ for row in rows:
232
+ if _choices_of(row) != choices:
233
+ raise ValueError('fit_hybrid needs the same choices in every row')
234
+ names = set(row['request']['state'].get('measures') or {})
235
+ clash = sorted(n for n in names if n.startswith(PREFIX))
236
+ if clash:
237
+ raise ValueError(f'row {row.get("id")}: measure names starting with {PREFIX!r} are reserved: {clash}')
238
+ keyed = [r for r in rows if r.get('forest_id') is not None]
239
+ if keyed:
240
+ examples = {}
241
+ for r in keyed:
242
+ fid = str(r['forest_id'])
243
+ m, y = r['request']['state'].get('measures') or {}, r['expected']['operation']
244
+ if fid in examples and (examples[fid][0] != m or examples[fid][1] != y):
245
+ raise ValueError(f'rows with forest_id {fid!r} differ in measures or label')
246
+ examples.setdefault(fid, (m, y))
247
+ row_key = lambda r: str(r['forest_id']) if r.get('forest_id') is not None else None # noqa: E731
248
+ else:
249
+ examples = {}
250
+ for r in rows:
251
+ if (r.get('split') or split_for(r['id'])) == 'train':
252
+ examples[str(r['id'])] = (r['request']['state'].get('measures') or {}, r['expected']['operation'])
253
+ row_key = lambda r: str(r['id']) if str(r['id']) in examples else None # noqa: E731
254
+ if not examples:
255
+ raise ValueError('no forest training rows')
256
+ order = list(examples) # first appearance in rows: the same rows in the same order give the same forest
257
+ inputs = list(forest_inputs) if forest_inputs else sorted(set().union(*(set(examples[k][0]) for k in order)))
258
+ head = ForestHead(choices, inputs, forest_params, forest_seed, n_estimators)
259
+ oob = head.fit([examples[k][0] for k in order], [examples[k][1] for k in order])
260
+ oob_of = dict(zip(order, oob))
261
+ others = [r for r in rows if row_key(r) is None]
262
+ full = head.predict_proba([r['request']['state'].get('measures') or {} for r in others]) if others else []
263
+ full_of = {id(r): p for r, p in zip(others, full)}
264
+ augmented = [_with_measures(r, head.measures(oob_of[row_key(r)] if row_key(r) is not None else full_of[id(r)]))
265
+ for r in rows]
266
+ out = Path(out)
267
+ fit_rows([{k: v for k, v in r.items() if k != 'forest_id'} for r in augmented], out, steps=steps, seed=seed,
268
+ card=card, quiet=quiet)
269
+ head.save(out / 'forest')
270
+ decider_card = json.loads((out / 'decider.json').read_text(encoding='utf8'))
271
+ decider_card['hybrid'] = {'forest': 'forest', 'forest_sha256': head.sha256, 'prefix': PREFIX,
272
+ 'inputs': head.inputs, 'choices': head.choices,
273
+ 'forest_rows': len(order), 'oob_rows_without_trees': int((head.oob_counts == 0).sum())}
274
+ (out / 'decider.json').write_text(json.dumps(decider_card, ensure_ascii=False, indent=1), encoding='utf8')
275
+ return HybridDecider(str(out))
276
+
277
+
278
+ # ---------------------------------------------------------------- using a hybrid decider
279
+
280
+ class HybridDecider:
281
+ """A decider folder with a forest next to it (made by fit_hybrid). The forest reads the measures, its
282
+ probabilities are added as forest_p_<choice>, and the decider answers as usual (decide, predict, ask...).
283
+
284
+ Both files are checked: the decider's weights against decider.json (as Decider does) and forest.pkl against
285
+ forest.json and against the forest_sha256 recorded in decider.json."""
286
+
287
+ def __init__(self, folder, check_sha256=True):
288
+ from .core import Decider
289
+ folder = Path(folder)
290
+ self.decider = Decider(str(folder), check_sha256=check_sha256)
291
+ hybrid = self.decider.preset.get('hybrid')
292
+ if not hybrid:
293
+ raise ValueError(f'{folder} has no forest (decider.json has no "hybrid" entry); use Decider')
294
+ self.forest = ForestHead.load(folder / hybrid['forest'], check_sha256=check_sha256)
295
+ if check_sha256 and hybrid.get('forest_sha256') not in (None, self.forest.sha256):
296
+ raise RuntimeError('forest.pkl does not match the forest_sha256 recorded in decider.json')
297
+ self.prefix = hybrid.get('prefix', PREFIX)
298
+ self.sha256 = self.decider.sha256
299
+
300
+ @property
301
+ def actions(self):
302
+ return self.decider.actions
303
+
304
+ @property
305
+ def measure_names(self):
306
+ return self.decider.measure_names
307
+
308
+ def forest_measures(self, measures):
309
+ """{name: number} -> the same dict plus forest_p_<choice> from the whole forest."""
310
+ if not measures:
311
+ raise ValueError('a hybrid decider needs the measures its forest reads: ' + ', '.join(self.forest.inputs))
312
+ p = self.forest.predict_proba([measures])[0]
313
+ return dict(measures, **self.forest.measures(p, self.prefix))
314
+
315
+ def with_forest(self, body):
316
+ """A protocol request with the forest probabilities added to state.measures (the input is not changed)."""
317
+ out = copy.deepcopy(body)
318
+ state = out['state']
319
+ state['measures'] = self.forest_measures(state.get('measures') or {})
320
+ return out
321
+
322
+ def request(self, state, actions=None, goal=None, tick=0, recent_actions=None, measures=None):
323
+ return self.decider.request(state, actions, goal, tick, recent_actions, measures=self.forest_measures(measures))
324
+
325
+ def decide(self, state, actions=None, goal=None, tick=0, recent_actions=None, measures=None):
326
+ return self.decider.decide(state, actions, goal, tick, recent_actions, measures=self.forest_measures(measures))
327
+
328
+ def predict(self, body):
329
+ return self.decider.predict(self.with_forest(body))
330
+
331
+ def predict_batch(self, bodies):
332
+ return self.decider.predict_batch([self.with_forest(b) for b in bodies])
333
+
334
+ def ask(self, body):
335
+ return self.decider.ask(self.with_forest(body))
336
+
337
+ def ask_batch(self, bodies):
338
+ return self.decider.ask_batch([self.with_forest(b) for b in bodies])
339
+
340
+ def __repr__(self):
341
+ return f'HybridDecider({self.decider.preset["name"]!r}, sha256={self.sha256[:12]}, forest={self.forest.sha256[:12]})'