File size: 9,796 Bytes
5ee3a5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""๋ฏผ๊ฐํ•œ P corpus๋ฅผ ๊ณต๊ฐœ๋ณธ๊ณผ ๋ถ„๋ฆฌํ•œ ์ œํ’ˆ์šฉ LiteRT Colab bundle์„ ๋งŒ๋“ ๋‹ค."""

from __future__ import annotations

import argparse
from datetime import datetime, timezone
from hashlib import sha256
import json
from pathlib import Path, PurePosixPath
from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile, ZipInfo

import torch

from scripts.export_math_ink_06_p_formula_student import (
    _file_sha25606,
    validate_p_formula_student_artifacts06,
    validate_p_formula_student_export06,
)


PROJECT_ROOT = Path(__file__).parents[1]
MANIFEST_NAME_06 = "P_MOBILE_COLAB_BUNDLE_MANIFEST.json"


def _bundle_files06(
    *,
    base_checkpoint: Path,
    adapter_checkpoint: Path,
    student_checkpoint: Path,
    p_data: Path,
) -> dict[str, Path]:
    """ํ•„์š” ๋ณ€์ˆ˜: P student ์ „์ฒด lineage. ์ž‘๋™ ์›๋ฆฌ: product pair exporter์˜ ๋‹ซํžŒ ์ตœ์†Œ ํŒŒ์ผ ์ง‘ํ•ฉ์„ ๋งŒ๋“ ๋‹ค."""

    data_name = "private/p_formula.jsonl.gz" if p_data.suffix == ".gz" else "private/p_formula.jsonl"
    return {
        "pyproject.toml": PROJECT_ROOT / "pyproject.toml",
        "src/math_grid_drawer/__init__.py": PROJECT_ROOT / "research/colab/litert_bundle_package_init.py",
        "src/math_grid_drawer/research/__init__.py": PROJECT_ROOT / "src/math_grid_drawer/research/__init__.py",
        "src/math_grid_drawer/research/ink06_canonical.py": PROJECT_ROOT / "src/math_grid_drawer/research/ink06_canonical.py",
        "src/math_grid_drawer/research/ink06_export.py": PROJECT_ROOT / "src/math_grid_drawer/research/ink06_export.py",
        "src/math_grid_drawer/research/math_ink_06.py": PROJECT_ROOT / "src/math_grid_drawer/research/math_ink_06.py",
        "src/math_grid_drawer/research/p_formula_dataset06.py": PROJECT_ROOT / "src/math_grid_drawer/research/p_formula_dataset06.py",
        "src/math_grid_drawer/research/p_formula_gate06.py": PROJECT_ROOT / "src/math_grid_drawer/research/p_formula_gate06.py",
        "src/math_grid_drawer/research/raster_skeleton06.py": PROJECT_ROOT / "src/math_grid_drawer/research/raster_skeleton06.py",
        "src/math_grid_drawer/research/skeleton_adapter06.py": PROJECT_ROOT / "src/math_grid_drawer/research/skeleton_adapter06.py",
        "src/math_grid_drawer/research/trajectory_sequence.py": PROJECT_ROOT / "src/math_grid_drawer/research/trajectory_sequence.py",
        "scripts/export_math_ink_06_litert.py": PROJECT_ROOT / "scripts/export_math_ink_06_litert.py",
        "scripts/export_math_ink_06_p_formula_student.py": PROJECT_ROOT / "scripts/export_math_ink_06_p_formula_student.py",
        "scripts/export_math_ink_06_p_mobile_pair.py": PROJECT_ROOT / "scripts/export_math_ink_06_p_mobile_pair.py",
        "artifacts/base_378.pt": base_checkpoint,
        "artifacts/online_adapter.pt": adapter_checkpoint,
        "artifacts/p_formula_student_adapter.pt": student_checkpoint,
        data_name: p_data,
    }


def build_p_mobile_colab_bundle06(
    *,
    base_checkpoint: Path,
    adapter_checkpoint: Path,
    student_checkpoint: Path,
    p_data: Path,
    output: Path,
) -> dict:
    """ํ•„์š” ๋ณ€์ˆ˜: P model/dataยท์ถœ๋ ฅ. ์ž‘๋™ ์›๋ฆฌ: hash ๊ฒ€์ฆ ํ›„ ๊ณต๊ฐœ ๊ธˆ์ง€ private Colab archive๋ฅผ ๊ฒฐ์ •์ ์œผ๋กœ ๋งŒ๋“ ๋‹ค."""

    for path in (base_checkpoint, adapter_checkpoint, student_checkpoint, p_data):
        if not path.is_file():
            raise FileNotFoundError(f"์ œํ’ˆ Colab bundle ํ•„์ˆ˜ ํŒŒ์ผ์ด ์—†์Šต๋‹ˆ๋‹ค: {path}")
    student = torch.load(student_checkpoint, map_location="cpu", weights_only=False)
    data_sha256 = _file_sha25606(p_data)
    validate_p_formula_student_export06(student, data_sha256=data_sha256)
    validate_p_formula_student_artifacts06(
        student,
        base_checkpoint=base_checkpoint,
        online_adapter=adapter_checkpoint,
    )
    files = _bundle_files06(
        base_checkpoint=base_checkpoint,
        adapter_checkpoint=adapter_checkpoint,
        student_checkpoint=student_checkpoint,
        p_data=p_data,
    )
    missing = [name for name, path in files.items() if not path.is_file()]
    if missing:
        raise FileNotFoundError(f"์ œํ’ˆ Colab source๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค: {missing}")
    payloads = {name: path.read_bytes() for name, path in files.items()}
    data_name = next(name for name in payloads if name.startswith("private/"))
    manifest = {
        "schema": "aiflow-math-ink-06-p-mobile-colab-bundle-v1",
        "generated_at": datetime.now(timezone.utc).isoformat(),
        "litert_torch_version": "0.9.1",
        "data_sha256": data_sha256,
        "teacher_seeds": [17, 31, 47],
        "privacy": {
            "contains_p_data": True,
            "public_upload_allowed": False,
            "server_upload_permitted": False,
        },
        "raster_output_count": 5,
        "command": [
            "python",
            "scripts/export_math_ink_06_p_mobile_pair.py",
            "--student-checkpoint",
            "artifacts/p_formula_student_adapter.pt",
            "--base-checkpoint",
            "artifacts/base_378.pt",
            "--adapter-checkpoint",
            "artifacts/online_adapter.pt",
            "--data",
            data_name,
            "--output",
            "outputs",
            "--convert-litert",
        ],
        "files": [
            {
                "path": name,
                "bytes": len(payload),
                "sha256": sha256(payload).hexdigest(),
            }
            for name, payload in payloads.items()
        ],
        "product_validation": False,
    }
    output.parent.mkdir(parents=True, exist_ok=True)
    temporary = output.with_suffix(output.suffix + ".part")
    with ZipFile(temporary, "w", allowZip64=True) as bundle:
        for name, payload in payloads.items():
            compression = (
                ZIP_STORED
                if PurePosixPath(name).suffix in {".pt", ".gz"}
                else ZIP_DEFLATED
            )
            info = ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0))
            info.compress_type = compression
            info.external_attr = 0o600 << 16 if name.startswith("private/") else 0o644 << 16
            bundle.writestr(info, payload)
        info = ZipInfo(MANIFEST_NAME_06, date_time=(1980, 1, 1, 0, 0, 0))
        info.compress_type = ZIP_DEFLATED
        info.external_attr = 0o600 << 16
        bundle.writestr(
            info,
            json.dumps(manifest, ensure_ascii=False, indent=2).encode("utf-8") + b"\n",
        )
    temporary.replace(output)
    manifest["bundle"] = str(output)
    manifest["bundle_bytes"] = output.stat().st_size
    manifest["bundle_sha256"] = sha256(output.read_bytes()).hexdigest()
    return manifest


def verify_p_mobile_colab_bundle06(bundle_path: Path) -> dict:
    """ํ•„์š” ๋ณ€์ˆ˜: private bundle. ์ž‘๋™ ์›๋ฆฌ: ์•ˆ์ „ ๊ฒฝ๋กœยทhashยทprivacy fail-closed ๊ณ„์•ฝ์„ ์ถ”์ถœ ์—†์ด ๊ฒ€์‚ฌํ•œ๋‹ค."""

    failures = []
    with ZipFile(bundle_path) as bundle:
        manifest = json.loads(bundle.read(MANIFEST_NAME_06).decode("utf-8"))
        privacy = manifest.get("privacy") or {}
        if privacy != {
            "contains_p_data": True,
            "public_upload_allowed": False,
            "server_upload_permitted": False,
        }:
            failures.append({"path": MANIFEST_NAME_06, "reason": "privacy_contract"})
        if int(manifest.get("raster_output_count", 0)) != 5:
            failures.append({"path": MANIFEST_NAME_06, "reason": "raster_output_count"})
        names = set(bundle.namelist())
        for row in manifest.get("files", []):
            name = str(row.get("path") or "")
            path = PurePosixPath(name)
            if path.is_absolute() or ".." in path.parts:
                failures.append({"path": name, "reason": "unsafe_path"})
            elif name not in names:
                failures.append({"path": name, "reason": "missing"})
            else:
                payload = bundle.read(name)
                if len(payload) != int(row["bytes"]):
                    failures.append({"path": name, "reason": "bytes"})
                elif sha256(payload).hexdigest() != str(row["sha256"]):
                    failures.append({"path": name, "reason": "sha256"})
    return {
        "schema": manifest.get("schema"),
        "files": len(manifest.get("files", [])),
        "failures": failures,
        "passed": not failures,
        "public_upload_allowed": False,
        "product_validation": False,
    }


def main() -> None:
    """ํ•„์š” ๋ณ€์ˆ˜: ์‹ค์ œ P lineageยท์ถœ๋ ฅ. ์ž‘๋™ ์›๋ฆฌ: private bundle ์ƒ์„ฑ ์งํ›„ archive๋ฅผ ์žฌ๊ฒ€์ฆํ•œ๋‹ค."""

    parser = argparse.ArgumentParser(description="Build private P mobile Colab bundle")
    parser.add_argument("--base-checkpoint", type=Path, required=True)
    parser.add_argument("--adapter-checkpoint", type=Path, required=True)
    parser.add_argument("--student-checkpoint", type=Path, required=True)
    parser.add_argument("--p-data", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    report = build_p_mobile_colab_bundle06(
        base_checkpoint=args.base_checkpoint,
        adapter_checkpoint=args.adapter_checkpoint,
        student_checkpoint=args.student_checkpoint,
        p_data=args.p_data,
        output=args.output,
    )
    report["verification"] = verify_p_mobile_colab_bundle06(args.output)
    if not report["verification"]["passed"]:
        raise ValueError(f"์ œํ’ˆ Colab bundle ๊ฒ€์ฆ ์‹คํŒจ: {report['verification']['failures']}")
    report_path = args.output.with_suffix(args.output.suffix + ".manifest.json")
    report_path.write_text(
        json.dumps(report, ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
    )
    print(json.dumps(report, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()