introspection-transform 0.2.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.4.0/PKG-INFO +168 -0
- introspection_transform-0.4.0/README.md +141 -0
- introspection_transform-0.4.0/introspection_transform/trainer/__init__.py +60 -0
- introspection_transform-0.4.0/introspection_transform/trainer/adapter.py +59 -0
- introspection_transform-0.4.0/introspection_transform/trainer/extras.py +30 -0
- introspection_transform-0.4.0/introspection_transform/trainer/fireworks.py +210 -0
- introspection_transform-0.4.0/introspection_transform/trainer/loop.py +143 -0
- introspection_transform-0.4.0/introspection_transform/trainer/lora.py +52 -0
- introspection_transform-0.4.0/introspection_transform/trainer/render.py +213 -0
- introspection_transform-0.4.0/introspection_transform/trainer/sample.py +182 -0
- introspection_transform-0.4.0/introspection_transform/trainer/tinker.py +121 -0
- {introspection_transform-0.2.0 → introspection_transform-0.4.0}/pyproject.toml +22 -1
- introspection_transform-0.2.0/PKG-INFO +0 -75
- introspection_transform-0.2.0/README.md +0 -56
- {introspection_transform-0.2.0 → introspection_transform-0.4.0}/.gitignore +0 -0
- {introspection_transform-0.2.0 → introspection_transform-0.4.0}/LICENSE +0 -0
- {introspection_transform-0.2.0 → introspection_transform-0.4.0}/introspection_transform/__init__.py +0 -0
- {introspection_transform-0.2.0 → introspection_transform-0.4.0}/introspection_transform/annotations.py +0 -0
- {introspection_transform-0.2.0 → introspection_transform-0.4.0}/introspection_transform/genai.py +0 -0
- {introspection_transform-0.2.0 → introspection_transform-0.4.0}/introspection_transform/genai_span.py +0 -0
- {introspection_transform-0.2.0 → introspection_transform-0.4.0}/introspection_transform/messages.py +0 -0
- {introspection_transform-0.2.0 → introspection_transform-0.4.0}/introspection_transform/projection.py +0 -0
- {introspection_transform-0.2.0 → introspection_transform-0.4.0}/introspection_transform/py.typed +0 -0
- {introspection_transform-0.2.0 → introspection_transform-0.4.0}/introspection_transform/training.py +0 -0
- {introspection_transform-0.2.0 → introspection_transform-0.4.0}/introspection_transform/trajectory.py +0 -0
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: introspection-transform
|
|
3
|
+
Version: 0.4.0
|
|
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
|
+
License-Expression: Apache-2.0
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Classifier: Development Status :: 3 - Alpha
|
|
8
|
+
Classifier: Intended Audience :: Developers
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Typing :: Typed
|
|
11
|
+
Requires-Python: >=3.11
|
|
12
|
+
Requires-Dist: ag-ui-protocol>=1.0.0
|
|
13
|
+
Requires-Dist: pydantic>=2.10.0
|
|
14
|
+
Provides-Extra: fireworks
|
|
15
|
+
Requires-Dist: fireworks-ai[training-sdk]>=1.2.39; extra == 'fireworks'
|
|
16
|
+
Requires-Dist: jinja2>=3.1; extra == 'fireworks'
|
|
17
|
+
Requires-Dist: transformers>=4.57.6; extra == 'fireworks'
|
|
18
|
+
Provides-Extra: test
|
|
19
|
+
Requires-Dist: jsonschema>=4.23.0; extra == 'test'
|
|
20
|
+
Requires-Dist: pytest-cov>=7.1.0; extra == 'test'
|
|
21
|
+
Requires-Dist: pytest>=9.0.0; extra == 'test'
|
|
22
|
+
Provides-Extra: tinker
|
|
23
|
+
Requires-Dist: jinja2>=3.1; extra == 'tinker'
|
|
24
|
+
Requires-Dist: tinker>=0.40.1; extra == 'tinker'
|
|
25
|
+
Requires-Dist: transformers>=4.57.6; extra == 'tinker'
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# introspection-transform
|
|
29
|
+
|
|
30
|
+
GenAI spans to a [Harbor](https://github.com/laude-institute/harbor) ATIF
|
|
31
|
+
trajectory, and an ATIF trajectory back to the AG-UI messages that open a
|
|
32
|
+
run. It is the projection `introspection-sdk` uses, published on its own so
|
|
33
|
+
an eval adapter can read a conversation's spans without installing the SDK.
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install introspection-transform
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
from introspection_transform import (
|
|
41
|
+
GenAiSpanList,
|
|
42
|
+
atif_to_messages,
|
|
43
|
+
sft_row,
|
|
44
|
+
span_to_example,
|
|
45
|
+
spans_to_atif,
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
spans = GenAiSpanList.model_validate_json(body).items
|
|
49
|
+
trajectory = spans_to_atif(spans, session_id="conv-1")
|
|
50
|
+
messages = atif_to_messages(trajectory, prompt="Continue the task")
|
|
51
|
+
|
|
52
|
+
# One annotated span as a training example; an item-detail read carries the whole history.
|
|
53
|
+
example = span_to_example(span, labels=["router-correct"])
|
|
54
|
+
row = sft_row(example) # {"messages": [...]} for Fireworks or Tinker SFT
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Training
|
|
58
|
+
|
|
59
|
+
`introspection_transform.trainer` runs LoRA SFT on `introspection.training/v1`
|
|
60
|
+
SFT rows on Fireworks or Tinker. Each provider is an optional extra; neither
|
|
61
|
+
pulls in `torch`:
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
pip install "introspection-transform[tinker]" # tinker
|
|
65
|
+
pip install "introspection-transform[fireworks]" # fireworks-ai[training-sdk], transformers
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
from transformers import AutoTokenizer
|
|
70
|
+
|
|
71
|
+
from introspection_transform import sft_row
|
|
72
|
+
from introspection_transform.trainer import (
|
|
73
|
+
FireworksAdapter,
|
|
74
|
+
TinkerAdapter,
|
|
75
|
+
generation_stop_tokens,
|
|
76
|
+
sample,
|
|
77
|
+
train,
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
rows = [sft_row(example) for example in examples]
|
|
81
|
+
tokenizer = AutoTokenizer.from_pretrained("zai-org/GLM-5.3-Flash")
|
|
82
|
+
stops = generation_stop_tokens("zai-org/GLM-5.3-Flash")
|
|
83
|
+
adapter = FireworksAdapter(
|
|
84
|
+
output_model_id=f"router-{training_id}"
|
|
85
|
+
) # or TinkerAdapter()
|
|
86
|
+
run = train(
|
|
87
|
+
rows,
|
|
88
|
+
adapter, # the SDK reads FIREWORKS_API_KEY / TINKER_API_KEY
|
|
89
|
+
tokenizer,
|
|
90
|
+
base_model="accounts/fireworks/models/glm-5p3-flash", # Tinker: zai-org/GLM-5.3-Flash:peft:262144
|
|
91
|
+
training_id=training_id, # stamped on provider objects as introspection_training_id
|
|
92
|
+
stop_tokens=stops,
|
|
93
|
+
lora_rank=8,
|
|
94
|
+
epochs=1,
|
|
95
|
+
batch_size=16,
|
|
96
|
+
learning_rate=1e-4,
|
|
97
|
+
)
|
|
98
|
+
run.path # accounts/<account>/models/router-<id> on Fireworks; a tinker:// path on Tinker
|
|
99
|
+
|
|
100
|
+
predictions = sample(
|
|
101
|
+
holdout_rows,
|
|
102
|
+
adapter,
|
|
103
|
+
tokenizer,
|
|
104
|
+
base_model="accounts/fireworks/models/glm-5p3-flash",
|
|
105
|
+
model=run.path, # None samples the base model
|
|
106
|
+
stop_tokens=stops,
|
|
107
|
+
)
|
|
108
|
+
[(p.text, p.reference, p.clean) for p in predictions] # score them your way
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Each row is rendered with the base model's chat template: the tokens of the
|
|
112
|
+
trainable reply get weight 1, everything before it 0. With `stop_tokens` (the
|
|
113
|
+
model's generation `eos_token_id` list), the trained reply ends right after its
|
|
114
|
+
first stop token, so the model learns to stop where the server stops it. Chat
|
|
115
|
+
templates disagree there: Qwen's writes a newline after `<|im_end|>`, and GLM's
|
|
116
|
+
ends the reply with no stop token at all (the next turn's `<|user|>` ends it),
|
|
117
|
+
so without `stop_tokens` a GLM model never learns to stop. With them, rendering
|
|
118
|
+
matched the Fireworks and Tinker cookbooks' renderers token for token on Muse
|
|
119
|
+
Glimmer 30B, GLM 5.3 Flash, Inkling 2 Mini and Qwen3-8B.
|
|
120
|
+
|
|
121
|
+
The adapter then opens a LoRA training client, sends each batch as
|
|
122
|
+
`forward_backward(datums, "cross_entropy")` and `optim_step(AdamParams(learning_rate))`,
|
|
123
|
+
saves the weights for sampling and closes the session (deleting it on
|
|
124
|
+
Fireworks). A Fireworks session's checkpoints are unreachable once it is
|
|
125
|
+
deleted, so with `output_model_id` the adapter promotes the final weights to a
|
|
126
|
+
model first, and the run returns that model. `TrainingAdapter` is the protocol
|
|
127
|
+
each provider implements.
|
|
128
|
+
|
|
129
|
+
`sample` samples a base or trained model on the same rows, with no deployment,
|
|
130
|
+
through `SamplingAdapter`, which both adapters also implement: Tinker samples a
|
|
131
|
+
`tinker://` path directly; Fireworks loads a promoted adapter into a LoRA session
|
|
132
|
+
and samples a snapshot of it. Replies are cut at the first stop token, and a
|
|
133
|
+
leading reasoning block is dropped; pass `parse` for a model that needs more.
|
|
134
|
+
|
|
135
|
+
[tinker-cookbook](https://github.com/thinking-machines-lab/tinker-cookbook)
|
|
136
|
+
was the reference design (its supervised loop and its per-message
|
|
137
|
+
`trainable` weights). Neither it nor `tml-renderers`, its renderer layer, is a
|
|
138
|
+
dependency, since both import `torch`. Not mapped: DPO and RL (both need a
|
|
139
|
+
custom loss computed client-side in `torch`), and checkpoint and resume.
|
|
140
|
+
|
|
141
|
+
## Layout
|
|
142
|
+
|
|
143
|
+
| Module | Holds |
|
|
144
|
+
| --- | --- |
|
|
145
|
+
| `introspection_transform.projection` | `spans_to_atif` and `AtifProjection`: a conversation's GenAI spans as one ATIF trajectory. |
|
|
146
|
+
| `introspection_transform.messages` | `atif_to_messages` and `AtifConversionError`: a trajectory as the `ag_ui.core` messages a run opens with. |
|
|
147
|
+
| `introspection_transform.trajectory` | The ATIF models the projection writes, at `ATIF_SCHEMA_VERSION`. |
|
|
148
|
+
| `introspection_transform.genai_span` | `GenAiSpan` and `GenAiSpanList`, the span a conversation read returns. |
|
|
149
|
+
| `introspection_transform.genai` | The OTel GenAI message and part models. |
|
|
150
|
+
| `introspection_transform.annotations` | `AnnotationState`, the annotation a span read can carry. |
|
|
151
|
+
| `introspection_transform.trainer` | `train`, `sample` and the `TinkerAdapter` / `FireworksAdapter` behind the `tinker` / `fireworks` extras: LoRA SFT on `sft_row` rows, and sampling a base or trained model on them. |
|
|
152
|
+
| `introspection_transform.training` | `span_to_example`: one span as an `introspection.training/v1` example (OpenAI chat messages with `trainable` on each, `tools`, an optional `rejected` reply), and its `sft_row` and `dpo_pair` views, which the Fireworks and Tinker training toolchains read. |
|
|
153
|
+
|
|
154
|
+
`introspection-sdk` re-exports each of these from its old module
|
|
155
|
+
(`introspection_sdk.atif`, `introspection_sdk.atif_messages`,
|
|
156
|
+
`introspection_sdk.schemas.atif`, `.genai`, `.genai_span`), so code that
|
|
157
|
+
imports them from the SDK keeps working.
|
|
158
|
+
|
|
159
|
+
## Development
|
|
160
|
+
|
|
161
|
+
```bash
|
|
162
|
+
uv sync --all-extras
|
|
163
|
+
uv run ruff format --check . && uv run ruff check .
|
|
164
|
+
uv run ty check introspection_transform tests
|
|
165
|
+
uv run pytest tests/ --cov=introspection_transform
|
|
166
|
+
uv run deptry .
|
|
167
|
+
npx --yes jscpd@5.4.1
|
|
168
|
+
```
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# introspection-transform
|
|
2
|
+
|
|
3
|
+
GenAI spans to a [Harbor](https://github.com/laude-institute/harbor) ATIF
|
|
4
|
+
trajectory, and an ATIF trajectory back to the AG-UI messages that open a
|
|
5
|
+
run. It is the projection `introspection-sdk` uses, published on its own so
|
|
6
|
+
an eval adapter can read a conversation's spans without installing the SDK.
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
pip install introspection-transform
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
```python
|
|
13
|
+
from introspection_transform import (
|
|
14
|
+
GenAiSpanList,
|
|
15
|
+
atif_to_messages,
|
|
16
|
+
sft_row,
|
|
17
|
+
span_to_example,
|
|
18
|
+
spans_to_atif,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
spans = GenAiSpanList.model_validate_json(body).items
|
|
22
|
+
trajectory = spans_to_atif(spans, session_id="conv-1")
|
|
23
|
+
messages = atif_to_messages(trajectory, prompt="Continue the task")
|
|
24
|
+
|
|
25
|
+
# One annotated span as a training example; an item-detail read carries the whole history.
|
|
26
|
+
example = span_to_example(span, labels=["router-correct"])
|
|
27
|
+
row = sft_row(example) # {"messages": [...]} for Fireworks or Tinker SFT
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Training
|
|
31
|
+
|
|
32
|
+
`introspection_transform.trainer` runs LoRA SFT on `introspection.training/v1`
|
|
33
|
+
SFT rows on Fireworks or Tinker. Each provider is an optional extra; neither
|
|
34
|
+
pulls in `torch`:
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install "introspection-transform[tinker]" # tinker
|
|
38
|
+
pip install "introspection-transform[fireworks]" # fireworks-ai[training-sdk], transformers
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from transformers import AutoTokenizer
|
|
43
|
+
|
|
44
|
+
from introspection_transform import sft_row
|
|
45
|
+
from introspection_transform.trainer import (
|
|
46
|
+
FireworksAdapter,
|
|
47
|
+
TinkerAdapter,
|
|
48
|
+
generation_stop_tokens,
|
|
49
|
+
sample,
|
|
50
|
+
train,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
rows = [sft_row(example) for example in examples]
|
|
54
|
+
tokenizer = AutoTokenizer.from_pretrained("zai-org/GLM-5.3-Flash")
|
|
55
|
+
stops = generation_stop_tokens("zai-org/GLM-5.3-Flash")
|
|
56
|
+
adapter = FireworksAdapter(
|
|
57
|
+
output_model_id=f"router-{training_id}"
|
|
58
|
+
) # or TinkerAdapter()
|
|
59
|
+
run = train(
|
|
60
|
+
rows,
|
|
61
|
+
adapter, # the SDK reads FIREWORKS_API_KEY / TINKER_API_KEY
|
|
62
|
+
tokenizer,
|
|
63
|
+
base_model="accounts/fireworks/models/glm-5p3-flash", # Tinker: zai-org/GLM-5.3-Flash:peft:262144
|
|
64
|
+
training_id=training_id, # stamped on provider objects as introspection_training_id
|
|
65
|
+
stop_tokens=stops,
|
|
66
|
+
lora_rank=8,
|
|
67
|
+
epochs=1,
|
|
68
|
+
batch_size=16,
|
|
69
|
+
learning_rate=1e-4,
|
|
70
|
+
)
|
|
71
|
+
run.path # accounts/<account>/models/router-<id> on Fireworks; a tinker:// path on Tinker
|
|
72
|
+
|
|
73
|
+
predictions = sample(
|
|
74
|
+
holdout_rows,
|
|
75
|
+
adapter,
|
|
76
|
+
tokenizer,
|
|
77
|
+
base_model="accounts/fireworks/models/glm-5p3-flash",
|
|
78
|
+
model=run.path, # None samples the base model
|
|
79
|
+
stop_tokens=stops,
|
|
80
|
+
)
|
|
81
|
+
[(p.text, p.reference, p.clean) for p in predictions] # score them your way
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Each row is rendered with the base model's chat template: the tokens of the
|
|
85
|
+
trainable reply get weight 1, everything before it 0. With `stop_tokens` (the
|
|
86
|
+
model's generation `eos_token_id` list), the trained reply ends right after its
|
|
87
|
+
first stop token, so the model learns to stop where the server stops it. Chat
|
|
88
|
+
templates disagree there: Qwen's writes a newline after `<|im_end|>`, and GLM's
|
|
89
|
+
ends the reply with no stop token at all (the next turn's `<|user|>` ends it),
|
|
90
|
+
so without `stop_tokens` a GLM model never learns to stop. With them, rendering
|
|
91
|
+
matched the Fireworks and Tinker cookbooks' renderers token for token on Muse
|
|
92
|
+
Glimmer 30B, GLM 5.3 Flash, Inkling 2 Mini and Qwen3-8B.
|
|
93
|
+
|
|
94
|
+
The adapter then opens a LoRA training client, sends each batch as
|
|
95
|
+
`forward_backward(datums, "cross_entropy")` and `optim_step(AdamParams(learning_rate))`,
|
|
96
|
+
saves the weights for sampling and closes the session (deleting it on
|
|
97
|
+
Fireworks). A Fireworks session's checkpoints are unreachable once it is
|
|
98
|
+
deleted, so with `output_model_id` the adapter promotes the final weights to a
|
|
99
|
+
model first, and the run returns that model. `TrainingAdapter` is the protocol
|
|
100
|
+
each provider implements.
|
|
101
|
+
|
|
102
|
+
`sample` samples a base or trained model on the same rows, with no deployment,
|
|
103
|
+
through `SamplingAdapter`, which both adapters also implement: Tinker samples a
|
|
104
|
+
`tinker://` path directly; Fireworks loads a promoted adapter into a LoRA session
|
|
105
|
+
and samples a snapshot of it. Replies are cut at the first stop token, and a
|
|
106
|
+
leading reasoning block is dropped; pass `parse` for a model that needs more.
|
|
107
|
+
|
|
108
|
+
[tinker-cookbook](https://github.com/thinking-machines-lab/tinker-cookbook)
|
|
109
|
+
was the reference design (its supervised loop and its per-message
|
|
110
|
+
`trainable` weights). Neither it nor `tml-renderers`, its renderer layer, is a
|
|
111
|
+
dependency, since both import `torch`. Not mapped: DPO and RL (both need a
|
|
112
|
+
custom loss computed client-side in `torch`), and checkpoint and resume.
|
|
113
|
+
|
|
114
|
+
## Layout
|
|
115
|
+
|
|
116
|
+
| Module | Holds |
|
|
117
|
+
| --- | --- |
|
|
118
|
+
| `introspection_transform.projection` | `spans_to_atif` and `AtifProjection`: a conversation's GenAI spans as one ATIF trajectory. |
|
|
119
|
+
| `introspection_transform.messages` | `atif_to_messages` and `AtifConversionError`: a trajectory as the `ag_ui.core` messages a run opens with. |
|
|
120
|
+
| `introspection_transform.trajectory` | The ATIF models the projection writes, at `ATIF_SCHEMA_VERSION`. |
|
|
121
|
+
| `introspection_transform.genai_span` | `GenAiSpan` and `GenAiSpanList`, the span a conversation read returns. |
|
|
122
|
+
| `introspection_transform.genai` | The OTel GenAI message and part models. |
|
|
123
|
+
| `introspection_transform.annotations` | `AnnotationState`, the annotation a span read can carry. |
|
|
124
|
+
| `introspection_transform.trainer` | `train`, `sample` and the `TinkerAdapter` / `FireworksAdapter` behind the `tinker` / `fireworks` extras: LoRA SFT on `sft_row` rows, and sampling a base or trained model on them. |
|
|
125
|
+
| `introspection_transform.training` | `span_to_example`: one span as an `introspection.training/v1` example (OpenAI chat messages with `trainable` on each, `tools`, an optional `rejected` reply), and its `sft_row` and `dpo_pair` views, which the Fireworks and Tinker training toolchains read. |
|
|
126
|
+
|
|
127
|
+
`introspection-sdk` re-exports each of these from its old module
|
|
128
|
+
(`introspection_sdk.atif`, `introspection_sdk.atif_messages`,
|
|
129
|
+
`introspection_sdk.schemas.atif`, `.genai`, `.genai_span`), so code that
|
|
130
|
+
imports them from the SDK keeps working.
|
|
131
|
+
|
|
132
|
+
## Development
|
|
133
|
+
|
|
134
|
+
```bash
|
|
135
|
+
uv sync --all-extras
|
|
136
|
+
uv run ruff format --check . && uv run ruff check .
|
|
137
|
+
uv run ty check introspection_transform tests
|
|
138
|
+
uv run pytest tests/ --cov=introspection_transform
|
|
139
|
+
uv run deptry .
|
|
140
|
+
npx --yes jscpd@5.4.1
|
|
141
|
+
```
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""LoRA SFT on ``introspection.training/v1`` rows, on Fireworks or Tinker.
|
|
2
|
+
|
|
3
|
+
:func:`train` renders each :func:`~introspection_transform.training.sft_row`
|
|
4
|
+
with the base model's chat template and drives one :class:`TrainingAdapter`:
|
|
5
|
+
:class:`FireworksAdapter` behind the ``fireworks`` extra or
|
|
6
|
+
:class:`TinkerAdapter` behind the ``tinker`` extra. :func:`sample` samples a
|
|
7
|
+
base or trained model on the same rows through the same adapters, with no
|
|
8
|
+
deployment. Importing this package needs neither extra; an adapter imports
|
|
9
|
+
its SDK when it is built.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from introspection_transform.trainer.adapter import (
|
|
13
|
+
METADATA_KEY,
|
|
14
|
+
RenderedExample,
|
|
15
|
+
TrainingAdapter,
|
|
16
|
+
)
|
|
17
|
+
from introspection_transform.trainer.extras import ProviderExtraMissing
|
|
18
|
+
from introspection_transform.trainer.fireworks import (
|
|
19
|
+
FireworksAdapter,
|
|
20
|
+
PromotionError,
|
|
21
|
+
)
|
|
22
|
+
from introspection_transform.trainer.loop import StepReport, TrainingRun, train
|
|
23
|
+
from introspection_transform.trainer.render import (
|
|
24
|
+
ChatTokenizer,
|
|
25
|
+
RenderError,
|
|
26
|
+
chat_message,
|
|
27
|
+
generation_stop_tokens,
|
|
28
|
+
render_example,
|
|
29
|
+
)
|
|
30
|
+
from introspection_transform.trainer.sample import (
|
|
31
|
+
Prediction,
|
|
32
|
+
SamplingAdapter,
|
|
33
|
+
prompt_tokens,
|
|
34
|
+
reply_text,
|
|
35
|
+
sample,
|
|
36
|
+
)
|
|
37
|
+
from introspection_transform.trainer.tinker import TinkerAdapter
|
|
38
|
+
|
|
39
|
+
__all__ = [
|
|
40
|
+
"METADATA_KEY",
|
|
41
|
+
"ChatTokenizer",
|
|
42
|
+
"FireworksAdapter",
|
|
43
|
+
"Prediction",
|
|
44
|
+
"PromotionError",
|
|
45
|
+
"ProviderExtraMissing",
|
|
46
|
+
"RenderError",
|
|
47
|
+
"RenderedExample",
|
|
48
|
+
"SamplingAdapter",
|
|
49
|
+
"StepReport",
|
|
50
|
+
"TinkerAdapter",
|
|
51
|
+
"TrainingAdapter",
|
|
52
|
+
"TrainingRun",
|
|
53
|
+
"chat_message",
|
|
54
|
+
"generation_stop_tokens",
|
|
55
|
+
"prompt_tokens",
|
|
56
|
+
"render_example",
|
|
57
|
+
"reply_text",
|
|
58
|
+
"sample",
|
|
59
|
+
"train",
|
|
60
|
+
]
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""The interface a provider implements, and the rendered example it trains on."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Protocol, TypeVar
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel, ConfigDict, model_validator
|
|
8
|
+
|
|
9
|
+
__all__ = ["METADATA_KEY", "RenderedExample", "Session", "TrainingAdapter"]
|
|
10
|
+
|
|
11
|
+
METADATA_KEY = "introspection_training_id"
|
|
12
|
+
|
|
13
|
+
Session = TypeVar("Session")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class RenderedExample(BaseModel):
|
|
17
|
+
"""One example as tokens, each weighted 1 when it is trained on, else 0."""
|
|
18
|
+
|
|
19
|
+
model_config = ConfigDict(frozen=True)
|
|
20
|
+
|
|
21
|
+
tokens: list[int]
|
|
22
|
+
weights: list[float]
|
|
23
|
+
|
|
24
|
+
@model_validator(mode="after")
|
|
25
|
+
def _aligned(self) -> RenderedExample:
|
|
26
|
+
if len(self.tokens) != len(self.weights):
|
|
27
|
+
raise ValueError("tokens and weights differ in length")
|
|
28
|
+
if len(self.tokens) < 2:
|
|
29
|
+
raise ValueError("an example needs at least two tokens")
|
|
30
|
+
return self
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class TrainingAdapter(Protocol[Session]):
|
|
34
|
+
"""One provider's LoRA training calls, as :func:`train` makes them.
|
|
35
|
+
|
|
36
|
+
Every provider object that takes metadata carries
|
|
37
|
+
``{"introspection_training_id": training_id}``.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def open(self, base_model: str, rank: int, training_id: str) -> Session:
|
|
41
|
+
"""A new LoRA training client on ``base_model``."""
|
|
42
|
+
...
|
|
43
|
+
|
|
44
|
+
def step(
|
|
45
|
+
self,
|
|
46
|
+
session: Session,
|
|
47
|
+
batch: list[RenderedExample],
|
|
48
|
+
learning_rate: float,
|
|
49
|
+
) -> dict[str, float]:
|
|
50
|
+
"""One cross-entropy forward/backward and one Adam step; its metrics."""
|
|
51
|
+
...
|
|
52
|
+
|
|
53
|
+
def save(self, session: Session, name: str) -> str:
|
|
54
|
+
"""Saves the weights for sampling; returns their path."""
|
|
55
|
+
...
|
|
56
|
+
|
|
57
|
+
def close(self, session: Session, ok: bool) -> None:
|
|
58
|
+
"""Ends the session, as succeeded or failed."""
|
|
59
|
+
...
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Imports a provider's SDK, naming the extra that installs it when it is missing."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib
|
|
6
|
+
from types import ModuleType
|
|
7
|
+
|
|
8
|
+
__all__ = ["ProviderExtraMissing", "require"]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ProviderExtraMissing(ImportError):
|
|
12
|
+
"""The provider's SDK is not installed; its extra installs it."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def require(module: str, extra: str) -> ModuleType:
|
|
16
|
+
"""``module``, imported.
|
|
17
|
+
|
|
18
|
+
Raises:
|
|
19
|
+
ProviderExtraMissing: ``module``'s package is not installed.
|
|
20
|
+
"""
|
|
21
|
+
try:
|
|
22
|
+
return importlib.import_module(module)
|
|
23
|
+
except ModuleNotFoundError as error:
|
|
24
|
+
if (error.name or "").split(".")[0] != module.split(".")[0]:
|
|
25
|
+
raise
|
|
26
|
+
raise ProviderExtraMissing(
|
|
27
|
+
f"{module} is not installed; "
|
|
28
|
+
f'pip install "introspection-transform[{extra}]"',
|
|
29
|
+
name=module,
|
|
30
|
+
) from error
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
"""The Fireworks adapter (``pip install "introspection-transform[fireworks]"``).
|
|
2
|
+
|
|
3
|
+
It trains on Fireworks' serverless training surface. The service and the
|
|
4
|
+
training run carry the training id in ``user_metadata``; Fireworks sampler
|
|
5
|
+
weights take no metadata and are found through their session. The SDK reads
|
|
6
|
+
``FIREWORKS_API_KEY`` itself. ``close`` deletes the training session, which
|
|
7
|
+
frees its concurrent-run slot.
|
|
8
|
+
|
|
9
|
+
A session's checkpoints cannot be reached once the session is deleted, so
|
|
10
|
+
with ``output_model_id`` :meth:`FireworksAdapter.save` promotes the saved
|
|
11
|
+
weights to ``accounts/<account>/models/<output_model_id>`` first, and that
|
|
12
|
+
model is what the run returns. Without one, the run returns the session-only
|
|
13
|
+
sampler path, which is usable only until :meth:`FireworksAdapter.close`.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import os
|
|
19
|
+
from collections.abc import Sequence
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from introspection_transform.trainer.adapter import (
|
|
24
|
+
METADATA_KEY,
|
|
25
|
+
RenderedExample,
|
|
26
|
+
)
|
|
27
|
+
from introspection_transform.trainer.extras import require
|
|
28
|
+
from introspection_transform.trainer.lora import Reply, lora_step
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"SERVERLESS_URL",
|
|
32
|
+
"FireworksAdapter",
|
|
33
|
+
"FireworksSampler",
|
|
34
|
+
"FireworksSession",
|
|
35
|
+
"PromotionError",
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
SERVERLESS_URL = "https://api.fireworks.ai/training/v1/serverless"
|
|
39
|
+
CONTROL_PLANE_URL = "https://api.fireworks.ai"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class PromotionError(RuntimeError):
|
|
43
|
+
"""The saved weights could not be promoted to a model."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class FireworksSession:
|
|
48
|
+
service: Any
|
|
49
|
+
client: Any
|
|
50
|
+
base_model: str
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True)
|
|
54
|
+
class FireworksSampler:
|
|
55
|
+
session: FireworksSession
|
|
56
|
+
client: Any
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class FireworksAdapter:
|
|
60
|
+
"""Trains a LoRA adapter on Fireworks serverless training.
|
|
61
|
+
|
|
62
|
+
``service`` is a ``FiretitanServiceClient``; without one, :meth:`open`
|
|
63
|
+
builds one on ``base_url``. ``output_model_id`` (1-63 lowercase letters,
|
|
64
|
+
digits or hyphens) promotes the final weights to a model; ``platform``
|
|
65
|
+
is the ``FireworksClient`` that promotes them, built from
|
|
66
|
+
``FIREWORKS_API_KEY`` when not given.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
def __init__(
|
|
70
|
+
self,
|
|
71
|
+
service: Any = None,
|
|
72
|
+
base_url: str = SERVERLESS_URL,
|
|
73
|
+
*,
|
|
74
|
+
output_model_id: str | None = None,
|
|
75
|
+
platform: Any = None,
|
|
76
|
+
) -> None:
|
|
77
|
+
self._sdk = require("fireworks.training.sdk", "fireworks")
|
|
78
|
+
self._service = service
|
|
79
|
+
self._base_url = base_url
|
|
80
|
+
self._output_model_id = output_model_id
|
|
81
|
+
self._platform = platform
|
|
82
|
+
|
|
83
|
+
def open(
|
|
84
|
+
self, base_model: str, rank: int, training_id: str
|
|
85
|
+
) -> FireworksSession:
|
|
86
|
+
metadata = {METADATA_KEY: training_id}
|
|
87
|
+
service = self.service(training_id)
|
|
88
|
+
client = service.create_lora_training_client(
|
|
89
|
+
base_model=base_model, rank=rank, user_metadata=metadata
|
|
90
|
+
)
|
|
91
|
+
return FireworksSession(service, client, base_model)
|
|
92
|
+
|
|
93
|
+
def service(self, training_id: str) -> Any:
|
|
94
|
+
"""The injected service, or a new one tagged with ``training_id``.
|
|
95
|
+
|
|
96
|
+
Building one connects to Fireworks.
|
|
97
|
+
"""
|
|
98
|
+
return self._service or self._sdk.FiretitanServiceClient(
|
|
99
|
+
base_url=self._base_url,
|
|
100
|
+
user_metadata={METADATA_KEY: training_id},
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
def step(
|
|
104
|
+
self,
|
|
105
|
+
session: FireworksSession,
|
|
106
|
+
batch: list[RenderedExample],
|
|
107
|
+
learning_rate: float,
|
|
108
|
+
) -> dict[str, float]:
|
|
109
|
+
return lora_step(self._sdk, session.client, batch, learning_rate)
|
|
110
|
+
|
|
111
|
+
def save(self, session: FireworksSession, name: str) -> str:
|
|
112
|
+
"""Saves the weights for sampling; with ``output_model_id``, promotes
|
|
113
|
+
them and returns the model's name.
|
|
114
|
+
|
|
115
|
+
Raises:
|
|
116
|
+
PromotionError: the session lists no promotable checkpoint named
|
|
117
|
+
``name``.
|
|
118
|
+
"""
|
|
119
|
+
path = session.client.save_weights_for_sampler(name).result().path
|
|
120
|
+
if not self._output_model_id:
|
|
121
|
+
return path
|
|
122
|
+
platform = self._platform or self._sdk.FireworksClient(
|
|
123
|
+
api_key=os.environ["FIREWORKS_API_KEY"],
|
|
124
|
+
base_url=os.environ.get("FIREWORKS_BASE_URL", CONTROL_PLANE_URL),
|
|
125
|
+
)
|
|
126
|
+
session_name = session.service.training_session_name
|
|
127
|
+
saved = [
|
|
128
|
+
checkpoint
|
|
129
|
+
for checkpoint in platform.list_training_session_checkpoints(
|
|
130
|
+
session_name
|
|
131
|
+
)
|
|
132
|
+
if checkpoint.get("promotable")
|
|
133
|
+
and name
|
|
134
|
+
in (checkpoint.get("checkpointName") or checkpoint["name"])
|
|
135
|
+
]
|
|
136
|
+
if not saved:
|
|
137
|
+
raise PromotionError(
|
|
138
|
+
f"{session_name} lists no promotable checkpoint named {name!r}"
|
|
139
|
+
)
|
|
140
|
+
latest = max(
|
|
141
|
+
saved, key=lambda checkpoint: checkpoint.get("createTime", "")
|
|
142
|
+
)
|
|
143
|
+
model = platform.promote_session_checkpoint(
|
|
144
|
+
name=latest["name"],
|
|
145
|
+
output_model_id=self._output_model_id,
|
|
146
|
+
base_model=session.base_model,
|
|
147
|
+
)
|
|
148
|
+
account = session_name.split("/")[1]
|
|
149
|
+
return model.get("name") or (
|
|
150
|
+
f"accounts/{account}/models/{self._output_model_id}"
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
def close(self, session: FireworksSession, ok: bool) -> None:
|
|
154
|
+
try:
|
|
155
|
+
session.service.delete_training_session()
|
|
156
|
+
finally:
|
|
157
|
+
session.service.close()
|
|
158
|
+
|
|
159
|
+
def open_sampler(
|
|
160
|
+
self,
|
|
161
|
+
base_model: str,
|
|
162
|
+
model: str | None,
|
|
163
|
+
rank: int,
|
|
164
|
+
training_id: str,
|
|
165
|
+
tokenizer: Any = None,
|
|
166
|
+
) -> FireworksSampler:
|
|
167
|
+
"""A LoRA session on ``base_model`` with ``model`` (a promoted
|
|
168
|
+
``accounts/<a>/models/<m>``) loaded into it, or untrained for the base
|
|
169
|
+
model, and a sampler over a snapshot of its weights. ``rank`` must be
|
|
170
|
+
the adapter's. The sampler needs ``tokenizer`` to send integer stop
|
|
171
|
+
tokens: Fireworks' completions API takes stop strings."""
|
|
172
|
+
session = self.open(base_model, rank, training_id)
|
|
173
|
+
try:
|
|
174
|
+
if model:
|
|
175
|
+
session.client.load_adapter(model).result()
|
|
176
|
+
path = (
|
|
177
|
+
session.client.save_weights_for_sampler("sample").result().path
|
|
178
|
+
)
|
|
179
|
+
client = session.service.create_sampling_client(
|
|
180
|
+
model_path=path, tokenizer=tokenizer
|
|
181
|
+
)
|
|
182
|
+
except BaseException:
|
|
183
|
+
self.close(session, False)
|
|
184
|
+
raise
|
|
185
|
+
return FireworksSampler(session, client)
|
|
186
|
+
|
|
187
|
+
def sample(
|
|
188
|
+
self,
|
|
189
|
+
sampler: FireworksSampler,
|
|
190
|
+
prompt: list[int],
|
|
191
|
+
max_tokens: int,
|
|
192
|
+
stop_tokens: Sequence[int],
|
|
193
|
+
) -> Reply:
|
|
194
|
+
return Reply(
|
|
195
|
+
sampler.client.sample(
|
|
196
|
+
prompt=self._sdk.ModelInput.from_ints(prompt),
|
|
197
|
+
num_samples=1,
|
|
198
|
+
sampling_params=self._sdk.SamplingParams(
|
|
199
|
+
max_tokens=max_tokens,
|
|
200
|
+
temperature=0.0,
|
|
201
|
+
stop=list(stop_tokens),
|
|
202
|
+
),
|
|
203
|
+
)
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
def close_sampler(self, sampler: FireworksSampler) -> None:
|
|
207
|
+
try:
|
|
208
|
+
getattr(sampler.client, "close", lambda: None)()
|
|
209
|
+
finally:
|
|
210
|
+
self.close(sampler.session, True)
|