import argparse import hashlib import json from pathlib import Path TEXT_EXTENSIONS = { ".json", ".txt", ".md", ".model", ".py", ".yaml", ".yml", ".ini", } def sha256_file(path: Path, chunk_size: int = 1024 * 1024) -> str: """计算文件的 SHA256,便于判断两个文件是否完全一致。""" digest = hashlib.sha256() with open(path, "rb") as f: while True: chunk = f.read(chunk_size) if not chunk: break digest.update(chunk) return digest.hexdigest() def collect_files(root: Path) -> dict[str, Path]: """收集目录下所有文件,并转成相对路径 -> 绝对路径的映射。""" files = {} for path in root.rglob("*"): if path.is_file(): rel_path = path.relative_to(root).as_posix() files[rel_path] = path return files def safe_load_json(path: Path): """尽量把 json 文件读出来;读失败时返回 None。""" try: with open(path, "r", encoding="utf-8") as f: return json.load(f) except Exception: return None def compare_json_dict(a, b, prefix="") -> list[str]: """递归比较两个 json/dict,输出简洁差异。""" diffs = [] if type(a) is not type(b): diffs.append(f"{prefix or ''}: type {type(a).__name__} != {type(b).__name__}") return diffs if isinstance(a, dict): keys = sorted(set(a.keys()) | set(b.keys())) for key in keys: new_prefix = f"{prefix}.{key}" if prefix else str(key) if key not in a: diffs.append(f"{new_prefix}: missing in A") elif key not in b: diffs.append(f"{new_prefix}: missing in B") else: diffs.extend(compare_json_dict(a[key], b[key], new_prefix)) return diffs if isinstance(a, list): if len(a) != len(b): diffs.append(f"{prefix or ''}: list len {len(a)} != {len(b)}") return diffs for idx, (va, vb) in enumerate(zip(a, b)): diffs.extend(compare_json_dict(va, vb, f"{prefix}[{idx}]")) return diffs if a != b: diffs.append(f"{prefix or ''}: {a!r} != {b!r}") return diffs def group_by_top_level(paths: set[str]) -> dict[str, list[str]]: """把相对路径按顶层目录分组,方便看哪个模块有差异。""" grouped = {} for rel_path in sorted(paths): top = rel_path.split("/", 1)[0] grouped.setdefault(top, []).append(rel_path) return grouped def compare_dirs(dir_a: Path, dir_b: Path, max_diffs: int = 50) -> dict: """比较两个 checkpoint 目录,输出结构、哈希和 json 级别的差异摘要。""" files_a = collect_files(dir_a) files_b = collect_files(dir_b) set_a = set(files_a.keys()) set_b = set(files_b.keys()) only_a = set_a - set_b only_b = set_b - set_a common = sorted(set_a & set_b) identical_files = [] different_files = [] json_diffs = {} for rel_path in common: path_a = files_a[rel_path] path_b = files_b[rel_path] same_hash = sha256_file(path_a) == sha256_file(path_b) if same_hash: identical_files.append(rel_path) continue record = { "path": rel_path, "size_a": path_a.stat().st_size, "size_b": path_b.stat().st_size, "sha256_a": sha256_file(path_a), "sha256_b": sha256_file(path_b), } different_files.append(record) if path_a.suffix.lower() in TEXT_EXTENSIONS and path_b.suffix.lower() in TEXT_EXTENSIONS: json_a = safe_load_json(path_a) json_b = safe_load_json(path_b) if json_a is not None and json_b is not None: diffs = compare_json_dict(json_a, json_b) if diffs: json_diffs[rel_path] = diffs[:max_diffs] return { "dir_a": str(dir_a), "dir_b": str(dir_b), "file_count_a": len(files_a), "file_count_b": len(files_b), "only_in_a_count": len(only_a), "only_in_b_count": len(only_b), "identical_file_count": len(identical_files), "different_file_count": len(different_files), "only_in_a_grouped": group_by_top_level(only_a), "only_in_b_grouped": group_by_top_level(only_b), "sample_identical_files": identical_files[:30], "sample_different_files": different_files[:30], "json_diffs": json_diffs, } def main(): """脚本入口:比较两个模型目录并输出报告。""" parser = argparse.ArgumentParser( description="Compare two checkpoint directories by file tree, hashes, and JSON configs." ) parser.add_argument("--dir-a", required=True, help="First checkpoint root directory.") parser.add_argument("--dir-b", required=True, help="Second checkpoint root directory.") parser.add_argument( "--report-path", default=None, help="Optional path to save the comparison report as JSON.", ) parser.add_argument( "--max-json-diffs", type=int, default=50, help="Maximum number of JSON diff entries stored per file.", ) args = parser.parse_args() dir_a = Path(args.dir_a) dir_b = Path(args.dir_b) if not dir_a.exists(): raise FileNotFoundError(f"Directory not found: {dir_a}") if not dir_b.exists(): raise FileNotFoundError(f"Directory not found: {dir_b}") report = compare_dirs(dir_a, dir_b, max_diffs=args.max_json_diffs) if args.report_path: report_path = Path(args.report_path) report_path.parent.mkdir(parents=True, exist_ok=True) with open(report_path, "w", encoding="utf-8") as f: json.dump(report, f, indent=2) print(f"Report written to: {report_path}") print(f"Compared: {dir_a} vs {dir_b}") print(f"Files only in A: {report['only_in_a_count']}") print(f"Files only in B: {report['only_in_b_count']}") print(f"Identical files: {report['identical_file_count']}") print(f"Different files: {report['different_file_count']}") if report["only_in_a_grouped"]: print("Top-level paths only in A:") for top, paths in report["only_in_a_grouped"].items(): print(f" {top}: {len(paths)}") if report["only_in_b_grouped"]: print("Top-level paths only in B:") for top, paths in report["only_in_b_grouped"].items(): print(f" {top}: {len(paths)}") if report["sample_different_files"]: print("Sample different files:") for item in report["sample_different_files"][:10]: print(f" {item['path']}") if __name__ == "__main__": main()