urml-model 0.5.0__py3-none-any.whl
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.
- urml_model/__init__.py +51 -0
- urml_model/backtranslate.py +216 -0
- urml_model/cli.py +151 -0
- urml_model/dataset.py +118 -0
- urml_model/export.py +101 -0
- urml_model/mining.py +166 -0
- urml_model/py.typed +0 -0
- urml_model/rejections.py +96 -0
- urml_model/synthesize.py +109 -0
- urml_model-0.5.0.dist-info/METADATA +76 -0
- urml_model-0.5.0.dist-info/RECORD +13 -0
- urml_model-0.5.0.dist-info/WHEEL +4 -0
- urml_model-0.5.0.dist-info/entry_points.txt +2 -0
urml_model/__init__.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""urml-model — dataset synthesis pipeline for a URML-native small model (RFC-0666).
|
|
2
|
+
|
|
3
|
+
The validator is the labeling oracle: every (natural language, program,
|
|
4
|
+
manifest) triple in a dataset produced here passed `urml_validator.validate`
|
|
5
|
+
at synthesis time, and every rejected bridge emission becomes a repair
|
|
6
|
+
example carrying the validator's machine-readable error codes.
|
|
7
|
+
|
|
8
|
+
This package never trains a model, never downloads weights, and never
|
|
9
|
+
calls a specific LLM vendor. It mines the repository's gold assets,
|
|
10
|
+
back-translates programs into utterances (deterministic templates in CI,
|
|
11
|
+
any `LLMProvider` at scale), filters through the oracle, and exports the
|
|
12
|
+
formats fine-tuning frameworks consume. The training itself is
|
|
13
|
+
operator-action, documented in ``docs/training-recipe.md``.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from urml_model.backtranslate import BackTranslator, LLMBackTranslator, TemplateBackTranslator
|
|
19
|
+
from urml_model.dataset import Dataset, DatasetRecord, Provenance, ValidatorVerdict
|
|
20
|
+
from urml_model.export import export_dpo, export_sft
|
|
21
|
+
from urml_model.mining import (
|
|
22
|
+
GoldExample,
|
|
23
|
+
mine_few_shot_pairs,
|
|
24
|
+
mine_fixture_programs,
|
|
25
|
+
resolve_envelope_ref,
|
|
26
|
+
resolve_manifest_ref,
|
|
27
|
+
)
|
|
28
|
+
from urml_model.rejections import RejectionSession, mine_rejections, session_from_result
|
|
29
|
+
from urml_model.synthesize import SynthesisReport, synthesize
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"BackTranslator",
|
|
33
|
+
"Dataset",
|
|
34
|
+
"DatasetRecord",
|
|
35
|
+
"GoldExample",
|
|
36
|
+
"LLMBackTranslator",
|
|
37
|
+
"Provenance",
|
|
38
|
+
"RejectionSession",
|
|
39
|
+
"SynthesisReport",
|
|
40
|
+
"TemplateBackTranslator",
|
|
41
|
+
"ValidatorVerdict",
|
|
42
|
+
"export_dpo",
|
|
43
|
+
"export_sft",
|
|
44
|
+
"mine_few_shot_pairs",
|
|
45
|
+
"mine_fixture_programs",
|
|
46
|
+
"mine_rejections",
|
|
47
|
+
"resolve_envelope_ref",
|
|
48
|
+
"resolve_manifest_ref",
|
|
49
|
+
"session_from_result",
|
|
50
|
+
"synthesize",
|
|
51
|
+
]
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
"""Back-translation: produce a natural-language utterance from a gold program (RFC-0666).
|
|
2
|
+
|
|
3
|
+
Fixture programs have no paired utterance. `BackTranslator` is the seam:
|
|
4
|
+
|
|
5
|
+
- `TemplateBackTranslator` renders deterministic English from the program's
|
|
6
|
+
steps. Hermetic, runs in CI, stylistically narrow by design. It exists so
|
|
7
|
+
the pipeline is testable end to end without a network and so the dataset
|
|
8
|
+
floor never depends on an external model.
|
|
9
|
+
- `LLMBackTranslator` asks any `LLMProvider` for paraphrases of the intent
|
|
10
|
+
a program encodes. This is where dataset diversity comes from; running it
|
|
11
|
+
at scale is operator-action. The provider protocol keeps it vendor-neutral.
|
|
12
|
+
|
|
13
|
+
Every candidate utterance goes through the validator oracle downstream
|
|
14
|
+
regardless of which translator produced it.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
from typing import Any, Protocol, runtime_checkable
|
|
21
|
+
|
|
22
|
+
from urml_llm_bridge.providers.base import LLMProvider
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@runtime_checkable
|
|
26
|
+
class BackTranslator(Protocol):
|
|
27
|
+
"""Anything that can phrase a URML program as the instruction that produces it."""
|
|
28
|
+
|
|
29
|
+
def to_utterances(
|
|
30
|
+
self,
|
|
31
|
+
program: dict[str, Any],
|
|
32
|
+
manifest: dict[str, Any],
|
|
33
|
+
*,
|
|
34
|
+
language: str = "en",
|
|
35
|
+
n: int = 1,
|
|
36
|
+
) -> list[str]:
|
|
37
|
+
"""Return up to `n` natural-language utterances for `program`."""
|
|
38
|
+
...
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _fmt_value(value: Any) -> str:
|
|
42
|
+
if isinstance(value, str):
|
|
43
|
+
return value.replace("_", " ")
|
|
44
|
+
return str(value)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _render_step(step: dict[str, Any]) -> str | None:
|
|
48
|
+
"""One clause of imperative English for one primitive step.
|
|
49
|
+
|
|
50
|
+
Unknown primitives return None and are skipped by the caller; the
|
|
51
|
+
template path renders what it knows and never invents phrasing for a
|
|
52
|
+
primitive it has no template for.
|
|
53
|
+
"""
|
|
54
|
+
if len(step) != 1:
|
|
55
|
+
return None
|
|
56
|
+
name, args = next(iter(step.items()))
|
|
57
|
+
if not isinstance(args, dict):
|
|
58
|
+
return None
|
|
59
|
+
match name:
|
|
60
|
+
case "move_to":
|
|
61
|
+
return f"go to {_fmt_value(args.get('location', 'the target'))}"
|
|
62
|
+
case "detect":
|
|
63
|
+
obj = _fmt_value(args.get("object", "the object"))
|
|
64
|
+
attrs = args.get("attributes")
|
|
65
|
+
if isinstance(attrs, dict) and "color" in attrs:
|
|
66
|
+
return f"find a {_fmt_value(attrs['color'])} {obj}"
|
|
67
|
+
return f"find a {obj}"
|
|
68
|
+
case "grasp":
|
|
69
|
+
return "pick it up"
|
|
70
|
+
case "release":
|
|
71
|
+
if args.get("mode") == "hand_to_user":
|
|
72
|
+
return "hand it to me"
|
|
73
|
+
return f"put it down at {_fmt_value(args['at'])}" if "at" in args else "put it down"
|
|
74
|
+
case "take_off":
|
|
75
|
+
alt = args.get("altitude")
|
|
76
|
+
return f"take off to {alt} meters" if alt is not None else "take off"
|
|
77
|
+
case "land":
|
|
78
|
+
return "land"
|
|
79
|
+
case "return_to_home":
|
|
80
|
+
return "return home"
|
|
81
|
+
case "hover":
|
|
82
|
+
over = args.get("over")
|
|
83
|
+
return f"hover over {_fmt_value(over)}" if over else "hover in place"
|
|
84
|
+
case "capture":
|
|
85
|
+
return f"take a {_fmt_value(args.get('media', 'photo'))}"
|
|
86
|
+
case "scan":
|
|
87
|
+
return "scan the area"
|
|
88
|
+
case "measure":
|
|
89
|
+
return f"measure the {_fmt_value(args.get('what', 'reading'))}"
|
|
90
|
+
case "report":
|
|
91
|
+
return "tell me the result" if args.get("to") == "user" else "report the result"
|
|
92
|
+
case "wait_for":
|
|
93
|
+
condition = args.get("condition")
|
|
94
|
+
if isinstance(condition, dict) and "event" in condition:
|
|
95
|
+
return f"wait for {_fmt_value(condition['event'])}"
|
|
96
|
+
return "wait for the condition"
|
|
97
|
+
case "wait_passively":
|
|
98
|
+
duration = args.get("duration")
|
|
99
|
+
return f"wait {_fmt_value(duration)}" if duration else "wait"
|
|
100
|
+
case "dock":
|
|
101
|
+
return f"dock at {_fmt_value(args.get('at', 'the dock'))}"
|
|
102
|
+
case "call_program":
|
|
103
|
+
return f"run the {_fmt_value(args.get('name', 'named'))} program"
|
|
104
|
+
case "speak":
|
|
105
|
+
return f"say {args.get('text', 'something')!r}"
|
|
106
|
+
case "listen":
|
|
107
|
+
return "listen for my reply"
|
|
108
|
+
case "drive":
|
|
109
|
+
if "radius" in args and "arc" in args:
|
|
110
|
+
return f"orbit {args['arc']} degrees with a {args['radius']} meter radius"
|
|
111
|
+
if "arc" in args:
|
|
112
|
+
return f"curve {args['arc']} degrees over {args.get('distance', 0)} meters"
|
|
113
|
+
return f"drive {args.get('distance', 0)} meters"
|
|
114
|
+
case "turn":
|
|
115
|
+
angle = args.get("angle", 0)
|
|
116
|
+
side = "left" if isinstance(angle, (int, float)) and angle >= 0 else "right"
|
|
117
|
+
return f"turn {side} {abs(angle) if isinstance(angle, (int, float)) else angle} degrees"
|
|
118
|
+
case "pick_from":
|
|
119
|
+
return f"pick a {_fmt_value(args.get('object', 'part'))} from {_fmt_value(args.get('source', 'the bin'))}"
|
|
120
|
+
case "place_at":
|
|
121
|
+
return f"place it at {_fmt_value(args.get('destination', 'the target'))}"
|
|
122
|
+
case "swap_tool":
|
|
123
|
+
return f"swap to the {_fmt_value(args.get('tool', 'next'))} tool"
|
|
124
|
+
case "set_output":
|
|
125
|
+
return f"set output {_fmt_value(args.get('line', ''))}".strip()
|
|
126
|
+
case "follow_trajectory" | "plan_trajectory":
|
|
127
|
+
return "follow the planned route"
|
|
128
|
+
case _:
|
|
129
|
+
return None
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _collect_clauses(node: Any) -> list[str]:
|
|
133
|
+
"""Walk a behavior tree and collect renderable clauses in order."""
|
|
134
|
+
clauses: list[str] = []
|
|
135
|
+
if isinstance(node, dict):
|
|
136
|
+
steps = node.get("steps")
|
|
137
|
+
branches = node.get("branches")
|
|
138
|
+
body = node.get("body")
|
|
139
|
+
if isinstance(steps, list):
|
|
140
|
+
for step in steps:
|
|
141
|
+
clauses.extend(_collect_clauses(step))
|
|
142
|
+
elif isinstance(branches, list):
|
|
143
|
+
for branch in branches:
|
|
144
|
+
clauses.extend(_collect_clauses(branch))
|
|
145
|
+
elif isinstance(body, dict):
|
|
146
|
+
clauses.extend(_collect_clauses(body))
|
|
147
|
+
else:
|
|
148
|
+
rendered = _render_step(node)
|
|
149
|
+
if rendered is not None:
|
|
150
|
+
clauses.append(rendered)
|
|
151
|
+
return clauses
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class TemplateBackTranslator:
|
|
155
|
+
"""Deterministic English rendering of a program's step sequence.
|
|
156
|
+
|
|
157
|
+
English only; other languages take the LLM path (RFC-0666 Unresolved
|
|
158
|
+
questions). Returns at most one utterance regardless of `n`, because a
|
|
159
|
+
template has exactly one way to say a thing.
|
|
160
|
+
"""
|
|
161
|
+
|
|
162
|
+
def to_utterances(
|
|
163
|
+
self,
|
|
164
|
+
program: dict[str, Any],
|
|
165
|
+
manifest: dict[str, Any],
|
|
166
|
+
*,
|
|
167
|
+
language: str = "en",
|
|
168
|
+
n: int = 1,
|
|
169
|
+
) -> list[str]:
|
|
170
|
+
if language != "en":
|
|
171
|
+
return []
|
|
172
|
+
clauses = _collect_clauses(program.get("behavior", {}))
|
|
173
|
+
if not clauses:
|
|
174
|
+
return []
|
|
175
|
+
if len(clauses) == 1:
|
|
176
|
+
sentence = clauses[0]
|
|
177
|
+
else:
|
|
178
|
+
sentence = ", ".join(clauses[:-1]) + f", then {clauses[-1]}"
|
|
179
|
+
return [sentence[0].upper() + sentence[1:] + "."]
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
_BACKTRANSLATE_SYSTEM = """\
|
|
183
|
+
You reverse-translate robot programs into the instruction a person would have
|
|
184
|
+
given to produce them. You will receive a URML program (JSON). Reply with a
|
|
185
|
+
JSON array of {n} distinct natural-language instructions in {language}, each a
|
|
186
|
+
single sentence a non-programmer might say, each fully implied by the program:
|
|
187
|
+
no added goals, no dropped steps. Reply with the JSON array only."""
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class LLMBackTranslator:
|
|
191
|
+
"""Paraphrase-diverse back-translation through any `LLMProvider`."""
|
|
192
|
+
|
|
193
|
+
def __init__(self, provider: LLMProvider) -> None:
|
|
194
|
+
self._provider = provider
|
|
195
|
+
|
|
196
|
+
def to_utterances(
|
|
197
|
+
self,
|
|
198
|
+
program: dict[str, Any],
|
|
199
|
+
manifest: dict[str, Any],
|
|
200
|
+
*,
|
|
201
|
+
language: str = "en",
|
|
202
|
+
n: int = 1,
|
|
203
|
+
) -> list[str]:
|
|
204
|
+
system = _BACKTRANSLATE_SYSTEM.format(n=n, language=language)
|
|
205
|
+
raw = self._provider.complete(
|
|
206
|
+
system=system,
|
|
207
|
+
user=json.dumps(program, sort_keys=True),
|
|
208
|
+
schema={"type": "array", "items": {"type": "string"}},
|
|
209
|
+
)
|
|
210
|
+
try:
|
|
211
|
+
parsed = json.loads(raw)
|
|
212
|
+
except json.JSONDecodeError:
|
|
213
|
+
return []
|
|
214
|
+
if not isinstance(parsed, list):
|
|
215
|
+
return []
|
|
216
|
+
return [item.strip() for item in parsed if isinstance(item, str) and item.strip()][:n]
|
urml_model/cli.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""urml-model — synthesize, export, and evaluate the URML-native model dataset (RFC-0666).
|
|
2
|
+
|
|
3
|
+
Three subcommands:
|
|
4
|
+
|
|
5
|
+
- ``urml-model synthesize --out data.jsonl`` mines the repo's gold assets
|
|
6
|
+
(conformance fixtures + few-shot library), back-translates fixture
|
|
7
|
+
programs with the deterministic template renderer, filters everything
|
|
8
|
+
through the validator oracle, and writes the dataset. Hermetic: no
|
|
9
|
+
network, no LLM.
|
|
10
|
+
- ``urml-model export --in data.jsonl --out sft.jsonl --fmt chatml`` writes
|
|
11
|
+
training files (chatml / completions / dpo).
|
|
12
|
+
- ``urml-model eval`` scores any local or canned model against a profile's
|
|
13
|
+
utterance set with the conformance scorer and writes the ResultRow YAML.
|
|
14
|
+
The LLM back-translation path (dataset diversity at scale) is a library
|
|
15
|
+
call, not a CLI flag: it needs an operator-configured provider and spend.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import argparse
|
|
21
|
+
import dataclasses
|
|
22
|
+
import json
|
|
23
|
+
import sys
|
|
24
|
+
from datetime import UTC, datetime
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
import yaml
|
|
29
|
+
|
|
30
|
+
from urml_model.backtranslate import TemplateBackTranslator
|
|
31
|
+
from urml_model.dataset import Dataset
|
|
32
|
+
from urml_model.export import export_dpo, export_sft
|
|
33
|
+
from urml_model.mining import mine_few_shot_pairs, mine_fixture_programs, resolve_manifest_ref
|
|
34
|
+
from urml_model.synthesize import synthesize
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _cmd_synthesize(args: argparse.Namespace) -> int:
|
|
38
|
+
profiles = tuple(args.profile or ())
|
|
39
|
+
gold = []
|
|
40
|
+
if not args.no_fixtures:
|
|
41
|
+
gold.extend(mine_fixture_programs(profiles=profiles))
|
|
42
|
+
if not args.no_few_shots:
|
|
43
|
+
gold.extend(mine_few_shot_pairs(profiles=profiles))
|
|
44
|
+
dataset, report = synthesize(gold, TemplateBackTranslator(), per_program=args.per_program)
|
|
45
|
+
count = dataset.write_jsonl(Path(args.out))
|
|
46
|
+
print(report.summary())
|
|
47
|
+
print(f"wrote {count} record(s) to {args.out}")
|
|
48
|
+
return 0
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _cmd_export(args: argparse.Namespace) -> int:
|
|
52
|
+
dataset = Dataset.read_jsonl(Path(args.infile))
|
|
53
|
+
out = Path(args.out)
|
|
54
|
+
if args.fmt == "dpo":
|
|
55
|
+
count = export_dpo(dataset, out)
|
|
56
|
+
else:
|
|
57
|
+
count = export_sft(dataset, out, fmt=args.fmt)
|
|
58
|
+
print(f"wrote {count} {args.fmt} example(s) to {out}")
|
|
59
|
+
return 0
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _build_eval_provider(args: argparse.Namespace) -> Any:
|
|
63
|
+
if args.backend == "echo":
|
|
64
|
+
if not args.echo_responses:
|
|
65
|
+
raise SystemExit("--backend echo requires --echo-responses (JSON map of utterance -> emission)")
|
|
66
|
+
with Path(args.echo_responses).open(encoding="utf-8") as fh:
|
|
67
|
+
responses = json.load(fh)
|
|
68
|
+
if not isinstance(responses, dict):
|
|
69
|
+
raise SystemExit("--echo-responses must contain a JSON object")
|
|
70
|
+
from urml_llm_bridge.providers.echo import EchoProvider
|
|
71
|
+
|
|
72
|
+
return EchoProvider(responses={str(k): str(v) for k, v in responses.items()})
|
|
73
|
+
if args.backend == "ollama":
|
|
74
|
+
from urml_llm_bridge.providers.ollama import OllamaProvider
|
|
75
|
+
|
|
76
|
+
return OllamaProvider(model=args.model)
|
|
77
|
+
from urml_llm_bridge.providers.llama_cpp import LlamaCppProvider
|
|
78
|
+
|
|
79
|
+
return LlamaCppProvider(model_label=args.model)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _cmd_eval(args: argparse.Namespace) -> int:
|
|
83
|
+
from urml_conformance.llm_bridge.loader import load_utterances
|
|
84
|
+
from urml_conformance.llm_bridge.scorer import score
|
|
85
|
+
|
|
86
|
+
utterances = load_utterances(Path(args.utterances_root), profile=args.profile, language=args.language)
|
|
87
|
+
manifest = resolve_manifest_ref(utterances.manifest)
|
|
88
|
+
recorded_at = args.recorded_at or datetime.now(UTC).isoformat(timespec="seconds")
|
|
89
|
+
row = score(
|
|
90
|
+
provider=_build_eval_provider(args),
|
|
91
|
+
utterances=utterances,
|
|
92
|
+
manifest=manifest,
|
|
93
|
+
backend=args.backend,
|
|
94
|
+
model_id=args.model,
|
|
95
|
+
recorded_at=recorded_at,
|
|
96
|
+
max_revisions=args.max_revisions,
|
|
97
|
+
)
|
|
98
|
+
payload = dataclasses.asdict(row)
|
|
99
|
+
out = Path(args.out)
|
|
100
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
101
|
+
with out.open("w", encoding="utf-8", newline="\n") as fh:
|
|
102
|
+
yaml.safe_dump(payload, fh, sort_keys=True)
|
|
103
|
+
print(
|
|
104
|
+
f"{row.model_id} on {row.profile}: structural {row.structural_pass_rate}, "
|
|
105
|
+
f"semantic {row.semantic_pass_rate}, revisions {row.revision_attempts_mean}"
|
|
106
|
+
)
|
|
107
|
+
print(f"wrote {out}")
|
|
108
|
+
return 0
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
112
|
+
parser = argparse.ArgumentParser(prog="urml-model", description=__doc__)
|
|
113
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
114
|
+
|
|
115
|
+
p_syn = sub.add_parser("synthesize", help="mine + back-translate + oracle-filter into a dataset JSONL")
|
|
116
|
+
p_syn.add_argument("--out", required=True, help="output dataset JSONL path")
|
|
117
|
+
p_syn.add_argument("--profile", action="append", help="restrict to a profile (repeatable)")
|
|
118
|
+
p_syn.add_argument("--per-program", type=int, default=1, help="utterances per fixture program")
|
|
119
|
+
p_syn.add_argument("--no-fixtures", action="store_true", help="skip conformance-fixture mining")
|
|
120
|
+
p_syn.add_argument("--no-few-shots", action="store_true", help="skip the few-shot library")
|
|
121
|
+
p_syn.set_defaults(func=_cmd_synthesize)
|
|
122
|
+
|
|
123
|
+
p_exp = sub.add_parser("export", help="write SFT/DPO training files from a dataset JSONL")
|
|
124
|
+
p_exp.add_argument("--in", dest="infile", required=True, help="input dataset JSONL")
|
|
125
|
+
p_exp.add_argument("--out", required=True, help="output path")
|
|
126
|
+
p_exp.add_argument("--fmt", choices=("chatml", "completions", "dpo"), default="chatml")
|
|
127
|
+
p_exp.set_defaults(func=_cmd_export)
|
|
128
|
+
|
|
129
|
+
p_eval = sub.add_parser("eval", help="score a model against an utterance set (conformance scorer)")
|
|
130
|
+
p_eval.add_argument("--utterances-root", required=True, help="root dir holding <profile>/utterances-<lang>.yaml")
|
|
131
|
+
p_eval.add_argument("--profile", required=True)
|
|
132
|
+
p_eval.add_argument("--language", default="en")
|
|
133
|
+
p_eval.add_argument("--backend", choices=("echo", "ollama", "llama_cpp"), required=True)
|
|
134
|
+
p_eval.add_argument("--model", required=True, help="model id label for the result row")
|
|
135
|
+
p_eval.add_argument("--out", required=True, help="output ResultRow YAML path")
|
|
136
|
+
p_eval.add_argument("--max-revisions", type=int, default=3)
|
|
137
|
+
p_eval.add_argument("--recorded-at", help="ISO timestamp for the row (defaults to now, UTC)")
|
|
138
|
+
p_eval.add_argument("--echo-responses", help="echo backend: JSON file mapping utterance -> emission")
|
|
139
|
+
p_eval.set_defaults(func=_cmd_eval)
|
|
140
|
+
|
|
141
|
+
return parser
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def main(argv: list[str] | None = None) -> int:
|
|
145
|
+
args = build_parser().parse_args(argv)
|
|
146
|
+
result: int = args.func(args)
|
|
147
|
+
return result
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
if __name__ == "__main__":
|
|
151
|
+
sys.exit(main())
|
urml_model/dataset.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Dataset records and JSONL persistence (RFC-0666).
|
|
2
|
+
|
|
3
|
+
The record schema here is the normative surface of RFC-0666: a dataset is
|
|
4
|
+
a JSONL file, one `DatasetRecord` per line. Records with a rejected
|
|
5
|
+
`validator_verdict` are permitted only for `rejection_repair` provenance,
|
|
6
|
+
where the rejected program plus the validator's error codes are the
|
|
7
|
+
training signal and `repair` carries the accepted target.
|
|
8
|
+
|
|
9
|
+
Everything else in the pipeline (mining, back-translation, synthesis,
|
|
10
|
+
export) produces or consumes this shape.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
from collections.abc import Iterable, Iterator
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any, Literal
|
|
19
|
+
|
|
20
|
+
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
|
21
|
+
|
|
22
|
+
Provenance = Literal[
|
|
23
|
+
"few_shot",
|
|
24
|
+
"fixture_backtranslation",
|
|
25
|
+
"llm_backtranslation",
|
|
26
|
+
"rejection_repair",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class ValidatorVerdict(BaseModel):
|
|
31
|
+
"""The validator's verdict for a record's program, measured at synthesis time."""
|
|
32
|
+
|
|
33
|
+
model_config = ConfigDict(extra="forbid")
|
|
34
|
+
|
|
35
|
+
accepted: bool
|
|
36
|
+
error_codes: list[str] = Field(default_factory=list)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class DatasetRecord(BaseModel):
|
|
40
|
+
"""One (natural language, program, manifest) training example."""
|
|
41
|
+
|
|
42
|
+
model_config = ConfigDict(extra="forbid")
|
|
43
|
+
|
|
44
|
+
nl: str
|
|
45
|
+
program: dict[str, Any]
|
|
46
|
+
manifest_ref: str
|
|
47
|
+
profile: str
|
|
48
|
+
language: str = "en"
|
|
49
|
+
provenance: Provenance
|
|
50
|
+
validator_verdict: ValidatorVerdict
|
|
51
|
+
envelope_ref: str | None = None
|
|
52
|
+
repair: dict[str, Any] | None = None
|
|
53
|
+
|
|
54
|
+
@model_validator(mode="after")
|
|
55
|
+
def _rejected_only_for_repair(self) -> DatasetRecord:
|
|
56
|
+
if not self.validator_verdict.accepted:
|
|
57
|
+
if self.provenance != "rejection_repair":
|
|
58
|
+
raise ValueError(
|
|
59
|
+
"a rejected program is only allowed with provenance "
|
|
60
|
+
"'rejection_repair'; every other record must be validator-accepted"
|
|
61
|
+
)
|
|
62
|
+
if self.repair is None:
|
|
63
|
+
raise ValueError("a rejection_repair record must carry the accepted program in `repair`")
|
|
64
|
+
return self
|
|
65
|
+
|
|
66
|
+
def dedup_key(self) -> tuple[str, str]:
|
|
67
|
+
"""Stable identity for deduplication: the utterance plus the canonical program JSON."""
|
|
68
|
+
return self.nl, json.dumps(self.program, sort_keys=True, separators=(",", ":"))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class Dataset(BaseModel):
|
|
72
|
+
"""An ordered collection of records with JSONL persistence."""
|
|
73
|
+
|
|
74
|
+
model_config = ConfigDict(extra="forbid")
|
|
75
|
+
|
|
76
|
+
records: list[DatasetRecord] = Field(default_factory=list)
|
|
77
|
+
|
|
78
|
+
def __len__(self) -> int:
|
|
79
|
+
return len(self.records)
|
|
80
|
+
|
|
81
|
+
def __iter__(self) -> Iterator[DatasetRecord]: # type: ignore[override]
|
|
82
|
+
return iter(self.records)
|
|
83
|
+
|
|
84
|
+
def extend(self, records: Iterable[DatasetRecord]) -> None:
|
|
85
|
+
self.records.extend(records)
|
|
86
|
+
|
|
87
|
+
def accepted(self) -> list[DatasetRecord]:
|
|
88
|
+
"""Records whose program the validator accepted."""
|
|
89
|
+
return [r for r in self.records if r.validator_verdict.accepted]
|
|
90
|
+
|
|
91
|
+
def repairs(self) -> list[DatasetRecord]:
|
|
92
|
+
"""The rejection_repair records (rejected program + accepted target)."""
|
|
93
|
+
return [r for r in self.records if r.provenance == "rejection_repair"]
|
|
94
|
+
|
|
95
|
+
def write_jsonl(self, path: Path) -> int:
|
|
96
|
+
"""Write one record per line; returns the record count."""
|
|
97
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
98
|
+
with path.open("w", encoding="utf-8", newline="\n") as fh:
|
|
99
|
+
for record in self.records:
|
|
100
|
+
fh.write(json.dumps(record.model_dump(exclude_none=True), sort_keys=True))
|
|
101
|
+
fh.write("\n")
|
|
102
|
+
return len(self.records)
|
|
103
|
+
|
|
104
|
+
@classmethod
|
|
105
|
+
def read_jsonl(cls, path: Path) -> Dataset:
|
|
106
|
+
"""Parse a JSONL file back into a Dataset, validating every line."""
|
|
107
|
+
records: list[DatasetRecord] = []
|
|
108
|
+
with path.open(encoding="utf-8") as fh:
|
|
109
|
+
for line_no, line in enumerate(fh, start=1):
|
|
110
|
+
line = line.strip()
|
|
111
|
+
if not line:
|
|
112
|
+
continue
|
|
113
|
+
try:
|
|
114
|
+
payload = json.loads(line)
|
|
115
|
+
except json.JSONDecodeError as exc:
|
|
116
|
+
raise ValueError(f"{path}:{line_no}: not valid JSON: {exc}") from exc
|
|
117
|
+
records.append(DatasetRecord.model_validate(payload))
|
|
118
|
+
return cls(records=records)
|
urml_model/export.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Export a dataset in the formats fine-tuning frameworks consume (RFC-0666).
|
|
2
|
+
|
|
3
|
+
Two families:
|
|
4
|
+
|
|
5
|
+
- `export_sft()` — supervised fine-tuning examples from the accepted
|
|
6
|
+
records. The `chatml` format rebuilds the bridge's real system prompt for
|
|
7
|
+
each record's manifest so the model trains on exactly the prompt shape
|
|
8
|
+
the bridge hands it at inference time. The `completions` format is the
|
|
9
|
+
bare (utterance, program) pair for frameworks that template their own
|
|
10
|
+
prompts.
|
|
11
|
+
- `export_dpo()` — (prompt, chosen, rejected) preference triples from the
|
|
12
|
+
rejection_repair records.
|
|
13
|
+
|
|
14
|
+
Assistant targets are compact JSON: that is what the bridge parses back.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any, Literal
|
|
22
|
+
|
|
23
|
+
from urml_llm_bridge.few_shot import few_shots_for
|
|
24
|
+
from urml_llm_bridge.prompt import build_system_prompt
|
|
25
|
+
from urml_validator import export_schema
|
|
26
|
+
|
|
27
|
+
from urml_model.dataset import Dataset
|
|
28
|
+
from urml_model.mining import resolve_envelope_ref, resolve_manifest_ref
|
|
29
|
+
|
|
30
|
+
SftFormat = Literal["chatml", "completions"]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _compact(program: dict[str, Any]) -> str:
|
|
34
|
+
return json.dumps(program, sort_keys=True, separators=(",", ":"))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _system_prompt_for(manifest_ref: str, envelope_ref: str | None, profile: str) -> str:
|
|
38
|
+
manifest = resolve_manifest_ref(manifest_ref)
|
|
39
|
+
envelope = resolve_envelope_ref(envelope_ref)
|
|
40
|
+
return build_system_prompt(
|
|
41
|
+
schema=export_schema("program"),
|
|
42
|
+
manifest=manifest,
|
|
43
|
+
envelope=envelope,
|
|
44
|
+
profiles=(profile,),
|
|
45
|
+
few_shots=few_shots_for((profile,)),
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def export_sft(dataset: Dataset, path: Path, *, fmt: SftFormat = "chatml") -> int:
|
|
50
|
+
"""Write accepted records as SFT examples; returns the example count.
|
|
51
|
+
|
|
52
|
+
System prompts are cached per (manifest_ref, envelope_ref, profile) so
|
|
53
|
+
exporting a large dataset does not rebuild identical prompts per line.
|
|
54
|
+
"""
|
|
55
|
+
prompt_cache: dict[tuple[str, str | None, str], str] = {}
|
|
56
|
+
count = 0
|
|
57
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
58
|
+
with path.open("w", encoding="utf-8", newline="\n") as fh:
|
|
59
|
+
for record in dataset.accepted():
|
|
60
|
+
if fmt == "chatml":
|
|
61
|
+
key = (record.manifest_ref, record.envelope_ref, record.profile)
|
|
62
|
+
if key not in prompt_cache:
|
|
63
|
+
prompt_cache[key] = _system_prompt_for(*key)
|
|
64
|
+
payload: dict[str, Any] = {
|
|
65
|
+
"messages": [
|
|
66
|
+
{"role": "system", "content": prompt_cache[key]},
|
|
67
|
+
{"role": "user", "content": record.nl},
|
|
68
|
+
{"role": "assistant", "content": _compact(record.program)},
|
|
69
|
+
]
|
|
70
|
+
}
|
|
71
|
+
else:
|
|
72
|
+
payload = {"prompt": record.nl, "completion": _compact(record.program)}
|
|
73
|
+
fh.write(json.dumps(payload, sort_keys=True))
|
|
74
|
+
fh.write("\n")
|
|
75
|
+
count += 1
|
|
76
|
+
return count
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def export_dpo(dataset: Dataset, path: Path) -> int:
|
|
80
|
+
"""Write rejection_repair records as DPO preference triples; returns the count."""
|
|
81
|
+
prompt_cache: dict[tuple[str, str | None, str], str] = {}
|
|
82
|
+
count = 0
|
|
83
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
84
|
+
with path.open("w", encoding="utf-8", newline="\n") as fh:
|
|
85
|
+
for record in dataset.repairs():
|
|
86
|
+
if record.repair is None:
|
|
87
|
+
continue
|
|
88
|
+
key = (record.manifest_ref, record.envelope_ref, record.profile)
|
|
89
|
+
if key not in prompt_cache:
|
|
90
|
+
prompt_cache[key] = _system_prompt_for(*key)
|
|
91
|
+
payload = {
|
|
92
|
+
"system": prompt_cache[key],
|
|
93
|
+
"prompt": record.nl,
|
|
94
|
+
"chosen": _compact(record.repair),
|
|
95
|
+
"rejected": _compact(record.program),
|
|
96
|
+
"rejected_error_codes": record.validator_verdict.error_codes,
|
|
97
|
+
}
|
|
98
|
+
fh.write(json.dumps(payload, sort_keys=True))
|
|
99
|
+
fh.write("\n")
|
|
100
|
+
count += 1
|
|
101
|
+
return count
|
urml_model/mining.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""Mine gold (program, manifest) material out of the repository's fixtures (RFC-0666).
|
|
2
|
+
|
|
3
|
+
Two sources:
|
|
4
|
+
|
|
5
|
+
- `mine_fixture_programs()` — every validator-accepted single-robot case in
|
|
6
|
+
the conformance suite. These are gold programs with no paired utterance;
|
|
7
|
+
back-translation supplies one downstream.
|
|
8
|
+
- `mine_few_shot_pairs()` — the curated few-shot library from the LLM
|
|
9
|
+
bridge. These already carry natural language and enter the dataset with
|
|
10
|
+
`provenance: few_shot`.
|
|
11
|
+
|
|
12
|
+
Both yield `GoldExample`, the pre-synthesis shape: the program, the fully
|
|
13
|
+
resolved validation context (manifest, envelope, policy, profile), and the
|
|
14
|
+
registry names that let a dataset record stay reproducible by reference.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any, Literal
|
|
22
|
+
|
|
23
|
+
import yaml
|
|
24
|
+
from urml_conformance.fixtures import (
|
|
25
|
+
ENVELOPE_REGISTRY,
|
|
26
|
+
MANIFEST_REGISTRY,
|
|
27
|
+
discover_fixtures,
|
|
28
|
+
resolve_envelope,
|
|
29
|
+
resolve_manifest,
|
|
30
|
+
resolve_policy,
|
|
31
|
+
)
|
|
32
|
+
from urml_llm_bridge.few_shot import (
|
|
33
|
+
drone_few_shots,
|
|
34
|
+
educational_few_shots,
|
|
35
|
+
home_few_shots,
|
|
36
|
+
industrial_few_shots,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
PolicyArg = dict[str, Any] | None | Literal["DEFAULT"]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class GoldExample:
|
|
44
|
+
"""One gold program plus everything needed to re-validate it."""
|
|
45
|
+
|
|
46
|
+
program: dict[str, Any]
|
|
47
|
+
manifest: dict[str, Any]
|
|
48
|
+
manifest_ref: str
|
|
49
|
+
profile: str
|
|
50
|
+
source: str
|
|
51
|
+
envelope: dict[str, Any] | None = None
|
|
52
|
+
envelope_ref: str | None = None
|
|
53
|
+
policy: PolicyArg = "DEFAULT"
|
|
54
|
+
nl: str | None = None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _validator_manifests_dir() -> Path:
|
|
58
|
+
"""The validator's manifest fixture directory, located via the public registry."""
|
|
59
|
+
return MANIFEST_REGISTRY["turtlebot4_home"].parent
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def resolve_manifest_ref(name: str) -> dict[str, Any]:
|
|
63
|
+
"""Resolve a manifest name against the conformance registry, then the validator fixtures.
|
|
64
|
+
|
|
65
|
+
The conformance `MANIFEST_REGISTRY` is the primary namespace. A few
|
|
66
|
+
canonical manifests (the few-shot library's educational buggy) live in
|
|
67
|
+
the validator's fixture directory without a registry entry; those
|
|
68
|
+
resolve by file stem as a fallback.
|
|
69
|
+
"""
|
|
70
|
+
if name in MANIFEST_REGISTRY:
|
|
71
|
+
return resolve_manifest(name)
|
|
72
|
+
candidate = _validator_manifests_dir() / f"{name}.yaml"
|
|
73
|
+
if candidate.is_file():
|
|
74
|
+
with candidate.open(encoding="utf-8") as fh:
|
|
75
|
+
loaded = yaml.safe_load(fh)
|
|
76
|
+
if not isinstance(loaded, dict):
|
|
77
|
+
raise ValueError(f"manifest {name!r} did not parse as a mapping")
|
|
78
|
+
return loaded
|
|
79
|
+
raise KeyError(f"unknown manifest {name!r}: not in MANIFEST_REGISTRY and no validator fixture stem matches")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def resolve_envelope_ref(name: str | None) -> dict[str, Any] | None:
|
|
83
|
+
"""Resolve an envelope name against the conformance registry; None passes through."""
|
|
84
|
+
if name is None:
|
|
85
|
+
return None
|
|
86
|
+
if name in ENVELOPE_REGISTRY:
|
|
87
|
+
return resolve_envelope(name)
|
|
88
|
+
raise KeyError(f"unknown envelope {name!r}; registered: {sorted(ENVELOPE_REGISTRY.keys())!r}")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def mine_fixture_programs(*, profiles: tuple[str, ...] = ()) -> list[GoldExample]:
|
|
92
|
+
"""Every validator-accepted single-robot conformance case as a GoldExample.
|
|
93
|
+
|
|
94
|
+
Fleet cases (RFC-0286 rosters) are excluded in v1: they validate with
|
|
95
|
+
`validate_fleet` and need a fleet-aware prompt shape (RFC-0666
|
|
96
|
+
Unresolved questions). Pass `profiles` to keep only those profiles.
|
|
97
|
+
"""
|
|
98
|
+
out: list[GoldExample] = []
|
|
99
|
+
for case in discover_fixtures():
|
|
100
|
+
if case.roster is not None or case.manifest is None:
|
|
101
|
+
continue
|
|
102
|
+
if not case.expected_validation.accepted:
|
|
103
|
+
continue
|
|
104
|
+
if case.uses_rulebook_fields:
|
|
105
|
+
# RFC-0702: a GoldExample carries no rulebooks, and a program a
|
|
106
|
+
# deployment rulebook allows (a take-off under a waiver) is not
|
|
107
|
+
# gold for every deployment.
|
|
108
|
+
continue
|
|
109
|
+
profile = case.profiles[0] if case.profiles else str(case.program.get("profile", "home"))
|
|
110
|
+
if profiles and profile not in profiles:
|
|
111
|
+
continue
|
|
112
|
+
out.append(
|
|
113
|
+
GoldExample(
|
|
114
|
+
program=case.program,
|
|
115
|
+
manifest=resolve_manifest(case.manifest),
|
|
116
|
+
manifest_ref=case.manifest,
|
|
117
|
+
profile=profile,
|
|
118
|
+
source=case.name,
|
|
119
|
+
envelope=resolve_envelope_ref(case.envelope),
|
|
120
|
+
envelope_ref=case.envelope,
|
|
121
|
+
policy=resolve_policy(case.policy),
|
|
122
|
+
)
|
|
123
|
+
)
|
|
124
|
+
return out
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
# Profile -> (manifest name, envelope name). Mirrors the pairings that
|
|
128
|
+
# `test_few_shot_library.py` asserts every few-shot validates against.
|
|
129
|
+
# The fleet set is excluded for the same reason fleet fixtures are.
|
|
130
|
+
_FEW_SHOT_CONTEXT: dict[str, tuple[str, str | None]] = {
|
|
131
|
+
"home": ("turtlebot4_home", "home_default"),
|
|
132
|
+
"industrial": ("industrial_cell", None),
|
|
133
|
+
"drone": ("drone_civilian", "drone_default"),
|
|
134
|
+
"educational": ("educational_buggy", None),
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def mine_few_shot_pairs(*, profiles: tuple[str, ...] = ()) -> list[GoldExample]:
|
|
139
|
+
"""The curated few-shot library as (utterance, program) GoldExamples."""
|
|
140
|
+
factories = {
|
|
141
|
+
"home": home_few_shots,
|
|
142
|
+
"industrial": industrial_few_shots,
|
|
143
|
+
"drone": drone_few_shots,
|
|
144
|
+
"educational": educational_few_shots,
|
|
145
|
+
}
|
|
146
|
+
out: list[GoldExample] = []
|
|
147
|
+
for profile, factory in factories.items():
|
|
148
|
+
if profiles and profile not in profiles:
|
|
149
|
+
continue
|
|
150
|
+
manifest_ref, envelope_ref = _FEW_SHOT_CONTEXT[profile]
|
|
151
|
+
manifest = resolve_manifest_ref(manifest_ref)
|
|
152
|
+
envelope = resolve_envelope_ref(envelope_ref)
|
|
153
|
+
for shot in factory():
|
|
154
|
+
out.append(
|
|
155
|
+
GoldExample(
|
|
156
|
+
program=shot.program,
|
|
157
|
+
manifest=manifest,
|
|
158
|
+
manifest_ref=manifest_ref,
|
|
159
|
+
profile=profile,
|
|
160
|
+
source=f"few_shot:{profile}",
|
|
161
|
+
envelope=envelope,
|
|
162
|
+
envelope_ref=envelope_ref,
|
|
163
|
+
nl=shot.user,
|
|
164
|
+
)
|
|
165
|
+
)
|
|
166
|
+
return out
|
urml_model/py.typed
ADDED
|
File without changes
|
urml_model/rejections.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""Mine rejected bridge emissions into repair training records (RFC-0666).
|
|
2
|
+
|
|
3
|
+
A bridge translation session that needed revisions is a free preference
|
|
4
|
+
signal: the failed attempts (with the validator's error codes for each)
|
|
5
|
+
versus the finally accepted program, all for the same utterance. This
|
|
6
|
+
module turns those sessions into `rejection_repair` records, exportable as
|
|
7
|
+
SFT-with-error-context or DPO preference pairs.
|
|
8
|
+
|
|
9
|
+
`TranslateResult.raw_completions` carries every attempt, not just the last
|
|
10
|
+
(the CLI's `--save-rejected` persists only the final one; consume the
|
|
11
|
+
result object programmatically to get the full trace).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from urml_llm_bridge.bridge import TranslateResult
|
|
21
|
+
from urml_validator import validate
|
|
22
|
+
|
|
23
|
+
from urml_model.dataset import DatasetRecord, ValidatorVerdict
|
|
24
|
+
from urml_model.mining import PolicyArg
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class RejectionSession:
|
|
29
|
+
"""One bridge translation session: the utterance, every raw attempt, the outcome."""
|
|
30
|
+
|
|
31
|
+
nl: str
|
|
32
|
+
raw_completions: tuple[str, ...]
|
|
33
|
+
accepted_program: dict[str, Any] | None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def session_from_result(nl: str, result: TranslateResult) -> RejectionSession:
|
|
37
|
+
"""Build a session from a successful `Bridge.translate()` result.
|
|
38
|
+
|
|
39
|
+
When the result was accepted after revisions, everything before the
|
|
40
|
+
last completion is a failed attempt. An exhausted or policy-violating
|
|
41
|
+
session (the bridge raised) has no accepted program; build the session
|
|
42
|
+
from the exception's `raw_completions` directly with
|
|
43
|
+
`RejectionSession(nl, tuple(exc.raw_completions), None)`.
|
|
44
|
+
"""
|
|
45
|
+
raw = tuple(result.raw_completions)
|
|
46
|
+
if result.accepted and result.program is not None:
|
|
47
|
+
return RejectionSession(nl=nl, raw_completions=raw[:-1], accepted_program=result.program)
|
|
48
|
+
return RejectionSession(nl=nl, raw_completions=raw, accepted_program=None)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def mine_rejections(
|
|
52
|
+
sessions: list[RejectionSession],
|
|
53
|
+
*,
|
|
54
|
+
manifest: dict[str, Any],
|
|
55
|
+
manifest_ref: str,
|
|
56
|
+
profile: str,
|
|
57
|
+
envelope: dict[str, Any] | None = None,
|
|
58
|
+
envelope_ref: str | None = None,
|
|
59
|
+
policy: PolicyArg = "DEFAULT",
|
|
60
|
+
language: str = "en",
|
|
61
|
+
) -> list[DatasetRecord]:
|
|
62
|
+
"""Turn revision sessions into rejection_repair records.
|
|
63
|
+
|
|
64
|
+
Sessions without an accepted program are skipped: a repair record needs
|
|
65
|
+
a repair target. Attempts that do not parse as JSON are skipped too
|
|
66
|
+
(the record schema requires a program object); the parse failure itself
|
|
67
|
+
is a decoding concern the GBNF grammar path already solves.
|
|
68
|
+
"""
|
|
69
|
+
records: list[DatasetRecord] = []
|
|
70
|
+
for session in sessions:
|
|
71
|
+
if session.accepted_program is None:
|
|
72
|
+
continue
|
|
73
|
+
for raw in session.raw_completions:
|
|
74
|
+
try:
|
|
75
|
+
program = json.loads(raw)
|
|
76
|
+
except json.JSONDecodeError:
|
|
77
|
+
continue
|
|
78
|
+
if not isinstance(program, dict):
|
|
79
|
+
continue
|
|
80
|
+
verdict = validate(program, manifest, envelope, profiles=(profile,), policy=policy)
|
|
81
|
+
if verdict.accepted:
|
|
82
|
+
continue
|
|
83
|
+
records.append(
|
|
84
|
+
DatasetRecord(
|
|
85
|
+
nl=session.nl,
|
|
86
|
+
program=program,
|
|
87
|
+
manifest_ref=manifest_ref,
|
|
88
|
+
profile=profile,
|
|
89
|
+
language=language,
|
|
90
|
+
provenance="rejection_repair",
|
|
91
|
+
validator_verdict=ValidatorVerdict(accepted=False, error_codes=verdict.codes()),
|
|
92
|
+
envelope_ref=envelope_ref,
|
|
93
|
+
repair=session.accepted_program,
|
|
94
|
+
)
|
|
95
|
+
)
|
|
96
|
+
return records
|
urml_model/synthesize.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Oracle-filtered dataset synthesis (RFC-0666).
|
|
2
|
+
|
|
3
|
+
`synthesize()` turns mined `GoldExample`s into `DatasetRecord`s:
|
|
4
|
+
|
|
5
|
+
1. Utterances: a few-shot example brings its own; a fixture program gets
|
|
6
|
+
back-translated.
|
|
7
|
+
2. The oracle: every program is re-validated against its manifest,
|
|
8
|
+
envelope, profile, and policy at synthesis time. Rejected programs are
|
|
9
|
+
dropped and reported, never silently.
|
|
10
|
+
3. Dedup: records collapse on (utterance, canonical program JSON).
|
|
11
|
+
|
|
12
|
+
The oracle call is not optional and not cached across schema versions: a
|
|
13
|
+
dataset is only as trustworthy as the validator that filtered it.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
|
|
20
|
+
from urml_validator import validate
|
|
21
|
+
|
|
22
|
+
from urml_model.backtranslate import BackTranslator, TemplateBackTranslator
|
|
23
|
+
from urml_model.dataset import Dataset, DatasetRecord, Provenance, ValidatorVerdict
|
|
24
|
+
from urml_model.mining import GoldExample
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class SynthesisReport:
|
|
29
|
+
"""What synthesize() kept and what it dropped, with reasons."""
|
|
30
|
+
|
|
31
|
+
kept: int = 0
|
|
32
|
+
deduplicated: int = 0
|
|
33
|
+
dropped_rejected: list[tuple[str, list[str]]] = field(default_factory=list)
|
|
34
|
+
dropped_no_utterance: list[str] = field(default_factory=list)
|
|
35
|
+
|
|
36
|
+
def summary(self) -> str:
|
|
37
|
+
lines = [f"kept {self.kept} record(s); {self.deduplicated} duplicate(s) collapsed"]
|
|
38
|
+
if self.dropped_rejected:
|
|
39
|
+
lines.append(f"dropped {len(self.dropped_rejected)} validator-rejected program(s):")
|
|
40
|
+
lines.extend(f" {source}: {codes}" for source, codes in self.dropped_rejected)
|
|
41
|
+
if self.dropped_no_utterance:
|
|
42
|
+
lines.append(
|
|
43
|
+
f"dropped {len(self.dropped_no_utterance)} program(s) the translator "
|
|
44
|
+
f"produced no utterance for: {self.dropped_no_utterance}"
|
|
45
|
+
)
|
|
46
|
+
return "\n".join(lines)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def synthesize(
|
|
50
|
+
gold: list[GoldExample],
|
|
51
|
+
translator: BackTranslator | None = None,
|
|
52
|
+
*,
|
|
53
|
+
per_program: int = 1,
|
|
54
|
+
language: str = "en",
|
|
55
|
+
) -> tuple[Dataset, SynthesisReport]:
|
|
56
|
+
"""Produce an oracle-filtered dataset from mined gold examples."""
|
|
57
|
+
translator = translator if translator is not None else TemplateBackTranslator()
|
|
58
|
+
dataset = Dataset()
|
|
59
|
+
report = SynthesisReport()
|
|
60
|
+
seen: set[tuple[str, str]] = set()
|
|
61
|
+
|
|
62
|
+
for example in gold:
|
|
63
|
+
verdict = validate(
|
|
64
|
+
example.program,
|
|
65
|
+
example.manifest,
|
|
66
|
+
example.envelope,
|
|
67
|
+
profiles=(example.profile,),
|
|
68
|
+
policy=example.policy,
|
|
69
|
+
)
|
|
70
|
+
if not verdict.accepted:
|
|
71
|
+
report.dropped_rejected.append((example.source, verdict.codes()))
|
|
72
|
+
continue
|
|
73
|
+
|
|
74
|
+
if example.nl is not None:
|
|
75
|
+
utterances = [example.nl]
|
|
76
|
+
provenance: Provenance = "few_shot"
|
|
77
|
+
else:
|
|
78
|
+
utterances = translator.to_utterances(
|
|
79
|
+
example.program, example.manifest, language=language, n=per_program
|
|
80
|
+
)
|
|
81
|
+
provenance = (
|
|
82
|
+
"fixture_backtranslation"
|
|
83
|
+
if isinstance(translator, TemplateBackTranslator)
|
|
84
|
+
else "llm_backtranslation"
|
|
85
|
+
)
|
|
86
|
+
if not utterances:
|
|
87
|
+
report.dropped_no_utterance.append(example.source)
|
|
88
|
+
continue
|
|
89
|
+
|
|
90
|
+
for utterance in utterances:
|
|
91
|
+
record = DatasetRecord(
|
|
92
|
+
nl=utterance,
|
|
93
|
+
program=example.program,
|
|
94
|
+
manifest_ref=example.manifest_ref,
|
|
95
|
+
profile=example.profile,
|
|
96
|
+
language=language,
|
|
97
|
+
provenance=provenance,
|
|
98
|
+
validator_verdict=ValidatorVerdict(accepted=True),
|
|
99
|
+
envelope_ref=example.envelope_ref,
|
|
100
|
+
)
|
|
101
|
+
key = record.dedup_key()
|
|
102
|
+
if key in seen:
|
|
103
|
+
report.deduplicated += 1
|
|
104
|
+
continue
|
|
105
|
+
seen.add(key)
|
|
106
|
+
dataset.records.append(record)
|
|
107
|
+
report.kept += 1
|
|
108
|
+
|
|
109
|
+
return dataset, report
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: urml-model
|
|
3
|
+
Version: 0.5.0
|
|
4
|
+
Summary: Dataset synthesis pipeline and training recipe for a URML-native small model (RFC-0666).
|
|
5
|
+
Project-URL: Homepage, https://github.com/urml-dev/URML
|
|
6
|
+
Project-URL: Repository, https://github.com/urml-dev/URML
|
|
7
|
+
Project-URL: Issues, https://github.com/urml-dev/URML/issues
|
|
8
|
+
Author: URML Maintainers
|
|
9
|
+
License: BUSL-1.1
|
|
10
|
+
Keywords: dataset,fine-tuning,llm,robotics,urml
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: Other/Proprietary License
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
19
|
+
Requires-Python: >=3.11
|
|
20
|
+
Requires-Dist: pydantic<3,>=2.6
|
|
21
|
+
Requires-Dist: pyyaml<7,>=6.0
|
|
22
|
+
Requires-Dist: urml-conformance>=0.5.0
|
|
23
|
+
Requires-Dist: urml-llm-bridge>=0.5.0
|
|
24
|
+
Requires-Dist: urml-validator>=0.5.0
|
|
25
|
+
Provides-Extra: dev
|
|
26
|
+
Requires-Dist: mypy>=1.10; extra == 'dev'
|
|
27
|
+
Requires-Dist: pytest-cov>=5; extra == 'dev'
|
|
28
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
29
|
+
Requires-Dist: ruff>=0.5; extra == 'dev'
|
|
30
|
+
Requires-Dist: types-pyyaml>=6.0; extra == 'dev'
|
|
31
|
+
Description-Content-Type: text/markdown
|
|
32
|
+
|
|
33
|
+
<p align="center">
|
|
34
|
+
<a href="https://urml.dev"><img src="https://urml.dev/favicon.svg" alt="URML" width="72" height="72"></a>
|
|
35
|
+
</p>
|
|
36
|
+
|
|
37
|
+
<p align="center">
|
|
38
|
+
A small, opinionated, human-readable language for describing robot intent.
|
|
39
|
+
</p>
|
|
40
|
+
|
|
41
|
+
<p align="center">
|
|
42
|
+
<a href="https://urml.dev"><b>urml.dev</b></a>
|
|
43
|
+
</p>
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
# urml-model
|
|
48
|
+
|
|
49
|
+
Dataset synthesis pipeline and training recipe for a URML-native small model ([RFC-0666](../../docs/rfcs/0666-urml-native-model-pipeline.md)).
|
|
50
|
+
|
|
51
|
+
The idea: URML already owns a perfect, free, machine-checkable reward signal. A candidate program is correct exactly when `urml_validator.validate` accepts it, and when it is wrong the validator says why in ~150 namespaced error codes. This package turns that oracle plus the repository's gold assets (conformance fixtures, the few-shot library, rejected bridge emissions) into a training dataset for a small open-weights model that emits first-pass-valid URML offline.
|
|
52
|
+
|
|
53
|
+
What this package does **not** do: train a model, download weights, or call a specific LLM vendor. Training is operator-action, documented in [docs/training-recipe.md](docs/training-recipe.md). No model artifact ever lives in this repository.
|
|
54
|
+
|
|
55
|
+
## Quick start
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
# Hermetic: mine the repo's gold assets into a dataset (no network, no LLM)
|
|
59
|
+
urml-model synthesize --out data/urml-sft.jsonl
|
|
60
|
+
|
|
61
|
+
# Write a chat-format SFT file (system prompt = the bridge's real prompt)
|
|
62
|
+
urml-model export --in data/urml-sft.jsonl --out data/sft-chatml.jsonl --fmt chatml
|
|
63
|
+
|
|
64
|
+
# After training: score the model with the conformance scorer (RFC-0021 metrics)
|
|
65
|
+
urml-model eval --utterances-root conformance/llm-bridge/fixtures \
|
|
66
|
+
--profile home --backend ollama --model my-urml-3b \
|
|
67
|
+
--out conformance/llm-bridge/results/$(date +%F)/home-my-urml-3b.yaml
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Dataset shape
|
|
71
|
+
|
|
72
|
+
One JSONL record per example: `nl`, `program`, `manifest_ref`, `profile`, `language`, `provenance`, `validator_verdict`, optional `envelope_ref` and `repair`. Records rejected by the validator are only allowed as `rejection_repair` examples (failed emission + error codes + the accepted program as the repair target). The full schema is normative in RFC-0666.
|
|
73
|
+
|
|
74
|
+
## Diversity at scale
|
|
75
|
+
|
|
76
|
+
The CLI's synthesize path uses the deterministic template back-translator so CI stays hermetic. Real phrasing diversity comes from `LLMBackTranslator`, a library call that takes any `LLMProvider` (Anthropic, OpenAI, Ollama, llama.cpp — the bridge's own adapters). Every candidate it produces still goes through the oracle before it enters the dataset.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
urml_model/__init__.py,sha256=w1AvydEdHFJjLAQdFk7x9DHZorraWkmnXMdPvw2ijfk,1810
|
|
2
|
+
urml_model/backtranslate.py,sha256=pr2ie3SOm86ep_G7u6BNfFl3lG3KYBEFw7vxzAvLL14,8286
|
|
3
|
+
urml_model/cli.py,sha256=-eaQlWe8E2cPNcmTPn8FWhue6RDKV6Zy3NG278fUUQg,6532
|
|
4
|
+
urml_model/dataset.py,sha256=3t3wdfWrfXo2Zk9aSS6ZBwNfA7HF-MujQrSOSQxE32I,4307
|
|
5
|
+
urml_model/export.py,sha256=T-TCMjOmO33xJXVmOKsmPIbrqAUFLg6uDXk7TEiNCC0,3967
|
|
6
|
+
urml_model/mining.py,sha256=LtmftthVlViOmf8luP6nFYxuVuqv3uTMynmE8PblGQg,6120
|
|
7
|
+
urml_model/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
urml_model/rejections.py,sha256=doZH7TJyAHrZXbyShsa3OPQCa-OjjuSpqlHpX5H1qM0,3670
|
|
9
|
+
urml_model/synthesize.py,sha256=rPQJ0U5L4BTyV3oFAGUhqomLQ2LukzAkxX2k-BZ8fjw,3932
|
|
10
|
+
urml_model-0.5.0.dist-info/METADATA,sha256=20KGX2lnamFCl0_Fuuxn1twc38kdTr_UyJ_kK9I7Udg,3842
|
|
11
|
+
urml_model-0.5.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
12
|
+
urml_model-0.5.0.dist-info/entry_points.txt,sha256=4h4wWnNo6qizDdZ9PzWDVhEJN5x4VFA8jGyuNbo2w6s,51
|
|
13
|
+
urml_model-0.5.0.dist-info/RECORD,,
|