Repository navigation
Expand file tree
/
Copy pathdata.py
More file actions
496 lines (447 loc) · 23.1 KB
/
Copy pathdata.py
File metadata and controls
496 lines (447 loc) · 23.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
"""Training records, token alignment, supervision, and teacher target preparation and storage."""
from __future__ import annotations
from copy import deepcopy
from dataclasses import asdict, dataclass
import hashlib
from importlib.metadata import version
import json
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, Mapping, Sequence
from ...backends import Message, TransformersBackend
from .loss_config import LossConfig
from .utils import checksum, write_json
if TYPE_CHECKING:
import torch
@dataclass
class TrainingRecord:
"""One assistant response to supervise, with its actual preceding student_messages.
response preserves reasoning_content and tool_calls. History includes
environment observations and tool results. If teacher_messages is omitted,
prepare builds it from the Experience context. Captured tokens allow exact
reuse with the same tokenizer and are optional for complete text records.
Truncated responses require original tokens; a full-message template must
not add EOS or close unfinished reasoning.
"""
id: str
experience_ids: list[str]
student_messages: list[Message]
response: Message
teacher_messages: list[Message] | None = None
tools: list[dict[str, Any]] | None = None
tokens: dict[str, Any] | None = None
episode_id: str | None = None
def load_records(path: str | Path) -> list[TrainingRecord]:
"""Load JSONL from prepare output or user-supplied text records."""
return [
TrainingRecord(**json.loads(line))
for line in Path(path).read_text(encoding="utf-8").split("\n")
if line.strip()
]
def save_records(records: Sequence[TrainingRecord], path: str | Path) -> None:
Path(path).write_text(
"".join(json.dumps(asdict(row), ensure_ascii=False, allow_nan=False) + "\n" for row in records),
encoding="utf-8",
)
def clean_messages(
messages: Sequence[Message], *, model_type: str | None = None
) -> list[Message]:
"""Save normalized messages without feeding inference diagnostics back to the model."""
result = []
for message in messages:
item = {k: deepcopy(v) for k, v in message.items() if k != "_generation"}
if "thinking" in item:
item["reasoning_content"] = item.pop("thinking")
if (model_type or "").startswith("qwen") and item.get("role") == "assistant":
# Disambiguate literal </think> only for Qwen. OSS renders analysis based on whether
# the thinking field exists; do not add an empty channel when the field is absent.
item.setdefault("reasoning_content", "")
result.append(item)
return result
def add_context(messages: Sequence[Message], context: str) -> list[Message]:
result = clean_messages(messages)
if context:
if result and result[0].get("role") in {"system", "developer"}:
original = result[0].get("content") or ""
if not isinstance(original, str):
raise TypeError("Cortex supports only text system/developer messages")
result[0]["content"] = context + ("\n\n" + original if original else "")
else:
result.insert(0, {"role": "system", "content": context})
return result
def bind_context(
records: Sequence[TrainingRecord],
contexts: Mapping[str, str],
*,
mode: Literal["individual", "joint"],
) -> list[TrainingRecord]:
"""Validate record experience IDs and fill omitted teacher inputs without changing the original."""
rows = deepcopy(list(records))
for row in rows:
if not set(row.experience_ids).issubset(contexts):
raise ValueError(f"{row.id}: experience_ids are not present in the current inputs")
if row.teacher_messages is None:
ids = list(contexts) if mode == "joint" else row.experience_ids
if mode == "individual" and len(ids) != 1:
raise ValueError("Each record must correspond to one Experience in individual mode")
row.teacher_messages = add_context(
row.student_messages, "\n\n".join(contexts[i] for i in ids)
)
row.experience_ids = ids
return rows
def validate_record(record: TrainingRecord) -> None:
"""Check for usable supervision; an optional checker decides whether responses must be complete."""
if (
not record.id
or not record.experience_ids
or len(set(record.experience_ids)) != len(record.experience_ids)
):
raise ValueError("Training records require an id and unique experience_ids")
if not record.student_messages:
raise ValueError(f"{record.id}: student_messages must not be empty")
if record.response.get("role") != "assistant":
raise ValueError(f"{record.id}: response must be an assistant message")
status = record.response.get("_generation", {}).get("finish_reason")
if status not in (None, "stop", "tool_calls", "eos", "end_turn", "length"):
raise ValueError(f"{record.id}: generation failed ({status})")
if record.tokens is not None:
for key in ("student_prompt_ids", "teacher_prompt_ids", "response_ids"):
ids = record.tokens.get(key)
if not isinstance(ids, list) or not ids or any(type(t) is not int or t < 0 for t in ids):
raise ValueError(f"{record.id}: tokens.{key} must be a nonempty list of nonnegative integers")
elif _needs_raw_tokens(record):
raise ValueError(
f"{record.id}: truncated responses or responses without final content require original tokens; "
"preserve generated prompt/response IDs instead of completing them with a full-message template"
)
def _needs_raw_tokens(record: TrainingRecord) -> bool:
"""Encode text-only records as complete messages without guessing unclosed channel boundaries."""
return record.response.get("_generation", {}).get("finish_reason") == "length" or not (
record.response.get("content") or record.response.get("tool_calls")
)
def tokenizer_signature(backend: TransformersBackend) -> str:
"""Identify the tokenization process; matching vocabularies alone does not ensure matching sequences."""
tokenizer = backend._tokenizer
value = {
# Field normalization affects templates; distinguish absent reasoning from explicitly empty reasoning.
"cortex_message_format": 3,
"tokenizer_class": f"{type(tokenizer).__module__}.{type(tokenizer).__qualname__}",
"vocab": tokenizer.get_vocab(),
"chat_template": tokenizer.chat_template,
"special_tokens": tokenizer.special_tokens_map,
"template_kwargs": backend.template_kwargs,
"model_type": backend._model.config.model_type,
"harmony_version": version("openai-harmony") if backend._model.config.model_type == "gpt_oss" else None,
"options": {
key: getattr(tokenizer, key, None)
for key in (
"add_bos_token",
"add_eos_token",
"add_prefix_space",
"do_lower_case",
"strip_accents",
"tokenize_chinese_chars",
"split_special_tokens",
"legacy",
)
},
}
native = getattr(tokenizer, "backend_tokenizer", None)
if native is not None:
# Includes normalizer, pre_tokenizer, BPE merges, AddedToken properties, and post_processor.
pipeline = json.loads(native.to_str())
# HF adjusts these settings during encoding; cached sequences have neither padding nor truncation.
pipeline.pop("padding", None)
pipeline.pop("truncation", None)
value["encoding"] = pipeline
else:
sp_model = getattr(tokenizer, "sp_model", None)
if sp_model is not None:
value["sentencepiece"] = hashlib.sha256(sp_model.serialized_model_proto()).hexdigest()
bpe_ranks = getattr(tokenizer, "bpe_ranks", None)
if bpe_ranks is not None:
value["bpe_ranks"] = sorted(bpe_ranks.items(), key=lambda item: item[1])
value["added_tokens"] = {
key: token.__getstate__() for key, token in tokenizer.added_tokens_decoder.items()
}
return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False).encode()).hexdigest()
def _encode(
backend: TransformersBackend, messages: Sequence[Message], tools: Any, *, prompt: bool
) -> list[int]:
return backend._encode(
clean_messages(messages, model_type=getattr(backend._model.config, "model_type", None)),
tools=deepcopy(tools),
add_generation_prompt=prompt,
)["input_ids"][0].tolist()
def _common_prefix(first: Sequence[int], second: Sequence[int]) -> int:
index = 0
for a, b in zip(first, second):
if a != b:
break
index += 1
return index
def _alignment_start(
backend: TransformersBackend, record: TrainingRecord, student: list[int], teacher: list[int]
) -> int:
"""Align from the first user message, excluding teacher-only context from oi supervision."""
empty = clean_messages(record.student_messages)
for message in empty:
if message.get("role") == "user" and isinstance(message.get("content"), str) and message["content"]:
message["content"] = ""
break
else:
raise ValueError(f"{record.id}: training history requires at least one nonempty text user message")
start = _common_prefix(student, _encode(backend, empty, record.tools, prompt=True))
suffix = student[start:]
if not suffix or len(teacher) < len(suffix) or teacher[-len(suffix) :] != suffix:
raise ValueError(f"{record.id}: teacher/student input suffixes differ and cannot be aligned token by token")
return start
def tokenize_record(record: TrainingRecord, backend: TransformersBackend) -> TrainingRecord:
"""Preserve captured generation tokens; tokenize text-only records for teacher forcing."""
validate_record(record)
if record.teacher_messages is None:
raise ValueError("tokenize_record requires populated teacher_messages")
row = deepcopy(record)
student = _encode(backend, row.student_messages, row.tools, prompt=True)
teacher = _encode(backend, row.teacher_messages, row.tools, prompt=True)
if row.tokens is not None:
if student != row.tokens["student_prompt_ids"] or teacher != row.tokens["teacher_prompt_ids"]:
if _needs_raw_tokens(row):
raise ValueError(
f"{row.id}: truncated response prompt IDs do not match the current tokenizer/template; "
"a full-message template cannot reconstruct truncated output"
)
# Imported text may tokenize differently at channel boundaries in full and generation templates.
# Validate the full sequence before reusing its boundary; captured generations use exact prefixes above.
for messages, key in (
(row.student_messages, "student_prompt_ids"),
(row.teacher_messages, "teacher_prompt_ids"),
):
full = _encode(backend, [*messages, row.response], row.tools, prompt=False)
if full != row.tokens[key] + row.tokens["response_ids"]:
raise ValueError(f"{row.id}: cached tokens do not match the current tokenizer/template")
student, teacher = row.tokens["student_prompt_ids"], row.tokens["teacher_prompt_ids"]
answer = list(row.tokens["response_ids"])
else:
response = clean_messages([row.response])[0]
student_full = _encode(backend, [*row.student_messages, response], row.tools, prompt=False)
teacher_full = _encode(backend, [*row.teacher_messages, response], row.tools, prompt=False)
for field in ("reasoning_content", "tool_calls", "content"):
if response.get(field):
omitted = {**response, field: [] if field == "tool_calls" else ""}
if student_full == _encode(
backend, [*row.student_messages, omitted], row.tools, prompt=False
):
raise ValueError(
f"{row.id}: chat template did not render response.{field}; use a template that supports this field"
)
# Full and generation templates can differ at newline/channel boundaries; use the full template here.
student_boundary = _common_prefix(student, student_full)
teacher_boundary = _common_prefix(teacher, teacher_full)
history = _encode(backend, row.student_messages, row.tools, prompt=False)
if student_boundary < len(history) or student_full[: len(history)] != history:
raise ValueError(
f"{row.id}: adding the assistant response changed history tokens; "
"capture original tokens through a support rollout in prepare instead of supervising rewritten history"
)
student, teacher = student_full[:student_boundary], teacher_full[:teacher_boundary]
answer = student_full[student_boundary:]
if answer != teacher_full[teacher_boundary:]:
raise ValueError(f"{row.id}: teacher/student response tokens differ")
if not answer:
raise ValueError(f"{row.id}: no response tokens are available for supervision")
start = _alignment_start(backend, row, student, teacher)
output_mask = (row.tokens or {}).get("output_mask")
row.tokens = {
"student_prompt_ids": student,
"teacher_prompt_ids": teacher,
"response_ids": answer,
"alignment_start": start,
}
if output_mask is not None:
row.tokens["output_mask"] = list(output_mask)
row.student_messages = clean_messages(row.student_messages)
row.teacher_messages = clean_messages(row.teacher_messages)
# train.jsonl preserves whether generation was truncated or ended naturally for later filtering.
# Keep full request diagnostics in records.jsonl without duplicating input_messages or raw_text.
metadata = row.response.get("_generation", {})
row.response = clean_messages([row.response])[0]
ending = {key: deepcopy(metadata[key]) for key in ("finish_reason", "parse_error") if key in metadata}
if ending:
row.response["_generation"] = ending
return row
def output_mask(tokens: dict[str, Any]) -> list[bool]:
"""Define masks by token position; the collator applies the KL next-token shift."""
prompt, answer = tokens["student_prompt_ids"], tokens["response_ids"]
size = len(prompt) + len(answer)
mask = tokens.get("output_mask", [False] * len(prompt) + [True] * len(answer))
start = tokens["alignment_start"]
if (
not prompt or not answer
or type(start) is not int or not 0 <= start < len(prompt)
or len(mask) != size or any(type(value) is not bool for value in mask)
or any(mask[:max(start, 1)]) or not any(mask[1:])
):
raise ValueError("Invalid training token lengths, alignment start, or output_mask")
return mask
def build_samples(
records: Sequence[TrainingRecord],
backend: TransformersBackend,
*,
mode: Literal["step", "episode"] = "step",
) -> list[TrainingRecord]:
"""Supervise each call in step mode or all assistant outputs in the final episode prefix.
episode merges only trajectories with continuous actual token prefixes.
If an Agent or template removes reasoning, compresses history, or changes
tool definitions, require step mode instead of treating rewritten history
as the original trajectory.
"""
if mode not in {"step", "episode"}:
raise ValueError("sample_mode must be step or episode")
rows = [tokenize_record(record, backend) for record in records]
if mode == "step":
for row in rows:
output_mask(row.tokens)
return rows
groups: dict[tuple[str, str], list[TrainingRecord]] = {}
for row in rows:
key = ("episode", row.episode_id) if row.episode_id is not None else ("record", row.id)
groups.setdefault(key, []).append(row)
samples = []
for group in groups.values():
sample = deepcopy(group[-1])
tokens = sample.tokens
full = tokens["student_prompt_ids"] + tokens["response_ids"]
teacher_full = tokens["teacher_prompt_ids"] + tokens["response_ids"]
mask = [False] * len(full)
previous_end = 0
for row in group:
current = row.tokens
student = current["student_prompt_ids"] + current["response_ids"]
teacher = current["teacher_prompt_ids"] + current["response_ids"]
begin = len(current["student_prompt_ids"])
if (
full[:len(student)] != student or teacher_full[:len(teacher)] != teacher
or begin < previous_end or row.tools != sample.tools
or row.experience_ids != sample.experience_ids
or current["alignment_start"] != tokens["alignment_start"]
):
raise ValueError(
f"{row.episode_id}: episode history is not a continuous actual token prefix; use sample_mode='step'"
)
# Preserve existing sparse masks so environment observations are not labeled as assistant output.
for position, selected in enumerate(output_mask(current)):
mask[position] |= selected
previous_end = len(student)
tokens["output_mask"] = mask
output_mask(tokens)
samples.append(sample)
return samples
def prepare_data(
records: Sequence[TrainingRecord],
backend: TransformersBackend,
*,
loss: LossConfig,
directory: Path,
mode: Literal["step", "episode"] = "step",
) -> list[TrainingRecord]:
"""Build tokens and supervision, then write teacher targets using the selected model state.
Inputs are already filtered and have teacher_messages. This function writes
training data; the method decides cache reuse and weight updates.
CE-only training does not require additional teacher targets.
"""
prepared = build_samples(records, backend, mode=mode)
save_records(prepared, directory / "train.jsonl")
cache_targets(backend, prepared, loss, directory / "targets")
return prepared
def save_prepared(directory: Path, metadata: Mapping[str, Any]) -> None:
"""Collect data checksums and write data.json last to mark successful preparation."""
files = {name: checksum(directory / name) for name in (
"train.jsonl", "records.jsonl", "results.jsonl", "generation.json", "selection.json"
)}
for target in sorted((directory / "targets").glob("*.safetensors")):
files[target.relative_to(directory).as_posix()] = checksum(target)
write_json(directory / "data.json", {**metadata, "files": files})
def select_states(output: Any, config: LossConfig) -> list[torch.Tensor]:
states = output.hidden_states
if states is None:
raise ValueError("MSE requires the model to return hidden_states")
layers = config.hidden_layers if config.hidden_layers is not None else range(len(states) - 1)
if max(layers) >= len(states) - 1:
raise ValueError("hidden_layers exceeds the model's decoder layer count")
return [states[index + 1] for index in layers]
def cache_targets(
backend: TransformersBackend,
records: Sequence[TrainingRecord],
config: LossConfig,
directory: Path,
) -> None:
"""Write targets per record to bound memory use; training masks handle the causal shift."""
if not (config.kl_weight or config.mse_weight):
return
import torch
from safetensors.torch import save_file
directory.mkdir(parents=True, exist_ok=True)
with backend._inference():
for index, record in enumerate(records):
tensors = {}
tokens = record.tokens
teacher = tokens["teacher_prompt_ids"]
student = tokens["student_prompt_ids"]
start = len(teacher) - len(student) + tokens["alignment_start"]
ids = teacher + tokens["response_ids"]
model_config = getattr(backend._model.config, "text_config", backend._model.config)
limit = getattr(model_config, "max_position_embeddings", None)
if limit is not None and len(ids) > limit:
raise ValueError(f"{record.id}: teacher sequence exceeds the model context length of {limit}")
input_ids = torch.tensor([ids], device=backend._input_device())
output = backend._model(
input_ids=input_ids,
attention_mask=torch.ones_like(input_ids),
use_cache=False,
output_hidden_states=bool(config.mse_weight),
)
if config.kl_weight:
logits = output.logits[0, start:]
top_k = min(config.teacher_top_k or logits.shape[-1], logits.shape[-1])
values, indices = logits.topk(top_k, dim=-1)
tensors["top_logits"] = values.float().cpu().contiguous()
tensors["top_ids"] = indices.cpu().contiguous()
del logits, values, indices
if config.mse_weight:
tensors["states"] = torch.stack(
[state[0, start:].cpu() for state in select_states(output, config)]
).contiguous()
del output
save_file(tensors, directory / f"{index}.safetensors")
def load_prepared(
directory: Path, teacher: dict[str, Any], loss: LossConfig
) -> tuple[dict[str, Any], list[TrainingRecord]]:
"""Validate and load cached data without generation, filtering, or teacher forward passes."""
metadata = json.loads((directory / "data.json").read_text(encoding="utf-8"))
if metadata.get("version") not in {1, 2} or metadata["teacher"] != teacher:
raise ValueError("Training data model/tokenizer/teacher state does not match the method; run prepare again")
files = metadata["files"]
if "train.jsonl" not in files:
raise ValueError("Prepared data directory is missing training record checksums")
allowed = {"train.jsonl", "records.jsonl", "results.jsonl", "generation.json", "selection.json"}
for name, digest in files.items():
relative = Path(name)
is_target = (
relative.parent == Path("targets") and relative.suffix == ".safetensors"
and relative.stem.isdecimal()
)
if (name not in allowed and not is_target) or checksum(directory / name) != digest:
raise ValueError("Training data or teacher targets have changed")
if loss.kl_weight and metadata["loss"]["teacher_top_k"] != loss.teacher_top_k:
raise ValueError("teacher_top_k differs from the prepared data; run prepare again")
if loss.mse_weight and metadata["loss"]["hidden_layers"] != (
list(loss.hidden_layers) if loss.hidden_layers is not None else None
):
raise ValueError("MSE hidden_layers differs from the prepared data; run prepare again")
records = load_records(directory / "train.jsonl")
if not records or len({record.id for record in records}) != len(records):
raise ValueError("Training records are empty or contain duplicate IDs")
if loss.kl_weight or loss.mse_weight:
if any(f"targets/{index}.safetensors" not in files for index in range(len(records))):
raise ValueError("The current loss requires teacher targets; run prepare with the corresponding LossConfig")
return metadata, records