laolao77 commited on
Commit
0205bb2
·
verified ·
1 Parent(s): 2236605

Support Decisions inference and refresh model documentation

Browse files

Add the Decisions protocol alongside SystemOne and refresh the model card with validated local examples and free API responses. Preserve model weights, configuration, tokenizer, and all other existing files.

Files changed (5) hide show
  1. MODEL_USAGE.md +3 -0
  2. README.md +269 -24
  3. decisions.py +160 -0
  4. modeling_valen.py +18 -4
  5. responses.py +2 -1
MODEL_USAGE.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Valen-4B
2
+
3
+ See [README.md](README.md) for model loading, both inference protocols, and results.
README.md CHANGED
@@ -14,50 +14,295 @@ tags:
14
  - custom-code
15
  ---
16
 
17
- # Valen-4B
 
 
 
18
 
19
- Valen-4B combines Qwen3.5-4B with a two-layer MLP-Mixer decision head. It predicts probability distributions for Choice, Noul (yes/no), and Score questions. A shared state can contain text, images, or video and serve multiple questions.
20
 
21
- Valen-4B 基于 Qwen3.5-4B 和两层 MLP-Mixer 决策头,支持图文、文本、视频,以及共享 state 的多题推理。
22
 
23
- ## Training / 训练
24
 
25
- - Two-stage SFT: decision-head warmup followed by joint LoRA, Mixer, and visual-merger fine-tuning. We train on millions of samples.
26
- - Backbone: BF16. Mixer: FP32. Videos use 16 sampled frames.
 
 
 
 
 
 
 
 
27
 
28
- ## Files / 权重格式
29
 
30
- - Root directory: complete backbone with merged LoRA, trained visual merger, FP32 Mixer, tokenizer, processor, and standalone loading code.
31
 
32
- These weights include merged LoRA adapters. BF16 rounding can cause small probability differences from the original training checkpoints used for the reported benchmarks.
33
 
34
- ## Load merged weights / 加载完整合并权重
35
 
36
- The verified environment uses Python 3.10, PyTorch 2.6.0, Transformers 5.4.0, torchvision 0.21.0, Pillow, and av 16.1.0. Flash Attention 2 requires a compatible flash-attn installation.
 
 
 
 
 
 
37
 
38
  ```python
39
  import torch
40
  from transformers import AutoModel
41
 
42
  model = AutoModel.from_pretrained(
43
- "Valen-Team/Valen-4B",
44
- trust_remote_code=True,
45
- dtype=torch.bfloat16,
46
- attn_implementation="sdpa", # or "flash_attention_2"
47
  ).to("cuda").eval()
48
  torch.set_float32_matmul_precision("highest")
49
  torch.backends.cudnn.allow_tf32 = False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
- response = model.predict({
52
- "state": "There is one cat in the room.",
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  "questions": {
54
- "animal": {"type": "choice", "instructions": "Which animal is present?",
55
- "criteria": {"cat": "A cat", "dog": "A dog"}},
56
- "is_cat": {"type": "noul", "instructions": "There is a cat in the room."},
 
 
57
  },
58
- }, execution="shared_state")
59
- print(response["answers"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  ```
61
 
62
- For a local copy, replace the repository ID with `"./Valen-4B"`.
63
- `execution="question"` scores questions separately. Images and video use the Valen `messages`, `image_url`, and `video_url` schema; relative media paths are resolved against `media_root`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  - custom-code
15
  ---
16
 
17
+ <p align="center">
18
+ <img src="https://raw.githubusercontent.com/Valen-Team/Valen/main/assets/branding/valen-mark-white.png" alt="Valen logo" width="112">
19
+ </p>
20
+ <h1 align="center">Valen-4B</h1>
21
 
