mo-trace 0.1.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/.gitignore +5 -0
- mo_trace-0.1.0/PKG-INFO +153 -0
- mo_trace-0.1.0/README.md +140 -0
- mo_trace-0.1.0/matrace/__init__.py +3 -0
- mo_trace-0.1.0/matrace/cli.py +151 -0
- mo_trace-0.1.0/matrace/convert.py +380 -0
- mo_trace-0.1.0/matrace/core.py +338 -0
- mo_trace-0.1.0/pyproject.toml +31 -0
- mo_trace-0.1.0/tests/conftest.py +47 -0
- mo_trace-0.1.0/tests/test_convert.py +99 -0
- mo_trace-0.1.0/tests/test_matrace.py +193 -0
mo_trace-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: mo-trace
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: nbdev-style literate programming for marimo notebooks
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Requires-Python: >=3.11
|
|
7
|
+
Requires-Dist: marimo<0.26,>=0.25
|
|
8
|
+
Provides-Extra: tinker
|
|
9
|
+
Requires-Dist: tinker-cookbook>=0.6; extra == 'tinker'
|
|
10
|
+
Requires-Dist: tinker>=0.39; extra == 'tinker'
|
|
11
|
+
Requires-Dist: tml-renderers>=0.4; extra == 'tinker'
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# matrace
|
|
15
|
+
|
|
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. matrace turns the exported cells into a normal Python package and keeps the two in sync.
|
|
18
|
+
|
|
19
|
+
| matrace | nbdev equivalent | does |
|
|
20
|
+
|---|---|---|
|
|
21
|
+
| `matrace-export` | `nbdev-export` | notebook cells → modules in `lib_path` |
|
|
22
|
+
| `matrace-export --update` | `nbdev-update` | edits made in modules → back into the notebook cells |
|
|
23
|
+
| `matrace-prepare` | `nbdev-prepare` | export, run every notebook's tests in parallel, then clean |
|
|
24
|
+
| `matrace-clean` | `nbdev-clean` | normalize notebooks so diffs and merges stay clean |
|
|
25
|
+
|
|
26
|
+
Run `matrace --help` for a guide to using it in a notebook and the CLI, and to organizing notebooks.
|
|
27
|
+
|
|
28
|
+
## Install
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
pip install mo-trace # or: uv add --dev mo-trace (imported as `matrace`)
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Add a `[tool.matrace]` table to your project's `pyproject.toml`:
|
|
35
|
+
|
|
36
|
+
```toml
|
|
37
|
+
[tool.matrace]
|
|
38
|
+
lib_path = "mypkg" # default: [project].name, with - replaced by _
|
|
39
|
+
nbs_path = "jobs" # default: jobs
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Writing notebooks
|
|
43
|
+
|
|
44
|
+
Directives are `#|` comments on the first lines of a cell. They work the same as in nbdev.
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
with app.setup:
|
|
48
|
+
#| default_exp core # where `#| export` cells go -> mypkg/core.py
|
|
49
|
+
import numpy as np
|
|
50
|
+
|
|
51
|
+
@app.cell
|
|
52
|
+
def _():
|
|
53
|
+
#| export # -> mypkg/core.py, listed in __all__
|
|
54
|
+
def norm(x): return x / np.linalg.norm(x)
|
|
55
|
+
return (norm,)
|
|
56
|
+
|
|
57
|
+
@app.cell
|
|
58
|
+
def _(norm):
|
|
59
|
+
#| export metrics.distance # choose the file for this cell -> mypkg/metrics/distance.py
|
|
60
|
+
def cosine(a, b): return norm(a) @ norm(b)
|
|
61
|
+
return (cosine,)
|
|
62
|
+
|
|
63
|
+
@app.cell
|
|
64
|
+
def _(cosine):
|
|
65
|
+
assert cosine(np.ones(3), np.ones(3)) == 1 # an ordinary cell is a test
|
|
66
|
+
return
|
|
67
|
+
|
|
68
|
+
@app.cell
|
|
69
|
+
def _():
|
|
70
|
+
#| eval: false # skipped by matrace-prepare
|
|
71
|
+
slow_benchmark()
|
|
72
|
+
return
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Supported directives: `default_exp`, `export [module]`, `exporti [module]` (exported but left out of `__all__`), `exports`, and
|
|
76
|
+
`eval: false`. matrace also follows nbdev for these details:
|
|
77
|
+
- `__all__` is built from the public names in exported cells, plus any names listed in `_all_`.
|
|
78
|
+
- `from mypkg.x import y` becomes a relative import in the generated module, and becomes absolute again when synced back.
|
|
79
|
+
- The module docstring comes from the `> summary` line under the notebook's `# Title` markdown cell.
|
|
80
|
+
- Notebooks whose names start with `_` or `.` are skipped.
|
|
81
|
+
|
|
82
|
+
## Differences from nbdev (by design or necessity)
|
|
83
|
+
|
|
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. matrace reads marimo's dataflow graph
|
|
86
|
+
instead. Each module gets an `# %% auto #1` block that imports what its cells use but don't define: import statements
|
|
87
|
+
from other cells, such as the setup cell, are copied, and names exported to other modules are imported from those modules.
|
|
88
|
+
- **`#| export other_module` can create a new file.** nbdev requires the target module to already exist.
|
|
89
|
+
- **Cells are identified by position.** Marimo files have no stable cell ids, so the `# %% ../jobs/nb.py #3` markers use the
|
|
90
|
+
cell's position. `--update` refuses to write if that cell is no longer an exported cell of the same module. Run
|
|
91
|
+
`matrace-export` again after reordering cells.
|
|
92
|
+
- **Tests run the notebook as a script**, `python nb.py`, one process per notebook, in the notebook's directory, with
|
|
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. `matrace-clean` rewrites each notebook
|
|
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. `matrace-clean --stdin` works as a git filter.
|
|
97
|
+
- **Not included:** docs, README generation, `_modidx.py`, `llms.txt` and Quarto. `matrace-prepare` is export + test + clean.
|
|
98
|
+
- **Private marimo APIs.** matrace uses marimo's internal parser and code generator, so it pins `marimo>=0.25,<0.26`.
|
|
99
|
+
|
|
100
|
+
## Example: a tiny language model from one notebook
|
|
101
|
+
|
|
102
|
+
[`examples/tinylm`](examples/tinylm) is a character-level bigram language model, the classic first language model. It
|
|
103
|
+
trains on a list of names, reports perplexity and samples new names. All of it is in [`jobs/tinylm.py`](examples/tinylm/jobs/tinylm.py).
|
|
104
|
+
Each cell picks its target file, giving `tinylm/{data,tokenizer,model,train}.py`. The tests sit next to the code they check.
|
|
105
|
+
|
|
106
|
+
```sh
|
|
107
|
+
cd examples/tinylm
|
|
108
|
+
matrace-prepare # export, test, clean -> Success.
|
|
109
|
+
pip install . # or: pip install -e .
|
|
110
|
+
tinylm-train # {'train_ppl': 11.14, 'val_ppl': 11.58} + sampled names
|
|
111
|
+
marimo edit jobs/tinylm.py # keep developing in the notebook
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
## Training data: notebook → Pi rollout → Tinker (`matrace-convert`)
|
|
115
|
+
|
|
116
|
+
```sh
|
|
117
|
+
pip install "mo-trace[tinker]"
|
|
118
|
+
matrace-convert examples/tinylm/jobs/tinylm.py -o traces
|
|
119
|
+
python examples/tinker_train.py traces # SFT, then on-policy distillation, on Tinker
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
`matrace-convert` replays a notebook as a session of the [Pi](https://github.com/earendil-works/pi-mono) coding agent
|
|
123
|
+
building it. The replay uses Pi 1.5.2's system prompt, its `read`/`bash`/`edit`/`write` tool schemas and its result
|
|
124
|
+
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 `matrace-prepare` after every step and finally checks that the package imports. Every tool
|
|
126
|
+
call runs for real in a scratch copy of the project, so tool results are real output. A notebook whose tests fail is
|
|
127
|
+
rejected. The output files are:
|
|
128
|
+
|
|
129
|
+
| file | contents |
|
|
130
|
+
|---|---|
|
|
131
|
+
| `pi_session.jsonl` | the rollout as a Pi v3 session file, with a `custom` entry recording its notebook source |
|
|
132
|
+
| `messages.json` | the same conversation in OpenAI / tinker-cookbook format, plus Pi's system prompt and tool specs |
|
|
133
|
+
| `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
|
+
| `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
|
+
|
|
136
|
+
Load the data with `matrace.convert.load_sft()`. `matrace.convert.opd_datum()` builds the `importance_sampling` datum,
|
|
137
|
+
with advantage = teacher logprob − student logprob for each sampled token.
|
|
138
|
+
|
|
139
|
+
Notes:
|
|
140
|
+
- **Teacher.** Inkling 2 Small's tokenizer isn't shared with any other Tinker model, Inkling v1 included. A token-level
|
|
141
|
+
teacher therefore has to be Inkling 2 Small as well. `teacher_prompt_tokens` gives it privileged context: the same
|
|
142
|
+
state, with the finished notebook in the task message. You can also use a stronger fine-tuned checkpoint.
|
|
143
|
+
- **Reasoning.** The markdown cells before each step become that turn's `thinking` block (Pi's and the cookbook's format),
|
|
144
|
+
which carries loss like the rest of the turn. A notebook with little prose gives little reasoning, so the default
|
|
145
|
+
thinking effort stays at 0 (`--effort`).
|
|
146
|
+
- **Ideal path only.** Traces don't yet include mistakes and recoveries. Distillation samples one turn per state; a
|
|
147
|
+
multi-turn version would run the student's tool calls in the record's `workspace` snapshot.
|
|
148
|
+
|
|
149
|
+
## Development
|
|
150
|
+
|
|
151
|
+
```sh
|
|
152
|
+
uv sync && uv run pytest # includes parity tests that run real nbdev on equivalent .ipynb notebooks
|
|
153
|
+
```
|
mo_trace-0.1.0/README.md
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
# matrace
|
|
2
|
+
|
|
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. matrace turns the exported cells into a normal Python package and keeps the two in sync.
|
|
5
|
+
|
|
6
|
+
| matrace | nbdev equivalent | does |
|
|
7
|
+
|---|---|---|
|
|
8
|
+
| `matrace-export` | `nbdev-export` | notebook cells → modules in `lib_path` |
|
|
9
|
+
| `matrace-export --update` | `nbdev-update` | edits made in modules → back into the notebook cells |
|
|
10
|
+
| `matrace-prepare` | `nbdev-prepare` | export, run every notebook's tests in parallel, then clean |
|
|
11
|
+
| `matrace-clean` | `nbdev-clean` | normalize notebooks so diffs and merges stay clean |
|
|
12
|
+
|
|
13
|
+
Run `matrace --help` for a guide to using it in a notebook and the CLI, and to organizing notebooks.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
pip install mo-trace # or: uv add --dev mo-trace (imported as `matrace`)
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Add a `[tool.matrace]` table to your project's `pyproject.toml`:
|
|
22
|
+
|
|
23
|
+
```toml
|
|
24
|
+
[tool.matrace]
|
|
25
|
+
lib_path = "mypkg" # default: [project].name, with - replaced by _
|
|
26
|
+
nbs_path = "jobs" # default: jobs
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Writing notebooks
|
|
30
|
+
|
|
31
|
+
Directives are `#|` comments on the first lines of a cell. They work the same as in nbdev.
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
with app.setup:
|
|
35
|
+
#| default_exp core # where `#| export` cells go -> mypkg/core.py
|
|
36
|
+
import numpy as np
|
|
37
|
+
|
|
38
|
+
@app.cell
|
|
39
|
+
def _():
|
|
40
|
+
#| export # -> mypkg/core.py, listed in __all__
|
|
41
|
+
def norm(x): return x / np.linalg.norm(x)
|
|
42
|
+
return (norm,)
|
|
43
|
+
|
|
44
|
+
@app.cell
|
|
45
|
+
def _(norm):
|
|
46
|
+
#| export metrics.distance # choose the file for this cell -> mypkg/metrics/distance.py
|
|
47
|
+
def cosine(a, b): return norm(a) @ norm(b)
|
|
48
|
+
return (cosine,)
|
|
49
|
+
|
|
50
|
+
@app.cell
|
|
51
|
+
def _(cosine):
|
|
52
|
+
assert cosine(np.ones(3), np.ones(3)) == 1 # an ordinary cell is a test
|
|
53
|
+
return
|
|
54
|
+
|
|
55
|
+
@app.cell
|
|
56
|
+
def _():
|
|
57
|
+
#| eval: false # skipped by matrace-prepare
|
|
58
|
+
slow_benchmark()
|
|
59
|
+
return
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Supported directives: `default_exp`, `export [module]`, `exporti [module]` (exported but left out of `__all__`), `exports`, and
|
|
63
|
+
`eval: false`. matrace also follows nbdev for these details:
|
|
64
|
+
- `__all__` is built from the public names in exported cells, plus any names listed in `_all_`.
|
|
65
|
+
- `from mypkg.x import y` becomes a relative import in the generated module, and becomes absolute again when synced back.
|
|
66
|
+
- The module docstring comes from the `> summary` line under the notebook's `# Title` markdown cell.
|
|
67
|
+
- Notebooks whose names start with `_` or `.` are skipped.
|
|
68
|
+
|
|
69
|
+
## Differences from nbdev (by design or necessity)
|
|
70
|
+
|
|
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. matrace reads marimo's dataflow graph
|
|
73
|
+
instead. Each module gets an `# %% auto #1` block that imports what its cells use but don't define: import statements
|
|
74
|
+
from other cells, such as the setup cell, are copied, and names exported to other modules are imported from those modules.
|
|
75
|
+
- **`#| export other_module` can create a new file.** nbdev requires the target module to already exist.
|
|
76
|
+
- **Cells are identified by position.** Marimo files have no stable cell ids, so the `# %% ../jobs/nb.py #3` markers use the
|
|
77
|
+
cell's position. `--update` refuses to write if that cell is no longer an exported cell of the same module. Run
|
|
78
|
+
`matrace-export` again after reordering cells.
|
|
79
|
+
- **Tests run the notebook as a script**, `python nb.py`, one process per notebook, in the notebook's directory, with
|
|
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. `matrace-clean` rewrites each notebook
|
|
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. `matrace-clean --stdin` works as a git filter.
|
|
84
|
+
- **Not included:** docs, README generation, `_modidx.py`, `llms.txt` and Quarto. `matrace-prepare` is export + test + clean.
|
|
85
|
+
- **Private marimo APIs.** matrace uses marimo's internal parser and code generator, so it pins `marimo>=0.25,<0.26`.
|
|
86
|
+
|
|
87
|
+
## Example: a tiny language model from one notebook
|
|
88
|
+
|
|
89
|
+
[`examples/tinylm`](examples/tinylm) is a character-level bigram language model, the classic first language model. It
|
|
90
|
+
trains on a list of names, reports perplexity and samples new names. All of it is in [`jobs/tinylm.py`](examples/tinylm/jobs/tinylm.py).
|
|
91
|
+
Each cell picks its target file, giving `tinylm/{data,tokenizer,model,train}.py`. The tests sit next to the code they check.
|
|
92
|
+
|
|
93
|
+
```sh
|
|
94
|
+
cd examples/tinylm
|
|
95
|
+
matrace-prepare # export, test, clean -> Success.
|
|
96
|
+
pip install . # or: pip install -e .
|
|
97
|
+
tinylm-train # {'train_ppl': 11.14, 'val_ppl': 11.58} + sampled names
|
|
98
|
+
marimo edit jobs/tinylm.py # keep developing in the notebook
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## Training data: notebook → Pi rollout → Tinker (`matrace-convert`)
|
|
102
|
+
|
|
103
|
+
```sh
|
|
104
|
+
pip install "mo-trace[tinker]"
|
|
105
|
+
matrace-convert examples/tinylm/jobs/tinylm.py -o traces
|
|
106
|
+
python examples/tinker_train.py traces # SFT, then on-policy distillation, on Tinker
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
`matrace-convert` replays a notebook as a session of the [Pi](https://github.com/earendil-works/pi-mono) coding agent
|
|
110
|
+
building it. The replay uses Pi 1.5.2's system prompt, its `read`/`bash`/`edit`/`write` tool schemas and its result
|
|
111
|
+
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 `matrace-prepare` after every step and finally checks that the package imports. Every tool
|
|
113
|
+
call runs for real in a scratch copy of the project, so tool results are real output. A notebook whose tests fail is
|
|
114
|
+
rejected. The output files are:
|
|
115
|
+
|
|
116
|
+
| file | contents |
|
|
117
|
+
|---|---|
|
|
118
|
+
| `pi_session.jsonl` | the rollout as a Pi v3 session file, with a `custom` entry recording its notebook source |
|
|
119
|
+
| `messages.json` | the same conversation in OpenAI / tinker-cookbook format, plus Pi's system prompt and tool specs |
|
|
120
|
+
| `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
|
+
| `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
|
+
|
|
123
|
+
Load the data with `matrace.convert.load_sft()`. `matrace.convert.opd_datum()` builds the `importance_sampling` datum,
|
|
124
|
+
with advantage = teacher logprob − student logprob for each sampled token.
|
|
125
|
+
|
|
126
|
+
Notes:
|
|
127
|
+
- **Teacher.** Inkling 2 Small's tokenizer isn't shared with any other Tinker model, Inkling v1 included. A token-level
|
|
128
|
+
teacher therefore has to be Inkling 2 Small as well. `teacher_prompt_tokens` gives it privileged context: the same
|
|
129
|
+
state, with the finished notebook in the task message. You can also use a stronger fine-tuned checkpoint.
|
|
130
|
+
- **Reasoning.** The markdown cells before each step become that turn's `thinking` block (Pi's and the cookbook's format),
|
|
131
|
+
which carries loss like the rest of the turn. A notebook with little prose gives little reasoning, so the default
|
|
132
|
+
thinking effort stays at 0 (`--effort`).
|
|
133
|
+
- **Ideal path only.** Traces don't yet include mistakes and recoveries. Distillation samples one turn per state; a
|
|
134
|
+
multi-turn version would run the student's tool calls in the record's `workspace` snapshot.
|
|
135
|
+
|
|
136
|
+
## Development
|
|
137
|
+
|
|
138
|
+
```sh
|
|
139
|
+
uv sync && uv run pytest # includes parity tests that run real nbdev on equivalent .ipynb notebooks
|
|
140
|
+
```
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""Command line entry points: matrace (the guide), matrace-export, matrace-prepare, matrace-clean."""
|
|
2
|
+
|
|
3
|
+
import argparse, sys
|
|
4
|
+
from . import __version__
|
|
5
|
+
from .core import nb_clean, nb_export, nb_test, nb_update, clean_text
|
|
6
|
+
|
|
7
|
+
GUIDE = '''
|
|
8
|
+
matrace is nbdev for marimo notebooks: write code, docs and tests in a marimo
|
|
9
|
+
notebook; matrace turns chosen cells into a regular Python package and keeps
|
|
10
|
+
the two in sync.
|
|
11
|
+
|
|
12
|
+
SETUP
|
|
13
|
+
Add to your project's pyproject.toml:
|
|
14
|
+
|
|
15
|
+
[tool.matrace]
|
|
16
|
+
lib_path = "mypkg" # package to generate (default: [project].name)
|
|
17
|
+
nbs_path = "jobs" # where notebooks live (default: jobs)
|
|
18
|
+
|
|
19
|
+
IN A MARIMO NOTEBOOK
|
|
20
|
+
Directives are `#|` comments on the first lines of a cell:
|
|
21
|
+
|
|
22
|
+
#| default_exp core once per notebook (the setup cell is a good
|
|
23
|
+
place): `#| export` cells go to mypkg/core.py
|
|
24
|
+
#| export write this cell to the default module and list
|
|
25
|
+
its public names in __all__
|
|
26
|
+
#| export io.fmt write this cell to mypkg/io/fmt.py instead
|
|
27
|
+
#| exporti [module] export, but leave out of __all__
|
|
28
|
+
#| eval: false skip this cell when testing
|
|
29
|
+
|
|
30
|
+
Any cell without an export directive is a test: plain `assert`s next to
|
|
31
|
+
the code they check. They run with the notebook, never land in the package.
|
|
32
|
+
|
|
33
|
+
with app.setup:
|
|
34
|
+
#| default_exp core
|
|
35
|
+
import numpy as np
|
|
36
|
+
|
|
37
|
+
@app.cell
|
|
38
|
+
def _():
|
|
39
|
+
#| export
|
|
40
|
+
def norm(x): return x / np.linalg.norm(x)
|
|
41
|
+
return (norm,)
|
|
42
|
+
|
|
43
|
+
@app.cell
|
|
44
|
+
def _(norm):
|
|
45
|
+
assert norm(np.ones(4)).sum() == 2 # a test
|
|
46
|
+
return
|
|
47
|
+
|
|
48
|
+
Import your own package absolutely (`from mypkg.core import norm`) only
|
|
49
|
+
from *other* notebooks; within one notebook just use the name, since marimo
|
|
50
|
+
forbids defining a name twice. matrace adds the imports a module needs
|
|
51
|
+
(setup-cell imports, names exported to sibling modules) automatically.
|
|
52
|
+
Underscore names (`_tmp`) are cell-local in marimo: use them in tests.
|
|
53
|
+
|
|
54
|
+
IN THE CLI
|
|
55
|
+
matrace-export notebooks -> mypkg/*.py
|
|
56
|
+
matrace-export --update edits made in mypkg/*.py -> back into notebooks
|
|
57
|
+
matrace-prepare export, run all notebooks' tests in parallel
|
|
58
|
+
(one process each, cwd = notebook dir), clean;
|
|
59
|
+
exits 1 and names any failing notebook
|
|
60
|
+
matrace-clean normalize notebooks (marimo's canonical format,
|
|
61
|
+
no trailing whitespace) to keep diffs small
|
|
62
|
+
matrace-convert NB -o DIR replay a notebook as a Pi coding-agent rollout
|
|
63
|
+
and write it as Tinker training data (SFT and
|
|
64
|
+
on-policy distillation) for Inkling 2 Small;
|
|
65
|
+
needs `pip install "mo-trace[tinker]"`
|
|
66
|
+
Run any command with --help for its options.
|
|
67
|
+
|
|
68
|
+
Typical loop:
|
|
69
|
+
marimo edit jobs/00_core.py write code + tests
|
|
70
|
+
matrace-prepare before committing
|
|
71
|
+
# edited mypkg/core.py directly (IDE, refactor tool)? then:
|
|
72
|
+
matrace-export --update && matrace-prepare
|
|
73
|
+
|
|
74
|
+
Generated modules start with `# AUTOGENERATED! DO NOT EDIT!` and carry
|
|
75
|
+
`# %% ../jobs/00_core.py #3` markers mapping each block to its cell. Only
|
|
76
|
+
edit inside those blocks, and run --update before changing the notebook.
|
|
77
|
+
|
|
78
|
+
ORGANIZING NOTEBOOKS
|
|
79
|
+
jobs/
|
|
80
|
+
00_core.py #| default_exp core foundations, no internal deps
|
|
81
|
+
01_data.py #| default_exp data may `from mypkg.core import ...`
|
|
82
|
+
02_model.py #| default_exp model
|
|
83
|
+
_scratch.py ignored: names starting with _ or . are skipped
|
|
84
|
+
sub/03_x.py subfolders work (recursive)
|
|
85
|
+
mypkg/ generated; commit it alongside the notebooks
|
|
86
|
+
|
|
87
|
+
- One notebook per module, numbered in dependency order, is the default.
|
|
88
|
+
- One notebook can also fan out into several files with `#| export <mod>`
|
|
89
|
+
(see examples/tinylm: one notebook -> data, tokenizer, model, train).
|
|
90
|
+
- Several notebooks may export into the same module; it is rebuilt whole.
|
|
91
|
+
- Keep notebooks fast: they are your test suite. Mark slow or interactive
|
|
92
|
+
cells `#| eval: false`.
|
|
93
|
+
- After reordering exported cells, run matrace-export before --update
|
|
94
|
+
(cells are matched by position; matrace refuses mismatched updates).
|
|
95
|
+
'''
|
|
96
|
+
|
|
97
|
+
def main_cli(argv=None):
|
|
98
|
+
p = argparse.ArgumentParser('matrace', description=f'matrace {__version__}: nbdev-style literate programming for '
|
|
99
|
+
'marimo notebooks', epilog=GUIDE, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
100
|
+
p.add_argument('--version', action='version', version=__version__)
|
|
101
|
+
p.parse_args(argv)
|
|
102
|
+
p.print_help()
|
|
103
|
+
|
|
104
|
+
def export_cli(argv=None):
|
|
105
|
+
p = argparse.ArgumentParser('matrace-export', description='Export marimo notebooks to Python modules '
|
|
106
|
+
'(like nbdev-export), or with --update sync module edits back (like nbdev-update)')
|
|
107
|
+
p.add_argument('path', nargs='?', help='notebook or directory to export (default: nbs_path); '
|
|
108
|
+
'with --update, a module or directory (default: lib_path)')
|
|
109
|
+
p.add_argument('--update', action='store_true', help='propagate edits in exported modules back to notebooks')
|
|
110
|
+
a = p.parse_args(argv)
|
|
111
|
+
for f in (nb_update if a.update else nb_export)(a.path): print(f'{"updated" if a.update else "exported"} {f}')
|
|
112
|
+
|
|
113
|
+
def clean_cli(argv=None):
|
|
114
|
+
p = argparse.ArgumentParser('matrace-clean', description='Normalize marimo notebooks to avoid merge conflicts')
|
|
115
|
+
p.add_argument('fname', nargs='?', help='notebook or directory to clean (default: nbs_path)')
|
|
116
|
+
p.add_argument('--stdin', action='store_true', help='clean a notebook read from stdin to stdout (git filter)')
|
|
117
|
+
a = p.parse_args(argv)
|
|
118
|
+
if a.stdin: return sys.stdout.write(clean_text(sys.stdin.read()))
|
|
119
|
+
for f in nb_clean(a.fname): print(f'cleaned {f}')
|
|
120
|
+
|
|
121
|
+
def convert_cli(argv=None):
|
|
122
|
+
p = argparse.ArgumentParser('matrace-convert', description='Replay a marimo notebook as a Pi coding-agent rollout '
|
|
123
|
+
'(real tool executions) and write it as Tinker training data for Inkling 2 Small: '
|
|
124
|
+
'pi_session.jsonl, messages.json, sft.jsonl, opd_prompts.jsonl')
|
|
125
|
+
p.add_argument('notebook', help='marimo notebook inside a matrace project')
|
|
126
|
+
p.add_argument('-o', '--out', default='traces', help='output directory (default: traces)')
|
|
127
|
+
p.add_argument('--model', default='thinkingmachines/Inkling-2-Small', help='Tinker model whose renderer to use')
|
|
128
|
+
p.add_argument('--effort', type=float, default=0.0, help='Inkling thinking-effort conditioning in [0, 1). Reasoning '
|
|
129
|
+
'comes only from the notebook\'s markdown and is usually short, so the default is 0')
|
|
130
|
+
p.add_argument('--cwd', default=None, help='working directory shown in the trace (default: /home/user/<project>)')
|
|
131
|
+
p.add_argument('--no-tinker', action='store_true', help='only write the Pi session and chat messages')
|
|
132
|
+
a = p.parse_args(argv)
|
|
133
|
+
tinker = not a.no_tinker
|
|
134
|
+
if tinker:
|
|
135
|
+
try: import tinker_cookbook # noqa: F401
|
|
136
|
+
except ImportError: sys.exit('matrace-convert: Tinker output needs `pip install "mo-trace[tinker]"` (or pass --no-tinker)')
|
|
137
|
+
from .convert import convert
|
|
138
|
+
ro, files = convert(a.notebook, a.out, model=a.model, effort=a.effort, cwd=a.cwd, tinker=tinker)
|
|
139
|
+
n = sum(m['role'] == 'assistant' for m in ro['messages'])
|
|
140
|
+
print(f'{a.notebook}: {n} assistant turns, {n - 1} tool calls')
|
|
141
|
+
for f in files: print(f'wrote {f}')
|
|
142
|
+
|
|
143
|
+
def prepare_cli(argv=None):
|
|
144
|
+
p = argparse.ArgumentParser('matrace-prepare', description='Export, test (in parallel) and clean notebooks')
|
|
145
|
+
p.add_argument('--n_workers', type=int, default=None, help='parallel test processes (default: min(cpus, 8))')
|
|
146
|
+
p.add_argument('--timing', action='store_true', help='print how long each notebook took')
|
|
147
|
+
p.add_argument('--timeout', type=float, default=None, help='seconds before a notebook test is killed')
|
|
148
|
+
a = p.parse_args(argv)
|
|
149
|
+
nb_export()
|
|
150
|
+
if not nb_test(n_workers=a.n_workers, timing=a.timing, timeout=a.timeout): sys.exit(1)
|
|
151
|
+
nb_clean()
|