File size: 13,470 Bytes
a832865
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
#!/usr/bin/env python3
"""Build the Hugging Face / Zenodo package from one or more benchmark result folders.

Each result folder is what benchmark/run_benchmark.py + standardize.py + plot_results.py wrote
(raw_runs.csv, benchmark_results.csv, hardware_environment.json, inputs_manifest.json, *.png, ...).

    python scripts/build_package.py \
        --machine laptop_i5-7200u_wsl2=/path/to/benchmark/results \
        --machine pc_i5-13500_wsl2=/path/s1,/path/s2 \
        --out dist/hpc-parallel-matrix-sorting-benchmark --version 1.0.0 [--doi 10.5281/zenodo.NNN]

`id=dirA,dirB` means one machine measured in several sessions (e.g. big matrix sizes in a later session).
The (workload, size) pairs of different sessions of one machine must be disjoint, because speedups are computed
inside one session; nothing is recomputed here except two derived columns S_N and E_N (defined below).
Per-machine caveats are read from caveats/<machine_id>.md and are mandatory.
"""
import argparse, hashlib, json, shutil, sys
from pathlib import Path
import numpy as np
import pandas as pd

HERE = Path(__file__).resolve().parent.parent
REPO = "Namra-5/hpc-parallel-matrix-sorting-benchmark"
GITHUB = "https://github.com/Namra-5/parallel_sorting_and_matrix_benchmark"
FIGS = ["matrix_speedup_kernel", "matrix_speedup_wall", "matrix_kernel_time", "matrix_kernel_time_all_workers",
        "mergesort_speedup_kernel", "mergesort_speedup_wall", "mergesort_kernel_time", "mergesort_kernel_time_all_workers"]
SIDE = ["hardware_environment.json", "inputs_manifest.json", "lscpu_excerpt.txt", "lscpu_full.txt", "cpu_model.txt",
        "python_packages.txt", "run.log"]


def die(msg):
    sys.exit(f"ERROR: {msg}")


def sha(path):
    h = hashlib.sha256()
    with open(path, "rb") as fh:
        for c in iter(lambda: fh.read(1 << 20), b""):
            h.update(c)
    return h.hexdigest()


def expected_runs(cfg, protocol):
    total = 0
    for wl, g in cfg.groupby("workload"):
        reps = protocol.get("sort_reps", protocol["reps"]) if wl == "mergesort" else protocol["reps"]
        total += len(g) * reps
    return total


def load_session(mid, k, d):
    d = Path(d)
    for f in ("raw_runs.csv", "benchmark_results.csv", "hardware_environment.json"):
        if not (d / f).exists():
            die(f"{d} has no {f}")
    raw = pd.read_csv(d / "raw_runs.csv")
    cfg = pd.read_csv(d / "benchmark_results.csv")
    hw = json.loads((d / "hardware_environment.json").read_text())
    bad = raw[raw["status"] != "ok"]
    if len(bad):
        die(f"{mid} session {k}: {len(bad)} of {len(raw)} runs are not 'ok'; refusing to publish")
    exp = expected_runs(cfg, hw["protocol"])
    if len(raw) != exp:
        die(f"{mid} session {k}: {len(raw)} runs but the recorded protocol implies {exp}")
    if hw.get("notes", "").startswith("EDIT:"):
        die(f"{mid} session {k}: hardware_environment.json still has the default placeholder notes")
    if hw.get("git", {}).get("dirty"):
        print(f"WARNING: {mid} session {k} was measured from a dirty git tree", file=sys.stderr)
    return d, raw, cfg, hw


def derived(cfg):
    """S_N = T_1 / T_N and E_N = S_N / N, T = median in-program (kernel) time of the SAME model, workload and size."""
    cfg = cfg.copy()
    cfg["S_N"] = cfg["kernel_speedup_vs_1worker"]
    cfg["E_N"] = (cfg["S_N"] / cfg["workers"]).round(6)
    return cfg