22
+ **Valen-4B** helps you classify customer messages, check whether images meet your requirements, and identify actions in videos. Try it instantly through our **[free API and web demo](https://valen-team.github.io/)**, with no installation, model download, or GPU required. We also release the **[training code](https://github.com/Valen-Team/Valen)** and **[training data](https://huggingface.co/datasets/Valen-Team/Valen-Training-General-100k)**, so you can fine-tune Valen for your own tasks.
23
 
24
+ ## Examples
25
 
26
+ Image, video, and game demonstrations from the [Valen repository](https://github.com/Valen-Team/Valen#demos). Click a preview to watch the full demonstration.
27
 
28
+ <table>
29
+ <tr>
30
+ <th>Image and video decisions</th>
31
+ <th>Sokoban decisions</th>
32
+ </tr>
33
+ <tr>
34
+ <td width="65%"><a href="https://raw.githubusercontent.com/Valen-Team/Valen/main/assets/demos/Valen.mp4"><img src="https://raw.githubusercontent.com/Valen-Team/Valen/main/assets/demos/valen-demo-preview.gif" alt="Valen image and video decision demo" width="100%"></a></td>
35
+ <td width="35%"><a href="https://raw.githubusercontent.com/Valen-Team/Valen/main/assets/demos/games/valen-sokoban.mp4"><img src="https://raw.githubusercontent.com/Valen-Team/Valen/main/assets/demos/games/valen-sokoban-preview.gif" alt="Valen Sokoban decision demo" width="100%"></a></td>
36
+ </tr>
37
+ </table>
38
 
39
+ ## Quick start
40
 
41
+ Valen supports two decision API formats: **SystemOne**, used by [Jev](https://docs.typesafe.ai/api/system-one), and **Decisions**, used by [OpenAI](https://developers.openai.com/api/docs/guides/decisions). Both work with the same Valen model.
42
 
43
+ Start with **Decisions** if you are new to Valen. If your application already uses the Jev/SystemOne format, use **SystemOne**. The examples below include everything you need to get started.
44
 
45
+ See the [Valen Transformers documentation](https://valen-team.github.io/docs/valen/quickstart/) for complete request formats, image/video inputs, and inference parameters.
46
 
47
+ ### Install and load
48
+
49
+ The Python example below runs locally on an NVIDIA GPU. If you prefer to skip local setup, try the **[free web demo or API](https://valen-team.github.io/)**.
50
+
51
+ ```bash
52
+ python -m pip install torch torchvision transformers pillow av
53
+ ```
54
 
55
  ```python
56
  import torch
57
  from transformers import AutoModel
58
 
59
  model = AutoModel.from_pretrained(
60
+ "Valen-Team/Valen-4B", trust_remote_code=True,
61
+ dtype="auto", attn_implementation="sdpa",
 
 
62
  ).to("cuda").eval()
63
  torch.set_float32_matmul_precision("highest")
64
  torch.backends.cudnn.allow_tf32 = False
65
+ ```
66
+
67
+ ### Decisions
68
+
69
+ Use `input` for the same input and a question list. Question types are `choice`, `predicate` (yes/no), and `score`; answers are returned in request order.
70
+
71
+ ```python
72
+ result = model.predict({
73
+ "input": "I moved. Please ship my order to 12 Elm Street instead.",
74
+ "questions": [
75
+ {"name": "intent", "type": "choice", "instructions": "What does the customer want?",
76
+ "choices": [{"value": "address", "description": "Change the delivery address"},
77
+ {"value": "cancel", "description": "Cancel the order"}]},
78
+ {"name": "change_address", "type": "predicate",
79
+ "instructions": "The customer requests a delivery address change."},
80
+ {"name": "explicitness", "type": "score", "instructions": "How explicit is the request?",
81
+ "levels": [{"label": "none", "description": "No request"},
82
+ {"label": "possible", "description": "Asks whether a change is possible"},
83
+ {"label": "explicit", "description": "Explicitly requests a change"}]},
84
+ ],
85
+ })
86
+ print("Intent:", result["answers"][0]["choice"])
87
+ print(f"Address change probability: {result['answers'][1]['probability']:.3f}")
88
+ print(f"Explicitness score (0–2): {result['answers'][2]['score']:.3f}")
89
+ ```
90
 
91
+ Example output:
92
+
93
+ ```text
94
+ Intent: address
95
+ Address change probability: 0.999
96
+ Explicitness score (0–2): 1.990
97
+ ```
98
+
99
+ ### SystemOne
100
+
101
+ Use `state` for the input and a question dictionary. Question types are `choice`, `noul` (yes/no), and `score`; answers are keyed by question ID.
102
+
103
+ ```python
104
+ result = model.predict({
105
+ "state": "I moved. Please ship my order to 12 Elm Street instead.",
106
  "questions": {
107
+ "intent": {"type": "choice", "instructions": "What does the customer want?",
108
+ "criteria": {"address": "Change the delivery address", "cancel": "Cancel the order"}},
109
+ "change_address": {"type": "noul", "instructions": "The customer requests a delivery address change."},
110
+ "explicitness": {"type": "score", "instructions": "How explicit is the request?",
111
+ "criteria": ["No request", "Asks whether a change is possible", "Explicitly requests a change"]},
112
  },
113
+ })
114
+ print("Intent:", result["answers"]["intent"]["choice"])
115
+ print(f"Address change probability: {result['answers']['change_address']['noul']:.3f}")
116
+ print(f"Explicitness score (0–2): {result['answers']['explicitness']['score']:.3f}")
117
+ ```
118
+
119
+ Example output:
120
+
121
+ ```text
122
+ Intent: address
123
+ Address change probability: 0.999
124
+ Explicitness score (0–2): 1.990
125
+ ```
126
+
127
+ `address` means changing the delivery address. Exact values may vary. In both examples, the yes/no result is a probability from 0 to 1, and the score is the probability-weighted mean of level indices (0–2 here). The [full guide](https://valen-team.github.io/docs/valen/quickstart/) covers `execution`, `temperature`, and additional examples for both protocols.
128
+
129
+ ### Images and video
130
+
131
+ Both examples use **Decisions** and reuse the model loaded above. They download the same image and video used in the [local inference notebook](https://github.com/Valen-Team/Valen/blob/main/cookbook/local_inference.ipynb).
132
+
133
+ ```python
134
+ from urllib.request import urlretrieve
135
+
136
+ urlretrieve("https://raw.githubusercontent.com/Valen-Team/Valen/main/assets/cookbook/sheep.jpg", "sheep.jpg")
137
+ result = model.predict({
138
+ "input": [{"role": "user", "content": [
139
+ {"type": "input_image", "image_url": "sheep.jpg"}
140
+ ]}],
141
+ "questions": [{"name": "animal", "type": "choice", "instructions": "Which animals are shown?",
142
+ "choices": [{"value": "sheep", "description": "Sheep"},
143
+ {"value": "dogs", "description": "Dogs"}]}],
144
+ })
145
+ print("Image answer:", result["answers"][0]["choice"])
146
+ ```
147
+
148
+ ```python
149
+ urlretrieve("https://raw.githubusercontent.com/Valen-Team/Valen/main/assets/cookbook/momos.mp4", "momos.mp4")
150
+ result = model.predict({
151
+ "input": [{"role": "user", "content": [
152
+ {"type": "input_video", "video_url": "momos.mp4"}
153
+ ]}],
154
+ "questions": [{"name": "sauce", "type": "choice",
155
+ "instructions": "What color is the sauce in the foil container on the left?",
156
+ "choices": [{"value": "brown", "description": "Brown"},
157
+ {"value": "white", "description": "White"},
158
+ {"value": "red", "description": "Red"},
159
+ {"value": "orange", "description": "Orange"}]}],
160
+ })
161
+ print("Video answer:", result["answers"][0]["choice"])
162
+ ```
163
+
164
+ Relative media paths resolve against `media_root` (the current directory by default); absolute paths also work. See the [Transformers guide](https://valen-team.github.io/docs/valen/quickstart/) for both protocols and complete image/video parameters.
165
+
166
+ ## Try it free: the API
167
+
168
+ Try the [interactive demo](https://valen-team.github.io/) or call the free API directly. No API key is required:
169
+
170
+ ```bash
171
+ curl https://api.valen-team.workers.dev/v1/decisions \
172
+ -H 'Content-Type: application/json' \
173
+ -H 'Origin: https://valen-team.github.io' \
174
+ -d '{
175
+ "model": "valen-4b",
176
+ "input": "Please send my order to my new address.",
177
+ "questions": [{"name": "change_address", "type": "predicate",
178
+ "instructions": "Is the customer requesting a delivery address change?"}]
179
+ }'
180
+ ```
181
+
182
+ Example response (captured from the free API; timing may vary):
183
+
184
+ ```json
185
+ {
186
+ "answers": [
187
+ {
188
+ "type": "predicate",
189
+ "name": "change_address",
190
+ "probability": 0.9811345101245704
191
+ }
192
+ ],
193
+ "model": "Valen-4B",
194
+ "model_id": "valen-4b",
195
+ "revision": "local",
196
+ "usage": {
197
+ "input_tokens": 79,
198
+ "output_tokens": 0
199
+ },
200
+ "internal_usage": {
201
+ "compute_tokens": 79
202
+ },
203
+ "timing": {
204
+ "total_ms": 105.17,
205
+ "image_ms": 0.0,
206
+ "compile_ms": 10.58,
207
+ "forward_ms": 73.06,
208
+ "queue_ms": 0.01
209
+ },
210
+ "images": []
211
+ }
212
+ ```
213
+
214
+ The predicate result is in `answers[0].probability`. See the [API reference](https://valen-team.github.io/docs/valen/api/) for image inputs, both protocols, and [available model IDs](https://valen-team.github.io/docs/valen/api/list-models/).
215
+
216
+ ## SGLang / vLLM deployment
217
+
218
+ Install the corresponding Valen plugin in a compatible official engine environment. Use Linux, Python 3.11+, and an NVIDIA GPU; the SGLang example uses FA3 on H100/H200-class GPUs. The two alternatives below expose `/v1/systemone` and `/v1/decisions` for text and image requests.
219
+
220
+ ### SGLang
221
+
222
+ ```bash
223
+ python -m pip install "git+https://github.com/Valen-Team/Valen.git#subdirectory=serving/sglang"
224
+ valen-sglang --model-path Valen-Team/Valen-4B \
225
+ --served-model-name valen --host 127.0.0.1 --port 30000 \
226
+ --attention-backend fa3
227
+ ```
228
+
229
+ ### vLLM
230
+
231
+ ```bash
232
+ python -m pip install "git+https://github.com/Valen-Team/Valen.git#subdirectory=serving/vllm"
233
+ valen-vllm --model-path Valen-Team/Valen-4B \
234
+ --served-model-name valen --host 127.0.0.1 --port 8000
235
+ ```
236
+
237
+ Once the chosen server is ready, send a local request. Use port `8000` for vLLM or `30000` for SGLang:
238
+
239
+ ```bash
240
+ curl http://127.0.0.1:8000/v1/decisions \
241
+ -H 'Content-Type: application/json' \
242
+ -d '{"model":"valen","input":"Please send my order to my new address.",
243
+ "questions":[{"name":"change_address","type":"predicate",
244
+ "instructions":"Is the customer requesting a delivery address change?"}]}'
245
+ ```
246
+
247
+ For Docker images, offline deployment kits, and complete setup instructions, see the [SGLang guide](https://valen-team.github.io/docs/valen/sglang/) and [vLLM guide](https://valen-team.github.io/docs/valen/vllm/).
248
+
249
+ ## Fine-tuning
250
+
251
+ Fine-tune Valen on your own text, image, or video data with **LoRA or full fine-tuning**. Follow the **[GitHub fine-tuning guide](https://github.com/Valen-Team/Valen#5-fine-tuning)** to install the training dependencies and run the commands below from the Valen repository root.
252
+
253
+ ```bash
254
+ hf download Valen-Team/Valen-4B --local-dir models/Valen-4B
255
+ cp configs/train/qwen/sft_finetune_lora.json finetune.json
256
  ```
257
 
258
+ Set `model.model_path` to `models/Valen-4B`, `data.path` to your dataset, and your training budget in `finetune.json`, then run:
259
+
260
+ ```bash
261
+ python -m valen.train --config finetune.json
262
+ ```
263
+
264
+ For full fine-tuning, use `configs/train/qwen/sft_finetune_full.json`. See GitHub for the [data format](https://github.com/Valen-Team/Valen/blob/main/docs/data-format.md), [training configuration](https://github.com/Valen-Team/Valen/tree/main/configs/train/qwen), and [checkpoint recovery](https://github.com/Valen-Team/Valen#5-fine-tuning).
265
+
266
+ ## Evaluation
267
+
268
+ ### Jev Decision Index
269
+
270
+ [Decision Index 0.4.1](https://huggingface.co/spaces/multimodalart/jev-decision-index), snapshot 2026-10-22. Full score combines private tests; Public score covers the public suite. These are normalized index scores (0–100), not accuracy percentages.
271
+
272
+ | Model | Full score ↑ | Public score ↑ |
273
+ | --- | ---: | ---: |
274
+ | Valen-0.8B | 16.55 | 20.71 |
275
+ | Valen-2B | 22.20 | 27.20 |
276
+ | Valen-4B | **37.57** | **38.54** |
277
+
278
+ ### JevalKit
279
+
280
+ Selected [JevalKit benchmarks](https://huggingface.co/spaces/Valen-Team/JevalKit-Leaderboard), snapshot 2026-10-23. Values are accuracy (%), higher is better. Best scores are bold.
281
+
282
+ | Benchmark | Valen-0.8B | Valen-2B | Valen-4B |
283
+ | --- | ---: | ---: | ---: |
284
+ | JevBench | 77.49 | 82.68 | **83.55** |
285
+ | Typed Decisions | 58.35 | 62.95 | **69.55** |
286
+ | VisualDecisionBench — Image | 75.82 | 80.47 | **83.12** |
287
+ | VisualDecisionBench — Video | 79.01 | 82.74 | **87.43** |
288
+
289
+ Full benchmark breakdowns, calibration metrics, and evaluation protocols are available on the linked leaderboards. Sources: [Decision Index data](https://huggingface.co/spaces/multimodalart/jev-decision-index/blob/0b5ecaf2396891e76c13a19aa17b874b59abcc37/data/index.json) · [JevalKit data](https://huggingface.co/spaces/Valen-Team/JevalKit-Leaderboard/blob/8ee9a5d1696fc4a0c0c12d3b8aabfbf51eb02eee/data/leaderboard.json).
290
+
291
+ ## License
292
+
293
+ Apache-2.0. See [LICENSE](LICENSE).
294
+
295
+ ## Citation
296
+
297
+ If you use Valen in your work, please cite this repository:
298
+
299
+ ```bibtex
300
+ @misc{valen,
301
+ author = {{Valen Team}},
302
+ title = {Valen},
303
+ howpublished = {GitHub - Valen-Team/Valen: A multimodal System One decision model for text, images and video.},
304
+ note = {GitHub repository},
305
+ year = {2026},
306
+ url = {https://github.com/Valen-Team/Valen}
307
+ }
308
+ ```
decisions.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Public Decisions contract. Keep serving copies byte-identical to this module."""
2
+ import math
3
+ from copy import deepcopy
4
+ from contextlib import contextmanager
5
+
6
+
7
+ def to_internal(body, *, allow_video=False):
8
+ """Validate public input and convert it to the training/compiler schema."""
9
+ if not isinstance(body, dict):
10
+ raise ValueError("Request must be an object")
11
+ temperature = body.get("temperature", 1.0)
12
+ if isinstance(temperature, bool) or not isinstance(temperature, (int, float)) or not math.isfinite(temperature) or temperature <= 0:
13
+ raise ValueError("temperature must be finite and positive")
14
+ source = body.get("input")
15
+ if isinstance(source, str):
16
+ state = source
17
+ elif isinstance(source, list) and source:
18
+ messages = deepcopy(source)
19
+ for message in messages:
20
+ if not isinstance(message, dict) or message.get("role") not in {"user", "assistant", "system"}:
21
+ raise ValueError("input messages require a supported role")
22
+ content = message.get("content")
23
+ if isinstance(content, str):
24
+ continue
25
+ if not isinstance(content, list) or not content:
26
+ raise ValueError("message content must be text or a nonempty list")
27
+ for part in content:
28
+ if not isinstance(part, dict):
29
+ raise ValueError("content parts must be objects")
30
+ if part.get("type") == "input_text" and isinstance(part.get("text"), str):
31
+ part["type"] = "text"
32
+ elif part.get("type") == "input_image" and isinstance(part.get("image_url"), str):
33
+ part["type"] = "image_url"
34
+ part["image_url"] = {"url": part["image_url"]}
35
+ elif allow_video and part.get("type") == "input_video" and isinstance(part.get("video_url"), str):
36
+ part["type"] = "video_url"
37
+ part["video_url"] = {"url": part["video_url"]}
38
+ else:
39
+ kinds = "input_text, input_image or input_video" if allow_video else "input_text or input_image"
40
+ raise ValueError(f"Use {kinds} content parts")
41
+ state = {"messages": messages}
42
+ else:
43
+ raise ValueError("input must be text or a nonempty message list")
44
+ public = body.get("questions")
45
+ if not isinstance(public, list) or not 1 <= len(public) <= 256:
46
+ raise ValueError("questions must contain 1–256 questions")
47
+ questions = {}
48
+ for index, q in enumerate(public):
49
+ if not isinstance(q, dict):
50
+ raise ValueError("questions must be objects")
51
+ name = q.get("name", str(index))
52
+ if not isinstance(name, str) or not name or name in questions:
53
+ raise ValueError("question names must be unique nonempty strings")
54
+ kind, instructions = q.get("type"), q.get("instructions")
55
+ if not isinstance(instructions, str) or not instructions.strip():
56
+ raise ValueError("instructions must be nonempty text")
57
+ item = {"type": "noul" if kind == "predicate" else kind, "instructions": instructions}
58
+ if kind in {"choice", "score"}:
59
+ entries = q.get("choices" if kind == "choice" else "levels")
60
+ minimum = 1 if kind == "choice" else 2
61
+ if not isinstance(entries, list) or not minimum <= len(entries) <= 255:
62
+ raise ValueError(f"{kind} requires {minimum}–255 candidates")
63
+ labels = []
64
+ descriptions = []
65
+ for entry in entries:
66
+ if not isinstance(entry, dict):
67
+ raise ValueError("candidates must be objects")
68
+ label = entry.get("value" if kind == "choice" else "label")
69
+ if (kind == "choice" and not isinstance(label, (str, bool))) or (kind == "score" and not isinstance(label, str)):
70
+ raise ValueError("choice values must be strings or booleans; level labels must be strings")
71
+ if label in labels:
72
+ raise ValueError("candidate values/labels must be unique")
73
+ description = entry.get("description")
74
+ if not isinstance(description, str) or not description.strip():
75
+ raise ValueError("candidate descriptions must be nonempty text")
76
+ labels.append(label)
77
+ descriptions.append(description)
78
+ if kind == "choice":
79
+ # Candidate keys are part of the trained prompt. Preserve string
80
+ # values so equivalent SystemOne/Decisions requests compile alike.
81
+ # Boolean values need string keys internally, while the public
82
+ # response retains their original type.
83
+ used = {label for label in labels if isinstance(label, str)}
84
+ keys = []
85
+ for label in labels:
86
+ key = label if isinstance(label, str) else str(label).lower()
87
+ if isinstance(label, bool):
88
+ while key in used:
89
+ key = "bool:" + key
90
+ used.add(key)
91
+ keys.append(key)
92
+ item["criteria"] = dict(zip(keys, descriptions))
93
+ else:
94
+ item["criteria"] = descriptions
95
+ elif kind != "predicate":
96
+ raise ValueError("question type must be predicate, choice or score")
97
+ questions[name] = item
98
+ result = {"state": state, "questions": questions}
99
+ if "model" in body:
100
+ result["model"] = body["model"]
101
+ return result
102
+
103
+
104
+ def to_public(body, response):
105
+ """Expose ordered typed answers while retaining available usage metadata."""
106
+ result = dict(response)
107
+ output = []
108
+ for index, q in enumerate(body["questions"]):
109
+ name = q.get("name", str(index))
110
+ old = response["answers"][name]
111
+ entry = {"name": name, "type": q["type"]}
112
+ if q["type"] == "predicate":
113
+ entry["probability"] = old["noul"]
114
+ else:
115
+ key = "choices" if q["type"] == "choice" else "levels"
116
+ candidates = q[key]
117
+ probabilities = list(old["probabilities"].values())
118
+ entry["probabilities"] = [
119
+ dict(value=c["value"], probability=p) if key == "choices" else
120
+ dict(label=c["label"], value=i, probability=p)
121
+ for i, (c, p) in enumerate(zip(candidates, probabilities))
122
+ ]
123
+ entry["confidence"] = old["confidence"]
124
+ if key == "choices":
125
+ entry["choice"] = candidates[max(range(len(probabilities)), key=probabilities.__getitem__)]["value"]
126
+ else:
127
+ entry["score"] = old["score"]
128
+ output.append(entry)
129
+ result["answers"] = output
130
+ return result
131
+
132
+
133
+ @contextmanager
134
+ def local_images(request):
135
+ """Materialize inline public images for the local compiler's path interface."""
136
+ import base64
137
+ from pathlib import Path
138
+ from tempfile import TemporaryDirectory
139
+
140
+ with TemporaryDirectory(prefix="valen-images-") as directory:
141
+ request = deepcopy(request)
142
+ state = request["state"]
143
+ if isinstance(state, dict):
144
+ for message in state["messages"]:
145
+ if not isinstance(message["content"], list):
146
+ continue
147
+ for part in message["content"]:
148
+ if part["type"] != "image_url":
149
+ continue
150
+ url = part["image_url"]["url"]
151
+ if url.startswith("data:"):
152
+ header, data = url.split(",", 1)
153
+ if header not in {"data:image/png;base64", "data:image/jpeg;base64", "data:image/webp;base64"}:
154
+ raise ValueError("Use a PNG, JPEG or WebP base64 data URL")
155
+ if len(data) > 24 * 1024 * 1024:
156
+ raise ValueError("Encoded image exceeds 24 MiB")
157
+ path = Path(directory) / str(len(list(Path(directory).iterdir())))
158
+ path.write_bytes(base64.b64decode(data, validate=True))
159
+ part["image_url"]["url"] = str(path)
160
+ yield request
modeling_valen.py CHANGED
@@ -1,4 +1,4 @@
1
- """Complete merged Qwen + decision head. / 已合并的完整 Qwen 和决策头。"""
2
  import torch
3
  from transformers import AutoProcessor
4
  from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5Model, Qwen3_5PreTrainedModel
@@ -8,6 +8,7 @@ from .heads import build_head
8
  from .runtime_model import ValenQwen
9
  from .compiler import Compiler
10
  from .responses import answer
 
11
  # List transitive files explicitly for Transformers' local dynamic loader.
12
  # 本地动态加载需要显式列出间接依赖,否则搬移后可能缺少这些模块。
13
  from .batching import collate_branches
@@ -30,6 +31,10 @@ class ValenQwenForDecisionMaking(Qwen3_5PreTrainedModel):
30
  self.backbone = backbone if backbone is not None else Qwen3_5Model(config)
31
  self.head = head if head is not None else build_head(config.text_config.hidden_size, config.valen_head)
32
  self.head.float()
 
 
 
 
33
  self._processor = None
34
  # Supplied weights are already trained: do not reinitialize them.
35
  # 传入的参数已训练完成,不能再次调用初始化覆盖它们。
@@ -60,6 +65,9 @@ class ValenQwenForDecisionMaking(Qwen3_5PreTrainedModel):
60
  forward_state_batch = ValenQwen.forward_state_batch
61
  forward_batch = ValenQwen.forward_batch
62
  score_features = ValenQwen.score_features
 
 
 
63
 
64
  def make_compiler(self, media_root=".", execution=None, processor=None):
65
  if processor is None:
@@ -74,11 +82,17 @@ class ValenQwenForDecisionMaking(Qwen3_5PreTrainedModel):
74
  self.eval()
75
  # Only request content reaches the compiler. / 只编译输入,不读取标签。
76
  request = request["request"] if "request" in request else request
 
 
 
 
77
  compiler = self.make_compiler(media_root, execution, processor)
78
- state = compiler.compile({"request": request})
79
- logits = self.forward_state(state) if state.inputs is not None else [self(q) for q in state.questions]
 
80
  answers = {q.qid: answer(q, z, temperature[q.kind] if isinstance(temperature, dict) else temperature)
81
  for q, z in zip(state.questions, logits)}
82
- return {"model": self.model_name, "answers": answers,
83
  "usage": {"input_tokens": state.logical_tokens, "output_tokens": 0},
84
  "internal_usage": {"compute_tokens": state.compute_tokens}}
 
 
1
+ """Standalone Qwen + decision head. / 可独立加载的 Qwen 和决策头。"""
2
  import torch
3
  from transformers import AutoProcessor
4
  from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5Model, Qwen3_5PreTrainedModel
 
8
  from .runtime_model import ValenQwen
9
  from .compiler import Compiler
10
  from .responses import answer
11
+ from .decisions import to_internal, to_public, local_images
12
  # List transitive files explicitly for Transformers' local dynamic loader.
13
  # 本地动态加载需要显式列出间接依赖,否则搬移后可能缺少这些模块。
14
  from .batching import collate_branches
 
31
  self.backbone = backbone if backbone is not None else Qwen3_5Model(config)
32
  self.head = head if head is not None else build_head(config.text_config.hidden_size, config.valen_head)
33
  self.head.float()
34
+ # Preserve full-SFT FP32 weights with BF16 compute. / 保留全参 SFT 的存储与计算精度。
35
+ self.backbone_autocast_dtype = (
36
+ torch.bfloat16 if getattr(config, "valen_backbone_autocast_dtype", None) == "bfloat16" else None
37
+ )
38
  self._processor = None
39
  # Supplied weights are already trained: do not reinitialize them.
40
  # 传入的参数已训练完成,不能再次调用初始化覆盖它们。
 
65
  forward_state_batch = ValenQwen.forward_state_batch
66
  forward_batch = ValenQwen.forward_batch
67
  score_features = ValenQwen.score_features
68
+ # Earlier LoRA runtime snapshots do not use this helper. / 兼容旧 LoRA 运行时代码。
69
+ if hasattr(ValenQwen, "_hidden"):
70
+ _hidden = ValenQwen._hidden
71
 
72
  def make_compiler(self, media_root=".", execution=None, processor=None):
73
  if processor is None:
 
82
  self.eval()
83
  # Only request content reaches the compiler. / 只编译输入,不读取标签。
84
  request = request["request"] if "request" in request else request
85
+ temperature = request.get("temperature", temperature)
86
+ public_request = request if "input" in request else None
87
+ if public_request is not None:
88
+ request = to_internal(public_request, allow_video=True)
89
  compiler = self.make_compiler(media_root, execution, processor)
90
+ with local_images(request) as prepared:
91
+ state = compiler.compile({"request": prepared})
92
+ logits = self.forward_state(state) if state.inputs is not None else [self(q) for q in state.questions]
93
  answers = {q.qid: answer(q, z, temperature[q.kind] if isinstance(temperature, dict) else temperature)
94
  for q, z in zip(state.questions, logits)}
95
+ response = {"model": self.model_name, "answers": answers,
96
  "usage": {"input_tokens": state.logical_tokens, "output_tokens": 0},
97
  "internal_usage": {"compute_tokens": state.compute_tokens}}
98
+ return to_public(public_request, response) if public_request is not None else response
responses.py CHANGED
@@ -6,7 +6,8 @@ def answer(question, logits, temperature=1.0):
6
  raise ValueError("Calibration temperature must be finite and positive")
7
  if logits.ndim != 1 or len(logits) != len(question.keys) or not torch.isfinite(logits).all():
8
  raise ValueError("Expected one finite logit per candidate")
9
- probs = (logits.float() / temperature).softmax(-1).detach().cpu().tolist()
 
10
  total = sum(probs)
11
  probs = [p / total for p in probs]
12
  result = {"type": question.kind}
 
6
  raise ValueError("Calibration temperature must be finite and positive")
7
  if logits.ndim != 1 or len(logits) != len(question.keys) or not torch.isfinite(logits).all():
8
  raise ValueError("Expected one finite logit per candidate")
9
+ scores = logits.double()
10
+ probs = ((scores - scores.max()) / temperature).softmax(-1).detach().cpu().tolist()
11
  total = sum(probs)
12
  probs = [p / total for p in probs]
13
  result = {"type": question.kind}