inertia-client 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- inertia_client-0.1.0/.gitignore +10 -0
- inertia_client-0.1.0/LICENSE +29 -0
- inertia_client-0.1.0/PKG-INFO +63 -0
- inertia_client-0.1.0/README.md +43 -0
- inertia_client-0.1.0/pyproject.toml +33 -0
- inertia_client-0.1.0/src/inertia_client/__init__.py +5 -0
- inertia_client-0.1.0/src/inertia_client/client.py +607 -0
- inertia_client-0.1.0/tests/test_client.py +380 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
BSD 3-Clause License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026, Arthur Lacote
|
|
4
|
+
All rights reserved.
|
|
5
|
+
|
|
6
|
+
Redistribution and use in source and binary forms, with or without
|
|
7
|
+
modification, are permitted provided that the following conditions are met:
|
|
8
|
+
|
|
9
|
+
* Redistributions of source code must retain the above copyright notice, this
|
|
10
|
+
list of conditions and the following disclaimer.
|
|
11
|
+
|
|
12
|
+
* Redistributions in binary form must reproduce the above copyright notice,
|
|
13
|
+
this list of conditions and the following disclaimer in the documentation
|
|
14
|
+
and/or other materials provided with the distribution.
|
|
15
|
+
|
|
16
|
+
* Neither the name of the copyright holder nor the names of its
|
|
17
|
+
contributors may be used to endorse or promote products derived from
|
|
18
|
+
this software without specific prior written permission.
|
|
19
|
+
|
|
20
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
21
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
22
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
23
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
24
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
25
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
26
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
27
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
28
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
29
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: inertia-client
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Submit labels to the inertia challenge, a scoreboard for k-means
|
|
5
|
+
Project-URL: Homepage, https://github.com/cakedev0/the-inertia-challenge
|
|
6
|
+
Project-URL: Issues, https://github.com/cakedev0/the-inertia-challenge/issues
|
|
7
|
+
Author: Arthur Lacote
|
|
8
|
+
License-Expression: BSD-3-Clause
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: benchmark,clustering,inertia,k-means
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Requires-Dist: inertia-scorer>=0.1.0
|
|
16
|
+
Requires-Dist: numpy
|
|
17
|
+
Provides-Extra: test
|
|
18
|
+
Requires-Dist: pytest; extra == 'test'
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# inertia-client
|
|
22
|
+
|
|
23
|
+
Submit labels to [the inertia challenge](../../README.md): `inertia-client` and
|
|
24
|
+
the `inertia_client` Python package.
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
inertia-client login
|
|
28
|
+
inertia-client submit sift_128 sift_128.npz --time 100=23.21 --hardware "M2, 8 cores" --tag algorithm=Lloyd
|
|
29
|
+
inertia-client status <id> --wait
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
`login` identifies you with GitHub. It gives a code to enter on github.com and
|
|
33
|
+
keeps a token in `~/.config/the-inertia-challenge/github-token`. The token can
|
|
34
|
+
only tell who you are: it gives no access to your repositories.
|
|
35
|
+
|
|
36
|
+
`submit` checks the file as the server will, without the dataset, then asks
|
|
37
|
+
before sending it: the server takes one submission per day and per dataset.
|
|
38
|
+
`check` only does the check. An upload that was stopped resumes with
|
|
39
|
+
`inertia-client resume <id> FILE`, for 6 hours.
|
|
40
|
+
|
|
41
|
+
`--time`, `--hardware` and `--tag` are what you say about the submission. They
|
|
42
|
+
are shown on the scoreboard as you give them. The time is for one number of
|
|
43
|
+
clusters: give `--time` once for each of them.
|
|
44
|
+
|
|
45
|
+
`--submit-only-improvement` scores the labels on your side (with
|
|
46
|
+
`inertia-scorer`, so the dataset must be downloaded, see `--data-dir`) and
|
|
47
|
+
compares each number of clusters to your best published score on the
|
|
48
|
+
scoreboard. The numbers of clusters that do not improve on it are not sent, and
|
|
49
|
+
nothing is sent when none does. A number of clusters where you have no score yet
|
|
50
|
+
is sent. Your scores are the ones of your GitHub login, and only the scores that
|
|
51
|
+
the listener published count: the ones less than 10% above the best.
|
|
52
|
+
|
|
53
|
+
From Python:
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
import inertia_client
|
|
57
|
+
|
|
58
|
+
inertia_client.submit(
|
|
59
|
+
"sift_128", {100: labels}, time_s={100: 23.21}, hardware="M2, 8 cores"
|
|
60
|
+
)
|
|
61
|
+
# Only the numbers of clusters that beat your best score; None if none does.
|
|
62
|
+
inertia_client.submit("sift_128", {100: labels}, submit_only_improvement=True)
|
|
63
|
+
```
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# inertia-client
|
|
2
|
+
|
|
3
|
+
Submit labels to [the inertia challenge](../../README.md): `inertia-client` and
|
|
4
|
+
the `inertia_client` Python package.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
inertia-client login
|
|
8
|
+
inertia-client submit sift_128 sift_128.npz --time 100=23.21 --hardware "M2, 8 cores" --tag algorithm=Lloyd
|
|
9
|
+
inertia-client status <id> --wait
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
`login` identifies you with GitHub. It gives a code to enter on github.com and
|
|
13
|
+
keeps a token in `~/.config/the-inertia-challenge/github-token`. The token can
|
|
14
|
+
only tell who you are: it gives no access to your repositories.
|
|
15
|
+
|
|
16
|
+
`submit` checks the file as the server will, without the dataset, then asks
|
|
17
|
+
before sending it: the server takes one submission per day and per dataset.
|
|
18
|
+
`check` only does the check. An upload that was stopped resumes with
|
|
19
|
+
`inertia-client resume <id> FILE`, for 6 hours.
|
|
20
|
+
|
|
21
|
+
`--time`, `--hardware` and `--tag` are what you say about the submission. They
|
|
22
|
+
are shown on the scoreboard as you give them. The time is for one number of
|
|
23
|
+
clusters: give `--time` once for each of them.
|
|
24
|
+
|
|
25
|
+
`--submit-only-improvement` scores the labels on your side (with
|
|
26
|
+
`inertia-scorer`, so the dataset must be downloaded, see `--data-dir`) and
|
|
27
|
+
compares each number of clusters to your best published score on the
|
|
28
|
+
scoreboard. The numbers of clusters that do not improve on it are not sent, and
|
|
29
|
+
nothing is sent when none does. A number of clusters where you have no score yet
|
|
30
|
+
is sent. Your scores are the ones of your GitHub login, and only the scores that
|
|
31
|
+
the listener published count: the ones less than 10% above the best.
|
|
32
|
+
|
|
33
|
+
From Python:
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
import inertia_client
|
|
37
|
+
|
|
38
|
+
inertia_client.submit(
|
|
39
|
+
"sift_128", {100: labels}, time_s={100: 23.21}, hardware="M2, 8 cores"
|
|
40
|
+
)
|
|
41
|
+
# Only the numbers of clusters that beat your best score; None if none does.
|
|
42
|
+
inertia_client.submit("sift_128", {100: labels}, submit_only_improvement=True)
|
|
43
|
+
```
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "inertia-client"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Submit labels to the inertia challenge, a scoreboard for k-means"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "BSD-3-Clause"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
authors = [{ name = "Arthur Lacote" }]
|
|
14
|
+
keywords = ["k-means", "clustering", "benchmark", "inertia"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Intended Audience :: Science/Research",
|
|
18
|
+
"Topic :: Scientific/Engineering",
|
|
19
|
+
]
|
|
20
|
+
dependencies = ["inertia-scorer>=0.1.0", "numpy"]
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
Homepage = "https://github.com/cakedev0/the-inertia-challenge"
|
|
24
|
+
Issues = "https://github.com/cakedev0/the-inertia-challenge/issues"
|
|
25
|
+
|
|
26
|
+
[project.optional-dependencies]
|
|
27
|
+
test = ["pytest"]
|
|
28
|
+
|
|
29
|
+
[project.scripts]
|
|
30
|
+
inertia-client = "inertia_client.client:main"
|
|
31
|
+
|
|
32
|
+
[tool.hatch.build.targets.wheel]
|
|
33
|
+
packages = ["src/inertia_client"]
|
|
@@ -0,0 +1,607 @@
|
|
|
1
|
+
"""Submit labels to the inertia challenge.
|
|
2
|
+
|
|
3
|
+
inertia-client login
|
|
4
|
+
inertia-client submit sift_128 sift_128.npz --time 100=23.21 --hardware M2
|
|
5
|
+
inertia-client status <id> --wait
|
|
6
|
+
|
|
7
|
+
A submission is a `.npz` file for one dataset, as for `inertia-score`: one
|
|
8
|
+
uint32 array of labels per number of clusters. The server takes one submission
|
|
9
|
+
per day and per dataset from a user, so `submit` first checks the file as the
|
|
10
|
+
server will, and asks before sending.
|
|
11
|
+
|
|
12
|
+
`login` identifies you with GitHub: it gives a code to enter on github.com, and
|
|
13
|
+
keeps a token that can only tell who you are (no access to your repositories).
|
|
14
|
+
From Python:
|
|
15
|
+
|
|
16
|
+
import inertia_client
|
|
17
|
+
|
|
18
|
+
inertia_client.submit("sift_128", {100: labels}, time_s={100: 23.21}, hardware="M2")
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import argparse
|
|
24
|
+
import json
|
|
25
|
+
import os
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
import sys
|
|
28
|
+
import tempfile
|
|
29
|
+
import time
|
|
30
|
+
import urllib.error
|
|
31
|
+
import urllib.parse
|
|
32
|
+
import urllib.request
|
|
33
|
+
import zipfile
|
|
34
|
+
|
|
35
|
+
import numpy as np
|
|
36
|
+
|
|
37
|
+
from inertia_scorer.challenge import Reader, get_dataset
|
|
38
|
+
from inertia_scorer.score import check_labels, read_labels, score_all
|
|
39
|
+
|
|
40
|
+
DEFAULT_SERVER = "https://the-inertia-challenge-server.arthur-lacote.workers.dev"
|
|
41
|
+
SERVER_VARIABLE = "INERTIA_SERVER"
|
|
42
|
+
TOKEN_VARIABLE = "INERTIA_GITHUB_TOKEN"
|
|
43
|
+
GITHUB = "https://github.com"
|
|
44
|
+
GITHUB_API = "https://api.github.com"
|
|
45
|
+
# The scores that the listener published, one file per dataset.
|
|
46
|
+
RESULTS_URL = (
|
|
47
|
+
"https://raw.githubusercontent.com/cakedev0/the-inertia-challenge/results/scores"
|
|
48
|
+
)
|
|
49
|
+
DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code"
|
|
50
|
+
# Times a part is sent again when the connection or the server fails.
|
|
51
|
+
RETRIES = 4
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class ServerError(RuntimeError):
|
|
55
|
+
"""The server refused a request. `status` is the HTTP status."""
|
|
56
|
+
|
|
57
|
+
def __init__(self, status: int, message: str, retry_after: int | None = None):
|
|
58
|
+
super().__init__(message)
|
|
59
|
+
self.status = status
|
|
60
|
+
self.retry_after = retry_after
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def token_path() -> Path:
|
|
64
|
+
config = os.environ.get("XDG_CONFIG_HOME") or "~/.config"
|
|
65
|
+
return Path(config).expanduser() / "the-inertia-challenge" / "github-token"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def check_submission(dataset_name: str, path) -> list[int]:
|
|
69
|
+
"""Check the `.npz` file `path` as the server will, without the dataset.
|
|
70
|
+
Return its numbers of clusters. Raise a ValueError if it would be rejected."""
|
|
71
|
+
dataset = get_dataset(dataset_name)
|
|
72
|
+
n_clusters = []
|
|
73
|
+
try:
|
|
74
|
+
for k, labels in read_labels(dataset, path):
|
|
75
|
+
try:
|
|
76
|
+
check_labels(labels, k, dataset.n_samples)
|
|
77
|
+
except ValueError as error:
|
|
78
|
+
raise ValueError(f"For {k} clusters: {error}") from None
|
|
79
|
+
n_clusters.append(k)
|
|
80
|
+
except zipfile.BadZipFile:
|
|
81
|
+
raise ValueError(f"{path} is not a .npz file.") from None
|
|
82
|
+
return n_clusters
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def save_labels(path, labels: dict) -> None:
|
|
86
|
+
"""Write `labels`, {n_clusters: array of labels}, as a submission."""
|
|
87
|
+
arrays = {}
|
|
88
|
+
for n_clusters, array in labels.items():
|
|
89
|
+
array = np.asarray(array)
|
|
90
|
+
if array.dtype != np.uint32:
|
|
91
|
+
if array.dtype.kind not in "iu" or (array.size and array.min() < 0):
|
|
92
|
+
raise ValueError(
|
|
93
|
+
f"The labels for {n_clusters} clusters are not non-negative "
|
|
94
|
+
f"integers (dtype {array.dtype})."
|
|
95
|
+
)
|
|
96
|
+
array = array.astype(np.uint32)
|
|
97
|
+
arrays[str(int(n_clusters))] = array
|
|
98
|
+
np.savez(path, **arrays)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class Client:
|
|
102
|
+
"""The server of the challenge, for a user.
|
|
103
|
+
|
|
104
|
+
The server is `server`, else $INERTIA_SERVER, else the one of the
|
|
105
|
+
challenge. The GitHub token is `token`, else $INERTIA_GITHUB_TOKEN, else
|
|
106
|
+
the one that `login` saved.
|
|
107
|
+
"""
|
|
108
|
+
|
|
109
|
+
def __init__(
|
|
110
|
+
self,
|
|
111
|
+
server=None,
|
|
112
|
+
token=None,
|
|
113
|
+
github=GITHUB,
|
|
114
|
+
timeout=120.0,
|
|
115
|
+
github_api=GITHUB_API,
|
|
116
|
+
results_url=RESULTS_URL,
|
|
117
|
+
):
|
|
118
|
+
server = server or os.environ.get(SERVER_VARIABLE) or DEFAULT_SERVER
|
|
119
|
+
self.server = server.rstrip("/")
|
|
120
|
+
url = urllib.parse.urlsplit(self.server)
|
|
121
|
+
if url.scheme != "https" and url.hostname not in ("localhost", "127.0.0.1"):
|
|
122
|
+
raise ValueError(f"The server must be in https, got {self.server}.")
|
|
123
|
+
self._token = token or os.environ.get(TOKEN_VARIABLE)
|
|
124
|
+
self.github = github
|
|
125
|
+
self.github_api = github_api.rstrip("/")
|
|
126
|
+
self.results_url = results_url.rstrip("/")
|
|
127
|
+
self.timeout = timeout
|
|
128
|
+
|
|
129
|
+
@property
|
|
130
|
+
def token(self) -> str:
|
|
131
|
+
if not self._token:
|
|
132
|
+
path = token_path()
|
|
133
|
+
if not path.is_file():
|
|
134
|
+
raise RuntimeError("You are not logged in. Run: inertia-client login")
|
|
135
|
+
self._token = path.read_text().strip()
|
|
136
|
+
return self._token
|
|
137
|
+
|
|
138
|
+
def _request(self, method, path, body=None, raw=None, auth=True) -> dict:
|
|
139
|
+
headers = {"User-Agent": "inertia-client"}
|
|
140
|
+
if auth:
|
|
141
|
+
headers["Authorization"] = f"Bearer {self.token}"
|
|
142
|
+
data = raw
|
|
143
|
+
if body is not None:
|
|
144
|
+
data = json.dumps(body).encode()
|
|
145
|
+
headers["Content-Type"] = "application/json"
|
|
146
|
+
request = urllib.request.Request(
|
|
147
|
+
f"{self.server}{path}", data=data, method=method, headers=headers
|
|
148
|
+
)
|
|
149
|
+
try:
|
|
150
|
+
with urllib.request.urlopen(request, timeout=self.timeout) as response:
|
|
151
|
+
return json.load(response)
|
|
152
|
+
except urllib.error.HTTPError as error:
|
|
153
|
+
try:
|
|
154
|
+
message = json.load(error)["error"]
|
|
155
|
+
except (ValueError, KeyError, TypeError):
|
|
156
|
+
message = f"The server answered {error.code}."
|
|
157
|
+
if error.code == 401:
|
|
158
|
+
message += " Run: inertia-client login"
|
|
159
|
+
retry_after = error.headers.get("Retry-After")
|
|
160
|
+
raise ServerError(
|
|
161
|
+
error.code, message, int(retry_after) if retry_after else None
|
|
162
|
+
) from None
|
|
163
|
+
|
|
164
|
+
# Login
|
|
165
|
+
|
|
166
|
+
def _github(self, path: str, **fields) -> dict:
|
|
167
|
+
request = urllib.request.Request(
|
|
168
|
+
f"{self.github}{path}",
|
|
169
|
+
data=urllib.parse.urlencode(fields).encode(),
|
|
170
|
+
headers={"Accept": "application/json", "User-Agent": "inertia-client"},
|
|
171
|
+
)
|
|
172
|
+
with urllib.request.urlopen(request, timeout=self.timeout) as response:
|
|
173
|
+
return json.load(response)
|
|
174
|
+
|
|
175
|
+
def login(self, show=print, save=True) -> str:
|
|
176
|
+
"""Identify the user with the device flow of GitHub: `show` gets the
|
|
177
|
+
code to enter on github.com. Return the token, saved for the next
|
|
178
|
+
calls."""
|
|
179
|
+
client_id = self._request("GET", "/", auth=False)["github_client_id"]
|
|
180
|
+
# No scope: the token only says who the user is.
|
|
181
|
+
device = self._github("/login/device/code", client_id=client_id)
|
|
182
|
+
show(
|
|
183
|
+
f"Open {device['verification_uri']} and enter the code "
|
|
184
|
+
f"{device['user_code']}\nWaiting for you there..."
|
|
185
|
+
)
|
|
186
|
+
interval = device.get("interval", 5)
|
|
187
|
+
deadline = time.monotonic() + device.get("expires_in", 900)
|
|
188
|
+
while time.monotonic() < deadline:
|
|
189
|
+
time.sleep(interval)
|
|
190
|
+
answer = self._github(
|
|
191
|
+
"/login/oauth/access_token",
|
|
192
|
+
client_id=client_id,
|
|
193
|
+
device_code=device["device_code"],
|
|
194
|
+
grant_type=DEVICE_GRANT,
|
|
195
|
+
)
|
|
196
|
+
if "access_token" in answer:
|
|
197
|
+
self._token = answer["access_token"]
|
|
198
|
+
if save:
|
|
199
|
+
path = token_path()
|
|
200
|
+
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
201
|
+
# Created for the user only, before the token is in it.
|
|
202
|
+
descriptor = os.open(
|
|
203
|
+
path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600
|
|
204
|
+
)
|
|
205
|
+
with os.fdopen(descriptor, "w") as file:
|
|
206
|
+
file.write(self._token + "\n")
|
|
207
|
+
return self._token
|
|
208
|
+
error = answer.get("error")
|
|
209
|
+
if error == "slow_down":
|
|
210
|
+
interval = answer.get("interval", interval + 5)
|
|
211
|
+
elif error != "authorization_pending":
|
|
212
|
+
raise RuntimeError(
|
|
213
|
+
f"GitHub refused the login: "
|
|
214
|
+
f"{answer.get('error_description') or error}"
|
|
215
|
+
)
|
|
216
|
+
raise RuntimeError("The code expired before it was entered.")
|
|
217
|
+
|
|
218
|
+
# Submissions
|
|
219
|
+
|
|
220
|
+
def user(self) -> str:
|
|
221
|
+
"""The GitHub login of the user, which is the user of the scores."""
|
|
222
|
+
request = urllib.request.Request(
|
|
223
|
+
f"{self.github_api}/user",
|
|
224
|
+
headers={
|
|
225
|
+
"Authorization": f"Bearer {self.token}",
|
|
226
|
+
"Accept": "application/vnd.github+json",
|
|
227
|
+
"User-Agent": "inertia-client",
|
|
228
|
+
},
|
|
229
|
+
)
|
|
230
|
+
try:
|
|
231
|
+
with urllib.request.urlopen(request, timeout=self.timeout) as response:
|
|
232
|
+
return json.load(response)["login"]
|
|
233
|
+
except urllib.error.HTTPError as error:
|
|
234
|
+
raise RuntimeError(
|
|
235
|
+
f"GitHub did not say who you are ({error.code}). "
|
|
236
|
+
"Run: inertia-client login"
|
|
237
|
+
) from None
|
|
238
|
+
|
|
239
|
+
def best_inertia(self, dataset: str, user: str | None = None) -> dict[int, float]:
|
|
240
|
+
"""The lowest inertia of the user on the scoreboard for each number of
|
|
241
|
+
clusters of `dataset`, as {n_clusters: inertia}. The user is `user`, else
|
|
242
|
+
the one of the token. Only the scores that the listener published count
|
|
243
|
+
(the ones that are not far above the best of everyone), so a number of
|
|
244
|
+
clusters can be missing."""
|
|
245
|
+
user = user or self.user()
|
|
246
|
+
request = urllib.request.Request(
|
|
247
|
+
f"{self.results_url}/{urllib.parse.quote(dataset)}.jsonl",
|
|
248
|
+
headers={"User-Agent": "inertia-client", "Cache-Control": "no-cache"},
|
|
249
|
+
)
|
|
250
|
+
try:
|
|
251
|
+
with urllib.request.urlopen(request, timeout=self.timeout) as response:
|
|
252
|
+
lines = response.read().decode().splitlines()
|
|
253
|
+
except urllib.error.HTTPError as error:
|
|
254
|
+
if error.code == 404: # no score yet for this dataset
|
|
255
|
+
return {}
|
|
256
|
+
raise RuntimeError(
|
|
257
|
+
f"Could not read the scores of {dataset} ({error.code})."
|
|
258
|
+
) from None
|
|
259
|
+
best: dict[int, float] = {}
|
|
260
|
+
for line in filter(None, lines):
|
|
261
|
+
score = json.loads(line)
|
|
262
|
+
if score.get("user") == user:
|
|
263
|
+
k, inertia = int(score["n_clusters"]), float(score["inertia"])
|
|
264
|
+
best[k] = min(inertia, best.get(k, inertia))
|
|
265
|
+
return best
|
|
266
|
+
|
|
267
|
+
def improvements(
|
|
268
|
+
self, dataset: str, path, *, data_dir=None
|
|
269
|
+
) -> dict[int, float | None]:
|
|
270
|
+
"""Score the submission `path` here and compare it to the best of the
|
|
271
|
+
user. Return {n_clusters: best} for the numbers of clusters that improve
|
|
272
|
+
on it, where `best` is the previous best inertia, None if there is none.
|
|
273
|
+
The dataset must be downloaded, see `inertia-download`."""
|
|
274
|
+
reader = Reader(get_dataset(dataset), data_dir)
|
|
275
|
+
best = self.best_inertia(dataset)
|
|
276
|
+
labels = dict(read_labels(reader.dataset, path))
|
|
277
|
+
improved = {}
|
|
278
|
+
for score in score_all(reader, labels):
|
|
279
|
+
previous = best.get(score.n_clusters)
|
|
280
|
+
if previous is None or score.inertia < previous:
|
|
281
|
+
improved[score.n_clusters] = previous
|
|
282
|
+
return improved
|
|
283
|
+
|
|
284
|
+
def submit(
|
|
285
|
+
self,
|
|
286
|
+
dataset: str,
|
|
287
|
+
labels,
|
|
288
|
+
*,
|
|
289
|
+
time_s: dict[int, float] | None = None,
|
|
290
|
+
hardware: str | None = None,
|
|
291
|
+
tags: dict[str, str] | None = None,
|
|
292
|
+
progress=None,
|
|
293
|
+
submit_only_improvement: bool = False,
|
|
294
|
+
data_dir=None,
|
|
295
|
+
log=None,
|
|
296
|
+
) -> dict | None:
|
|
297
|
+
"""Check and send a submission. Return it as the server sees it.
|
|
298
|
+
|
|
299
|
+
`labels` is a `.npz` file, or {n_clusters: array of labels}. `time_s`,
|
|
300
|
+
`hardware` and `tags` are what you say about it: how long the
|
|
301
|
+
clustering took for each number of clusters, as {n_clusters: seconds},
|
|
302
|
+
on what, and free text as {"algorithm": "Lloyd"}.
|
|
303
|
+
`progress(done, total)` is called after each part, in bytes.
|
|
304
|
+
|
|
305
|
+
With `submit_only_improvement`, the labels are first scored here, on the
|
|
306
|
+
dataset of `data_dir` (see `inertia-download`), and compared to the best
|
|
307
|
+
score of the user on the scoreboard: the numbers of clusters that do not
|
|
308
|
+
improve on it are not sent, and `log(message)` says which. When none
|
|
309
|
+
improves, nothing is sent and the result is None.
|
|
310
|
+
"""
|
|
311
|
+
if isinstance(labels, dict):
|
|
312
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
313
|
+
path = Path(directory) / f"{dataset}.npz"
|
|
314
|
+
save_labels(path, labels)
|
|
315
|
+
return self.submit(
|
|
316
|
+
dataset,
|
|
317
|
+
path,
|
|
318
|
+
time_s=time_s,
|
|
319
|
+
hardware=hardware,
|
|
320
|
+
tags=tags,
|
|
321
|
+
progress=progress,
|
|
322
|
+
submit_only_improvement=submit_only_improvement,
|
|
323
|
+
data_dir=data_dir,
|
|
324
|
+
log=log,
|
|
325
|
+
)
|
|
326
|
+
path = Path(labels)
|
|
327
|
+
n_clusters = check_submission(dataset, path)
|
|
328
|
+
if submit_only_improvement:
|
|
329
|
+
improved = self.improvements(dataset, path, data_dir=data_dir)
|
|
330
|
+
for k in n_clusters:
|
|
331
|
+
if log:
|
|
332
|
+
previous = improved.get(k)
|
|
333
|
+
log(
|
|
334
|
+
f"{k} clusters: "
|
|
335
|
+
+ (
|
|
336
|
+
"not sent, no improvement."
|
|
337
|
+
if k not in improved
|
|
338
|
+
else "sent, no score yet."
|
|
339
|
+
if previous is None
|
|
340
|
+
else f"sent, improves on {previous:.9e}."
|
|
341
|
+
)
|
|
342
|
+
)
|
|
343
|
+
if not improved:
|
|
344
|
+
return None
|
|
345
|
+
if len(improved) < len(n_clusters):
|
|
346
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
347
|
+
kept = Path(directory) / f"{dataset}.npz"
|
|
348
|
+
save_labels(
|
|
349
|
+
kept,
|
|
350
|
+
{
|
|
351
|
+
k: array
|
|
352
|
+
for k, array in read_labels(get_dataset(dataset), path)
|
|
353
|
+
if k in improved
|
|
354
|
+
},
|
|
355
|
+
)
|
|
356
|
+
# The times of the numbers of clusters that are not sent go.
|
|
357
|
+
skipped = set(n_clusters) - set(improved)
|
|
358
|
+
return self.submit(
|
|
359
|
+
dataset,
|
|
360
|
+
kept,
|
|
361
|
+
time_s=time_s
|
|
362
|
+
and {k: s for k, s in time_s.items() if int(k) not in skipped},
|
|
363
|
+
hardware=hardware,
|
|
364
|
+
tags=tags,
|
|
365
|
+
progress=progress,
|
|
366
|
+
)
|
|
367
|
+
body = {"dataset": dataset, "size": path.stat().st_size}
|
|
368
|
+
if time_s:
|
|
369
|
+
if not isinstance(time_s, dict):
|
|
370
|
+
raise ValueError(
|
|
371
|
+
"`time_s` is the time for each number of clusters, as "
|
|
372
|
+
f"{{{n_clusters[0]}: 23.21}}, got {time_s!r}."
|
|
373
|
+
)
|
|
374
|
+
unknown = sorted(set(map(int, time_s)) - set(n_clusters))
|
|
375
|
+
if unknown:
|
|
376
|
+
raise ValueError(
|
|
377
|
+
f"There is a time for {', '.join(map(str, unknown))} clusters, "
|
|
378
|
+
"but no labels."
|
|
379
|
+
)
|
|
380
|
+
body["time_s"] = {str(int(k)): float(s) for k, s in time_s.items()}
|
|
381
|
+
if hardware is not None:
|
|
382
|
+
body["hardware"] = hardware
|
|
383
|
+
if tags:
|
|
384
|
+
body["tags"] = tags
|
|
385
|
+
created = self._request("POST", "/submissions", body)
|
|
386
|
+
return self.upload(created["id"], path, progress)
|
|
387
|
+
|
|
388
|
+
def upload(self, submission_id: str, path, progress=None) -> dict:
|
|
389
|
+
"""Send the parts of `path` that the server does not have, and complete
|
|
390
|
+
the submission. Also resumes an upload that was stopped."""
|
|
391
|
+
path = Path(path)
|
|
392
|
+
submission = self.status(submission_id)
|
|
393
|
+
if submission["status"] != "uploading":
|
|
394
|
+
return submission
|
|
395
|
+
size, part_size = submission["size"], submission["part_size"]
|
|
396
|
+
if path.stat().st_size != size:
|
|
397
|
+
raise ValueError(
|
|
398
|
+
f"{path} has {path.stat().st_size} bytes, the submission has {size}."
|
|
399
|
+
)
|
|
400
|
+
uploaded = set(submission["uploaded_parts"])
|
|
401
|
+
done = sum(min(part_size, size - (part - 1) * part_size) for part in uploaded)
|
|
402
|
+
with open(path, "rb") as file:
|
|
403
|
+
for part in range(1, submission["n_parts"] + 1):
|
|
404
|
+
if part in uploaded:
|
|
405
|
+
continue
|
|
406
|
+
file.seek((part - 1) * part_size)
|
|
407
|
+
data = file.read(part_size)
|
|
408
|
+
self._upload_part(submission_id, part, data)
|
|
409
|
+
done += len(data)
|
|
410
|
+
if progress:
|
|
411
|
+
progress(done, size)
|
|
412
|
+
return self._request("POST", f"/submissions/{submission_id}/complete")
|
|
413
|
+
|
|
414
|
+
def _upload_part(self, submission_id: str, part: int, data: bytes) -> None:
|
|
415
|
+
for attempt in range(RETRIES + 1):
|
|
416
|
+
try:
|
|
417
|
+
self._request(
|
|
418
|
+
"PUT", f"/submissions/{submission_id}/parts/{part}", raw=data
|
|
419
|
+
)
|
|
420
|
+
return
|
|
421
|
+
except (ServerError, OSError) as error:
|
|
422
|
+
refused = isinstance(error, ServerError) and error.status < 500
|
|
423
|
+
if refused or attempt == RETRIES:
|
|
424
|
+
raise
|
|
425
|
+
time.sleep(2**attempt)
|
|
426
|
+
|
|
427
|
+
def status(self, submission_id: str) -> dict:
|
|
428
|
+
return self._request("GET", f"/submissions/{submission_id}")
|
|
429
|
+
|
|
430
|
+
def wait(self, submission_id: str, poll: float = 10.0, timeout=None) -> dict:
|
|
431
|
+
"""The submission once it is scored or rejected."""
|
|
432
|
+
start = time.monotonic()
|
|
433
|
+
while True:
|
|
434
|
+
submission = self.status(submission_id)
|
|
435
|
+
if submission["status"] not in ("uploading", "queued"):
|
|
436
|
+
return submission
|
|
437
|
+
if timeout is not None and time.monotonic() - start > timeout:
|
|
438
|
+
raise TimeoutError(f"{submission_id} is still {submission['status']}.")
|
|
439
|
+
time.sleep(poll)
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def submit(dataset: str, labels, **options) -> dict:
|
|
443
|
+
"""`Client().submit`: check and send a submission, see `Client.submit`."""
|
|
444
|
+
return Client().submit(dataset, labels, **options)
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def _print_submission(submission: dict) -> None:
|
|
448
|
+
print(f"{submission['id']} {submission['dataset']} {submission['status']}")
|
|
449
|
+
if submission.get("error"):
|
|
450
|
+
print(f" {submission['error']}")
|
|
451
|
+
for score in submission.get("scores", []):
|
|
452
|
+
print(
|
|
453
|
+
f" {score['n_clusters']} clusters: inertia {score['inertia']:.9e} "
|
|
454
|
+
f"({score['outcome']})"
|
|
455
|
+
)
|
|
456
|
+
if submission["status"] == "uploading":
|
|
457
|
+
print(
|
|
458
|
+
f" {len(submission['uploaded_parts'])} of {submission['n_parts']} parts "
|
|
459
|
+
f"uploaded. To resume: inertia-client resume {submission['id']} FILE"
|
|
460
|
+
)
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _progress(done: int, total: int) -> None:
|
|
464
|
+
unit, name = (1e6, "MB") if total >= 1e7 else (1e3, "kB")
|
|
465
|
+
print(
|
|
466
|
+
f"\r uploaded {done / unit:.0f} of {total / unit:.0f} {name}",
|
|
467
|
+
end="",
|
|
468
|
+
flush=True,
|
|
469
|
+
)
|
|
470
|
+
if done == total:
|
|
471
|
+
print()
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def _tags(pairs: list[str]) -> dict[str, str]:
|
|
475
|
+
tags = {}
|
|
476
|
+
for pair in pairs:
|
|
477
|
+
key, separator, value = pair.partition("=")
|
|
478
|
+
if not separator or not key:
|
|
479
|
+
raise ValueError(f"A tag is KEY=VALUE, got {pair!r}.")
|
|
480
|
+
tags[key] = value
|
|
481
|
+
return tags
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def _times(pairs: list[str]) -> dict[int, float]:
|
|
485
|
+
times = {}
|
|
486
|
+
for pair in pairs:
|
|
487
|
+
try:
|
|
488
|
+
n_clusters, seconds = pair.split("=")
|
|
489
|
+
times[int(n_clusters)] = float(seconds)
|
|
490
|
+
except ValueError:
|
|
491
|
+
raise ValueError(f"A time is N_CLUSTERS=SECONDS, got {pair!r}.") from None
|
|
492
|
+
return times
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def main(argv=None):
|
|
496
|
+
parser = argparse.ArgumentParser(
|
|
497
|
+
description="Submit labels to the inertia challenge.",
|
|
498
|
+
)
|
|
499
|
+
parser.add_argument(
|
|
500
|
+
"--server",
|
|
501
|
+
help=f"URL of the server (default: ${SERVER_VARIABLE}, else the one of the "
|
|
502
|
+
"challenge)",
|
|
503
|
+
)
|
|
504
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
505
|
+
commands.add_parser("login", help="identify yourself with GitHub")
|
|
506
|
+
|
|
507
|
+
check = commands.add_parser("check", help="check a submission, without sending it")
|
|
508
|
+
check.add_argument("dataset")
|
|
509
|
+
check.add_argument("file", help=".npz file, {n_clusters: uint32 labels}")
|
|
510
|
+
|
|
511
|
+
send = commands.add_parser("submit", help="check and send a submission")
|
|
512
|
+
send.add_argument("dataset")
|
|
513
|
+
send.add_argument("file", help=".npz file, {n_clusters: uint32 labels}")
|
|
514
|
+
send.add_argument(
|
|
515
|
+
"--time",
|
|
516
|
+
action="append",
|
|
517
|
+
default=[],
|
|
518
|
+
metavar="N_CLUSTERS=SECONDS",
|
|
519
|
+
help="how long the clustering took for a number of clusters, as 100=23.21 "
|
|
520
|
+
"(can be repeated)",
|
|
521
|
+
)
|
|
522
|
+
send.add_argument("--hardware", help='on what, as "M2, 8 cores"')
|
|
523
|
+
send.add_argument(
|
|
524
|
+
"--tag",
|
|
525
|
+
action="append",
|
|
526
|
+
default=[],
|
|
527
|
+
metavar="KEY=VALUE",
|
|
528
|
+
help="free text about the submission, as algorithm=Lloyd (can be repeated)",
|
|
529
|
+
)
|
|
530
|
+
send.add_argument(
|
|
531
|
+
"--submit-only-improvement",
|
|
532
|
+
action="store_true",
|
|
533
|
+
help="score the labels here (the dataset must be downloaded) and only send "
|
|
534
|
+
"the numbers of clusters that beat your best score on the scoreboard",
|
|
535
|
+
)
|
|
536
|
+
send.add_argument(
|
|
537
|
+
"--data-dir",
|
|
538
|
+
help="directory of the datasets, for --submit-only-improvement (default: "
|
|
539
|
+
"$INERTIA_CHALLENGE_DATA, else ~/.cache/the-inertia-challenge)",
|
|
540
|
+
)
|
|
541
|
+
send.add_argument("--yes", action="store_true", help="do not ask before sending")
|
|
542
|
+
send.add_argument("--wait", action="store_true", help="wait for the scores")
|
|
543
|
+
|
|
544
|
+
resume = commands.add_parser("resume", help="resume an upload that was stopped")
|
|
545
|
+
resume.add_argument("id")
|
|
546
|
+
resume.add_argument("file")
|
|
547
|
+
|
|
548
|
+
status = commands.add_parser("status", help="where a submission is, and its scores")
|
|
549
|
+
status.add_argument("id")
|
|
550
|
+
status.add_argument("--wait", action="store_true", help="wait for the scores")
|
|
551
|
+
args = parser.parse_args(argv)
|
|
552
|
+
|
|
553
|
+
try:
|
|
554
|
+
client = Client(args.server)
|
|
555
|
+
if args.command == "login":
|
|
556
|
+
# Flushed: the code must show up when the output is not a terminal.
|
|
557
|
+
client.login(show=lambda message: print(message, flush=True))
|
|
558
|
+
print(f"Logged in. The token is in {token_path()}")
|
|
559
|
+
elif args.command == "check":
|
|
560
|
+
n_clusters = check_submission(args.dataset, args.file)
|
|
561
|
+
print(
|
|
562
|
+
f"{args.file} is a valid submission for {args.dataset}, for "
|
|
563
|
+
f"{', '.join(map(str, n_clusters))} clusters."
|
|
564
|
+
)
|
|
565
|
+
elif args.command == "submit":
|
|
566
|
+
n_clusters = check_submission(args.dataset, args.file)
|
|
567
|
+
tags = _tags(args.tag)
|
|
568
|
+
times = _times(args.time)
|
|
569
|
+
print(
|
|
570
|
+
f"{args.file} is a valid submission for {args.dataset}, for "
|
|
571
|
+
f"{', '.join(map(str, n_clusters))} clusters."
|
|
572
|
+
)
|
|
573
|
+
if not args.yes:
|
|
574
|
+
answer = input(
|
|
575
|
+
f"You can submit once per day for {args.dataset}. Send it? [y/N] "
|
|
576
|
+
)
|
|
577
|
+
if answer.strip().lower() not in ("y", "yes"):
|
|
578
|
+
sys.exit("Not sent.")
|
|
579
|
+
submission = client.submit(
|
|
580
|
+
args.dataset,
|
|
581
|
+
args.file,
|
|
582
|
+
time_s=times,
|
|
583
|
+
hardware=args.hardware,
|
|
584
|
+
tags=tags,
|
|
585
|
+
progress=_progress,
|
|
586
|
+
submit_only_improvement=args.submit_only_improvement,
|
|
587
|
+
data_dir=args.data_dir,
|
|
588
|
+
log=print,
|
|
589
|
+
)
|
|
590
|
+
if submission is None:
|
|
591
|
+
sys.exit("Nothing sent: no number of clusters improves on your best.")
|
|
592
|
+
if args.wait:
|
|
593
|
+
submission = client.wait(submission["id"])
|
|
594
|
+
_print_submission(submission)
|
|
595
|
+
elif args.command == "resume":
|
|
596
|
+
_print_submission(client.upload(args.id, args.file, _progress))
|
|
597
|
+
elif args.command == "status":
|
|
598
|
+
submission = client.wait(args.id) if args.wait else client.status(args.id)
|
|
599
|
+
_print_submission(submission)
|
|
600
|
+
except (ValueError, RuntimeError, OSError) as error:
|
|
601
|
+
sys.exit(f"Error: {error}")
|
|
602
|
+
except KeyboardInterrupt:
|
|
603
|
+
sys.exit(130)
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
if __name__ == "__main__":
|
|
607
|
+
main()
|
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
2
|
+
import json
|
|
3
|
+
import re
|
|
4
|
+
import stat
|
|
5
|
+
import threading
|
|
6
|
+
import urllib.parse
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import pytest
|
|
10
|
+
|
|
11
|
+
from inertia_client import Client, ServerError, check_submission, client, save_labels
|
|
12
|
+
from inertia_scorer import challenge, download, score
|
|
13
|
+
from inertia_scorer.challenge import Dataset, Reader
|
|
14
|
+
|
|
15
|
+
N_SAMPLES = 1000
|
|
16
|
+
PART_SIZE = 3000
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class FakeServer(ThreadingHTTPServer):
|
|
20
|
+
"""The API of the server for one user, and the device flow of GitHub."""
|
|
21
|
+
|
|
22
|
+
def __init__(self):
|
|
23
|
+
super().__init__(("127.0.0.1", 0), Handler)
|
|
24
|
+
self.url = f"http://127.0.0.1:{self.server_port}"
|
|
25
|
+
self.submissions = {}
|
|
26
|
+
self.tokens = {"token-of-ada"}
|
|
27
|
+
self.failures = [] # statuses to answer to the next uploads of parts
|
|
28
|
+
self.polls = 0 # of the device flow
|
|
29
|
+
self.requests = []
|
|
30
|
+
self.scores = [] # lines of the published scores of "toy"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Handler(BaseHTTPRequestHandler):
|
|
34
|
+
def answer(self, status, body):
|
|
35
|
+
data = json.dumps(body).encode()
|
|
36
|
+
self.send_response(status)
|
|
37
|
+
self.send_header("Content-Length", str(len(data)))
|
|
38
|
+
if status == 429:
|
|
39
|
+
self.send_header("Retry-After", "3600")
|
|
40
|
+
self.end_headers()
|
|
41
|
+
self.wfile.write(data)
|
|
42
|
+
|
|
43
|
+
def answer_text(self, text):
|
|
44
|
+
data = text.encode()
|
|
45
|
+
self.send_response(200)
|
|
46
|
+
self.send_header("Content-Length", str(len(data)))
|
|
47
|
+
self.end_headers()
|
|
48
|
+
self.wfile.write(data)
|
|
49
|
+
|
|
50
|
+
def view(self, submission):
|
|
51
|
+
result = {key: submission[key] for key in ("id", "dataset", "status", "size")}
|
|
52
|
+
result |= {"scores": submission["scores"], "error": None}
|
|
53
|
+
if submission["status"] == "uploading":
|
|
54
|
+
result |= {
|
|
55
|
+
"part_size": PART_SIZE,
|
|
56
|
+
"n_parts": -(-submission["size"] // PART_SIZE),
|
|
57
|
+
"uploaded_parts": sorted(submission["parts"]),
|
|
58
|
+
}
|
|
59
|
+
return result
|
|
60
|
+
|
|
61
|
+
def handle_request(self):
|
|
62
|
+
server = self.server
|
|
63
|
+
length = int(self.headers.get("Content-Length") or 0)
|
|
64
|
+
data = self.rfile.read(length)
|
|
65
|
+
server.requests.append((self.command, self.path))
|
|
66
|
+
|
|
67
|
+
# GitHub
|
|
68
|
+
if self.path == "/login/device/code":
|
|
69
|
+
assert urllib.parse.parse_qs(data.decode()) == {"client_id": ["client-id"]}
|
|
70
|
+
return self.answer(
|
|
71
|
+
200,
|
|
72
|
+
{
|
|
73
|
+
"device_code": "device",
|
|
74
|
+
"user_code": "ABCD-1234",
|
|
75
|
+
"verification_uri": "https://github.com/login/device",
|
|
76
|
+
"interval": 0,
|
|
77
|
+
"expires_in": 900,
|
|
78
|
+
},
|
|
79
|
+
)
|
|
80
|
+
if self.path == "/login/oauth/access_token":
|
|
81
|
+
server.polls += 1
|
|
82
|
+
if server.polls < 3:
|
|
83
|
+
return self.answer(200, {"error": "authorization_pending"})
|
|
84
|
+
return self.answer(200, {"access_token": "token-of-ada"})
|
|
85
|
+
|
|
86
|
+
# The public scores, and who a token is
|
|
87
|
+
if self.path == "/scores/toy.jsonl":
|
|
88
|
+
return self.answer_text(
|
|
89
|
+
"".join(json.dumps(s) + "\n" for s in server.scores)
|
|
90
|
+
)
|
|
91
|
+
if self.path == "/scores/mnist.jsonl":
|
|
92
|
+
return self.answer(404, {})
|
|
93
|
+
|
|
94
|
+
# The server
|
|
95
|
+
if self.path == "/":
|
|
96
|
+
return self.answer(200, {"github_client_id": "client-id"})
|
|
97
|
+
token = (self.headers.get("Authorization") or "").removeprefix("Bearer ")
|
|
98
|
+
if token not in server.tokens:
|
|
99
|
+
return self.answer(401, {"error": "This is not a valid GitHub token."})
|
|
100
|
+
if self.path == "/user":
|
|
101
|
+
return self.answer(200, {"login": "ada"})
|
|
102
|
+
if self.path == "/submissions":
|
|
103
|
+
body = json.loads(data)
|
|
104
|
+
if any(
|
|
105
|
+
s["dataset"] == body["dataset"] for s in server.submissions.values()
|
|
106
|
+
):
|
|
107
|
+
return self.answer(429, {"error": "One submission per 24 hours."})
|
|
108
|
+
name = f"id-{len(server.submissions)}"
|
|
109
|
+
server.submissions[name] = body | {
|
|
110
|
+
"id": name,
|
|
111
|
+
"status": "uploading",
|
|
112
|
+
"parts": {},
|
|
113
|
+
"scores": [],
|
|
114
|
+
}
|
|
115
|
+
return self.answer(201, {"id": name})
|
|
116
|
+
match = re.fullmatch(
|
|
117
|
+
r"/submissions/([\w-]+)(?:/(parts/(\d+)|complete))?", self.path
|
|
118
|
+
)
|
|
119
|
+
submission = server.submissions.get(match.group(1)) if match else None
|
|
120
|
+
if not submission:
|
|
121
|
+
return self.answer(404, {"error": "You have no submission with this id."})
|
|
122
|
+
if match.group(3):
|
|
123
|
+
if server.failures:
|
|
124
|
+
return self.answer(
|
|
125
|
+
server.failures.pop(0), {"error": "The server failed."}
|
|
126
|
+
)
|
|
127
|
+
submission["parts"][int(match.group(3))] = data
|
|
128
|
+
return self.answer(200, {"part_number": int(match.group(3))})
|
|
129
|
+
if match.group(2) == "complete":
|
|
130
|
+
parts = submission["parts"]
|
|
131
|
+
submission["content"] = b"".join(parts[part] for part in sorted(parts))
|
|
132
|
+
assert len(submission["content"]) == submission["size"]
|
|
133
|
+
submission["status"] = "queued"
|
|
134
|
+
self.answer(200, self.view(submission))
|
|
135
|
+
|
|
136
|
+
do_GET = do_POST = do_PUT = handle_request
|
|
137
|
+
|
|
138
|
+
def log_message(self, *arguments):
|
|
139
|
+
pass
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@pytest.fixture
|
|
143
|
+
def server(monkeypatch, tmp_path):
|
|
144
|
+
monkeypatch.setitem(
|
|
145
|
+
challenge.DATASETS, "toy", Dataset("toy", N_SAMPLES, 5, (4, 16), "")
|
|
146
|
+
)
|
|
147
|
+
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "config"))
|
|
148
|
+
monkeypatch.delenv(client.TOKEN_VARIABLE, raising=False)
|
|
149
|
+
monkeypatch.delenv(client.SERVER_VARIABLE, raising=False)
|
|
150
|
+
monkeypatch.setattr(client.time, "sleep", lambda seconds: None)
|
|
151
|
+
server = FakeServer()
|
|
152
|
+
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
153
|
+
yield server
|
|
154
|
+
server.shutdown()
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def labels(k, dtype=np.uint32):
|
|
158
|
+
return np.random.default_rng(k).integers(0, k, N_SAMPLES).astype(dtype)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def test_submit(server, tmp_path):
|
|
162
|
+
progress = []
|
|
163
|
+
submission = Client(server.url, "token-of-ada").submit(
|
|
164
|
+
"toy",
|
|
165
|
+
{4: labels(4), 16: labels(16, np.int64)},
|
|
166
|
+
time_s={4: 23, 16: 1.5},
|
|
167
|
+
hardware="M2",
|
|
168
|
+
tags={"algorithm": "Lloyd"},
|
|
169
|
+
progress=lambda done, total: progress.append((done, total)),
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
assert submission["status"] == "queued"
|
|
173
|
+
sent = server.submissions[submission["id"]]
|
|
174
|
+
assert sent["time_s"] == {"4": 23.0, "16": 1.5}
|
|
175
|
+
assert (sent["hardware"], sent["tags"]) == ("M2", {"algorithm": "Lloyd"})
|
|
176
|
+
# 2 arrays of 4000 bytes and the headers, by parts of 3000 bytes.
|
|
177
|
+
assert sorted(sent["parts"]) == [1, 2, 3]
|
|
178
|
+
assert [done for done, total in progress] == [3000, 6000, sent["size"]]
|
|
179
|
+
(tmp_path / "received.npz").write_bytes(sent["content"])
|
|
180
|
+
assert check_submission("toy", tmp_path / "received.npz") == [4, 16]
|
|
181
|
+
with np.load(tmp_path / "received.npz") as received:
|
|
182
|
+
assert received["16"].dtype == np.uint32
|
|
183
|
+
np.testing.assert_array_equal(received["16"], labels(16))
|
|
184
|
+
|
|
185
|
+
# The limit of the server.
|
|
186
|
+
with pytest.raises(ServerError, match="One submission per 24 hours") as error:
|
|
187
|
+
Client(server.url, "token-of-ada").submit("toy", {4: labels(4)})
|
|
188
|
+
assert (error.value.status, error.value.retry_after) == (429, 3600)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
@pytest.mark.parametrize(
|
|
192
|
+
"arrays, match",
|
|
193
|
+
[
|
|
194
|
+
({"4": labels(4, np.int32)}, "For 4 clusters: The labels must be a uint32"),
|
|
195
|
+
({"4": labels(4)[:-1]}, "For 4 clusters: The labels must have shape"),
|
|
196
|
+
({"4": labels(16)}, "For 4 clusters: The labels must be in"),
|
|
197
|
+
({"5": labels(4)}, "are among 4, 16"),
|
|
198
|
+
({"4": labels(4), "centers": np.zeros(3)}, "are among 4, 16"),
|
|
199
|
+
({}, "empty"),
|
|
200
|
+
],
|
|
201
|
+
)
|
|
202
|
+
def test_invalid_file_is_not_sent(server, tmp_path, arrays, match):
|
|
203
|
+
path = tmp_path / "labels.npz"
|
|
204
|
+
np.savez(path, **arrays)
|
|
205
|
+
with pytest.raises(ValueError, match=match):
|
|
206
|
+
Client(server.url, "token-of-ada").submit("toy", path)
|
|
207
|
+
path.write_bytes(b"not a zip file")
|
|
208
|
+
with pytest.raises(ValueError, match="not a .npz file"):
|
|
209
|
+
Client(server.url, "token-of-ada").submit("toy", path)
|
|
210
|
+
with pytest.raises(ValueError, match="Unknown dataset"):
|
|
211
|
+
Client(server.url, "token-of-ada").submit("mnist", path)
|
|
212
|
+
assert not server.requests
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
@pytest.mark.parametrize(
|
|
216
|
+
"time_s, match",
|
|
217
|
+
[(23.21, "for each number of clusters, as {4: 23.21}"), ({16: 1.5}, "no labels")],
|
|
218
|
+
)
|
|
219
|
+
def test_invalid_times_are_not_sent(server, time_s, match):
|
|
220
|
+
with pytest.raises(ValueError, match=match):
|
|
221
|
+
Client(server.url, "token-of-ada").submit("toy", {4: labels(4)}, time_s=time_s)
|
|
222
|
+
assert not server.requests
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def test_save_labels(tmp_path):
|
|
226
|
+
for invalid in (labels(4).astype(float), -labels(4).astype(np.int64) - 1):
|
|
227
|
+
with pytest.raises(ValueError, match="not non-negative integers"):
|
|
228
|
+
save_labels(tmp_path / "labels.npz", {4: invalid})
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def test_upload_is_resumed_and_retried(server, tmp_path):
|
|
232
|
+
path = tmp_path / "labels.npz"
|
|
233
|
+
save_labels(path, {4: labels(4), 16: labels(16)})
|
|
234
|
+
user = Client(server.url, "token-of-ada")
|
|
235
|
+
# The server fails 5 times: the client gives up at the first part.
|
|
236
|
+
server.failures = [500, 500, 500, 500, 500]
|
|
237
|
+
with pytest.raises(ServerError, match="The server failed"):
|
|
238
|
+
user.submit("toy", path)
|
|
239
|
+
(submission,) = server.submissions.values()
|
|
240
|
+
assert sorted(submission["parts"]) == [] and submission["status"] == "uploading"
|
|
241
|
+
|
|
242
|
+
server.failures = [500, 502]
|
|
243
|
+
server.requests.clear()
|
|
244
|
+
assert user.upload(submission["id"], path)["status"] == "queued"
|
|
245
|
+
assert submission["content"] == path.read_bytes()
|
|
246
|
+
parts = [path for method, path in server.requests if method == "PUT"]
|
|
247
|
+
assert [int(part.rsplit("/", 1)[1]) for part in parts] == [1, 1, 1, 2, 3]
|
|
248
|
+
|
|
249
|
+
# A refusal is not tried again, and a completed submission is left alone.
|
|
250
|
+
other = tmp_path / "other.npz"
|
|
251
|
+
save_labels(other, {4: labels(4)})
|
|
252
|
+
assert user.upload(submission["id"], other)["status"] == "queued"
|
|
253
|
+
with pytest.raises(ServerError, match="no submission with this id") as error:
|
|
254
|
+
user.upload("unknown", path)
|
|
255
|
+
assert error.value.status == 404
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def test_login(server, tmp_path, capsys):
|
|
259
|
+
user = Client(server.url, github=server.url)
|
|
260
|
+
with pytest.raises(RuntimeError, match="Run: inertia-client login"):
|
|
261
|
+
user.status("id-0")
|
|
262
|
+
|
|
263
|
+
user.login()
|
|
264
|
+
|
|
265
|
+
assert "enter the code ABCD-1234" in capsys.readouterr().out
|
|
266
|
+
assert server.polls == 3
|
|
267
|
+
saved = client.token_path()
|
|
268
|
+
assert saved == tmp_path / "config" / "the-inertia-challenge" / "github-token"
|
|
269
|
+
assert saved.read_text() == "token-of-ada\n"
|
|
270
|
+
assert stat.S_IMODE(saved.stat().st_mode) == 0o600
|
|
271
|
+
# Another client finds the token.
|
|
272
|
+
with pytest.raises(ServerError, match="no submission with this id"):
|
|
273
|
+
Client(server.url).status("id-0")
|
|
274
|
+
|
|
275
|
+
with pytest.raises(ServerError, match="Run: inertia-client login") as error:
|
|
276
|
+
Client(server.url, "another token").status("id-0")
|
|
277
|
+
assert error.value.status == 401
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def test_server_in_https():
|
|
281
|
+
with pytest.raises(ValueError, match="must be in https"):
|
|
282
|
+
Client("http://example.com")
|
|
283
|
+
assert Client().server == client.DEFAULT_SERVER
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def test_command_line(server, tmp_path, capsys, monkeypatch):
|
|
287
|
+
monkeypatch.setenv(client.TOKEN_VARIABLE, "token-of-ada")
|
|
288
|
+
monkeypatch.setenv(client.SERVER_VARIABLE, server.url)
|
|
289
|
+
path = tmp_path / "labels.npz"
|
|
290
|
+
save_labels(path, {4: labels(4)})
|
|
291
|
+
|
|
292
|
+
client.main(["check", "toy", str(path)])
|
|
293
|
+
assert "is a valid submission for toy, for 4 clusters" in capsys.readouterr().out
|
|
294
|
+
assert not server.requests
|
|
295
|
+
|
|
296
|
+
monkeypatch.setattr("builtins.input", lambda prompt: "n")
|
|
297
|
+
with pytest.raises(SystemExit, match="Not sent"):
|
|
298
|
+
client.main(["submit", "toy", str(path)])
|
|
299
|
+
assert not server.requests
|
|
300
|
+
|
|
301
|
+
arguments = ["--time", "4=1.5", "--hardware", "M2", "--tag", "algorithm=a=b"]
|
|
302
|
+
client.main(["submit", "toy", str(path), "--yes", *arguments])
|
|
303
|
+
assert "id-0 toy queued" in capsys.readouterr().out
|
|
304
|
+
assert server.submissions["id-0"]["tags"] == {"algorithm": "a=b"}
|
|
305
|
+
assert server.submissions["id-0"]["time_s"] == {"4": 1.5}
|
|
306
|
+
|
|
307
|
+
server.submissions["id-0"] |= {
|
|
308
|
+
"status": "scored",
|
|
309
|
+
"scores": [{"n_clusters": 4, "inertia": 123.5, "outcome": "best"}],
|
|
310
|
+
}
|
|
311
|
+
client.main(["status", "id-0", "--wait"])
|
|
312
|
+
output = capsys.readouterr().out
|
|
313
|
+
assert "id-0 toy scored" in output
|
|
314
|
+
assert "4 clusters: inertia 1.235000000e+02 (best)" in output
|
|
315
|
+
|
|
316
|
+
with pytest.raises(SystemExit, match="Error: A time is N_CLUSTERS=SECONDS"):
|
|
317
|
+
client.main(["submit", "toy", str(path), "--yes", "--time", "1.5"])
|
|
318
|
+
with pytest.raises(SystemExit, match="Error: A tag is KEY=VALUE"):
|
|
319
|
+
client.main(["submit", "toy", str(path), "--yes", "--tag", "fast"])
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def toy_data(tmp_path):
|
|
323
|
+
X = np.random.default_rng(0).standard_normal((N_SAMPLES, 5)).astype(np.float32)
|
|
324
|
+
dataset = challenge.get_dataset("toy")
|
|
325
|
+
download._write_dense(dataset, tmp_path, [X[:3], X[3:]])
|
|
326
|
+
challenge.write_meta(dataset, tmp_path, {"n_samples": N_SAMPLES, "n_features": 5})
|
|
327
|
+
return Reader(dataset, tmp_path)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def test_submit_only_improvement(server, tmp_path):
|
|
331
|
+
reader = toy_data(tmp_path)
|
|
332
|
+
inertia = {k: score.score_labels(reader, labels(k), k).inertia for k in (4, 16)}
|
|
333
|
+
user = Client(
|
|
334
|
+
server.url,
|
|
335
|
+
"token-of-ada",
|
|
336
|
+
github_api=server.url,
|
|
337
|
+
results_url=server.url + "/scores",
|
|
338
|
+
)
|
|
339
|
+
messages = []
|
|
340
|
+
# Ada is better than the labels for 4 clusters, worse for 16; another user
|
|
341
|
+
# is better than everyone.
|
|
342
|
+
server.scores = [
|
|
343
|
+
{"user": "ada", "n_clusters": 4, "inertia": inertia[4] * 0.9},
|
|
344
|
+
{"user": "ada", "n_clusters": 4, "inertia": inertia[4] * 2},
|
|
345
|
+
{"user": "ada", "n_clusters": 16, "inertia": inertia[16] * 1.1},
|
|
346
|
+
{"user": "bob", "n_clusters": 16, "inertia": 0.0},
|
|
347
|
+
]
|
|
348
|
+
submission = user.submit(
|
|
349
|
+
"toy",
|
|
350
|
+
{4: labels(4), 16: labels(16)},
|
|
351
|
+
time_s={4: 1.0, 16: 2.0},
|
|
352
|
+
submit_only_improvement=True,
|
|
353
|
+
data_dir=tmp_path,
|
|
354
|
+
log=messages.append,
|
|
355
|
+
)
|
|
356
|
+
|
|
357
|
+
assert submission["status"] == "queued"
|
|
358
|
+
sent = server.submissions[submission["id"]]
|
|
359
|
+
assert sent["time_s"] == {"16": 2.0}
|
|
360
|
+
(tmp_path / "received.npz").write_bytes(sent["content"])
|
|
361
|
+
assert check_submission("toy", tmp_path / "received.npz") == [16]
|
|
362
|
+
assert messages[0].startswith("4 clusters: not sent")
|
|
363
|
+
assert messages[1].startswith("16 clusters: sent, improves on")
|
|
364
|
+
|
|
365
|
+
# Nothing improves: nothing is sent.
|
|
366
|
+
server.submissions.clear()
|
|
367
|
+
server.scores = [{"user": "ada", "n_clusters": 4, "inertia": 0.0}]
|
|
368
|
+
assert (
|
|
369
|
+
user.submit(
|
|
370
|
+
"toy", {4: labels(4)}, submit_only_improvement=True, data_dir=tmp_path
|
|
371
|
+
)
|
|
372
|
+
is None
|
|
373
|
+
)
|
|
374
|
+
assert not server.submissions
|
|
375
|
+
|
|
376
|
+
# No score of the user yet: it is sent.
|
|
377
|
+
server.scores = []
|
|
378
|
+
assert user.submit(
|
|
379
|
+
"toy", {4: labels(4)}, submit_only_improvement=True, data_dir=tmp_path
|
|
380
|
+
)
|