def check_s_n(raw, cfg):
    """Recompute S_N from the raw runs and compare with the stored column."""
    ok = raw[raw["status"] == "ok"]
    med = ok.groupby(["workload", "model", "size", "workers"])["kernel_s"].median()
    worst = 0.0
    for r in cfg.itertuples():
        if r.model == "seq":
            if not np.isnan(r.S_N):
                die("S_N must be empty for the sequential model")
            continue
        s = med[(r.workload, r.model, r.size, 1)] / med[(r.workload, r.model, r.size, r.workers)]
        worst = max(worst, abs(s - r.S_N))
        if abs(s - r.E_N * r.workers) > 2e-6 * r.workers:
            die(f"E_N inconsistent for {r}")
    if worst > 1e-6:
        die(f"S_N differs from recomputation from raw runs by {worst}")
    return worst


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--machine", action="append", required=True, metavar="ID=DIR[,DIR...]")
    ap.add_argument("--out", required=True)
    ap.add_argument("--version", default="1.0.0")
    ap.add_argument("--doi", default=None, help="Zenodo DOI once minted, e.g. 10.5281/zenodo.1234567")
    ap.add_argument("--extra", action="append", default=[], metavar="ID=FILE", help="copy FILE into machines/ID/ (e.g. the driver progress log)")
    a = ap.parse_args()

    out = Path(a.out)
    if out.exists():
        die(f"{out} exists; remove it first")
    (out / "data").mkdir(parents=True)
    raws, cfgs, rows = [], [], []
    for spec in a.machine:
        if "=" not in spec:
            die("--machine needs ID=DIR")
        mid, dirs = spec.split("=", 1)
        cav = HERE / "caveats" / f"{mid}.md"
        if not cav.exists():
            die(f"missing {cav}: write the machine-specific caveats first")
        seen = set()
        for k, d in enumerate(dirs.split(","), 1):
            d, raw, cfg, hw = load_session(mid, k, d)
            keys = set(zip(cfg["workload"], cfg["size"]))
            if keys & seen:
                die(f"{mid}: sessions overlap in {sorted(keys & seen)}")
            seen |= keys
            cfg = derived(cfg)
            w = check_s_n(raw, cfg)
            print(f"{mid} session {k}: {len(raw)} runs, {len(cfg)} configurations, S_N matches raw to {w:.1e}")
            for df, store in ((raw, raws), (cfg, cfgs)):
                df = df.copy()
                df.insert(0, "session", k)
                df.insert(0, "machine_id", mid)
                store.append(df)
            dst = out / "machines" / mid / f"session_{k}"
            dst.mkdir(parents=True)
            for f in SIDE:
                if (d / f).exists():
                    shutil.copy2(d / f, dst / f)
            (dst / "figures").mkdir()
            for f in FIGS:
                if (d / f"{f}.png").exists():
                    shutil.copy2(d / f"{f}.png", dst / "figures" / f"{f}.png")
            shutil.copy2(cav, out / "machines" / mid / "CAVEATS.md")
            p = hw["protocol"]
            rows.append({"machine_id": mid, "session": k, "collected_utc": hw["collected_utc"], "cpu_model": hw["cpu_model"],
                         "effective_cores_used_by_harness": hw["effective_cores"], "physical_cores_reported": hw["physical_cores"],
                         "logical_cpus_usable": hw["logical_cpus_usable"], "memory_total_gib": hw["memory_total_gib"],
                         "os": hw["os"], "gcc": hw["gcc"], "mpirun": hw["mpirun"], "git_commit": hw["git"]["commit"],
                         "workers": " ".join(map(str, p["workers"])),
                         "workloads_reps": ", ".join(f"{wl}: {p.get('sort_reps', p['reps']) if wl == 'mergesort' else p['reps']} reps" for wl in sorted(cfg["workload"].unique())),
                         "cooldown_s": p["cooldown_s"], "warmup": p["warmup"],
                         "notes": hw["notes"], "n_runs": len(raw), "n_configurations": len(cfg)})
    raw = pd.concat(raws, ignore_index=True)
    cfg = pd.concat(cfgs, ignore_index=True)
    mach = pd.DataFrame(rows)
    raw.to_csv(out / "data" / "raw_runs.csv", index=False, lineterminator="\n")
    cfg.to_csv(out / "data" / "benchmark_results.csv", index=False, lineterminator="\n")
    mach.to_csv(out / "data" / "machines.csv", index=False, lineterminator="\n")

    # ---- dataset card -------------------------------------------------------------------------------------------
    n_raw, n_cfg = len(raw), len(cfg)
    size_cat = "n<1K" if n_raw < 1000 else "1K<n<10K" if n_raw < 10000 else "10K<n<100K"
    msz = sorted(cfg[cfg.workload == "matrix"]["size"].unique())
    ssz = sorted(cfg[cfg.workload == "mergesort"]["size"].unique())
    doi_line = f"https://doi.org/{a.doi}" if a.doi else "<<DOI: fill in after the Zenodo upload>>"
    bib_doi = f"  doi       = {{{a.doi}}},\n" if a.doi else "  doi       = {<<DOI: fill in after the Zenodo upload>>},\n"
    mtab = ["| machine_id | CPU (as reported) | harness effective cores | logical CPUs | workers | workloads (repetitions) | collected (UTC) | runs |",
            "|---|---|---|---|---|---|---|---|"]
    for r in mach.itertuples():
        mtab.append(f"| `{r.machine_id}` (session {r.session}) | {r.cpu_model} | {r.effective_cores_used_by_harness} | "
                    f"{r.logical_cpus_usable} | {r.workers} | {r.workloads_reps} | {r.collected_utc[:10]} | {r.n_runs} |")
    caveats = "\n\n".join(f"### `{m}`\n\n" + (HERE / "caveats" / f"{m}.md").read_text().strip()
                          for m in dict.fromkeys(mach["machine_id"]))
    tpl = (HERE / "templates" / "dataset_card.md").read_text()
    card = (tpl.replace("{{SIZE_CAT}}", size_cat).replace("{{N_RAW}}", str(n_raw)).replace("{{N_CFG}}", str(n_cfg))
            .replace("{{N_MACH}}", str(mach["machine_id"].nunique())).replace("{{MATRIX_SIZES}}", ", ".join(map(str, msz)))
            .replace("{{SORT_SIZES}}", ", ".join(f"{s:,}" for s in ssz)).replace("{{MACHINE_TABLE}}", "\n".join(mtab))
            .replace("{{CAVEATS}}", caveats).replace("{{VERSION}}", a.version).replace("{{DOI_LINE}}", doi_line)
            .replace("{{BIB_DOI}}", bib_doi).replace("{{REPO}}", REPO).replace("{{GITHUB}}", GITHUB)
            .replace("{{WORKERS_ALL}}", ", ".join(map(str, sorted(set(cfg['workers']))))))
    (out / "README.md").write_text(card)

    # ---- citation + Zenodo metadata ----------------------------------------------------------------------------
    cff = ["cff-version: 1.2.0", 'message: "If you use this dataset, please cite it as below."', "type: dataset",
           'title: "Parallel merge sort and matrix multiplication scaling measurements (Sequential, OpenMP, Pthreads, MPI)"',
           "authors:", "  - family-names: Basharat", "    given-names: Namra",
           '    affiliation: "National University of Sciences and Technology (NUST), School of Interdisciplinary Engineering & Sciences"',
           "license: CC-BY-4.0", f"version: {a.version}", f'repository-code: "{GITHUB}"', f'url: "https://huggingface.co/datasets/{REPO}"']
    if a.doi:
        cff.append(f'doi: "{a.doi}"')
    (out / "CITATION.cff").write_text("\n".join(cff) + "\n")
    zen = {"metadata": {
        "upload_type": "dataset",
        "title": "Parallel merge sort and matrix multiplication scaling measurements (Sequential, OpenMP, Pthreads, MPI)",
        "creators": [{"name": "Basharat, Namra",
                      "affiliation": "National University of Sciences and Technology (NUST), School of Interdisciplinary Engineering & Sciences"}],
        "description": (f"<p>Validated timing measurements of four execution models (sequential, OpenMP, Pthreads, MPI) on merge "
                        f"sort and dense matrix multiplication. {n_raw} recorded runs in {n_cfg} configurations from "
                        f"{mach['machine_id'].nunique()} machine(s). Every run exited cleanly and printed the same output as the "
                        f"sequential program (SHA-256 comparison). Matrix sizes: {', '.join(map(str, msz))}; sort sizes: "
                        f"{', '.join(f'{s:,}' for s in ssz)}; worker counts: "
                        f"{', '.join(map(str, sorted(set(cfg['workers']))))}. Includes raw runs, per-configuration statistics "
                        f"(speedup S_N, efficiency E_N), hardware/software environment files, input checksums and figures. "
                        f"Measurement code: {GITHUB}</p>"),
        "access_right": "open", "license": "cc-by-4.0", "version": a.version, "language": "eng",
        "keywords": ["parallel computing", "benchmark", "OpenMP", "MPI", "Pthreads", "merge sort", "matrix multiplication",
                     "speedup", "parallel efficiency", "reproducibility"],
        "related_identifiers": [
            {"relation": "isSupplementTo", "identifier": GITHUB, "scheme": "url", "resource_type": "software"},
            {"relation": "isAlternateIdentifier", "identifier": f"https://huggingface.co/datasets/{REPO}", "scheme": "url"}]}}
    (out / "zenodo_metadata.json").write_text(json.dumps(zen, indent=2) + "\n")
    for spec in a.extra:
        if "=" not in spec:
            die("--extra needs ID=FILE")
        mid, fp = spec.split("=", 1)
        if mid not in set(mach["machine_id"]) or not Path(fp).is_file():
            die(f"--extra {spec}: unknown machine id or missing file")
        shutil.copy2(fp, out / "machines" / mid / Path(fp).name)
    for sub in ("scripts", "caveats", "templates"):   # the build tool travels with the data, same relative layout
        shutil.copytree(HERE / sub, out / "tools" / sub, ignore=shutil.ignore_patterns("__pycache__"))
    sums = sorted(p for p in out.rglob("*") if p.is_file() and p.name != "SHA256SUMS")
    (out / "SHA256SUMS").write_text("".join(f"{sha(p)}  {p.relative_to(out).as_posix()}\n" for p in sums))
    left = [p for p in [out / "README.md", out / "CITATION.cff"] if "<<" in p.read_text()]
    print(f"built {out}  ({n_raw} runs, {n_cfg} configurations, {len(sums)} files)")
    if left:
        print("NOTE: DOI placeholders remain in", ", ".join(p.name for p in left), "- rebuild with --doi after minting.")


if __name__ == "__main__":
    main()