Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
test(perf): add CPU and MPS detector benchmark tools
myhlolic3d34f379f1f
diff --git a/tools/analyze_det_cpu.py b/tools/analyze_det_cpu.pynew file mode 100644index 00000000..176e4c06--- /dev/null+++ b/tools/analyze_det_cpu.py@@ -0,0 +1,279 @@+"""仅重放冻结 det 输入,拆开比较 CPU Conv-BN 融合及 N=1 拆分。"""++from __future__ import annotations++import argparse+import hashlib+import json+import shutil+import statistics+from pathlib import Path+from typing import Any++from analyze_det_fusion import execute_run, load_runs+from benchmark_det_corpus import DEFAULT_CORPUS, project_replay_shape, read_json+from benchmark_mps_det_service import write_json++NAMES = {"A": "CPU 原 batch", "L": "CPU 原 batch+融合 36 组", "M": "CPU N=1 拆分,无融合", "N": "CPU N=1 拆分+融合 36 组"}+FUSION_DOC = "https://docs.pytorch.org/docs/2.14/generated/torch.nn.utils.fusion.fuse_conv_bn_eval.html"+++def collect(args: argparse.Namespace) -> dict[str, Any]:+ """独立复核已保存框、实际 NCHW、CPU/FP32、融合结构和源码指纹后汇总各轮数据。"""+ manifest = read_json(args.corpus / "manifest.json")+ documents = {row["name"]: row for row in manifest["documents"]}+ required = {(call["box_thresh"], call["unclip_ratio"]) for doc in documents.values() for call in doc["calls"]}+ fingerprints = set()+ groups: dict[str, dict[str, Any]] = {}+ for entry in load_runs(args.output):+ if entry["directory"] not in {"smoke", "round-1", "round-2", "repeat"}:+ continue+ policy, protocol, env, rows = entry["policy"], entry["protocol"], entry["environment"], entry["records"]+ assert protocol["cycles"] == 1 and protocol["documents"] == "tender,python,114"+ assert not protocol["start_call"] and not protocol["call_indices"] and not protocol["save_maps"]+ if entry["directory"] != "smoke":+ assert not protocol["limit_calls"]+ assert env["threads"] == 4 and env["interop_threads"] == 10+ assert env["det_source_sha256_before"] == env["det_source_sha256_after"]+ fingerprints.add(+ tuple(+ env[key]+ for key in (+ "python",+ "torch_commit",+ "threads",+ "interop_threads",+ "model_sha256",+ "script_sha256",+ "shape_adapter_sha256",+ "det_source_sha256_before",+ "det_source_sha256_after",+ )+ )+ + (env.get("cpu_microbatch_adapter_sha256", ""),)+ )+ profiles = {tuple(model["profile"]) for row in rows for model in row["models"]}+ assert profiles == required+ for profile in profiles:+ assert len({model["net_id"] for row in rows for model in row["models"] if tuple(model["profile"]) == profile}) == 1+ for row in rows:+ for model in row["models"]:+ assert model["device"] == "cpu" and model["dtype"] == "torch.float32"+ assert model["fusion"]["before_bn"] == 36+ assert model["fusion"]["after_bn"] == (0 if policy in {"L", "N"} else 36)+ assert len(model["fusion"]["pairs"]) == (36 if policy in {"L", "N"} else 0)+ calls = documents[row["document"]]["calls"]+ if protocol["limit_calls"]:+ calls = calls[: protocol["limit_calls"]]+ actual = read_json(args.output / entry["directory"] / policy / f"{row['label']}-boxes.json")+ expected = [+ (call_index, item_index, call, item)+ for call_index, call in enumerate(calls)+ for item_index, item in enumerate(call["items"])+ ]+ assert len(actual) == len(expected) == row["crops"]+ for result, (call_index, item_index, call, item) in zip(actual, expected):+ assert (+ result["crop"] == item["crop"] and result["call_index"] == call_index and result["item_index"] == item_index+ )+ assert result["profile"] == [call["box_thresh"], call["unclip_ratio"]]+ assert result["reference_equal"] == (result["boxes"] == item["boxes"])+ assert row["reference_exact_crops"] == sum(result["reference_equal"] for result in actual)+ for metric in row["call_metrics"]:+ assert metric["network_shapes"] == project_replay_shape(metric["shape"], policy)["network_shapes"]+ count = sum(row["crops"] for row in rows)+ if entry["directory"] != "smoke":+ assert count == 2280 and sum(row["calls"] for row in rows) == 638+ loading = sum(model["loading_seconds"] for model in env["model_loads"])+ fusion = sum(model["fusion"]["seconds"] for model in env["model_loads"])+ cleanup = sum(row["cleanup_seconds"] for row in rows) + env["shutdown_seconds"]+ seconds = sum(row["seconds"] for row in rows)+ value = {+ "det_seconds": seconds,+ "loading_seconds": loading,+ "fusion_seconds": fusion,+ "cleanup_seconds": cleanup,+ "operational_seconds": loading + fusion + seconds + cleanup,+ "inputs": count,+ "exact": all(row["reference_exact_crops"] == row["crops"] for row in rows),+ "differences": sum(len(row["differences"]) for row in rows),+ "forward_calls": sum(len(metric["network_shapes"]) for row in rows for metric in row["call_metrics"]),+ "peak_footprint": max(+ [row["peak_memory_diagnostics"]["phys_footprint"] for row in rows]+ + [+ env["shutdown_memory_diagnostics_before"]["phys_footprint"],+ env["shutdown_memory_diagnostics_after"]["phys_footprint"],+ ]+ ),+ "documents": rows,+ "environment": env,+ }+ groups.setdefault(entry["directory"], {})[policy] = value+ if len(fingerprints) > 1:+ raise ValueError("运行环境、权重或推理源码不同,不能合并比较")+ return {+ "groups": groups,+ "matched_environment": len(fingerprints) == 1,+ "manifest_sha256": hashlib.sha256((args.corpus / "manifest.json").read_bytes()).hexdigest(),+ }+++def summarize(args: argparse.Namespace) -> None:+ """区分融合和拆批的独立收益,展示逐文档阶段耗时、内存和加载清理成本。"""+ summary = collect(args)+ groups = summary["groups"]+ formal = {name: group for name, group in groups.items() if name != "smoke"}+ assert {"round-1", "round-2"}.issubset(formal)+ policies = list(groups["round-1"])+ assert all(set(group) == set(policies) for group in formal.values())+ medians = {}+ rows, docs, memories = [], [], []+ for policy in policies:+ values = [group[policy] for group in formal.values()]+ medians[policy] = {+ "det_seconds": statistics.median(value["det_seconds"] for value in values),+ "operational_seconds": statistics.median(value["operational_seconds"] for value in values),+ "outputs_exact": all(value["exact"] for value in values),+ "peak_footprint": max(value["peak_footprint"] for value in values),+ }+ for name, group in formal.items():+ for policy, value in group.items():+ rows.append(+ f"| {name} | {policy} | {value['det_seconds']:.3f} | {value['loading_seconds']:.3f} | "+ f"{value['fusion_seconds']:.4f} | {value['cleanup_seconds']:.3f} | {value['operational_seconds']:.3f} | "+ f"{value['peak_footprint'] / 1024**3:.3f} | {value['exact']} | {value['forward_calls']} |"+ )+ for row in value["documents"]:+ stages = row["stages"]+ docs.append(+ f"| {name} | {policy} | {row['document']} | {row['seconds']:.3f} | {stages['preprocess']:.3f} | "+ f"{stages['forward']:.3f} | {stages['output_transfer']:.3f} | {stages['postprocess']:.3f} |"+ )+ diagnostics = row["memory_diagnostics_after"]+ memories.append(+ f"| {name} | {policy} | {row['document']} | {row['memory_after']['rss'] / 1024**3:.3f} | "+ f"{diagnostics['phys_footprint'] / 1024**3:.3f} | {diagnostics['compressed'] / 1024**3:.3f} | "+ f"{diagnostics['system_swap_used'] / 1024**3:.3f} |"+ )+ baseline = medians["A"]["det_seconds"]+ for policy, value in medians.items():+ value["reduction_vs_a"] = 1 - value["det_seconds"] / baseline+ value["per_round_reductions"] = [+ 1 - group[policy]["det_seconds"] / group["A"]["det_seconds"] for group in formal.values()+ ]+ comparisons = {+ f"{before}_to_{after}": 1 - medians[after]["det_seconds"] / medians[before]["det_seconds"]+ for before, after in (("A", "L"), ("A", "M"), ("M", "N"), ("L", "N"))+ if before in medians and after in medians+ }+ summary.update({"medians": medians, "comparisons": comparisons})+ write_json(args.output / "summary.json", summary)+ headline = [+ f"| {policy} {NAMES[policy]} | {value['det_seconds']:.3f} | {value['reduction_vs_a']:.1%} | "+ f"{value['operational_seconds']:.3f} | {value['peak_footprint'] / 1024**3:.3f} | {value['outputs_exact']} |"+ for policy, value in medians.items()+ ]+ report = f"""# CPU det:Conv+BN 融合与 N=1 拆分++相同三份冻结文档(95/88/114 页),2280 个输入,原顺序、原 H/W、两组后处理参数;不重跑 PDF。+所有策略为 CPU/FP32,生产线程 4/10,两组模型在各自进程内复用,每本文档沿用原清理。+烟测每份文档前 12 次调用,参数覆盖及框检查通过的策略才进入正式轮次。+全量正序 A/L/M/N、反序 N/M/L/A,独立新进程串行,无额外前向预热。+若小幅候选收益或两轮方向相反,再追加一轮对照;重复数据始终单列,不冒充原定轮次。+实际源码归档在 executed-scripts/,权重及推理源码校验在每个 environment.json。++| 策略 | 三文档 det 中位数秒 | 相对 A 耗时降低 | 加载+融合+det+清理中位数秒 | 采样峰 footprint GiB | 框完全一致 |+| --- | ---: | ---: | ---: | ---: | --- |+{chr(10).join(headline)}++融合仅限 eval 下已有的 36 组 Conv+BN,在 CPU 加载及原重参数化后使用+[fuse_conv_bn_eval]({FUSION_DOC}),head 反卷积使用 transpose=True;融合后的 BN 全部替换为 Identity。+M/N 保留 batch 前后处理,仅逐个 N=1 网络前向;没有 H/W 或虚假样本补齐。+各次调用的实际 NCHW 已断言。A/L 为 638 次前向,M/N 为 2280 次。+比较 A→L 看原 batch 融合收益,A→M 看未融合 N 拆分收益,M→N 看拆批后的融合收益,L→N 看融合后的拆批收益。+上述配对的中位数耗时降低率:{json.dumps(comparisons, ensure_ascii=False)}。++| 轮次 | 策略 | det 秒 | 加载秒 | 融合秒 | 清理秒 | 合计秒 | 峰 footprint GiB | 框一致 | 前向次数 |+| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | --- | ---: |+{chr(10).join(rows)}++| 轮次 | 策略 | 文档 | det 秒 | 前处理秒 | forward 秒 | 回传秒 | 后处理秒 |+| --- | --- | --- | ---: | ---: | ---: | ---: | ---: |+{chr(10).join(docs)}++| 轮次 | 策略 | 文档 | 清理后 RSS GiB | footprint GiB | compressed GiB | 全机 swap GiB |+| --- | --- | --- | ---: | ---: | ---: | ---: |+{chr(10).join(memories)}++det 包含真实前处理、张量准备、forward、回传、DB 后处理及循环调度;PNG 读取、采样和保存排除在外。+原始框被独立重读并核对数量、顺序和四点坐标,差异输入及叠框保存在对应 review/。+CPU 执行同步完成。内存沿用原调用结束采样,采样峰值不代表算子内部瞬时峰值;各内存指标不能相加,swap 属于全机。+仅代表本机 M4、当前 tiny/FP32 det,不能泛化其他 CPU 平台、完整 Basic/OCR 或 Standard/VLM。+本轮不更改生产默认、公开接口或原权重文件。++```bash+.venv4/bin/python tools/analyze_det_cpu.py experiment --output NEW_OUTPUT+.venv4/bin/python tools/analyze_det_cpu.py summarize --output {args.output}+.venv4/bin/python tools/benchmark_det_corpus.py run --policies A,L,M,N --cycles 1 --limit-calls 12 --output NEW_SMOKE+```+"""+ (args.output / "report.md").write_text(report, encoding="utf-8")+ print(json.dumps({"medians": medians, "comparisons": comparisons}, ensure_ascii=False), flush=True)+++def experiment(args: argparse.Namespace) -> None:+ """先烟测四种 CPU 策略,再正反两轮测速;小收益或方向变化时补一轮确认。"""+ args.output.mkdir(parents=True, exist_ok=False)+ archive = args.output / "executed-scripts"+ archive.mkdir()+ for name in (+ "benchmark_det_corpus.py",+ "benchmark_mps_det_service.py",+ "det_shape_buckets.py",+ "analyze_det_fusion.py",+ Path(__file__).name,+ ):+ shutil.copy2(Path(__file__).parent / name, archive / name)+ execute_run(args, "smoke", "A,L,M,N", limit_calls=12)+ smoke = collect(args)["groups"]["smoke"]+ assert smoke["A"]["exact"], "CPU 基线烟测框不一致,停止正式对照"+ eligible = [policy for policy in NAMES if smoke[policy]["exact"]]+ state = {"phase": "round-1", "policies": eligible, "excluded": [policy for policy in NAMES if policy not in eligible]}+ write_json(args.output / "experiment.json", state)+ execute_run(args, "round-1", ",".join(eligible))+ state["phase"] = "round-2"+ write_json(args.output / "experiment.json", state)+ execute_run(args, "round-2", ",".join(reversed(eligible)))+ groups = collect(args)["groups"]+ noisy = []+ for policy in eligible:+ if policy == "A":+ continue+ reductions = [+ 1 - groups[name][policy]["det_seconds"] / groups[name]["A"]["det_seconds"] for name in ("round-1", "round-2")+ ]+ if any(0 < value < 0.1 for value in reductions) or min(reductions) <= 0 < max(reductions):+ noisy.append(policy)+ if noisy:+ state.update({"phase": "repeat", "repeat_reason": noisy})+ write_json(args.output / "experiment.json", state)+ execute_run(args, "repeat", ",".join(eligible))+ summarize(args)+ state["phase"] = "complete"+ write_json(args.output / "experiment.json", state)+++def main() -> None:+ """提供可复测的 CPU 对照入口,默认设备和既有 ABC 实验行为不变。"""+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("command", choices=("experiment", "summarize"))+ parser.add_argument("--output", required=True, type=Path)+ parser.add_argument("--corpus", type=Path, default=DEFAULT_CORPUS)+ args = parser.parse_args()+ args.output, args.corpus = args.output.resolve(), args.corpus.resolve()+ args.documents = "tender,python,114"+ {"experiment": experiment, "summarize": summarize}[args.command](args)+++if __name__ == "__main__":+ main()diff --git a/tools/analyze_det_fusion.py b/tools/analyze_det_fusion.pynew file mode 100644index 00000000..ae0c1e2d--- /dev/null+++ b/tools/analyze_det_fusion.py@@ -0,0 +1,512 @@+"""调度并验收冻结 det 语料的融合实验,不改变生产模型或设备策略。"""++from __future__ import annotations++import argparse+import json+import shutil+import statistics+from pathlib import Path+from typing import Any++from benchmark_det_corpus import read_json, run+from benchmark_mps_det_service import write_json+++def execute_run(args: argparse.Namespace, directory: str, policies: str, **changes: Any) -> None:+ """使用同一个 det 重放入口启动独立进程,所有策略始终串行执行。"""+ values = vars(args) | {+ "output": args.output / directory,+ "policies": policies,+ "cycles": 1,+ "limit_calls": 0,+ "start_call": 0,+ "call_indices": "",+ "save_maps": False,+ }+ run(argparse.Namespace(**(values | changes)))+++def load_runs(root: Path) -> list[dict[str, Any]]:+ """读取已完成的实验运行,不把概率图诊断混入正式计时和内存验收。"""+ runs = []+ for directory in sorted(root.iterdir()):+ if not directory.is_dir() or directory.name == "diagnostics" or not (directory / "protocol.json").exists():+ continue+ protocol = read_json(directory / "protocol.json")+ for policy in protocol["policies"].split(","):+ target = directory / policy+ if not (target / "environment.json").exists():+ continue+ runs.append(+ {+ "directory": directory.name,+ "policy": policy,+ "protocol": protocol,+ "records": read_json(target / "results.json"),+ "environment": read_json(target / "environment.json"),+ }+ )+ return runs+++def select_candidate(summary: dict[str, Any], passed_only: bool) -> str | None:+ """从输出和内存合格的候选选最快者,差距不足 5% 时优先融合范围较小的 D。"""+ candidates = summary["candidates"]+ available = [+ policy+ for policy in ("D", "E")+ if policy in candidates and candidates[policy]["research_pass" if passed_only else "eligible"]+ ]+ if not available:+ return None+ winner = min(available, key=lambda policy: candidates[policy]["median_det_seconds"])+ if set(available) == {"D", "E"}:+ slower = max(candidates[policy]["median_det_seconds"] for policy in available)+ faster = min(candidates[policy]["median_det_seconds"] for policy in available)+ if 1 - faster / slower < 0.05:+ return "D"+ return winner+++def collect_summary(args: argparse.Namespace) -> dict[str, Any]:+ """按独立进程轮次计算配对中位数、严格框一致性、8 GiB 预算与生命周期门槛。"""+ runs = load_runs(args.output)+ smoke = [entry for entry in runs if entry["directory"].startswith("smoke")]+ formal = [entry for entry in runs if entry["directory"].startswith("round-")]+ lifecycle = [entry for entry in runs if entry["directory"] == "lifecycle"]+ required_profiles = {+ (call["box_thresh"], call["unclip_ratio"])+ for document in read_json(args.corpus / "manifest.json")["documents"]+ for call in document["calls"]+ }+ smoke_checks = {}+ for policy in "ABDE":+ entries = [entry for entry in smoke if entry["policy"] == policy]+ records = [row for entry in entries for row in entry["records"]]+ profiles = {tuple(model["profile"]) for row in records for model in row["models"]}+ smoke_checks[policy] = {+ "exact": bool(records) and all(row["crops"] == row["reference_exact_crops"] for row in records),+ "profiles_complete": profiles == required_profiles,+ "inputs": sum(row["crops"] for row in records),+ "differences": sum(len(row["differences"]) for row in records),+ }+ by_round: dict[str, dict[str, Any]] = {}+ for entry in formal:+ protocol = entry["protocol"]+ if (+ protocol["cycles"] != 1+ or protocol["limit_calls"]+ or protocol["start_call"]+ or protocol["call_indices"]+ or protocol["save_maps"]+ ):+ raise ValueError("正式轮次必须整份语料单遍重放,不能筛选调用、另存 maps 或混入生命周期运行")+ if protocol["documents"] != "tender,python,114":+ raise ValueError("正式文档顺序与约定不同")+ environment = entry["environment"]+ records = entry["records"]+ loading = sum(load["loading_seconds"] for load in environment["model_loads"])+ fusion = sum(load["fusion"]["seconds"] for load in environment["model_loads"])+ det = sum(row["seconds"] for row in records)+ cleanup = sum(row["cleanup_seconds"] for row in records) + environment["shutdown_seconds"]+ peak = max(row["peak_memory_diagnostics"]["phys_footprint"] for row in records)+ peak = max(+ peak,+ environment["shutdown_memory_diagnostics_before"]["phys_footprint"],+ environment["shutdown_memory_diagnostics_after"]["phys_footprint"],+ )+ by_round.setdefault(entry["directory"], {})[entry["policy"]] = {+ "det_seconds": det,+ "loading_seconds": loading,+ "fusion_seconds": fusion,+ "cleanup_seconds": cleanup,+ "operational_seconds": loading + fusion + det + cleanup,+ "peak_footprint": peak,+ "exact": all(row["crops"] == row["reference_exact_crops"] for row in records),+ }+ environments = [entry["environment"] for entry in runs]+ matched_environment = (+ len(+ {+ (+ environment["model_sha256"],+ environment["torch_commit"],+ environment["python"],+ environment["threads"],+ environment["interop_threads"],+ environment["git_head"],+ environment["script_sha256"],+ )+ for environment in environments+ }+ )+ == 1+ if environments+ else False+ )+ fp32 = all(model["dtype"] == "torch.float32" for entry in runs for row in entry["records"] for model in row["models"])+ models_reused = all(+ len({model["net_id"] for row in entry["records"] for model in row["models"] if tuple(model["profile"]) == profile}) == 1+ for entry in runs+ for profile in {tuple(model["profile"]) for row in entry["records"] for model in row["models"]}+ )+ baseline_exact = all(smoke_checks[policy]["exact"] and smoke_checks[policy]["profiles_complete"] for policy in "AB")+ baseline_exact &= all(value["exact"] for group in by_round.values() for policy, value in group.items() if policy in "AB")+ candidates = {}+ for policy in "DE":+ paired = [group for group in by_round.values() if {"A", "B", policy}.issubset(group)]+ if not paired:+ continue+ seconds = statistics.median(group[policy]["det_seconds"] for group in paired)+ cpu = statistics.median(group["A"]["det_seconds"] for group in paired)+ mps = statistics.median(group["B"]["det_seconds"] for group in paired)+ exact = smoke_checks[policy]["exact"] and all(group[policy]["exact"] for group in paired)+ peak = max(group[policy]["peak_footprint"] for group in paired)+ eligible = exact and peak <= 8 * 1024**3 and matched_environment and fp32 and models_reused and baseline_exact+ improvements = [1 - group[policy]["det_seconds"] / group["B"]["det_seconds"] for group in paired]+ majority = sum(value > 0 for value in improvements) > len(paired) / 2+ reduction = 1 - seconds / mps+ cpu_reduction = 1 - seconds / cpu+ candidates[policy] = {+ "rounds": len(paired),+ "median_det_seconds": seconds,+ "matched_cpu_seconds": cpu,+ "matched_mps_seconds": mps,+ "reduction_vs_b": reduction,+ "reduction_vs_a": cpu_reduction,+ "round_improvements_vs_b": improvements,+ "peak_footprint": peak,+ "outputs_exact": exact,+ "eligible": eligible,+ "research_pass": eligible and len(paired) >= 2 and reduction >= 0.25 and majority,+ "repeat_needed": eligible+ and (+ reduction < 0.1+ or (any(value <= 0 for value in improvements) and any(value > 0 for value in improvements))+ or abs(reduction - 0.25) < 0.05+ or abs(cpu_reduction - 0.25) < 0.05+ ),+ "lifecycle_pass": None,+ "default_candidate": False,+ }+ for entry in lifecycle:+ policy = entry["policy"]+ records = entry["records"]+ if len(records) != 6 or policy not in candidates:+ raise ValueError("生命周期验证必须为候选连续两遍三文档")+ first = records[2]["memory_after"] | {"footprint": records[2]["memory_diagnostics_after"]["phys_footprint"]}+ second = records[5]["memory_after"] | {"footprint": records[5]["memory_diagnostics_after"]["phys_footprint"]}+ growth = {+ key: {+ "first": first[key],+ "second": second[key],+ "delta": second[key] - first[key],+ "limit": max(first[key] * 0.1, 256 * 1024**2),+ }+ for key in first+ }+ peak = max(row["peak_memory_diagnostics"]["phys_footprint"] for row in records)+ exact = all(row["crops"] == row["reference_exact_crops"] for row in records)+ passed = exact and peak <= 8 * 1024**3 and all(value["delta"] <= value["limit"] for value in growth.values())+ candidates[policy].update({"lifecycle_pass": passed, "lifecycle_growth": growth, "lifecycle_peak_footprint": peak})+ candidates[policy]["default_candidate"] = (+ candidates[policy]["research_pass"] and passed and candidates[policy]["reduction_vs_a"] >= 0.25+ )+ return {+ "smoke": smoke_checks,+ "rounds": by_round,+ "candidates": candidates,+ "matched_environment": matched_environment,+ "fp32": fp32,+ "models_reused": models_reused,+ "baseline_exact": baseline_exact,+ "runs": runs,+ }+++def diagnose_differences(args: argparse.Namespace, baseline_policies: tuple[str, ...] = ("A", "B")) -> None:+ """按文档集中重放所有差异调用,独立保存 CPU、MPS 基线和候选的概率图。"""+ import numpy as np++ groups: dict[str, dict[str, set[Any]]] = {}+ for entry in load_runs(args.output):+ for row in entry["records"]:+ for difference in row["differences"]:+ group = groups.setdefault(row["document"], {"indices": set(), "policies": set(baseline_policies)})+ group["indices"].add(difference["call_index"])+ group["policies"].add(entry["policy"])+ comparisons = []+ for document, group in groups.items():+ directory = f"diagnostics/{document}"+ indices = sorted(group["indices"])+ policies = sorted(group["policies"])+ execute_run(+ args, directory, ",".join(policies), documents=document, call_indices=",".join(map(str, indices)), save_maps=True+ )+ for index in indices:+ filename = f"01-{document}-call{index:04d}.npz"+ with np.load(args.output / directory / "A/maps" / filename) as saved:+ reference = saved["maps"]+ for policy in policies:+ if policy == "A":+ continue+ with np.load(args.output / directory / policy / "maps" / filename) as saved:+ actual = saved["maps"]+ delta = np.abs(actual - reference)+ comparisons.append(+ {+ "document": document,+ "call_index": index,+ "policy": policy,+ "shape": list(actual.shape),+ "finite": bool(np.isfinite(actual).all()),+ "max_abs": float(delta.max()),+ "mean_abs": float(delta.mean()),+ "threshold_changed_pixels": int(np.count_nonzero((actual > 0.3) != (reference > 0.3))),+ }+ )+ write_json(args.output / "probability-diagnostics.json", comparisons)+++def fusion_experiment(args: argparse.Namespace) -> None:+ """先烟测再按门槛执行两轮、必要复测和生命周期验证,失败候选不进入正式测速。"""+ if args.documents != "tender,python,114" or args.start_call or args.limit_calls or args.call_indices or args.save_maps:+ raise ValueError("自动融合实验使用固定完整语料;定点调试请使用 run")+ if args.output.exists() and any(args.output.iterdir()):+ raise FileExistsError("融合实验必须使用全新的输出目录")+ args.output.mkdir(parents=True, exist_ok=True)+ source = args.output / "executed-scripts"+ source.mkdir()+ for name in ("benchmark_det_corpus.py", "analyze_det_fusion.py", "benchmark_mps_det_service.py", "det_shape_buckets.py"):+ shutil.copy2(Path(__file__).parent / name, source / name)+ state: dict[str, Any] = {"phase": "smoke", "corpus": str(args.corpus), "footprint_budget": 8 * 1024**3}+ write_json(args.output / "experiment.json", state)+ execute_run(args, "smoke", "A,B,D,E", limit_calls=12)+ summary = collect_summary(args)+ manifest = read_json(args.corpus / "manifest.json")+ seen = {tuple(model["profile"]) for entry in summary["runs"] for row in entry["records"] for model in row["models"]}+ missing = {(call["box_thresh"], call["unclip_ratio"]) for doc in manifest["documents"] for call in doc["calls"]} - seen+ for number, profile in enumerate(sorted(missing)):+ document, index = next(+ (doc["name"], index)+ for doc in manifest["documents"]+ for index, call in enumerate(doc["calls"])+ if (call["box_thresh"], call["unclip_ratio"]) == profile+ )+ execute_run(args, f"smoke-profile-{number + 1}", "A,B,D,E", documents=document, call_indices=str(index))+ summary = collect_summary(args)+ candidates = [+ policy for policy in "DE" if summary["smoke"][policy]["exact"] and summary["smoke"][policy]["profiles_complete"]+ ]+ if not summary["baseline_exact"]:+ state["phase"] = "baseline_rejected"+ elif not candidates:+ state["phase"] = "candidates_rejected_at_smoke"+ else:+ state.update({"phase": "formal", "formal_candidates": candidates})+ write_json(args.output / "experiment.json", state)+ policies = ["A", "B", *candidates]+ execute_run(args, "round-1", ",".join(policies))+ execute_run(args, "round-2", ",".join(reversed(policies)))+ summary = collect_summary(args)+ best = select_candidate(summary, passed_only=False)+ if best and summary["candidates"][best]["repeat_needed"]:+ execute_run(args, "round-3", f"A,B,{best}")+ summary = collect_summary(args)+ best = select_candidate(summary, passed_only=True)+ if best:+ state["lifecycle_policy"] = best+ execute_run(args, "lifecycle", best, cycles=2)+ state["phase"] = "complete"+ write_json(args.output / "experiment.json", state)+ diagnose_differences(args)+ fusion_summarize(args)+++def fusion_summarize(args: argparse.Namespace) -> None:+ """输出独立融合验收报告、融合清单和内存曲线,不覆盖第一轮 ABC 证据。"""+ summary = collect_summary(args)+ state = read_json(args.output / "experiment.json")+ summary["experiment"] = state+ summary["probability_diagnostics"] = (+ read_json(args.output / "probability-diagnostics.json")+ if (args.output / "probability-diagnostics.json").exists()+ else []+ )+ summary["validation"] = read_json(args.output / "validation.json") if (args.output / "validation.json").exists() else None+ write_json(args.output / "summary.json", summary)+ smoke_rows = [+ f"| {policy} | {value['inputs']} | {value['differences']} | {value['exact']} | {value['profiles_complete']} |"+ for policy, value in summary["smoke"].items()+ ]+ rows = []+ for entry in summary["runs"]:+ for row in entry["records"]:+ diagnostic = row["memory_diagnostics_after"]+ rows.append(+ f"| {entry['directory']} | {entry['policy']} | {row['label']} | {row['seconds']:.3f} | "+ f"{row['stages']['forward']:.3f} | {row['peak_memory_diagnostics']['phys_footprint'] / 1024**3:.2f} | "+ f"{diagnostic['phys_footprint'] / 1024**3:.2f} | {row['memory_after']['rss'] / 1024**3:.2f} | "+ f"{row['memory_after']['mps_driver'] / 1024**3:.2f} | {row['reference_exact_crops']}/{row['crops']} |"+ )+ totals = [+ f"| {round_name} | {policy} | {value['det_seconds']:.3f} | {value['loading_seconds']:.3f} | "+ f"{value['fusion_seconds']:.3f} | {value['cleanup_seconds']:.3f} | {value['operational_seconds']:.3f} |"+ for round_name, group in summary["rounds"].items()+ for policy, value in group.items()+ ]+ gates = [+ f"| {policy} | {value['median_det_seconds']:.3f} | {value['reduction_vs_b']:.1%} | {value['reduction_vs_a']:.1%} | "+ f"{value['peak_footprint'] / 1024**3:.2f} | {value['outputs_exact']} | {value['research_pass']} | "+ f"{value['lifecycle_pass']} | {value['default_candidate']} |"+ for policy, value in summary["candidates"].items()+ ]+ fusion = {+ entry["policy"]: entry["environment"]["model_loads"] for entry in summary["runs"] if entry["directory"] == "smoke"+ }+ write_json(args.output / "fusion-inventory.json", fusion)+ if state["phase"] == "candidates_rejected_at_smoke":+ conclusion = "D/E 在烟测阶段未通过严格检测框一致性,因此没有进入正式两轮性能验收。局部烟测耗时不能代表全量收益。"+ elif state["phase"] == "baseline_rejected":+ conclusion = "CPU/MPS 基线或参数覆盖未通过烟测,正式验收暂停;先调查基线,不能归因于融合。"+ else:+ conclusion = "正式对照已完成。研究收益和默认策略候选分别按下表判断;生命周期数据不混入速度中位数。"+ if summary["candidates"]:+ conclusions = []+ for policy, value in summary["candidates"].items():+ conclusions.append(+ f"{policy} det 中位数 {value['median_det_seconds']:.2f} 秒,比原始 MPS 降低 "+ f"{value['reduction_vs_b']:.1%};采样峰 footprint {value['peak_footprint'] / 1024**3:.2f} GiB。"+ )+ conclusion += "\n\n" + "\n".join(conclusions)+ if all(not value["eligible"] for value in summary["candidates"].values()):+ conclusion += "\n\n没有满足严格输出与 8 GiB 预算的候选,未触发追加速度复测或生命周期验证。"+ environment = summary["runs"][0]["environment"]+ differences = sum(len(row["differences"]) for entry in summary["runs"] for row in entry["records"])+ total_inputs = sum(row["crops"] for entry in summary["runs"] for row in entry["records"])+ validation_report = ""+ if summary["validation"]:+ validation_report = (+ "\n## 工具验证\n\n"+ f"旧 ABC 原始记录的聚合、门槛和差异结果逐项不变:{summary['validation']['abc_legacy_summary_unchanged']}。\n"+ "另以真实 Python 第 50 次调用验证 A/B/D/E 的概率图另存路径;各 4 个输入,"+ "float32、形状 (4,1,160,352)、数值有限且框完全一致。\n"+ "该调用的概率值并非逐像素相同,最大偏差约 1.7e-5 至 2.7e-5,"+ "没有像素跨越 0.3 阈值;结果不混入正式速度与内存门槛。\n"+ "详细证据链接保存在 validation.json。\n"+ )+ report = f"""# 每本文档清理条件下的 MPS det 融合实验++{conclusion}++状态:{state["phase"]}。仅改动实验脚本;生产设备默认、公开接口和权重文件保持原样。+语料:{args.corpus},95/88/114 页 PDF 的 2280 个普通文字 det 输入、2262 张唯一 PNG。+本实验只加载冻结 PNG 和 det;不再解析 PDF,不执行 layout/rec/VLM/导出。+A=CPU 原模型,B=MPS 原模型,D=MPS backbone 34 组融合,E=MPS 全部 36 组融合(包含 head 反卷积)。+全部 FP32、相同权重与生产线程;融合在 CPU/eval/既有 reparam 之后、MPS 迁移之前执行,不预热。+每本文档执行原 clean_memory('mps'),模型按两组后处理参数在同进程复用。+环境及原权重一致:{summary["matched_environment"]};实际 FP32:{summary["fp32"]};模型实例复用:{summary["models_reused"]}。+环境:{environment["cpu"]},{environment["platform"]},Python {environment["python"]},Torch {environment["torch"]}。+Torch commit:`{environment["torch_commit"]}`;intra/inter-op 线程:{environment["threads"]}/{environment["interop_threads"]}。+原权重 SHA256:`{environment["model_sha256"]}`;仓库版本:`{environment["git_head"]}`。+详细版本、权重 SHA256、脚本 SHA256 和融合路径在 environment.json / fusion-inventory.json。+executed-scripts/ 保留实际执行时的实验源码;基准脚本与各子进程记录的指纹一致。++## 烟测与一致性++| 策略 | 输入次数 | 差异输入数 | 框完全一致 | 参数覆盖完整 |+| --- | ---: | ---: | --- | --- |+{chr(10).join(smoke_rows)}++检测框按数量、顺序、四点坐标逐项比较,任何变化都判定未通过。+烟测和正式运行共比较 {total_inputs} 次输入,差异输入记录 {differences} 条。+每个差异保留原输入 PNG、参考/候选叠框、参数与原始坐标;位于各策略 review/ 和 results.json。+差异调用另在 diagnostics/ 中以独立进程重放 CPU、原始 MPS、涉及候选,保存原始概率图 npz。+probability-diagnostics.json 保存最大/平均概率偏差及跨 0.3 阈值像素数;这些不是放宽检测框门槛的依据。+无框差异时不产生差异概率图诊断,probability-diagnostics.json 为空列表。++## 正式性能与验收++| 轮次 | 策略 | 三文档 det 秒 | 加载/迁移秒 | 融合秒 | 清理秒(含退出) | 操作合计秒 |+| --- | --- | ---: | ---: | ---: | ---: | ---: |+{chr(10).join(totals) if totals else "| 未执行 | — | — | — | — | — | — |"}++| 候选 | det 中位数秒 | 比 B 降低 | 比 A 降低 | 采样峰 footprint GiB | 框一致 | 研究门槛 | 生命周期 | 默认策略候选 |+| --- | ---: | ---: | ---: | ---: | --- | --- | --- | --- |+{chr(10).join(gates) if gates else "| 无合格候选 | — | — | — | — | False | False | 未执行 | False |"}++正式第一轮 A→B→D→E,第二轮反向;未通过烟测的候选被剔除。三份文档顺序始终不变,每本均清理图缓存。+速度取各独立轮次三文档合计的中位数;追加轮次使用候选与当轮 A/B 配对计算。+研究门槛:比 B 降低至少 25%、多数轮次同向、严格框一致、采样峰 footprint ≤8 GiB。+默认策略候选还须比 CPU A 降低至少 25%,并通过独立两遍生命周期验证。+生命周期增长门槛:RSS、footprint、MPS allocated/driver 均不超过 max(10%,256 MiB)。+无合格候选时保持 CPU 默认;仅改善 B 而仍慢于 A 时,只认定研究收益。++## 逐文档性能与内存++| 运行 | 策略 | 文档 | det 秒 | forward 秒 | 峰 footprint GiB | 清理后 footprint GiB | RSS GiB | driver GiB | 框一致输入 |+| --- | --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |+{chr(10).join(rows)}++det 包含预处理、设备传输、同步推理、输出回传与 DB 后处理;模型加载/融合、PNG 读取、写出、比较、清理和采样在外。+“操作合计”只包含加载+融合+det+清理,不冒充完整请求或整个 worker 墙钟。+每次调用结束同步采样 footprint/compressed/RSS/allocated/driver,另记录文档清理前后和退出清理前后。+采样峰值不是算子内部瞬时峰值。footprint 包含压缩/换出页记账,与 RSS/driver 重叠,不能相加或当作当前驻留 RAM。+全机 available/swap 为系统指标,不全部归属于 det;详见每次调用 memory_diagnostics。++## 复测++```bash+.venv4/bin/python tools/benchmark_det_corpus.py fusion-experiment --output NEW_OUTPUT+.venv4/bin/python tools/benchmark_det_corpus.py fusion-summarize --output {args.output}+```++新目录保留所有原始证据;原 ABC 默认行为与入口继续可用。新增函数均有中文注释。+本结果不推导完整 Basic/OCR 或 Standard/VLM 性能,没有开展形状归并、预热或 FP16 实验。+{validation_report}+++"""+ (args.output / "report.md").write_text(report, encoding="utf-8")+ import matplotlib++ matplotlib.use("Agg")+ import matplotlib.pyplot as plt++ fig, axes = plt.subplots(1, 2, figsize=(13, 4), constrained_layout=True)+ for policy in "ABDE":+ entries = [+ entry for entry in summary["runs"] if entry["policy"] == policy and entry["directory"] in ("round-1", "smoke")+ ]+ if not entries:+ continue+ entry = next((entry for entry in entries if entry["directory"] == "round-1"), entries[0])+ rows = entry["records"]+ x = range(1, len(rows) + 1)+ axes[0].plot(x, [row["seconds"] for row in rows], "o-", label=policy)+ footprint = []+ for row in rows:+ footprint.extend(metric["memory_diagnostics"]["phys_footprint"] / 1024**3 for metric in row["call_metrics"])+ footprint.append(row["memory_diagnostics_after"]["phys_footprint"] / 1024**3)+ axes[1].plot(range(1, len(footprint) + 1), footprint, label=policy)+ axes[0].set(xlabel="Document replay index", ylabel="det seconds", title="Formal first round or rejected smoke")+ axes[1].set(+ xlabel="Call samples plus document cleanup boundaries",+ ylabel="Sampled footprint GiB",+ title="Footprint during the first formal round or smoke",+ )+ axes[1].axhline(8, color="red", linestyle="--", label="8 GiB budget")+ for axis in axes:+ axis.legend()+ axis.grid(alpha=0.25)+ fig.savefig(args.output / "performance-memory.png", dpi=160)+ plt.close(fig)+ print(+ json.dumps(+ {"phase": state["phase"], "smoke": summary["smoke"], "candidates": summary["candidates"]},+ ensure_ascii=False,+ indent=2,+ ),+ flush=True,+ )diff --git a/tools/analyze_det_microbatch.py b/tools/analyze_det_microbatch.pynew file mode 100644index 00000000..ecd4c29b--- /dev/null+++ b/tools/analyze_det_microbatch.py@@ -0,0 +1,209 @@+"""在本机冻结 det 语料上验收无融合 CPU 阈值拆分及 microbatch。"""++from __future__ import annotations++import argparse+import json+import shutil+import statistics+from pathlib import Path+from typing import Any++from analyze_det_cpu import collect as collect_cpu+from analyze_det_fusion import execute_run+from benchmark_det_corpus import DEFAULT_CORPUS, read_json+from benchmark_mps_det_service import write_json+from det_cpu_microbatch import CPU_MICROBATCH_STRATEGIES++NAMES = {+ "A": "原 batch",+ "M": "全部拆 N=1(上一轮实现)",+ "O": "N≥16 才拆,每批 1",+ "P": "N≥16 才拆,每批 2",+ "Q": "N≥16 才拆,每批 4",+ "R": "N≥16 才拆,每批 8",+ "S": "全局 microbatch 上限 2",+ "T": "全局 microbatch 上限 4",+ "U": "全局 microbatch 上限 8",+}+++def collect(args: argparse.Namespace) -> dict[str, Any]:+ """复用逐框独立复核,并额外保证本轮所有模型保持 36 个 BN、融合成本为零。"""+ summary = collect_cpu(args)+ for group in summary["groups"].values():+ for policy, value in group.items():+ if policy not in NAMES:+ raise ValueError(f"混入本轮范围之外的策略 {policy}")+ for load in value["environment"]["model_loads"]:+ assert load["fusion"]["before_bn"] == load["fusion"]["after_bn"] == 36+ assert not load["fusion"]["pairs"] and load["fusion"]["seconds"] == 0+ return summary+++def summarize(args: argparse.Namespace) -> None:+ """以完整正反两轮的中位数排名,必要补测单列,不混入其他策略的比较样本。"""+ summary = collect(args)+ groups = summary["groups"]+ formal = {name: groups[name] for name in ("round-1", "round-2")}+ policies = list(formal["round-1"])+ assert set(formal["round-2"]) == set(policies)+ medians = {}+ for policy in policies:+ values = [group[policy] for group in formal.values()]+ seconds = statistics.median(value["det_seconds"] for value in values)+ peak = max(value["peak_footprint"] for value in values)+ exact = all(value["exact"] for value in values)+ medians[policy] = {+ "det_seconds": seconds,+ "operational_seconds": statistics.median(value["operational_seconds"] for value in values),+ "peak_footprint": peak,+ "outputs_exact": exact,+ "eligible": exact and peak <= 8 * 1024**3,+ "per_round_reductions": [1 - group[policy]["det_seconds"] / group["A"]["det_seconds"] for group in formal.values()],+ }+ for value in medians.values():+ value["reduction_vs_a"] = 1 - value["det_seconds"] / medians["A"]["det_seconds"]+ value["reduction_vs_m"] = 1 - value["det_seconds"] / medians["M"]["det_seconds"]+ candidates = [policy for policy in policies if policy in CPU_MICROBATCH_STRATEGIES and medians[policy]["eligible"]]+ ranking = sorted(candidates, key=lambda policy: medians[policy]["det_seconds"])+ summary.update({"medians": medians, "ranking": ranking, "primary_rounds": list(formal)})+ write_json(args.output / "summary.json", summary)+ headlines = [+ f"| {policy} {NAMES[policy]} | {formal['round-1'][policy]['det_seconds']:.3f} | "+ f"{formal['round-2'][policy]['det_seconds']:.3f} | {value['det_seconds']:.3f} | "+ f"{value['reduction_vs_a']:.1%} | {value['reduction_vs_m']:.1%} | "+ f"{value['peak_footprint'] / 1024**3:.3f} | {value['outputs_exact']} |"+ for policy, value in medians.items()+ ]+ documents, details, repeats = [], [], []+ for name, group in groups.items():+ if name == "smoke":+ continue+ for policy, value in group.items():+ if name == "repeat":+ repeats.append(+ f"| {policy} | {value['det_seconds']:.3f} | {value['peak_footprint'] / 1024**3:.3f} | {value['exact']} |"+ )+ details.append(+ f"| {name} | {policy} | {value['det_seconds']:.3f} | {value['loading_seconds']:.3f} | "+ f"{value['cleanup_seconds']:.3f} | {value['operational_seconds']:.3f} | {value['forward_calls']} |"+ )+ for row in value["documents"]:+ stages = row["stages"]+ documents.append(+ f"| {name} | {policy} | {row['document']} | {row['seconds']:.3f} | "+ f"{stages['preprocess']:.3f} | {stages['forward']:.3f} | "+ f"{stages['output_transfer']:.3f} | {stages['postprocess']:.3f} |"+ )+ report = f"""# 本机 CPU det:大 batch 才拆分及 microbatch++相同三份冻结文档(95/88/114 页),原调用顺序,每遍 2280 个输入、638 次原调用。+同一 tiny 权重、FP32、生产线程 4/10、两组后处理模型复用;独立新进程串行,每本文档原清理。+本轮无融合,所有模型 BN=36;不修改 H/W,不补齐空间或尾批,不做额外前向预热。+未拆分的调用直接执行原方法,拆分调用使用连续数组视图并按原顺序恢复概率图,后处理参数不变。+O/P/Q/R 只在原 N≥16 且超出上限时拆分;S/T/U 对所有超出上限的调用拆分。+本语料最大的原 N 是 16,“≥16”组实际只有 33 次 N=16,不能泛化为其他大小的最优阈值。++| 策略 | 第一轮 det 秒 | 第二轮 det 秒 | 中位数秒 | 相对 A 耗时降低 | 相对 M 耗时降低 | 峰 footprint GiB | 框完全一致 |+| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |+{chr(10).join(headlines)}++满足严格框一致及 ≤8 GiB 的候选排序:{ranking}。+完整两轮才参与主比较;必要补测数据单列。主指标为三文档 det 合计中位数,包含前处理、张量准备、forward、回传和 DB 后处理。+PNG 读取、同步内存采样、结果保存、模型加载和清理排除在 det 之外;下表保留准备及清理成本。++| 轮次 | 策略 | det 秒 | 加载秒 | 清理秒 | 加载+det+清理秒 | 实际前向次数 |+| --- | --- | ---: | ---: | ---: | ---: | ---: |+{chr(10).join(details)}++| 轮次 | 策略 | 文档 | det 秒 | 前处理秒 | forward 秒 | 回传秒 | 后处理秒 |+| --- | --- | --- | ---: | ---: | ---: | ---: | ---: |+{chr(10).join(documents)}++必要补测:++| 策略 | det 秒 | 峰 footprint GiB | 框完全一致 |+| --- | ---: | ---: | --- |+{chr(10).join(repeats)}++保存的框独立逐项核对数量、顺序及四点坐标,实际 NCHW 与投影断言一致,差异图保留在各策略 review/。+每个模型为 CPU/FP32;权重、线程、推理源码以及拆分脚本指纹已核对;实际运行脚本另存 executed-scripts/。+内存沿原调用结束采样,采样峰不代表算子内部瞬时峰值;footprint 与 RSS/driver/compressed 不能相加,swap 为全机指标。+仅测本机 det,不推导完整 Basic/OCR、Standard/VLM、CUDA 或其他 CPU 平台的收益;本轮未修改生产默认、公开接口或权重。+未做持久服务生命周期验收。++```bash+.venv4/bin/python tools/analyze_det_microbatch.py experiment --output NEW_OUTPUT+.venv4/bin/python tools/analyze_det_microbatch.py summarize --output {args.output}+.venv4/bin/python tools/benchmark_det_corpus.py run --policies A,M,O,P,Q,R,S,T,U --cycles 1 --limit-calls 12 --output NEW_SMOKE+```+"""+ (args.output / "report.md").write_text(report, encoding="utf-8")+ print(json.dumps({"medians": medians, "ranking": ranking}, ensure_ascii=False), flush=True)+++def experiment(args: argparse.Namespace) -> None:+ """先验收烟测,再完整正反两轮;接近的优选只追加一次配对补测。"""+ args.output.mkdir(parents=True, exist_ok=False)+ archive = args.output / "executed-scripts"+ archive.mkdir()+ for name in (+ "benchmark_det_corpus.py",+ "benchmark_mps_det_service.py",+ "det_shape_buckets.py",+ "det_cpu_microbatch.py",+ "analyze_det_fusion.py",+ "analyze_det_cpu.py",+ Path(__file__).name,+ ):+ shutil.copy2(Path(__file__).parent / name, archive / name)+ execute_run(args, "smoke", ",".join(NAMES), limit_calls=12)+ smoke = collect(args)["groups"]["smoke"]+ assert smoke["A"]["exact"] and smoke["M"]["exact"], "原基线或上一轮 N=1 烟测不一致,先调查"+ eligible = [policy for policy in NAMES if smoke[policy]["exact"]]+ state = {"phase": "round-1", "policies": eligible, "excluded": [policy for policy in NAMES if policy not in eligible]}+ write_json(args.output / "experiment.json", state)+ execute_run(args, "round-1", ",".join(eligible))+ state["phase"] = "round-2"+ write_json(args.output / "experiment.json", state)+ execute_run(args, "round-2", ",".join(reversed(eligible)))+ summarize(args)+ summary = read_json(args.output / "summary.json")+ ranking, medians = summary["ranking"], summary["medians"]+ if ranking:+ best = ranking[0]+ reductions = medians[best]["per_round_reductions"]+ close = len(ranking) > 1 and 1 - medians[best]["det_seconds"] / medians[ranking[1]]["det_seconds"] < 0.05+ noisy = medians[best]["reduction_vs_a"] < 0.1 or min(reductions) <= 0 < max(reductions)+ near_gate = abs(medians[best]["reduction_vs_a"] - 0.25) < 0.05+ if close or noisy or near_gate:+ chosen = ["A", "M", *ranking[:2]]+ state.update(+ {+ "phase": "repeat",+ "repeat_policies": chosen,+ "repeat_reason": {"close": close, "noisy": noisy, "near_25_percent": near_gate},+ }+ )+ write_json(args.output / "experiment.json", state)+ execute_run(args, "repeat", ",".join(chosen))+ summarize(args)+ state["phase"] = "complete"+ write_json(args.output / "experiment.json", state)+++def main() -> None:+ """提供可复用的 CPU microbatch 实验入口,原 ABC 和融合实验入口不变。"""+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("command", choices=("experiment", "summarize"))+ parser.add_argument("--output", type=Path, required=True)+ parser.add_argument("--corpus", type=Path, default=DEFAULT_CORPUS)+ args = parser.parse_args()+ args.output, args.corpus = args.output.resolve(), args.corpus.resolve()+ args.documents = "tender,python,114"+ {"experiment": experiment, "summarize": summarize}[args.command](args)+++if __name__ == "__main__":+ main()diff --git a/tools/analyze_det_nnpack.py b/tools/analyze_det_nnpack.pynew file mode 100644index 00000000..d36bdcb7--- /dev/null+++ b/tools/analyze_det_nnpack.py@@ -0,0 +1,257 @@+"""比较原 CPU batch、仅关闭 NNPACK 和 N≥16 拆分,不修改生产默认。"""++from __future__ import annotations++import argparse+import json+import shutil+import statistics+import subprocess+import sys+from datetime import datetime+from pathlib import Path+from typing import Any++from analyze_det_cpu import collect as collect_cpu+from analyze_det_fusion import execute_run+from benchmark_det_corpus import DEFAULT_CORPUS, read_json, worker+from benchmark_mps_det_service import write_json++NAMES = {"A": "原 batch / NNPACK 开", "V": "原 batch / NNPACK 关", "R": "N≥16 拆成 N≤8 / NNPACK 开"}+ROUNDS = {"round-1": "A,V,R", "round-2": "R,A,V", "repeat": "V,R,A"}+NNPACK_DOC = "https://docs.pytorch.org/docs/2.14/backends.html#torch.backends.nnpack"+++def collect(args: argparse.Namespace) -> dict[str, Any]:+ """独立逐框复核,并断言设备、线程、融合及 NNPACK 状态符合唯一变量对照。"""+ summary = collect_cpu(args)+ for group in summary["groups"].values():+ for policy, value in group.items():+ assert policy in NAMES+ env = value["environment"]+ assert env["nnpack_enabled"] == env["nnpack_enabled_at_exit"] == (policy != "V")+ for load in env["model_loads"]:+ assert load["fusion"]["before_bn"] == load["fusion"]["after_bn"] == 36+ assert not load["fusion"]["pairs"] and load["fusion"]["seconds"] == 0+ if policy in {"A", "V"}:+ for row in value["documents"]:+ assert all(call["network_shapes"] == [call["shape"]] for call in row["call_metrics"])+ return summary+++def background_snapshot(output: Path, label: str) -> None:+ """保存轮次边界的后台进程占用快照,仅记录负载,不改变其他应用。"""+ process = subprocess.run(["ps", "-axo", "pid,pcpu,pmem,etime,comm"], capture_output=True, text=True, check=True)+ lines = process.stdout.splitlines()+ ordered = sorted(lines[1:], key=lambda line: float(line.split()[1]), reverse=True)+ record = {"time": datetime.now().astimezone().isoformat(), "label": label, "processes": ordered[:20]}+ with (output / "background-load.jsonl").open("a", encoding="utf-8") as stream:+ stream.write(json.dumps(record, ensure_ascii=False) + "\n")+++def profile_route(args: argparse.Namespace) -> None:+ """独立定点追踪真实 N=16 调用的卷积选路,诊断数据不参与正式测速。"""+ import torch++ from mineru.model.runtime.cpu_threads import initialize_torch_threads++ initialize_torch_threads()+ manifest = read_json(args.corpus / "manifest.json")+ document = next(row for row in manifest["documents"] if row["name"] == "tender")+ index = next(index for index, call in enumerate(document["calls"]) if call["shape"][0] == 16)+ measured = argparse.Namespace(+ corpus=args.corpus,+ output=args.output,+ policy=args.policy,+ documents="tender",+ cycles=1,+ start_call=0,+ limit_calls=0,+ call_indices=str(index),+ save_maps=False,+ )+ with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CPU]) as profile:+ worker(measured)+ operators = [+ {"operator": event.key, "count": event.count, "self_cpu_us": event.self_cpu_time_total}+ for event in profile.key_averages()+ if any(name in event.key.lower() for name in ("nnpack", "slow_conv", "thnn", "winograd", "mkldnn"))+ ]+ target = args.output / args.policy+ write_json(target / "operators.json", {"call_index": index, "operators": operators})+ profile.export_chrome_trace(str(target / "cpu-trace.json"))+ rows = read_json(target / "results.json")+ assert all(row["reference_exact_crops"] == row["crops"] for row in rows)+ uses_nnpack = any(row["operator"] == "aten::_nnpack_spatial_convolution" for row in operators)+ assert uses_nnpack == (args.policy == "A"), "实际 NNPACK 卷积选路与预期不同"+ print(json.dumps({"policy": args.policy, "call_index": index, "operators": operators}), flush=True)+++def summarize(args: argparse.Namespace) -> None:+ """汇总三轮平衡顺序的独立进程中位数、N 分组收益、内存及严格框一致性。"""+ summary = collect(args)+ groups = summary["groups"]+ medians: dict[str, Any] = {}+ details, documents, strata = [], [], []+ for policy in NAMES:+ values = [groups[name][policy] for name in ROUNDS]+ medians[policy] = {+ "det_seconds": statistics.median(value["det_seconds"] for value in values),+ "operational_seconds": statistics.median(value["operational_seconds"] for value in values),+ "peak_footprint": max(value["peak_footprint"] for value in values),+ "peak_rss": max(row["peak_memory"]["rss"] for value in values for row in value["documents"]),+ "outputs_exact": all(value["exact"] for value in values),+ "inputs_checked": sum(value["inputs"] for value in values),+ "per_round_reductions_vs_a": [+ 1 - groups[name][policy]["det_seconds"] / groups[name]["A"]["det_seconds"] for name in ROUNDS+ ],+ }+ for n_range in ("N<16", "N≥16"):+ totals = [+ sum(+ call["seconds"]+ for row in value["documents"]+ for call in row["call_metrics"]+ if (call["shape"][0] >= 16) == (n_range == "N≥16")+ )+ for value in values+ ]+ medians[policy][n_range] = {"round_seconds": totals, "median_seconds": statistics.median(totals)}+ strata.append(+ f"| {policy} | {n_range} | {' / '.join(f'{value:.3f}' for value in totals)} | {statistics.median(totals):.3f} |"+ )+ for value in medians.values():+ value["reduction_vs_a"] = 1 - value["det_seconds"] / medians["A"]["det_seconds"]+ value["reduction_vs_r"] = 1 - value["det_seconds"] / medians["R"]["det_seconds"]+ for name in ROUNDS:+ assert set(groups[name]) == set(NAMES)+ for policy, value in groups[name].items():+ details.append(+ f"| {name} | {policy} | {value['det_seconds']:.3f} | {value['loading_seconds']:.3f} | "+ f"{value['cleanup_seconds']:.3f} | {value['operational_seconds']:.3f} | {value['forward_calls']} |"+ )+ for row in value["documents"]:+ stages = row["stages"]+ documents.append(+ f"| {name} | {policy} | {row['document']} | {row['seconds']:.3f} | {stages['preprocess']:.3f} | "+ f"{stages['forward']:.3f} | {stages['output_transfer']:.3f} | {stages['postprocess']:.3f} |"+ )+ summary.update({"medians": medians, "primary_rounds": list(ROUNDS), "orders": ROUNDS})+ write_json(args.output / "summary.json", summary)+ per_round_display = {+ policy: " / ".join(format(groups[name][policy]["det_seconds"], ".3f") for name in ROUNDS) for policy in NAMES+ }+ headlines = [+ f"| {policy} {NAMES[policy]} | {per_round_display[policy]} | "+ f"{value['det_seconds']:.3f} | {value['reduction_vs_a']:.1%} | {value['reduction_vs_r']:.1%} | "+ f"{value['peak_footprint'] / 1024**3:.3f} | {value['peak_rss'] / 1024**3:.3f} | {value['outputs_exact']} |"+ for policy, value in medians.items()+ ]+ env = groups["round-1"]["A"]["environment"]+ report = f"""# 本机 CPU det:仅关闭 NNPACK++复用三份冻结文档(95/88/114 页),每遍 2280 个输入、638 次原调用;不重新解析 PDF。+同一 Tiny 权重、CPU FP32、生产线程 4/10、两组后处理模型复用,每本文档原清理。+环境:{env["cpu"]};Python {env["python"]};PyTorch {env["torch"]}({env["torch_commit"]})。+权重 SHA256:`{env["model_sha256"]}`;冻结 manifest SHA256:`{summary["manifest_sha256"]}`。+A/V 使用完全相同的原 batch 方法,唯一干预为 V 在实验子进程调用 `torch.backends.nnpack.set_flags(False)`。+R 为上一轮 N≥16 才拆成 N≤8 的对照;三种策略均无融合、BN=36,无 H/W 补齐或额外前向预热。+三轮顺序 A→V→R、R→A→V、V→R→A,各策略在每个运行位置出现一次,均为独立新进程串行。+repeat/ 是第三轮完整数据,三轮均纳入中位数。后台 CPU 有占用,边界快照见 background-load.jsonl;并非空闲机器校准。++| 策略 | 三轮 det 秒 | 中位数秒 | 相对 A 耗时降低 | 相对 R 耗时降低 | 峰 footprint GiB | 峰 RSS GiB | 框完全一致 |+| --- | --- | ---: | ---: | ---: | ---: | ---: | --- |+{chr(10).join(headlines)}++| 轮次 | 策略 | det 秒 | 加载秒 | 清理秒 | 加载+det+清理秒 | 前向次数 |+| --- | --- | ---: | ---: | ---: | ---: | ---: |+{chr(10).join(details)}++| 轮次 | 策略 | 文档 | det 秒 | 前处理秒 | 同步 forward 秒 | 回传秒 | 后处理秒 |+| --- | --- | --- | ---: | ---: | ---: | ---: | ---: |+{chr(10).join(documents)}++| 策略 | 原 N 分组 | 三轮 det 秒 | 中位数秒 |+| --- | --- | --- | ---: |+{chr(10).join(strata)}++全量逐项复核检测框数量、顺序、四点坐标,模型实例复用、实际 NCHW、FP32、线程和源码/权重指纹。+每策略三轮共 6840 个输入;差异输入、参数、原始/候选框及叠框由原重放器保存在 review/。+定点 profiler 对 tender 首个 N=16 调用另存 diagnostics/,确认 A 使用 NNPACK,V/R 不使用;诊断开销不混入正式测速。+PNG 读取、模型加载、清理、同步内存采样和结果保存排除在 det 外;det 包括前处理、张量准备、网络执行和 DB 后处理。+内存为调用结束及清理边界采样;采样峰不是算子内部瞬时峰值。footprint/RSS/compressed 不相加,swap 是全机值。+NNPACK 开关是进程全局设置,其他 CPU 模型会共享该状态:[PyTorch 文档]({NNPACK_DOC})。+本轮只验证本机 det;未修改生产默认,不推导其他模型、CPU 平台、MPS/CUDA 或完整解析收益。++```bash+.venv4/bin/python tools/analyze_det_nnpack.py experiment --output NEW_OUTPUT+.venv4/bin/python tools/analyze_det_nnpack.py summarize --output {args.output}+.venv4/bin/python tools/benchmark_det_corpus.py run --policies A,V --cycles 1 --output NEW_OUTPUT+```+"""+ (args.output / "report.md").write_text(report, encoding="utf-8")+ print(json.dumps(medians, ensure_ascii=False), flush=True)+++def experiment(args: argparse.Namespace) -> None:+ """先烟测和独立选路诊断,再运行三轮平衡顺序的全量对照,全部证据另存新目录。"""+ args.output.mkdir(parents=True, exist_ok=False)+ archive = args.output / "executed-scripts"+ archive.mkdir()+ for name in (+ "benchmark_det_corpus.py",+ "benchmark_mps_det_service.py",+ "det_shape_buckets.py",+ "det_cpu_microbatch.py",+ "analyze_det_fusion.py",+ "analyze_det_cpu.py",+ Path(__file__).name,+ ):+ shutil.copy2(Path(__file__).parent / name, archive / name)+ background_snapshot(args.output, "before-smoke")+ execute_run(args, "smoke", ",".join(NAMES), limit_calls=12)+ smoke = collect(args)["groups"]["smoke"]+ assert all(value["exact"] for value in smoke.values()), "烟测检测框不一致,暂停正式测速"+ for policy in NAMES:+ with (args.output / f"profile-{policy}.log").open("w", encoding="utf-8") as stream:+ subprocess.run(+ [+ sys.executable,+ str(Path(__file__).resolve()),+ "profile",+ "--policy",+ policy,+ "--corpus",+ str(args.corpus),+ "--output",+ str(args.output / "diagnostics"),+ ],+ stdout=stream,+ stderr=subprocess.STDOUT,+ check=True,+ )+ for name, policies in ROUNDS.items():+ write_json(args.output / "experiment.json", {"phase": name, "policies": policies})+ background_snapshot(args.output, f"before-{name}")+ execute_run(args, name, policies)+ background_snapshot(args.output, f"after-{name}")+ collect(args)+ summarize(args)+ write_json(args.output / "experiment.json", {"phase": "complete", "orders": ROUNDS})+++def main() -> None:+ """提供仅关闭 NNPACK 的实验、汇总及独立 profiler 入口。"""+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("command", choices=("experiment", "summarize", "profile"))+ parser.add_argument("--output", type=Path, required=True)+ parser.add_argument("--corpus", type=Path, default=DEFAULT_CORPUS)+ parser.add_argument("--policy", choices=tuple(NAMES), default="V")+ args = parser.parse_args()+ args.output, args.corpus = args.output.resolve(), args.corpus.resolve()+ args.documents = "tender,python,114"+ {"experiment": experiment, "summarize": summarize, "profile": profile_route}[args.command](args)+++if __name__ == "__main__":+ main()diff --git a/tools/analyze_det_shapes.py b/tools/analyze_det_shapes.pynew file mode 100644index 00000000..f54e01d2--- /dev/null+++ b/tools/analyze_det_shapes.py@@ -0,0 +1,482 @@+"""在融合 E 基线上调度 N/H/W 归并实验,保留严格输出与 8 GiB 内存门槛。"""++from __future__ import annotations++import argparse+import json+import shutil+import statistics+from pathlib import Path+from typing import Any++from analyze_det_fusion import diagnose_differences, execute_run, load_runs+from benchmark_det_corpus import read_json+from benchmark_mps_det_service import write_json+from det_shape_buckets import SHAPE_STRATEGIES, project_shape++NAMES = {+ "A": "CPU 原模型",+ "E": "MPS 全融合,原 N/H/W",+ "F": "MPS 全融合,拆为 N=1",+ "G": "MPS 全融合,拆分并补齐 N=4",+ "H": "MPS 全融合,H/W 补齐到 64 倍数",+ "I": "MPS 全融合,H/W 补齐到 128 倍数",+}+++def shape_distribution(args: argparse.Namespace) -> dict[str, Any]:+ """在执行前统计准确网络形状和计算量,避免只凭桶数量估计速度。"""+ documents = read_json(args.corpus / "manifest.json")["documents"]+ result = {}+ for policy in ("E", *SHAPE_STRATEGIES):+ rows = []+ for document in documents:+ projected = [project_shape(call["shape"], policy) for call in document["calls"]]+ shapes = {tuple(shape) for item in projected for shape in item["network_shapes"]}+ rows.append(+ {+ "document": document["name"],+ "unique_shapes": len(shapes),+ "forward_calls": sum(len(item["network_shapes"]) for item in projected),+ "processed_pixels": sum(item["processed_pixels"] for item in projected),+ "original_pixels": sum(item["original_pixels"] for item in projected),+ }+ )+ result[policy] = rows+ return result+++def collect_shape_summary(args: argparse.Namespace) -> dict[str, Any]:+ """使用同轮 A/E 配对验收新策略,烟测失败或内存超预算都不算有效收益。"""+ runs = load_runs(args.output)+ smoke = [entry for entry in runs if entry["directory"].startswith("smoke")]+ formal = [entry for entry in runs if entry["directory"].startswith("round-")]+ checks = {}+ required = {+ (call["box_thresh"], call["unclip_ratio"])+ for document in read_json(args.corpus / "manifest.json")["documents"]+ for call in document["calls"]+ }+ for policy in NAMES:+ rows = [row for entry in smoke if entry["policy"] == policy for row in entry["records"]]+ profiles = {tuple(model["profile"]) for row in rows for model in row["models"]}+ checks[policy] = {+ "inputs": sum(row["crops"] for row in rows),+ "differences": sum(len(row["differences"]) for row in rows),+ "exact": bool(rows) and all(row["reference_exact_crops"] == row["crops"] for row in rows),+ "profiles_complete": profiles == required,+ "det_seconds": sum(row["seconds"] for row in rows),+ }+ fingerprints = {+ (+ entry["environment"]["model_sha256"],+ entry["environment"]["torch_commit"],+ entry["environment"]["python"],+ entry["environment"]["threads"],+ entry["environment"]["interop_threads"],+ entry["environment"]["git_head"],+ entry["environment"]["script_sha256"],+ entry["environment"]["shape_adapter_sha256"],+ )+ for entry in runs+ }+ matched = len(fingerprints) == 1+ fp32 = all(model["dtype"] == "torch.float32" for entry in runs for row in entry["records"] for model in row["models"])+ reuse = all(+ len({model["net_id"] for row in entry["records"] for model in row["models"] if tuple(model["profile"]) == profile}) == 1+ for entry in runs+ for profile in {tuple(model["profile"]) for row in entry["records"] for model in row["models"]}+ )+ rounds: dict[str, dict[str, Any]] = {}+ for entry in formal:+ protocol = entry["protocol"]+ if (+ protocol["documents"] != "tender,python,114"+ or protocol["cycles"] != 1+ or protocol["limit_calls"]+ or protocol["start_call"]+ or protocol["call_indices"]+ or protocol["save_maps"]+ ):+ raise ValueError("正式形状对照必须完整单遍重放,不能混入诊断或生命周期数据")+ env = entry["environment"]+ rows = entry["records"]+ loading = sum(item["loading_seconds"] for item in env["model_loads"])+ fusion = sum(item["fusion"]["seconds"] for item in env["model_loads"])+ cleanup = sum(row["cleanup_seconds"] for row in rows) + env["shutdown_seconds"]+ det = sum(row["seconds"] for row in rows)+ metrics = [metric for row in rows for metric in row["call_metrics"]]+ rounds.setdefault(entry["directory"], {})[entry["policy"]] = {+ "det_seconds": det,+ "loading_seconds": loading,+ "fusion_seconds": fusion,+ "cleanup_seconds": cleanup,+ "operational_seconds": det + loading + fusion + cleanup,+ "peak_footprint": max(+ *(row["peak_memory_diagnostics"]["phys_footprint"] for row in rows),+ env["shutdown_memory_diagnostics_before"]["phys_footprint"],+ env["shutdown_memory_diagnostics_after"]["phys_footprint"],+ ),+ "exact": all(row["reference_exact_crops"] == row["crops"] for row in rows),+ "forward_calls": sum(len(metric["network_shapes"]) for metric in metrics),+ "pixel_ratio": sum(metric["shape_projection"]["processed_pixels"] for metric in metrics)+ / sum(metric["shape_projection"]["original_pixels"] for metric in metrics),+ "bucket_padding_seconds": sum(metric["bucket_padding_seconds"] for metric in metrics),+ }+ baseline = all(checks[policy]["exact"] and checks[policy]["profiles_complete"] for policy in ("A", "E"))+ baseline &= all(value["exact"] for group in rounds.values() for policy, value in group.items() if policy in ("A", "E"))+ candidates = {}+ for policy in SHAPE_STRATEGIES:+ paired = [group for group in rounds.values() if {"A", "E", policy}.issubset(group)]+ if not paired:+ continue+ seconds = statistics.median(group[policy]["det_seconds"] for group in paired)+ cpu = statistics.median(group["A"]["det_seconds"] for group in paired)+ original = statistics.median(group["E"]["det_seconds"] for group in paired)+ peak = max(group[policy]["peak_footprint"] for group in paired)+ exact = checks[policy]["exact"] and all(group[policy]["exact"] for group in paired)+ gains = [1 - group[policy]["det_seconds"] / group["E"]["det_seconds"] for group in paired]+ reduction = 1 - seconds / original+ cpu_reduction = 1 - seconds / cpu+ eligible = matched and fp32 and reuse and baseline and exact and peak <= 8 * 1024**3+ candidates[policy] = {+ "rounds": len(paired),+ "median_det_seconds": seconds,+ "matched_e_seconds": original,+ "matched_cpu_seconds": cpu,+ "reduction_vs_e": reduction,+ "reduction_vs_a": cpu_reduction,+ "round_gains": gains,+ "peak_footprint": peak,+ "outputs_exact": exact,+ "eligible": eligible,+ "research_pass": eligible+ and len(paired) >= 2+ and reduction >= 0.25+ and sum(gain > 0 for gain in gains) > len(gains) / 2,+ "repeat_needed": eligible+ and (+ reduction < 0.1+ or (any(gain <= 0 for gain in gains) and any(gain > 0 for gain in gains))+ or abs(reduction - 0.25) < 0.05+ or abs(cpu_reduction - 0.25) < 0.05+ ),+ "lifecycle_pass": None,+ "default_candidate": False,+ }+ for entry in runs:+ if entry["directory"] != "lifecycle":+ continue+ policy = entry["policy"]+ rows = entry["records"]+ if len(rows) != 6 or policy not in candidates:+ raise ValueError("生命周期要求候选连续两遍三文档")+ before = rows[2]["memory_after"] | {"footprint": rows[2]["memory_diagnostics_after"]["phys_footprint"]}+ after = rows[5]["memory_after"] | {"footprint": rows[5]["memory_diagnostics_after"]["phys_footprint"]}+ growth = {+ key: {+ "delta": after[key] - before[key],+ "limit": max(before[key] * 0.1, 256 * 1024**2),+ "first": before[key],+ "second": after[key],+ }+ for key in before+ }+ peak = max(row["peak_memory_diagnostics"]["phys_footprint"] for row in rows)+ passed = (+ all(value["delta"] <= value["limit"] for value in growth.values())+ and all(row["crops"] == row["reference_exact_crops"] for row in rows)+ and peak <= 8 * 1024**3+ )+ candidates[policy].update(+ {+ "lifecycle_pass": passed,+ "lifecycle_peak_footprint": peak,+ "lifecycle_growth": growth,+ "default_candidate": passed+ and candidates[policy]["research_pass"]+ and candidates[policy]["reduction_vs_a"] >= 0.25,+ }+ )+ return {+ "smoke": checks,+ "rounds": rounds,+ "candidates": candidates,+ "baseline_exact": baseline,+ "matched_environment": matched,+ "fp32": fp32,+ "models_reused": reuse,+ "runs": runs,+ }+++def shape_experiment(args: argparse.Namespace) -> None:+ """按烟测、正反两轮、必要复测和生命周期顺序验收形状归并,输出失败者仅保留诊断证据。"""+ if args.documents != "tender,python,114" or args.start_call or args.limit_calls or args.call_indices or args.save_maps:+ raise ValueError("自动形状实验使用固定完整语料,定点调用请使用 run")+ if args.output.exists() and any(args.output.iterdir()):+ raise FileExistsError("请用全新输出目录保留上一轮证据")+ args.output.mkdir(parents=True, exist_ok=True)+ source = args.output / "executed-scripts"+ source.mkdir()+ for name in (+ "benchmark_det_corpus.py",+ "benchmark_mps_det_service.py",+ "analyze_det_fusion.py",+ "analyze_det_shapes.py",+ "det_shape_buckets.py",+ ):+ shutil.copy2(Path(__file__).parent / name, source / name)+ write_json(args.output / "shape-distribution.json", shape_distribution(args))+ state: dict[str, Any] = {"phase": "smoke", "footprint_budget": 8 * 1024**3, "baseline": "E", "corpus": str(args.corpus)}+ write_json(args.output / "experiment.json", state)+ execute_run(args, "smoke", "A,E,F,G,H,I", limit_calls=12)+ summary = collect_shape_summary(args)+ if not all(value["profiles_complete"] for value in summary["smoke"].values()):+ manifest = read_json(args.corpus / "manifest.json")+ seen = {tuple(model["profile"]) for entry in summary["runs"] for row in entry["records"] for model in row["models"]}+ missing = {(call["box_thresh"], call["unclip_ratio"]) for doc in manifest["documents"] for call in doc["calls"]} - seen+ for number, profile in enumerate(sorted(missing)):+ doc, index = next(+ (doc["name"], index)+ for doc in manifest["documents"]+ for index, call in enumerate(doc["calls"])+ if (call["box_thresh"], call["unclip_ratio"]) == profile+ )+ execute_run(args, f"smoke-profile-{number + 1}", "A,E,F,G,H,I", documents=doc, call_indices=str(index))+ summary = collect_shape_summary(args)+ candidates = [+ policy+ for policy in SHAPE_STRATEGIES+ if summary["smoke"][policy]["exact"] and summary["smoke"][policy]["profiles_complete"]+ ]+ if not summary["baseline_exact"]:+ state["phase"] = "baseline_rejected"+ elif not candidates:+ state["phase"] = "candidates_rejected_at_smoke"+ else:+ state.update({"phase": "formal", "formal_candidates": candidates})+ write_json(args.output / "experiment.json", state)+ policies = ["A", "E", *candidates]+ execute_run(args, "round-1", ",".join(policies))+ execute_run(args, "round-2", ",".join(reversed(policies)))+ summary = collect_shape_summary(args)+ valid = [policy for policy, value in summary["candidates"].items() if value["eligible"]]+ best = min(valid, key=lambda policy: summary["candidates"][policy]["median_det_seconds"]) if valid else None+ if best and summary["candidates"][best]["repeat_needed"]:+ execute_run(args, "round-3", f"A,E,{best}")+ summary = collect_shape_summary(args)+ passed = [policy for policy, value in summary["candidates"].items() if value["research_pass"]]+ if passed:+ best = min(passed, key=lambda policy: summary["candidates"][policy]["median_det_seconds"])+ state["lifecycle_policy"] = best+ execute_run(args, "lifecycle", best, cycles=2)+ state["phase"] = "complete"+ write_json(args.output / "experiment.json", state)+ diagnose_differences(args, baseline_policies=("A", "E"))+ shape_summarize(args)+++def shape_summarize(args: argparse.Namespace) -> None:+ """保存形状收益、真实算量、框差异和内存门槛,区分烟测淘汰与正式性能结论。"""+ summary = collect_shape_summary(args)+ summary["experiment"] = read_json(args.output / "experiment.json")+ summary["distribution"] = read_json(args.output / "shape-distribution.json")+ summary["probability_diagnostics"] = (+ read_json(args.output / "probability-diagnostics.json")+ if (args.output / "probability-diagnostics.json").exists()+ else []+ )+ write_json(args.output / "summary.json", summary)+ smoke_rows = []+ for policy, value in summary["smoke"].items():+ smoke_rows.append(+ f"| {policy} | {NAMES[policy]} | {value['inputs']} | {value['differences']} | "+ f"{value['exact']} | {value['det_seconds']:.3f} |"+ )+ distribution_rows = []+ for policy, rows in summary["distribution"].items():+ for row in rows:+ distribution_rows.append(+ f"| {policy} | {row['document']} | {row['unique_shapes']} | {row['forward_calls']} | "+ f"{row['processed_pixels'] / row['original_pixels']:.3f} |"+ )+ performance = []+ for round_name, group in summary["rounds"].items():+ for policy, value in group.items():+ performance.append(+ f"| {round_name} | {policy} | {value['det_seconds']:.3f} | {value['operational_seconds']:.3f} | "+ f"{value['peak_footprint'] / 1024**3:.2f} | {value['forward_calls']} | "+ f"{value['pixel_ratio']:.3f} | {value['exact']} |"+ )+ gates = []+ for policy, value in summary["candidates"].items():+ gates.append(+ f"| {policy} | {value['median_det_seconds']:.3f} | {value['reduction_vs_e']:.1%} | {value['reduction_vs_a']:.1%} | "+ f"{value['peak_footprint'] / 1024**3:.2f} | {value['outputs_exact']} | {value['research_pass']} | "+ f"{value['lifecycle_pass']} | {value['default_candidate']} |"+ )+ document_rows = []+ for entry in summary["runs"]:+ for row in entry["records"]:+ document_rows.append(+ f"| {entry['directory']} | {entry['policy']} | {row['label']} | {row['seconds']:.3f} | "+ f"{len(row['shape_counts'])} | {row['peak_memory_diagnostics']['phys_footprint'] / 1024**3:.2f} | "+ f"{row['reference_exact_crops']}/{row['crops']} |"+ )+ env = summary["runs"][0]["environment"]+ failed = [policy for policy in SHAPE_STRATEGIES if not summary["smoke"][policy]["exact"]]+ conclusions = []+ for policy, value in summary["candidates"].items():+ conclusions.append(+ f"{policy}:det 中位数 {value['median_det_seconds']:.2f} 秒,相对 E 降低 {value['reduction_vs_e']:.1%},"+ f"采样峰 footprint {value['peak_footprint'] / 1024**3:.2f} GiB,框一致 {value['outputs_exact']}。"+ )+ if value["lifecycle_pass"] is False:+ growth = value["lifecycle_growth"]+ conclusions.append(+ f"{policy} 生命周期未通过:结束 footprint 从 {growth['footprint']['first'] / 1024**3:.2f} "+ f"增至 {growth['footprint']['second'] / 1024**3:.2f} GiB,"+ f"RSS 增长 {growth['rss']['delta'] / 1024**3:.2f} GiB;allocated/driver 的增长见 summary.json。"+ )+ lifetime_rows = []+ for entry in summary["runs"]:+ if entry["directory"] == "lifecycle":+ for row in entry["records"]:+ diagnostic = row["memory_diagnostics_after"]+ lifetime_rows.append(+ f"| {entry['policy']} | {row['label']} | {row['seconds']:.3f} | "+ f"{row['peak_memory_diagnostics']['phys_footprint'] / 1024**3:.2f} | "+ f"{diagnostic['phys_footprint'] / 1024**3:.2f} | {row['memory_after']['rss'] / 1024**3:.2f} | "+ f"{row['memory_after']['mps_driver'] / 1024**3:.3f} |"+ )+ difference_counts = {}+ unchanged_spatial_differences = 0+ for entry in summary["runs"]:+ for row in entry["records"]:+ by_call = {metric["call_index"]: metric for metric in row["call_metrics"]}+ for difference in row["differences"]:+ counter = difference_counts.setdefault(entry["policy"], {"inputs": 0, "box_count_changes": 0})+ counter["inputs"] += 1+ counter["box_count_changes"] += len(difference["reference"] or []) != len(difference["actual"] or [])+ if entry["policy"] in ("H", "I"):+ metric = by_call[difference["call_index"]]+ unchanged_spatial_differences += metric["shape"][2:] == metric["network_shapes"][0][2:]+ write_json(args.output / "difference-counts.json", difference_counts)+ count_description = (+ ";".join(+ f"{policy} 有 {value['inputs']} 个差异输入,其中 {value['box_count_changes']} 个改变框数量"+ for policy, value in difference_counts.items()+ )+ or "没有检测框差异"+ )+ defaults = [policy for policy, value in summary["candidates"].items() if value["default_candidate"]]+ default_description = (+ f"下一轮默认策略验证候选:{defaults}。" if defaults else "本轮没有满足默认策略要求的候选,保持 CPU 默认。"+ )+ report = f"""# 融合 E 基线上的 det 形状归并++{chr(10).join(conclusions)}++状态:{summary["experiment"]["phase"]}。烟测框一致性失败的候选:{failed},这些策略不进入正式性能验收。+仅改实验脚本;使用冻结的 2280 个普通文字 det 输入,不再解析 PDF。生产默认和原权重不变。+沿用完全一致的检测框门槛与 8 GiB 采样峰 footprint 预算;研究收益要求相对 E 至少降低 25%。+全部策略独立进程串行,正式两轮顺序互逆,每本文档执行原 MPS 清理;不保留跨文档图缓存、不预热。+环境一致:{summary["matched_environment"]},FP32:{summary["fp32"]},模型复用:{summary["models_reused"]}。+{env["cpu"]} / {env["platform"]} / Python {env["python"]} / Torch {env["torch"]}。+intra/inter-op {env["threads"]}/{env["interop_threads"]}。+原权重 SHA256:`{env["model_sha256"]}`。实际执行源码保存在 executed-scripts/。++## 实现和烟测++E/F/G/H/I 都融合同样的 36 组 Conv/BN,A 为 CPU 原模型。形状阶段的对照是 E,不将上一轮融合收益计为归并收益。+保留原 resize、归一化与原始坐标信息;F/G 只改变 N,G 用最后一个真实样本补齐并丢弃额外输出。+H/I 在归一化后的 CPU 输入右侧/底部补 0,不改变原图像素;先将输出回传 CPU,再裁切到原 H/W,最后执行原 DB 后处理。+Tiny 模型包含全局池化和 SE,裁切输出不能保证空间补齐等价;通过逐项检测框比较裁决。+记录原调用与实际网络形状、拆批次数、实际像素算量和补齐耗时(已计入 det)。原调用输出顺序不变。++| 策略 | 方案 | 烟测输入 | 差异输入 | 框一致 | 烟测 det 秒 |+| --- | --- | ---: | ---: | --- | ---: |+{chr(10).join(smoke_rows)}++## 全量形状预估++| 策略 | 文档 | 唯一 NCHW | forward 次数 | 像素算量相对 E |+| --- | --- | ---: | ---: | ---: |+{chr(10).join(distribution_rows)}++## 正式性能与验收++| 轮次 | 策略 | det 秒 | 加载+融合+det+清理秒 | 峰 footprint GiB | forward 次数 | 像素算量比 | 框一致 |+| --- | --- | ---: | ---: | ---: | ---: | ---: | --- |+{chr(10).join(performance) if performance else "| 未执行 | — | — | — | — | — | — | — |"}++| 候选 | det 中位数秒 | 相对 E 降低 | 相对 A 降低 | 峰 footprint GiB | 框一致 | 研究门槛 | 生命周期 | 默认策略候选 |+| --- | ---: | ---: | ---: | ---: | --- | --- | --- | --- |+{chr(10).join(gates) if gates else "| 无合格候选 | — | — | — | — | False | False | 未执行 | False |"}++速度取独立轮次三文档合计中位数;研究门槛为输出严格一致、≤8 GiB、相对 E 降低 ≥25% 且多数轮次同向。+通过者另作同进程两遍三文档生命周期验证;清理后 RSS/footprint/allocated/driver 增长均须 ≤max(10%,256 MiB)。+相对 CPU A 降低 ≥25% 且通过生命周期才可成为下一轮默认策略候选。+{default_description} 生命周期的内存增长不能直接等同于已确认泄漏。++## 生命周期++| 策略 | 文档 | det 秒 | 峰 footprint GiB | 清理后 footprint GiB | 清理后 RSS GiB | 清理后 driver GiB |+| --- | --- | ---: | ---: | ---: | ---: | ---: |+{chr(10).join(lifetime_rows) if lifetime_rows else "| 未执行 | — | — | — | — | — | — |"}++## 逐文档记录和差异证据++| 运行 | 策略 | 文档 | det 秒 | 实际唯一 NCHW | 峰 footprint GiB | 框一致输入 |+| --- | --- | --- | ---: | ---: | ---: | --- |+{chr(10).join(document_rows)}++所有差异的原 PNG、坐标和叠框位于各策略 review/ 与 results.json;CPU、E 及涉及候选的差异调用概率图保存在 diagnostics/。+probability-diagnostics.json 给出概率图最大/平均误差和跨 0.3 阈值像素数,仅用于诊断,不能放宽框一致性门槛。+difference-counts.json 另区分坐标变化与框数量变化:{count_description}。+H/I 未改变 H/W 的输入发生框差异 {unchanged_spatial_differences} 次;裁切最终概率图不能保证消除 padding 的影响。+det 包含真实前处理、补齐/拆批、张量传输、同步网络执行、输出恢复及后处理。读 PNG、写结果、采样与清理在外。+采样峰值不是内部瞬时峰值;footprint 包含压缩页记账,与 RSS/driver 重叠。全机 swap 不能全部归属 det。+仅代表 det 阶段,不推导完整 Basic/OCR 或 Standard/VLM。++```bash+.venv4/bin/python tools/benchmark_det_corpus.py shape-experiment --output NEW_OUTPUT+.venv4/bin/python tools/benchmark_det_corpus.py shape-summarize --output {args.output}+```+++"""+ (args.output / "report.md").write_text(report, encoding="utf-8")+ import matplotlib++ matplotlib.use("Agg")+ import matplotlib.pyplot as plt++ fig, axes = plt.subplots(1, 2, figsize=(13, 4), constrained_layout=True)+ plotted_phase = "round-1" if summary["rounds"] else "smoke"+ for policy in NAMES:+ entries = [entry for entry in summary["runs"] if entry["policy"] == policy and entry["directory"] == plotted_phase]+ if not entries:+ continue+ chosen = entries[0]+ rows = chosen["records"]+ axes[0].plot(range(1, len(rows) + 1), [row["seconds"] for row in rows], "o-", label=f"{policy} ({chosen['directory']})")+ samples = [metric["memory_diagnostics"]["phys_footprint"] / 1024**3 for row in rows for metric in row["call_metrics"]]+ axes[1].plot(range(1, len(samples) + 1), samples, label=policy)+ axes[0].set(xlabel="Document replay index", ylabel="det seconds", title=f"det performance: {plotted_phase}")+ axes[1].set(xlabel="Original call index", ylabel="Sampled footprint GiB", title="Memory accounting")+ axes[1].axhline(8, color="red", linestyle="--", label="8 GiB budget")+ for axis in axes:+ axis.legend(fontsize=8)+ axis.grid(alpha=0.25)+ fig.savefig(args.output / "performance-memory.png", dpi=160)+ plt.close(fig)+ print(+ json.dumps(+ {"phase": summary["experiment"]["phase"], "smoke": summary["smoke"], "candidates": summary["candidates"]},+ ensure_ascii=False,+ indent=2,+ ),+ flush=True,+ )diff --git a/tools/analyze_det_single.py b/tools/analyze_det_single.pynew file mode 100644index 00000000..5d1f9fcb--- /dev/null+++ b/tools/analyze_det_single.py@@ -0,0 +1,305 @@+"""对照 3.4 单图入口、当前 batch 和 N=1 拆分,仅重放冻结 det 输入。"""++from __future__ import annotations++import argparse+import ast+import hashlib+import json+import shutil+import statistics+import subprocess+from pathlib import Path+from typing import Any++from analyze_det_fusion import execute_run, load_runs+from benchmark_det_corpus import DEFAULT_CORPUS, ROOT, read_json+from benchmark_mps_det_service import write_json++NAMES = {+ "A": "CPU 原 batch,无融合",+ "E": "MPS 原 batch,融合 36 组",+ "F": "MPS batch 内拆 N=1,融合 36 组",+ "J": "MPS 逐图 3.4 __call__,无融合",+ "K": "MPS 逐图 3.4 __call__,融合 36 组",+}+++def method_body(source: str, method: str) -> str:+ """抽取 TextDetector 方法的 AST 主体,忽略中文注释和文档字符串比较真实执行逻辑。"""+ tree = ast.parse(source)+ detector = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "TextDetector")+ function = next(node for node in detector.body if isinstance(node, ast.FunctionDef) and node.name == method)+ body = function.body+ if (+ body+ and isinstance(body[0], ast.Expr)+ and isinstance(body[0].value, ast.Constant)+ and isinstance(body[0].value.value, str)+ ):+ body = body[1:]+ return ast.dump(ast.Module(body=body, type_ignores=[]), include_attributes=False)+++def inspect_history(output: Path) -> dict[str, Any]:+ """归档 3.4 发布源码并核实单图及共享方法等价,避免将不同模型版本混为入口收益。"""+ target = output / "history"+ target.mkdir(exist_ok=True)+ current = (ROOT / "mineru/model/_internal/pytorchocr/infer/predict_det.py").read_text()+ methods = ("__call__", "_preprocess_det_image", "_build_det_preds", "_postprocess_det_batch", "_batch_process_preprocessed")+ records = []+ for tag in ("mineru-3.4.0-released", "mineru-3.4.5-released"):+ path = "mineru/model/utils/tools/infer/predict_det.py"+ source = subprocess.check_output(["git", "show", f"{tag}:{path}"], cwd=ROOT, text=True)+ (target / f"{tag}-predict_det.py").write_text(source)+ config = subprocess.check_output(+ ["git", "show", f"{tag}:mineru/model/utils/pytorchocr/utils/resources/models_config.yml"], cwd=ROOT, text=True+ )+ (target / f"{tag}-models_config.yml").write_text(config)+ records.append(+ {+ "tag": tag,+ "commit": subprocess.check_output(["git", "rev-parse", tag], cwd=ROOT, text=True).strip(),+ "source_sha256": hashlib.sha256(source.encode()).hexdigest(),+ "equal_method_bodies": {+ method: method_body(current, method) == method_body(source, method) for method in methods+ },+ "default_ch_model": "ch_PP-OCRv6_small_det_infer.safetensors",+ "experiment_model": "ch_PP-OCRv6_tiny_det_infer.safetensors",+ }+ )+ if not all(all(record["equal_method_bodies"].values()) for record in records):+ raise ValueError("当前调用链与 3.4 单图方法不等价,需先调查差异,不能直接称为 3.4 入口")+ write_json(output / "history-proof.json", records)+ return {"tags": records, "single_n": 1, "shared_batch_helper": True, "weights_and_fp32_controlled": True}+++def collect(args: argparse.Namespace) -> dict[str, Any]:+ """配对比较单图融合、batch 融合与 N=1 拆分,验证实际形状、参考框和推理源码指纹。"""+ runs = load_runs(args.output)+ fingerprints = set()+ smoke = {}+ rounds = {}+ fp32, reused, source_stable, shapes_valid = True, True, True, True+ for entry in runs:+ env, rows = entry["environment"], entry["records"]+ fingerprints.add(+ tuple(+ env[key]+ for key in (+ "python",+ "torch_commit",+ "threads",+ "interop_threads",+ "model_sha256",+ "script_sha256",+ "shape_adapter_sha256",+ "det_source_sha256_before",+ "det_source_sha256_after",+ )+ )+ )+ source_stable &= env["det_source_sha256_before"] == env["det_source_sha256_after"]+ fp32 &= all(model["dtype"] == "torch.float32" for row in rows for model in row["models"])+ profiles = {tuple(model["profile"]) for row in rows for model in row["models"]}+ reused &= all(+ len({model["net_id"] for row in rows for model in row["models"] if tuple(model["profile"]) == profile}) == 1+ for profile in profiles+ )+ for row in rows:+ for metric in row["call_metrics"]:+ if entry["policy"] in {"F", "J", "K"}:+ shapes_valid &= len(metric["network_shapes"]) == metric["shape"][0] and all(+ shape[0] == 1 and shape[1:] == metric["shape"][1:] for shape in metric["network_shapes"]+ )+ required = {+ (call["box_thresh"], call["unclip_ratio"])+ for doc in read_json(args.corpus / "manifest.json")["documents"]+ for call in doc["calls"]+ }+ value = {+ "det_seconds": sum(row["seconds"] for row in rows),+ "inputs": sum(row["crops"] for row in rows),+ "exact": all(row["reference_exact_crops"] == row["crops"] for row in rows),+ "differences": sum(len(row["differences"]) for row in rows),+ "profiles_complete": profiles == required,+ "peak_footprint": max(+ *(row["peak_memory_diagnostics"]["phys_footprint"] for row in rows),+ env["shutdown_memory_diagnostics_before"]["phys_footprint"],+ env["shutdown_memory_diagnostics_after"]["phys_footprint"],+ ),+ "forward_calls": sum(len(metric["network_shapes"]) for row in rows for metric in row["call_metrics"]),+ "documents": rows,+ "environment": env,+ }+ loading = sum(model["loading_seconds"] for model in env["model_loads"])+ fusion = sum(model["fusion"]["seconds"] for model in env["model_loads"])+ cleanup = sum(row["cleanup_seconds"] for row in rows) + env["shutdown_seconds"]+ value.update({"loading_seconds": loading, "fusion_seconds": fusion, "cleanup_seconds": cleanup})+ value["operational_seconds"] = value["det_seconds"] + loading + fusion + cleanup+ if entry["directory"] == "smoke":+ smoke[entry["policy"]] = value+ elif entry["directory"].startswith("round-"):+ protocol = entry["protocol"]+ if (+ protocol["cycles"] != 1+ or protocol["limit_calls"]+ or protocol["start_call"]+ or protocol["call_indices"]+ or protocol["save_maps"]+ ):+ raise ValueError("正式对照必须三份文档全量单遍,不能混入诊断")+ if value["inputs"] != 2280:+ raise ValueError("正式对照输入数量不完整")+ rounds.setdefault(entry["directory"], {})[entry["policy"]] = value+ medians = {}+ for policy in NAMES:+ values = [group[policy] for group in rounds.values() if policy in group]+ if values:+ medians[policy] = {+ "det_seconds": statistics.median(value["det_seconds"] for value in values),+ "operational_seconds": statistics.median(value["operational_seconds"] for value in values),+ "peak_footprint": max(value["peak_footprint"] for value in values),+ "outputs_exact": all(value["exact"] for value in values),+ }+ return {+ "smoke": smoke,+ "rounds": rounds,+ "medians": medians,+ "fp32": fp32,+ "models_reused": reused,+ "source_stable": source_stable,+ "matched_execution_environment": len(fingerprints) == 1,+ "n1_shapes_verified": shapes_valid,+ }+++def summarize(args: argparse.Namespace) -> None:+ """保存单图入口收益、融合收益和 N 拆分重叠关系,结论只针对当前 tiny/FP32 det。"""+ summary = collect(args)+ medians = summary["medians"]+ rows, docs = [], []+ for name, group in summary["rounds"].items():+ for policy, value in group.items():+ rows.append(+ f"| {name} | {policy} | {value['det_seconds']:.3f} | {value['operational_seconds']:.3f} | "+ f"{value['peak_footprint'] / 1024**3:.3f} | {value['exact']} | {value['forward_calls']} |"+ )+ for row in value["documents"]:+ stages = row["stages"]+ docs.append(+ f"| {name} | {policy} | {row['document']} | {row['seconds']:.3f} | {stages['preprocess']:.3f} | "+ f"{stages['forward']:.3f} | {stages['output_transfer']:.3f} | {stages['postprocess']:.3f} | "+ f"{len(row['shape_counts'])} |"+ )+ comparisons = {+ "single_fusion_reduction_j_to_k": 1 - medians["K"]["det_seconds"] / medians["J"]["det_seconds"],+ "fused_single_reduction_vs_fused_batch": 1 - medians["K"]["det_seconds"] / medians["E"]["det_seconds"],+ "single_seconds_ratio_to_n1_split": medians["K"]["det_seconds"] / medians["F"]["det_seconds"],+ "single_reduction_vs_cpu": 1 - medians["K"]["det_seconds"] / medians["A"]["det_seconds"],+ }+ summary["comparisons"] = comparisons+ write_json(args.output / "summary.json", summary)+ headline = [+ f"| {policy} | {NAMES[policy]} | {value['det_seconds']:.3f} | "+ f"{value['peak_footprint'] / 1024**3:.3f} | {value['outputs_exact']} |"+ for policy, value in medians.items()+ ]+ report = f"""# 3.4 单图入口与 batch/N=1 det 对照++单图入口融合后,相对未融合单图耗时降低 {comparisons["single_fusion_reduction_j_to_k"]:.1%};+相对融合 batch E 降低 {comparisons["fused_single_reduction_vs_fused_batch"]:.1%}。+K/F 耗时比 {comparisons["single_seconds_ratio_to_n1_split"]:.3f};相对 CPU A 降低+{comparisons["single_reduction_vs_cpu"]:.1%}(负数表示慢于 CPU)。++3.4.0/3.4.5 的 TextDetector.__call__ 及四个共享方法,与当前方法执行主体 AST 完全相同,证据见 history-proof.json。+单图入口使用共享底层方法,实际每次网络前向 N=1。3.4 默认中文 det 是 small;本实验继续使用同一 tiny 权重及 FP32,+只比较调用路径,不能推导完整 3.4 默认模型/精度/解析流程速度。++融合与调用路径无关:在 CPU/eval/现有 reparam 后使用原融合器,K 剩余 BN=0;J 不融合。+单图入口已经 N=1,无法再通过 N 拆分降低 N;F 与 K 均为 N=1,区别在批量前后处理与逐图前后处理。+F/J/K 不改变 H/W,不补齐空间或虚假样本。实际网络 NCHW 全部保存并验证。++使用 2280 个冻结输入、两组原后处理参数、FP32、生产线程,两轮 A/E/F/J/K 与反序,独立新进程串行。+三文档原顺序,每本文档完整清理,无额外前向预热;模型在进程内复用。+执行环境一致:{summary["matched_execution_environment"]};det 源码运行前后稳定:{summary["source_stable"]};+FP32:{summary["fp32"]};实例复用:{summary["models_reused"]};N=1 形状核实:{summary["n1_shapes_verified"]}。+实际执行源码在 executed-scripts/,历史源码在 history/。++| 策略 | 说明 | 三文档 det 中位数秒 | 峰 footprint GiB | 与冻结参考框完全一致 |+| --- | --- | ---: | ---: | --- |+{chr(10).join(headline)}++| 轮次 | 策略 | det 秒 | 加载+融合+det+清理秒 | 峰 footprint GiB | 框一致 | 网络前向次数 |+| --- | --- | ---: | ---: | ---: | --- | ---: |+{chr(10).join(rows)}++| 轮次 | 策略 | 文档 | det 秒 | 前处理秒 | 同步 forward 秒 | 回传秒 | 后处理秒 | 唯一 NCHW |+| --- | --- | --- | ---: | ---: | ---: | ---: | ---: | ---: |+{chr(10).join(docs)}++总 det 包括前处理、张量创建、同步 forward、回传、DB 后处理和循环调度。+PNG 读取、采样与结果写盘排除在 det 外。模型加载、融合及清理单独记录。+所有策略沿用冻结原调用结束的同步采样边界;J/K 在该边界内逐张推理,没有额外插入单张内存采样。+采样峰值不代表算子内部瞬时峰值;footprint 包含压缩页记账,与 RSS/driver 重叠,不能相加。全机 swap 单独记录。+本轮不更改生产设备默认、公开接口和原权重,不再测试 H/W 补齐。短测不证明持久服务内存稳定。++```bash+.venv4/bin/python tools/analyze_det_single.py experiment --output NEW_OUTPUT+.venv4/bin/python tools/analyze_det_single.py summarize --output {args.output}+.venv4/bin/python tools/benchmark_det_corpus.py run --policies J,K --cycles 1 --limit-calls 12 --output NEW_SMOKE+```+"""+ (args.output / "report.md").write_text(report, encoding="utf-8")+ print(json.dumps({"medians": medians, "comparisons": comparisons}, ensure_ascii=False), flush=True)+++def experiment(args: argparse.Namespace) -> None:+ """先确认历史单图方法与烟测输出,再按正反两轮独立进程比较五种策略。"""+ if args.output.exists() and any(path.name != "smoke" for path in args.output.iterdir()):+ raise FileExistsError("实验要求全新目录或仅包含本次已完成的 smoke")+ args.output.mkdir(parents=True, exist_ok=True)+ inspect_history(args.output)+ archive = args.output / "executed-scripts"+ archive.mkdir()+ for name in (+ "benchmark_det_corpus.py",+ "benchmark_mps_det_service.py",+ "det_shape_buckets.py",+ "analyze_det_fusion.py",+ Path(__file__).name,+ ):+ shutil.copy2(Path(__file__).parent / name, archive / name)+ if not (args.output / "smoke/protocol.json").exists():+ execute_run(args, "smoke", "A,E,F,J,K", limit_calls=12)+ summary = collect(args)+ if set(summary["smoke"]) != set(NAMES):+ raise ValueError("烟测策略尚未全部完成")+ if not all(row["exact"] and row["profiles_complete"] for row in summary["smoke"].values()):+ write_json(args.output / "smoke-failed.json", summary)+ raise ValueError("烟测框差异或参数覆盖缺失,停止正式计时")+ state = {"phase": "round-1", "det_only": True, "original_weights": True}+ write_json(args.output / "experiment.json", state)+ execute_run(args, "round-1", "A,E,F,J,K")+ state["phase"] = "round-2"+ write_json(args.output / "experiment.json", state)+ execute_run(args, "round-2", "K,J,F,E,A")+ summarize(args)+ state["phase"] = "complete"+ write_json(args.output / "experiment.json", state)+++def main() -> None:+ """提供单图入口实验和独立汇总命令,既有 ABC/融合/形状汇总接口保持不变。"""+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("command", choices=("experiment", "summarize"))+ parser.add_argument("--output", type=Path, required=True)+ parser.add_argument("--corpus", type=Path, default=DEFAULT_CORPUS)+ args = parser.parse_args()+ args.output, args.corpus = args.output.resolve(), args.corpus.resolve()+ args.documents = "tender,python,114"+ {"experiment": experiment, "summarize": summarize}[args.command](args)+++if __name__ == "__main__":+ main()diff --git a/tools/analyze_det_spatial.py b/tools/analyze_det_spatial.pynew file mode 100644index 00000000..2564bf9d--- /dev/null+++ b/tools/analyze_det_spatial.py@@ -0,0 +1,517 @@+"""按逐输入数量一致、忽略顺序和人工几何裁决重新评估 H/W 补齐,仅用于实验。"""++from __future__ import annotations++import argparse+import json+import shutil+import statistics+import subprocess+from pathlib import Path+from typing import Any++from analyze_det_fusion import execute_run, load_runs+from benchmark_det_corpus import DEFAULT_CORPUS, ROOT, read_json+from benchmark_mps_det_service import write_json+++def match_boxes(reference: list[Any], actual: list[Any]) -> dict[str, Any]:+ """使用四边形 IoU 的最优一对一匹配忽略输出顺序,并记录原图像素中的角点误差。"""+ import cv2+ import numpy as np+ from scipy.optimize import linear_sum_assignment++ count_equal = len(reference) == len(actual)+ if reference == actual:+ return {"count_equal": True, "ordered_exact": True, "unordered_exact": True, "pairs": [], "triage": "exact"}+ overlaps = np.zeros((len(reference), len(actual)), dtype=np.float64)+ for i, left in enumerate(reference):+ left_array = np.asarray(left, dtype=np.float32)+ left_area = abs(cv2.contourArea(left_array))+ for j, right in enumerate(actual):+ right_array = np.asarray(right, dtype=np.float32)+ intersection, _ = cv2.intersectConvexConvex(left_array, right_array)+ union = left_area + abs(cv2.contourArea(right_array)) - intersection+ overlaps[i, j] = intersection / union if union > 0 else 0.0+ indices, candidates = linear_sum_assignment(-overlaps)+ pairs = []+ for i, j in zip(indices.tolist(), candidates.tolist()):+ left = np.asarray(reference[i], dtype=np.float64)+ right = np.asarray(actual[j], dtype=np.float64)+ variants = [np.roll(points, offset, axis=0) for points in (right, right[::-1]) for offset in range(4)]+ aligned = min(variants, key=lambda points: float(np.square(left - points).sum()))+ max_shift = float(np.linalg.norm(left - aligned, axis=1).max())+ # 相对短边可区分大表格的几像素变化与小字框的同样位移。+ short_side = max(1.0, float(np.linalg.norm(left - np.roll(left, -1, axis=0), axis=1).min()))+ pairs.append(+ {+ "reference_index": i,+ "actual_index": j,+ "iou": float(overlaps[i, j]),+ "max_corner_shift_px": max_shift,+ "shift_relative_short_side": max_shift / short_side,+ "corners_exact": bool(np.array_equal(left, aligned)),+ }+ )+ unordered_exact = count_equal and all(pair["corners_exact"] for pair in pairs)+ small = count_equal and all(+ pair["max_corner_shift_px"] <= 3 and pair["iou"] >= 0.8 and pair["shift_relative_short_side"] <= 0.15 for pair in pairs+ )+ return {+ "count_equal": count_equal,+ "ordered_exact": False,+ "unordered_exact": unordered_exact,+ "reference_count": len(reference),+ "actual_count": len(actual),+ "pairs": pairs,+ "unmatched_reference": sorted(set(range(len(reference))) - set(indices.tolist())),+ "unmatched_actual": sorted(set(range(len(actual))) - set(candidates.tolist())),+ "max_corner_shift_px": max((pair["max_corner_shift_px"] for pair in pairs), default=0.0),+ "min_iou": min((pair["iou"] for pair in pairs), default=0.0),+ "triage": "count_failure" if not count_equal else "order_only" if unordered_exact else "small" if small else "review",+ }+++def audit_run(entry: dict[str, Any], root: Path, documents: dict[str, Any]) -> dict[str, Any]:+ """逐个输入对照冻结参考,保留全部匹配明细,不用文档总框数抵消漏检或新增。"""+ changes = []+ inputs = 0+ for row in entry["records"]:+ calls = documents[row["document"]]["calls"]+ output = root / entry["directory"] / entry["policy"]+ boxes = read_json(output / f"{row['label']}-boxes.json")+ if len(boxes) != row["crops"]:+ raise ValueError("结果数量与原运行记录不一致")+ for result in boxes:+ reference = calls[result["call_index"]]["items"][result["item_index"]]+ if reference["crop"] != result["crop"]:+ raise ValueError("输入图像键与冻结调用不一致")+ comparison = match_boxes(reference["boxes"] or [], result["boxes"] or [])+ inputs += 1+ if comparison["ordered_exact"]:+ continue+ changes.append(+ {+ "directory": entry["directory"],+ "policy": entry["policy"],+ "document": row["document"],+ "label": row["label"],+ "call_index": result["call_index"],+ "item_index": result["item_index"],+ "crop": result["crop"],+ "profile": result["profile"],+ "reference": reference["boxes"],+ "actual": result["boxes"],+ "comparison": comparison,+ }+ )+ return {+ "inputs": inputs,+ "ordered_exact": inputs - len(changes),+ "count_failures": sum(not item["comparison"]["count_equal"] for item in changes),+ "order_only": sum(item["comparison"]["triage"] == "order_only" for item in changes),+ "small_triage": sum(item["comparison"]["triage"] == "small" for item in changes),+ "review_triage": sum(item["comparison"]["triage"] == "review" for item in changes),+ "changes": changes,+ }+++def make_inspection(corpus: Path, changes: list[dict[str, Any]], output: Path) -> list[dict[str, Any]]:+ """按数量变化和最大几何差异生成局部原图/参考/候选三栏图,人工裁决与自动分流分开保存。"""+ from PIL import Image, ImageDraw++ output.mkdir(parents=True, exist_ok=True)+ unique = {}+ for change in changes:+ key = (change["policy"], change["document"], change["call_index"], change["item_index"])+ unique.setdefault(key, change)+ selected = sorted(+ unique.values(),+ key=lambda item: (+ item["comparison"]["count_equal"],+ item["comparison"].get("min_iou", 1.0),+ -item["comparison"].get("max_corner_shift_px", 0.0),+ ),+ )+ inventory = []+ for index, item in enumerate(selected):+ comparison = item["comparison"]+ focus = [item["reference"][i] for i in comparison["unmatched_reference"]]+ focus += [item["actual"][i] for i in comparison["unmatched_actual"]]+ if not focus and comparison["pairs"]:+ worst = min(comparison["pairs"], key=lambda pair: pair["iou"])+ focus = [item["reference"][worst["reference_index"]], item["actual"][worst["actual_index"]]]+ with Image.open(corpus / "images" / f"{item['crop']}.png") as opened:+ source = opened.convert("RGB")+ points = [point for box in focus for point in box]+ region = (+ (+ max(0, int(min(point[0] for point in points)) - 20),+ max(0, int(min(point[1] for point in points)) - 20),+ min(source.width, int(max(point[0] for point in points)) + 21),+ min(source.height, int(max(point[1] for point in points)) + 21),+ )+ if points+ else (0, 0, source.width, source.height)+ )+ width, height = region[2] - region[0], region[3] - region[1]+ scale = min(2.0, 460 / width, 360 / height)+ panel_width, panel_height = max(1, int(width * scale)), max(1, int(height * scale))+ canvas = Image.new("RGB", (panel_width * 3, panel_height + 65), "white")+ title = (+ f"{index:04d} {item['policy']} {item['document']} call{item['call_index']} item{item['item_index']} "+ f"count {len(item['reference'])}->{len(item['actual'])} "+ f"IoU {comparison.get('min_iou', 1):.3f} shift {comparison.get('max_corner_shift_px', 0):.1f}px"+ )+ ImageDraw.Draw(canvas).text((4, 3), title, fill="black")+ for column, (label, boxes, color) in enumerate(+ (("source", [], "black"), ("reference", item["reference"], "red"), ("padded", item["actual"], "blue"))+ ):+ panel = source.copy()+ draw = ImageDraw.Draw(panel)+ for box in boxes:+ draw.line([tuple(point) for point in box] + [tuple(box[0])], fill=color, width=1)+ panel = panel.crop(region).resize((panel_width, panel_height))+ canvas.paste(panel, (column * panel_width, 65))+ ImageDraw.Draw(canvas).text((column * panel_width + 4, 38), label, fill=color)+ name = f"{index:04d}-{item['policy']}-{item['document']}-call{item['call_index']:04d}-item{item['item_index']:03d}.png"+ canvas.save(output / name)+ inventory.append({"image": name, "region": list(region), "change": item, "verdict": None})+ write_json(output / "inventory.json", inventory)+ return inventory+++def review_git_revisions(heads: set[str]) -> dict[str, Any]:+ """仅容许已核实未被 det 重放入口调用的印章修复及测试提交,其他源码漂移仍阻止环境通过。"""+ ignored_runtime = {+ "mineru/model/ocr/pp_ocr_v6_onnx.py",+ "mineru/model/ocr/pytorch_paddle.py",+ "mineru/model/ocr/seal_crop.py",+ }+ revisions = sorted(heads)+ changes = []+ for revision in revisions[1:]:+ paths = subprocess.check_output(+ ["git", "diff", "--name-only", revisions[0], revision], cwd=ROOT, text=True+ ).splitlines()+ relevant = [path for path in paths if not path.startswith("tests/") and path not in ignored_runtime]+ changes.append({"from": revisions[0], "to": revision, "changed_paths": paths, "unreviewed_paths": relevant})+ return {+ "heads": revisions,+ "same_head": len(revisions) == 1,+ "det_source_equivalent": bool(revisions) and all(not change["unreviewed_paths"] for change in changes),+ "changes": changes,+ "reason": "worker 直接调用 _internal.pytorchocr.infer.predict_det.TextDetector,不执行三处印章裁剪/引擎代码。",+ }+++def collect(args: argparse.Namespace, root: Path) -> dict[str, Any]:+ """汇总配对耗时与逐输入数量检查,细微 bbox 分流阈值只用于选图,不自动判合格。"""+ state_file = root / "experiment.json"+ if state_file.exists() and read_json(state_file).get("timing_valid") is False:+ raise ValueError("该目录已标记并行 VLM 干扰,耗时禁止用于性能汇总;请在安静时段另开目录重测")+ documents = {document["name"]: document for document in read_json(args.corpus / "manifest.json")["documents"]}+ runs = load_runs(root)+ groups = {}+ environments = set()+ execution_environments = set()+ heads = set()+ fp32 = True+ reused = True+ required_profiles = {(call["box_thresh"], call["unclip_ratio"]) for doc in documents.values() for call in doc["calls"]}+ profiles_complete = True+ for entry in runs:+ rows, env = entry["records"], entry["environment"]+ environments.add(+ tuple(+ env[key]+ for key in (+ "model_sha256",+ "torch_commit",+ "python",+ "threads",+ "interop_threads",+ "git_head",+ "script_sha256",+ "shape_adapter_sha256",+ )+ )+ )+ execution_environments.add(+ tuple(+ env[key]+ for key in (+ "model_sha256",+ "torch_commit",+ "python",+ "threads",+ "interop_threads",+ "script_sha256",+ "shape_adapter_sha256",+ )+ )+ )+ heads.add(env["git_head"])+ fp32 &= all(model["dtype"] == "torch.float32" for row in rows for model in row["models"])+ profiles = {tuple(model["profile"]) for row in rows for model in row["models"]}+ profiles_complete &= profiles == required_profiles+ reused &= all(+ len({model["net_id"] for row in rows for model in row["models"] if tuple(model["profile"]) == profile}) == 1+ for profile in profiles+ )+ quality = audit_run(entry, root, documents)+ det = sum(row["seconds"] for row in rows)+ loading = sum(model["loading_seconds"] for model in env["model_loads"])+ fusion = sum(model["fusion"]["seconds"] for model in env["model_loads"])+ cleanup = sum(row["cleanup_seconds"] for row in rows) + env["shutdown_seconds"]+ groups.setdefault(entry["directory"], {})[entry["policy"]] = {+ "det_seconds": det,+ "operational_seconds": det + loading + fusion + cleanup,+ "loading_seconds": loading,+ "fusion_seconds": fusion,+ "cleanup_seconds": cleanup,+ "peak_footprint": max(+ *(row["peak_memory_diagnostics"]["phys_footprint"] for row in rows),+ env["shutdown_memory_diagnostics_before"]["phys_footprint"],+ env["shutdown_memory_diagnostics_after"]["phys_footprint"],+ ),+ "quality": quality,+ "documents": [+ {+ key: row[key]+ for key in (+ "document",+ "seconds",+ "crops",+ "stages",+ "cleanup_seconds",+ "memory_after",+ "memory_diagnostics_after",+ )+ }+ for row in rows+ ],+ }+ revision_review = review_git_revisions(heads)+ return {+ "groups": groups,+ "matched_environment": len(environments) == 1,+ "matched_execution_environment": len(execution_environments) == 1 and revision_review["det_source_equivalent"],+ "revision_review": revision_review,+ "fp32": fp32,+ "models_reused": reused,+ "profiles_complete": profiles_complete,+ "environments": [{key: value for key, value in entry["environment"].items() if key != "model_loads"} for entry in runs],+ }+++def render_metrics(summary: dict[str, Any], source: Path, output: Path) -> None:+ """绘制独立轮次的耗时及逐调用 footprint 曲线,避免将数量失败的速度误画成验收通过。"""+ import matplotlib++ matplotlib.use("Agg")+ import matplotlib.pyplot as plt++ groups = {name: group for name, group in summary["groups"].items() if name.startswith("round-")}+ if not groups:+ return+ figure, axes = plt.subplots(1, 2, figsize=(12, 4), constrained_layout=True)+ policies = [policy for policy in ("A", "E", "H", "I") if policy in summary["policies"]]+ medians = [summary["policies"][policy]["median_det_seconds"] for policy in policies]+ axes[0].bar(policies, medians, alpha=0.6)+ for index, policy in enumerate(policies):+ axes[0].scatter([index] * len(groups), [group[policy]["det_seconds"] for group in groups.values()], c="black", s=18)+ axes[0].set(ylabel="det seconds", title="Three-document median; dots = independent runs")+ axes[1].bar(policies, [summary["policies"][policy]["peak_footprint"] / 1024**3 for policy in policies], alpha=0.6)+ axes[1].axhline(8, color="red", linestyle="--", label="8 GiB budget")+ axes[1].set(ylabel="Sampled footprint GiB", title="Quality is evaluated separately")+ axes[1].legend()+ figure.savefig(output / "performance-memory.png", dpi=160)+ plt.close(figure)+ figure, axes = plt.subplots(len(groups), 1, figsize=(12, 3 * len(groups)), squeeze=False, constrained_layout=True)+ for axis, (name, group) in zip(axes[:, 0], groups.items()):+ for policy in group:+ rows = read_json(source / name / policy / "results.json")+ samples = [+ metric["memory_diagnostics"]["phys_footprint"] / 1024**3 for row in rows for metric in row["call_metrics"]+ ]+ axis.plot(range(1, len(samples) + 1), samples, label=policy)+ axis.axhline(8, color="red", linestyle="--")+ axis.set(xlabel="Original det call index; cleanup after each document", ylabel="footprint GiB", title=name)+ axis.grid(alpha=0.2)+ axis.legend()+ figure.savefig(output / "memory-curves.png", dpi=160)+ plt.close(figure)+++def summarize(args: argparse.Namespace, root: Path | None = None) -> None:+ """保存放宽坐标门槛后的独立报告,数量失败的性能数据始终标为探索结果。"""+ source = root or args.output+ summary = collect(args, source)+ args.output.mkdir(parents=True, exist_ok=True)+ changes = [+ change for group in summary["groups"].values() for value in group.values() for change in value["quality"]["changes"]+ ]+ make_inspection(args.corpus, changes, args.output / "inspection")+ summaries = {}+ for policy in ("A", "E", "H", "I"):+ groups = [group for name, group in summary["groups"].items() if name.startswith("round-") and policy in group]+ if not groups:+ continue+ values = [group[policy] for group in groups]+ paired = [group for group in groups if "E" in group]+ total = statistics.median(value["det_seconds"] for value in values)+ quality = [value["quality"] for value in values]+ summaries[policy] = {+ "rounds": len(groups),+ "median_det_seconds": total,+ "reduction_vs_e": 1 - total / statistics.median(group["E"]["det_seconds"] for group in paired) if paired else None,+ "round_gains_vs_e": [1 - group[policy]["det_seconds"] / group["E"]["det_seconds"] for group in paired],+ "peak_footprint": max(value["peak_footprint"] for value in values),+ "inputs": sum(value["inputs"] for value in quality),+ "count_failures": sum(value["count_failures"] for value in quality),+ "count_gate_pass": all(value["count_failures"] == 0 for value in quality),+ "bbox_visual_acceptance": (+ "not_eligible_count_failed"+ if any(value["count_failures"] for value in quality)+ else "not_required"+ if all(not value["changes"] for value in quality)+ else "pending"+ ),+ "research_pass": False,+ }+ summary["policies"] = summaries+ write_json(args.output / "summary.json", summary)+ write_json(args.output / "source-revision-review.json", summary["revision_review"])+ render_metrics(summary, source, args.output)+ rows, detail = [], []+ for name, group in summary["groups"].items():+ for policy, value in group.items():+ quality = value["quality"]+ rows.append(+ f"| {name} | {policy} | {value['det_seconds']:.3f} | {value['operational_seconds']:.3f} | "+ f"{value['peak_footprint'] / 1024**3:.3f} | {quality['count_failures']}/{quality['inputs']} | "+ f"{quality['order_only']} | {quality['small_triage']} | {quality['review_triage']} |"+ )+ for doc in value["documents"]:+ stage = doc["stages"]+ detail.append(+ f"| {name} | {policy} | {doc['document']} | {doc['seconds']:.3f} | {stage['preprocess']:.3f} | "+ f"{stage['forward']:.3f} | {stage['output_transfer']:.3f} | {stage['postprocess']:.3f} |"+ )+ medians = [+ f"| {policy} | {value['median_det_seconds']:.3f} | {value['reduction_vs_e']:.1%} | "+ f"{value['peak_footprint'] / 1024**3:.3f} | {value['count_gate_pass']} |"+ for policy, value in summaries.items()+ if value["reduction_vs_e"] is not None+ ]+ report = f"""# H/W 补齐:放宽顺序及细微 bbox 后的 det 实验++数量门槛按每个 det 输入检查;允许框顺序不同,四边形以最大 IoU 最优匹配。+细微 bbox 必须结合原图判断。角点 ≤3 px、IoU ≥0.8、位移 ≤短边 15% 仅用于选图分流,**不自动代表验收**。+数量变化无论正负都失败,不能用同本文档的总框数相同抵消。++A 为 CPU 原模型;E 为 36 组 Conv/BN 全融合 MPS、原形状;H/I 与 E 相同,但归一化输入右/下补 0 到 64/128 倍数。+使用冻结 2280 个输入、原顺序/batch、FP32、两种原后处理参数、每本文档原清理、同进程模型复用。+基线与候选独立进程串行,第二轮策略顺序反转;没有前向预热、跨文档保留图缓存或重跑 PDF。+即使先前烟测已发现数量问题,本轮也执行速度探索,**不将速度收益等同于通过输出验收**。+环境指纹一致:{summary["matched_environment"]};FP32:{summary["fp32"]};模型复用:{summary["models_reused"]};+两种后处理参数覆盖:{summary["profiles_complete"]}。详细环境、权重及源码 SHA256 保存在各策略 environment.json。+提交号一致:{summary["revision_review"]["same_head"]};普通 det 源码等价核验:+{summary["revision_review"]["det_source_equivalent"]};排除已核实的印章提交元信息后,执行环境一致:+{summary["matched_execution_environment"]}。提交差异的原始文件清单保存在 source-revision-review.json,未隐藏原提交号。++| 轮次 | 策略 | det 秒 | 加载+融合+det+清理 秒 | 峰 footprint GiB | 数量变化/输入 | 仅顺序变化 | 细微差异分流 | 需重点审阅 |+| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |+{chr(10).join(rows)}++| 策略 | 三文档 det 中位数秒 | 相对 E 降低 | 峰 footprint GiB | 逐输入数量门槛 |+| --- | ---: | ---: | ---: | --- |+{chr(10).join(medians)}++| 轮次 | 策略 | 文档 | det 秒 | 前处理秒 | 同步 forward 秒 | 回传秒 | 后处理秒 |+| --- | --- | --- | ---: | ---: | ---: | ---: | ---: |+{chr(10).join(detail)}++det 包含前处理、补齐、同步 forward、回传、原形状恢复和后处理。+PNG 读取、输出写盘、差异图绘制、逐调用采样、模型加载/融合及清理不计入 det;这些记录仍保存在原始数据。+采样 footprint 包含压缩页记账,不能与 RSS/driver 相加,采样峰值不代表算子内部瞬时峰值。+内存预算仍为 8 GiB。全机 swap 不归属于单个进程。仅代表 det,不推导整本解析速度。++全部原框/候选框/最优匹配保存在 summary.json;原图与全图叠框在各策略 review/,+局部三栏审阅图在 inspection/,其中 inventory.json 的 verdict 初始为 null,不冒充已完成视觉验收。+旧烟测及概率图证据:{args.previous}。本轮保留旧报告不覆盖。++```bash+.venv4/bin/python tools/analyze_det_spatial.py experiment --output NEW_OUTPUT+.venv4/bin/python tools/analyze_det_spatial.py summarize --output {args.output}+.venv4/bin/python tools/benchmark_det_corpus.py run --policies E,H,I --cycles 1 \\+ --documents 114 --call-indices 0,1 --save-maps --output NEW_DIAGNOSTIC+```+"""+ (args.output / "report.md").write_text(report, encoding="utf-8")+ print(+ json.dumps({"matched_environment": summary["matched_environment"], "policies": summaries}, ensure_ascii=False),+ flush=True,+ )+++def experiment(args: argparse.Namespace) -> None:+ """在全新目录执行正反两轮全量速度探索,数量失败者不进入生命周期或生产候选验收。"""+ if args.output.exists() and any(args.output.iterdir()):+ raise FileExistsError("实验要求全新目录,不能覆盖旧证据")+ args.output.mkdir(parents=True, exist_ok=True)+ source = args.output / "executed-scripts"+ source.mkdir()+ for path in Path(__file__).parent.glob("*det*.py"):+ if path.name in {+ "benchmark_det_corpus.py",+ "benchmark_mps_det_service.py",+ "analyze_det_fusion.py",+ "det_shape_buckets.py",+ Path(__file__).name,+ }:+ shutil.copy2(path, source / path.name)+ state = {+ "phase": "round-1",+ "previous": str(args.previous),+ "mode": "speed_exploration_count_gate_required",+ "timing_valid": True,+ "context_note": args.context_note,+ }+ write_json(args.output / "experiment.json", state)+ execute_run(args, "round-1", "A,E,H,I")+ state["phase"] = "round-2"+ write_json(args.output / "experiment.json", state)+ execute_run(args, "round-2", "I,H,E,A")+ summarize(args)+ state.update({"phase": "complete", "lifecycle": "not_executed_for_count_failed_candidates"})+ write_json(+ args.output / "experiment.json",+ state,+ )+++def main() -> None:+ """提供独立速度探索、汇总和旧烟测重新几何评估入口,不修改既有严格实验入口。"""+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("command", choices=("experiment", "summarize", "audit"))+ parser.add_argument("--corpus", type=Path, default=DEFAULT_CORPUS)+ parser.add_argument("--output", type=Path, required=True)+ parser.add_argument("--previous", type=Path, default=Path("tmp/pdfs/issue5632-det-shapes-20261012-1826"))+ parser.add_argument("--context-note", default="", help="记录开始计时前的外部任务完成状态,不替代环境数据")+ args = parser.parse_args()+ args.corpus, args.output, args.previous = args.corpus.resolve(), args.output.resolve(), args.previous.resolve()+ args.documents = "tender,python,114"+ if args.command == "experiment":+ experiment(args)+ elif args.command == "audit":+ if args.output.exists() and any(args.output.iterdir()):+ raise FileExistsError("旧烟测重新审阅要求全新目录")+ summarize(args, args.previous)+ else:+ summarize(args)+++if __name__ == "__main__":+ main()diff --git a/tools/analyze_mps_det_service.py b/tools/analyze_mps_det_service.pynew file mode 100644index 00000000..114e1540--- /dev/null+++ b/tools/analyze_mps_det_service.py@@ -0,0 +1,291 @@+"""汇总独立服务实验的时间、内存、完整输出和逐裁剪检测框差异。"""++from __future__ import annotations++import argparse+import json+import sys+from collections import defaultdict+from pathlib import Path+from typing import Any++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT))++from benchmark_mps_det_service import DEFAULT_OUTPUT, SAMPLES, write_json # noqa: E402+++def read_json(path: Path) -> Any:+ """读取完整原始结果,不删除源文档的创建时间等语义元数据。"""+ return json.loads(path.read_text(encoding="utf-8"))+++def differences(left: Any, right: Any, path: str = "") -> list[dict[str, Any]]:+ """逐项保存所有不同叶子的路径和值,完整输入另保存在原始文件中。"""+ if type(left) is not type(right):+ return [{"path": path, "left": left, "right": right}]+ if isinstance(left, dict):+ result: list[dict[str, Any]] = []+ for key in sorted(left.keys() | right.keys()):+ if key not in left or key not in right:+ result.append({"path": f"{path}/{key}", "left": left.get(key), "right": right.get(key)})+ else:+ result.extend(differences(left[key], right[key], f"{path}/{key}"))+ return result+ if isinstance(left, list):+ result = []+ if len(left) != len(right):+ result.append({"path": f"{path}/length", "left": len(left), "right": len(right)})+ for index, (first, second) in enumerate(zip(left, right)):+ result.extend(differences(first, second, f"{path}/{index}"))+ for index in range(min(len(left), len(right)), max(len(left), len(right))):+ result.append(+ {+ "path": f"{path}/{index}",+ "left": left[index] if index < len(left) else None,+ "right": right[index] if index < len(right) else None,+ }+ )+ return result+ return [] if left == right else [{"path": path, "left": left, "right": right}]+++def det_items(path: Path) -> dict[str, list[Any]]:+ """按裁剪内容和后处理参数对齐检测结果,允许模型实例地址不同。"""+ result: dict[str, list[Any]] = defaultdict(list)+ for line in path.read_text().splitlines():+ batch = json.loads(line)+ for item in batch["items"]:+ key = f"{batch['box_thresh']}:{batch['unclip_ratio']}:{item['crop']}"+ result[key].append(item["boxes"])+ return dict(result)+++def det_overlay(+ root: Path, target: Path, left_policy: str, right_policy: str, key: str, left: list[Any] | None, right: list[Any] | None+) -> None:+ """逐个保存变化裁剪的前后检测框,缺少对应输入时明确标注。"""+ from PIL import Image, ImageDraw++ crop_hash = key.split(":")[-1]+ source = root / left_policy / "crops" / f"{crop_hash}.png"+ if not source.exists():+ source = root / right_policy / "crops" / f"{crop_hash}.png"+ with Image.open(source) as opened:+ original = opened.convert("RGB")+ width, height = original.size+ canvas = Image.new("RGB", (2 * width, height + 36), "white")+ for column, (policy, groups, color) in enumerate(((left_policy, left, "red"), (right_policy, right, "blue"))):+ panel = original.copy()+ draw = ImageDraw.Draw(panel)+ if groups:+ for boxes in groups:+ for box in boxes or []:+ draw.line([tuple(point) for point in box] + [tuple(box[0])], fill=color, width=2)+ canvas.paste(panel, (column * width, 36))+ ImageDraw.Draw(canvas).text(+ (column * width + 5, 8),+ f"{policy}: {sum(len(boxes or []) for boxes in groups) if groups else 'no matching input'}",+ fill="black",+ )+ canvas.save(target)+++def draw_blocks(image: Any, blocks: list[dict[str, Any]], color: str) -> Any:+ """递归绘制共享 MiddleJson 的归一化 block 几何,保留原始页面像素。"""+ from PIL import ImageDraw++ panel = image.copy()+ draw = ImageDraw.Draw(panel)+ width, height = image.size++ def visit(items: list[dict[str, Any]]) -> None:+ """遍历有几何信息的块及子块,不把内容文本当作几何数据。"""+ for block in items:+ bbox = block.get("bbox")+ if isinstance(bbox, list) and len(bbox) == 4:+ draw.rectangle([bbox[0] * width, bbox[1] * height, bbox[2] * width, bbox[3] * height], outline=color, width=2)+ for field in ("children", "blocks"):+ if isinstance(block.get(field), list):+ visit(block[field])++ visit(blocks)+ return panel+++def page_overlays(directory: Path, sample: str, left: dict[str, Any], right: dict[str, Any], pages: list[int]) -> None:+ """为所有语义变化页保存原文、CPU 和候选整页叠框,不声称未查看页面已人工审阅。"""+ from docvortex.document.pdf import PDFDocument++ left_pages = {page["page_idx"]: page for page in left["pages"]}+ right_pages = {page["page_idx"]: page for page in right["pages"]}+ with PDFDocument(str(SAMPLES[sample])) as document:+ for index in pages:+ image = document.render_page(index).pil_image.convert("RGB")+ image.save(directory / f"page-{index + 1:03d}-source.png")+ draw_blocks(image, left_pages.get(index, {}).get("blocks", []), "red").save(+ directory / f"page-{index + 1:03d}-baseline.png"+ )+ draw_blocks(image, right_pages.get(index, {}).get("blocks", []), "blue").save(+ directory / f"page-{index + 1:03d}-candidate.png"+ )+++def compare_request(root: Path, label: str, policy: str, sample: str, baseline_label: str | None = None) -> dict[str, Any]:+ """比较 CPU 基线与一份候选请求,完整保留数值变化与视觉证据。"""+ baseline_label = baseline_label or label+ first = root / "A" / baseline_label+ second = root / policy / label+ target = root / "comparisons" / f"A-{baseline_label}-vs-{policy}-{label}"+ target.mkdir(parents=True, exist_ok=True)+ middle_a = read_json(first / "middle_json.json")+ middle_b = read_json(second / "middle_json.json")+ # 当前共享协议没有运行计时字段;源文档元数据和所有语义字段均原样比较。+ middle_diff = differences(middle_a, middle_b)+ model_diff = differences(read_json(first / "bundle/model_output.json"), read_json(second / "bundle/model_output.json"))+ a, b = det_items(first / "det-trace.jsonl"), det_items(second / "det-trace.jsonl")+ det_diff = [+ {"key": key, "left": a.get(key), "right": b.get(key)} for key in sorted(a.keys() | b.keys()) if a.get(key) != b.get(key)+ ]+ write_json(target / "middle-differences.json", middle_diff)+ write_json(target / "model-differences.json", model_diff)+ write_json(target / "det-differences.json", det_diff)+ markdown_equal = (first / "markdown.md").read_bytes() == (second / "markdown.md").read_bytes()+ if not markdown_equal:+ import difflib++ delta = difflib.unified_diff(+ (first / "markdown.md").read_text().splitlines(True),+ (second / "markdown.md").read_text().splitlines(True),+ fromfile="baseline",+ tofile="candidate",+ )+ (target / "markdown.diff").write_text("".join(delta), encoding="utf-8")+ changed_pages = sorted(+ {+ int(item["path"].split("/")[2])+ for item in middle_diff+ if item["path"].startswith("/pages/") and item["path"].split("/")[2].isdigit()+ }+ )+ page_overlays(target, sample, middle_a, middle_b, changed_pages)+ for index, delta in enumerate(det_diff):+ det_overlay(root, target / f"det-{index:05d}.png", "A", policy, delta["key"], delta["left"], delta["right"])+ return {+ "policy": policy,+ "label": label,+ "baseline_label": baseline_label,+ "markdown_equal": markdown_equal,+ "middle_equal": not middle_diff,+ "model_equal": not model_diff,+ "det_equal": not det_diff,+ "middle_changed_leaves": len(middle_diff),+ "model_changed_leaves": len(model_diff),+ "det_changed_keys": len(det_diff),+ "changed_pages": [index + 1 for index in changed_pages],+ "directory": str(target),+ }+++def analyze(root: Path) -> None:+ """计算预先约定的速度、内存和输出门槛,给出下一步决策所需证据。"""+ requests = {policy: read_json(root / policy / "requests.json") for policy in ("A", "B", "C")}+ comparisons = []+ for policy, records in requests.items():+ for record in records:+ if policy != "A":+ comparisons.append(compare_request(root, record["label"], policy, record["sample"]))+ if record["label"].startswith(("04-", "05-", "06-")):+ baseline_label = f"{int(record['label'][:2]) - 3:02d}-{record['sample']}"+ comparisons.append(compare_request(root, record["label"], policy, record["sample"], baseline_label))+ aggregate: dict[str, Any] = {}+ for policy, records in requests.items():+ aggregate[policy] = {}+ for cycle, subset in (("first", records[:3]), ("second", records[3:6])):+ aggregate[policy][cycle] = {+ key: sum(record[key] for record in subset)+ for key in ("request_seconds", "server_seconds", "det_seconds", "capture_seconds")+ }+ aggregate[policy]["memory_growth"] = {+ key: {+ "first": records[2]["memory_after"][key],+ "second": records[5]["memory_after"][key],+ "growth": records[5]["memory_after"][key] - records[2]["memory_after"][key],+ "limit": max(256 * 1024**2, records[2]["memory_after"][key] * 0.1),+ }+ for key in ("rss", "mps_allocated", "mps_driver")+ }+ cpu, candidate = aggregate["A"]["second"], aggregate["C"]["second"]+ det_reduction = 1 - candidate["det_seconds"] / cpu["det_seconds"]+ wall_ratio = candidate["request_seconds"] / cpu["request_seconds"]+ gate = {+ "det_reduction": det_reduction,+ "det_pass": det_reduction >= 0.25,+ "request_time_ratio": wall_ratio,+ "request_pass": wall_ratio <= 1.05,+ "memory_pass": all(value["growth"] <= value["limit"] for value in aggregate["C"]["memory_growth"].values()),+ "output_exact": all(+ check["middle_equal"] and check["markdown_equal"] and check["det_equal"] and check["model_equal"]+ for check in comparisons+ ),+ "additional_memory_cycle_needed": any(+ value["growth"] > value["limit"] for value in aggregate["C"]["memory_growth"].values()+ ),+ "reverse_order_needed": abs(1 - wall_ratio) < 0.1 or abs(det_reduction) < 0.1,+ }+ summary = {"aggregates": aggregate, "gates": gate, "comparisons": comparisons}+ write_json(root / "summary.json", summary)+ rows = []+ for policy, records in requests.items():+ for record in records:+ rows.append(+ f"| {policy} | {record['label']} | {record['request_seconds']:.2f} | {record['det_seconds']:.2f} | "+ f"{record['memory_after']['rss'] / 1024**3:.2f} | {record['memory_after']['mps_driver'] / 1024**3:.2f} | "+ f"{record['crops']} | {record['new_shapes']}/{record['reused_shapes']} |"+ )+ report = f"""**MPS det 跨文档 API 实验:第一轮验收**++三种策略在独立进程中串行运行。A=CPU det+原清理,B=MPS det+原清理,C=MPS det+仅 GC 保留缓存。+每个进程使用本地真实 V1 API、Basic、强制 OCR、全部页面、关闭可选图像描述、并发 1。+顺序为 95 页招标文件、88 页 Python.pdf、114 页 _114.pdf,再重复一次;没有 VLM、预热或算法优化。++| 策略 | 文档 | API 完整秒 | 普通 det 秒 | 结束 RSS GiB | 结束 MPS driver GiB | 裁剪数 | 新形状/复用形状调用 |+| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: |+{chr(10).join(rows)}++第二遍三本文档合计:C 相对 A 的 det 耗时降低 {det_reduction:.2%},API 完整请求耗时比值 {wall_ratio:.3f}。+预定门槛:det 降低至少 25%,完整请求不回退超过 5%;分别为 {gate["det_pass"]}、{gate["request_pass"]}。+内存筛查通过:{gate["memory_pass"]};输出逐项完全一致:{gate["output_exact"]}。+需要追加内存轮次:{gate["additional_memory_cycle_needed"]};需要逆序复测:{gate["reverse_order_needed"]}。++内存门槛为第二遍结束对第一遍结束的增长不超过 max(10%,256 MiB),同时检查 RSS、MPS allocated、driver。+这只验证有限形状集合的两遍输入,不证明无限种类文档下缓存有界。+完整服务结束后会清空本地模型并释放 MPS 缓存,证据在各策略 shutdown.json。++普通 det 时间包含所有非印章 det 实例的真实预处理与同步推理/后处理,涵盖正文和表格使用的 det。+预处理截图、哈希和取证 JSON 写出耗时单独记录,不计入普通 det 时间。+原始 API 完整墙钟包含这些取证开销、生产导出和调度,但不包括结果下载。+第二遍已有裁剪不重复保存 PNG。NCHW 复用统计表示输入形状再次出现,不是底层 MPSGraph 命中率;原清理后会重置观察集合。+初始模型加载计入第一份文档完整请求,不计入 det 内部执行时间。其他模型的设备、精度和推理流程均不改。++所有请求保存 job.json、middle_json.json、markdown.md、自包含 zip/model_output.json、逐裁剪 det-trace.jsonl。+comparisons/ 保存所有变化叶子、Markdown diff、变化页的原文/基线/候选叠框,以及变化裁剪的前后 det 框。+源文档元数据全部保留,没有以删除 metadata 或模糊数值容差制造输出一致;job ID/运行计时属于单独的 API 请求记录。+自动差异和人工视觉裁决需分别报告,本报告生成时尚未自动把所有图片宣称为人工审阅完成。++本轮结论限定为本机 Basic/OCR 的整本流程及共享 det,不泛化为 Standard/VLM 全流程,也不直接修改默认设备或缓存策略。+"""+ (root / "report.md").write_text(report, encoding="utf-8")+ print(json.dumps(gate, ensure_ascii=False, indent=2))+++def main() -> None:+ """允许显式选择实验目录,分析阶段不与正式推理同时运行。"""+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)+ args = parser.parse_args()+ analyze(args.output.resolve())+++if __name__ == "__main__":+ main()diff --git a/tools/benchmark_basic_nnpack.py b/tools/benchmark_basic_nnpack.pynew file mode 100644index 00000000..91478f8e--- /dev/null+++ b/tools/benchmark_basic_nnpack.py@@ -0,0 +1,364 @@+"""在 CPU 上用 demo1/demo2 强制 OCR 跑 Basic,简单比较全局 NNPACK 开关。"""++from __future__ import annotations++import argparse+import hashlib+import json+import os+import platform+import re+import shutil+import statistics+import subprocess+import sys+import threading+import time+from collections import Counter+from pathlib import Path+from typing import Any++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT))++from analyze_mps_det_service import differences # noqa: E402+from benchmark_det_corpus import mac_memory_diagnostics # noqa: E402+from benchmark_det_corpus import det_source_fingerprint # noqa: E402+from benchmark_mps_det_service import write_json # noqa: E402++DOCUMENTS = (ROOT / "demo/pdfs/demo1.pdf", ROOT / "demo/pdfs/demo2.pdf")+STAGES = {+ "pdf.layout": "Layout",+ "pdf.formulas": "MFR(含首次加载)",+ "pdf.ocr_detection": "正文 OCR det",+ "pdf.ocr_recognition": "正文 OCR rec",+ "pdf.table_recognition": "表格识别(含表内 OCR)",+ "pdf.formula_numbers": "公式编号(含 OCR rec)",+ "model.initialize": "模型初始化(嵌套,不能重复相加)",+}+++def sha256(path: Path) -> str:+ """分块校验权重与样本,避免一次性读取大权重增加内存占用。"""+ digest = hashlib.sha256()+ with path.open("rb") as stream:+ for chunk in iter(lambda: stream.read(8 * 1024**2), b""):+ digest.update(chunk)+ return digest.hexdigest()+++def inspect_models() -> list[dict[str, Any]]:+ """核对已加载 Torch 模型的全部参数确实为 CPU FP32,并记录权重位置及实例复用。"""+ import torch++ from mineru.model.runtime.hybrid import AtomModelSingleton++ records = []+ for key, wrapper in AtomModelSingleton._models.items():+ components = [wrapper]+ if hasattr(wrapper, "text_sys"):+ components = [wrapper.text_sys.text_detector, wrapper.text_sys.text_recognizer]+ elif hasattr(wrapper, "text_detector"):+ components = [wrapper.text_detector, wrapper.text_recognizer]+ for model in components:+ network = getattr(model, "net", None)+ if network is None:+ network = getattr(model, "model", None)+ if not isinstance(network, torch.nn.Module):+ continue+ parameters = list(network.parameters())+ devices = sorted({str(parameter.device) for parameter in parameters})+ dtypes = sorted({str(parameter.dtype) for parameter in parameters if parameter.is_floating_point()})+ assert devices == ["cpu"] and dtypes == ["torch.float32"], (type(model).__name__, devices, dtypes)+ weight = getattr(model, "weights_path", None) or getattr(model, "model_dir", None)+ records.append(+ {+ "key": str(key),+ "class": type(model).__name__,+ "id": id(model),+ "network_id": id(network),+ "devices": devices,+ "dtypes": dtypes,+ "weight": str(weight) if weight else None,+ }+ )+ assert any(row["class"] == "PPDocLayoutV2LayoutModel" for row in records), "未核对到 Torch Layout"+ assert any(row["class"] == "FormulaRecognizer" for row in records), "未核对到 Torch MFR"+ assert any(row["class"] == "TextDetector" for row in records), "未核对到 Torch det"+ assert any(row["class"] == "TextRecognizer" for row in records), "未核对到 Torch rec"+ return records+++def worker(args: argparse.Namespace) -> None:+ """在独立进程只改变 NNPACK 开关,通过公开 SDK 完成两份 PDF 的真实 CPU Basic/OCR 解析。"""+ os.environ["MINERU_DEVICE_MODE"] = "cpu"+ os.environ["MINERU_TABLE_DEVICE"] = "cpu"+ os.environ["MINERU_PROFILE_STAGES"] = "1"+ import psutil+ import torch+ from loguru import logger++ from mineru.config import config+ from mineru.model.runtime.cpu_threads import initialize_torch_threads+ from mineru.parser import parse+ from mineru.parser.writer import FileBasedDataWriter++ config.model.small_backend = "torch"+ config.llm_aided.features.title_leveling = False+ config.llm_aided.features.cross_page_table_cell_merge = False+ initialize_torch_threads()+ source_before = det_source_fingerprint()+ torch.backends.nnpack.set_flags(args.policy == "on")+ target = args.output / args.policy+ target.mkdir(parents=True, exist_ok=False)+ current: dict[str, Any] | None = None+ process = psutil.Process()+ stopped = threading.Event()++ def record_stage(message: Any) -> None:+ """收集生产 stage_timer 日志,保留阶段嵌套关系对应的原始完成时间。"""+ match = re.search(r"MinerU stage: name=([^,]+), elapsed_s=([0-9.]+)", message.record["message"])+ if match is not None and current is not None:+ current["stage_events"].append({"name": match[1], "seconds": float(match[2]), "finished_at": time.perf_counter()})++ def sample_memory() -> None:+ """半秒采集本进程 RSS/footprint,采样峰不代表算子内部瞬时峰值。"""+ with (target / "memory-samples.jsonl").open("w", encoding="utf-8") as stream:+ while not stopped.wait(0.5):+ value = {"time": time.time(), "rss": process.memory_info().rss, **mac_memory_diagnostics()}+ if current is not None:+ value["document"] = current["document"]+ stream.write(json.dumps(value) + "\n")+ stream.flush()++ sink = logger.add(record_stage, level="INFO", format="{message}")+ monitor = threading.Thread(target=sample_memory, daemon=True)+ monitor.start()+ records = []+ weights: dict[str, str] = {}+ try:+ for path in DOCUMENTS:+ current = {"document": path.stem, "stage_events": []}+ started = time.perf_counter()+ result = parse(path, tier="basic", ocr_mode="ocr", image_analysis=False, page_range="all")+ current["parse_seconds"] = time.perf_counter() - started+ current["pages"] = len(result.pages)+ current["metadata"] = result.middle_json.extensions["mineru"]+ assert current["pages"] == (13 if path.stem == "demo1" else 6)+ assert current["metadata"] == {"tier": "basic", "parse_mode": "ocr"}+ stages: Counter[str] = Counter()+ for event in current["stage_events"]:+ stages[event["name"]] += event["seconds"]+ current["stages"] = dict(stages)+ for stage in ("pdf.layout", "pdf.formulas", "pdf.ocr_detection", "pdf.ocr_recognition"):+ assert stages[stage] > 0, f"{path.stem} 未实际执行 {stage}"+ current["models"] = inspect_models()+ current["memory_after_parse"] = {"rss": process.memory_info().rss, **mac_memory_diagnostics()}+ export_started = time.perf_counter()+ result.save(FileBasedDataWriter(str(target / path.stem)))+ current["export_seconds_excluded"] = time.perf_counter() - export_started+ for model in current["models"]:+ if not model["weight"]:+ continue+ weight_path = Path(model["weight"])+ files = list(weight_path.glob("*.safetensors")) if weight_path.is_dir() else [weight_path]+ for weight_file in files:+ if str(weight_file) not in weights:+ weights[str(weight_file)] = sha256(weight_file)+ records.append(current)+ write_json(target / "results.json", records)+ print(f"DONE {args.policy} {path.stem} parse={current['parse_seconds']:.3f}s stages={dict(stages)}", flush=True)+ current = None+ del result+ finally:+ stopped.set()+ monitor.join()+ logger.remove(sink)+ write_json(+ target / "environment.json",+ {+ "pid": os.getpid(),+ "policy": args.policy,+ "nnpack_enabled": torch._C._get_nnpack_enabled(),+ "device": os.environ["MINERU_DEVICE_MODE"],+ "table_device": os.environ["MINERU_TABLE_DEVICE"],+ "small_backend": config.model.small_backend,+ "torch": torch.__version__,+ "torch_commit": torch.version.git_version,+ "python": platform.python_version(),+ "platform": platform.platform(),+ "threads": torch.get_num_threads(),+ "interop_threads": torch.get_num_interop_threads(),+ "documents_sha256": {str(path.relative_to(ROOT)): sha256(path) for path in DOCUMENTS},+ "weights_sha256": weights,+ "script_sha256": sha256(Path(__file__)),+ "det_source_before": source_before,+ "det_source_after": det_source_fingerprint(),+ "crop_fix_sha256": {+ name: sha256(ROOT / name)+ for name in (+ "mineru/model/ocr/results.py",+ "mineru/model/ocr/image.py",+ "mineru/model/ocr/pytorch_paddle.py",+ )+ },+ },+ )+++def summarize(args: argparse.Namespace) -> None:+ """逐项比较完整结果,按两份 PDF 合计中位数汇总各阶段,不把嵌套初始化重复相加。"""+ groups: dict[str, dict[str, Any]] = {}+ fingerprints = set()+ for round_name in ("round-1", "round-2"):+ groups[round_name] = {}+ for policy in ("on", "off"):+ directory = args.output / round_name / policy+ rows = json.loads((directory / "results.json").read_text())+ env = json.loads((directory / "environment.json").read_text())+ assert env["nnpack_enabled"] == (policy == "on")+ assert env["device"] == env["table_device"] == "cpu" and env["small_backend"] == "torch"+ assert env["det_source_before"] == env["det_source_after"]+ fingerprints.add(+ json.dumps(+ {key: value for key, value in env.items() if key not in {"pid", "policy", "nnpack_enabled"}}, sort_keys=True+ )+ )+ stage_totals: Counter[str] = Counter()+ for row in rows:+ stage_totals.update(row["stages"])+ groups[round_name][policy] = {+ "rows": rows,+ "parse_seconds": sum(row["parse_seconds"] for row in rows),+ "stages": dict(stage_totals),+ "environment": env,+ }+ assert len(fingerprints) == 1, "CPU 配置、线程、权重或代码不一致"+ comparisons = []+ comparison_root = args.output / "comparisons"+ comparison_root.mkdir(exist_ok=True)+ baseline = args.output / "round-1" / "on"+ for round_name in groups:+ for policy in groups[round_name]:+ for path in DOCUMENTS:+ left, right = baseline / path.stem, args.output / round_name / policy / path.stem+ target = comparison_root / f"{round_name}-{policy}-{path.stem}"+ target.mkdir(exist_ok=True)+ result = {"round": round_name, "policy": policy, "document": path.stem}+ for name in ("middle_json.json", "model_output.json", "structured_content.json"):+ delta = differences(json.loads((left / name).read_text()), json.loads((right / name).read_text()))+ write_json(target / (name + ".differences.json"), delta)+ result[name] = {"exact": not delta, "changed_leaves": len(delta)}+ result["markdown_exact"] = (left / "markdown.md").read_bytes() == (right / "markdown.md").read_bytes()+ if not result["markdown_exact"]:+ import difflib++ (target / "markdown.diff").write_text(+ "".join(+ difflib.unified_diff(+ (left / "markdown.md").read_text().splitlines(True),+ (right / "markdown.md").read_text().splitlines(True),+ )+ )+ )+ comparisons.append(result)+ medians = {+ policy: {+ "parse_seconds": statistics.median(groups[name][policy]["parse_seconds"] for name in groups),+ "stages": {+ stage: statistics.median(groups[name][policy]["stages"].get(stage, 0) for name in groups) for stage in STAGES+ },+ }+ for policy in ("on", "off")+ }+ tables = [+ f"| SDK parse 合计 | {medians['on']['parse_seconds']:.3f} | {medians['off']['parse_seconds']:.3f} | "+ f"{1 - medians['off']['parse_seconds'] / medians['on']['parse_seconds']:.1%} |"+ ]+ for stage, label in STAGES.items():+ on, off = medians["on"]["stages"][stage], medians["off"]["stages"][stage]+ tables.append(+ f"| {label} | {on:.3f} | {off:.3f} | {1 - off / on:.1%} |" if on else f"| {label} | {on:.3f} | {off:.3f} | — |"+ )+ per_document = []+ for name, group in groups.items():+ for policy, value in group.items():+ for row in value["rows"]:+ s = row["stages"]+ per_document.append(+ f"| {name} | {policy} | {row['document']} | {row['parse_seconds']:.3f} | {s['pdf.layout']:.3f} | "+ f"{s['pdf.formulas']:.3f} | {s['pdf.ocr_detection']:.3f} | {s['pdf.ocr_recognition']:.3f} |"+ )+ write_json(args.output / "summary.json", {"groups": groups, "medians": medians, "comparisons": comparisons})+ env = groups["round-1"]["on"]["environment"]+ report = f"""# CPU Basic/OCR:demo1+demo2,NNPACK 开关++demo1 13 页,demo2 6 页,每个独立进程按此顺序各解析一次。两轮策略顺序 on→off、off→on,共 76 页。+通过公开 `mineru.parser.parse()`:tier=basic、ocr_mode=ocr、image_analysis=False、整本。+强制 MINERU_DEVICE_MODE=cpu、MINERU_TABLE_DEVICE=cpu、small_backend=torch;核对 Layout/MFR/det/rec 全部参数为 CPU FP32。+使用 .venv4,Python {env["python"]}、PyTorch {env["torch"]},生产线程 {env["threads"]}/{env["interop_threads"]}。+没有前向预热、实验融合或 N/H/W 拆分补齐;保留生产内部已有的优化。每本文档执行真实生产清理。+两种策略都使用相同的零尺寸 OCR 裁图修复:先执行既有窄框过滤,并丢弃无法生成至少一像素裁图的退化框。+初次未修复基线在 demo2 崩溃,失败现场单独保留,不混入本轮正式统计。+首份 demo1 含模型冷加载,demo2 复用模型;不混为全热态或单模型纯 forward 速度。+使用生产 MINERU_PROFILE_STAGES 日志;MFR 阶段含首次 MFR 初始化,model.initialize 嵌套于准备/MFR,不能重复相加。+表格与公式编号还会执行 OCR,正文 det/rec 列不包括这部分;对应时间保留单独阶段。+SDK parse 包括读取、模型初始化、推理、PDF 清理和确定性后处理;结果导出、权重校验排除在计时之外。++| 阶段(两份 PDF 合计,两轮中位数) | NNPACK 开 秒 | NNPACK 关 秒 | 耗时降低 |+| --- | ---: | ---: | ---: |+{chr(10).join(tables)}++| 轮次 | NNPACK | 文档 | parse 秒 | Layout 秒 | MFR 秒 | 正文 det 秒 | 正文 rec 秒 |+| --- | --- | --- | ---: | ---: | ---: | ---: | ---: |+{chr(10).join(per_document)}++输出逐项比较完整 Middle/Model/Structured JSON 与 Markdown,未删除源元数据或对数值施加容差;完整差异见 comparisons/。+一致性结果:`{json.dumps(comparisons, ensure_ascii=False)}`。+环境、权重与输入摘要在各进程 environment.json;生产阶段事件与内存采样单独保留。+NNPACK N≥16 属于 PyTorch 启发式,并非保证本机快:此前固定 N=16 的原 batch 在关闭后转到普通卷积路径,耗时明显降低。+FFT/Winograd 变换、打包、线程调度与硬件适配可能影响实际收益;本实验不能单独裁定其中哪一项占主导。+不修改生产配置、公开接口或权重;仅适用于这两份文档的本机 CPU Torch Basic/OCR。++```bash+.venv4/bin/python tools/benchmark_basic_nnpack.py experiment --output NEW_OUTPUT+.venv4/bin/python tools/benchmark_basic_nnpack.py summarize --output {args.output}+```+"""+ (args.output / "report.md").write_text(report)+ print(json.dumps({"medians": medians, "comparisons": comparisons}, ensure_ascii=False), flush=True)+++def experiment(args: argparse.Namespace) -> None:+ """串行执行两轮反序的独立进程对照,并保存实际使用脚本与完整结果。"""+ args.output.mkdir(parents=True, exist_ok=False)+ shutil.copy2(Path(__file__), args.output / "executed-script.py")+ for name, policies in (("round-1", ("on", "off")), ("round-2", ("off", "on"))):+ directory = args.output / name+ directory.mkdir()+ for policy in policies:+ with (directory / f"{policy}.log").open("w") as stream:+ subprocess.run(+ [sys.executable, str(Path(__file__).resolve()), "worker", "--policy", policy, "--output", str(directory)],+ cwd=ROOT,+ stdout=stream,+ stderr=subprocess.STDOUT,+ check=True,+ )+ print(f"FINISHED {name} {policy}", flush=True)+ summarize(args)+++def main() -> None:+ """提供简单的完整 Basic/OCR 对照及复测入口。"""+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("command", choices=("experiment", "worker", "summarize"))+ parser.add_argument("--policy", choices=("on", "off"), default="on")+ parser.add_argument("--output", type=Path, required=True)+ args = parser.parse_args()+ args.output = args.output.resolve()+ {"experiment": experiment, "worker": worker, "summarize": summarize}[args.command](args)+++if __name__ == "__main__":+ main()diff --git a/tools/benchmark_det_corpus.py b/tools/benchmark_det_corpus.pynew file mode 100644index 00000000..ab39c159--- /dev/null+++ b/tools/benchmark_det_corpus.py@@ -0,0 +1,950 @@+"""冻结生产 det 裁剪并独立重放 A/B/C 或融合 D/E,后续测速无需完整解析。"""++from __future__ import annotations++import argparse+import gc+import hashlib+import json+import os+import platform+import shutil+import subprocess+import sys+import time+from collections import Counter+from pathlib import Path+from typing import Any++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT))++from benchmark_mps_det_service import SAMPLES, write_json # noqa: E402+from det_cpu_microbatch import CPU_MICROBATCH_STRATEGIES, project_cpu_microbatch # noqa: E402+from det_shape_buckets import SHAPE_STRATEGIES, project_shape # noqa: E402++DEFAULT_CORPUS = ROOT / "tmp/pdfs/issue5632-det-corpus-20261012"+DEFAULT_RESULTS = ROOT / "tmp/pdfs/issue5632-det-only-20261012"+CAPTURE = ROOT / "tmp/pdfs/issue5632-cross-document-run2-20261012/A"+SINGLE_POLICIES = {"J", "K"}+CPU_POLICIES = {"A", "L", "M", "N", "V", *CPU_MICROBATCH_STRATEGIES}+CPU_SPLIT_POLICIES = {"M", "N"}+FUSION_REPLAY_POLICIES = {"F": "E", "G": "E", "H": "E", "I": "E", "K": "E", "L": "E", "N": "E"}+++def project_replay_shape(shape: list[int], policy: str) -> dict[str, Any]:+ """单图入口逐张运行 N=1,其他实验策略保留原来的形状投影与行为。"""+ if policy in CPU_MICROBATCH_STRATEGIES:+ return project_cpu_microbatch(shape, policy)+ projection = project_shape(shape, "F" if policy in SINGLE_POLICIES | CPU_SPLIT_POLICIES else policy)+ if policy in SINGLE_POLICIES:+ projection["entrypoint"] = "TextDetector.__call__"+ return projection+++def det_source_fingerprint() -> str:+ """对本实验直接使用的普通 det 源码树取摘要,区分无关提交号变化与实际推理代码变化。"""+ paths = [ROOT / "mineru/model/registry.py"]+ for directory in (ROOT / "mineru/model/_internal/pytorchocr", ROOT / "mineru/model/runtime"):+ paths.extend(path for path in directory.rglob("*") if path.suffix in {".py", ".yaml", ".yml"})+ digest = hashlib.sha256()+ for path in sorted(paths):+ digest.update(str(path.relative_to(ROOT)).encode())+ digest.update(path.read_bytes())+ return digest.hexdigest()+++def read_json(path: Path) -> Any:+ """读取已冻结的输入和原始结果。"""+ return json.loads(path.read_text(encoding="utf-8"))+++def mac_memory_diagnostics() -> dict[str, Any]:+ """读取本进程 TASK_VM_INFO,补充 RSS 未计入的压缩页和物理 footprint。"""+ import ctypes+ import psutil++ result: dict[str, Any] = {+ "system_available": psutil.virtual_memory().available,+ "system_swap_used": psutil.swap_memory().used,+ }+ if sys.platform != "darwin":+ return result+ library = ctypes.CDLL(None)+ task = ctypes.c_uint.in_dll(library, "mach_task_self_").value+ values = (ctypes.c_uint64 * 128)()+ count = ctypes.c_uint(ctypes.sizeof(values) // ctypes.sizeof(ctypes.c_uint))+ library.task_info.argtypes = [ctypes.c_uint, ctypes.c_int, ctypes.c_void_p, ctypes.POINTER(ctypes.c_uint)]+ library.task_info.restype = ctypes.c_int+ code = library.task_info(task, 22, values, ctypes.byref(count))+ # 本机 SDK mach/task_info.h 中 compressed、phys_footprint、ledger_phys_footprint_peak 的偏移。+ if code == 0 and count.value >= 44:+ result.update({"compressed": values[15], "phys_footprint": values[18], "phys_footprint_peak": values[21]})+ else:+ result["task_info_error"] = code+ return result+++def fuse_det_eval(net: Any, policy: str) -> dict[str, Any]:+ """仅在实验模型的 CPU/eval 状态融合明确的 Conv-BN 对,保留生产模型实现和权重文件。"""+ import torch+ from torch.nn.utils import fuse_conv_bn_eval+ from mineru.model._internal.pytorchocr.modeling.backbones.rec_lcnetv4 import PPLCNetV4ConvLayer+ from mineru.model._internal.pytorchocr.modeling.heads.det_db_head import PPOCRV6DBConvBatchnormLayer++ before = sum(isinstance(module, torch.nn.BatchNorm2d) for module in net.modules())+ report: dict[str, Any] = {"before_bn": before, "after_bn": before, "pairs": [], "seconds": 0.0}+ if policy not in {"D", "E"}:+ return report+ if before != 36 or net.training or any(parameter.device.type != "cpu" for parameter in net.parameters()):+ raise ValueError("融合要求 CPU/eval Tiny-det,且现有重参数化之后恰好剩余 36 个 BN")+ backbone = [(name, module) for name, module in net.named_modules() if isinstance(module, PPLCNetV4ConvLayer)]+ head = [(name, module) for name, module in net.named_modules() if isinstance(module, PPOCRV6DBConvBatchnormLayer)]+ if len(backbone) != 34 or len(head) != 2:+ raise ValueError(f"融合结构与约定不符:backbone={len(backbone)}, head={len(head)}")+ pairs = [(name, module, "normalization") for name, module in backbone]+ if policy == "E":+ pairs += [(name, module, "norm") for name, module in head]+ started = time.perf_counter()+ for name, module, bn_attribute in pairs:+ convolution = module.convolution+ normalization = getattr(module, bn_attribute)+ if not isinstance(convolution, (torch.nn.Conv2d, torch.nn.ConvTranspose2d)):+ raise TypeError(f"{name} 不是明确支持的卷积类型")+ if not isinstance(normalization, torch.nn.BatchNorm2d) or convolution.training or normalization.training:+ raise ValueError(f"{name} 的 Conv/BN 不满足 eval 融合条件")+ if normalization.running_mean is None or normalization.running_var is None:+ raise ValueError(f"{name} 缺少 BN running buffers")+ transpose = isinstance(convolution, torch.nn.ConvTranspose2d)+ module.convolution = fuse_conv_bn_eval(convolution, normalization, transpose=transpose)+ setattr(module, bn_attribute, torch.nn.Identity())+ report["pairs"].append(+ {"module": name, "bn_attribute": bn_attribute, "convolution": type(convolution).__name__, "transpose": transpose}+ )+ net.eval()+ report["seconds"] = time.perf_counter() - started+ report["after_bn"] = sum(isinstance(module, torch.nn.BatchNorm2d) for module in net.modules())+ expected = 2 if policy == "D" else 0+ if report["after_bn"] != expected:+ raise ValueError(f"融合之后应剩余 {expected} 个 BN,实际 {report['after_bn']}")+ return report+++def selected_calls(document: dict[str, Any], args: argparse.Namespace) -> list[tuple[int, dict[str, Any]]]:+ """保留原调用编号,支持普通顺序重放和仅诊断指定调用集合。"""+ if args.call_indices:+ indices = [int(index) for index in args.call_indices.split(",")]+ if len(indices) != len(set(indices)) or any(index < 0 or index >= len(document["calls"]) for index in indices):+ raise ValueError("call-indices 包含重复或越界调用")+ else:+ indices = list(range(args.start_call, len(document["calls"])))+ if args.limit_calls:+ indices = indices[: args.limit_calls]+ if not indices:+ raise ValueError(f"{document['name']} 的调用范围为空")+ return [(index, document["calls"][index]) for index in indices]+++def freeze(args: argparse.Namespace) -> None:+ """复制三份文档进入生产 det 的全部 PNG、参数、原 batch 和参考检测框。"""+ import numpy as np+ from PIL import Image+ from docvortex.document.pdf import PDFDocument++ if (args.corpus / "manifest.json").exists():+ raise FileExistsError("已有冻结语料,请使用新目录,避免覆盖旧输入")+ (args.corpus / "images").mkdir(parents=True, exist_ok=True)+ documents = []+ verified: set[str] = set()+ for index, (sample, source) in enumerate(SAMPLES.items()):+ label = f"{index + 1:02d}-{sample}"+ captured = args.capture / label+ job = read_json(captured / "job.json")+ assert job["status"] == "completed", f"源文档取样未完整完成:{label}"+ calls = [json.loads(line) for line in (captured / "det-trace.jsonl").read_text().splitlines()]+ for call in calls:+ for item in call["items"]:+ crop = item["crop"]+ if crop in verified:+ continue+ source_png = args.capture / "crops" / f"{crop}.png"+ target_png = args.corpus / "images" / f"{crop}.png"+ shutil.copy2(source_png, target_png)+ with Image.open(target_png) as image:+ array = np.array(image.convert("RGB"))[:, :, ::-1].copy()+ assert list(array.shape) == item["original_shape"]+ actual = hashlib.sha256(str(array.shape).encode() + array.tobytes()).hexdigest()+ assert actual == crop, f"PNG 不能恢复原始 BGR 输入:{crop}"+ verified.add(crop)+ directory = args.corpus / sample+ directory.mkdir(exist_ok=True)+ (directory / "inputs").mkdir(exist_ok=True)+ input_index = 0+ with (directory / "inputs.jsonl").open("w", encoding="utf-8") as index_file:+ for call_index, call in enumerate(calls):+ for item_index, item in enumerate(call["items"]):+ link = directory / "inputs" / f"{input_index:05d}.png"+ link.symlink_to(Path("../../images") / f"{item['crop']}.png")+ index_file.write(+ json.dumps(+ {+ "document": sample,+ "input_index": input_index,+ "call_index": call_index,+ "item_index": item_index,+ "png": str(link.relative_to(args.corpus)),+ "shape": call["shape"],+ "box_thresh": call["box_thresh"],+ "unclip_ratio": call["unclip_ratio"],+ "reference_box_count": len(item["boxes"] or []),+ },+ ensure_ascii=False,+ )+ + "\n"+ )+ input_index += 1+ shutil.copy2(captured / "bundle/model_output.json", directory / "model_output.json")+ shutil.copy2(captured / "middle_json.json", directory / "middle_json.json")+ with PDFDocument(str(source)) as document:+ pages = document.page_count+ documents.append(+ {+ "name": sample,+ "source_pdf": str(source),+ "source_sha256": hashlib.sha256(source.read_bytes()).hexdigest(),+ "pages": pages,+ "calls": calls,+ "crops": sum(len(call["items"]) for call in calls),+ "source_model_output": f"{sample}/model_output.json",+ "source_middle_json": f"{sample}/middle_json.json",+ }+ )+ write_json(+ args.corpus / "manifest.json",+ {+ "version": 1,+ "capture": str(args.capture),+ "capture_route": "V1 API / Basic / forced OCR / all pages",+ "documents": documents,+ "unique_images": len(verified),+ "parameters": {+ "det_algorithm": "DB",+ "det_limit_side_len": 960,+ "det_limit_type": "max",+ "det_max_side_limit": 4000,+ "det_db_thresh": 0.3,+ "det_box_type": "quad",+ "det_db_score_mode": "fast",+ "use_dilation": False,+ "lang": "ch",+ },+ "parameter_source": "box_thresh/unclip_ratio recorded per call; other fields are unchanged production defaults",+ "git_head": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip(),+ },+ )+ (args.corpus / "README.md").write_text(+ "# 可复用 det 输入\n\n"+ "images/ 保存无损 PNG,manifest.json 保存原始 batch、NCHW、参数和参考框。\n"+ "每份文档 inputs/ 按 det 输入顺序编号,inputs.jsonl 映射到原调用;编号不是 PDF 页码或语义块编号。\n"+ "model_output.json 和 middle_json.json 保留源解析上下文。\n\n"+ "快速烟测:\n\n"+ f"`.venv4/bin/python tools/benchmark_det_corpus.py run --corpus {args.corpus} "+ "--output NEW_OUTPUT --limit-calls 12`\n\n"+ "定点调试追加 `--documents python --start-call 50 --limit-calls 1`;全量去掉 limit-calls。\n"+ "完成后用相同 corpus/output 执行 summarize;每轮请使用新 output 保留证据。\n",+ encoding="utf-8",+ )+ print(+ f"FROZEN documents={len(documents)} crops={sum(doc['crops'] for doc in documents)} unique_png={len(verified)}",+ flush=True,+ )+++def worker(args: argparse.Namespace) -> None:+ """独立进程仅加载 det,重放冻结调用,并在文档之间执行约定清理。"""+ import numpy as np+ import psutil+ import torch+ from PIL import Image+ from mineru.model._internal.pytorchocr.infer.predict_det import TextDetector+ from mineru.model._internal.pytorchocr.infer.pytorchocr_utility import init_args+ from mineru.model.registry import MINERU_4_MODELS_TORCH+ from mineru.model.runtime.cpu_threads import initialize_torch_threads+ from mineru.model.runtime.memory import clean_memory++ initialize_torch_threads()+ nnpack_enabled_before = torch._C._get_nnpack_enabled()+ # 实验对照显式保留旧 NNPACK 开启基线,避免生产默认变化使后续重测失去对照。+ torch.backends.nnpack.set_flags(args.policy != "V")+ nnpack_enabled = torch._C._get_nnpack_enabled()+ source_before = det_source_fingerprint()+ device = "cpu" if args.policy in CPU_POLICIES else "mps"+ output = args.output / args.policy+ output.mkdir(parents=True, exist_ok=True)+ manifest = read_json(args.corpus / "manifest.json")+ documents = {doc["name"]: doc for doc in manifest["documents"]}+ process = psutil.Process()+ totals: Counter[str] = Counter()+ shapes: Counter[tuple[int, ...]] = Counter()+ seen_shapes: set[tuple[int, ...]] = set()+ last_shape: tuple[int, ...] | None = None+ network_shapes: list[list[int]] = []++ def memory() -> dict[str, int]:+ """在同步边界记录 CPU RSS 和两类 MPS 内存,输入图像不跨文档保留。"""+ torch.mps.synchronize()+ return {+ "rss": process.memory_info().rss,+ "mps_allocated": torch.mps.current_allocated_memory(),+ "mps_driver": torch.mps.driver_allocated_memory(),+ }++ class MeasuredDetector(TextDetector):+ """计时生产前处理和网络执行,不保存或变换额外输入。"""++ def __init__(self, parameters: Any) -> None:+ """保留生产权重、reparam 和 FP32,只迁移本实验实例的设备。"""+ loading_started = time.perf_counter()+ super().__init__(parameters)+ loading_seconds = time.perf_counter() - loading_started+ self.fusion = fuse_det_eval(self.net, FUSION_REPLAY_POLICIES.get(args.policy, args.policy))+ transfer_started = time.perf_counter()+ self.device = device+ self._apply_inference_precision(device, precision_override="fp32")+ torch.mps.synchronize()+ self.loading_seconds = loading_seconds + time.perf_counter() - transfer_started+ self.started = 0.0+ self.last_maps = None+ self.capture_maps = args.save_maps+ self.bucket_padding_seconds = 0.0+ self.net.register_forward_pre_hook(self.before_forward)+ self.net.register_forward_hook(self.after_forward)++ def _preprocess_det_image(self, img: Any) -> Any:+ """记录真实 resize、归一化和 CHW 转换耗时。"""+ started = time.perf_counter()+ result = super()._preprocess_det_image(img)+ totals["preprocess"] += time.perf_counter() - started+ return result++ def _batch_process_preprocessed(self, batch_items: list[Any]) -> tuple[list[Any], float]:+ """仅在形状实验及 CPU N 拆分实验中替换网络批次,其他策略继续调用原实现。"""+ if args.policy in CPU_MICROBATCH_STRATEGIES and batch_items:+ shape = [len(batch_items), *batch_items[0][1].shape]+ if project_cpu_microbatch(shape, args.policy)["split_required"]:+ from det_cpu_microbatch import process_cpu_microbatch++ return process_cpu_microbatch(self, batch_items, args.policy)+ return super()._batch_process_preprocessed(batch_items)+ if args.policy in SHAPE_STRATEGIES or args.policy in CPU_SPLIT_POLICIES:+ from det_shape_buckets import process_bucketed_batch++ bucket_policy = "F" if args.policy in CPU_SPLIT_POLICIES else args.policy+ return process_bucketed_batch(self, batch_items, bucket_policy)+ return super()._batch_process_preprocessed(batch_items)++ def before_forward(self, module: Any, inputs: Any) -> None:+ """记录完整 NCHW 形状;这里只统计复用机会,不声称是底层命中率。"""+ nonlocal last_shape+ if device == "mps":+ torch.mps.synchronize()+ self.started = time.perf_counter()+ last_shape = tuple(inputs[0].shape)+ network_shapes.append(list(last_shape))+ totals["new_shapes" if last_shape not in seen_shapes else "reused_shapes"] += 1+ seen_shapes.add(last_shape)+ shapes[last_shape] += 1++ def after_forward(self, module: Any, inputs: Any, outputs: Any) -> None:+ """同步实际 GPU 执行完成,累计纯模型 forward 时间。"""+ if device == "mps":+ torch.mps.synchronize()+ totals["forward"] += time.perf_counter() - self.started++ def _build_det_preds(self, outputs: Any) -> Any:+ """记录结果转 FP32 并回传 CPU 的耗时。"""+ started = time.perf_counter()+ result = super()._build_det_preds(outputs)+ totals["output_transfer"] += time.perf_counter() - started+ if args.save_maps:+ self.last_maps = result["maps"]+ return result++ def _postprocess_det_batch(self, preds: Any, batch_shapes: Any, ori_shapes: Any) -> Any:+ """记录 DB 后处理、裁剪和检测框过滤的耗时。"""+ started = time.perf_counter()+ result = super()._postprocess_det_batch(preds, batch_shapes, ori_shapes)+ totals["postprocess"] += time.perf_counter() - started+ return result++ model_path = MINERU_4_MODELS_TORCH.pytorch_paddle.path("ch_PP-OCRv6_tiny_det_infer.safetensors").ensure()+ models: dict[tuple[float, float], MeasuredDetector] = {}+ model_loads = []+ records = []+ sequence = args.documents.split(",") * args.cycles+ for position, name in enumerate(sequence):+ document = documents[name]+ calls = selected_calls(document, args)+ totals.clear()+ shapes.clear()+ before = memory()+ diagnostics_before = mac_memory_diagnostics()+ peak = dict(before)+ peak_diagnostics = {key: diagnostics_before[key] for key in ("phys_footprint", "compressed")}+ results = []+ call_metrics = []+ differences = []+ seconds = 0.0+ input_seconds = 0.0+ for index, (call_index, call) in enumerate(calls):+ profile = (call["box_thresh"], call["unclip_ratio"])+ if profile not in models:+ parameters = init_args().parse_args([])+ for key, value in manifest["parameters"].items():+ setattr(parameters, key, value)+ parameters.device = "cpu"+ parameters.det_model_path = str(model_path)+ parameters.det_db_box_thresh, parameters.det_db_unclip_ratio = profile+ started = time.perf_counter()+ models[profile] = MeasuredDetector(parameters)+ torch.mps.synchronize()+ model_loads.append(+ {+ "profile": list(profile),+ "seconds": time.perf_counter() - started,+ "loading_seconds": models[profile].loading_seconds,+ "fusion": models[profile].fusion,+ }+ )+ started = time.perf_counter()+ images = []+ for item in call["items"]:+ with Image.open(args.corpus / "images" / f"{item['crop']}.png") as image:+ images.append(np.array(image.convert("RGB"))[:, :, ::-1].copy())+ input_seconds += time.perf_counter() - started+ detector = models[profile]+ stages_before = dict(totals)+ network_shapes.clear()+ padding_before = detector.bucket_padding_seconds+ started = time.perf_counter()+ if args.policy in SINGLE_POLICIES:+ detected = []+ single_maps = []+ for input_image in images:+ detected.append(detector(input_image))+ if args.save_maps:+ single_maps.append(detector.last_maps)+ if args.save_maps:+ detector.last_maps = np.concatenate(single_maps, axis=0)+ else:+ detected = detector.batch_predict(images, max_batch_size=call["shape"][0])+ if device == "mps":+ torch.mps.synchronize()+ elapsed = time.perf_counter() - started+ seconds += elapsed+ call_metrics.append(+ {+ "call_index": call_index,+ "shape": call["shape"],+ "profile": list(profile),+ "network_shapes": list(network_shapes),+ "shape_projection": project_replay_shape(call["shape"], args.policy),+ "bucket_padding_seconds": detector.bucket_padding_seconds - padding_before,+ "seconds": elapsed,+ "stages": {+ key: totals[key] - stages_before.get(key, 0)+ for key in ("preprocess", "forward", "output_transfer", "postprocess", "new_shapes", "reused_shapes")+ },+ }+ )+ assert network_shapes == project_replay_shape(call["shape"], args.policy)["network_shapes"], (+ "实际网络 NCHW 与策略投影不同"+ )+ assert len(detected) == len(call["items"])+ for item_index, (item, (boxes, _)) in enumerate(zip(call["items"], detected)):+ points = boxes.tolist() if hasattr(boxes, "tolist") else boxes+ results.append(+ {+ "crop": item["crop"],+ "profile": list(profile),+ "call_index": call_index,+ "item_index": item_index,+ "boxes": points,+ "reference_equal": points == item["boxes"],+ }+ )+ if points != item["boxes"]:+ difference = {+ "policy": args.policy,+ "document": name,+ "call_index": call_index,+ "item_index": item_index,+ "crop": item["crop"],+ "shape": call["shape"],+ "profile": list(profile),+ "reference": item["boxes"],+ "actual": points,+ }+ differences.append(difference)+ review = output / "review"+ review.mkdir(exist_ok=True)+ prefix = f"{position + 1:02d}-{name}-call{call_index:04d}-item{item_index:03d}"+ shutil.copy2(args.corpus / "images" / f"{item['crop']}.png", review / f"{prefix}-source.png")+ render_crop_comparison(args.corpus, review / f"{prefix}-boxes.png", item["crop"], item["boxes"], points)+ if args.save_maps:+ (output / "maps").mkdir(exist_ok=True)+ np.savez_compressed(+ output / "maps" / f"{position + 1:02d}-{name}-call{call_index:04d}.npz", maps=detector.last_maps+ )+ detector.last_maps = None+ del images, detected+ snapshot = memory()+ diagnostics = mac_memory_diagnostics()+ call_metrics[-1]["memory"] = snapshot+ call_metrics[-1]["memory_diagnostics"] = diagnostics+ for key in peak:+ peak[key] = max(peak[key], snapshot[key])+ for key in peak_diagnostics:+ peak_diagnostics[key] = max(peak_diagnostics[key], diagnostics[key])+ if (index + 1) % 50 == 0:+ print(+ f"PROGRESS {args.policy} {position + 1}-{name} calls={index + 1}/{len(calls)} det={seconds:.2f}s",+ flush=True,+ )+ memory_before_cleanup = memory()+ diagnostics_before_cleanup = mac_memory_diagnostics()+ cleanup_started = time.perf_counter()+ if args.policy == "C":+ gc.collect()+ else:+ # A 也沿用宿主 MPS 的原回收边界,CPU 模型参数继续复用。+ clean_memory("mps")+ if device == "mps":+ seen_shapes.clear()+ cleanup_seconds = time.perf_counter() - cleanup_started+ diagnostics_after = mac_memory_diagnostics()+ for key in peak_diagnostics:+ peak_diagnostics[key] = max(peak_diagnostics[key], diagnostics_before_cleanup[key], diagnostics_after[key])+ label = f"{position + 1:02d}-{name}"+ record = {+ "label": label,+ "document": name,+ "cycle": position // len(args.documents.split(",")) + 1,+ "seconds": seconds,+ "crops": len(results),+ "calls": len(calls),+ "stages": dict(totals),+ "input_seconds_excluded": input_seconds,+ "cleanup_seconds": cleanup_seconds,+ "memory_before": before,+ "memory_before_cleanup": memory_before_cleanup,+ "memory_after": memory(),+ "memory_diagnostics_before": diagnostics_before,+ "memory_diagnostics_before_cleanup": diagnostics_before_cleanup,+ "memory_diagnostics_after": diagnostics_after,+ "peak_memory": peak,+ "peak_memory_diagnostics": peak_diagnostics,+ "call_metrics": call_metrics,+ "differences": differences,+ "models": [+ {+ "profile": list(profile),+ "id": id(model),+ "net_id": id(model.net),+ "device": model.device,+ "dtype": str(model.ocr_inference_dtype),+ "fusion": model.fusion,+ }+ for profile, model in models.items()+ ],+ "reference_exact_crops": sum(result["reference_equal"] for result in results),+ "shape_counts": [{"shape": list(shape), "calls": count} for shape, count in shapes.items()],+ }+ records.append(record)+ write_json(output / f"{label}-boxes.json", results)+ write_json(output / "results.json", records)+ print(+ f"DONE {args.policy} {label} det={seconds:.3f}s crops={len(results)} "+ f"reference_exact={record['reference_exact_crops']} "+ f"memory={record['memory_after']}",+ flush=True,+ )+ if args.policy == "C" and position + 1 == len(args.documents.split(",")) * args.cycles and args.cycles >= 2:+ first = records[len(args.documents.split(",")) - 1]["memory_after"]+ second = record["memory_after"]+ if any(second[key] - first[key] > max(256 * 1024**2, first[key] * 0.1) for key in first):+ sequence.extend(args.documents.split(","))+ print("EXTEND C: 同进程追加一遍输入,验证内存增长趋势", flush=True)+ shutdown_before = mac_memory_diagnostics()+ shutdown_started = time.perf_counter()+ del detector+ models.clear()+ gc.collect()+ clean_memory("mps")+ shutdown_seconds = time.perf_counter() - shutdown_started+ write_json(+ output / "environment.json",+ {+ "pid": os.getpid(),+ "policy": args.policy,+ "python": platform.python_version(),+ "torch": torch.__version__,+ "torch_commit": torch.version.git_version,+ "platform": platform.platform(),+ "cpu": subprocess.check_output(["sysctl", "-n", "machdep.cpu.brand_string"], text=True).strip(),+ "threads": torch.get_num_threads(),+ "interop_threads": torch.get_num_interop_threads(),+ "nnpack_enabled_before": nnpack_enabled_before,+ "nnpack_enabled": nnpack_enabled,+ "nnpack_enabled_at_exit": torch._C._get_nnpack_enabled(),+ "model_sha256": hashlib.sha256(Path(model_path).read_bytes()).hexdigest(),+ "model_loads": model_loads,+ "shutdown_memory": memory(),+ "shutdown_memory_diagnostics_before": shutdown_before,+ "shutdown_memory_diagnostics_after": mac_memory_diagnostics(),+ "shutdown_seconds": shutdown_seconds,+ "git_head": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip(),+ "script_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),+ "shape_adapter_sha256": hashlib.sha256((ROOT / "tools/det_shape_buckets.py").read_bytes()).hexdigest(),+ "cpu_microbatch_adapter_sha256": hashlib.sha256((ROOT / "tools/det_cpu_microbatch.py").read_bytes()).hexdigest(),+ "det_source_sha256_before": source_before,+ "det_source_sha256_after": det_source_fingerprint(),+ "limit_calls": args.limit_calls,+ "start_call": args.start_call,+ },+ )+++def run(args: argparse.Namespace) -> None:+ """串行启动独立策略进程,复测仅依赖冻结 PNG 和 manifest。"""+ policies = args.policies.split(",")+ if len(set(policies)) != len(policies) or any(+ policy not in "ABCDEFGHIJKLMNOPQRSTUV" or len(policy) != 1 for policy in policies+ ):+ raise ValueError("policies 必须是无重复的 A 至 V 逗号列表")+ names = args.documents.split(",")+ available = {document["name"] for document in read_json(args.corpus / "manifest.json")["documents"]}+ if any(name not in available for name in names):+ raise ValueError(f"documents 必须取自 {sorted(available)}")+ if (args.output / "protocol.json").exists():+ raise FileExistsError("请用新的 --output 保留此前结果")+ args.output.mkdir(parents=True, exist_ok=True)+ write_json(+ args.output / "protocol.json",+ {+ "corpus": str(args.corpus),+ "documents": args.documents,+ "cycles": args.cycles,+ "limit_calls": args.limit_calls,+ "start_call": args.start_call,+ "policies": args.policies,+ "call_indices": args.call_indices,+ "save_maps": args.save_maps,+ },+ )+ for policy in policies:+ directory = args.output / policy+ if (directory / "results.json").exists():+ raise FileExistsError("请用新的 --output 保留此前结果")+ directory.mkdir(exist_ok=True)+ with (directory / "run.log").open("w", encoding="utf-8") as log:+ subprocess.run(+ [+ sys.executable,+ str(Path(__file__).resolve()),+ "worker",+ "--policy",+ policy,+ "--corpus",+ str(args.corpus),+ "--output",+ str(args.output),+ "--documents",+ args.documents,+ "--cycles",+ str(args.cycles),+ "--limit-calls",+ str(args.limit_calls),+ "--start-call",+ str(args.start_call),+ "--call-indices",+ args.call_indices,+ *(["--save-maps"] if args.save_maps else []),+ ],+ cwd=ROOT,+ stdout=log,+ stderr=subprocess.STDOUT,+ check=True,+ )+ print(f"FINISHED policy={policy} report={directory / 'results.json'}", flush=True)+++def summarize(args: argparse.Namespace) -> None:+ """汇总冷热 det 性能和缓存成本,保存差异图以及可直接复测的命令。"""+ import numpy as np++ manifest = read_json(args.corpus / "manifest.json")+ protocol = read_json(args.output / "protocol.json")+ document_count = len(protocol["documents"].split(","))+ policies = protocol["policies"].split(",")+ if not {"A", "C"}.issubset(policies):+ raise ValueError("速度验收汇总至少需要 A 和 C;其他定点运行可直接读取 results.json")+ results = {policy: read_json(args.output / policy / "results.json") for policy in policies}+ environments = {policy: read_json(args.output / policy / "environment.json") for policy in policies}+ aggregate = {}+ for policy, records in results.items():+ aggregate[policy] = {+ "first_seconds": sum(record["seconds"] for record in records[:document_count]),+ "second_seconds": sum(record["seconds"] for record in records[document_count : 2 * document_count]),+ "reference_exact": all(record["reference_exact_crops"] == record["crops"] for record in records),+ "crops_per_cycle": sum(record["crops"] for record in records[:document_count]),+ }+ cpu = aggregate["A"]["second_seconds"]+ candidate = aggregate["C"]["second_seconds"]+ first_memory = results["C"][document_count - 1]["memory_after"]+ second_memory = results["C"][2 * document_count - 1]["memory_after"]+ memory_growth = {+ key: {+ "first": first_memory[key],+ "second": second_memory[key],+ "delta": second_memory[key] - first_memory[key],+ "limit": max(first_memory[key] * 0.1, 256 * 1024**2),+ }+ for key in first_memory+ }+ gate = {+ "det_reduction": 1 - candidate / cpu,+ "det_speedup": cpu / candidate,+ "det_performance_pass": candidate <= cpu * 0.75,+ "outputs_exact": all(value["reference_exact"] for value in aggregate.values()),+ "weights_equal": len({env["model_sha256"] for env in environments.values()}) == 1,+ "det_fp32": all(+ model["dtype"] == "torch.float32" for records in results.values() for row in records for model in row["models"]+ ),+ "models_reused": all(+ len({model["net_id"] for row in records for model in row["models"] if tuple(model["profile"]) == profile}) == 1+ for records in results.values()+ for profile in {tuple(model["profile"]) for row in records for model in row["models"]}+ ),+ "memory_screen_pass": all(value["delta"] <= value["limit"] for value in memory_growth.values()),+ "reverse_order_needed": abs(1 - candidate / cpu) < 0.1,+ "additional_cycle_executed": len(results["C"]) > 2 * document_count,+ }+ if gate["additional_cycle_executed"]:+ third_memory = results["C"][3 * document_count - 1]["memory_after"]+ gate["third_cycle_memory_growth"] = {+ key: {"delta": third_memory[key] - second_memory[key], "limit": max(second_memory[key] * 0.1, 256 * 1024**2)}+ for key in third_memory+ }+ checks = []+ review = args.output / "review"+ review.mkdir(exist_ok=True)+ for policy, records in results.items():+ for record in records:+ captured = read_json(args.output / policy / f"{record['label']}-boxes.json")+ document = next(doc for doc in manifest["documents"] if doc["name"] == record["document"])+ source_calls = document["calls"][protocol.get("start_call", 0) :]+ if protocol["limit_calls"]:+ source_calls = source_calls[: protocol["limit_calls"]]+ references = [item for call in source_calls for item in call["items"]]+ for index, (item, reference) in enumerate(zip(captured, references)):+ assert item["crop"] == reference["crop"], "重放顺序不同"+ if item["reference_equal"]:+ continue+ delta = {+ "policy": policy,+ "document": record["document"],+ "label": record["label"],+ "input_index": index,+ "crop": item["crop"],+ "reference": reference["boxes"],+ "actual": item["boxes"],+ }+ checks.append(delta)+ render_crop_comparison(+ args.corpus,+ review / f"{policy}-{record['label']}-{index:05d}.png",+ item["crop"],+ reference["boxes"],+ item["boxes"],+ )+ # 每份文档另留一个真实长文本裁剪,方便人工确认输入和检测框的含义。+ for document in manifest["documents"]:+ if document["name"] not in protocol["documents"].split(","):+ continue+ case = next(record for record in results["C"] if record["document"] == document["name"])+ replay = read_json(args.output / "C" / f"{case['label']}-boxes.json")+ if not replay:+ continue+ item = max(replay, key=lambda value: len(value["boxes"] or []))+ reference = next(+ source+ for call in document["calls"]+ for source in call["items"]+ if source["crop"] == item["crop"] and [call["box_thresh"], call["unclip_ratio"]] == item["profile"]+ )+ render_crop_comparison(+ args.corpus, review / f"sample-{document['name']}.png", item["crop"], reference["boxes"], item["boxes"]+ )+ summary = {+ "aggregates": aggregate,+ "gates": gate,+ "memory_growth": memory_growth,+ "differences": checks,+ "requests": results,+ "environments": environments,+ }+ write_json(args.output / "summary.json", summary)+ rows = []+ diagnostic_rows = []+ for policy, records in results.items():+ for record in records:+ rows.append(+ f"| {policy} | {record['label']} | {record['seconds']:.3f} | {record['crops'] / record['seconds']:.1f} | "+ f"{record['stages']['preprocess']:.3f} | {record['stages']['forward']:.3f} | "+ f"{record['stages']['postprocess']:.3f} | {record['memory_after']['rss'] / 1024**3:.2f} | "+ f"{record['memory_after']['mps_driver'] / 1024**3:.2f} |"+ )+ diagnostics = record.get("memory_diagnostics_after", {})+ if "phys_footprint" in diagnostics:+ diagnostic_rows.append(+ f"| {policy} | {record['label']} | {diagnostics['phys_footprint'] / 1024**3:.2f} | "+ f"{diagnostics['compressed'] / 1024**3:.2f} | {diagnostics['system_available'] / 1024**3:.2f} | "+ f"{diagnostics['system_swap_used'] / 1024**3:.2f} |"+ )+ diagnostics_report = ""+ if diagnostic_rows:+ diagnostics_report = (+ "\n补充 macOS TASK_VM_INFO 记账值:\n\n"+ "| 策略 | 输入 | footprint GiB | compressed GiB | 系统 available GiB | 系统 swap used GiB |\n"+ "| --- | --- | ---: | ---: | ---: | ---: |\n"+ + "\n".join(diagnostic_rows)+ + "\n\nfootprint 包含压缩/换出页记账,不能理解为当前驻留物理 RAM,不能与 RSS/driver 相加。"+ "原内存门槛只检查 RSS/allocated/driver 的增长,不能排除高绝对 footprint 的成本。\n"+ )+ command = f".venv4/bin/python tools/benchmark_det_corpus.py run --corpus {args.corpus} --output NEW_OUTPUT"+ report = f"""**仅 det 的冻结语料 A/B/C 对照**++完整语料保存 3 份真实文档的全部普通文字 det 输入:95、88、114 页,共 2280 次裁剪、2262 张唯一 PNG。+语料来自实际 Basic/OCR 生产调用,包含正文和表格 det,保留原始 batch 及每次调用的 box_thresh/unclip_ratio。+PNG 逐个恢复 BGR 并验证像素 SHA256;manifest 保存每次调用的输入形状、图像键和参考框,model_output 保留源块上下文。+只有输入准备阶段经过完整解析;以下测试不调用 layout、rec、表格识别、VLM 或文档导出。++A=CPU det+每本文档原 MPS 清理;B=MPS det+每本文档原 MPS 清理;C=MPS det+每本文档仅 GC 保留缓存。+本次顺序 {protocol["policies"]},文档顺序 {protocol["documents"]},每轮起始调用 {protocol.get("start_call", 0)},+每本文档调用上限 {protocol["limit_calls"]}(0 为全部)。策略使用独立进程串行运行、相同权重、FP32、生产线程配置。+相同 det 参数的模型在同一进程复用。+每份文档严格重放捕获的 batch,断言实际 NCHW 一致。不存在手工补齐形状、融合算子或其他算法优化。++| 策略 | 输入 | det 秒 | 裁剪/秒 | 预处理秒 | forward 秒 | 后处理秒 | 结束 RSS GiB | MPS driver GiB |+| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |+{chr(10).join(rows)}++第二遍所选输入的 det 合计:A {cpu:.3f} 秒,C {candidate:.3f} 秒。+C/A 耗时比 {candidate / cpu:.3f},耗时降低 {1 - candidate / cpu:.2%}(负值表示回退)。+预定速度门槛(降低至少 25%):{gate["det_performance_pass"]}。+与真实捕获参考框逐项一致:{gate["outputs_exact"]};三种策略权重相同:{gate["weights_equal"]}。+det FP32:{gate["det_fp32"]};模型实例持续复用:{gate["models_reused"]}。+内存初筛通过:{gate["memory_screen_pass"]};追加第三遍:{gate["additional_cycle_executed"]}。+内存分项与第三遍趋势保存在 summary.json,门槛为增长不超过 max(10%,256 MiB)。+{diagnostics_report}+不同 NCHW 的首次执行仍可能慢;有限输入集合的稳定性不能证明无限种类文档的缓存有界。++det 时间包含真实预处理、张量创建、同步推理、输出回传和 DB 后处理。+模型加载、PNG 读取、结果 JSON 写出、文档间 GC/empty_cache 单独记录,不计入 det 秒。+内存高水位在每次调用结束同步采样,未宣称捕获每个算子内部的瞬时峰值。+此结果只代表普通文字 det 阶段,不代表整本 API 或 Standard/VLM 的速度。++变化框全部保存在 review/ 和 summary.json;每份文档另保存一个真实长文本裁剪供人工核查。+语料目录:{args.corpus}+全量复测:`{command}`。+快速烟测:在上述命令追加 `--limit-calls 12`;只测某份文档可用 `--documents python`。+定点调试:用 `--start-call 50 --limit-calls 1 --documents python` 重放指定的原始调用(从 0 开始编号)。+所有重复调用使用 PNG 和 manifest,无需重跑 PDF 解析。运行结束会释放模型和 MPS 缓存。+"""+ (args.output / "report.md").write_text(report, encoding="utf-8")+ import matplotlib++ matplotlib.use("Agg")+ import matplotlib.pyplot as plt++ figure, axes = plt.subplots(1, 2, figsize=(12, 4), constrained_layout=True)+ for policy, records in results.items():+ indices = np.arange(1, len(records) + 1)+ axes[0].plot(indices, [record["seconds"] for record in records], "o-", label=policy)+ axes[1].plot(indices, [record["memory_after"]["mps_driver"] / 1024**3 for record in records], "o-", label=policy)+ axes[0].set(xlabel="Document replay index", ylabel="det seconds", title="A CPU / B MPS clear / C MPS retain")+ axes[1].set(xlabel="Document replay index", ylabel="MPS driver GiB", title="Cache residency after cleanup")+ for axis in axes:+ axis.grid(alpha=0.25)+ axis.legend()+ figure.savefig(args.output / "performance-memory.png", dpi=160)+ plt.close(figure)+ print(json.dumps(gate, ensure_ascii=False, indent=2))+++def render_crop_comparison(corpus: Path, target: Path, crop: str, reference: Any, actual: Any) -> None:+ """绘制真实 PNG 的参考/实际检测框,颜色不同但原像素相同。"""+ from PIL import Image, ImageDraw++ with Image.open(corpus / "images" / f"{crop}.png") as opened:+ image = opened.convert("RGB")+ width, height = image.size+ output = Image.new("RGB", (2 * width, height + 32), "white")+ for column, (name, boxes, color) in enumerate((("Captured reference", reference, "red"), ("Replay", actual, "blue"))):+ panel = image.copy()+ draw = ImageDraw.Draw(panel)+ for box in boxes or []:+ draw.line([tuple(point) for point in box] + [tuple(box[0])], fill=color, width=2)+ output.paste(panel, (column * width, 32))+ ImageDraw.Draw(output).text((column * width + 5, 8), name, fill="black")+ output.save(target)+++def main() -> None:+ """提供一次性冻结、完整 det 重放和少量调用烟测的可复用入口。"""+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "command",+ choices=(+ "freeze",+ "run",+ "worker",+ "summarize",+ "fusion-experiment",+ "fusion-summarize",+ "shape-experiment",+ "shape-summarize",+ ),+ )+ parser.add_argument("--corpus", type=Path, default=DEFAULT_CORPUS)+ parser.add_argument("--capture", type=Path, default=CAPTURE)+ parser.add_argument("--output", type=Path, default=DEFAULT_RESULTS)+ parser.add_argument("--policy", choices=tuple("ABCDEFGHIJKLMNOPQRSTUV"), default="A")+ parser.add_argument("--policies", default="A,B,C")+ parser.add_argument("--documents", default="tender,python,114")+ parser.add_argument("--cycles", type=int, default=2)+ parser.add_argument("--limit-calls", type=int, default=0)+ parser.add_argument("--start-call", type=int, default=0)+ parser.add_argument("--call-indices", default="", help="只诊断指定原调用编号,逗号分隔;不用于正式性能对照")+ parser.add_argument("--save-maps", action="store_true", help="诊断时另存概率图,不纳入正式性能对照")+ args = parser.parse_args()+ args.corpus, args.output, args.capture = args.corpus.resolve(), args.output.resolve(), args.capture.resolve()+ if args.cycles < 1 or args.limit_calls < 0 or args.start_call < 0:+ parser.error("cycles 必须为正,调用范围参数不能为负")+ if args.command == "summarize" and read_json(args.output / "protocol.json")["cycles"] < 2:+ parser.error("冷热对照汇总需要至少两遍输入;单遍调试可直接查看 results.json")+ if args.command.startswith("fusion-"):+ from analyze_det_fusion import fusion_experiment, fusion_summarize++ {"fusion-experiment": fusion_experiment, "fusion-summarize": fusion_summarize}[args.command](args)+ elif args.command.startswith("shape-"):+ from analyze_det_shapes import shape_experiment, shape_summarize++ {"shape-experiment": shape_experiment, "shape-summarize": shape_summarize}[args.command](args)+ else:+ {"freeze": freeze, "run": run, "worker": worker, "summarize": summarize}[args.command](args)+++if __name__ == "__main__":+ main()diff --git a/tools/benchmark_mps_det_service.py b/tools/benchmark_mps_det_service.pynew file mode 100644index 00000000..795a8608--- /dev/null+++ b/tools/benchmark_mps_det_service.py@@ -0,0 +1,535 @@+"""隔离子进程中的 MPS det 服务实验;不改变 MinerU 的默认设备和清理策略。"""++from __future__ import annotations++import argparse+import gc+import hashlib+import io+import json+import os+import re+import signal+import socket+import subprocess+import sys+import threading+import time+import weakref+import zipfile+from collections import Counter+from contextlib import asynccontextmanager+from pathlib import Path+from typing import Any++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT))+SAMPLES = {+ "tender": Path("/Volumes/2TB/pdf-test/表格困难户/跨页合并表/跨页单元格合并列")+ / "中国科协创新战略研究院科技智库大模型迭代建设与运维项目招标文件-最终稿.pdf",+ "python": Path("/Volumes/2TB/pdf-test/新的一批badcase/来自mac/Python.pdf"),+ "114": Path("/Volumes/2TB/pdf-test/新的一批badcase/来自mac/_114.pdf"),+}+DEFAULT_OUTPUT = ROOT / "tmp/pdfs/issue5632-cross-document-20261012"+++def write_json(path: Path, value: Any) -> None:+ """原子保存进度,进程异常退出时也保留此前完成的请求。"""+ temporary = path.with_suffix(path.suffix + ".new")+ temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")+ temporary.replace(path)+++class Observer:+ """记录普通文字 det、清理边界和显存,不持有模型或页面图像。"""++ def __init__(self, policy: str, output: Path) -> None:+ """建立当前实验进程的取证目录和后台内存采样线程。"""+ import psutil+ import torch++ self.torch = torch+ self.process = psutil.Process()+ self.policy = policy+ self.output = output+ self.current: dict[str, Any] | None = None+ self.detectors: list[weakref.ReferenceType[Any]] = []+ self.seen_shapes: set[tuple[int, ...]] = set()+ self.seen_crops: set[str] = set()+ self.cleanups: list[dict[str, Any]] = []+ self.initialized: list[dict[str, Any]] = []+ self.trace: Any = None+ self.stop_event = threading.Event()+ self.lock = threading.RLock()+ (output / "crops").mkdir(parents=True, exist_ok=True)+ self.sampler = threading.Thread(target=self.sample_loop, daemon=True)+ self.sampler.start()++ def memory(self) -> dict[str, int]:+ """采集进程内存和 MPS allocator/driver 的当前值。"""+ return {+ "rss": self.process.memory_info().rss,+ "mps_allocated": self.torch.mps.current_allocated_memory(),+ "mps_driver": self.torch.mps.driver_allocated_memory(),+ }++ def sample_loop(self) -> None:+ """以半秒间隔记录高水位,JSONL 不保存在内存中。"""+ with (self.output / "memory-samples.jsonl").open("w", encoding="utf-8") as stream:+ while not self.stop_event.wait(0.5):+ sample = {"time": time.time(), **self.memory()}+ with self.lock:+ if self.current is not None:+ sample["document"] = self.current["label"]+ for key in ("rss", "mps_allocated", "mps_driver"):+ self.current["peak_memory"][key] = max(self.current["peak_memory"][key], sample[key])+ stream.write(json.dumps(sample) + "\n")+ stream.flush()++ def begin(self, label: str) -> dict[str, Any]:+ """开始一次 API 请求的取证,模型和跨文档形状集合继续复用。"""+ assert self.current is None+ directory = self.output / label+ directory.mkdir(exist_ok=True)+ self.trace = (directory / "det-trace.jsonl").open("w", encoding="utf-8")+ memory = self.memory()+ self.current = {+ "label": label,+ "pid": os.getpid(),+ "stages": [],+ "cleanups": [],+ "preprocess_seconds": 0.0,+ "batch_seconds": 0.0,+ "forward_seconds": 0.0,+ "capture_seconds": 0.0,+ "trace_seconds": 0.0,+ "ordinary_det_calls": 0,+ "crops": 0,+ "boxes": 0,+ "new_shapes": 0,+ "reused_shapes": 0,+ "shapes": Counter(),+ "memory_before": memory,+ "peak_memory": dict(memory),+ }+ return self.current++ def finish(self) -> dict[str, Any]:+ """请求结束后保存统计,释放取证句柄而不影响模型缓存。"""+ self.torch.mps.synchronize()+ with self.lock:+ assert self.current is not None+ result = self.current+ result["memory_after"] = self.memory()+ result["det_seconds"] = result["preprocess_seconds"] + result["batch_seconds"]+ result["shape_counts"] = [{"shape": list(shape), "calls": count} for shape, count in result.pop("shapes").items()]+ result["models"] = [+ {+ "detector_id": id(detector),+ "net_id": id(detector.net),+ "device": detector.device,+ "dtype": str(detector.ocr_inference_dtype),+ "box_thresh": detector.args.det_db_box_thresh,+ "unclip_ratio": detector.args.det_db_unclip_ratio,+ }+ for ref in self.detectors+ if (detector := ref()) is not None+ ]+ self.trace.close()+ self.trace = None+ self.current = None+ assert result["ordinary_det_calls"] > 0, "本次请求未执行真实 det"+ write_json(self.output / result["label"] / "observation.json", result)+ return result++ def log_stage(self, message: Any) -> None:+ """读取生产 stage_timer 的日志,不替换实际阶段编排。"""+ match = re.search(r"MinerU stage: name=([^,]+), elapsed_s=([0-9.]+)", message.record["message"])+ if match is not None and self.current is not None:+ self.current["stages"].append({"name": match[1], "seconds": float(match[2])})++ def cleanup(self, device: str, original: Any) -> None:+ """只在独立实验进程切换文档清理策略,记录真实调用边界。"""+ started = time.perf_counter()+ before = self.memory()+ if self.policy == "C" and device.startswith("mps"):+ gc.collect()+ else:+ original(device)+ if device.startswith("mps"):+ self.seen_shapes.clear()+ self.torch.mps.synchronize()+ event = {+ "device": device,+ "seconds": time.perf_counter() - started,+ "before": before,+ "after": self.memory(),+ "empty_cache": self.policy != "C",+ }+ self.cleanups.append(event)+ if self.current is not None:+ self.current["cleanups"].append(event)++ def close(self) -> None:+ """停止采样并关闭异常请求尚未释放的文件句柄。"""+ self.stop_event.set()+ self.sampler.join()+ if self.trace is not None:+ self.trace.close()+++def install_det_observer(observer: Observer) -> None:+ """在实验子进程用计时子类替换构造器,覆盖所有普通文字 det 实例。"""+ import numpy as np+ import torch+ from PIL import Image++ from mineru.model._internal.pytorchocr.infer import predict_cls, predict_det, predict_rec, predict_system++ class ExperimentalDetector(predict_det.TextDetector):+ """保留生产前后处理,只显式选择普通文字 det 设备和记录数据。"""++ def __init__(self, args: Any, **kwargs: Any) -> None:+ """复用权重和 FP32 初始化,印章 det 维持原有行为。"""+ self.ordinary = getattr(args, "lang", "ch") not in {"seal", "seal_lite"}+ self.prepared: dict[int, str] = {}+ self.forward_started = 0.0+ super().__init__(args, **kwargs)+ if self.ordinary:+ self.device = "cpu" if observer.policy == "A" else "mps"+ self._apply_inference_precision(self.device, precision_override="fp32")+ assert next(self.net.parameters()).dtype == torch.float32+ observer.detectors.append(weakref.ref(self))+ observer.initialized.append({"id": id(self), "device": self.device, "box_thresh": args.det_db_box_thresh})+ self.net.register_forward_pre_hook(self.before_forward)+ self.net.register_forward_hook(self.after_forward)++ def before_forward(self, module: Any, inputs: Any) -> None:+ """同步实际执行起点,并记录 NCHW 形状是否在当前缓存周期出现过。"""+ if self.device == "mps":+ torch.mps.synchronize()+ self.forward_started = time.perf_counter()+ current = observer.current+ if current is not None:+ shape = tuple(inputs[0].shape)+ current["shapes"][shape] += 1+ current["new_shapes" if shape not in observer.seen_shapes else "reused_shapes"] += 1+ observer.seen_shapes.add(shape)++ def after_forward(self, module: Any, inputs: Any, outputs: Any) -> None:+ """同步 GPU 完成时间,避免把异步提交时间当作网络执行时间。"""+ if self.device == "mps":+ torch.mps.synchronize()+ if observer.current is not None:+ observer.current["forward_seconds"] += time.perf_counter() - self.forward_started++ def _preprocess_det_image(self, img: Any) -> Any:+ """计时生产预处理,并保存可复查的原始裁剪,取证耗时单独统计。"""+ started = time.perf_counter()+ result = super()._preprocess_det_image(img)+ elapsed = time.perf_counter() - started+ current = observer.current+ if self.ordinary and current is not None and result is not None:+ current["preprocess_seconds"] += elapsed+ capture_started = time.perf_counter()+ crop_hash = hashlib.sha256(str(img.shape).encode() + np.ascontiguousarray(img).tobytes()).hexdigest()+ if crop_hash not in observer.seen_crops:+ Image.fromarray(img[:, :, ::-1]).save(observer.output / "crops" / f"{crop_hash}.png")+ observer.seen_crops.add(crop_hash)+ self.prepared[id(result[0])] = crop_hash+ current["capture_seconds"] += time.perf_counter() - capture_started+ return result++ def _batch_process_preprocessed(self, batch_items: Any) -> Any:+ """计时生产批处理,保存输入对应的最终框而不持有原始数组。"""+ started = time.perf_counter()+ results, elapsed = super()._batch_process_preprocessed(batch_items)+ batch_seconds = time.perf_counter() - started+ current = observer.current+ if self.ordinary and current is not None:+ current["batch_seconds"] += batch_seconds+ current["ordinary_det_calls"] += 1+ current["crops"] += len(batch_items)+ trace_started = time.perf_counter()+ record = {+ "detector_id": id(self),+ "box_thresh": self.args.det_db_box_thresh,+ "unclip_ratio": self.args.det_db_unclip_ratio,+ "shape": [len(batch_items), *batch_items[0][1].shape],+ "seconds": batch_seconds,+ "items": [],+ }+ for item, (boxes, _) in zip(batch_items, results):+ points = boxes.tolist() if hasattr(boxes, "tolist") else boxes+ record["items"].append(+ {"crop": self.prepared.pop(id(item[1])), "original_shape": list(item[3]), "boxes": points}+ )+ current["boxes"] += len(points) if points is not None else 0+ observer.trace.write(json.dumps(record) + "\n")+ current["trace_seconds"] += time.perf_counter() - trace_started+ return results, elapsed++ def initialize_system(system: Any, args: Any, **kwargs: Any) -> None:+ """在调用侧替换 det 构造器,保留原定义模块中显式 super 的类身份。"""+ system.text_detector = ExperimentalDetector(args, **kwargs)+ system.text_recognizer = predict_rec.TextRecognizer(args, **kwargs)+ system.use_angle_cls = args.use_angle_cls+ system.drop_score = args.drop_score+ if system.use_angle_cls:+ system.text_classifier = predict_cls.TextClassifier(args, **kwargs)++ predict_system.TextSystem.__init__ = initialize_system+++def serve(args: argparse.Namespace) -> None:+ """启动只有本轮实验使用的本地 API,策略不传播到其他进程。"""+ os.environ["MINERU_DEVICE_MODE"] = "mps"+ os.environ["MINERU_PROFILE_STAGES"] = "1"+ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"+ import uvicorn+ from loguru import logger+ from mineru.config import config+ from mineru.backend.analysis.pdf import pipeline+ from mineru.model.runtime.hybrid import AtomModelSingleton, HybridLocalModelContextSingleton+ from mineru.model.runtime.memory import clean_memory+ from mineru.parser.api_server import create_app++ config.model.small_backend = "torch"+ output = args.output / args.policy+ output.mkdir(parents=True, exist_ok=True)+ observer = Observer(args.policy, output)+ install_det_observer(observer)+ logger.add(observer.log_stage, level="INFO", format="{message}")++ def document_cleanup(device: str) -> None:+ """保留生产 release_document 边界,仅注入本进程的回收回调。"""+ observer.cleanup(device, clean_memory)++ pipeline.clean_memory = document_cleanup+ app = create_app(+ tier="basic",+ concurrency=1,+ allow_local_source=True,+ image_analysis=False,+ preload_models=False,+ retention_seconds=0,+ upload_dir=str(output / "service-storage"),+ )+ production_lifespan = app.router.lifespan_context++ @asynccontextmanager+ async def lifespan(application: Any) -> Any:+ """先完整执行生产服务关闭,再释放本进程的本地模型和 MPS 缓存。"""+ try:+ async with production_lifespan(application):+ yield+ finally:+ before = observer.memory()+ HybridLocalModelContextSingleton._models.clear()+ AtomModelSingleton._models.clear()+ gc.collect()+ clean_memory("mps")+ observer.torch.mps.synchronize()+ write_json(+ output / "shutdown.json",+ {+ "before": before,+ "after": observer.memory(),+ "initialized": observer.initialized,+ "cleanups": observer.cleanups,+ },+ )+ observer.close()++ app.router.lifespan_context = lifespan++ @app.post("/_benchmark/begin")+ async def begin(body: dict[str, str]) -> dict[str, Any]:+ """控制器在提交单个真实 API 任务之前开启观察窗口。"""+ return observer.begin(body["label"])++ @app.post("/_benchmark/end")+ async def end() -> dict[str, Any]:+ """控制器确认任务终态后,保存此次请求的阶段与内存统计。"""+ return observer.finish()++ uvicorn.run(app, host="127.0.0.1", port=args.port, log_level="warning", access_log=False)+++def reserve_port() -> int:+ """申请临时本地端口,避免打扰已经运行的用户服务。"""+ with socket.socket() as sock:+ sock.bind(("127.0.0.1", 0))+ return int(sock.getsockname()[1])+++def get_with_retry(client: Any, url: str) -> Any:+ """仅重试幂等 GET 的短暂连接重置,绝不重新提交正在执行的解析任务。"""+ import httpx++ for attempt in range(3):+ try:+ return client.get(url)+ except httpx.TransportError:+ if attempt == 2:+ raise+ time.sleep(0.5)+ raise AssertionError("不可达的重试分支")+++def run_policy(args: argparse.Namespace, policy: str) -> list[dict[str, Any]]:+ """启动独立服务进程,逐个提交新任务,并完整关闭服务。"""+ import httpx++ output = args.output / policy+ if (output / "requests.json").exists():+ raise FileExistsError(f"已有结果,需使用新输出目录:{output}")+ output.mkdir(parents=True, exist_ok=True)+ port = reserve_port()+ records: list[dict[str, Any]] = []+ with (output / "server.log").open("w", encoding="utf-8") as log:+ child = subprocess.Popen(+ [+ sys.executable,+ str(Path(__file__).resolve()),+ "serve",+ "--policy",+ policy,+ "--output",+ str(args.output),+ "--port",+ str(port),+ ],+ cwd=ROOT,+ stdout=log,+ stderr=subprocess.STDOUT,+ )+ try:+ with httpx.Client(base_url=f"http://127.0.0.1:{port}", timeout=60, trust_env=False) as client:+ deadline = time.monotonic() + 180+ while True:+ if child.poll() is not None:+ raise RuntimeError(f"服务启动失败:{output / 'server.log'}")+ try:+ if client.get("/v1/health").status_code == 200:+ break+ except httpx.HTTPError:+ pass+ if time.monotonic() > deadline:+ raise TimeoutError("等待服务启动超时")+ time.sleep(0.5)+ sequence = args.sequence.split(",")+ for position, sample in enumerate(sequence):+ label = f"{position + 1:02d}-{sample}"+ response = client.post("/_benchmark/begin", json={"label": label})+ response.raise_for_status()+ payload = {+ "tier": "basic",+ "ocr_mode": "ocr",+ "output_formats": ["markdown", "middle_json", "zip"],+ "files": [{"source": {"type": "local", "path": str(SAMPLES[sample])}, "page_range": args.pages}],+ }+ started = time.perf_counter()+ response = client.post("/v1/parse/jobs", json=payload)+ response.raise_for_status()+ job = response.json()+ job_id = job["job_id"]+ announced = time.monotonic()+ while job["status"] not in {"completed", "partial", "failed", "canceled"}:+ time.sleep(0.25)+ response = get_with_retry(client, f"/v1/parse/jobs/{job_id}")+ response.raise_for_status()+ job = response.json()+ if time.monotonic() - announced >= 30:+ print(+ f"RUN policy={policy} document={label} elapsed={time.perf_counter() - started:.1f}s", flush=True+ )+ announced = time.monotonic()+ request_seconds = time.perf_counter() - started+ directory = output / label+ write_json(directory / "job.json", job)+ if job["status"] != "completed":+ raise RuntimeError(f"任务未完整完成:{directory / 'job.json'}")+ observation = client.post("/_benchmark/end")+ observation.raise_for_status()+ record = observation.json()+ record.update(+ {+ "sample": sample,+ "job_id": job_id,+ "request_seconds": request_seconds,+ "server_seconds": job["files"][0]["parse"]["duration_ms"] / 1000,+ }+ )+ for kind, reference in job["files"][0]["output_files"].items():+ if reference is None:+ continue+ response = get_with_retry(client, f"/v1/files/{reference['file_id']}/content")+ response.raise_for_status()+ suffix = {"markdown": "md", "middle_json": "json", "zip": "zip"}[kind]+ (directory / f"{kind}.{suffix}").write_bytes(response.content)+ if kind == "zip":+ with zipfile.ZipFile(io.BytesIO(response.content)) as archive:+ archive.extractall(directory / "bundle")+ records.append(record)+ write_json(output / "requests.json", records)+ if policy == "C" and len(records) == 6:+ first = records[2]["memory_after"]+ second = records[5]["memory_after"]+ if any(second[key] - first[key] > max(256 * 1024**2, first[key] * 0.1) for key in first):+ sequence.extend(sequence[:3])+ print("EXTEND C: 内存增长超过门槛,在同一服务进程追加第三遍三本文档", flush=True)+ print(+ f"DONE policy={policy} document={label} request={request_seconds:.2f}s "+ f"det={record['det_seconds']:.2f}s "+ f"crops={record['crops']} memory={record['memory_after']}",+ flush=True,+ )+ finally:+ if child.poll() is None:+ child.send_signal(signal.SIGINT)+ try:+ child.wait(timeout=90)+ except subprocess.TimeoutExpired:+ child.terminate()+ child.wait(timeout=30)+ if child.returncode != 0:+ print(f"服务退出码={child.returncode},日志:{output / 'server.log'}", flush=True)+ return records+++def main() -> None:+ """提供服务子进程与串行控制器入口,默认执行三种策略的两遍文档。"""+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("command", choices=("serve", "run"))+ parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)+ parser.add_argument("--policy", choices=("A", "B", "C"), default="A")+ parser.add_argument("--policies", default="A,B,C")+ parser.add_argument("--port", type=int, default=0)+ parser.add_argument("--sequence", default="tender,python,114,tender,python,114")+ parser.add_argument("--pages", default="all")+ args = parser.parse_args()+ args.output = args.output.resolve()+ if args.command == "serve":+ serve(args)+ else:+ args.output.mkdir(parents=True, exist_ok=True)+ write_json(+ args.output / "protocol.json",+ {+ "sequence": args.sequence,+ "pages": args.pages,+ "policies": args.policies,+ "samples": {+ key: {"path": str(path), "sha256": hashlib.sha256(path.read_bytes()).hexdigest()}+ for key, path in SAMPLES.items()+ },+ "git_head": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip(),+ },+ )+ for policy in args.policies.split(","):+ run_policy(args, policy)+++if __name__ == "__main__":+ main()diff --git a/tools/det_cpu_microbatch.py b/tools/det_cpu_microbatch.pynew file mode 100644index 00000000..20de5b46--- /dev/null+++ b/tools/det_cpu_microbatch.py@@ -0,0 +1,84 @@+"""仅供本机 CPU det 实验使用的真实尾批拆分,不修改生产调用路径。"""++from __future__ import annotations++import time+from typing import Any++CPU_MICROBATCH_STRATEGIES: dict[str, tuple[int, int]] = {+ "O": (16, 1),+ "P": (16, 2),+ "Q": (16, 4),+ "R": (16, 8),+ "S": (1, 2),+ "T": (1, 4),+ "U": (1, 8),+}+++def project_cpu_microbatch(shape: list[int], policy: str) -> dict[str, Any]:+ """明确计算阈值分流及每个真实 microbatch 的 NCHW,尾批不复制虚假样本。"""+ threshold, cap = CPU_MICROBATCH_STRATEGIES[policy]+ n, channels, height, width = shape+ if any(value < 1 for value in shape):+ raise ValueError("CPU microbatch 输入形状必须为正")+ split = n >= threshold and n > cap+ shapes = [[min(cap, n - offset), channels, height, width] for offset in range(0, n, cap)] if split else [shape]+ return {+ "original_shape": shape,+ "network_shapes": shapes,+ "real_images": n,+ "processed_images": n,+ "original_pixels": n * height * width,+ "processed_pixels": n * height * width,+ "spatial_alignment": None,+ "spatial_pad_normalized_value": None,+ "batch_pad": None,+ "batch_bucket": cap,+ "split_threshold": threshold,+ "split_required": split,+ }+++def process_cpu_microbatch(detector: Any, batch_items: list[Any], policy: str) -> tuple[list[Any], float]:+ """按真实 N 切连续数组视图、串行前向,恢复原概率图顺序后执行一次原后处理。"""+ import numpy as np+ import torch++ if not batch_items:+ return [], 0.0+ started = time.perf_counter()+ images = np.ascontiguousarray(np.stack([item[1] for item in batch_items]))+ n, _, height, width = images.shape+ projection = project_cpu_microbatch(list(images.shape), policy)+ if not projection["split_required"] or detector.device != "cpu":+ raise ValueError("拆分函数只接受已满足阈值的 CPU 输入;未拆批时应直接调用原实现")+ cap = projection["batch_bucket"]+ maps = []+ organization_seconds = 0.0+ for offset in range(0, n, cap):+ preparation_started = time.perf_counter()+ chunk = np.ascontiguousarray(images[offset : offset + cap])+ organization_seconds += time.perf_counter() - preparation_started+ with torch.inference_mode():+ inputs = detector._to_inference_dtype(torch.from_numpy(chunk).to(detector.device))+ outputs = detector.net(inputs)+ predictions = detector._build_det_preds(outputs)["maps"]+ if predictions.shape != (len(chunk), 1, height, width):+ raise ValueError(f"CPU microbatch 概率图形状异常:{predictions.shape}")+ maps.append(predictions)+ del predictions, inputs, outputs, chunk+ concatenation_started = time.perf_counter()+ restored = np.concatenate(maps, axis=0)+ organization_seconds += time.perf_counter() - concatenation_started+ # 复用实验计时字段记录拆批组织成本;本策略没有 padding 操作。+ detector.bucket_padding_seconds += organization_seconds+ if restored.shape != (n, 1, height, width):+ raise ValueError("CPU microbatch 未恢复原 N/H/W")+ if detector.capture_maps:+ detector.last_maps = restored+ boxes = detector._postprocess_det_batch(+ {"maps": restored}, np.stack([item[2] for item in batch_items]), [item[3] for item in batch_items]+ )+ elapsed = time.perf_counter() - started+ return [(box, elapsed / n) for box in boxes], elapseddiff --git a/tools/det_shape_buckets.py b/tools/det_shape_buckets.pynew file mode 100644index 00000000..75172cf3--- /dev/null+++ b/tools/det_shape_buckets.py@@ -0,0 +1,86 @@+"""仅供冻结语料实验使用的 N/H/W 归并;不改变生产 det 的预处理和后处理。"""++from __future__ import annotations++import math+import time+from typing import Any++SHAPE_STRATEGIES: dict[str, tuple[int | None, int | None]] = {+ "F": (1, None),+ "G": (4, None),+ "H": (None, 64),+ "I": (None, 128),+}+++def project_shape(shape: list[int], policy: str) -> dict[str, Any]:+ """预先计算真实送入网络的形状、拆批数量和额外像素工作量。"""+ n, c, height, width = shape+ batch, alignment = SHAPE_STRATEGIES.get(policy, (None, None))+ target_batch = batch or n+ target_height = math.ceil(height / alignment) * alignment if alignment else height+ target_width = math.ceil(width / alignment) * alignment if alignment else width+ chunks = math.ceil(n / target_batch)+ shapes = [[target_batch, c, target_height, target_width] for _ in range(chunks)]+ return {+ "original_shape": shape,+ "network_shapes": shapes,+ "real_images": n,+ "processed_images": target_batch * chunks,+ "original_pixels": n * height * width,+ "processed_pixels": target_batch * chunks * target_height * target_width,+ "spatial_alignment": alignment,+ "batch_bucket": batch,+ "spatial_pad_normalized_value": 0.0 if alignment else None,+ "batch_pad": "repeat_last_real_image" if target_batch * chunks > n else None,+ }+++def process_bucketed_batch(detector: Any, batch_items: list[Any], policy: str) -> tuple[list[Any], float]:+ """保留原图 resize/坐标,只在网络入口拆批补齐,并在 CPU 恢复原概率图后执行一次 DB 后处理。"""+ import numpy as np+ import torch++ if not batch_items:+ return [], 0.0+ started = time.perf_counter()+ images = np.ascontiguousarray(np.stack([item[1] for item in batch_items]))+ shape = list(images.shape)+ projection = project_shape(shape, policy)+ n, _, height, width = shape+ batch, _, padded_height, padded_width = projection["network_shapes"][0]+ maps = []+ padding_seconds = 0.0+ for offset in range(0, n, batch):+ padding_started = time.perf_counter()+ real = images[offset : offset + batch]+ count = len(real)+ padded = np.zeros((batch, shape[1], padded_height, padded_width), dtype=images.dtype)+ padded[:count, :, :height, :width] = real+ if count < batch:+ # eval 网络不存在跨样本归一化,补齐样本的输出会在 CPU 丢弃。+ padded[count:] = padded[count - 1]+ padding_seconds += time.perf_counter() - padding_started+ with torch.inference_mode():+ inputs = detector._to_inference_dtype(torch.from_numpy(padded).to(detector.device))+ outputs = detector.net(inputs)+ predictions = detector._build_det_preds(outputs)["maps"]+ if predictions.shape[:2] != (batch, 1) or predictions.shape[2:] != (padded_height, padded_width):+ raise ValueError(f"归并后的概率图形状不符合 DBHead 约定:{predictions.shape}")+ # 先回传 CPU,再裁切,避免额外 MPS slice 图缓存和错误的后处理缩放。+ maps.append(np.ascontiguousarray(predictions[:count, :, :height, :width]))+ del predictions, inputs, outputs, padded+ concatenation_started = time.perf_counter()+ restored = np.concatenate(maps, axis=0)+ padding_seconds += time.perf_counter() - concatenation_started+ detector.bucket_padding_seconds += padding_seconds+ if restored.shape != (n, 1, height, width):+ raise ValueError("归并后的概率图未恢复原始 N/H/W")+ if detector.capture_maps:+ detector.last_maps = restored+ boxes = detector._postprocess_det_batch(+ {"maps": restored}, np.stack([item[2] for item in batch_items]), [item[3] for item in batch_items]+ )+ elapsed = time.perf_counter() - started+ return [(box, elapsed / n) for box in boxes], elapsed