introspection-transform 0.3.0__tar.gz → 0.4.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {introspection_transform-0.3.0 → introspection_transform-0.4.0}/PKG-INFO +1 -1
- {introspection_transform-0.3.0 → introspection_transform-0.4.0}/introspection_transform/trainer/__init__.py +4 -1
- introspection_transform-0.4.0/introspection_transform/trainer/loop.py +143 -0
- introspection_transform-0.4.0/introspection_transform/trainer/render.py +213 -0
- {introspection_transform-0.3.0 → introspection_transform-0.4.0}/introspection_transform/trainer/sample.py +2 -5
- {introspection_transform-0.3.0 → introspection_transform-0.4.0}/pyproject.toml +1 -1
- introspection_transform-0.3.0/introspection_transform/trainer/loop.py +0 -76
- introspection_transform-0.3.0/introspection_transform/trainer/render.py +0 -148
- {introspection_transform-0.3.0 → introspection_transform-0.4.0}/.gitignore +0 -0
- {introspection_transform-0.3.0 → introspection_transform-0.4.0}/LICENSE +0 -0
- {introspection_transform-0.3.0 → introspection_transform-0.4.0}/README.md +0 -0
- {introspection_transform-0.3.0 → introspection_transform-0.4.0}/introspection_transform/__init__.py +0 -0
- {introspection_transform-0.3.0 → introspection_transform-0.4.0}/introspection_transform/annotations.py +0 -0
- {introspection_transform-0.3.0 → introspection_transform-0.4.0}/introspection_transform/genai.py +0 -0
- {introspection_transform-0.3.0 → introspection_transform-0.4.0}/introspection_transform/genai_span.py +0 -0
- {introspection_transform-0.3.0 → introspection_transform-0.4.0}/introspection_transform/messages.py +0 -0
- {introspection_transform-0.3.0 → introspection_transform-0.4.0}/introspection_transform/projection.py +0 -0
- {introspection_transform-0.3.0 → introspection_transform-0.4.0}/introspection_transform/py.typed +0 -0
- {introspection_transform-0.3.0 → introspection_transform-0.4.0}/introspection_transform/trainer/adapter.py +0 -0
- {introspection_transform-0.3.0 → introspection_transform-0.4.0}/introspection_transform/trainer/extras.py +0 -0
- {introspection_transform-0.3.0 → introspection_transform-0.4.0}/introspection_transform/trainer/fireworks.py +0 -0
- {introspection_transform-0.3.0 → introspection_transform-0.4.0}/introspection_transform/trainer/lora.py +0 -0
- {introspection_transform-0.3.0 → introspection_transform-0.4.0}/introspection_transform/trainer/tinker.py +0 -0
- {introspection_transform-0.3.0 → introspection_transform-0.4.0}/introspection_transform/training.py +0 -0
- {introspection_transform-0.3.0 → introspection_transform-0.4.0}/introspection_transform/trajectory.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: introspection-transform
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: GenAI spans to a Harbor ATIF trajectory and to introspection.training/v1 examples, and an ATIF trajectory to the AG-UI messages that open a run
|
|
5
5
|
License-Expression: Apache-2.0
|
|
6
6
|
License-File: LICENSE
|
|
@@ -19,10 +19,11 @@ from introspection_transform.trainer.fireworks import (
|
|
|
19
19
|
FireworksAdapter,
|
|
20
20
|
PromotionError,
|
|
21
21
|
)
|
|
22
|
-
from introspection_transform.trainer.loop import TrainingRun, train
|
|
22
|
+
from introspection_transform.trainer.loop import StepReport, TrainingRun, train
|
|
23
23
|
from introspection_transform.trainer.render import (
|
|
24
24
|
ChatTokenizer,
|
|
25
25
|
RenderError,
|
|
26
|
+
chat_message,
|
|
26
27
|
generation_stop_tokens,
|
|
27
28
|
render_example,
|
|
28
29
|
)
|
|
@@ -45,9 +46,11 @@ __all__ = [
|
|
|
45
46
|
"RenderError",
|
|
46
47
|
"RenderedExample",
|
|
47
48
|
"SamplingAdapter",
|
|
49
|
+
"StepReport",
|
|
48
50
|
"TinkerAdapter",
|
|
49
51
|
"TrainingAdapter",
|
|
50
52
|
"TrainingRun",
|
|
53
|
+
"chat_message",
|
|
51
54
|
"generation_stop_tokens",
|
|
52
55
|
"prompt_tokens",
|
|
53
56
|
"render_example",
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""The training loop: render the rows, step through batches, save, close."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import random
|
|
7
|
+
import time
|
|
8
|
+
from collections.abc import Callable, Iterator, Mapping, Sequence
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from pydantic import BaseModel
|
|
12
|
+
|
|
13
|
+
from introspection_transform.trainer.adapter import (
|
|
14
|
+
RenderedExample,
|
|
15
|
+
Session,
|
|
16
|
+
TrainingAdapter,
|
|
17
|
+
)
|
|
18
|
+
from introspection_transform.trainer.render import (
|
|
19
|
+
ChatTokenizer,
|
|
20
|
+
render_example,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
__all__ = ["StepReport", "TrainingRun", "train"]
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class TrainingRun(BaseModel):
|
|
29
|
+
"""A finished run: the sampler weights' path and each step's metrics."""
|
|
30
|
+
|
|
31
|
+
path: str
|
|
32
|
+
steps: int
|
|
33
|
+
metrics: list[dict[str, float]]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class StepReport(BaseModel):
|
|
37
|
+
"""One optimizer step, as :func:`train` hands it to ``on_step``."""
|
|
38
|
+
|
|
39
|
+
step: int
|
|
40
|
+
"""1-based."""
|
|
41
|
+
examples: int
|
|
42
|
+
tokens: int
|
|
43
|
+
"""Tokens the batch sent, over every example."""
|
|
44
|
+
trained_tokens: int
|
|
45
|
+
"""Tokens the batch weighted, over every example."""
|
|
46
|
+
started_ns: int
|
|
47
|
+
ended_ns: int
|
|
48
|
+
metrics: dict[str, float]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def train(
|
|
52
|
+
rows: Sequence[Mapping[str, Any]],
|
|
53
|
+
adapter: TrainingAdapter[Session],
|
|
54
|
+
tokenizer: ChatTokenizer,
|
|
55
|
+
*,
|
|
56
|
+
base_model: str,
|
|
57
|
+
training_id: str,
|
|
58
|
+
lora_rank: int = 8,
|
|
59
|
+
epochs: int = 1,
|
|
60
|
+
max_steps: int | None = None,
|
|
61
|
+
batch_size: int = 16,
|
|
62
|
+
learning_rate: float = 1e-4,
|
|
63
|
+
seed: int = 0,
|
|
64
|
+
stop_tokens: Sequence[int] | None = None,
|
|
65
|
+
max_seq_len: int | None = None,
|
|
66
|
+
on_step: Callable[[StepReport], None] | None = None,
|
|
67
|
+
) -> TrainingRun:
|
|
68
|
+
"""LoRA SFT on ``rows`` (:func:`~introspection_transform.training.sft_row`).
|
|
69
|
+
|
|
70
|
+
Each epoch shuffles the rows with ``random.Random(seed)``. With
|
|
71
|
+
``max_steps``, the run takes exactly that many steps, starting a freshly
|
|
72
|
+
shuffled epoch whenever one runs out, and ``epochs`` is ignored. The
|
|
73
|
+
weights are saved for sampling as ``final``. The session is closed either
|
|
74
|
+
way, as failed when anything raised, and the error is re-raised.
|
|
75
|
+
``stop_tokens`` end each trained reply at the model's stop token (see
|
|
76
|
+
:func:`~introspection_transform.trainer.render_example`); pass
|
|
77
|
+
:func:`~introspection_transform.trainer.generation_stop_tokens`.
|
|
78
|
+
``on_step`` is called after each step, for progress and telemetry.
|
|
79
|
+
|
|
80
|
+
Raises:
|
|
81
|
+
RenderError: a row cannot be rendered, or renders longer than
|
|
82
|
+
``max_seq_len``; nothing is opened.
|
|
83
|
+
"""
|
|
84
|
+
examples = [
|
|
85
|
+
render_example(row, tokenizer, stop_tokens, max_seq_len)
|
|
86
|
+
for row in rows
|
|
87
|
+
]
|
|
88
|
+
order = random.Random(seed)
|
|
89
|
+
session = adapter.open(base_model, lora_rank, training_id)
|
|
90
|
+
metrics: list[dict[str, float]] = []
|
|
91
|
+
try:
|
|
92
|
+
for batch in _batches(examples, order, epochs, max_steps, batch_size):
|
|
93
|
+
started = time.time_ns()
|
|
94
|
+
result = adapter.step(session, batch, learning_rate)
|
|
95
|
+
metrics.append(result)
|
|
96
|
+
logger.debug(
|
|
97
|
+
"Trained a step",
|
|
98
|
+
extra={"training_id": training_id, "step": len(metrics)},
|
|
99
|
+
)
|
|
100
|
+
if on_step is not None:
|
|
101
|
+
on_step(
|
|
102
|
+
StepReport(
|
|
103
|
+
step=len(metrics),
|
|
104
|
+
examples=len(batch),
|
|
105
|
+
tokens=sum(len(example.tokens) for example in batch),
|
|
106
|
+
trained_tokens=int(
|
|
107
|
+
sum(sum(example.weights) for example in batch)
|
|
108
|
+
),
|
|
109
|
+
started_ns=started,
|
|
110
|
+
ended_ns=time.time_ns(),
|
|
111
|
+
metrics=result,
|
|
112
|
+
)
|
|
113
|
+
)
|
|
114
|
+
path = adapter.save(session, "final")
|
|
115
|
+
except BaseException:
|
|
116
|
+
adapter.close(session, False)
|
|
117
|
+
raise
|
|
118
|
+
adapter.close(session, True)
|
|
119
|
+
return TrainingRun(path=path, steps=len(metrics), metrics=metrics)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _batches(
|
|
123
|
+
examples: list[RenderedExample],
|
|
124
|
+
order: random.Random,
|
|
125
|
+
epochs: int,
|
|
126
|
+
max_steps: int | None,
|
|
127
|
+
batch_size: int,
|
|
128
|
+
) -> Iterator[list[RenderedExample]]:
|
|
129
|
+
"""Each step's batch: ``epochs`` shuffled passes, or exactly ``max_steps``."""
|
|
130
|
+
if not examples:
|
|
131
|
+
return
|
|
132
|
+
steps = 0
|
|
133
|
+
epoch = 0
|
|
134
|
+
while (max_steps is None and epoch < epochs) or (
|
|
135
|
+
max_steps is not None and steps < max_steps
|
|
136
|
+
):
|
|
137
|
+
shuffled = order.sample(examples, len(examples))
|
|
138
|
+
for first in range(0, len(shuffled), batch_size):
|
|
139
|
+
if max_steps is not None and steps >= max_steps:
|
|
140
|
+
return
|
|
141
|
+
yield shuffled[first : first + batch_size]
|
|
142
|
+
steps += 1
|
|
143
|
+
epoch += 1
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""An SFT row as weighted tokens, rendered with the base model's chat template.
|
|
2
|
+
|
|
3
|
+
Each trainable assistant message is trained on the tokens the template adds for
|
|
4
|
+
it after its generation prompt; everything before, its generation prompt
|
|
5
|
+
included, is untrained, so a row may interleave trained replies with untrained
|
|
6
|
+
turns. A template that does not reproduce what came before as the start of a
|
|
7
|
+
later rendering (one that rewrites earlier turns, such as dropping past
|
|
8
|
+
thinking) is refused rather than mis-weighted.
|
|
9
|
+
|
|
10
|
+
With ``stop_tokens`` (the ids sampling stops on: the model's generation
|
|
11
|
+
``eos_token_id`` list, see :func:`generation_stop_tokens`), the trained reply
|
|
12
|
+
ends right after its first stop token, so the model learns to stop where the
|
|
13
|
+
server stops it. Templates disagree here: some write a newline after the stop
|
|
14
|
+
token, which would be trained but never sampled, and some (GLM) end the reply
|
|
15
|
+
without one, because the next turn's opening token is what ends it. Such a
|
|
16
|
+
reply is extended with how the template opens a following user turn, and cut
|
|
17
|
+
after the first stop token that brings.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from collections.abc import Mapping, Sequence
|
|
23
|
+
from typing import Any, Protocol
|
|
24
|
+
|
|
25
|
+
from introspection_transform.trainer.adapter import RenderedExample
|
|
26
|
+
from introspection_transform.trainer.extras import require
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"ChatTokenizer",
|
|
30
|
+
"RenderError",
|
|
31
|
+
"chat_message",
|
|
32
|
+
"generation_stop_tokens",
|
|
33
|
+
"render_example",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class RenderError(ValueError):
|
|
38
|
+
"""An SFT row cannot be rendered into weighted tokens."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class ChatTokenizer(Protocol):
|
|
42
|
+
"""The part of a Hugging Face tokenizer rendering uses."""
|
|
43
|
+
|
|
44
|
+
def apply_chat_template(
|
|
45
|
+
self,
|
|
46
|
+
conversation: list[dict[str, Any]],
|
|
47
|
+
*,
|
|
48
|
+
tools: list[dict[str, Any]] | None = None,
|
|
49
|
+
add_generation_prompt: bool = False,
|
|
50
|
+
tokenize: bool = True,
|
|
51
|
+
return_dict: bool = False,
|
|
52
|
+
) -> Any: ...
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def chat_message(message: Mapping[str, Any]) -> dict[str, Any]:
|
|
56
|
+
"""A training message as a chat template reads it.
|
|
57
|
+
|
|
58
|
+
``trainable`` is dropped. Content given as parts (``span_to_example``
|
|
59
|
+
writes a thinking part as ``{"type": "thinking"}``) becomes the text parts'
|
|
60
|
+
text, and the thinking parts' text becomes ``reasoning_content``, the key
|
|
61
|
+
chat templates read reasoning from.
|
|
62
|
+
"""
|
|
63
|
+
rendered = {
|
|
64
|
+
key: value
|
|
65
|
+
for key, value in message.items()
|
|
66
|
+
if key not in ("trainable", "content")
|
|
67
|
+
}
|
|
68
|
+
content = message.get("content")
|
|
69
|
+
if isinstance(content, list):
|
|
70
|
+
rendered["content"] = "".join(
|
|
71
|
+
part.get("text", "")
|
|
72
|
+
for part in content
|
|
73
|
+
if part.get("type") == "text"
|
|
74
|
+
)
|
|
75
|
+
thinking = "".join(
|
|
76
|
+
part.get("thinking", "")
|
|
77
|
+
for part in content
|
|
78
|
+
if part.get("type") == "thinking"
|
|
79
|
+
)
|
|
80
|
+
if thinking:
|
|
81
|
+
rendered["reasoning_content"] = thinking
|
|
82
|
+
else:
|
|
83
|
+
rendered["content"] = content if content is not None else ""
|
|
84
|
+
return rendered
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def generation_stop_tokens(model: str) -> list[int]:
|
|
88
|
+
"""The token ids generation stops on for ``model``, from its Hugging Face
|
|
89
|
+
``generation_config``: what to pass as ``stop_tokens``.
|
|
90
|
+
|
|
91
|
+
Needs ``transformers``, which both extras install.
|
|
92
|
+
"""
|
|
93
|
+
transformers = require("transformers", "fireworks")
|
|
94
|
+
ids = transformers.GenerationConfig.from_pretrained(model).eos_token_id
|
|
95
|
+
return [ids] if isinstance(ids, int) else list(ids or [])
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _template(
|
|
99
|
+
tokenizer: ChatTokenizer,
|
|
100
|
+
messages: list[dict[str, Any]],
|
|
101
|
+
tools: list[dict[str, Any]] | None,
|
|
102
|
+
*,
|
|
103
|
+
add_generation_prompt: bool = False,
|
|
104
|
+
) -> list[int]:
|
|
105
|
+
return list(
|
|
106
|
+
tokenizer.apply_chat_template(
|
|
107
|
+
messages,
|
|
108
|
+
tools=tools,
|
|
109
|
+
add_generation_prompt=add_generation_prompt,
|
|
110
|
+
tokenize=True,
|
|
111
|
+
return_dict=False,
|
|
112
|
+
)
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _end_at_stop(
|
|
117
|
+
reply: list[int], stops: set[int], following: list[int]
|
|
118
|
+
) -> list[int]:
|
|
119
|
+
"""``reply`` through its first stop token, reading on into ``following``."""
|
|
120
|
+
tokens = reply + following
|
|
121
|
+
for index, token in enumerate(tokens):
|
|
122
|
+
if token in stops:
|
|
123
|
+
return tokens[: index + 1]
|
|
124
|
+
raise RenderError(
|
|
125
|
+
"no stop token ends the reply, even after the template opens the "
|
|
126
|
+
"next turn; pass the model's generation stop tokens"
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _extend(
|
|
131
|
+
tokens: list[int], weights: list[float], rendered: list[int], weight: float
|
|
132
|
+
) -> None:
|
|
133
|
+
"""Appends what ``rendered`` adds after ``tokens``, which it must start with."""
|
|
134
|
+
if rendered[: len(tokens)] != tokens:
|
|
135
|
+
raise RenderError(
|
|
136
|
+
"the chat template renders an earlier message differently "
|
|
137
|
+
"inside a later one"
|
|
138
|
+
)
|
|
139
|
+
added = rendered[len(tokens) :]
|
|
140
|
+
tokens.extend(added)
|
|
141
|
+
weights.extend([weight] * len(added))
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def render_example(
|
|
145
|
+
row: Mapping[str, Any],
|
|
146
|
+
tokenizer: ChatTokenizer,
|
|
147
|
+
stop_tokens: Sequence[int] | None = None,
|
|
148
|
+
max_seq_len: int | None = None,
|
|
149
|
+
) -> RenderedExample:
|
|
150
|
+
"""``row``, an :func:`~introspection_transform.training.sft_row`, as tokens.
|
|
151
|
+
|
|
152
|
+
``stop_tokens``, when given, end the trained reply (see the module).
|
|
153
|
+
Messages go to the template as :func:`chat_message` makes them.
|
|
154
|
+
|
|
155
|
+
Each trainable assistant message is trained after its own generation
|
|
156
|
+
prompt, so a row may interleave trained replies with untrained turns;
|
|
157
|
+
messages after the last trainable one are left out.
|
|
158
|
+
|
|
159
|
+
Raises:
|
|
160
|
+
RenderError: the row has no trainable message, the template does not
|
|
161
|
+
extend a prompt with its reply or re-renders an earlier message
|
|
162
|
+
differently, no stop token ends a reply, or the row renders
|
|
163
|
+
longer than ``max_seq_len``.
|
|
164
|
+
"""
|
|
165
|
+
messages = row["messages"]
|
|
166
|
+
flags = [bool(message.get("trainable")) for message in messages]
|
|
167
|
+
if True not in flags:
|
|
168
|
+
raise RenderError("the row has no trainable message")
|
|
169
|
+
last = len(flags) - 1 - flags[::-1].index(True)
|
|
170
|
+
plain = [chat_message(message) for message in messages[: last + 1]]
|
|
171
|
+
tools = row.get("tools") or None
|
|
172
|
+
stops = set(stop_tokens or ())
|
|
173
|
+
tokens: list[int] = []
|
|
174
|
+
weights: list[float] = []
|
|
175
|
+
for index, message in enumerate(plain):
|
|
176
|
+
if flags[index] and message.get("role") == "assistant":
|
|
177
|
+
# Each trained reply follows its own generation prompt, untrained.
|
|
178
|
+
prompt = _template(
|
|
179
|
+
tokenizer, plain[:index], tools, add_generation_prompt=True
|
|
180
|
+
)
|
|
181
|
+
_extend(tokens, weights, prompt, 0.0)
|
|
182
|
+
full = _template(tokenizer, plain[: index + 1], tools)
|
|
183
|
+
if len(full) <= len(tokens) or full[: len(tokens)] != tokens:
|
|
184
|
+
raise RenderError(
|
|
185
|
+
"the chat template does not extend the prompt with the reply"
|
|
186
|
+
)
|
|
187
|
+
reply = full[len(tokens) :]
|
|
188
|
+
if stops:
|
|
189
|
+
following: list[int] = []
|
|
190
|
+
if not stops.intersection(reply):
|
|
191
|
+
opened = _template(
|
|
192
|
+
tokenizer,
|
|
193
|
+
[*plain[: index + 1], {"role": "user", "content": ""}],
|
|
194
|
+
tools,
|
|
195
|
+
)
|
|
196
|
+
if opened[: len(full)] == full:
|
|
197
|
+
following = opened[len(full) :]
|
|
198
|
+
reply = _end_at_stop(reply, stops, following)
|
|
199
|
+
tokens.extend(reply)
|
|
200
|
+
weights.extend([1.0] * len(reply))
|
|
201
|
+
elif flags[index]:
|
|
202
|
+
# A trainable message that is not a reply (a tool result) is
|
|
203
|
+
# trained as the template renders it. Untrained messages need no
|
|
204
|
+
# rendering of their own: the next reply's generation prompt
|
|
205
|
+
# covers them.
|
|
206
|
+
rendered = _template(tokenizer, plain[: index + 1], tools)
|
|
207
|
+
_extend(tokens, weights, rendered, 1.0)
|
|
208
|
+
if max_seq_len is not None and len(tokens) > max_seq_len:
|
|
209
|
+
raise RenderError(
|
|
210
|
+
f"the row renders to {len(tokens)} tokens, "
|
|
211
|
+
f"over max_seq_len {max_seq_len}"
|
|
212
|
+
)
|
|
213
|
+
return RenderedExample(tokens=tokens, weights=weights)
|
|
@@ -17,7 +17,7 @@ from typing import Any, Protocol, TypeVar
|
|
|
17
17
|
|
|
18
18
|
from pydantic import BaseModel
|
|
19
19
|
|
|
20
|
-
from introspection_transform.trainer.render import ChatTokenizer
|
|
20
|
+
from introspection_transform.trainer.render import ChatTokenizer, chat_message
|
|
21
21
|
|
|
22
22
|
__all__ = [
|
|
23
23
|
"Prediction",
|
|
@@ -80,10 +80,7 @@ class SamplingAdapter(Protocol[Sampler]):
|
|
|
80
80
|
def _messages(
|
|
81
81
|
row: Mapping[str, Any],
|
|
82
82
|
) -> tuple[list[dict[str, Any]], str | None]:
|
|
83
|
-
messages = [
|
|
84
|
-
{key: value for key, value in message.items() if key != "trainable"}
|
|
85
|
-
for message in row["messages"]
|
|
86
|
-
]
|
|
83
|
+
messages = [chat_message(message) for message in row["messages"]]
|
|
87
84
|
flags = [bool(message.get("trainable")) for message in row["messages"]]
|
|
88
85
|
if True not in flags:
|
|
89
86
|
return messages, None
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "introspection-transform"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.4.0"
|
|
8
8
|
description = "GenAI spans to a Harbor ATIF trajectory and to introspection.training/v1 examples, and an ATIF trajectory to the AG-UI messages that open a run"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.11"
|
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
"""The training loop: render the rows, step through batches, save, close."""
|
|
2
|
-
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
5
|
-
import logging
|
|
6
|
-
import random
|
|
7
|
-
from collections.abc import Mapping, Sequence
|
|
8
|
-
from typing import Any
|
|
9
|
-
|
|
10
|
-
from pydantic import BaseModel
|
|
11
|
-
|
|
12
|
-
from introspection_transform.trainer.adapter import Session, TrainingAdapter
|
|
13
|
-
from introspection_transform.trainer.render import (
|
|
14
|
-
ChatTokenizer,
|
|
15
|
-
render_example,
|
|
16
|
-
)
|
|
17
|
-
|
|
18
|
-
__all__ = ["TrainingRun", "train"]
|
|
19
|
-
|
|
20
|
-
logger = logging.getLogger(__name__)
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
class TrainingRun(BaseModel):
|
|
24
|
-
"""A finished run: the sampler weights' path and each step's metrics."""
|
|
25
|
-
|
|
26
|
-
path: str
|
|
27
|
-
steps: int
|
|
28
|
-
metrics: list[dict[str, float]]
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
def train(
|
|
32
|
-
rows: Sequence[Mapping[str, Any]],
|
|
33
|
-
adapter: TrainingAdapter[Session],
|
|
34
|
-
tokenizer: ChatTokenizer,
|
|
35
|
-
*,
|
|
36
|
-
base_model: str,
|
|
37
|
-
training_id: str,
|
|
38
|
-
lora_rank: int = 8,
|
|
39
|
-
epochs: int = 1,
|
|
40
|
-
batch_size: int = 16,
|
|
41
|
-
learning_rate: float = 1e-4,
|
|
42
|
-
seed: int = 0,
|
|
43
|
-
stop_tokens: Sequence[int] | None = None,
|
|
44
|
-
) -> TrainingRun:
|
|
45
|
-
"""LoRA SFT on ``rows`` (:func:`~introspection_transform.training.sft_row`).
|
|
46
|
-
|
|
47
|
-
Each epoch shuffles the rows with ``random.Random(seed)``. The weights
|
|
48
|
-
are saved for sampling as ``final``. The session is closed either way,
|
|
49
|
-
as failed when anything raised, and the error is re-raised.
|
|
50
|
-
``stop_tokens`` end each trained reply at the model's stop token (see
|
|
51
|
-
:func:`~introspection_transform.trainer.render_example`); pass
|
|
52
|
-
:func:`~introspection_transform.trainer.generation_stop_tokens`.
|
|
53
|
-
|
|
54
|
-
Raises:
|
|
55
|
-
RenderError: a row cannot be rendered; nothing is opened.
|
|
56
|
-
"""
|
|
57
|
-
examples = [render_example(row, tokenizer, stop_tokens) for row in rows]
|
|
58
|
-
order = random.Random(seed)
|
|
59
|
-
session = adapter.open(base_model, lora_rank, training_id)
|
|
60
|
-
metrics: list[dict[str, float]] = []
|
|
61
|
-
try:
|
|
62
|
-
for _ in range(epochs):
|
|
63
|
-
shuffled = order.sample(examples, len(examples))
|
|
64
|
-
for first in range(0, len(shuffled), batch_size):
|
|
65
|
-
batch = shuffled[first : first + batch_size]
|
|
66
|
-
metrics.append(adapter.step(session, batch, learning_rate))
|
|
67
|
-
logger.debug(
|
|
68
|
-
"Trained a step",
|
|
69
|
-
extra={"training_id": training_id, "step": len(metrics)},
|
|
70
|
-
)
|
|
71
|
-
path = adapter.save(session, "final")
|
|
72
|
-
except BaseException:
|
|
73
|
-
adapter.close(session, False)
|
|
74
|
-
raise
|
|
75
|
-
adapter.close(session, True)
|
|
76
|
-
return TrainingRun(path=path, steps=len(metrics), metrics=metrics)
|
|
@@ -1,148 +0,0 @@
|
|
|
1
|
-
"""An SFT row as weighted tokens, rendered with the base model's chat template.
|
|
2
|
-
|
|
3
|
-
The prompt is every message before the first trainable one, rendered with the
|
|
4
|
-
generation prompt; the full row is rendered without it. Only the tokens the
|
|
5
|
-
full rendering adds after the prompt are trained on, so every message after
|
|
6
|
-
the first trainable one must be trainable too. A template that does not
|
|
7
|
-
reproduce the prompt as the start of the full rendering (one that rewrites
|
|
8
|
-
earlier turns, such as dropping past thinking) is refused rather than
|
|
9
|
-
mis-weighted.
|
|
10
|
-
|
|
11
|
-
With ``stop_tokens`` (the ids sampling stops on: the model's generation
|
|
12
|
-
``eos_token_id`` list, see :func:`generation_stop_tokens`), the trained reply
|
|
13
|
-
ends right after its first stop token, so the model learns to stop where the
|
|
14
|
-
server stops it. Templates disagree here: some write a newline after the stop
|
|
15
|
-
token, which would be trained but never sampled, and some (GLM) end the reply
|
|
16
|
-
without one, because the next turn's opening token is what ends it. Such a
|
|
17
|
-
reply is extended with how the template opens a following user turn, and cut
|
|
18
|
-
after the first stop token that brings.
|
|
19
|
-
"""
|
|
20
|
-
|
|
21
|
-
from __future__ import annotations
|
|
22
|
-
|
|
23
|
-
from collections.abc import Mapping, Sequence
|
|
24
|
-
from typing import Any, Protocol
|
|
25
|
-
|
|
26
|
-
from introspection_transform.trainer.adapter import RenderedExample
|
|
27
|
-
from introspection_transform.trainer.extras import require
|
|
28
|
-
|
|
29
|
-
__all__ = [
|
|
30
|
-
"ChatTokenizer",
|
|
31
|
-
"RenderError",
|
|
32
|
-
"generation_stop_tokens",
|
|
33
|
-
"render_example",
|
|
34
|
-
]
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
class RenderError(ValueError):
|
|
38
|
-
"""An SFT row cannot be rendered into weighted tokens."""
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
class ChatTokenizer(Protocol):
|
|
42
|
-
"""The part of a Hugging Face tokenizer rendering uses."""
|
|
43
|
-
|
|
44
|
-
def apply_chat_template(
|
|
45
|
-
self,
|
|
46
|
-
conversation: list[dict[str, Any]],
|
|
47
|
-
*,
|
|
48
|
-
tools: list[dict[str, Any]] | None = None,
|
|
49
|
-
add_generation_prompt: bool = False,
|
|
50
|
-
tokenize: bool = True,
|
|
51
|
-
return_dict: bool = False,
|
|
52
|
-
) -> Any: ...
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
def generation_stop_tokens(model: str) -> list[int]:
|
|
56
|
-
"""The token ids generation stops on for ``model``, from its Hugging Face
|
|
57
|
-
``generation_config``: what to pass as ``stop_tokens``.
|
|
58
|
-
|
|
59
|
-
Needs ``transformers``, which both extras install.
|
|
60
|
-
"""
|
|
61
|
-
transformers = require("transformers", "fireworks")
|
|
62
|
-
ids = transformers.GenerationConfig.from_pretrained(model).eos_token_id
|
|
63
|
-
return [ids] if isinstance(ids, int) else list(ids or [])
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
def _template(
|
|
67
|
-
tokenizer: ChatTokenizer,
|
|
68
|
-
messages: list[dict[str, Any]],
|
|
69
|
-
tools: list[dict[str, Any]] | None,
|
|
70
|
-
*,
|
|
71
|
-
add_generation_prompt: bool = False,
|
|
72
|
-
) -> list[int]:
|
|
73
|
-
return list(
|
|
74
|
-
tokenizer.apply_chat_template(
|
|
75
|
-
messages,
|
|
76
|
-
tools=tools,
|
|
77
|
-
add_generation_prompt=add_generation_prompt,
|
|
78
|
-
tokenize=True,
|
|
79
|
-
return_dict=False,
|
|
80
|
-
)
|
|
81
|
-
)
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
def _end_at_stop(
|
|
85
|
-
reply: list[int], stops: set[int], following: list[int]
|
|
86
|
-
) -> list[int]:
|
|
87
|
-
"""``reply`` through its first stop token, reading on into ``following``."""
|
|
88
|
-
tokens = reply + following
|
|
89
|
-
for index, token in enumerate(tokens):
|
|
90
|
-
if token in stops:
|
|
91
|
-
return tokens[: index + 1]
|
|
92
|
-
raise RenderError(
|
|
93
|
-
"no stop token ends the reply, even after the template opens the "
|
|
94
|
-
"next turn; pass the model's generation stop tokens"
|
|
95
|
-
)
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
def render_example(
|
|
99
|
-
row: Mapping[str, Any],
|
|
100
|
-
tokenizer: ChatTokenizer,
|
|
101
|
-
stop_tokens: Sequence[int] | None = None,
|
|
102
|
-
) -> RenderedExample:
|
|
103
|
-
"""``row``, an :func:`~introspection_transform.training.sft_row`, as tokens.
|
|
104
|
-
|
|
105
|
-
``stop_tokens``, when given, end the trained reply (see the module).
|
|
106
|
-
|
|
107
|
-
Raises:
|
|
108
|
-
RenderError: the row has no trainable message, has an untrained one
|
|
109
|
-
after it, the template does not extend the prompt, or no stop
|
|
110
|
-
token ends the reply.
|
|
111
|
-
"""
|
|
112
|
-
messages = row["messages"]
|
|
113
|
-
flags = [bool(message.get("trainable")) for message in messages]
|
|
114
|
-
if True not in flags:
|
|
115
|
-
raise RenderError("the row has no trainable message")
|
|
116
|
-
first = flags.index(True)
|
|
117
|
-
if not all(flags[first:]):
|
|
118
|
-
raise RenderError(
|
|
119
|
-
"an untrained message follows the first trainable one"
|
|
120
|
-
)
|
|
121
|
-
plain = [
|
|
122
|
-
{key: value for key, value in message.items() if key != "trainable"}
|
|
123
|
-
for message in messages
|
|
124
|
-
]
|
|
125
|
-
tools = row.get("tools") or None
|
|
126
|
-
prompt = _template(
|
|
127
|
-
tokenizer, plain[:first], tools, add_generation_prompt=True
|
|
128
|
-
)
|
|
129
|
-
full = _template(tokenizer, plain, tools)
|
|
130
|
-
if len(full) <= len(prompt) or full[: len(prompt)] != prompt:
|
|
131
|
-
raise RenderError(
|
|
132
|
-
"the chat template does not extend the prompt with the reply"
|
|
133
|
-
)
|
|
134
|
-
reply = full[len(prompt) :]
|
|
135
|
-
if stop_tokens:
|
|
136
|
-
stops = set(stop_tokens)
|
|
137
|
-
following: list[int] = []
|
|
138
|
-
if not stops.intersection(reply):
|
|
139
|
-
opened = _template(
|
|
140
|
-
tokenizer, [*plain, {"role": "user", "content": ""}], tools
|
|
141
|
-
)
|
|
142
|
-
if opened[: len(full)] == full:
|
|
143
|
-
following = opened[len(full) :]
|
|
144
|
-
reply = _end_at_stop(reply, stops, following)
|
|
145
|
-
return RenderedExample(
|
|
146
|
-
tokens=prompt + reply,
|
|
147
|
-
weights=[0.0] * len(prompt) + [1.0] * len(reply),
|
|
148
|
-
)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{introspection_transform-0.3.0 → introspection_transform-0.4.0}/introspection_transform/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
{introspection_transform-0.3.0 → introspection_transform-0.4.0}/introspection_transform/genai.py
RENAMED
|
File without changes
|
|
File without changes
|
{introspection_transform-0.3.0 → introspection_transform-0.4.0}/introspection_transform/messages.py
RENAMED
|
File without changes
|
|
File without changes
|
{introspection_transform-0.3.0 → introspection_transform-0.4.0}/introspection_transform/py.typed
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{introspection_transform-0.3.0 → introspection_transform-0.4.0}/introspection_transform/training.py
RENAMED
|
File without changes
|
|
File without changes
|