File size: 6,829 Bytes
779dd0e
 
 
 
8f37329
 
779dd0e
 
 
 
 
 
095f297
779dd0e
 
 
 
 
 
 
 
 
 
8f37329
 
 
 
 
 
 
9de8f1b
 
 
 
 
 
 
 
 
 
 
 
 
7105268
9de8f1b
 
 
8f37329
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
779dd0e
 
 
 
 
 
 
 
 
8f37329
779dd0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e8e4e0
779dd0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f37329
 
 
779dd0e
8f37329
 
779dd0e
 
095f297
 
 
 
 
 
 
 
 
 
 
 
 
 
5711ab3
 
 
 
 
 
 
 
 
 
 
779dd0e
 
 
 
 
 
 
 
8f37329
779dd0e
 
8f37329
779dd0e
 
 
095f297
779dd0e
 
8f37329
779dd0e
 
 
 
 
8f37329
779dd0e
 
 
 
 
 
 
 
5711ab3
779dd0e
 
 
 
 
 
 
 
 
 
 
 
095f297
 
 
 
 
779dd0e
 
 
 
 
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
"""Submit the reviewed translation Job without hard-coding a moving runner SHA.

This launcher is run by an operator with access to the ``hf-doc-build``
namespace. It resolves the current immutable commit of the public runner
dataset, then uses that same SHA for an in-Job snapshot download and the
``RUNNER_REVISION`` manifest field.
"""

from __future__ import annotations

import argparse
import json
import os
import re
from typing import Any


RUNNER_REPOSITORY = "hf-doc-build/translation-runner"
MODEL_REPOSITORY = "google/translategemma-27b-it"
MODEL_REVISION = "7d10f0b72f89a2d0f268cea30727d8b77c0d25c2"
DOC_BUILDER_REVISION = "e60a538eea9817ab312196d0d233604b01697265"
IMAGE = "huggingface/transformers-pytorch-gpu:latest"
NAMESPACE = "hf-doc-build"
RUNNER_LOCAL_DIR = "/tmp/translation-runner"
CONFIG_PATH = f"{RUNNER_LOCAL_DIR}/configs/transformers-ja-job.yml"

BOOTSTRAP = """\
import json
import os
from pathlib import Path
import subprocess
import sys

subprocess.run(
    [
        sys.executable,
        "-m",
        "pip",
        "install",
        "--disable-pip-version-check",
        "--no-cache-dir",
        "--upgrade",
        "huggingface-hub==1.8.0",
        "wheel>=0.38",
    ],
    check=True,
)

from huggingface_hub import snapshot_download


revision = os.environ["RUNNER_REVISION"]
runner = Path(
    snapshot_download(
        repo_id="hf-doc-build/translation-runner",
        repo_type="dataset",
        revision=revision,
        local_dir="/tmp/translation-runner",
        cache_dir="/tmp/runner-download-cache",
        force_download=True,
    )
)
config_path = runner / "configs" / "transformers-ja-job.yml"
if not config_path.is_file():
    raise RuntimeError(f"runner snapshot is incomplete: {config_path}")

runner_arguments = json.loads(os.environ["RUNNER_ARGUMENTS"])
if not isinstance(runner_arguments, list) or not all(isinstance(item, str) for item in runner_arguments):
    raise RuntimeError("RUNNER_ARGUMENTS must be a JSON array of strings")

environment = os.environ.copy()
runner_src = str(runner / "src")
existing_pythonpath = environment.get("PYTHONPATH")
environment["PYTHONPATH"] = os.pathsep.join(
    value for value in (runner_src, existing_pythonpath) if value
)
command = ["python3", "-m", "hf_doc_translation.sync", *runner_arguments]
os.execvpe(command[0], command, environment)
"""


def _runner_revision(api: Any) -> str:
    revision = str(api.dataset_info(RUNNER_REPOSITORY).sha or "")
    if not re.fullmatch(r"[0-9a-f]{40}", revision):
        raise RuntimeError(f"Hub did not return an immutable runner revision: {revision!r}")
    return revision


