interplane.Get Omega
Read in your language

omega-helix

This project has not described itself yet.

Brought by drakestapleton

branch main Branches Tags History

omega-helix / tools / distill / harvest.py

594 lines · 22559 bytes Raw Blame History
1"""Universal trace & corpus harvester + OpenWALDO & OLLMDK01 exporters.
2
3Harvests OpenAI/Anthropic chat JSONL, ShareGPT conversations, instruction/prompt-completion
4JSONL, canonical OpenWALDO JSONL/EXPORT.json, and raw code/text directories into deduplicated
5training records, writes verifiable OpenWALDO schema-1 exports, and packs sparse top-K teacher
6distributions into OLLMDK01 binary shards.
7
8Python 3 standard library only — zero external packages.
9"""
10
11from __future__ import annotations
12
13import datetime
14import hashlib
15import json
16import math
17import os
18import struct
19import sys
20from pathlib import Path
21from typing import Any
22
23TOOLS_DIR = Path(__file__).resolve().parents[1]
24OPENWALDO_DIR = TOOLS_DIR / "openwaldo"
25if str(OPENWALDO_DIR) not in sys.path:
26 sys.path.insert(0, str(OPENWALDO_DIR))
27
28import openwaldo_bridge as ow_bridge # noqa: E402
29
30UMAGIC_DK1 = 3544415663467285583
31UDKHDR = 64
32UDK_MAXK = 64
33
34TEXT_EXTS = {
35 ".txt", ".md", ".om", ".py", ".c", ".h", ".rs", ".go", ".ts", ".tsx",
36 ".js", ".jsx", ".sh", ".json", ".yaml", ".yml",
37}
38SKIP_DIRS = {".git", ".hg", ".svn", "node_modules", "__pycache__", ".venv", "venv", "build", "dist"}
39
40
41def utc_now() -> str:
42 return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
43
44
45def fnv1a64(data: bytes) -> int:
46 """Standard 64-bit FNV-1a digest matching native/univ/umath.om & udistill.om."""
47 h = 14695981039346656037
48 mask = 0xFFFFFFFFFFFFFFFF
49 for b in data:
50 h = ((h ^ b) * 1099511628211) & mask
51 return h
52
53
54def _flatten_content(val: Any) -> str:
55 if isinstance(val, str):
56 return val
57 if isinstance(val, list):
58 parts: list[str] = []
59 for item in val:
60 if isinstance(item, str):
61 parts.append(item)
62 elif isinstance(item, dict) and isinstance(item.get("text"), str):
63 parts.append(item["text"])
64 return "".join(parts)
65 if isinstance(val, dict) and isinstance(val.get("text"), str):
66 return val["text"]
67 return str(val) if val is not None else ""
68
69
70def _norm_role(role: Any) -> str:
71 r = str(role or "").strip().lower()
72 if r in ("system", "developer"):
73 return "system"
74 if r in ("user", "human", "prompter"):
75 return "user"
76 if r in ("assistant", "gpt", "model", "bot", "completion"):
77 return "assistant"
78 if r == "tool":
79 return "tool"
80 return "user"
81
82
83def _compute_chat_spans(messages: list[dict[str, str]]) -> tuple[str, str, list[list[int]]]:
84 """Render deterministic chat transcript plus exact assistant UTF-8 byte spans."""
85 rendered_parts: list[str] = []
86 spans: list[list[int]] = []
87 assistant_chunks: list[str] = []
88 byte_off = 0
89 for idx, msg in enumerate(messages):
90 prefix = f"{msg['role']}: "
91 body = msg["content"]
92 suffix = "\n" if idx + 1 < len(messages) else ""
93 prefix_b = prefix.encode("utf-8")
94 body_b = body.encode("utf-8")
95 if msg["role"] == "assistant" and body_b:
96 spans.append([byte_off + len(prefix_b), byte_off + len(prefix_b) + len(body_b)])
97 assistant_chunks.append(body)
98 chunk = prefix + body + suffix
99 rendered_parts.append(chunk)
100 byte_off += len(chunk.encode("utf-8"))
101 rendered = "".join(rendered_parts)
102 assistant_text = "\n\n".join(assistant_chunks) if assistant_chunks else rendered
103 return rendered, assistant_text, spans
104
105
106def _normalize_record(
107 obj: dict[str, Any],
108 *,
109 default_source: str,
110 default_license: str,
111) -> dict[str, Any] | None:
112 src = str(obj.get("source") or default_source)
113 lic = str(obj.get("license") or default_license)
114 logprobs = obj.get("logprobs")
115 teacher_model = str(obj.get("teacher_model") or obj.get("model") or "")
116
117 # 1. OpenWALDO canonical record
118 if obj.get("kind") in ("conversation", "pretrain") and isinstance(obj.get("text"), str):
119 raw_text = obj["text"]
120 if obj["kind"] == "conversation":
121 conv = json.loads(raw_text)
122 msgs = [
123 {"role": _norm_role(m.get("role")), "content": _flatten_content(m.get("content"))}
124 for m in conv.get("messages", [])
125 if _flatten_content(m.get("content")).strip()
126 ]
127 if not msgs:
128 return None
129 rendered, assistant_text, spans = _compute_chat_spans(msgs)
130 return {
131 "kind": "conversation",
132 "messages": msgs,
133 "text": json.dumps({"messages": msgs}, ensure_ascii=False),
134 "rendered_text": rendered,
135 "assistant_text": assistant_text,
136 "assistant_spans": spans,
137 "source": src,
138 "license": lic,
139 "teacher_model": teacher_model,
140 "logprobs": logprobs,
141 }
142 if not raw_text.strip():
143 return None
144 return {
145 "kind": "pretrain",
146 "messages": None,
147 "text": raw_text,
148 "rendered_text": raw_text,
149 "assistant_text": raw_text,
150 "assistant_spans": [[0, len(raw_text.encode("utf-8"))]],
151 "source": src,
152 "license": lic,
153 "teacher_model": teacher_model,
154 "logprobs": logprobs,
155 }
156
157 # 2. Chat messages / ShareGPT conversations
158 raw_msgs = obj.get("messages") or obj.get("conversations")
159 if isinstance(raw_msgs, list) and raw_msgs:
160 msgs: list[dict[str, str]] = []
161 for m in raw_msgs:
162 if not isinstance(m, dict):
163 continue
164 role = _norm_role(m.get("role") if "role" in m else m.get("from"))
165 content = _flatten_content(m.get("content") if "content" in m else m.get("value")).strip()
166 if content:
167 msgs.append({"role": role, "content": content})
168 if not msgs:
169 return None
170 rendered, assistant_text, spans = _compute_chat_spans(msgs)
171 return {
172 "kind": "conversation",
173 "messages": msgs,
174 "text": json.dumps({"messages": msgs}, ensure_ascii=False),
175 "rendered_text": rendered,
176 "assistant_text": assistant_text,
177 "assistant_spans": spans,
178 "source": src,
179 "license": lic,
180 "teacher_model": teacher_model,
181 "logprobs": logprobs,
182 }
183
184 # 3. Prompt/response or instruction/input/output or question/answer
185 prompt = ""
186 response = ""
187 if "prompt" in obj or "response" in obj or "completion" in obj:
188 prompt = _flatten_content(obj.get("prompt")).strip()
189 response = _flatten_content(obj.get("response") or obj.get("completion")).strip()
190 elif "instruction" in obj or "output" in obj:
191 inst = _flatten_content(obj.get("instruction")).strip()
192 inp = _flatten_content(obj.get("input")).strip()
193 prompt = f"{inst}\n\n{inp}".strip() if inp else inst
194 response = _flatten_content(obj.get("output")).strip()
195 elif "question" in obj or "answer" in obj:
196 prompt = _flatten_content(obj.get("question")).strip()
197 response = _flatten_content(obj.get("answer")).strip()
198
199 if prompt and response:
200 msgs = [{"role": "user", "content": prompt}, {"role": "assistant", "content": response}]
201 rendered, assistant_text, spans = _compute_chat_spans(msgs)
202 return {
203 "kind": "conversation",
204 "messages": msgs,
205 "text": json.dumps({"messages": msgs}, ensure_ascii=False),
206 "rendered_text": rendered,
207 "assistant_text": assistant_text,
208 "assistant_spans": spans,
209 "source": src,
210 "license": lic,
211 "teacher_model": teacher_model,
212 "logprobs": logprobs,
213 }
214 if response or isinstance(obj.get("text"), str):
215 txt = response or str(obj.get("text") or "")
216 if not txt.strip():
217 return None
218 return {
219 "kind": "pretrain",
220 "messages": None,
221 "text": txt,
222 "rendered_text": txt,
223 "assistant_text": txt,
224 "assistant_spans": [[0, len(txt.encode("utf-8"))]],
225 "source": src,
226 "license": lic,
227 "teacher_model": teacher_model,
228 "logprobs": logprobs,
229 }
230 return None
231
232
233def _harvest_jsonl(
234 path: Path,
235 out: list[dict[str, Any]],
236 seen: set[str],
237 stats: dict[str, int],
238 *,
239 source_tag: str,
240 license_id: str,
241) -> None:
242 with path.open("rb") as f:
243 for raw in f:
244 line = raw.rstrip(b"\r\n")
245 if not line:
246 continue
247 stats["raw_records"] += 1
248 obj = json.loads(line.decode("utf-8"))
249 if not isinstance(obj, dict):
250 raise ValueError(f"{path}: JSONL line must decode to object")
251 rec = _normalize_record(obj, default_source=source_tag, default_license=license_id)
252 if rec is None:
253 continue
254 digest = hashlib.sha256(rec["text"].encode("utf-8")).hexdigest()
255 if digest in seen:
256 stats["duplicates_skipped"] += 1
257 continue
258 seen.add(digest)
259 rec["sha256"] = digest
260 out.append(rec)
261
262
263def harvest_paths(
264 inputs: list[str | Path],
265 *,
266 source_tag: str = "distill-harvest",
267 license_id: str = "Apache-2.0",
268) -> dict[str, Any]:
269 """Harvest records from JSONL traces, OpenWALDO EXPORT.json dirs, or code/text files."""
270 if not inputs:
271 raise ValueError("harvest_paths requires at least one input path")
272
273 records: list[dict[str, Any]] = []
274 seen: set[str] = set()
275 stats = {"files_scanned": 0, "raw_records": 0, "duplicates_skipped": 0}
276 input_shas: list[dict[str, Any]] = []
277
278 for raw_in in inputs:
279 p = Path(raw_in).expanduser().resolve()
280 if not p.exists():
281 raise FileNotFoundError(f"harvest input not found: {p}")
282
283 if p.is_dir():
284 export_json = p / "EXPORT.json"
285 if export_json.is_file():
286 rep = ow_bridge.verify_export(p, check_records=True)
287 input_shas.append({"path": str(export_json), "sha256": rep["export_json_sha256"]})
288 for fentry in rep["files"]:
289 fp = Path(fentry["abs_path"])
290 stats["files_scanned"] += 1
291 _harvest_jsonl(fp, records, seen, stats, source_tag=source_tag, license_id=license_id)
292 continue
293
294 for dirpath, dirnames, filenames in os.walk(p):
295 dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIRS)
296 for fn in sorted(filenames):
297 fp = Path(dirpath) / fn
298 if fp.suffix.lower() == ".jsonl":
299 stats["files_scanned"] += 1
300 sha, _ = ow_bridge.file_sha256_and_bytes(fp)
301 input_shas.append({"path": str(fp), "sha256": sha})
302 _harvest_jsonl(fp, records, seen, stats, source_tag=source_tag, license_id=license_id)
303 elif fp.suffix.lower() in TEXT_EXTS:
304 stats["files_scanned"] += 1
305 txt = fp.read_text(encoding="utf-8", errors="replace")
306 if not txt.strip():
307 continue
308 stats["raw_records"] += 1
309 digest = hashlib.sha256(txt.encode("utf-8")).hexdigest()
310 if digest in seen:
311 stats["duplicates_skipped"] += 1
312 continue
313 seen.add(digest)
314 records.append({
315 "kind": "pretrain",
316 "messages": None,
317 "text": txt,
318 "rendered_text": txt,
319 "assistant_text": txt,
320 "assistant_spans": [[0, len(txt.encode("utf-8"))]],
321 "source": f"{source_tag}:{fp.name}",
322 "license": license_id,
323 "teacher_model": "",
324 "logprobs": None,
325 "sha256": digest,
326 })
327 elif p.suffix.lower() == ".json" and p.name == "EXPORT.json":
328 rep = ow_bridge.verify_export(p, check_records=True)
329 input_shas.append({"path": str(p), "sha256": rep["export_json_sha256"]})
330 for fentry in rep["files"]:
331 fp = Path(fentry["abs_path"])
332 stats["files_scanned"] += 1
333 _harvest_jsonl(fp, records, seen, stats, source_tag=source_tag, license_id=license_id)
334 elif p.suffix.lower() == ".jsonl":
335 stats["files_scanned"] += 1
336 sha, _ = ow_bridge.file_sha256_and_bytes(p)
337 input_shas.append({"path": str(p), "sha256": sha})
338 _harvest_jsonl(p, records, seen, stats, source_tag=source_tag, license_id=license_id)
339 else:
340 stats["files_scanned"] += 1
341 txt = p.read_text(encoding="utf-8", errors="replace")
342 if txt.strip():
343 stats["raw_records"] += 1
344 digest = hashlib.sha256(txt.encode("utf-8")).hexdigest()
345 if digest in seen:
346 stats["duplicates_skipped"] += 1
347 else:
348 seen.add(digest)
349 sha, _ = ow_bridge.file_sha256_and_bytes(p)
350 input_shas.append({"path": str(p), "sha256": sha})
351 records.append({
352 "kind": "pretrain",
353 "messages": None,
354 "text": txt,
355 "rendered_text": txt,
356 "assistant_text": txt,
357 "assistant_spans": [[0, len(txt.encode("utf-8"))]],
358 "source": f"{source_tag}:{p.name}",
359 "license": license_id,
360 "teacher_model": "",
361 "logprobs": None,
362 "sha256": digest,
363 })
364
365 stats["unique_records"] = len(records)
366 return {"records": records, "stats": stats, "inputs": input_shas}
367
368
369def write_openwaldo_export(
370 records: list[dict[str, Any]],
371 out_dir: str | Path,
372 *,
373 corpus_name: str = "distilled-traces",
374 license_id: str = "Apache-2.0",
375 source_tag: str = "distill-harvest",
376) -> dict[str, Any]:
377 """Materialize canonical OpenWALDO EXPORT.json + shard-00000.jsonl + MASKS.jsonl."""
378 if not records:
379 raise ValueError("cannot write empty OpenWALDO export")
380 root = Path(out_dir).expanduser().resolve()
381 data_dir = root / "data"
382 data_dir.mkdir(parents=True, exist_ok=True)
383 shard_rel = "data/shard-00000.jsonl"
384 shard_path = root / shard_rel
385 masks_path = root / "MASKS.jsonl"
386
387 lines: list[bytes] = []
388 mask_lines: list[bytes] = []
389 for idx, rec in enumerate(records):
390 text = str(rec["text"])
391 kind = str(rec.get("kind") or "pretrain")
392 if kind not in ("pretrain", "conversation"):
393 kind = "pretrain"
394 rec_sha = hashlib.sha256(text.encode("utf-8")).hexdigest()
395 src = str(rec.get("source") or source_tag)
396 lic = str(rec.get("license") or license_id)
397 entry = {
398 "sha256": rec_sha,
399 "kind": kind,
400 "text": text,
401 "source": src,
402 "license": lic,
403 }
404 lines.append((json.dumps(entry, ensure_ascii=False) + "\n").encode("utf-8"))
405 mask_entry = {
406 "index": idx,
407 "sha256": rec_sha,
408 "kind": kind,
409 "assistant_spans": rec.get("assistant_spans") or [],
410 "teacher_model": rec.get("teacher_model") or "",
411 }
412 mask_lines.append((json.dumps(mask_entry, ensure_ascii=False) + "\n").encode("utf-8"))
413
414 raw_shard = b"".join(lines)
415 tmp_shard = shard_path.with_suffix(".jsonl.tmp")
416 with tmp_shard.open("wb") as f:
417 f.write(raw_shard)
418 f.flush()
419 os.fsync(f.fileno())
420 os.replace(tmp_shard, shard_path)
421
422 tmp_masks = masks_path.with_suffix(".jsonl.tmp")
423 with tmp_masks.open("wb") as f:
424 f.write(b"".join(mask_lines))
425 f.flush()
426 os.fsync(f.fileno())
427 os.replace(tmp_masks, masks_path)
428
429 shard_sha, shard_bytes = ow_bridge.file_sha256_and_bytes(shard_path)
430 export_doc = {
431 "kind": "waldo-corpus-export",
432 "schema": 1,
433 "format": "jsonl",
434 "generated": utc_now(),
435 "files": [
436 {
437 "path": shard_rel,
438 "manifest": corpus_name,
439 "format": "jsonl",
440 "object_sha256": shard_sha,
441 "object_bytes": shard_bytes,
442 "sha256": shard_sha,
443 "bytes": shard_bytes,
444 "docs": len(records),
445 "license": license_id,
446 "licenses": [license_id],
447 }
448 ],
449 "bom": {
450 "kind": "openwaldo-bom",
451 "schema": 1,
452 "index": {"name": corpus_name, "source": source_tag},
453 "paths": [shard_rel],
454 "shards": [
455 {
456 "manifest": corpus_name,
457 "sha256": shard_sha,
458 "bytes": shard_bytes,
459 "license": license_id,
460 }
461 ],
462 },
463 }
464 export_path = root / "EXPORT.json"
465 tmp_export = export_path.with_suffix(".json.tmp")
466 tmp_export.write_text(json.dumps(export_doc, indent=2) + "\n", encoding="utf-8")
467 os.replace(tmp_export, export_path)
468
469 verified = ow_bridge.verify_export(root, check_records=True)
470 return {
471 "export_dir": str(root),
472 "export_json": verified["export_json"],
473 "export_json_sha256": verified["export_json_sha256"],
474 "masks_jsonl": str(masks_path),
475 "docs": verified["total_docs"],
476 "bytes": verified["total_bytes"],
477 "licenses": verified["licenses"],
478 }
479
480
481def write_ollmdk01(
482 records_dk: list[dict[str, Any]],
483 out_path: str | Path,
484 *,
485 V: int,
486 K: int,
487 T: int,
488) -> dict[str, Any]:
489 """Write a verified OLLMDK01 sparse top-K distillation shard atomically."""
490 if V < 2:
491 raise ValueError(f"V must be >= 2, got {V}")
492 if K < 1 or K > UDK_MAXK or K > V:
493 raise ValueError(f"K={K} must satisfy 1 <= K <= min({UDK_MAXK}, V={V})")
494 if T < 1:
495 raise ValueError(f"T must be >= 1, got {T}")
496 if not records_dk:
497 raise ValueError("records_dk must be non-empty")
498
499 body_chunks: list[bytes] = []
500 for idx, rec in enumerate(records_dk):
501 toks = list(rec["tokens"])
502 mask = list(rec["mask"])
503 top_ids = list(rec["top_ids"])
504 top_probs = list(rec["top_probs"])
505 if len(toks) != T + 1:
506 raise ValueError(f"record {idx}: expected {T + 1} tokens, got {len(toks)}")
507 if len(mask) != T:
508 raise ValueError(f"record {idx}: expected {T} mask bytes, got {len(mask)}")
509 if len(top_ids) != T * K or len(top_probs) != T * K:
510 raise ValueError(f"record {idx}: expected {T * K} sparse entries")
511 for tok in toks:
512 if not isinstance(tok, int) or tok < 0 or tok >= V:
513 raise ValueError(f"record {idx}: token {tok!r} out of range [0, {V})")
514 for m in mask:
515 if m not in (0, 1):
516 raise ValueError(f"record {idx}: invalid mask byte {m!r}")
517 for pos in range(T):
518 s = 0.0
519 base = pos * K
520 for j in range(K):
521 tid = top_ids[base + j]
522 pr = float(top_probs[base + j])
523 if not isinstance(tid, int) or tid < 0 or tid >= V:
524 raise ValueError(f"record {idx} pos {pos}: top_id {tid!r} out of range")
525 if not math.isfinite(pr) or pr < 0.0:
526 raise ValueError(f"record {idx} pos {pos}: invalid prob {pr!r}")
527 s += pr
528 if s > 1.0001:
529 raise ValueError(f"record {idx} pos {pos}: prob sum {s} > 1.0001")
530
531 body_chunks.append(struct.pack(f"<{T + 1}I", *toks))
532 body_chunks.append(bytes(mask))
533 body_chunks.append(struct.pack(f"<{T * K}I", *top_ids))
534 body_chunks.append(struct.pack(f"<{T * K}f", *(float(x) for x in top_probs)))
535
536 body = b"".join(body_chunks)
537 fnv = fnv1a64(body)
538 hdr = struct.pack("<8Q", UMAGIC_DK1, 1, V, K, T, len(records_dk), 0, fnv)
539 dest = Path(out_path).expanduser().resolve()
540 dest.parent.mkdir(parents=True, exist_ok=True)
541 tmp = dest.with_name(dest.name + ".tmp")
542 with tmp.open("wb") as f:
543 f.write(hdr)
544 f.write(body)
545 f.flush()
546 os.fsync(f.fileno())
547 os.replace(tmp, dest)
548 sha, total_bytes = ow_bridge.file_sha256_and_bytes(dest)
549 return {
550 "path": str(dest),
551 "magic": "OLLMDK01",
552 "version": 1,
553 "V": V,
554 "K": K,
555 "T": T,
556 "N": len(records_dk),
557 "flags": 0,
558 "fnv_body": fnv,
559 "fnv_hex": f"{fnv:016x}",
560 "sha256": sha,
561 "bytes": total_bytes,
562 }
563
564
565def read_ollmdk01_header(path: str | Path) -> dict[str, Any]:
566 p = Path(path).expanduser().resolve()
567 raw = p.read_bytes()
568 if len(raw) < UDKHDR:
569 raise ValueError(f"{p}: truncated OLLMDK01 header ({len(raw)} bytes)")
570 magic, ver, V, K, T, N, flags, want_fnv = struct.unpack("<8Q", raw[:UDKHDR])
571 if magic != UMAGIC_DK1 or ver != 1 or flags != 0:
572 raise ValueError(f"{p}: bad OLLMDK01 magic/version/flags ({magic}, {ver}, {flags})")
573 rec_sz = 4 * (T + 1) + T + 8 * T * K
574 want_sz = UDKHDR + N * rec_sz
575 if len(raw) != want_sz:
576 raise ValueError(f"{p}: size mismatch (got {len(raw)}, expected {want_sz})")
577 got_fnv = fnv1a64(raw[UDKHDR:])
578 if got_fnv != want_fnv:
579 raise ValueError(f"{p}: body FNV-1a mismatch (got {got_fnv:016x}, expected {want_fnv:016x})")
580 sha, size = ow_bridge.file_sha256_and_bytes(p)
581 return {
582 "path": str(p),
583 "magic": "OLLMDK01",
584 "version": ver,
585 "V": V,
586 "K": K,
587 "T": T,
588 "N": N,
589 "flags": flags,
590 "fnv_body": want_fnv,
591 "fnv_hex": f"{want_fnv:016x}",
592 "sha256": sha,
593 "bytes": size,
594 }