kobkrit commited on
Commit
dfba102
·
verified ·
1 Parent(s): c7d85d1

OpenThai-SystemOne release

Browse files
Files changed (11) hide show
  1. .gitattributes +1 -0
  2. README.md +176 -0
  3. chat_template.jinja +154 -0
  4. config.json +107 -0
  5. configuration.py +40 -0
  6. formatting.py +291 -0
  7. model.safetensors +3 -0
  8. modeling.py +210 -0
  9. tokenizer.json +3 -0
  10. tokenizer_config.json +32 -0
  11. types.py +135 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - th
5
+ - en
6
+ base_model: Qwen/Qwen3.5-0.8B-Base
7
+ pipeline_tag: zero-shot-classification
8
+ tags:
9
+ - thai
10
+ - zero-shot-classification
11
+ - system-one
12
+ - decision-model
13
+ - computer-use
14
+ - openthaigpt
15
+ - iapp
16
+ ---
17
+
18
+ # OpenThai-SystemOne
19
+
20
+ **An open Thai + English "System One" decision model.** It does not generate text. Given a *state* (any text or JSON)
21
+ and typed *questions*, it returns calibrated probabilities over the options in **one forward pass**:
22
+
23
+ | Question | You give | You get |
24
+ |---|---|---|
25
+ | `choice` | instructions + up to **255 options** (name → description or null) | `choice`, `probabilities`, `confidence` |
26
+ | `score` | instructions + 2–10 ordered level descriptions | `score` (probability-weighted, fractional), `probabilities`, `confidence` |
27
+ | `noul` | a yes/no question | `noul` = p(yes) |
28
+
29
+ The request/response contract mirrors TypeSafe's `POST /v1/systemone` so code written for the TypeSafe SDK can be
30
+ pointed at this model unchanged. Typical uses: ticket routing, moderation, intent detection, RAG relevance judging,
31
+ LLM-output verification, and **computer-use / browser-agent action selection** (which element to click, which tool to call).
32
+
33
+ ## How it works
34
+
35
+ * Backbone: text tower of [Qwen/Qwen3.5-0.8B-Base](https://huggingface.co/Qwen/Qwen3.5-0.8B-Base) (24 layers, hybrid
36
+ Gated-DeltaNet / attention, 262k context), vision encoder removed, then **continued-pretrained on ~5B tokens of Thai**
37
+ (web, Wikipedia, parallel Thai↔English, and machine-state text such as accessibility trees and JSON).
38
+ * The 248k-token LM head is **replaced by a 256-way slot head**. Options are introduced by control tokens
39
+ `<|ts_opt_0|> … <|ts_opt_254|>`; the hidden state at each `<|ts_answer|>` token is projected to 256 logits, slots beyond
40
+ the number of options are masked, and a softmax gives the distribution. Slot 255 is *abstain* (none of the options fit).
41
+ * Trained on ~2–3M decision examples converted from public Thai/English classification, NLI, QA, rating, agent and
42
+ tool-selection datasets plus synthetic Thai/English decision tasks, with option-order shuffling and abstain examples;
43
+ then a short calibration stage (Brier loss + per-type temperature) so that higher confidence ⇒ higher accuracy.
44
+
45
+ ## Usage
46
+
47
+ ```bash
48
+ pip install openthai-systemone # or: pip install "git+https://github.com/iapp-technology/openthai-systemone"
49
+ ```
50
+
51
+ ```python
52
+ from openthai_systemone import SystemOneClient, Choice, Score, Noul
53
+
54
+ client = SystemOneClient("iapp/OpenThai-SystemOne")
55
+ resp = client.system_one(
56
+ state={"ticket": "ลูกค้าแจ้งว่าโดนหักเงินซ้ำสองครั้ง ขอเงินคืนด่วน โทรมาสามรอบแล้ว"},
57
+ questions={
58
+ "department": Choice(instructions="ทีมใดควรรับผิดชอบ", criteria={"billing": "การเงิน/ค่าบริการ", "technical": "ระบบใช้งานไม่ได้", "sales": None}),
59
+ "frustration": Score(instructions="ลูกค้าหงุดหงิดแค่ไหน", criteria=["ใจเย็น", "หงุดหงิดแต่สุภาพ", "โกรธมาก"]),
60
+ "refund_requested": Noul(instructions="ลูกค้าขอเงินคืนอย่างชัดเจนหรือไม่"),
61
+ },
62
+ )
63
+ print(resp.answers["department"].choice, resp.answers["department"].probabilities)
64
+ print(resp.answers["frustration"].score, resp.answers["refund_requested"].noul)
65
+ ```
66
+
67
+ HTTP server with the TypeSafe-compatible contract:
68
+
69
+ ```bash
70
+ OPENTHAI_SYSTEMONE_MODEL=iapp/OpenThai-SystemOne uvicorn openthai_systemone.server:app --port 8000
71
+ curl -X POST localhost:8000/v1/systemone -H 'content-type: application/json' -d '{"state": "...", "questions": {...}}'
72
+ ```
73
+
74
+ Or with plain transformers (remote code shipped in this repo):
75
+
76
+ ```python
77
+ from transformers import AutoModel, AutoTokenizer
78
+ model = AutoModel.from_pretrained("iapp/OpenThai-SystemOne", trust_remote_code=True)
79
+ ```
80
+
81
+ ## Evaluation
82
+
83
+ All numbers are zero-shot: the model sees only the state, the instructions and the option names/descriptions.
84
+
85
+ ### Public benchmark (same 13 subsets, splits, instructions and sampler as Bespoke Nimble's `docs/PUBLIC_BENCHMARKS.md`)
86
+
87
+ Nimble-9B and Jev numbers are as published by Bespoke Labs (2026-09-18); ours are measured with `scripts/06_eval.py`
88
+ on `scripts/06b_public_benchmarks.py` rebuilds of the same subsets.
89
+
90
+ | subset | type | n | **OpenThai 0.8B** | Nimble-9B | Jev 1.13.0 | our ECE |
91
+ |---|---|---|---|---|---|---|
92
+ | aegis2 | noul | 250 | 58.0 | 81.2 | 80.4 | 0.243 |
93
+ | boolq | noul | 300 | 63.7 | 86.0 | 89.7 | 0.195 |
94
+ | civil_comments | noul | 300 | **78.0** | 70.3 | 81.0 | 0.127 |
95
+ | helpsteer2 | score | 250 | **42.8** | 39.0 | 34.1 | 0.400 |
96
+ | massive-de-DE | choice | 350 | 64.6 | 83.4 | 86.9 | 0.199 |
97
+ | massive-en-US | choice | 350 | 75.7 | 86.9 | 87.4 | 0.133 |
98
+ | multinli | choice | 299 | **85.6** | 85.3 | 82.9 | 0.035 |
99
+ | paws | noul | 250 | 67.2 | 82.8 | 89.2 | 0.143 |
100
+ | pubmedqa | choice | 250 | 53.6 | 75.6 | 77.2 | 0.154 |
101
+ | squad2 | noul | 299 | 50.2 | 80.6 | 82.9 | 0.461 |
102
+ | summeval-consistency | score | 144 | **84.0** | 75.7 | 81.2 | 0.061 |
103
+ | summeval-relevance | score | 240 | 13.8 | 49.2 | 35.0 | 0.791 |
104
+ | vitaminc-dev | choice | 599 | 67.1 | 76.6 | 80.1 | 0.098 |
105
+ | **macro average** | | | **61.9** | 74.8 | 76.0 | |
106
+
107
+ Reference: raw Qwen3.5-0.8B prompted with letter log-probs scores 45.4 macro on the same bench (Bespoke's number).
108
+ `choice`/`noul` report accuracy; `score` reports exact-level match. Bold = ahead of Bespoke-Nimble-9B.
109
+ Honest reading: the 0.8B model is ahead of the 9B on 4 of 13 subsets (NLI, summary consistency, helpfulness scoring,
110
+ toxicity) and clearly behind on reading-comprehension style yes/no tasks (squad2 is at chance, boolq, pubmedqa) and on
111
+ summary *relevance* scoring, which is the one subset where our score head is badly miscalibrated (ECE 0.79).
112
+
113
+ ### Thai held-out sets (never in training; whole datasets held out where marked)
114
+
115
+ | set | type | n | accuracy | macro-F1 / MAE | ECE | note |
116
+ |---|---|---|---|---|---|---|
117
+ | MASSIVE-th intent (60-way) | choice | 5007 | **86.4** | F1 0.829 | 0.048 | eval split |
118
+ | Prachathai67k topics | choice | 3501 | **97.7** | F1 0.924 | 0.005 | eval split |
119
+ | Prachathai67k topics | noul | 13119 | **94.1** | | 0.008 | eval split |
120
+ | XNLI-th | choice | 2490 | **76.5** | F1 0.767 | 0.028 | eval split |
121
+ | XNLI-th (entailment yes/no) | noul | 2490 | **84.3** | | 0.042 | eval split |
122
+ | SIB-200 Thai topic (7-way) | choice | 204 | **77.5** | F1 0.752 | 0.074 | whole dataset held out |
123
+ | Thai contrastive pairs (one-fact flips) | choice | 296 | **78.7** | F1 0.724 | 0.105 | synthetic, eval-only |
124
+ | Thai contrastive pairs | score | 56 | **73.2** | MAE 0.48 | 0.133 | synthetic, eval-only |
125
+ | Thai contrastive pairs | noul | 248 | **82.3** | | 0.088 | synthetic, eval-only |
126
+ | Wongnai review stars (1–5) | score | 6203 | **63.3** | MAE 0.44 | 0.010 | eval split |
127
+ | Wisesight sentiment (4-class) | choice | 2671 | 38.7 | F1 0.357 | 0.341 | whole dataset held out — **known weak spot**, v0.2 targets it |
128
+ | banking77 intent (77-way, English) | choice | 3076 | 32.7 | F1 0.290 | 0.165 | whole dataset held out — weak on fine-grained 77-way intents |
129
+ | xLAM tool selection (English) | choice | 884 | **99.4** | F1 0.986 | 0.007 | eval slice |
130
+
131
+ Batch-1 latency, one question with 255 options, H100 shared with a training job: **44 ms** (public bench run),
132
+ 48 ms (held-out run). A 3-question Thai ticket (166 tokens): ~40 ms on H100, 154 ms on a MacBook M3 Max (MPS).
133
+
134
+ ### Calibration (Stage 3)
135
+
136
+ After SFT (12k steps) the backbone was frozen and the slot head plus one temperature per question type were trained for
137
+ 400 steps on the SFT mixture with cross-entropy + Brier loss (`configs/calib.yaml`, `brier_weight: 1.0`,
138
+ `train_temperature: true`). Learned temperatures: choice 1.062, noul 1.047, score 1.008.
139
+
140
+ Before/after on the same sources (before = SFT checkpoint, 150–300-item smoke slices; after = calibrated checkpoint, full slices,
141
+ so accuracies are not strictly comparable, ECE is):
142
+
143
+ | set | type | ECE before → after | accuracy before → after |
144
+ |---|---|---|---|
145
+ | multinli | choice | 0.049 → **0.035** | 84.7 → 85.6 |
146
+ | massive-en-US | choice | 0.064 → 0.133 | 73.3 → 75.7 |
147
+ | boolq | noul | 0.086 → 0.195 | 69.3 → 63.7 |
148
+ | paws | noul | 0.108 → 0.143 | 69.3 → 67.2 |
149
+ | vitaminc-dev | choice | 0.104 → **0.098** | 58.0 → 67.1 |
150
+ | MASSIVE-th | choice | 0.032 → 0.048 | 89.7 → 86.4 |
151
+ | Prachathai (choice / noul) | | 0.033 / 0.024 → **0.005 / 0.008** | 97.4 / 93.4 → 97.7 / 94.1 |
152
+ | XNLI-th (choice / noul) | | 0.062 / 0.012 → **0.028 / 0.042** | 80.0 / 87.0 → 76.5 / 84.3 |
153
+ | SIB-200 th | choice | 0.062 → 0.074 | 77.5 → 77.5 |
154
+ | Wongnai stars | score | 0.071 → **0.010** | 66.3 → 63.3 |
155
+ | Thai contrastive (choice / noul) | | 0.083 / 0.075 → 0.105 / 0.088 | 79.1 / 84.6 → 78.7 / 82.3 |
156
+ | Wisesight | choice | 0.286 → 0.341 | 39.0 → 38.7 |
157
+
158
+ Reading: calibration helps where the model is already competent (Thai topic/NLI, Wongnai scoring, MultiNLI: ECE
159
+ ≤ 0.05) and does not rescue sets where accuracy itself is low (wisesight, squad2, summeval-relevance) — a temperature
160
+ cannot fix a wrong ranking. On the English public bench the median ECE is 0.15; treat `confidence` as reliable on the
161
+ Thai sets and on NLI/topic tasks, and route low-confidence English yes/no decisions to a bigger model.
162
+
163
+ ## Limits
164
+
165
+ * Text only. Up to 255 options per question in one stage (bucket into groups for more). 64k tokens per request.
166
+ * It is a small model: use the `confidence` field and route low-confidence cases to a bigger model or a human.
167
+ * Not a reasoning model: it will not do multi-step verification or arithmetic.
168
+ * v0.1 known weak spots (numbers above): Thai social-media sentiment (wisesight 38.7), fine-grained 77-way English
169
+ intents (banking77 32.7), extractive-QA style yes/no (squad2 at chance), and summary *relevance* scoring. v0.2 adds a
170
+ synthetic Thai sentiment set and a second SFT round; expect the first to move, not the others.
171
+ * English calibration is weaker than Thai (median ECE 0.15 vs ≤ 0.05): the training mix is Thai-heavy by design.
172
+
173
+ ## License & credits
174
+
175
+ Apache-2.0. Built by iApp Technology / OpenThaiGPT on Qwen3.5-0.8B-Base (Apache-2.0). Inspired by TypeSafe AI's
176
+ System One models (Jev); this is an independent open re-implementation and is not affiliated with TypeSafe AI.
chat_template.jinja ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- set image_count = namespace(value=0) %}
2
+ {%- set video_count = namespace(value=0) %}
3
+ {%- macro render_content(content, do_vision_count, is_system_content=false) %}
4
+ {%- if content is string %}
5
+ {{- content }}
6
+ {%- elif content is iterable and content is not mapping %}
7
+ {%- for item in content %}
8
+ {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
9
+ {%- if is_system_content %}
10
+ {{- raise_exception('System message cannot contain images.') }}
11
+ {%- endif %}
12
+ {%- if do_vision_count %}
13
+ {%- set image_count.value = image_count.value + 1 %}
14
+ {%- endif %}
15
+ {%- if add_vision_id %}
16
+ {{- 'Picture ' ~ image_count.value ~ ': ' }}
17
+ {%- endif %}
18
+ {{- '<|vision_start|><|image_pad|><|vision_end|>' }}
19
+ {%- elif 'video' in item or item.type == 'video' %}
20
+ {%- if is_system_content %}
21
+ {{- raise_exception('System message cannot contain videos.') }}
22
+ {%- endif %}
23
+ {%- if do_vision_count %}
24
+ {%- set video_count.value = video_count.value + 1 %}
25
+ {%- endif %}
26
+ {%- if add_vision_id %}
27
+ {{- 'Video ' ~ video_count.value ~ ': ' }}
28
+ {%- endif %}
29
+ {{- '<|vision_start|><|video_pad|><|vision_end|>' }}
30
+ {%- elif 'text' in item %}
31
+ {{- item.text }}
32
+ {%- else %}
33
+ {{- raise_exception('Unexpected item type in content.') }}
34
+ {%- endif %}
35
+ {%- endfor %}
36
+ {%- elif content is none or content is undefined %}
37
+ {{- '' }}
38
+ {%- else %}
39
+ {{- raise_exception('Unexpected content type.') }}
40
+ {%- endif %}
41
+ {%- endmacro %}
42
+ {%- if not messages %}
43
+ {{- raise_exception('No messages provided.') }}
44
+ {%- endif %}
45
+ {%- if tools and tools is iterable and tools is not mapping %}
46
+ {{- '<|im_start|>system\n' }}
47
+ {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
48
+ {%- for tool in tools %}
49
+ {{- "\n" }}
50
+ {{- tool | tojson }}
51
+ {%- endfor %}
52
+ {{- "\n</tools>" }}
53
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
54
+ {%- if messages[0].role == 'system' %}
55
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
56
+ {%- if content %}
57
+ {{- '\n\n' + content }}
58
+ {%- endif %}
59
+ {%- endif %}
60
+ {{- '<|im_end|>\n' }}
61
+ {%- else %}
62
+ {%- if messages[0].role == 'system' %}
63
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
64
+ {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
65
+ {%- endif %}
66
+ {%- endif %}
67
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
68
+ {%- for message in messages[::-1] %}
69
+ {%- set index = (messages|length - 1) - loop.index0 %}
70
+ {%- if ns.multi_step_tool and message.role == "user" %}
71
+ {%- set content = render_content(message.content, false)|trim %}
72
+ {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
73
+ {%- set ns.multi_step_tool = false %}
74
+ {%- set ns.last_query_index = index %}
75
+ {%- endif %}
76
+ {%- endif %}
77
+ {%- endfor %}
78
+ {%- if ns.multi_step_tool %}
79
+ {{- raise_exception('No user query found in messages.') }}
80
+ {%- endif %}
81
+ {%- for message in messages %}
82
+ {%- set content = render_content(message.content, true)|trim %}
83
+ {%- if message.role == "system" %}
84
+ {%- if not loop.first %}
85
+ {{- raise_exception('System message must be at the beginning.') }}
86
+ {%- endif %}
87
+ {%- elif message.role == "user" %}
88
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
89
+ {%- elif message.role == "assistant" %}
90
+ {%- set reasoning_content = '' %}
91
+ {%- if message.reasoning_content is string %}
92
+ {%- set reasoning_content = message.reasoning_content %}
93
+ {%- else %}
94
+ {%- if '</think>' in content %}
95
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
96
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
97
+ {%- endif %}
98
+ {%- endif %}
99
+ {%- set reasoning_content = reasoning_content|trim %}
100
+ {%- if loop.index0 > ns.last_query_index %}
101
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
102
+ {%- else %}
103
+ {{- '<|im_start|>' + message.role + '\n' + content }}
104
+ {%- endif %}
105
+ {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
106
+ {%- for tool_call in message.tool_calls %}
107
+ {%- if tool_call.function is defined %}
108
+ {%- set tool_call = tool_call.function %}
109
+ {%- endif %}
110
+ {%- if loop.first %}
111
+ {%- if content|trim %}
112
+ {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
113
+ {%- else %}
114
+ {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
115
+ {%- endif %}
116
+ {%- else %}
117
+ {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
118
+ {%- endif %}
119
+ {%- if tool_call.arguments is defined %}
120
+ {%- for args_name, args_value in tool_call.arguments|items %}
121
+ {{- '<parameter=' + args_name + '>\n' }}
122
+ {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
123
+ {{- args_value }}
124
+ {{- '\n</parameter>\n' }}
125
+ {%- endfor %}
126
+ {%- endif %}
127
+ {{- '</function>\n</tool_call>' }}
128
+ {%- endfor %}
129
+ {%- endif %}
130
+ {{- '<|im_end|>\n' }}
131
+ {%- elif message.role == "tool" %}
132
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
133
+ {{- '<|im_start|>user' }}
134
+ {%- endif %}
135
+ {{- '\n<tool_response>\n' }}
136
+ {{- content }}
137
+ {{- '\n</tool_response>' }}
138
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
139
+ {{- '<|im_end|>\n' }}
140
+ {%- elif loop.last %}
141
+ {{- '<|im_end|>\n' }}
142
+ {%- endif %}
143
+ {%- else %}
144
+ {{- raise_exception('Unexpected message role.') }}
145
+ {%- endif %}
146
+ {%- endfor %}
147
+ {%- if add_generation_prompt %}
148
+ {{- '<|im_start|>assistant\n' }}
149
+ {%- if enable_thinking is defined and enable_thinking is true %}
150
+ {{- '<think>\n' }}
151
+ {%- else %}
152
+ {{- '<think>\n\n</think>\n\n' }}
153
+ {%- endif %}
154
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "abstain_slot": 255,
3
+ "answer_token_id": 248082,
4
+ "architectures": [
5
+ "OpenThaiSystemOneForDecision"
6
+ ],
7
+ "dtype": "bfloat16",
8
+ "head_bias": true,
9
+ "model_type": "openthai_systemone",
10
+ "n_slots": 256,
11
+ "n_temperatures": 3,
12
+ "pad_token_id": 248044,
13
+ "text_config": {
14
+ "_name_or_path": "runs/cpt/latest",
15
+ "architectures": [
16
+ "Qwen3_5ForCausalLM"
17
+ ],
18
+ "attention_bias": false,
19
+ "attention_dropout": 0.0,
20
+ "attn_output_gate": true,
21
+ "bos_token_id": null,
22
+ "chunk_size_feed_forward": 0,
23
+ "dtype": "bfloat16",
24
+ "eos_token_id": 248044,
25
+ "full_attention_interval": 4,
26
+ "head_dim": 256,
27
+ "hidden_act": "silu",
28
+ "hidden_size": 1024,
29
+ "id2label": {
30
+ "0": "LABEL_0",
31
+ "1": "LABEL_1"
32
+ },
33
+ "initializer_range": 0.02,
34
+ "intermediate_size": 3584,
35
+ "is_encoder_decoder": false,
36
+ "label2id": {
37
+ "LABEL_0": 0,
38
+ "LABEL_1": 1
39
+ },
40
+ "layer_types": [
41
+ "linear_attention",
42
+ "linear_attention",
43
+ "linear_attention",
44
+ "full_attention",
45
+ "linear_attention",
46
+ "linear_attention",
47
+ "linear_attention",
48
+ "full_attention",
49
+ "linear_attention",
50
+ "linear_attention",
51
+ "linear_attention",
52
+ "full_attention",
53
+ "linear_attention",
54
+ "linear_attention",
55
+ "linear_attention",
56
+ "full_attention",
57
+ "linear_attention",
58
+ "linear_attention",
59
+ "linear_attention",
60
+ "full_attention",
61
+ "linear_attention",
62
+ "linear_attention",
63
+ "linear_attention",
64
+ "full_attention"
65
+ ],
66
+ "linear_conv_kernel_dim": 4,
67
+ "linear_key_head_dim": 128,
68
+ "linear_num_key_heads": 16,
69
+ "linear_num_value_heads": 16,
70
+ "linear_value_head_dim": 128,
71
+ "mamba_ssm_dtype": "float32",
72
+ "max_position_embeddings": 262144,
73
+ "mlp_only_layers": [],
74
+ "model_type": "qwen3_5_text",
75
+ "mtp_num_hidden_layers": 1,
76
+ "mtp_use_dedicated_embeddings": false,
77
+ "num_attention_heads": 8,
78
+ "num_hidden_layers": 24,
79
+ "num_key_value_heads": 2,
80
+ "output_attentions": false,
81
+ "output_hidden_states": false,
82
+ "pad_token_id": null,
83
+ "partial_rotary_factor": 0.25,
84
+ "problem_type": null,
85
+ "return_dict": true,
86
+ "rms_norm_eps": 1e-06,
87
+ "rope_parameters": {
88
+ "mrope_interleaved": true,
89
+ "mrope_section": [
90
+ 11,
91
+ 11,
92
+ 10
93
+ ],
94
+ "partial_rotary_factor": 0.25,
95
+ "rope_theta": 10000000,
96
+ "rope_type": "default"
97
+ },
98
+ "tie_word_embeddings": false,
99
+ "use_cache": true,
100
+ "vocab_size": 248339
101
+ },
102
+ "transformers_version": "5.17.0",
103
+ "auto_map": {
104
+ "AutoConfig": "configuration.OpenThaiSystemOneConfig",
105
+ "AutoModel": "modeling.OpenThaiSystemOneForDecision"
106
+ }
107
+ }
configuration.py ADDED
@@ -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
formatting.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Turn (state, questions) into token ids + slot bookkeeping.
2
+
3
+ Layout (one sequence, causal):
4
+
5
+ <|ts_state|> {state text}
6
+ <|ts_q|><|ts_choice|> {instructions}
7
+ <|ts_opt_0|> {option name}: {description}
8
+ <|ts_opt_1|> {option name}
9
+ ...
10
+ <|ts_answer|> <- hidden state here -> SlotHead (256 logits)
11
+ <|ts_q|><|ts_noul|> {instructions}
12
+ <|ts_opt_0|> no
13
+ <|ts_opt_1|> yes
14
+ <|ts_answer|>
15
+ ...
16
+
17
+ Slot i (0..254) means "the option introduced by <|ts_opt_i|>"; slot 255 = abstain.
18
+ All answers for all questions are read out from one forward pass.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import json
23
+ import random
24
+ from dataclasses import dataclass, field
25
+ from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
26
+
27
+ from .types import Choice, Noul, Score, Question, MAX_OPTIONS
28
+
29
+ N_SLOTS = 256
30
+ ABSTAIN_SLOT = 255
31
+
32
+ TOK_STATE = "<|ts_state|>"
33
+ TOK_Q = "<|ts_q|>"
34
+ TOK_CHOICE = "<|ts_choice|>"
35
+ TOK_SCORE = "<|ts_score|>"
36
+ TOK_NOUL = "<|ts_noul|>"
37
+ TOK_ANSWER = "<|ts_answer|>"
38
+ TOK_OPT = [f"<|ts_opt_{i}|>" for i in range(N_SLOTS)]
39
+
40
+ SPECIAL_TOKENS: List[str] = [TOK_STATE, TOK_Q, TOK_CHOICE, TOK_SCORE, TOK_NOUL, TOK_ANSWER] + TOK_OPT
41
+
42
+ NOUL_OPTIONS = ("no", "yes") # slot 0 = no, slot 1 = yes -> noul = p(slot 1)
43
+
44
+ DEFAULT_MAX_TOTAL_TOKENS = 65536
45
+ DEFAULT_MAX_STATE_TOKENS = 32768
46
+
47
+
48
+ def add_special_tokens(tokenizer) -> int:
49
+ """Register the TypeSafe control tokens. Returns number of tokens added."""
50
+ existing = set(tokenizer.get_vocab())
51
+ new = [t for t in SPECIAL_TOKENS if t not in existing]
52
+ if not new:
53
+ return 0
54
+ return tokenizer.add_tokens(new, special_tokens=True)
55
+
56
+
57
+ def sanitize(text: str) -> str:
58
+ """Stop user content from smuggling control tokens into the sequence."""
59
+ return text.replace("<|ts_", "<​|ts_") if "<|ts_" in text else text
60
+
61
+
62
+ def state_to_text(state: Union[str, Dict[str, Any], List[Any]], *, indent: Optional[int] = None) -> str:
63
+ if isinstance(state, str):
64
+ return state
65
+ return json.dumps(state, ensure_ascii=False, indent=indent)
66
+
67
+
68
+ @dataclass
69
+ class QuestionSpec:
70
+ """A question flattened to option strings + slot bookkeeping."""
71
+
72
+ qid: str
73
+ qtype: str # choice | score | noul
74
+ instructions: str
75
+ option_names: List[str] # in slot order (after any permutation)
76
+ option_descs: List[Optional[str]]
77
+ perm: List[int] # perm[slot] = original index of the option at that slot
78
+ label_slot: Optional[int] = None # training only
79
+
80
+
81
+ def question_to_spec(
82
+ qid: str,
83
+ q: Question,
84
+ *,
85
+ label: Optional[Union[str, int, bool]] = None,
86
+ shuffle: bool = False,
87
+ rng: Optional[random.Random] = None,
88
+ drop_label: bool = False,
89
+ ) -> QuestionSpec:
90
+ """Flatten a typed question.
91
+
92
+ label: for training. Choice -> option name; Score -> level index (int); Noul -> bool.
93
+ shuffle: permute option order (Choice only; Score/Noul order is semantic).
94
+ drop_label: remove the correct option from a Choice so the target becomes ABSTAIN_SLOT.
95
+ """
96
+ if isinstance(q, Choice):
97
+ names = list(q.criteria.keys())
98
+ descs = [q.criteria[n] for n in names]
99
+ idx = list(range(len(names)))
100
+ label_idx = None
101
+ if label is not None:
102
+ if label not in q.criteria:
103
+ raise ValueError(f"label {label!r} is not one of the options")
104
+ label_idx = names.index(str(label))
105
+ if drop_label and label_idx is not None:
106
+ if len(idx) < 2:
107
+ raise ValueError("cannot drop the only option")
108
+ idx.remove(label_idx)
109
+ label_idx = None
110
+ if shuffle:
111
+ (rng or random).shuffle(idx)
112
+ names_p = [names[i] for i in idx]
113
+ descs_p = [descs[i] for i in idx]
114
+ if label is None:
115
+ slot = None
116
+ elif label_idx is None:
117
+ slot = ABSTAIN_SLOT
118
+ else:
119
+ slot = idx.index(label_idx)
120
+ return QuestionSpec(qid, "choice", q.instructions, names_p, descs_p, idx, slot)
121
+
122
+ if isinstance(q, Score):
123
+ names = [str(i) for i in range(len(q.criteria))]
124
+ descs = list(q.criteria)
125
+ slot = int(label) if label is not None else None
126
+ if slot is not None and not (0 <= slot < len(descs)):
127
+ raise ValueError("score label out of range")
128
+ return QuestionSpec(qid, "score", q.instructions, names, descs, list(range(len(names))), slot)
129
+
130
+ if isinstance(q, Noul):
131
+ c = q.criteria or {}
132
+ descs = [c.get("false"), c.get("true")]
133
+ slot = None if label is None else int(bool(label))
134
+ return QuestionSpec(qid, "noul", q.instructions, list(NOUL_OPTIONS), descs, [0, 1], slot)
135
+
136
+ raise TypeError(type(q))
137
+
138
+
139
+ def spec_to_text(spec: QuestionSpec) -> str:
140
+ head = {"choice": TOK_CHOICE, "score": TOK_SCORE, "noul": TOK_NOUL}[spec.qtype]
141
+ lines = [f"{TOK_Q}{head} {sanitize(spec.instructions).strip()}"]
142
+ for i, (name, desc) in enumerate(zip(spec.option_names, spec.option_descs)):
143
+ name = sanitize(str(name)).strip()
144
+ if desc:
145
+ lines.append(f"{TOK_OPT[i]} {name}: {sanitize(str(desc)).strip()}")
146
+ else:
147
+ lines.append(f"{TOK_OPT[i]} {name}")
148
+ lines.append(TOK_ANSWER)
149
+ return "\n".join(lines) + "\n"
150
+
151
+
152
+ @dataclass
153
+ class Encoded:
154
+ input_ids: List[int]
155
+ answer_positions: List[int] # index of each <|ts_answer|> token, question order
156
+ option_counts: List[int] # k per question (valid slots 0..k-1)
157
+ specs: List[QuestionSpec]
158
+ labels: List[int] = field(default_factory=list) # -100 if unknown
159
+ truncated_state: bool = False
160
+
161
+ @property
162
+ def n_tokens(self) -> int:
163
+ return len(self.input_ids)
164
+
165
+
166
+ class Formatter:
167
+ """Tokenizer-aware encoder shared by training and inference."""
168
+
169
+ def __init__(
170
+ self,
171
+ tokenizer,
172
+ *,
173
+ max_total_tokens: int = DEFAULT_MAX_TOTAL_TOKENS,
174
+ max_state_tokens: int = DEFAULT_MAX_STATE_TOKENS,
175
+ ):
176
+ self.tok = tokenizer
177
+ add_special_tokens(self.tok)
178
+ self.max_total_tokens = max_total_tokens
179
+ self.max_state_tokens = max_state_tokens
180
+ self.answer_id = self.tok.convert_tokens_to_ids(TOK_ANSWER)
181
+ self.state_id = self.tok.convert_tokens_to_ids(TOK_STATE)
182
+ self.opt_ids = self.tok.convert_tokens_to_ids(TOK_OPT)
183
+ assert self.answer_id is not None and self.answer_id != self.tok.unk_token_id
184
+
185
+ def _ids(self, text: str) -> List[int]:
186
+ return self.tok(text, add_special_tokens=False)["input_ids"]
187
+
188
+ def encode(
189
+ self,
190
+ state: Union[str, Dict[str, Any], List[Any]],
191
+ questions: Dict[str, Question],
192
+ *,
193
+ labels: Optional[Dict[str, Union[str, int, bool]]] = None,
194
+ shuffle_options: bool = False,
195
+ shuffle_questions: bool = False,
196
+ drop_label_for: Optional[Sequence[str]] = None,
197
+ rng: Optional[random.Random] = None,
198
+ state_indent: Optional[int] = None,
199
+ ) -> Encoded:
200
+ rng = rng or random.Random()
201
+ labels = labels or {}
202
+ drop = set(drop_label_for or [])
203
+ qids = list(questions.keys())
204
+ if shuffle_questions:
205
+ rng.shuffle(qids)
206
+
207
+ specs = [
208
+ question_to_spec(
209
+ qid,
210
+ questions[qid],
211
+ label=labels.get(qid),
212
+ shuffle=shuffle_options,
213
+ rng=rng,
214
+ drop_label=qid in drop,
215
+ )
216
+ for qid in qids
217
+ ]
218
+ q_texts = [spec_to_text(s) for s in specs]
219
+ q_ids = [self._ids(t) for t in q_texts]
220
+ q_total = sum(len(x) for x in q_ids)
221
+
222
+ state_text = sanitize(state_to_text(state, indent=state_indent))
223
+ state_ids = self._ids(TOK_STATE + " " + state_text.strip() + "\n")
224
+ budget = min(self.max_state_tokens, self.max_total_tokens - q_total)
225
+ truncated = False
226
+ if len(state_ids) > budget:
227
+ # keep the head (state token) and the tail of the state; the end is usually the most recent info
228
+ keep_tail = max(budget - 1, 0)
229
+ state_ids = state_ids[:1] + state_ids[len(state_ids) - keep_tail :]
230
+ truncated = True
231
+
232
+ ids: List[int] = list(state_ids)
233
+ answer_positions: List[int] = []
234
+ for qi in q_ids:
235
+ ids.extend(qi)
236
+ # the answer token is the last non-newline token of each question block
237
+ pos = len(ids) - 1
238
+ while ids[pos] != self.answer_id:
239
+ pos -= 1
240
+ answer_positions.append(pos)
241
+
242
+ return Encoded(
243
+ input_ids=ids,
244
+ answer_positions=answer_positions,
245
+ option_counts=[len(s.option_names) for s in specs],
246
+ specs=specs,
247
+ labels=[(-100 if s.label_slot is None else s.label_slot) for s in specs],
248
+ truncated_state=truncated,
249
+ )
250
+
251
+
252
+ def slot_mask(option_counts: Sequence[int], *, include_abstain: bool = True, n_slots: int = N_SLOTS):
253
+ """Boolean mask (Q, n_slots): True where a slot is valid for that question."""
254
+ import torch
255
+
256
+ k = torch.as_tensor(list(option_counts), dtype=torch.long)
257
+ ar = torch.arange(n_slots)
258
+ mask = ar[None, :] < k[:, None]
259
+ if include_abstain:
260
+ mask[:, ABSTAIN_SLOT] = True
261
+ return mask
262
+
263
+
264
+ def collate(encoded: Sequence[Encoded], pad_id: int, *, max_questions: Optional[int] = None):
265
+ """Right-pad a batch. Returns dict of tensors for OpenThaiSystemOneForDecision.forward."""
266
+ import torch
267
+
268
+ B = len(encoded)
269
+ T = max(e.n_tokens for e in encoded)
270
+ Q = max_questions or max(len(e.answer_positions) for e in encoded)
271
+ input_ids = torch.full((B, T), pad_id, dtype=torch.long)
272
+ attention_mask = torch.zeros((B, T), dtype=torch.long)
273
+ answer_positions = torch.zeros((B, Q), dtype=torch.long)
274
+ option_counts = torch.zeros((B, Q), dtype=torch.long)
275
+ labels = torch.full((B, Q), -100, dtype=torch.long)
276
+ for b, e in enumerate(encoded):
277
+ n = e.n_tokens
278
+ input_ids[b, :n] = torch.tensor(e.input_ids)
279
+ attention_mask[b, :n] = 1
280
+ q = len(e.answer_positions)
281
+ answer_positions[b, :q] = torch.tensor(e.answer_positions)
282
+ option_counts[b, :q] = torch.tensor(e.option_counts)
283
+ if e.labels:
284
+ labels[b, :q] = torch.tensor(e.labels)
285
+ return {
286
+ "input_ids": input_ids,
287
+ "attention_mask": attention_mask,
288
+ "answer_positions": answer_positions,
289
+ "option_counts": option_counts,
290
+ "labels": labels,
291
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f1893a6a005902da12282d18c8cb8e84b6f19d09bf9c20dc3ab991796b7c45ee
3
+ size 1505386774
modeling.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenThai-SystemOne decision model.
2
+
3
+ text tower (Qwen3.5-0.8B, LM head removed) -> hidden state at every <|ts_answer|> -> SlotHead (256 logits)
4
+ mask slots >= k -> softmax -> probabilities over the k options
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import math
9
+ from dataclasses import dataclass
10
+ from typing import Optional
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F
15
+ from transformers import AutoModel, AutoModelForCausalLM, AutoTokenizer, PreTrainedModel
16
+ from transformers.utils import ModelOutput
17
+
18
+ from .configuration import OpenThaiSystemOneConfig
19
+ from .formatting import SPECIAL_TOKENS, TOK_ANSWER, add_special_tokens
20
+
21
+ QTYPE_INDEX = {"choice": 0, "score": 1, "noul": 2}
22
+
23
+
24
+ @dataclass
25
+ class DecisionOutput(ModelOutput):
26
+ loss: Optional[torch.Tensor] = None
27
+ logits: Optional[torch.Tensor] = None # (B, Q, n_slots), masked with -inf
28
+ probs: Optional[torch.Tensor] = None # (B, Q, n_slots)
29
+ hidden_states: Optional[torch.Tensor] = None # (B, Q, H) at answer positions
30
+
31
+
32
+ class OpenThaiSystemOneForDecision(PreTrainedModel):
33
+ config_class = OpenThaiSystemOneConfig
34
+ base_model_prefix = "model"
35
+ supports_gradient_checkpointing = True
36
+ _supports_flash_attn = True
37
+ _supports_sdpa = True
38
+
39
+ def __init__(self, config: OpenThaiSystemOneConfig):
40
+ super().__init__(config)
41
+ self.model = AutoModel.from_config(config.text_config)
42
+ self.slot_head = nn.Linear(config.hidden_size, config.n_slots, bias=config.head_bias)
43
+ # log-temperatures per question type (choice/score/noul); learned in the calibration stage
44
+ self.log_temperature = nn.Parameter(torch.zeros(config.n_temperatures))
45
+ self.post_init()
46
+
47
+ # ------------------------------------------------------------------ construction
48
+ @classmethod
49
+ def from_causal_lm(
50
+ cls,
51
+ path: str,
52
+ *,
53
+ tokenizer=None,
54
+ n_slots: int = 256,
55
+ torch_dtype=torch.bfloat16,
56
+ **kwargs,
57
+ ):
58
+ """Build a decision model from a (text-only) causal-LM checkpoint: drop lm_head, add tokens + head."""
59
+ tok = tokenizer or AutoTokenizer.from_pretrained(path)
60
+ added = add_special_tokens(tok)
61
+ lm = AutoModelForCausalLM.from_pretrained(path, dtype=torch_dtype, **kwargs)
62
+ base = lm.model if hasattr(lm, "model") else lm.base_model
63
+ text_cfg = base.config
64
+ if added:
65
+ lm.resize_token_embeddings(len(tok), mean_resizing=False)
66
+ text_cfg.vocab_size = lm.get_input_embeddings().weight.shape[0]
67
+ _init_new_token_embeddings(lm.get_input_embeddings().weight, tok, added)
68
+ cfg = OpenThaiSystemOneConfig(
69
+ text_config=text_cfg,
70
+ n_slots=n_slots,
71
+ answer_token_id=tok.convert_tokens_to_ids(TOK_ANSWER),
72
+ pad_token_id=tok.pad_token_id,
73
+ )
74
+ cfg.text_config.tie_word_embeddings = False # there is no LM head any more
75
+ model = cls(cfg).to(torch_dtype)
76
+ missing, unexpected = model.model.load_state_dict(base.state_dict(), strict=False)
77
+ assert not unexpected, unexpected
78
+ _init_slot_head(model.slot_head)
79
+ model.model.config = cfg.text_config
80
+ return model, tok
81
+
82
+ # ------------------------------------------------------------------ forward
83
+ def gather_answer_states(self, hidden: torch.Tensor, answer_positions: torch.Tensor) -> torch.Tensor:
84
+ idx = answer_positions.clamp(min=0).unsqueeze(-1).expand(-1, -1, hidden.shape[-1])
85
+ return torch.gather(hidden, 1, idx) # (B, Q, H)
86
+
87
+ def slot_logits(
88
+ self,
89
+ answer_hidden: torch.Tensor,
90
+ option_counts: torch.Tensor,
91
+ *,
92
+ include_abstain: bool = True,
93
+ qtypes: Optional[torch.Tensor] = None,
94
+ apply_temperature: bool = True,
95
+ ) -> torch.Tensor:
96
+ logits = self.slot_head(answer_hidden.to(self.slot_head.weight.dtype)).float()
97
+ if apply_temperature:
98
+ if qtypes is None:
99
+ t = self.log_temperature[0].exp()
100
+ else:
101
+ t = self.log_temperature.exp()[qtypes.clamp(min=0)] # (B, Q)
102
+ t = t.unsqueeze(-1)
103
+ logits = logits / t
104
+ ar = torch.arange(logits.shape[-1], device=logits.device)
105
+ valid = ar[None, None, :] < option_counts.unsqueeze(-1)
106
+ if include_abstain:
107
+ valid = valid.clone()
108
+ valid[..., self.config.abstain_slot] = True
109
+ # questions that are padding (option_counts == 0) keep slot 0 valid to avoid NaNs
110
+ valid[..., 0] |= option_counts.unsqueeze(-1).squeeze(-1) == 0
111
+ return logits.masked_fill(~valid, float("-inf"))
112
+
113
+ def forward(
114
+ self,
115
+ input_ids: torch.Tensor,
116
+ attention_mask: Optional[torch.Tensor] = None,
117
+ answer_positions: Optional[torch.Tensor] = None,
118
+ option_counts: Optional[torch.Tensor] = None,
119
+ labels: Optional[torch.Tensor] = None,
120
+ soft_labels: Optional[torch.Tensor] = None,
121
+ qtypes: Optional[torch.Tensor] = None,
122
+ include_abstain: bool = True,
123
+ label_smoothing: float = 0.0,
124
+ brier_weight: float = 0.0,
125
+ apply_temperature: bool = True,
126
+ **kwargs,
127
+ ) -> DecisionOutput:
128
+ out = self.model(input_ids=input_ids, attention_mask=attention_mask, **kwargs)
129
+ hidden = out.last_hidden_state
130
+ if answer_positions is None:
131
+ answer_positions = (input_ids == self.config.answer_token_id).nonzero()[:, 1].unsqueeze(0)
132
+ if option_counts is None:
133
+ raise ValueError("option_counts required")
134
+ h = self.gather_answer_states(hidden, answer_positions)
135
+ logits = self.slot_logits(h, option_counts, include_abstain=include_abstain, qtypes=qtypes, apply_temperature=apply_temperature)
136
+ probs = logits.softmax(-1)
137
+
138
+ loss = None
139
+ if labels is not None or soft_labels is not None:
140
+ logp = logits.log_softmax(-1)
141
+ if soft_labels is not None:
142
+ valid = (option_counts > 0)
143
+ tgt = soft_labels.float()
144
+ nll = -(tgt * logp.masked_fill(torch.isinf(logp), 0.0)).sum(-1)
145
+ loss = (nll * valid).sum() / valid.sum().clamp(min=1)
146
+ else:
147
+ flat_logp = logp.reshape(-1, logp.shape[-1])
148
+ flat_lab = labels.reshape(-1)
149
+ keep = flat_lab != -100
150
+ if keep.any():
151
+ lp = flat_logp[keep]
152
+ lb = flat_lab[keep]
153
+ nll = -lp.gather(1, lb[:, None]).squeeze(1)
154
+ if label_smoothing > 0:
155
+ n_valid = torch.isfinite(lp).sum(-1).clamp(min=1).float()
156
+ smooth = -(lp.masked_fill(torch.isinf(lp), 0.0)).sum(-1) / n_valid
157
+ nll = (1 - label_smoothing) * nll + label_smoothing * smooth
158
+ loss = nll.mean()
159
+ if brier_weight > 0:
160
+ p = lp.exp()
161
+ onehot = F.one_hot(lb, p.shape[-1]).float()
162
+ loss = loss + brier_weight * ((p - onehot) ** 2).sum(-1).mean()
163
+ else:
164
+ loss = logits.sum() * 0.0
165
+ return DecisionOutput(loss=loss, logits=logits, probs=probs, hidden_states=h)
166
+
167
+
168
+ def use_reference_kernels():
169
+ """Force the pure-PyTorch Gated-DeltaNet / causal-conv paths.
170
+
171
+ transformers routes `chunk_gated_delta_rule` & co. to the Triton kernels (flash-linear-attention, causal-conv1d)
172
+ whenever those packages are importable, without checking the tensor device, which crashes on CPU/MPS.
173
+ Call this before running on a non-CUDA device.
174
+ """
175
+ try:
176
+ from transformers.models.qwen3_5 import modeling_qwen3_5 as m
177
+ except Exception: # pragma: no cover
178
+ return
179
+ for name in ("torch_chunk_gated_delta_rule", "torch_recurrent_gated_delta_rule", "chunk_gated_delta_rule",
180
+ "fused_recurrent_gated_delta_rule", "causal_conv1d_fn", "causal_conv1d_update"):
181
+ fn = getattr(m, name, None)
182
+ if fn is not None and hasattr(fn, "__wrapped__"):
183
+ setattr(m, name, fn.__wrapped__)
184
+
185
+
186
+ def _init_slot_head(head: nn.Linear):
187
+ nn.init.normal_(head.weight, std=0.02)
188
+ if head.bias is not None:
189
+ nn.init.zeros_(head.bias)
190
+
191
+
192
+ @torch.no_grad()
193
+ def _init_new_token_embeddings(weight: torch.Tensor, tok, n_added: int):
194
+ """New control tokens start near the mean of digit-token embeddings + small noise."""
195
+ digit_ids = [tok.convert_tokens_to_ids(d) for d in "0123456789"]
196
+ digit_ids = [i for i in digit_ids if i is not None and i != tok.unk_token_id]
197
+ mean = weight[digit_ids].float().mean(0) if digit_ids else weight[: weight.shape[0] - n_added].float().mean(0)
198
+ std = weight[: weight.shape[0] - n_added].float().std()
199
+ new = mean[None, :] + torch.randn(n_added, weight.shape[1]) * std * 0.1
200
+ weight[-n_added:] = new.to(weight.dtype)
201
+
202
+
203
+ def confidence_from_probs(p: torch.Tensor, k: int) -> float:
204
+ """1 - normalised entropy over the k valid options."""
205
+ if k <= 1:
206
+ return 1.0
207
+ p = p[:k].clamp(min=1e-12)
208
+ p = p / p.sum()
209
+ h = -(p * p.log()).sum().item()
210
+ return float(max(0.0, min(1.0, 1.0 - h / math.log(k))))
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d3400f1532d54f98d82b24c503e61908aa66f84e22e566e59fc80494add3a5c3
3
+ size 20039242
tokenizer_config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "audio_bos_token": "<|audio_start|>",
4
+ "audio_eos_token": "<|audio_end|>",
5
+ "audio_token": "<|audio_pad|>",
6
+ "backend": "tokenizers",
7
+ "bos_token": null,
8
+ "clean_up_tokenization_spaces": false,
9
+ "eos_token": "<|endoftext|>",
10
+ "errors": "replace",
11
+ "image_token": "<|image_pad|>",
12
+ "is_local": true,
13
+ "local_files_only": false,
14
+ "model_max_length": 262144,
15
+ "model_specific_special_tokens": {
16
+ "audio_bos_token": "<|audio_start|>",
17
+ "audio_eos_token": "<|audio_end|>",
18
+ "audio_token": "<|audio_pad|>",
19
+ "image_token": "<|image_pad|>",
20
+ "video_token": "<|video_pad|>",
21
+ "vision_bos_token": "<|vision_start|>",
22
+ "vision_eos_token": "<|vision_end|>"
23
+ },
24
+ "pad_token": "<|endoftext|>",
25
+ "pretokenize_regex": "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
26
+ "split_special_tokens": false,
27
+ "tokenizer_class": "Qwen2Tokenizer",
28
+ "unk_token": null,
29
+ "video_token": "<|video_pad|>",
30
+ "vision_bos_token": "<|vision_start|>",
31
+ "vision_eos_token": "<|vision_end|>"
32
+ }
types.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Request / response types.
2
+
3
+ Field names deliberately mirror the TypeSafe `POST /v1/systemone` contract so that
4
+ code written against the TypeSafe SDK can be pointed at OpenThai-SystemOne unchanged:
5
+
6
+ state : str | dict | list -- the thing to judge
7
+ questions : {id: Choice|Score|Noul} -- typed questions
8
+ answers : {id: ChoiceAnswer|ScoreAnswer|NoulAnswer}
9
+ """
10
+ from __future__ import annotations
11
+
12
+ from typing import Any, Dict, List, Literal, Optional, Union
13
+
14
+ from pydantic import BaseModel, Field, field_validator, model_validator
15
+
16
+ MAX_OPTIONS = 255 # single-stage cardinality limit (slots 0..254); slot 255 = abstain
17
+ MIN_SCORE_LEVELS = 2
18
+ MAX_SCORE_LEVELS = 10
19
+
20
+
21
+ class Noul(BaseModel):
22
+ """A yes/no question. Returns p(yes)."""
23
+
24
+ type: Literal["noul"] = "noul"
25
+ instructions: str
26
+ criteria: Optional[Dict[str, Optional[str]]] = None # {"true": "...", "false": "..."}
27
+
28
+ @field_validator("criteria")
29
+ @classmethod
30
+ def _check_criteria(cls, v):
31
+ if v is None:
32
+ return v
33
+ extra = set(v) - {"true", "false"}
34
+ if extra:
35
+ raise ValueError(f"noul criteria keys must be 'true'/'false', got {sorted(extra)}")
36
+ return v
37
+
38
+
39
+ class Choice(BaseModel):
40
+ """Pick one option. `criteria` maps option name -> description (or null)."""
41
+
42
+ type: Literal["choice"] = "choice"
43
+ instructions: str
44
+ criteria: Dict[str, Optional[str]]
45
+
46
+ @field_validator("criteria")
47
+ @classmethod
48
+ def _check_criteria(cls, v):
49
+ if len(v) < 1:
50
+ raise ValueError("choice needs at least one option")
51
+ if len(v) > MAX_OPTIONS:
52
+ raise ValueError(f"choice supports at most {MAX_OPTIONS} options in one stage")
53
+ for k in v:
54
+ if not str(k).strip():
55
+ raise ValueError("option names must be non-empty")
56
+ return v
57
+
58
+
59
+ class Score(BaseModel):
60
+ """Rate the state against ordered levels; `criteria[i]` describes level i (low -> high)."""
61
+
62
+ type: Literal["score"] = "score"
63
+ instructions: str
64
+ criteria: List[str]
65
+
66
+ @field_validator("criteria")
67
+ @classmethod
68
+ def _check_criteria(cls, v):
69
+ if not (MIN_SCORE_LEVELS <= len(v) <= MAX_SCORE_LEVELS):
70
+ raise ValueError(f"score needs {MIN_SCORE_LEVELS}..{MAX_SCORE_LEVELS} levels")
71
+ return v
72
+
73
+
74
+ Question = Union[Noul, Choice, Score]
75
+
76
+
77
+ class NoulAnswer(BaseModel):
78
+ type: Literal["noul"] = "noul"
79
+ noul: float
80
+
81
+
82
+ class ChoiceAnswer(BaseModel):
83
+ type: Literal["choice"] = "choice"
84
+ choice: str
85
+ probabilities: Dict[str, float]
86
+ confidence: float
87
+ abstain: Optional[float] = None # OpenThai extension: p(none of the options); not in TypeSafe
88
+
89
+
90
+ class ScoreAnswer(BaseModel):
91
+ type: Literal["score"] = "score"
92
+ score: float
93
+ legend: Dict[int, str]
94
+ probabilities: Dict[str, float]
95
+ confidence: float
96
+
97
+
98
+ Answer = Union[NoulAnswer, ChoiceAnswer, ScoreAnswer]
99
+
100
+
101
+ class Usage(BaseModel):
102
+ input_tokens: int
103
+ output_tokens: int = 0
104
+
105
+
106
+ class SystemOneRequest(BaseModel):
107
+ state: Union[str, Dict[str, Any], List[Any]]
108
+ model: str = "openthai-systemone"
109
+ questions: Dict[str, Question] = Field(discriminator=None)
110
+
111
+ @model_validator(mode="after")
112
+ def _non_empty(self):
113
+ if not self.questions:
114
+ raise ValueError("at least one question is required")
115
+ return self
116
+
117
+
118
+ class SystemOneResponse(BaseModel):
119
+ model: str
120
+ answers: Dict[str, Answer]
121
+ usage: Usage
122
+
123
+
124
+ def parse_question(obj: Union[Question, Dict[str, Any]]) -> Question:
125
+ """Accept a dict (raw JSON) or an already-typed question."""
126
+ if isinstance(obj, (Noul, Choice, Score)):
127
+ return obj
128
+ t = obj.get("type")
129
+ if t == "noul":
130
+ return Noul(**obj)
131
+ if t == "choice":
132
+ return Choice(**obj)
133
+ if t == "score":
134
+ return Score(**obj)
135
+ raise ValueError(f"unknown question type: {t!r}")