def _volumes(Volume: Any) -> list[Any]:
    return [
        Volume(type="model", source=MODEL_REPOSITORY, mount_path="/model", revision=MODEL_REVISION, read_only=True),
        Volume(type="bucket", source="hf-doc-build/doc-translation-cache", mount_path="/translation-cache"),
        Volume(
            type="bucket",
            source="hf-doc-build/doc-build-cache",
            mount_path="/doc-build-cache",
            read_only=True,
        ),
    ]


def _common_args() -> list[str]:
    return [
        "--config",
        CONFIG_PATH,
        "--repository",
        "stevhliu/transformers",
        "--base-ref",
        "ja-translation",
        "--environment",
        "staging",
        "--model-path",
        "/model",
        "--cache-dir",
        "/translation-cache",
        "--runner-revision",
        "{runner_revision}",
    ]


def _command_arguments(mode: str, runner_revision: str) -> list[str]:
    arguments = ["smoke-batching"] if mode == "smoke" else []
    arguments.extend(value.format(runner_revision=runner_revision) for value in _common_args())
    if mode == "backfill":
        arguments.append("--force-backfill")
    return arguments


def _github_secrets(mode: str) -> dict[str, str] | None:
    """Read the GitHub credential only from the submitter's environment."""

    if mode not in {"backfill", "schedule"}:
        return None
    token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
    if not token:
        raise RuntimeError(
            "publishing requires GITHUB_TOKEN or GH_TOKEN in the local environment; "
            "the value is passed encrypted to the Job and is never read from the repository"
        )
    return {"GITHUB_TOKEN": token}


def _status_json(job: Any) -> dict[str, str | None] | None:
    status = getattr(job, "status", None)
    if status is None:
        return None
    stage = getattr(status, "stage", None)
    return {
        "stage": getattr(stage, "value", str(stage)) if stage is not None else None,
        "message": getattr(status, "message", None),
    }


def submit(mode: str, soak_complete: bool = False) -> dict[str, Any]:
    from huggingface_hub import HfApi, Volume

    if mode == "schedule" and not soak_complete:
        raise RuntimeError("refusing to enable the daily schedule before the 30-day staging soak is complete")
    api = HfApi()
    runner_revision = _runner_revision(api)
    command_mode = "backfill" if mode in {"backfill", "schedule"} else "smoke"
    runner_arguments = _command_arguments(command_mode, runner_revision)
    environment = {
        "RUNNER_REVISION": runner_revision,
        "RUNNER_ARGUMENTS": json.dumps(runner_arguments),
        "TRANSLATEGEMMA_REVISION": MODEL_REVISION,
        "DOC_BUILDER_REVISION": DOC_BUILDER_REVISION,
    }
    secrets = _github_secrets(mode)
    kwargs = {
        "image": IMAGE,
        "command": ["python3", "-c", BOOTSTRAP],
        "env": environment,
        "secrets": secrets,
        "flavor": "a100-large",
        "timeout": "12h" if command_mode == "backfill" else "2h",
        "labels": {"purpose": "transformers-ja-doc-sync", "environment": "staging"},
        "volumes": _volumes(Volume),
        "namespace": NAMESPACE,
    }
    job = api.create_scheduled_job(schedule="@daily", suspend=False, concurrency=False, **kwargs) if mode == "schedule" else api.run_job(**kwargs)
    return {
        "mode": mode,
        "runner_revision": runner_revision,
        "job_id": getattr(job, "id", None),
        "job_url": getattr(job, "url", None),
        "status": _status_json(job),
    }


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("mode", choices=("smoke", "backfill", "schedule"))
    parser.add_argument(
        "--soak-complete",
        action="store_true",
        help="required safety acknowledgement before enabling the daily schedule",
    )
    args = parser.parse_args()
    try:
        result = submit(args.mode, soak_complete=args.soak_complete)
    except RuntimeError as exc:
        parser.error(str(exc))
    print(json.dumps(result, indent=2, sort_keys=True))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())