openthai-systemone 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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.4
2
+ Name: openthai-systemone
3
+ Version: 0.1.0
4
+ Summary: OpenThai-SystemOne: an open Thai/English System-One decision model (256-way slot softmax on Qwen3.5-0.8B)
5
+ Author: iApp Technology / OpenThai
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://iapp.co.th/docs/llm/openthai-systemone
8
+ Project-URL: Repository, https://github.com/iapp-technology/openthai-systemone
9
+ Project-URL: Model, https://huggingface.co/iapp/OpenThai-SystemOne
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: torch>=2.4
14
+ Requires-Dist: transformers>=5.0
15
+ Requires-Dist: numpy
16
+ Requires-Dist: pydantic>=2
17
+ Provides-Extra: server
18
+ Requires-Dist: fastapi; extra == "server"
19
+ Requires-Dist: uvicorn; extra == "server"
20
+ Provides-Extra: train
21
+ Requires-Dist: datasets; extra == "train"
22
+ Requires-Dist: accelerate; extra == "train"
23
+ Requires-Dist: pyyaml; extra == "train"
24
+ Requires-Dist: tqdm; extra == "train"
25
+ Requires-Dist: openai; extra == "train"
26
+ Provides-Extra: dev
27
+ Requires-Dist: pytest; extra == "dev"
28
+ Dynamic: license-file
29
+
30
+ # OpenThai-SystemOne
31
+
32
+ ![OpenThai-SystemOne launch: Jev ภาษาไทยมาแล้ว — open Thai + English System One decision model](https://raw.githubusercontent.com/iapp-technology/openthai-systemone/main/docs/assets/fb_launch_v3_1x1.png)
33
+
34
+ Open-source Thai + English **System One decision model**: a Qwen3.5-0.8B text tower whose LM head is replaced by a
35
+ **256-way slot softmax**, continued-pretrained on Thai, and trained to answer typed questions (`choice` / `score` /
36
+ `noul`) about an arbitrary *state* in a single forward pass with calibrated probabilities. The request/response contract
37
+ mirrors TypeSafe AI's `POST /v1/systemone` (Jev), so SDK code written for TypeSafe can point at this model.
38
+
39
+ ## Quickstart
40
+
41
+ ```bash
42
+ pip install "git+https://github.com/iapp-technology/openthai-systemone" # or: pip install openthai-systemone
43
+ ```
44
+
45
+ ```python
46
+ from openthai_systemone import SystemOneClient, Choice, Score, Noul
47
+
48
+ client = SystemOneClient("iapp/OpenThai-SystemOne") # CUDA, MPS or CPU
49
+ resp = client.system_one(
50
+ state={"ticket": "โดนหักเงินซ้ำสองครั้ง ขอเงินคืนด่วน โทรไปสามรอบแล้วไม่มีใครรับ"},
51
+ questions={
52
+ "department": Choice(instructions="ทีมใดควรรับผิดชอบ", criteria={"billing": "การเงิน/คืนเงิน", "technical": "ระบบใช้งานไม่ได้", "sales": None}),
53
+ "frustration": Score(instructions="ลูกค้าหงุดหงิดแค่ไหน", criteria=["ใจเย็น", "หงุดหงิดแต่สุภาพ", "โกรธมาก"]),
54
+ "refund": Noul(instructions="ลูกค้าขอเงินคืนอย่างชัดเจนหรือไม่"),
55
+ },
56
+ )
57
+ print(resp.answers["department"].choice, resp.answers["department"].probabilities)
58
+ print(resp.answers["frustration"].score, resp.answers["refund"].noul)
59
+ ```
60
+
61
+ HTTP server with the same JSON contract as TypeSafe's `POST /v1/systemone`:
62
+
63
+ ```bash
64
+ OPENTHAI_SYSTEMONE_MODEL=iapp/OpenThai-SystemOne uvicorn openthai_systemone.server:app --port 8000
65
+ ```
66
+
67
+ Model card with benchmark tables: https://huggingface.co/iapp/OpenThai-SystemOne. Design rationale: `docs/PLAN.md`.
68
+
69
+ ## Layout
70
+
71
+ ```
72
+ openthai_systemone/ pip package: types (Choice/Score/Noul), formatting (prompt + slots), modeling (SlotHead), client, server
73
+ scripts/00..07_*.py one script per pipeline stage (see below)
74
+ configs/*.yaml CPT / SFT / calibration hyper-parameters (1x H100)
75
+ tests/ CPU unit tests
76
+ ```
77
+
78
+ ## Pipeline
79
+
80
+ | stage | script | where | output |
81
+ |---|---|---|---|
82
+ | 0 surgery | `scripts/00_prepare_base.py` | CPU | `base/qwen3.5-0.8b-text` (vision encoder dropped) |
83
+ | 1 CPT data | `scripts/01_cpt_data.py` | CPU, needs internet | `data/cpt/shard-*.bin` (5B Thai-heavy tokens) |
84
+ | 1 CPT | `scripts/02_cpt_train.py --config configs/cpt.yaml` | 1x H100, ~1 day | `runs/cpt/latest` |
85
+ | 2 decision data | `scripts/03_decision_data.py`, `scripts/03b_synth_generate.py` | CPU + LLM endpoint | `data/decision/*.jsonl`, `data/synth/*.jsonl` |
86
+ | 2 SFT | `scripts/04_decision_train.py --config configs/sft.yaml` | 1x H100, ~0.5 day | `runs/sft/latest` |
87
+ | 3 calibration | `scripts/04_decision_train.py --config configs/calib.yaml --init runs/sft/latest` | 1x H100, hours | `runs/calib/latest` |
88
+ | 4 eval | `scripts/06_eval.py --model runs/calib/latest` | GPU | `runs/eval.json` |
89
+ | 5 release | `scripts/07_export_release.py --ckpt runs/calib/latest --out release/... --push iapp/OpenThai-SystemOne` | – | HF Hub |
90
+
91
+ ## Dev
92
+
93
+ ```bash
94
+ uv venv -p 3.12 .venv && source .venv/bin/activate
95
+ uv pip install -e ".[server,train,dev]"
96
+ pytest -q
97
+ ```
98
+
99
+ Synthetic data needs an OpenAI-compatible endpoint:
100
+
101
+ ```bash
102
+ export SYNTH_BASE_URL=http://localhost:11436/v1 SYNTH_MODEL=openthai2.0-qwen3.8-27b SYNTH_API_KEY=...
103
+ python scripts/03b_synth_generate.py --out data/synth --n 600000 --concurrency 32
104
+ ```
@@ -0,0 +1,75 @@
1
+ # OpenThai-SystemOne
2
+
3
+ ![OpenThai-SystemOne launch: Jev ภาษาไทยมาแล้ว — open Thai + English System One decision model](https://raw.githubusercontent.com/iapp-technology/openthai-systemone/main/docs/assets/fb_launch_v3_1x1.png)
4
+
5
+ Open-source Thai + English **System One decision model**: a Qwen3.5-0.8B text tower whose LM head is replaced by a
6
+ **256-way slot softmax**, continued-pretrained on Thai, and trained to answer typed questions (`choice` / `score` /
7
+ `noul`) about an arbitrary *state* in a single forward pass with calibrated probabilities. The request/response contract
8
+ mirrors TypeSafe AI's `POST /v1/systemone` (Jev), so SDK code written for TypeSafe can point at this model.
9
+
10
+ ## Quickstart
11
+
12
+ ```bash
13
+ pip install "git+https://github.com/iapp-technology/openthai-systemone" # or: pip install openthai-systemone
14
+ ```
15
+
16
+ ```python
17
+ from openthai_systemone import SystemOneClient, Choice, Score, Noul
18
+
19
+ client = SystemOneClient("iapp/OpenThai-SystemOne") # CUDA, MPS or CPU
20
+ resp = client.system_one(
21
+ state={"ticket": "โดนหักเงินซ้ำสองครั้ง ขอเงินคืนด่วน โทรไปสามรอบแล้วไม่มีใครรับ"},
22
+ questions={
23
+ "department": Choice(instructions="ทีมใดควรรับผิดชอบ", criteria={"billing": "การเงิน/คืนเงิน", "technical": "ระบบใช้งานไม่ได้", "sales": None}),
24
+ "frustration": Score(instructions="ลูกค้าหงุดหงิดแค่ไหน", criteria=["ใจเย็น", "หงุดหงิดแต่สุภาพ", "โกรธมาก"]),
25
+ "refund": Noul(instructions="ลูกค้าขอเงินคืนอย่างชัดเจนหรือไม่"),
26
+ },
27
+ )
28
+ print(resp.answers["department"].choice, resp.answers["department"].probabilities)
29
+ print(resp.answers["frustration"].score, resp.answers["refund"].noul)
30
+ ```
31
+
32
+ HTTP server with the same JSON contract as TypeSafe's `POST /v1/systemone`:
33
+
34
+ ```bash
35
+ OPENTHAI_SYSTEMONE_MODEL=iapp/OpenThai-SystemOne uvicorn openthai_systemone.server:app --port 8000
36
+ ```
37
+
38
+ Model card with benchmark tables: https://huggingface.co/iapp/OpenThai-SystemOne. Design rationale: `docs/PLAN.md`.
39
+
40
+ ## Layout
41
+
42
+ ```
43
+ openthai_systemone/ pip package: types (Choice/Score/Noul), formatting (prompt + slots), modeling (SlotHead), client, server
44
+ scripts/00..07_*.py one script per pipeline stage (see below)
45
+ configs/*.yaml CPT / SFT / calibration hyper-parameters (1x H100)
46
+ tests/ CPU unit tests
47
+ ```
48
+
49
+ ## Pipeline
50
+
51
+ | stage | script | where | output |
52
+ |---|---|---|---|
53
+ | 0 surgery | `scripts/00_prepare_base.py` | CPU | `base/qwen3.5-0.8b-text` (vision encoder dropped) |
54
+ | 1 CPT data | `scripts/01_cpt_data.py` | CPU, needs internet | `data/cpt/shard-*.bin` (5B Thai-heavy tokens) |
55
+ | 1 CPT | `scripts/02_cpt_train.py --config configs/cpt.yaml` | 1x H100, ~1 day | `runs/cpt/latest` |
56
+ | 2 decision data | `scripts/03_decision_data.py`, `scripts/03b_synth_generate.py` | CPU + LLM endpoint | `data/decision/*.jsonl`, `data/synth/*.jsonl` |
57
+ | 2 SFT | `scripts/04_decision_train.py --config configs/sft.yaml` | 1x H100, ~0.5 day | `runs/sft/latest` |
58
+ | 3 calibration | `scripts/04_decision_train.py --config configs/calib.yaml --init runs/sft/latest` | 1x H100, hours | `runs/calib/latest` |
59
+ | 4 eval | `scripts/06_eval.py --model runs/calib/latest` | GPU | `runs/eval.json` |
60
+ | 5 release | `scripts/07_export_release.py --ckpt runs/calib/latest --out release/... --push iapp/OpenThai-SystemOne` | – | HF Hub |
61
+
62
+ ## Dev
63
+
64
+ ```bash
65
+ uv venv -p 3.12 .venv && source .venv/bin/activate
66
+ uv pip install -e ".[server,train,dev]"
67
+ pytest -q
68
+ ```
69
+
70
+ Synthetic data needs an OpenAI-compatible endpoint:
71
+
72
+ ```bash
73
+ export SYNTH_BASE_URL=http://localhost:11436/v1 SYNTH_MODEL=openthai2.0-qwen3.8-27b SYNTH_API_KEY=...
74
+ python scripts/03b_synth_generate.py --out data/synth --n 600000 --concurrency 32
75
+ ```
@@ -0,0 +1,21 @@
1
+ from .types import Choice, Noul, Score, ChoiceAnswer, NoulAnswer, ScoreAnswer, SystemOneRequest, SystemOneResponse
2
+ from .configuration import OpenThaiSystemOneConfig
3
+ from .modeling import OpenThaiSystemOneForDecision
4
+ from .formatting import Formatter, SPECIAL_TOKENS, N_SLOTS, ABSTAIN_SLOT
5
+ from .client import SystemOneClient
6
+
7
+ from transformers import AutoConfig, AutoModel
8
+
9
+ try: # make AutoConfig/AutoModel aware of the architecture when the package is installed
10
+ AutoConfig.register("openthai_systemone", OpenThaiSystemOneConfig)
11
+ AutoModel.register(OpenThaiSystemOneConfig, OpenThaiSystemOneForDecision)
12
+ except ValueError: # already registered (e.g. remote code + package both imported)
13
+ pass
14
+
15
+ __version__ = "0.1.0"
16
+ __all__ = [
17
+ "Choice", "Noul", "Score", "ChoiceAnswer", "NoulAnswer", "ScoreAnswer",
18
+ "SystemOneRequest", "SystemOneResponse",
19
+ "OpenThaiSystemOneConfig", "OpenThaiSystemOneForDecision",
20
+ "Formatter", "SPECIAL_TOKENS", "N_SLOTS", "ABSTAIN_SLOT", "SystemOneClient",
21
+ ]
@@ -0,0 +1,109 @@
1
+ """Local inference: `client.system_one(state, questions)` -> answers, mirroring the TypeSafe SDK."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any, Dict, List, Optional, Sequence, Union
5
+
6
+ import torch
7
+ from transformers import AutoTokenizer
8
+
9
+ from .formatting import Encoded, Formatter, collate
10
+ from .modeling import OpenThaiSystemOneForDecision, QTYPE_INDEX, confidence_from_probs, use_reference_kernels
11
+ from .types import (
12
+ Answer,
13
+ Choice,
14
+ ChoiceAnswer,
15
+ Noul,
16
+ NoulAnswer,
17
+ Question,
18
+ Score,
19
+ ScoreAnswer,
20
+ SystemOneResponse,
21
+ Usage,
22
+ parse_question,
23
+ )
24
+
25
+
26
+ class SystemOneClient:
27
+ def __init__(
28
+ self,
29
+ model_path: str,
30
+ *,
31
+ device: Optional[str] = None,
32
+ dtype: Optional[torch.dtype] = None,
33
+ max_total_tokens: int = 65536,
34
+ max_state_tokens: int = 32768,
35
+ model_name: str = "openthai-systemone",
36
+ ):
37
+ if device is None:
38
+ device = "cuda" if torch.cuda.is_available() else ("mps" if torch.backends.mps.is_available() else "cpu")
39
+ if dtype is None:
40
+ dtype = torch.bfloat16 if device == "cuda" else torch.float32
41
+ self.device = device
42
+ if device != "cuda":
43
+ use_reference_kernels()
44
+ self.tok = AutoTokenizer.from_pretrained(model_path)
45
+ self.model = OpenThaiSystemOneForDecision.from_pretrained(model_path, dtype=dtype).to(device).eval()
46
+ self.fmt = Formatter(self.tok, max_total_tokens=max_total_tokens, max_state_tokens=max_state_tokens)
47
+ self.model_name = model_name
48
+ pad = self.tok.pad_token_id
49
+ self.pad_id = pad if pad is not None else (self.tok.eos_token_id or 0)
50
+
51
+ # ------------------------------------------------------------------ public API
52
+ @torch.no_grad()
53
+ def system_one(
54
+ self,
55
+ state: Union[str, Dict[str, Any], List[Any]],
56
+ questions: Dict[str, Union[Question, Dict[str, Any]]],
57
+ ) -> SystemOneResponse:
58
+ return self.system_one_batch([(state, questions)])[0]
59
+
60
+ @torch.no_grad()
61
+ def system_one_batch(
62
+ self,
63
+ items: Sequence[tuple],
64
+ ) -> List[SystemOneResponse]:
65
+ parsed = [(s, {k: parse_question(v) for k, v in qs.items()}) for s, qs in items]
66
+ encs = [self.fmt.encode(s, qs) for s, qs in parsed]
67
+ batch = collate(encs, self.pad_id)
68
+ qtypes = torch.full_like(batch["option_counts"], -1)
69
+ for b, e in enumerate(encs):
70
+ for qi, spec in enumerate(e.specs):
71
+ qtypes[b, qi] = QTYPE_INDEX[spec.qtype]
72
+ batch = {k: v.to(self.device) for k, v in batch.items()}
73
+ out = self.model(
74
+ input_ids=batch["input_ids"],
75
+ attention_mask=batch["attention_mask"],
76
+ answer_positions=batch["answer_positions"],
77
+ option_counts=batch["option_counts"],
78
+ qtypes=qtypes.to(self.device),
79
+ include_abstain=True,
80
+ )
81
+ probs = out.probs.float().cpu()
82
+ return [self._decode(e, probs[b]) for b, e in enumerate(encs)]
83
+
84
+ # ------------------------------------------------------------------ decoding
85
+ def _decode(self, enc: Encoded, probs: torch.Tensor) -> SystemOneResponse:
86
+ answers: Dict[str, Answer] = {}
87
+ for qi, spec in enumerate(enc.specs):
88
+ p = probs[qi]
89
+ k = len(spec.option_names)
90
+ abstain = float(p[self.model.config.abstain_slot])
91
+ pk = p[:k]
92
+ pk = pk / pk.sum().clamp(min=1e-12) # renormalise over the real options
93
+ conf = confidence_from_probs(pk, k)
94
+ if spec.qtype == "noul":
95
+ answers[spec.qid] = NoulAnswer(noul=float(pk[1]))
96
+ elif spec.qtype == "choice":
97
+ prob_map = {spec.option_names[i]: float(pk[i]) for i in range(k)}
98
+ best = max(prob_map, key=prob_map.get)
99
+ answers[spec.qid] = ChoiceAnswer(choice=best, probabilities=prob_map, confidence=conf, abstain=abstain)
100
+ else: # score
101
+ levels = torch.arange(k, dtype=torch.float32)
102
+ score = float((pk * levels).sum())
103
+ answers[spec.qid] = ScoreAnswer(
104
+ score=score,
105
+ legend={i: spec.option_descs[i] or str(i) for i in range(k)},
106
+ probabilities={str(i): float(pk[i]) for i in range(k)},
107
+ confidence=conf,
108
+ )
109
+ return SystemOneResponse(model=self.model_name, answers=answers, usage=Usage(input_tokens=enc.n_tokens))
@@ -0,0 +1,40 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Dict, Optional
4
+
5
+ from transformers import AutoConfig, PretrainedConfig
6
+
7
+
8
+ class OpenThaiSystemOneConfig(PretrainedConfig):
9
+ """Config = a text-tower config (Qwen3.5 text by default) + slot-head settings."""
10
+
11
+ model_type = "openthai_systemone"
12
+ sub_configs = {"text_config": AutoConfig}
13
+
14
+ def __init__(
15
+ self,
16
+ text_config: Optional[Dict[str, Any] | PretrainedConfig] = None,
17
+ n_slots: int = 256,
18
+ abstain_slot: int = 255,
19
+ answer_token_id: Optional[int] = None,
20
+ head_bias: bool = True,
21
+ n_temperatures: int = 3, # per question type: choice / score / noul
22
+ **kwargs,
23
+ ):
24
+ if isinstance(text_config, dict):
25
+ text_config = AutoConfig.for_model(**text_config) if "model_type" in text_config else AutoConfig.for_model("qwen3_5_text", **text_config)
26
+ self.text_config = text_config
27
+ self.n_slots = n_slots
28
+ self.abstain_slot = abstain_slot
29
+ self.answer_token_id = answer_token_id
30
+ self.head_bias = head_bias
31
+ self.n_temperatures = n_temperatures
32
+ super().__init__(**kwargs)
33
+
34
+ @property
35
+ def hidden_size(self) -> int:
36
+ return self.text_config.hidden_size
37
+
38
+ @property
39
+ def vocab_size(self) -> int:
40
+ return self.text_config.vocab_size
@@ -0,0 +1,95 @@
1
+ """Unified decision record format shared by all data builders and the SFT trainer.
2
+
3
+ {
4
+ "id": str, "source": str, "lang": "th"|"en"|"mixed"|..., "split": "train"|"eval",
5
+ "state": str | dict | list,
6
+ "questions": {qid: {"type": "choice"|"score"|"noul", "instructions": str, "criteria": ...}},
7
+ "labels": {qid: option-name | level-index | bool}
8
+ }
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import random
14
+ from dataclasses import dataclass, field
15
+ from typing import Any, Dict, Iterable, Iterator, List, Optional, Union
16
+
17
+ # Instruction paraphrases: the model must not overfit to one phrasing per dataset.
18
+ TH_CHOICE_TEMPLATES = [
19
+ "ข้อความนี้จัดอยู่ในหมวด{what}ใด",
20
+ "เลือก{what}ที่ตรงกับข้อความมากที่สุด",
21
+ "จาก state ด้านบน {what}ที่ถูกต้องคือข้อใด",
22
+ "ระบุ{what}ของข้อความนี้",
23
+ ]
24
+ EN_CHOICE_TEMPLATES = [
25
+ "Which {what} best matches this text?",
26
+ "Classify the {what} of the state above.",
27
+ "Select the correct {what}.",
28
+ "What is the {what}?",
29
+ ]
30
+ TH_NOUL_TEMPLATES = ["ข้อความนี้{what}หรือไม่", "จริงหรือไม่ว่า ข้อความนี้{what}", "state นี้{what}ใช่หรือไม่"]
31
+ EN_NOUL_TEMPLATES = ["Is this text {what}?", "Does the state {what}?", "True or false: the text {what}."]
32
+
33
+
34
+ @dataclass
35
+ class Record:
36
+ id: str
37
+ source: str
38
+ lang: str
39
+ state: Union[str, Dict[str, Any], List[Any]]
40
+ questions: Dict[str, Dict[str, Any]]
41
+ labels: Dict[str, Union[str, int, bool]]
42
+ split: str = "train"
43
+ meta: Dict[str, Any] = field(default_factory=dict)
44
+
45
+ def to_json(self) -> str:
46
+ return json.dumps(self.__dict__, ensure_ascii=False)
47
+
48
+ @staticmethod
49
+ def from_json(line: str) -> "Record":
50
+ d = json.loads(line)
51
+ known = {"id", "source", "lang", "state", "questions", "labels", "split", "meta"}
52
+ meta = dict(d.get("meta", {}))
53
+ meta.update({k: v for k, v in d.items() if k not in known})
54
+ return Record(**{k: d[k] for k in ("id", "source", "lang", "state", "questions", "labels")},
55
+ split=d.get("split", "train"), meta=meta)
56
+
57
+
58
+ def choice_q(instructions: str, options: Iterable[str], descs: Optional[Dict[str, Optional[str]]] = None) -> Dict[str, Any]:
59
+ descs = descs or {}
60
+ return {"type": "choice", "instructions": instructions, "criteria": {o: descs.get(o) for o in options}}
61
+
62
+
63
+ def score_q(instructions: str, levels: List[str]) -> Dict[str, Any]:
64
+ return {"type": "score", "instructions": instructions, "criteria": list(levels)}
65
+
66
+
67
+ def noul_q(instructions: str, true_desc: Optional[str] = None, false_desc: Optional[str] = None) -> Dict[str, Any]:
68
+ q: Dict[str, Any] = {"type": "noul", "instructions": instructions}
69
+ if true_desc or false_desc:
70
+ q["criteria"] = {"true": true_desc, "false": false_desc}
71
+ return q
72
+
73
+
74
+ def pick_template(rng: random.Random, lang: str, kind: str, what: str) -> str:
75
+ if kind == "choice":
76
+ t = TH_CHOICE_TEMPLATES if lang == "th" else EN_CHOICE_TEMPLATES
77
+ else:
78
+ t = TH_NOUL_TEMPLATES if lang == "th" else EN_NOUL_TEMPLATES
79
+ return rng.choice(t).format(what=what)
80
+
81
+
82
+ def write_jsonl(path, records: Iterable[Record]) -> int:
83
+ n = 0
84
+ with open(path, "w", encoding="utf-8") as f:
85
+ for r in records:
86
+ f.write(r.to_json() + "\n")
87
+ n += 1
88
+ return n
89
+
90
+
91
+ def read_jsonl(path) -> Iterator[Record]:
92
+ with open(path, encoding="utf-8") as f:
93
+ for line in f:
94
+ if line.strip():
95
+ yield Record.from_json(line)