xrtm-train 0.1.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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that you changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tour (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 XRTM Team
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,66 @@
1
+ Metadata-Version: 2.4
2
+ Name: xrtm-train
3
+ Version: 0.1.0
4
+ Summary: The Learning/Optimization layer for XRTM.
5
+ Author-email: XRTM Team <moy@xrtm.org>
6
+ License: Apache-2.0
7
+ Requires-Python: >=3.11
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: pydantic>=2.0.0
11
+ Requires-Dist: numpy>=1.24.0
12
+ Requires-Dist: scikit-learn>=1.3.0
13
+ Requires-Dist: xrtm-data
14
+ Requires-Dist: xrtm-eval
15
+ Requires-Dist: xrtm-forecast
16
+ Provides-Extra: dev
17
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
18
+ Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
19
+ Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
20
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
21
+ Requires-Dist: mypy>=1.0.0; extra == "dev"
22
+ Dynamic: license-file
23
+
24
+ # xrtm-train
25
+
26
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
27
+ [![Python](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
28
+
29
+ **The Optimization Layer for XRTM.**
30
+
31
+ `xrtm-train` is the engine that closes the loop. It simulates history by replaying agents against past "Ground Truth" snapshots stored in `xrtm-data`, scoring them with `xrtm-eval`, and optimizing their reasoning parameters.
32
+
33
+ ## Installation
34
+
35
+ ```bash
36
+ uv pip install xrtm-train
37
+ ```
38
+
39
+ ## Core Primitives
40
+
41
+ ### The Simulation Loop
42
+ The `Backtester` orchestrates the simulation. It ensures strict temporal isolation—agents are never exposed to data from the future.
43
+
44
+ ```python
45
+ from xrtm.train import Backtester
46
+
47
+ # Initialize components
48
+ backtester = Backtester(agent=my_agent, evaluator=my_evaluator)
49
+
50
+ # Run simulation
51
+ results = await backtester.run(dataset=historical_questions)
52
+ print(f"Mean Brier Score: {results.mean_score}")
53
+ ```
54
+
55
+ ## Development
56
+
57
+ Prerequisites:
58
+ - [uv](https://github.com/astral-sh/uv)
59
+
60
+ ```bash
61
+ # Install dependencies
62
+ uv sync
63
+
64
+ # Run tests
65
+ uv run pytest
66
+ ```
@@ -0,0 +1,43 @@
1
+ # xrtm-train
2
+
3
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
4
+ [![Python](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
5
+
6
+ **The Optimization Layer for XRTM.**
7
+
8
+ `xrtm-train` is the engine that closes the loop. It simulates history by replaying agents against past "Ground Truth" snapshots stored in `xrtm-data`, scoring them with `xrtm-eval`, and optimizing their reasoning parameters.
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+ uv pip install xrtm-train
14
+ ```
15
+
16
+ ## Core Primitives
17
+
18
+ ### The Simulation Loop
19
+ The `Backtester` orchestrates the simulation. It ensures strict temporal isolation—agents are never exposed to data from the future.
20
+
21
+ ```python
22
+ from xrtm.train import Backtester
23
+
24
+ # Initialize components
25
+ backtester = Backtester(agent=my_agent, evaluator=my_evaluator)
26
+
27
+ # Run simulation
28
+ results = await backtester.run(dataset=historical_questions)
29
+ print(f"Mean Brier Score: {results.mean_score}")
30
+ ```
31
+
32
+ ## Development
33
+
34
+ Prerequisites:
35
+ - [uv](https://github.com/astral-sh/uv)
36
+
37
+ ```bash
38
+ # Install dependencies
39
+ uv sync
40
+
41
+ # Run tests
42
+ uv run pytest
43
+ ```
@@ -0,0 +1,60 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "xrtm-train"
7
+ version = "0.1.0"
8
+ description = "The Learning/Optimization layer for XRTM."
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = {text = "Apache-2.0"}
12
+ authors = [
13
+ {name = "XRTM Team", email = "moy@xrtm.org"}
14
+ ]
15
+ dependencies = [
16
+ "pydantic>=2.0.0",
17
+ "numpy>=1.24.0",
18
+ "scikit-learn>=1.3.0",
19
+ "xrtm-data",
20
+ "xrtm-eval",
21
+ "xrtm-forecast",
22
+ ]
23
+
24
+ [project.optional-dependencies]
25
+ dev = [
26
+ "pytest>=7.0.0",
27
+ "pytest-asyncio>=0.21.0",
28
+ "pytest-cov>=4.1.0",
29
+ "ruff>=0.1.0",
30
+ "mypy>=1.0.0",
31
+ ]
32
+
33
+ [tool.setuptools]
34
+ package-dir = {"" = "src"}
35
+ packages = {find = {where = ["src"], include = ["xrtm*"], namespaces = true}}
36
+
37
+ [tool.uv.sources]
38
+ xrtm-data = { git = "https://github.com/xrtm-org/data.git", branch = "main" }
39
+ xrtm-eval = { git = "https://github.com/xrtm-org/eval.git", branch = "main" }
40
+ xrtm-forecast = { git = "https://github.com/xrtm-org/forecast.git", branch = "refactor/split-architecture" }
41
+
42
+ [tool.pytest.ini_options]
43
+ pythonpath = ["."]
44
+ testpaths = ["tests"]
45
+ asyncio_mode = "strict"
46
+
47
+ [tool.ruff]
48
+ line-length = 120
49
+ target-version = "py311"
50
+ exclude = [".git", ".venv", "build", "dist"]
51
+
52
+ [tool.ruff.lint]
53
+ select = ["E", "F", "I", "W"]
54
+ ignore = ["E501"]
55
+
56
+ [tool.mypy]
57
+ python_version = "3.11"
58
+ ignore_missing_imports = true
59
+ strict = false
60
+ explicit_package_bases = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,22 @@
1
+ # coding=utf-8
2
+ # Copyright 2026 XRTM Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from xrtm.train.simulation.backtester import Backtester
17
+ from xrtm.train.simulation.replayer import TraceReplayer
18
+
19
+ __all__ = [
20
+ "Backtester",
21
+ "TraceReplayer",
22
+ ]
@@ -0,0 +1,6 @@
1
+ # coding=utf-8
2
+ # Copyright 2026 XRTM Team. All rights reserved.
3
+
4
+ from .eval.calibration import BetaScaler, PlattScaler
5
+
6
+ __all__ = ["PlattScaler", "BetaScaler"]
@@ -0,0 +1,3 @@
1
+ from .calibration import BetaScaler, PlattScaler
2
+
3
+ __all__ = ["PlattScaler", "BetaScaler"]
@@ -0,0 +1,82 @@
1
+ # coding=utf-8
2
+ # Copyright 2026 XRTM Team. All rights reserved.
3
+
4
+ import pickle
5
+ from pathlib import Path
6
+ from typing import List, Union
7
+
8
+ import numpy as np
9
+ from pydantic import BaseModel, ConfigDict
10
+ from sklearn.linear_model import LogisticRegression
11
+
12
+
13
+ class PlattScaler(BaseModel):
14
+ model_config = ConfigDict(arbitrary_types_allowed=True)
15
+ a: float = 1.0
16
+ b: float = 0.0
17
+ fitted: bool = False
18
+
19
+ def fit(self, y_true: List[int], y_prob: List[float]) -> "PlattScaler":
20
+ eps = 1e-15
21
+ p = np.clip(y_prob, eps, 1 - eps)
22
+ logits = np.log(p / (1 - p)).reshape(-1, 1)
23
+ clf = LogisticRegression(C=1e10, solver="lbfgs")
24
+ clf.fit(logits, y_true)
25
+ self.a = float(clf.coef_[0][0])
26
+ self.b = float(clf.intercept_[0])
27
+ self.fitted = True
28
+ return self
29
+
30
+ def transform(self, y_prob: Union[float, List[float]]) -> Union[float, List[float]]:
31
+ if not self.fitted:
32
+ return y_prob
33
+ is_scalar = isinstance(y_prob, (float, int))
34
+ y_prob_arr = np.array([y_prob]) if is_scalar else np.array(y_prob)
35
+ eps = 1e-15
36
+ p = np.clip(y_prob_arr, eps, 1 - eps)
37
+ logits = np.log(p / (1 - p))
38
+ scaled_logits = self.a * logits + self.b
39
+ p_calib = 1.0 / (1.0 + np.exp(-scaled_logits))
40
+ return float(p_calib[0]) if is_scalar else p_calib.tolist()
41
+
42
+ def save(self, path: Union[str, Path]) -> None:
43
+ with open(path, "wb") as f:
44
+ pickle.dump({"a": self.a, "b": self.b, "fitted": self.fitted}, f)
45
+
46
+ def load(self, path: Union[str, Path]) -> "PlattScaler":
47
+ with open(path, "rb") as f:
48
+ data = pickle.load(f)
49
+ self.a, self.b, self.fitted = data["a"], data["b"], data["fitted"]
50
+ return self
51
+
52
+
53
+ class BetaScaler(BaseModel):
54
+ model_config = ConfigDict(arbitrary_types_allowed=True)
55
+ a: float = 1.0
56
+ b: float = 1.0
57
+ c: float = 0.0
58
+ fitted: bool = False
59
+
60
+ def fit(self, y_true: List[int], y_prob: List[float]) -> "BetaScaler":
61
+ eps = 1e-15
62
+ p = np.clip(y_prob, eps, 1 - eps)
63
+ X = np.stack([np.log(p), -np.log(1 - p)], axis=1)
64
+ clf = LogisticRegression(C=1e10, solver="lbfgs")
65
+ clf.fit(X, y_true)
66
+ self.a, self.b, self.c = float(clf.coef_[0][0]), float(clf.coef_[0][1]), float(clf.intercept_[0])
67
+ self.fitted = True
68
+ return self
69
+
70
+ def transform(self, y_prob: Union[float, List[float]]) -> Union[float, List[float]]:
71
+ if not self.fitted:
72
+ return y_prob
73
+ is_scalar = isinstance(y_prob, (float, int))
74
+ y_prob_arr = np.array([y_prob]) if is_scalar else np.array(y_prob)
75
+ eps = 1e-15
76
+ p = np.clip(y_prob_arr, eps, 1 - eps)
77
+ scaled_logits = self.a * np.log(p) - self.b * np.log(1 - p) + self.c
78
+ p_calib = 1.0 / (1.0 + np.exp(-scaled_logits))
79
+ return float(p_calib[0]) if is_scalar else p_calib.tolist()
80
+
81
+
82
+ __all__ = ["PlattScaler", "BetaScaler"]
@@ -0,0 +1,3 @@
1
+ from .learner import EpisodicLearner
2
+
3
+ __all__ = ["EpisodicLearner"]
@@ -0,0 +1,29 @@
1
+ # coding=utf-8
2
+ # Copyright 2026 XRTM Team. All rights reserved.
3
+
4
+ import logging
5
+
6
+ # From xrtm-forecast
7
+ from xrtm.forecast.kit.memory.unified import Memory as UnifiedMemory
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+ class EpisodicLearner:
12
+ def __init__(self, memory: UnifiedMemory):
13
+ self.memory = memory
14
+
15
+ def get_lessons_for_subject(self, subject_id: str, n_results: int = 3) -> str:
16
+ try:
17
+ query = f"Past performance and lessons for {subject_id}"
18
+ experiences = self.memory.retrieve_similar(query, n_results=n_results)
19
+ if not experiences:
20
+ return "No relevant past experiences found."
21
+ formatted_lessons = "\n--- PAST LESSONS LEARNED ---\n"
22
+ for i, doc in enumerate(experiences, 1):
23
+ formatted_lessons += f"Experience {i}:\n{doc.strip()}\n"
24
+ return formatted_lessons
25
+ except Exception as e:
26
+ logger.error(f"[LEARNER] Failed to retrieve lessons: {e}")
27
+ return "Error retrieving past lessons."
28
+
29
+ __all__ = ["EpisodicLearner"]
@@ -0,0 +1,3 @@
1
+ from .compiler import BrierOptimizer
2
+
3
+ __all__ = ["BrierOptimizer"]
@@ -0,0 +1,32 @@
1
+ # coding=utf-8
2
+ # Copyright 2026 XRTM Team. All rights reserved.
3
+
4
+ import logging
5
+ from typing import Any, List, Tuple
6
+
7
+ # From xrtm-forecast
8
+ from xrtm.forecast.kit.agents.prompting import CompiledAgent, PromptTemplate
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ class BrierOptimizer:
13
+ def __init__(self, optimizer_model: Any):
14
+ self.optimizer_model = optimizer_model
15
+
16
+ async def optimize(self, agent: CompiledAgent, dataset: List[Tuple[Any, float, int]]) -> PromptTemplate:
17
+ total_error = sum((p - g) ** 2 for _, p, g in dataset) / len(dataset)
18
+ meta_prompt = f"""
19
+ You are a Prompt Optimizer for a forecasting engine.
20
+ Current Goal: Minimize Brier Score (Current: {total_error:.4f}).
21
+ Current Instruction: "{agent.template.instruction}"
22
+ Performance Snippets (Input -> Pred vs Truth):
23
+ """
24
+ for inp, pred, truth in dataset[:5]:
25
+ meta_prompt += f"- {str(inp)[:50]}... -> {pred} (Actual: {truth})\n"
26
+ meta_prompt += "\nSuggest a NEW system instruction that corrects for these errors.\nReturn ONLY the new instruction string."
27
+ new_instruction = await self.optimizer_model.generate(meta_prompt)
28
+ return PromptTemplate(
29
+ instruction=new_instruction.strip(), examples=agent.template.examples, version=agent.template.version + 1
30
+ )
31
+
32
+ __all__ = ["BrierOptimizer"]
@@ -0,0 +1,64 @@
1
+ # coding=utf-8
2
+ # Copyright 2026 XRTM Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import logging
17
+ from typing import List, Tuple
18
+
19
+ # From xrtm-data
20
+ from xrtm.data.schemas.forecast import ForecastQuestion
21
+
22
+ # From xrtm-eval
23
+ from xrtm.eval.core.eval.definitions import EvaluationReport, EvaluationResult, Evaluator
24
+ from xrtm.eval.schemas.forecast import ForecastResolution
25
+
26
+ # From xrtm-forecast (Internal)
27
+ from xrtm.forecast.kit.agents.base import Agent
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ class Backtester:
33
+ """Orchestrates the backtesting process for a specific agent and evaluator."""
34
+
35
+ def __init__(self, agent: Agent, evaluator: Evaluator):
36
+ self.agent = agent
37
+ self.evaluator = evaluator
38
+
39
+ async def run(self, dataset: List[Tuple[ForecastQuestion, ForecastResolution]]) -> EvaluationReport:
40
+ results: List[EvaluationResult] = []
41
+ total_score = 0.0
42
+
43
+ for question, resolution in dataset:
44
+ try:
45
+ logger.info(f"Backtesting question: {question.id}")
46
+ prediction = await self.agent.run(question)
47
+ conf = getattr(prediction, "confidence", prediction)
48
+ eval_res = self.evaluator.evaluate(
49
+ prediction=conf, ground_truth=resolution.outcome, subject_id=question.id
50
+ )
51
+ results.append(eval_res)
52
+ total_score += eval_res.score
53
+ except Exception as e:
54
+ logger.error(f"Failed to evaluate question {question.id}: {e}")
55
+
56
+ count = len(results)
57
+ mean_score = total_score / count if count > 0 else 0.0
58
+
59
+ return EvaluationReport(
60
+ metric_name="Brier Score", mean_score=mean_score, total_evaluations=count, results=results
61
+ )
62
+
63
+
64
+ __all__ = ["Backtester"]
@@ -0,0 +1,81 @@
1
+ # coding=utf-8
2
+ # Copyright 2026 XRTM Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import logging
17
+ from typing import Optional
18
+
19
+ # From xrtm-eval
20
+ from xrtm.eval.core.eval.definitions import EvaluationResult, Evaluator
21
+ from xrtm.eval.schemas.forecast import ForecastResolution
22
+
23
+ # From xrtm-data
24
+ # From xrtm-forecast (Internal)
25
+ from xrtm.forecast.core.orchestrator import Orchestrator
26
+ from xrtm.forecast.core.schemas.graph import BaseGraphState
27
+
28
+ from xrtm.train.simulation.runner import BacktestRunner
29
+
30
+ __all__ = ["TraceReplayer"]
31
+ logger = logging.getLogger(__name__)
32
+
33
+
34
+ class TraceReplayer:
35
+ """Utility class for saving, loading, and replaying evaluation traces."""
36
+
37
+ @staticmethod
38
+ def save_trace(state: BaseGraphState, path: str) -> None:
39
+ try:
40
+ json_str = state.model_dump_json(indent=2)
41
+ with open(path, "w", encoding="utf-8") as f:
42
+ f.write(json_str)
43
+ logger.info(f"Trace saved to {path}")
44
+ except Exception as e:
45
+ logger.error(f"Failed to save trace to {path}: {e}")
46
+ raise
47
+
48
+ @staticmethod
49
+ def load_trace(path: str) -> BaseGraphState:
50
+ try:
51
+ with open(path, "r", encoding="utf-8") as f:
52
+ json_str = f.read()
53
+ state = BaseGraphState.model_validate_json(json_str)
54
+ return state
55
+ except Exception as e:
56
+ logger.error(f"Failed to load trace from {path}: {e}")
57
+ raise
58
+
59
+ def replay_evaluation(
60
+ self,
61
+ trace_path: str,
62
+ resolution: ForecastResolution | float | str,
63
+ evaluator: Optional[Evaluator] = None,
64
+ subject_id_override: Optional[str] = None,
65
+ ) -> EvaluationResult:
66
+ state = self.load_trace(trace_path)
67
+ subject_id = subject_id_override or state.subject_id
68
+ if not isinstance(resolution, ForecastResolution):
69
+ resolution = ForecastResolution(
70
+ question_id=subject_id, outcome=str(resolution), metadata={"source": "replay_override"}
71
+ )
72
+ dummy_orch: Orchestrator[BaseGraphState] = Orchestrator()
73
+ runner = BacktestRunner(orchestrator=dummy_orch, evaluator=evaluator)
74
+ result = runner.evaluate_state(
75
+ state=state,
76
+ resolution=resolution,
77
+ subject_id=subject_id,
78
+ reference_time=state.temporal_context.reference_time if state.temporal_context else None,
79
+ )
80
+ result.metadata["is_replay"] = True
81
+ return result
@@ -0,0 +1,157 @@
1
+ # coding=utf-8
2
+ # Copyright 2026 XRTM Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import asyncio
17
+ import logging
18
+ from datetime import datetime
19
+ from typing import List, Optional
20
+
21
+ from pydantic import BaseModel
22
+
23
+ # From xrtm-data
24
+ from xrtm.data.schemas.forecast import ForecastOutput, ForecastQuestion
25
+
26
+ # From xrtm-eval
27
+ from xrtm.eval.core.eval.definitions import EvaluationReport, EvaluationResult, Evaluator
28
+ from xrtm.eval.kit.eval.analytics import SliceAnalytics
29
+ from xrtm.eval.kit.eval.metrics import BrierScoreEvaluator, ExpectedCalibrationErrorEvaluator
30
+ from xrtm.eval.schemas.forecast import ForecastResolution
31
+
32
+ # From xrtm-forecast (Internal)
33
+ from xrtm.forecast.core.orchestrator import Orchestrator
34
+ from xrtm.forecast.core.schemas.graph import BaseGraphState, TemporalContext
35
+
36
+ logger = logging.getLogger(__name__)
37
+
38
+
39
+ class BacktestInstance(BaseModel):
40
+ """Represents a single instance in a backtest dataset."""
41
+
42
+ question: ForecastQuestion
43
+ resolution: ForecastResolution
44
+ reference_time: datetime
45
+ tags: Optional[List[str]] = None
46
+
47
+
48
+ class BacktestDataset(BaseModel):
49
+ """A collection of backtest instances representing an evaluation dataset."""
50
+
51
+ name: str = "default_backtest"
52
+ items: List[BacktestInstance]
53
+
54
+
55
+ class BacktestRunner:
56
+ """Executes backtests on a dataset using a provided orchestrator."""
57
+
58
+ def __init__(
59
+ self,
60
+ orchestrator: Orchestrator,
61
+ evaluator: Optional[Evaluator] = None,
62
+ entry_node: str = "ingestion",
63
+ concurrency: int = 5,
64
+ ):
65
+ self.orchestrator = orchestrator
66
+ self.evaluator = evaluator or BrierScoreEvaluator()
67
+ self.entry_node = entry_node
68
+ self.semaphore = asyncio.Semaphore(concurrency)
69
+
70
+ async def _run_single(self, instance: BacktestInstance) -> EvaluationResult:
71
+ async with self.semaphore:
72
+ state = BaseGraphState(
73
+ subject_id=instance.question.id,
74
+ temporal_context=TemporalContext(reference_time=instance.reference_time, is_backtest=True),
75
+ )
76
+ state.context["question_title"] = instance.question.title
77
+ if instance.question.content:
78
+ state.context["question_content"] = instance.question.content
79
+
80
+ try:
81
+ await self.orchestrator.run(state, entry_node=self.entry_node)
82
+ return self.evaluate_state(
83
+ state, instance.resolution, instance.question.id, instance.reference_time, instance.tags
84
+ )
85
+ except Exception as e:
86
+ logger.error(f"Backtest error on {instance.question.id}: {e}")
87
+ return EvaluationResult(
88
+ subject_id=instance.question.id,
89
+ score=1.0,
90
+ ground_truth=instance.resolution.outcome,
91
+ prediction=0.5,
92
+ metadata={"error": str(e)},
93
+ )
94
+
95
+ def evaluate_state(
96
+ self,
97
+ state: BaseGraphState,
98
+ resolution: ForecastResolution,
99
+ subject_id: str,
100
+ reference_time: Optional[datetime] = None,
101
+ tags: Optional[List[str]] = None,
102
+ ) -> EvaluationResult:
103
+ prediction_val = 0.5
104
+ for report in reversed(list(state.node_reports.values())):
105
+ if isinstance(report, ForecastOutput):
106
+ prediction_val = report.confidence
107
+ break
108
+ elif isinstance(report, dict) and "confidence" in report:
109
+ prediction_val = float(report["confidence"])
110
+ break
111
+ elif isinstance(report, (int, float)):
112
+ prediction_val = float(report)
113
+ break
114
+
115
+ outcome_raw = resolution.outcome
116
+ if isinstance(outcome_raw, str):
117
+ if outcome_raw.lower() in ["true", "yes", "1", "pass"]:
118
+ gt_val = 1.0
119
+ elif outcome_raw.lower() in ["false", "no", "0", "fail"]:
120
+ gt_val = 0.0
121
+ else:
122
+ try:
123
+ gt_val = float(outcome_raw)
124
+ except ValueError:
125
+ gt_val = 0.0
126
+ else:
127
+ gt_val = float(outcome_raw)
128
+
129
+ eval_res = self.evaluator.evaluate(prediction=prediction_val, ground_truth=gt_val, subject_id=subject_id)
130
+ if reference_time:
131
+ eval_res.metadata["reference_time"] = reference_time.isoformat()
132
+ eval_res.metadata["total_latency"] = sum(state.latencies.values())
133
+ if tags:
134
+ eval_res.metadata["tags"] = tags
135
+ return eval_res
136
+
137
+ async def run(self, dataset: BacktestDataset) -> EvaluationReport:
138
+ tasks = [self._run_single(item) for item in dataset.items]
139
+ results = await asyncio.gather(*tasks)
140
+ total_score = sum(r.score for r in results)
141
+ count = len(results)
142
+ mean_score = total_score / count if count > 0 else 0.0
143
+ ece_evaluator = ExpectedCalibrationErrorEvaluator()
144
+ ece_score, ece_bins = ece_evaluator.compute_calibration_data(results)
145
+ slices = SliceAnalytics.compute_slices(results)
146
+ return EvaluationReport(
147
+ metric_name=getattr(self.evaluator, "name", "Brier Score"),
148
+ mean_score=mean_score,
149
+ total_evaluations=count,
150
+ results=results,
151
+ reliability_bins=ece_bins,
152
+ summary_statistics={"ece": ece_score},
153
+ slices=slices,
154
+ )
155
+
156
+
157
+ __all__ = ["BacktestInstance", "BacktestDataset", "BacktestRunner"]
@@ -0,0 +1,66 @@
1
+ Metadata-Version: 2.4
2
+ Name: xrtm-train
3
+ Version: 0.1.0
4
+ Summary: The Learning/Optimization layer for XRTM.
5
+ Author-email: XRTM Team <moy@xrtm.org>
6
+ License: Apache-2.0
7
+ Requires-Python: >=3.11
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: pydantic>=2.0.0
11
+ Requires-Dist: numpy>=1.24.0
12
+ Requires-Dist: scikit-learn>=1.3.0
13
+ Requires-Dist: xrtm-data
14
+ Requires-Dist: xrtm-eval
15
+ Requires-Dist: xrtm-forecast
16
+ Provides-Extra: dev
17
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
18
+ Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
19
+ Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
20
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
21
+ Requires-Dist: mypy>=1.0.0; extra == "dev"
22
+ Dynamic: license-file
23
+
24
+ # xrtm-train
25
+
26
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
27
+ [![Python](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
28
+
29
+ **The Optimization Layer for XRTM.**
30
+
31
+ `xrtm-train` is the engine that closes the loop. It simulates history by replaying agents against past "Ground Truth" snapshots stored in `xrtm-data`, scoring them with `xrtm-eval`, and optimizing their reasoning parameters.
32
+
33
+ ## Installation
34
+
35
+ ```bash
36
+ uv pip install xrtm-train
37
+ ```
38
+
39
+ ## Core Primitives
40
+
41
+ ### The Simulation Loop
42
+ The `Backtester` orchestrates the simulation. It ensures strict temporal isolation—agents are never exposed to data from the future.
43
+
44
+ ```python
45
+ from xrtm.train import Backtester
46
+
47
+ # Initialize components
48
+ backtester = Backtester(agent=my_agent, evaluator=my_evaluator)
49
+
50
+ # Run simulation
51
+ results = await backtester.run(dataset=historical_questions)
52
+ print(f"Mean Brier Score: {results.mean_score}")
53
+ ```
54
+
55
+ ## Development
56
+
57
+ Prerequisites:
58
+ - [uv](https://github.com/astral-sh/uv)
59
+
60
+ ```bash
61
+ # Install dependencies
62
+ uv sync
63
+
64
+ # Run tests
65
+ uv run pytest
66
+ ```
@@ -0,0 +1,20 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/xrtm/train/__init__.py
5
+ src/xrtm/train/core/__init__.py
6
+ src/xrtm/train/core/eval/__init__.py
7
+ src/xrtm/train/core/eval/calibration.py
8
+ src/xrtm/train/kit/memory/__init__.py
9
+ src/xrtm/train/kit/memory/learner.py
10
+ src/xrtm/train/kit/optimization/__init__.py
11
+ src/xrtm/train/kit/optimization/compiler.py
12
+ src/xrtm/train/simulation/backtester.py
13
+ src/xrtm/train/simulation/replayer.py
14
+ src/xrtm/train/simulation/runner.py
15
+ src/xrtm_train.egg-info/PKG-INFO
16
+ src/xrtm_train.egg-info/SOURCES.txt
17
+ src/xrtm_train.egg-info/dependency_links.txt
18
+ src/xrtm_train.egg-info/requires.txt
19
+ src/xrtm_train.egg-info/top_level.txt
20
+ tests/test_backtester.py
@@ -0,0 +1,13 @@
1
+ pydantic>=2.0.0
2
+ numpy>=1.24.0
3
+ scikit-learn>=1.3.0
4
+ xrtm-data
5
+ xrtm-eval
6
+ xrtm-forecast
7
+
8
+ [dev]
9
+ pytest>=7.0.0
10
+ pytest-asyncio>=0.21.0
11
+ pytest-cov>=4.1.0
12
+ ruff>=0.1.0
13
+ mypy>=1.0.0
@@ -0,0 +1,60 @@
1
+ # coding=utf-8
2
+ # Copyright 2026 XRTM Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from unittest.mock import AsyncMock, MagicMock
17
+
18
+ import pytest
19
+ from xrtm.data import ForecastOutput, ForecastQuestion
20
+ from xrtm.eval import EvaluationResult
21
+
22
+ from xrtm.train import Backtester
23
+
24
+
25
+ @pytest.mark.asyncio
26
+ async def test_backtester_flow():
27
+ """Verify that Backtester correctly calls agent and evaluator."""
28
+
29
+ # Mocks
30
+ mock_agent = AsyncMock()
31
+ mock_evaluator = MagicMock()
32
+
33
+ # Setup Data
34
+ question = MagicMock(spec=ForecastQuestion)
35
+ question.id = "q1"
36
+ resolution = MagicMock()
37
+ resolution.outcome = 1
38
+
39
+ prediction = MagicMock(spec=ForecastOutput)
40
+ prediction.confidence = 0.8
41
+ mock_agent.run.return_value = prediction
42
+
43
+ eval_result = EvaluationResult(
44
+ subject_id="q1",
45
+ score=0.04,
46
+ ground_truth=1,
47
+ prediction=0.8
48
+ )
49
+ mock_evaluator.evaluate.return_value = eval_result
50
+
51
+ # Run Backtester
52
+ backtester = Backtester(agent=mock_agent, evaluator=mock_evaluator)
53
+ report = await backtester.run([(question, resolution)])
54
+
55
+ # Assertions
56
+ assert report.total_evaluations == 1
57
+ assert report.mean_score == 0.04
58
+
59
+ mock_agent.run.assert_awaited_once_with(question)
60
+ mock_evaluator.evaluate.assert_called_once()