baseline_pdexp_result / code /materialization /materialize_morphosis_dsv4.py
ergt2025's picture
Add Excel, metrics, analysis code, and manifests
349eba5 verified
Raw History Blame Contribute Delete
19.5 kB
#!/usr/bin/env python3
"""Retokenize Morphosis logical-order traces for strict DSV4 replay.
The input actor rows remain byte-preserved in the sealed source artifact. This
materializer creates one tar.gz bundle per root program, replacing only the GLM
prompt/output token IDs and output length with values produced by the frozen
DeepSeek-V4 serving encoder and tokenizer.
"""
from __future__ import annotations
import argparse
import copy
import hashlib
import importlib.util
import json
import lzma
import os
import re
import shutil
import tarfile
import tempfile
import time
from collections import Counter
from pathlib import Path
from types import ModuleType
from typing import Any, Iterable
from transformers import AutoTokenizer
ROOT_ID_RE = re.compile(r"root-\d{3}-[A-Za-z0-9_.-]+")
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
while chunk := handle.read(8 << 20):
digest.update(chunk)
return digest.hexdigest()
def sha256_json(value: Any) -> str:
return hashlib.sha256(
json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
).hexdigest()
def load_encoder(path: Path) -> ModuleType:
spec = importlib.util.spec_from_file_location("frozen_encoding_dsv4", path)
if spec is None or spec.loader is None:
raise ValueError(f"cannot load DSV4 encoder: {path}")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
if not hasattr(module, "encode_messages"):
raise ValueError(f"DSV4 encoder lacks encode_messages: {path}")
return module
def flatten_content(content: Any, *, location: str, audit: Counter[str]) -> str:
if content is None:
return ""
if isinstance(content, str):
return content
if not isinstance(content, list):
raise TypeError(f"{location}: unsupported content type {type(content).__name__}")
parts: list[str] = []
for index, part in enumerate(content):
if isinstance(part, str):
audit["content_part:string"] += 1
parts.append(part)
continue
if not isinstance(part, dict):
raise TypeError(f"{location}[{index}]: invalid content part")
kind = str(part.get("type") or "")
if kind in {"text", "input_text"} and isinstance(part.get("text"), str):
audit[f"content_part:{kind}"] += 1
parts.append(part["text"])
continue
raise ValueError(f"{location}[{index}]: unsupported content part {kind!r}")
return " ".join(parts)
def prepare_messages(
messages: list[dict[str, Any]],
*,
tools: list[dict[str, Any]],
location: str,
audit: Counter[str],
) -> list[dict[str, Any]]:
prepared = copy.deepcopy(messages)
for index, message in enumerate(prepared):
if not isinstance(message, dict):
raise TypeError(f"{location}.messages[{index}] is not an object")
role = message.get("role")
if not isinstance(role, str) or not role:
raise ValueError(f"{location}.messages[{index}] has invalid role")
if "content" in message:
message["content"] = flatten_content(
message["content"],
location=f"{location}.messages[{index}].content",
audit=audit,
)
elif role == "assistant":
message["content"] = ""
for call_index, tool_call in enumerate(message.get("tool_calls") or []):
function = tool_call.get("function") if isinstance(tool_call, dict) else None
if not isinstance(function, dict):
raise TypeError(
f"{location}.messages[{index}].tool_calls[{call_index}] is invalid"
)
arguments = function.get("arguments")
if isinstance(arguments, str):
arguments = json.loads(arguments)
function["arguments"] = arguments
if arguments is not None and not isinstance(arguments, dict):
raise TypeError(
f"{location}.messages[{index}].tool_calls[{call_index}] "
"arguments must be an object"
)
if not prepared or prepared[0].get("role") != "system":
prepared.insert(0, {"role": "system", "content": ""})
prepared[0]["tools"] = copy.deepcopy(tools)
return prepared
def converted_actor(
row: dict[str, Any],
*,
tokenizer: Any,
encoder: ModuleType,
vocab_size: int,
context_limit: int,
audit: Counter[str],
) -> tuple[dict[str, Any], dict[str, int], list[dict[str, Any]]]:
trace_id = row.get("trace_id")
if row.get("schema_version") != 2 or not isinstance(trace_id, str):
raise ValueError("input is not a schema-v2 ReplayTrace")
metadata = row.get("metadata")
if not isinstance(metadata, dict) or not isinstance(metadata.get("multiagent"), dict):
raise ValueError(f"{trace_id}: missing multiagent metadata")
output = copy.deepcopy(row)
messages = copy.deepcopy(row.get("initial_messages") or [])
tools = copy.deepcopy(row.get("tools") or [])
source_requests: list[dict[str, Any]] = []
totals: Counter[str] = Counter()
generate_index = 0
for event_index, event in enumerate(output["events"]):
kind = event.get("type")
if kind == "append_message":
messages.append(copy.deepcopy(event["message"]))
continue
if kind == "replace_context":
messages = copy.deepcopy(event["messages"])
continue
if kind == "wait":
continue
if kind != "generate":
raise ValueError(f"{trace_id}: unknown event type {kind!r}")
assistant = event.get("recorded_assistant")
source_prompt_ids = event.get("recorded_prompt_token_ids")
source_output_ids = event.get("recorded_output_token_ids")
if (
not isinstance(assistant, dict)
or not isinstance(source_prompt_ids, list)
or not source_prompt_ids
or not isinstance(source_output_ids, list)
or not source_output_ids
):
raise ValueError(
f"{trace_id}: request {generate_index} lacks complete source contract"
)
location = f"{trace_id}/request-{generate_index}"
prompt_messages = prepare_messages(
messages,
tools=tools,
location=location,
audit=audit,
)
completed_messages = prepare_messages(
messages + [assistant],
tools=tools,
location=location,
audit=audit,
)
prompt_text = encoder.encode_messages(
prompt_messages,
thinking_mode="thinking",
reasoning_effort="high",
reasoning_effort_profile="preview",
)
completed_text = encoder.encode_messages(
completed_messages,
thinking_mode="thinking",
reasoning_effort="high",
reasoning_effort_profile="preview",
)
if not completed_text.startswith(prompt_text):
raise ValueError(f"{location}: assistant is not a text continuation")
prompt_ids = tokenizer.encode(prompt_text)
completed_ids = tokenizer.encode(completed_text)
if completed_ids[: len(prompt_ids)] != prompt_ids:
raise ValueError(f"{location}: completed tokens do not extend prompt tokens")
output_ids = completed_ids[len(prompt_ids) :]
if not prompt_ids or prompt_ids[0] != tokenizer.bos_token_id:
raise ValueError(f"{location}: converted prompt lacks DSV4 BOS")
if not output_ids or output_ids[-1] != tokenizer.eos_token_id:
raise ValueError(f"{location}: converted output lacks DSV4 EOS")
if max(prompt_ids) >= vocab_size or max(output_ids) >= vocab_size:
raise ValueError(f"{location}: converted token exceeds vocab size")
if len(prompt_ids) + len(output_ids) > context_limit:
raise ValueError(
f"{location}: context {len(prompt_ids) + len(output_ids)} "
f"exceeds {context_limit}"
)
target_prompt_sha256 = sha256_json(prompt_ids)
target_output_sha256 = sha256_json(output_ids)
source_requests.append(
{
"event_index": event_index,
"generate_index": generate_index,
"source_model": event.get("source_model"),
"source_prompt_tokens": len(source_prompt_ids),
"source_output_tokens": len(source_output_ids),
"source_prompt_sha256": sha256_json(source_prompt_ids),
"source_output_sha256": sha256_json(source_output_ids),
"target_prompt_tokens": len(prompt_ids),
"target_output_tokens": len(output_ids),
"target_prompt_sha256": target_prompt_sha256,
"target_output_sha256": target_output_sha256,
}
)
event["recorded_prompt_token_ids"] = prompt_ids
event["recorded_prompt_token_count"] = len(prompt_ids)
event["recorded_prompt_token_ids_sha256"] = target_prompt_sha256
event["recorded_output_token_ids"] = output_ids
event["max_tokens"] = len(output_ids)
totals["requests"] += 1
totals["source_prompt_tokens"] += len(source_prompt_ids)
totals["source_output_tokens"] += len(source_output_ids)
totals["target_prompt_tokens"] += len(prompt_ids)
totals["target_output_tokens"] += len(output_ids)
totals["target_max_prompt_tokens"] = max(
totals["target_max_prompt_tokens"], len(prompt_ids)
)
totals["target_max_output_tokens"] = max(
totals["target_max_output_tokens"], len(output_ids)
)
messages.append(copy.deepcopy(assistant))
generate_index += 1
return output, dict(totals), source_requests
def write_root_bundle(
*,
output_dir: Path,
root_id: str,
actor_rows: list[dict[str, Any]],
actor_totals: list[dict[str, int]],
) -> dict[str, Any]:
if ROOT_ID_RE.fullmatch(root_id) is None:
raise ValueError(f"unsafe root id: {root_id!r}")
archive_path = output_dir / f"{root_id}.tar.gz"
if archive_path.exists():
raise FileExistsError(archive_path)
totals: Counter[str] = Counter()
for row in actor_totals:
for key, value in row.items():
if key.startswith("target_max_"):
totals[key] = max(totals[key], value)
else:
totals[key] += value
manifest = {
"schema_version": 1,
"root_id": root_id,
"actors": len(actor_rows),
"lead_actors": sum(
row["metadata"]["multiagent"].get("parent_trace_id") is None
for row in actor_rows
),
**dict(totals),
}
with tempfile.TemporaryDirectory(prefix=f"{root_id}-", dir=output_dir) as temp:
root = Path(temp) / root_id
root.mkdir()
actors_path = root / "actors.jsonl"
with actors_path.open("w", encoding="utf-8") as handle:
for row in actor_rows:
handle.write(
json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n"
)
(root / "manifest.json").write_text(
json.dumps(manifest, indent=2, sort_keys=True) + "\n",
encoding="utf-8",
)
temp_archive = archive_path.with_suffix(archive_path.suffix + ".tmp")
with tarfile.open(temp_archive, "w:gz", compresslevel=1) as archive:
archive.add(root, arcname=root_id)
os.replace(temp_archive, archive_path)
manifest["archive"] = archive_path.name
manifest["archive_bytes"] = archive_path.stat().st_size
manifest["archive_sha256"] = sha256_file(archive_path)
return manifest
def rows(path: Path) -> Iterable[dict[str, Any]]:
with lzma.open(path, "rt", encoding="utf-8") as handle:
for line_number, line in enumerate(handle, 1):
try:
yield json.loads(line)
except json.JSONDecodeError as error:
raise ValueError(f"invalid JSONL row {line_number}") from error
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--input-xz", type=Path, required=True)
parser.add_argument("--output-dir", type=Path, required=True)
parser.add_argument("--target-model", type=Path, required=True)
parser.add_argument("--dsv4-encoder", type=Path, required=True)
parser.add_argument("--source-artifact-sha256", required=True)
parser.add_argument("--max-roots", type=int)
parser.add_argument("--shard-count", type=int, default=1)
parser.add_argument("--shard-index", type=int, default=0)
args = parser.parse_args()
if args.output_dir.exists():
raise FileExistsError(args.output_dir)
if args.max_roots is not None and args.max_roots <= 0:
raise ValueError("--max-roots must be positive")
if args.shard_count <= 0 or not 0 <= args.shard_index < args.shard_count:
raise ValueError("shard index must be in [0, shard count)")
args.output_dir.mkdir(parents=True)
tokenizer = AutoTokenizer.from_pretrained(
args.target_model,
trust_remote_code=True,
local_files_only=True,
)
encoder = load_encoder(args.dsv4_encoder)
model_config = json.loads((args.target_model / "config.json").read_text())
vocab_size = int(model_config["vocab_size"])
context_limit = int(model_config["max_position_embeddings"])
if not isinstance(tokenizer.eos_token_id, int):
raise TypeError("target tokenizer lacks EOS token")
audit: Counter[str] = Counter()
archives: list[dict[str, Any]] = []
current_root: str | None = None
actor_rows: list[dict[str, Any]] = []
actor_totals: list[dict[str, int]] = []
seen_roots: set[str] = set()
seen_input_roots: set[str] = set()
input_root: str | None = None
input_root_index = -1
selected = False
request_audit_rows = 0
def flush() -> bool:
nonlocal actor_rows, actor_totals, current_root
if current_root is None:
return False
archives.append(
write_root_bundle(
output_dir=args.output_dir,
root_id=current_root,
actor_rows=actor_rows,
actor_totals=actor_totals,
)
)
print(json.dumps(archives[-1], sort_keys=True), flush=True)
seen_roots.add(current_root)
actor_rows = []
actor_totals = []
current_root = None
return args.max_roots is not None and len(archives) >= args.max_roots
started = time.time()
request_audit_path = args.output_dir / "request-token-audit.jsonl.xz"
with lzma.open(
request_audit_path,
"wt",
encoding="utf-8",
preset=1,
) as request_audit:
for source_row in rows(args.input_xz):
root_id = source_row["metadata"]["multiagent"]["root_task_id"]
if root_id != input_root:
if current_root is not None and flush():
break
if root_id in seen_input_roots:
raise ValueError(f"non-contiguous root block: {root_id}")
seen_input_roots.add(root_id)
input_root = root_id
input_root_index += 1
selected = input_root_index % args.shard_count == args.shard_index
if selected:
if root_id in seen_roots:
raise ValueError(f"selected root repeated: {root_id}")
current_root = root_id
if not selected:
continue
output_row, totals, request_rows = converted_actor(
source_row,
tokenizer=tokenizer,
encoder=encoder,
vocab_size=vocab_size,
context_limit=context_limit,
audit=audit,
)
actor_rows.append(output_row)
actor_totals.append(totals)
for request_row in request_rows:
request_audit.write(
json.dumps(
{
"root_id": root_id,
"trace_id": output_row["trace_id"],
**request_row,
},
separators=(",", ":"),
sort_keys=True,
)
+ "\n"
)
request_audit_rows += 1
if current_root is not None and (
args.max_roots is None or len(archives) < args.max_roots
):
flush()
global_totals: Counter[str] = Counter()
for item in archives:
for key in (
"actors",
"lead_actors",
"requests",
"source_prompt_tokens",
"source_output_tokens",
"target_prompt_tokens",
"target_output_tokens",
):
global_totals[key] += int(item[key])
for key in ("target_max_prompt_tokens", "target_max_output_tokens"):
global_totals[key] = max(global_totals[key], int(item[key]))
seal = {
"schema_version": 1,
"kind": "morphosis-dsv4-materialization",
"created_at_s": time.time(),
"elapsed_s": time.time() - started,
"source": {
"artifact_sha256": args.source_artifact_sha256,
"logical_order_xz": str(args.input_xz),
"logical_order_xz_sha256": sha256_file(args.input_xz),
},
"target": {
"model": "deepseek-v4-flash",
"model_path": str(args.target_model),
"vocab_size": vocab_size,
"context_limit": context_limit,
"eos_token_id": tokenizer.eos_token_id,
"tokenizer_sha256": sha256_file(args.target_model / "tokenizer.json"),
"tokenizer_config_sha256": sha256_file(
args.target_model / "tokenizer_config.json"
),
"dsv4_encoder": str(args.dsv4_encoder),
"dsv4_encoder_sha256": sha256_file(args.dsv4_encoder),
"thinking_mode": "thinking",
"reasoning_effort": "high",
"reasoning_effort_profile": "preview",
},
"shard": {
"count": args.shard_count,
"index": args.shard_index,
"input_roots_seen": len(seen_input_roots),
},
"roots": len(archives),
"totals": dict(global_totals),
"content_audit": dict(sorted(audit.items())),
"request_token_audit": {
"path": request_audit_path.name,
"rows": request_audit_rows,
"sha256": sha256_file(request_audit_path),
},
"archives": archives,
}
(args.output_dir / "materialization-seal.json").write_text(
json.dumps(seal, indent=2, sort_keys=True) + "\n",
encoding="utf-8",
)
with (args.output_dir / "archives.sha256").open("w") as handle:
for item in archives:
handle.write(f"{item['archive_sha256']} {item['archive']}\n")
print(json.dumps({"seal": seal}, sort_keys=True), flush=True)
if __name__ == "__main__":
main()