mo-trace 0.1.0__tar.gz → 0.3.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.
- {mo_trace-0.1.0 → mo_trace-0.3.0}/PKG-INFO +55 -26
- {mo_trace-0.1.0 → mo_trace-0.3.0}/README.md +54 -25
- {mo_trace-0.1.0/matrace → mo_trace-0.3.0/motrace}/__init__.py +1 -1
- mo_trace-0.3.0/motrace/cli.py +199 -0
- {mo_trace-0.1.0/matrace → mo_trace-0.3.0/motrace}/convert.py +10 -10
- {mo_trace-0.1.0/matrace → mo_trace-0.3.0/motrace}/core.py +9 -8
- mo_trace-0.3.0/motrace/trajectory.py +318 -0
- {mo_trace-0.1.0 → mo_trace-0.3.0}/pyproject.toml +11 -8
- {mo_trace-0.1.0 → mo_trace-0.3.0}/tests/conftest.py +4 -4
- {mo_trace-0.1.0 → mo_trace-0.3.0}/tests/test_convert.py +9 -9
- mo_trace-0.1.0/tests/test_matrace.py → mo_trace-0.3.0/tests/test_motrace.py +27 -27
- mo_trace-0.3.0/tests/test_trajectory.py +268 -0
- mo_trace-0.1.0/matrace/cli.py +0 -151
- {mo_trace-0.1.0 → mo_trace-0.3.0}/.gitignore +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: mo-trace
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: nbdev-style literate programming for marimo notebooks
|
|
5
5
|
License-Expression: Apache-2.0
|
|
6
6
|
Requires-Python: >=3.11
|
|
@@ -11,30 +11,30 @@ Requires-Dist: tinker>=0.39; extra == 'tinker'
|
|
|
11
11
|
Requires-Dist: tml-renderers>=0.4; extra == 'tinker'
|
|
12
12
|
Description-Content-Type: text/markdown
|
|
13
13
|
|
|
14
|
-
#
|
|
14
|
+
# motrace
|
|
15
15
|
|
|
16
16
|
A minimal [nbdev](https://nbdev.fast.ai) for [marimo](https://marimo.io) notebooks. Write the code, its docs and its tests
|
|
17
|
-
in a marimo notebook.
|
|
17
|
+
in a marimo notebook. motrace turns the exported cells into a normal Python package and keeps the two in sync.
|
|
18
18
|
|
|
19
|
-
|
|
|
19
|
+
| motrace | nbdev equivalent | does |
|
|
20
20
|
|---|---|---|
|
|
21
|
-
| `
|
|
22
|
-
| `
|
|
23
|
-
| `
|
|
24
|
-
| `
|
|
21
|
+
| `motrace-export` | `nbdev-export` | notebook cells → modules in `lib_path` |
|
|
22
|
+
| `motrace-export --update` | `nbdev-update` | edits made in modules → back into the notebook cells |
|
|
23
|
+
| `motrace-prepare` | `nbdev-prepare` | export, run every notebook's tests in parallel, then clean |
|
|
24
|
+
| `motrace-clean` | `nbdev-clean` | normalize notebooks so diffs and merges stay clean |
|
|
25
25
|
|
|
26
|
-
Run `
|
|
26
|
+
Run `motrace --help` for a guide to using it in a notebook and the CLI, and to organizing notebooks.
|
|
27
27
|
|
|
28
28
|
## Install
|
|
29
29
|
|
|
30
30
|
```sh
|
|
31
|
-
pip install mo-trace # or: uv add --dev mo-trace (imported as `
|
|
31
|
+
pip install mo-trace # or: uv add --dev mo-trace (imported as `motrace`)
|
|
32
32
|
```
|
|
33
33
|
|
|
34
|
-
Add a `[tool.
|
|
34
|
+
Add a `[tool.motrace]` table to your project's `pyproject.toml`:
|
|
35
35
|
|
|
36
36
|
```toml
|
|
37
|
-
[tool.
|
|
37
|
+
[tool.motrace]
|
|
38
38
|
lib_path = "mypkg" # default: [project].name, with - replaced by _
|
|
39
39
|
nbs_path = "jobs" # default: jobs
|
|
40
40
|
```
|
|
@@ -67,13 +67,13 @@ def _(cosine):
|
|
|
67
67
|
|
|
68
68
|
@app.cell
|
|
69
69
|
def _():
|
|
70
|
-
#| eval: false # skipped by
|
|
70
|
+
#| eval: false # skipped by motrace-prepare
|
|
71
71
|
slow_benchmark()
|
|
72
72
|
return
|
|
73
73
|
```
|
|
74
74
|
|
|
75
75
|
Supported directives: `default_exp`, `export [module]`, `exporti [module]` (exported but left out of `__all__`), `exports`, and
|
|
76
|
-
`eval: false`.
|
|
76
|
+
`eval: false`. motrace also follows nbdev for these details:
|
|
77
77
|
- `__all__` is built from the public names in exported cells, plus any names listed in `_all_`.
|
|
78
78
|
- `from mypkg.x import y` becomes a relative import in the generated module, and becomes absolute again when synced back.
|
|
79
79
|
- The module docstring comes from the `> summary` line under the notebook's `# Title` markdown cell.
|
|
@@ -82,20 +82,20 @@ Supported directives: `default_exp`, `export [module]`, `exporti [module]` (expo
|
|
|
82
82
|
## Differences from nbdev (by design or necessity)
|
|
83
83
|
|
|
84
84
|
- **Imports across modules are generated for you.** Marimo forbids defining a name in more than one cell, so a cell exported
|
|
85
|
-
to `metrics/distance.py` cannot re-import `norm` the way an nbdev notebook would.
|
|
85
|
+
to `metrics/distance.py` cannot re-import `norm` the way an nbdev notebook would. motrace reads marimo's dataflow graph
|
|
86
86
|
instead. Each module gets an `# %% auto #1` block that imports what its cells use but don't define: import statements
|
|
87
87
|
from other cells, such as the setup cell, are copied, and names exported to other modules are imported from those modules.
|
|
88
88
|
- **`#| export other_module` can create a new file.** nbdev requires the target module to already exist.
|
|
89
89
|
- **Cells are identified by position.** Marimo files have no stable cell ids, so the `# %% ../jobs/nb.py #3` markers use the
|
|
90
90
|
cell's position. `--update` refuses to write if that cell is no longer an exported cell of the same module. Run
|
|
91
|
-
`
|
|
91
|
+
`motrace-export` again after reordering cells.
|
|
92
92
|
- **Tests run the notebook as a script**, `python nb.py`, one process per notebook, in the notebook's directory, with
|
|
93
93
|
`IN_TEST=1` set. Cells execute in marimo's dependency order.
|
|
94
|
-
- **Clean has less to remove.** Marimo files contain no outputs or execution counts. `
|
|
94
|
+
- **Clean has less to remove.** Marimo files contain no outputs or execution counts. `motrace-clean` rewrites each notebook
|
|
95
95
|
in marimo's own canonical format and strips trailing whitespace. It keeps `__generated_with` unchanged, so upgrading marimo
|
|
96
|
-
doesn't change every notebook. `
|
|
97
|
-
- **Not included:** docs, README generation, `_modidx.py`, `llms.txt` and Quarto. `
|
|
98
|
-
- **Private marimo APIs.**
|
|
96
|
+
doesn't change every notebook. `motrace-clean --stdin` works as a git filter.
|
|
97
|
+
- **Not included:** docs, README generation, `_modidx.py`, `llms.txt` and Quarto. `motrace-prepare` is export + test + clean.
|
|
98
|
+
- **Private marimo APIs.** motrace uses marimo's internal parser and code generator, so it pins `marimo>=0.25,<0.26`.
|
|
99
99
|
|
|
100
100
|
## Example: a tiny language model from one notebook
|
|
101
101
|
|
|
@@ -105,24 +105,53 @@ Each cell picks its target file, giving `tinylm/{data,tokenizer,model,train}.py`
|
|
|
105
105
|
|
|
106
106
|
```sh
|
|
107
107
|
cd examples/tinylm
|
|
108
|
-
|
|
108
|
+
motrace-prepare # export, test, clean -> Success.
|
|
109
109
|
pip install . # or: pip install -e .
|
|
110
110
|
tinylm-train # {'train_ppl': 11.14, 'val_ppl': 11.58} + sampled names
|
|
111
111
|
marimo edit jobs/tinylm.py # keep developing in the notebook
|
|
112
112
|
```
|
|
113
113
|
|
|
114
|
-
## Training data: notebook
|
|
114
|
+
## Training data: notebook ↔ agent trajectory (`motrace-convert`)
|
|
115
|
+
|
|
116
|
+
```sh
|
|
117
|
+
motrace-convert # every notebook in nbs_path -> traces/<notebook>.jsonl
|
|
118
|
+
motrace-convert jobs/00_core.py -o all.jsonl # one notebook (or a directory) into one JSONL file
|
|
119
|
+
motrace-convert traces/00_core.jsonl -o nbs/ # back: trajectory -> nbs/00_core.py
|
|
120
|
+
motrace-convert t.json --to-notebook -o x.py # force the reverse direction for any file name
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
`motrace-convert` turns each notebook into a trajectory of an agent writing it one cell at a time:
|
|
124
|
+
|
|
125
|
+
- a **narration cell** (a hidden cell holding only `mo.md(r"""...""")`) becomes the text of one assistant message;
|
|
126
|
+
- every other cell becomes a `run_cell` tool call (`code`, plus `name` for the setup cell or a reusable function, and
|
|
127
|
+
`hide_code`) on the message that carries the narration before it;
|
|
128
|
+
- the cell's output, recorded in the notebook's marimo session (`__marimo__/session/<name>.json`), becomes the tool
|
|
129
|
+
result. Outputs are matched by code hash, so a stale output is never attached to edited code; those cells get
|
|
130
|
+
`(output not recorded)`, and `metadata.outputs_recorded` counts the rest.
|
|
131
|
+
|
|
132
|
+
Each row is `{"messages", "tools", "metadata"}`: OpenAI-style chat messages and tool calls (tinker-cookbook's
|
|
133
|
+
`ToolCall` shape), tool specs as `{name, description, parameters}`, and metadata with the notebook path, app config
|
|
134
|
+
and file header (PEP 723 block, docstring). Converting a row back gives the notebook exactly as `motrace-clean` writes
|
|
135
|
+
it. Only `hide_code` survives as a cell option, so cells that set `disabled`, `column` etc. are rejected.
|
|
136
|
+
`--instruction FILE` sets the user turn (default: built from the first heading), `--session` picks another session
|
|
137
|
+
file, and `--max-output-chars` truncates tool results. In Python: `motrace.trajectory.to_trajectory(nb)`,
|
|
138
|
+
`to_notebook(row)`, and `training_messages(row, renderer)` for a tinker-cookbook renderer.
|
|
139
|
+
|
|
140
|
+
To keep trajectories next to the code, set `traces_path = "traces"` in `[tool.motrace]`: `motrace-prepare` then
|
|
141
|
+
converts every notebook before exporting.
|
|
142
|
+
|
|
143
|
+
### Pi rollout → Tinker (`motrace-convert --pi`)
|
|
115
144
|
|
|
116
145
|
```sh
|
|
117
146
|
pip install "mo-trace[tinker]"
|
|
118
|
-
|
|
147
|
+
motrace-convert examples/tinylm/jobs/tinylm.py --pi -o traces
|
|
119
148
|
python examples/tinker_train.py traces # SFT, then on-policy distillation, on Tinker
|
|
120
149
|
```
|
|
121
150
|
|
|
122
|
-
`
|
|
151
|
+
`motrace-convert --pi` replays a notebook as a session of the [Pi](https://github.com/earendil-works/pi-mono) coding agent
|
|
123
152
|
building it. The replay uses Pi 1.5.2's system prompt, its `read`/`bash`/`edit`/`write` tool schemas and its result
|
|
124
153
|
strings. The agent explores the project, writes the first cells, then edits in each exported cell with its tests, in
|
|
125
|
-
marimo dependency order. It runs `
|
|
154
|
+
marimo dependency order. It runs `motrace-prepare` after every step and finally checks that the package imports. Every tool
|
|
126
155
|
call runs for real in a scratch copy of the project, so tool results are real output. A notebook whose tests fail is
|
|
127
156
|
rejected. The output files are:
|
|
128
157
|
|
|
@@ -133,7 +162,7 @@ rejected. The output files are:
|
|
|
133
162
|
| `sft.jsonl` | a Tinker `Datum` (`model_input`, `target_tokens`, 0/1 `weights`) of the whole trajectory, rendered with Inkling 2 Small's renderer. Only assistant tokens carry loss: reasoning, text, tool calls and end-of-turn |
|
|
134
163
|
| `opd_prompts.jsonl` | one starting state per assistant turn for on-policy distillation. Each has `prompt_tokens` (a token prefix of the trajectory), `teacher_prompt_tokens`, the reference turn, and the workspace files at that point |
|
|
135
164
|
|
|
136
|
-
Load the data with `
|
|
165
|
+
Load the data with `motrace.convert.load_sft()`. `motrace.convert.opd_datum()` builds the `importance_sampling` datum,
|
|
137
166
|
with advantage = teacher logprob − student logprob for each sampled token.
|
|
138
167
|
|
|
139
168
|
Notes:
|
|
@@ -1,27 +1,27 @@
|
|
|
1
|
-
#
|
|
1
|
+
# motrace
|
|
2
2
|
|
|
3
3
|
A minimal [nbdev](https://nbdev.fast.ai) for [marimo](https://marimo.io) notebooks. Write the code, its docs and its tests
|
|
4
|
-
in a marimo notebook.
|
|
4
|
+
in a marimo notebook. motrace turns the exported cells into a normal Python package and keeps the two in sync.
|
|
5
5
|
|
|
6
|
-
|
|
|
6
|
+
| motrace | nbdev equivalent | does |
|
|
7
7
|
|---|---|---|
|
|
8
|
-
| `
|
|
9
|
-
| `
|
|
10
|
-
| `
|
|
11
|
-
| `
|
|
8
|
+
| `motrace-export` | `nbdev-export` | notebook cells → modules in `lib_path` |
|
|
9
|
+
| `motrace-export --update` | `nbdev-update` | edits made in modules → back into the notebook cells |
|
|
10
|
+
| `motrace-prepare` | `nbdev-prepare` | export, run every notebook's tests in parallel, then clean |
|
|
11
|
+
| `motrace-clean` | `nbdev-clean` | normalize notebooks so diffs and merges stay clean |
|
|
12
12
|
|
|
13
|
-
Run `
|
|
13
|
+
Run `motrace --help` for a guide to using it in a notebook and the CLI, and to organizing notebooks.
|
|
14
14
|
|
|
15
15
|
## Install
|
|
16
16
|
|
|
17
17
|
```sh
|
|
18
|
-
pip install mo-trace # or: uv add --dev mo-trace (imported as `
|
|
18
|
+
pip install mo-trace # or: uv add --dev mo-trace (imported as `motrace`)
|
|
19
19
|
```
|
|
20
20
|
|
|
21
|
-
Add a `[tool.
|
|
21
|
+
Add a `[tool.motrace]` table to your project's `pyproject.toml`:
|
|
22
22
|
|
|
23
23
|
```toml
|
|
24
|
-
[tool.
|
|
24
|
+
[tool.motrace]
|
|
25
25
|
lib_path = "mypkg" # default: [project].name, with - replaced by _
|
|
26
26
|
nbs_path = "jobs" # default: jobs
|
|
27
27
|
```
|
|
@@ -54,13 +54,13 @@ def _(cosine):
|
|
|
54
54
|
|
|
55
55
|
@app.cell
|
|
56
56
|
def _():
|
|
57
|
-
#| eval: false # skipped by
|
|
57
|
+
#| eval: false # skipped by motrace-prepare
|
|
58
58
|
slow_benchmark()
|
|
59
59
|
return
|
|
60
60
|
```
|
|
61
61
|
|
|
62
62
|
Supported directives: `default_exp`, `export [module]`, `exporti [module]` (exported but left out of `__all__`), `exports`, and
|
|
63
|
-
`eval: false`.
|
|
63
|
+
`eval: false`. motrace also follows nbdev for these details:
|
|
64
64
|
- `__all__` is built from the public names in exported cells, plus any names listed in `_all_`.
|
|
65
65
|
- `from mypkg.x import y` becomes a relative import in the generated module, and becomes absolute again when synced back.
|
|
66
66
|
- The module docstring comes from the `> summary` line under the notebook's `# Title` markdown cell.
|
|
@@ -69,20 +69,20 @@ Supported directives: `default_exp`, `export [module]`, `exporti [module]` (expo
|
|
|
69
69
|
## Differences from nbdev (by design or necessity)
|
|
70
70
|
|
|
71
71
|
- **Imports across modules are generated for you.** Marimo forbids defining a name in more than one cell, so a cell exported
|
|
72
|
-
to `metrics/distance.py` cannot re-import `norm` the way an nbdev notebook would.
|
|
72
|
+
to `metrics/distance.py` cannot re-import `norm` the way an nbdev notebook would. motrace reads marimo's dataflow graph
|
|
73
73
|
instead. Each module gets an `# %% auto #1` block that imports what its cells use but don't define: import statements
|
|
74
74
|
from other cells, such as the setup cell, are copied, and names exported to other modules are imported from those modules.
|
|
75
75
|
- **`#| export other_module` can create a new file.** nbdev requires the target module to already exist.
|
|
76
76
|
- **Cells are identified by position.** Marimo files have no stable cell ids, so the `# %% ../jobs/nb.py #3` markers use the
|
|
77
77
|
cell's position. `--update` refuses to write if that cell is no longer an exported cell of the same module. Run
|
|
78
|
-
`
|
|
78
|
+
`motrace-export` again after reordering cells.
|
|
79
79
|
- **Tests run the notebook as a script**, `python nb.py`, one process per notebook, in the notebook's directory, with
|
|
80
80
|
`IN_TEST=1` set. Cells execute in marimo's dependency order.
|
|
81
|
-
- **Clean has less to remove.** Marimo files contain no outputs or execution counts. `
|
|
81
|
+
- **Clean has less to remove.** Marimo files contain no outputs or execution counts. `motrace-clean` rewrites each notebook
|
|
82
82
|
in marimo's own canonical format and strips trailing whitespace. It keeps `__generated_with` unchanged, so upgrading marimo
|
|
83
|
-
doesn't change every notebook. `
|
|
84
|
-
- **Not included:** docs, README generation, `_modidx.py`, `llms.txt` and Quarto. `
|
|
85
|
-
- **Private marimo APIs.**
|
|
83
|
+
doesn't change every notebook. `motrace-clean --stdin` works as a git filter.
|
|
84
|
+
- **Not included:** docs, README generation, `_modidx.py`, `llms.txt` and Quarto. `motrace-prepare` is export + test + clean.
|
|
85
|
+
- **Private marimo APIs.** motrace uses marimo's internal parser and code generator, so it pins `marimo>=0.25,<0.26`.
|
|
86
86
|
|
|
87
87
|
## Example: a tiny language model from one notebook
|
|
88
88
|
|
|
@@ -92,24 +92,53 @@ Each cell picks its target file, giving `tinylm/{data,tokenizer,model,train}.py`
|
|
|
92
92
|
|
|
93
93
|
```sh
|
|
94
94
|
cd examples/tinylm
|
|
95
|
-
|
|
95
|
+
motrace-prepare # export, test, clean -> Success.
|
|
96
96
|
pip install . # or: pip install -e .
|
|
97
97
|
tinylm-train # {'train_ppl': 11.14, 'val_ppl': 11.58} + sampled names
|
|
98
98
|
marimo edit jobs/tinylm.py # keep developing in the notebook
|
|
99
99
|
```
|
|
100
100
|
|
|
101
|
-
## Training data: notebook
|
|
101
|
+
## Training data: notebook ↔ agent trajectory (`motrace-convert`)
|
|
102
|
+
|
|
103
|
+
```sh
|
|
104
|
+
motrace-convert # every notebook in nbs_path -> traces/<notebook>.jsonl
|
|
105
|
+
motrace-convert jobs/00_core.py -o all.jsonl # one notebook (or a directory) into one JSONL file
|
|
106
|
+
motrace-convert traces/00_core.jsonl -o nbs/ # back: trajectory -> nbs/00_core.py
|
|
107
|
+
motrace-convert t.json --to-notebook -o x.py # force the reverse direction for any file name
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
`motrace-convert` turns each notebook into a trajectory of an agent writing it one cell at a time:
|
|
111
|
+
|
|
112
|
+
- a **narration cell** (a hidden cell holding only `mo.md(r"""...""")`) becomes the text of one assistant message;
|
|
113
|
+
- every other cell becomes a `run_cell` tool call (`code`, plus `name` for the setup cell or a reusable function, and
|
|
114
|
+
`hide_code`) on the message that carries the narration before it;
|
|
115
|
+
- the cell's output, recorded in the notebook's marimo session (`__marimo__/session/<name>.json`), becomes the tool
|
|
116
|
+
result. Outputs are matched by code hash, so a stale output is never attached to edited code; those cells get
|
|
117
|
+
`(output not recorded)`, and `metadata.outputs_recorded` counts the rest.
|
|
118
|
+
|
|
119
|
+
Each row is `{"messages", "tools", "metadata"}`: OpenAI-style chat messages and tool calls (tinker-cookbook's
|
|
120
|
+
`ToolCall` shape), tool specs as `{name, description, parameters}`, and metadata with the notebook path, app config
|
|
121
|
+
and file header (PEP 723 block, docstring). Converting a row back gives the notebook exactly as `motrace-clean` writes
|
|
122
|
+
it. Only `hide_code` survives as a cell option, so cells that set `disabled`, `column` etc. are rejected.
|
|
123
|
+
`--instruction FILE` sets the user turn (default: built from the first heading), `--session` picks another session
|
|
124
|
+
file, and `--max-output-chars` truncates tool results. In Python: `motrace.trajectory.to_trajectory(nb)`,
|
|
125
|
+
`to_notebook(row)`, and `training_messages(row, renderer)` for a tinker-cookbook renderer.
|
|
126
|
+
|
|
127
|
+
To keep trajectories next to the code, set `traces_path = "traces"` in `[tool.motrace]`: `motrace-prepare` then
|
|
128
|
+
converts every notebook before exporting.
|
|
129
|
+
|
|
130
|
+
### Pi rollout → Tinker (`motrace-convert --pi`)
|
|
102
131
|
|
|
103
132
|
```sh
|
|
104
133
|
pip install "mo-trace[tinker]"
|
|
105
|
-
|
|
134
|
+
motrace-convert examples/tinylm/jobs/tinylm.py --pi -o traces
|
|
106
135
|
python examples/tinker_train.py traces # SFT, then on-policy distillation, on Tinker
|
|
107
136
|
```
|
|
108
137
|
|
|
109
|
-
`
|
|
138
|
+
`motrace-convert --pi` replays a notebook as a session of the [Pi](https://github.com/earendil-works/pi-mono) coding agent
|
|
110
139
|
building it. The replay uses Pi 1.5.2's system prompt, its `read`/`bash`/`edit`/`write` tool schemas and its result
|
|
111
140
|
strings. The agent explores the project, writes the first cells, then edits in each exported cell with its tests, in
|
|
112
|
-
marimo dependency order. It runs `
|
|
141
|
+
marimo dependency order. It runs `motrace-prepare` after every step and finally checks that the package imports. Every tool
|
|
113
142
|
call runs for real in a scratch copy of the project, so tool results are real output. A notebook whose tests fail is
|
|
114
143
|
rejected. The output files are:
|
|
115
144
|
|
|
@@ -120,7 +149,7 @@ rejected. The output files are:
|
|
|
120
149
|
| `sft.jsonl` | a Tinker `Datum` (`model_input`, `target_tokens`, 0/1 `weights`) of the whole trajectory, rendered with Inkling 2 Small's renderer. Only assistant tokens carry loss: reasoning, text, tool calls and end-of-turn |
|
|
121
150
|
| `opd_prompts.jsonl` | one starting state per assistant turn for on-policy distillation. Each has `prompt_tokens` (a token prefix of the trajectory), `teacher_prompt_tokens`, the reference turn, and the workspace files at that point |
|
|
122
151
|
|
|
123
|
-
Load the data with `
|
|
152
|
+
Load the data with `motrace.convert.load_sft()`. `motrace.convert.opd_datum()` builds the `importance_sampling` datum,
|
|
124
153
|
with advantage = teacher logprob − student logprob for each sampled token.
|
|
125
154
|
|
|
126
155
|
Notes:
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""Command line entry points: motrace (the guide), motrace-export, motrace-prepare, motrace-clean, motrace-convert."""
|
|
2
|
+
|
|
3
|
+
import argparse, sys
|
|
4
|
+
from . import __version__
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from .core import clean_text, get_config, nb_clean, nb_export, nb_test, nb_update
|
|
7
|
+
|
|
8
|
+
GUIDE = '''
|
|
9
|
+
motrace is nbdev for marimo notebooks: write code, docs and tests in a marimo
|
|
10
|
+
notebook; motrace turns chosen cells into a regular Python package and keeps
|
|
11
|
+
the two in sync.
|
|
12
|
+
|
|
13
|
+
SETUP
|
|
14
|
+
Add to your project's pyproject.toml:
|
|
15
|
+
|
|
16
|
+
[tool.motrace]
|
|
17
|
+
lib_path = "mypkg" # package to generate (default: [project].name)
|
|
18
|
+
nbs_path = "jobs" # where notebooks live (default: jobs)
|
|
19
|
+
traces_path = "traces" # optional: motrace-prepare also writes
|
|
20
|
+
# notebook trajectories here, before exporting
|
|
21
|
+
|
|
22
|
+
IN A MARIMO NOTEBOOK
|
|
23
|
+
Directives are `#|` comments on the first lines of a cell:
|
|
24
|
+
|
|
25
|
+
#| default_exp core once per notebook (the setup cell is a good
|
|
26
|
+
place): `#| export` cells go to mypkg/core.py
|
|
27
|
+
#| export write this cell to the default module and list
|
|
28
|
+
its public names in __all__
|
|
29
|
+
#| export io.fmt write this cell to mypkg/io/fmt.py instead
|
|
30
|
+
#| exporti [module] export, but leave out of __all__
|
|
31
|
+
#| eval: false skip this cell when testing
|
|
32
|
+
|
|
33
|
+
Any cell without an export directive is a test: plain `assert`s next to
|
|
34
|
+
the code they check. They run with the notebook, never land in the package.
|
|
35
|
+
|
|
36
|
+
with app.setup:
|
|
37
|
+
#| default_exp core
|
|
38
|
+
import numpy as np
|
|
39
|
+
|
|
40
|
+
@app.cell
|
|
41
|
+
def _():
|
|
42
|
+
#| export
|
|
43
|
+
def norm(x): return x / np.linalg.norm(x)
|
|
44
|
+
return (norm,)
|
|
45
|
+
|
|
46
|
+
@app.cell
|
|
47
|
+
def _(norm):
|
|
48
|
+
assert norm(np.ones(4)).sum() == 2 # a test
|
|
49
|
+
return
|
|
50
|
+
|
|
51
|
+
Import your own package absolutely (`from mypkg.core import norm`) only
|
|
52
|
+
from *other* notebooks; within one notebook just use the name, since marimo
|
|
53
|
+
forbids defining a name twice. motrace adds the imports a module needs
|
|
54
|
+
(setup-cell imports, names exported to sibling modules) automatically.
|
|
55
|
+
Underscore names (`_tmp`) are cell-local in marimo: use them in tests.
|
|
56
|
+
|
|
57
|
+
IN THE CLI
|
|
58
|
+
motrace-export notebooks -> mypkg/*.py
|
|
59
|
+
motrace-export --update edits made in mypkg/*.py -> back into notebooks
|
|
60
|
+
motrace-prepare export, run all notebooks' tests in parallel
|
|
61
|
+
(one process each, cwd = notebook dir), clean;
|
|
62
|
+
exits 1 and names any failing notebook. With
|
|
63
|
+
traces_path set, converts notebooks first
|
|
64
|
+
motrace-clean normalize notebooks (marimo's canonical format,
|
|
65
|
+
no trailing whitespace) to keep diffs small
|
|
66
|
+
motrace-convert [NB|DIR] notebooks -> run_cell agent trajectories (JSONL,
|
|
67
|
+
one row per notebook) in traces_path or traces/;
|
|
68
|
+
hidden `mo.md(r"""...""")` cells are the
|
|
69
|
+
agent's narration, other cells its tool calls,
|
|
70
|
+
session outputs the tool results
|
|
71
|
+
motrace-convert T.jsonl trajectory -> notebook (or --to-notebook)
|
|
72
|
+
motrace-convert NB --pi replay a notebook as a Pi coding-agent rollout
|
|
73
|
+
and write Tinker training data for Inkling 2
|
|
74
|
+
Small; needs `pip install "mo-trace[tinker]"`
|
|
75
|
+
Run any command with --help for its options.
|
|
76
|
+
|
|
77
|
+
Typical loop:
|
|
78
|
+
marimo edit jobs/00_core.py write code + tests
|
|
79
|
+
motrace-prepare before committing
|
|
80
|
+
# edited mypkg/core.py directly (IDE, refactor tool)? then:
|
|
81
|
+
motrace-export --update && motrace-prepare
|
|
82
|
+
|
|
83
|
+
Generated modules start with `# AUTOGENERATED! DO NOT EDIT!` and carry
|
|
84
|
+
`# %% ../jobs/00_core.py #3` markers mapping each block to its cell. Only
|
|
85
|
+
edit inside those blocks, and run --update before changing the notebook.
|
|
86
|
+
|
|
87
|
+
ORGANIZING NOTEBOOKS
|
|
88
|
+
jobs/
|
|
89
|
+
00_core.py #| default_exp core foundations, no internal deps
|
|
90
|
+
01_data.py #| default_exp data may `from mypkg.core import ...`
|
|
91
|
+
02_model.py #| default_exp model
|
|
92
|
+
_scratch.py ignored: names starting with _ or . are skipped
|
|
93
|
+
sub/03_x.py subfolders work (recursive)
|
|
94
|
+
mypkg/ generated; commit it alongside the notebooks
|
|
95
|
+
|
|
96
|
+
- One notebook per module, numbered in dependency order, is the default.
|
|
97
|
+
- One notebook can also fan out into several files with `#| export <mod>`
|
|
98
|
+
(see examples/tinylm: one notebook -> data, tokenizer, model, train).
|
|
99
|
+
- Several notebooks may export into the same module; it is rebuilt whole.
|
|
100
|
+
- Keep notebooks fast: they are your test suite. Mark slow or interactive
|
|
101
|
+
cells `#| eval: false`.
|
|
102
|
+
- After reordering exported cells, run motrace-export before --update
|
|
103
|
+
(cells are matched by position; motrace refuses mismatched updates).
|
|
104
|
+
'''
|
|
105
|
+
|
|
106
|
+
def main_cli(argv=None):
|
|
107
|
+
p = argparse.ArgumentParser('motrace', description=f'motrace {__version__}: nbdev-style literate programming for '
|
|
108
|
+
'marimo notebooks', epilog=GUIDE, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
109
|
+
p.add_argument('--version', action='version', version=__version__)
|
|
110
|
+
p.parse_args(argv)
|
|
111
|
+
p.print_help()
|
|
112
|
+
|
|
113
|
+
def export_cli(argv=None):
|
|
114
|
+
p = argparse.ArgumentParser('motrace-export', description='Export marimo notebooks to Python modules '
|
|
115
|
+
'(like nbdev-export), or with --update sync module edits back (like nbdev-update)')
|
|
116
|
+
p.add_argument('path', nargs='?', help='notebook or directory to export (default: nbs_path); '
|
|
117
|
+
'with --update, a module or directory (default: lib_path)')
|
|
118
|
+
p.add_argument('--update', action='store_true', help='propagate edits in exported modules back to notebooks')
|
|
119
|
+
a = p.parse_args(argv)
|
|
120
|
+
for f in (nb_update if a.update else nb_export)(a.path): print(f'{"updated" if a.update else "exported"} {f}')
|
|
121
|
+
|
|
122
|
+
def clean_cli(argv=None):
|
|
123
|
+
p = argparse.ArgumentParser('motrace-clean', description='Normalize marimo notebooks to avoid merge conflicts')
|
|
124
|
+
p.add_argument('fname', nargs='?', help='notebook or directory to clean (default: nbs_path)')
|
|
125
|
+
p.add_argument('--stdin', action='store_true', help='clean a notebook read from stdin to stdout (git filter)')
|
|
126
|
+
a = p.parse_args(argv)
|
|
127
|
+
if a.stdin: return sys.stdout.write(clean_text(sys.stdin.read()))
|
|
128
|
+
for f in nb_clean(a.fname): print(f'cleaned {f}')
|
|
129
|
+
|
|
130
|
+
def convert_cli(argv=None):
|
|
131
|
+
p = argparse.ArgumentParser('motrace-convert', formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
132
|
+
description='Convert marimo notebooks to run_cell agent trajectories (JSONL), and back.\n\n'
|
|
133
|
+
'Narration cells (hidden `mo.md(r"""...""")`) become assistant text; every other cell\n'
|
|
134
|
+
'becomes a run_cell tool call whose result is the output recorded in the notebook\'s\n'
|
|
135
|
+
'marimo session.',
|
|
136
|
+
epilog='''examples:
|
|
137
|
+
motrace-convert all notebooks in nbs_path -> traces_path (default: traces/)
|
|
138
|
+
motrace-convert jobs/00_core.py -> traces/00_core.jsonl
|
|
139
|
+
motrace-convert jobs/ -o all.jsonl every notebook, one row each, in one file
|
|
140
|
+
motrace-convert traces/00_core.jsonl -o nbs/ trajectory -> nbs/00_core.py (.json/.jsonl inputs go back)
|
|
141
|
+
motrace-convert t.txt --to-notebook -o x.py force the reverse direction
|
|
142
|
+
motrace-convert jobs/00_core.py --pi -o out/ Pi coding-agent rollout + Tinker data (the 0.2 behavior)''')
|
|
143
|
+
p.add_argument('paths', nargs='*', help='notebooks or directories (default: nbs_path); trajectory .json/.jsonl '
|
|
144
|
+
'files convert back to notebooks')
|
|
145
|
+
p.add_argument('-o', '--out', help='notebook -> trajectory: a directory (default: traces_path, else traces) or '
|
|
146
|
+
'one .jsonl file; trajectory -> notebook: a directory (default: .) or one .py file; '
|
|
147
|
+
'--pi: a directory (default: traces)')
|
|
148
|
+
p.add_argument('--to-notebook', action='store_true', help='convert trajectories back to notebooks (implied when '
|
|
149
|
+
'every input is .json/.jsonl)')
|
|
150
|
+
p.add_argument('--force', action='store_true', help='with --to-notebook, overwrite existing notebooks')
|
|
151
|
+
p.add_argument('--session', help='marimo session JSON with the recorded outputs (default: the notebook\'s '
|
|
152
|
+
'__marimo__/session/<name>.json); one notebook only')
|
|
153
|
+
p.add_argument('--instruction', help='text file with the user turn (default: built from the first heading)')
|
|
154
|
+
p.add_argument('--max-output-chars', type=int, default=4000, help='truncate each tool result (default: 4000)')
|
|
155
|
+
pi = p.add_argument_group('Pi rollout (--pi)')
|
|
156
|
+
pi.add_argument('--pi', action='store_true', help='replay the notebook as a Pi coding-agent rollout (real tool '
|
|
157
|
+
'executions) and write pi_session.jsonl, messages.json, sft.jsonl, opd_prompts.jsonl')
|
|
158
|
+
pi.add_argument('--model', default='thinkingmachines/Inkling-2-Small', help='Tinker model whose renderer to use')
|
|
159
|
+
pi.add_argument('--effort', type=float, default=0.0, help='Inkling thinking-effort conditioning in [0, 1). '
|
|
160
|
+
'Reasoning comes only from the notebook\'s markdown and is usually short, so the default is 0')
|
|
161
|
+
pi.add_argument('--cwd', default=None, help='working directory shown in the trace (default: /home/user/<project>)')
|
|
162
|
+
pi.add_argument('--no-tinker', action='store_true', help='only write the Pi session and chat messages')
|
|
163
|
+
a = p.parse_args(argv)
|
|
164
|
+
if a.pi: return _convert_pi(p, a)
|
|
165
|
+
from .trajectory import nb_from_trajectories, nb_trajectories
|
|
166
|
+
if a.to_notebook or (a.paths and all(x.endswith(('.json', '.jsonl')) for x in a.paths)):
|
|
167
|
+
if not a.paths: p.error('--to-notebook needs trajectory files')
|
|
168
|
+
for f in nb_from_trajectories(a.paths, a.out or '.', force=a.force): print(f'wrote {f}')
|
|
169
|
+
return
|
|
170
|
+
if a.session and (len(a.paths) != 1 or Path(a.paths[0]).is_dir()): p.error('--session needs exactly one notebook')
|
|
171
|
+
files = nb_trajectories(a.paths, a.out, session=a.session, max_output_chars=a.max_output_chars,
|
|
172
|
+
instruction=Path(a.instruction).read_text() if a.instruction else None)
|
|
173
|
+
if not files: print('No notebooks found')
|
|
174
|
+
for f in files: print(f'wrote {f}')
|
|
175
|
+
|
|
176
|
+
def _convert_pi(p, a):
|
|
177
|
+
if len(a.paths) != 1: p.error('--pi converts exactly one notebook')
|
|
178
|
+
tinker = not a.no_tinker
|
|
179
|
+
if tinker:
|
|
180
|
+
try: import tinker_cookbook # noqa: F401
|
|
181
|
+
except ImportError: sys.exit('motrace-convert: Tinker output needs `pip install "mo-trace[tinker]"` (or pass --no-tinker)')
|
|
182
|
+
from .convert import convert
|
|
183
|
+
ro, files = convert(a.paths[0], a.out or 'traces', model=a.model, effort=a.effort, cwd=a.cwd, tinker=tinker)
|
|
184
|
+
n = sum(m['role'] == 'assistant' for m in ro['messages'])
|
|
185
|
+
print(f'{a.paths[0]}: {n} assistant turns, {n - 1} tool calls')
|
|
186
|
+
for f in files: print(f'wrote {f}')
|
|
187
|
+
|
|
188
|
+
def prepare_cli(argv=None):
|
|
189
|
+
p = argparse.ArgumentParser('motrace-prepare', description='Export, test (in parallel) and clean notebooks')
|
|
190
|
+
p.add_argument('--n_workers', type=int, default=None, help='parallel test processes (default: min(cpus, 8))')
|
|
191
|
+
p.add_argument('--timing', action='store_true', help='print how long each notebook took')
|
|
192
|
+
p.add_argument('--timeout', type=float, default=None, help='seconds before a notebook test is killed')
|
|
193
|
+
a = p.parse_args(argv)
|
|
194
|
+
if get_config().traces_path:
|
|
195
|
+
from .trajectory import nb_trajectories
|
|
196
|
+
for f in nb_trajectories(): print(f'wrote {f}')
|
|
197
|
+
nb_export()
|
|
198
|
+
if not nb_test(n_workers=a.n_workers, timing=a.timing, timeout=a.timeout): sys.exit(1)
|
|
199
|
+
nb_clean()
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""motrace-convert: replay a marimo notebook as a Pi coding-agent rollout, then render it as Tinker training data.
|
|
2
2
|
|
|
3
3
|
The rollout is what Pi (https://github.com/earendil-works/pi-mono) would record if an agent built the notebook
|
|
4
4
|
step by step: explore the project, `write` the first cells, `edit` in each further exported cell plus its tests,
|
|
5
|
-
run `
|
|
5
|
+
run `motrace-prepare` after every step, and finally check the generated package. Every tool call is actually
|
|
6
6
|
executed in a scratch copy of the project, so every tool result is real output.
|
|
7
7
|
|
|
8
8
|
Outputs (in `out_dir`):
|
|
@@ -200,15 +200,15 @@ def rollout(nb, cwd=None):
|
|
|
200
200
|
if title:
|
|
201
201
|
summ = next((l[2:].strip() for l in title.splitlines() if l.startswith('> ')), '')
|
|
202
202
|
lines.append(f'{title.splitlines()[0][2:]}' + (f': {summ}' if summ else '') + '\n')
|
|
203
|
-
lines.append(f'Build the `{lib}` package as a marimo notebook at `{nbrel}`, using
|
|
203
|
+
lines.append(f'Build the `{lib}` package as a marimo notebook at `{nbrel}`, using motrace: cells marked '
|
|
204
204
|
f'`#| export <module>` are written to `{lib}/<module>.py`, and every other cell is a test.\n\nThe package should provide:')
|
|
205
205
|
for mod, idxs in mods.items():
|
|
206
206
|
api = ', '.join(f'`{n}`' + (f' ({d.rstrip(".")})' if d else '') for n, d in _api(cells, idxs))
|
|
207
207
|
lines.append(f'- `{lib}/{mod.replace(".", "/")}.py`: {api}')
|
|
208
|
-
lines.append('\nWrite tests as ordinary notebook cells next to the code they check, and finish with `
|
|
208
|
+
lines.append('\nWrite tests as ordinary notebook cells next to the code they check, and finish with `motrace-prepare` passing.')
|
|
209
209
|
task = '\n'.join(lines)
|
|
210
210
|
|
|
211
|
-
tmp = Path(tempfile.mkdtemp(prefix='
|
|
211
|
+
tmp = Path(tempfile.mkdtemp(prefix='motrace_convert_'))
|
|
212
212
|
try:
|
|
213
213
|
for f in cfg.root.iterdir(): # the project as the agent finds it: top-level files only, no notebooks, no package
|
|
214
214
|
if f.is_file() and not f.name.startswith('.'): shutil.copy(f, tmp/f.name)
|
|
@@ -247,15 +247,15 @@ def rollout(nb, cwd=None):
|
|
|
247
247
|
if k == 0 or not (e := _edit_for(text, new)): turn(say, 'write', {'path': nbrel, 'content': new}, think)
|
|
248
248
|
else: turn(say, 'edit', {'path': nbrel, 'edits': [e]}, think)
|
|
249
249
|
text = new
|
|
250
|
-
out, err = turn('', 'bash', {'command': '
|
|
251
|
-
if err: raise RuntimeError(f'step {k} of {nb.name} fails
|
|
250
|
+
out, err = turn('', 'bash', {'command': 'motrace-prepare'})
|
|
251
|
+
if err: raise RuntimeError(f'step {k} of {nb.name} fails motrace-prepare:\n{out}')
|
|
252
252
|
mod_names = list(mods)
|
|
253
253
|
check = f'python -c "import importlib\nfor m in {mod_names!r}: print(m, importlib.import_module(\'{lib}.\' + m).__all__)"'
|
|
254
254
|
out, err = turn('All steps pass. Checking that the generated package imports cleanly.', 'bash', {'command': check})
|
|
255
255
|
if err: raise RuntimeError(f'generated package does not import:\n{out}')
|
|
256
256
|
summary = '\n'.join(f'- `{lib}/{m.replace(".", "/")}.py`: ' + ', '.join(f'`{n}`' for n, _ in _api(cells, idxs))
|
|
257
257
|
for m, idxs in mods.items())
|
|
258
|
-
turn(f'Done. `{nbrel}` builds the `{lib}` package with
|
|
258
|
+
turn(f'Done. `{nbrel}` builds the `{lib}` package with motrace, and `motrace-prepare` passes.\n\n{summary}')
|
|
259
259
|
final = (tmp/nbrel).read_text()
|
|
260
260
|
finally: shutil.rmtree(tmp, ignore_errors=True)
|
|
261
261
|
return {'system': pi_system_prompt(cwd), 'tools': TOOLS, 'messages': msgs, 'snapshots': snaps, 'cwd': cwd,
|
|
@@ -270,13 +270,13 @@ def to_pi_session(ro):
|
|
|
270
270
|
t0 = ro['messages'][0]['timestamp'] - 1000
|
|
271
271
|
lines = [{'type': 'session', 'version': 3, 'id': f'{sid[:8]}-{sid[8:12]}-{sid[12:16]}-{sid[16:20]}-{sid[20:32]}',
|
|
272
272
|
'timestamp': iso(t0), 'cwd': ro['cwd']},
|
|
273
|
-
{'type': 'custom', 'id': sid[:8], 'parentId': None, 'timestamp': iso(t0), 'customType': '
|
|
273
|
+
{'type': 'custom', 'id': sid[:8], 'parentId': None, 'timestamp': iso(t0), 'customType': 'motrace-convert',
|
|
274
274
|
'data': {'source': ro['notebook'], 'sha256': ro['source_sha256'], 'pi_version': PI_VERSION,
|
|
275
275
|
'note': 'synthetic rollout replayed from a marimo notebook; tool results are real executions'}}]
|
|
276
276
|
usage = {'input': 0, 'output': 0, 'cacheRead': 0, 'cacheWrite': 0, 'totalTokens': 0,
|
|
277
277
|
'cost': {'input': 0, 'output': 0, 'cacheRead': 0, 'cacheWrite': 0, 'total': 0}}
|
|
278
278
|
for i, m in enumerate(ro['messages']):
|
|
279
|
-
if m['role'] == 'assistant': m = {**m, 'api': 'openai-completions', 'provider': '
|
|
279
|
+
if m['role'] == 'assistant': m = {**m, 'api': 'openai-completions', 'provider': 'motrace', 'model': 'notebook-replay', 'usage': usage}
|
|
280
280
|
eid = hashlib.sha256(f'{sid}{i}'.encode()).hexdigest()[:8]
|
|
281
281
|
lines.append({'type': 'message', 'id': eid, 'parentId': lines[-1]['id'], 'timestamp': iso(m['timestamp']), 'message': m})
|
|
282
282
|
return [json.dumps(l) for l in lines]
|