File size: 6,833 Bytes
465d9ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
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 '<root>'}: 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 '<root>'}: 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 '<root>'}: {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()