compute-horde-sdk 0.0.0__py3-none-any.whl
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.
- compute_horde_core/__init__.py +0 -0
- compute_horde_core/executor_class.py +7 -0
- compute_horde_core/output_upload.py +83 -0
- compute_horde_core/signature.py +302 -0
- compute_horde_core/volume.py +88 -0
- compute_horde_sdk/__init__.py +0 -0
- compute_horde_sdk/_internal/__init__.py +5 -0
- compute_horde_sdk/_internal/exceptions.py +10 -0
- compute_horde_sdk/_internal/models.py +193 -0
- compute_horde_sdk/_internal/sdk.py +345 -0
- compute_horde_sdk/py.typed +0 -0
- compute_horde_sdk/v1/__init__.py +21 -0
- compute_horde_sdk-0.0.0.dist-info/METADATA +160 -0
- compute_horde_sdk-0.0.0.dist-info/RECORD +17 -0
- compute_horde_sdk-0.0.0.dist-info/WHEEL +4 -0
- compute_horde_sdk-0.0.0.dist-info/entry_points.txt +4 -0
- compute_horde_sdk-0.0.0.dist-info/licenses/LICENSE +21 -0
|
File without changes
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import enum
|
|
2
|
+
import re
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from typing import Annotated, Literal
|
|
5
|
+
from urllib.parse import urlparse
|
|
6
|
+
|
|
7
|
+
import pydantic
|
|
8
|
+
from pydantic import Field
|
|
9
|
+
|
|
10
|
+
SAFE_DOMAIN_REGEX = re.compile(r".*")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class OutputUploadType(str, enum.Enum):
|
|
14
|
+
zip_and_http_post = "zip_and_http_post"
|
|
15
|
+
zip_and_http_put = "zip_and_http_put"
|
|
16
|
+
multi_upload = "multi_upload"
|
|
17
|
+
single_file_post = "single_file_post"
|
|
18
|
+
single_file_put = "single_file_put"
|
|
19
|
+
|
|
20
|
+
# default __str__ method returns "OutputUploadType.inline", we want just "inline"
|
|
21
|
+
def __str__(self):
|
|
22
|
+
return str.__str__(self)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ZipAndHttpPostUpload(pydantic.BaseModel):
|
|
26
|
+
output_upload_type: Literal[OutputUploadType.zip_and_http_post] = OutputUploadType.zip_and_http_post
|
|
27
|
+
url: str
|
|
28
|
+
form_fields: Mapping[str, str] | None = None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ZipAndHttpPutUpload(pydantic.BaseModel):
|
|
32
|
+
output_upload_type: Literal[OutputUploadType.zip_and_http_put] = OutputUploadType.zip_and_http_put
|
|
33
|
+
url: str
|
|
34
|
+
# TODO: PUT implementation does not support it - find out why and clean up
|
|
35
|
+
# form_fields: Mapping[str, str] | None = None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class SingleFilePostUpload(pydantic.BaseModel):
|
|
39
|
+
output_upload_type: Literal[OutputUploadType.single_file_post] = OutputUploadType.single_file_post
|
|
40
|
+
url: str
|
|
41
|
+
form_fields: Mapping[str, str] | None = None
|
|
42
|
+
relative_path: str
|
|
43
|
+
signed_headers: Mapping[str, str] | None = None
|
|
44
|
+
|
|
45
|
+
def is_safe(self) -> bool:
|
|
46
|
+
domain = urlparse(self.url).netloc
|
|
47
|
+
if SAFE_DOMAIN_REGEX.fullmatch(domain):
|
|
48
|
+
return True
|
|
49
|
+
return False
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class SingleFilePutUpload(pydantic.BaseModel):
|
|
53
|
+
output_upload_type: Literal[OutputUploadType.single_file_put] = OutputUploadType.single_file_put
|
|
54
|
+
url: str
|
|
55
|
+
# TODO: PUT implementation does not support it - find out why and clean up
|
|
56
|
+
# form_fields: Mapping[str, str] | None = None
|
|
57
|
+
relative_path: str
|
|
58
|
+
signed_headers: Mapping[str, str] | None = None
|
|
59
|
+
|
|
60
|
+
def is_safe(self) -> bool:
|
|
61
|
+
domain = urlparse(self.url).netloc
|
|
62
|
+
if SAFE_DOMAIN_REGEX.fullmatch(domain):
|
|
63
|
+
return True
|
|
64
|
+
return False
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
SingleFileUpload = Annotated[
|
|
68
|
+
SingleFilePostUpload | SingleFilePutUpload,
|
|
69
|
+
Field(discriminator="output_upload_type"),
|
|
70
|
+
]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class MultiUpload(pydantic.BaseModel):
|
|
74
|
+
output_upload_type: Literal[OutputUploadType.multi_upload] = OutputUploadType.multi_upload
|
|
75
|
+
uploads: list[SingleFileUpload]
|
|
76
|
+
# allow custom uploads for stdout and stderr
|
|
77
|
+
system_output: ZipAndHttpPostUpload | ZipAndHttpPutUpload | None = None
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
OutputUpload = Annotated[
|
|
81
|
+
SingleFilePostUpload | SingleFilePutUpload | ZipAndHttpPostUpload | ZipAndHttpPutUpload | MultiUpload,
|
|
82
|
+
Field(discriminator="output_upload_type"),
|
|
83
|
+
]
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
import abc
|
|
2
|
+
import base64
|
|
3
|
+
import datetime
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import time
|
|
8
|
+
import typing
|
|
9
|
+
from enum import StrEnum
|
|
10
|
+
from typing import ClassVar, Protocol
|
|
11
|
+
|
|
12
|
+
import bittensor
|
|
13
|
+
from pydantic import BaseModel, JsonValue, field_serializer, field_validator
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class SignatureScope(StrEnum):
|
|
17
|
+
SignedFields = "SignedFields"
|
|
18
|
+
FullRequest = "FullRequest"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Signature(BaseModel, extra="forbid"):
|
|
22
|
+
# has defaults to allow easy instantiation
|
|
23
|
+
signature_type: str = ""
|
|
24
|
+
signatory: str = "" # identity of the signer (e.g. sa58 address if signature_type == "bittensor")
|
|
25
|
+
timestamp_ns: int = 0 # UNIX timestamp in nanoseconds
|
|
26
|
+
signature: bytes
|
|
27
|
+
signature_scope: SignatureScope = SignatureScope.SignedFields
|
|
28
|
+
|
|
29
|
+
@field_validator("signature")
|
|
30
|
+
@classmethod
|
|
31
|
+
def validate_signature(cls, signature: str) -> bytes:
|
|
32
|
+
return base64.b64decode(signature)
|
|
33
|
+
|
|
34
|
+
@field_serializer("signature")
|
|
35
|
+
def serialize_signature(self, signature: bytes) -> str:
|
|
36
|
+
return base64.b64encode(signature).decode("utf-8")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class SignedFields(BaseModel):
|
|
40
|
+
executor_class: str
|
|
41
|
+
docker_image: str
|
|
42
|
+
raw_script: str
|
|
43
|
+
args: list[str]
|
|
44
|
+
env: dict[str, str]
|
|
45
|
+
use_gpu: bool
|
|
46
|
+
artifacts_dir: str
|
|
47
|
+
on_trusted_miner: bool
|
|
48
|
+
|
|
49
|
+
volumes: list[JsonValue]
|
|
50
|
+
uploads: list[JsonValue]
|
|
51
|
+
|
|
52
|
+
@staticmethod
|
|
53
|
+
def from_facilitator_sdk_json(data: JsonValue):
|
|
54
|
+
data = typing.cast(dict[str, JsonValue], data)
|
|
55
|
+
|
|
56
|
+
signed_fields = SignedFields(
|
|
57
|
+
executor_class=str(data.get("executor_class")),
|
|
58
|
+
docker_image=str(data.get("docker_image", "")),
|
|
59
|
+
raw_script=str(data.get("raw_script", "")),
|
|
60
|
+
args=typing.cast(list[str], data.get("args", [])),
|
|
61
|
+
env=typing.cast(dict[str, str], data.get("env", {})),
|
|
62
|
+
use_gpu=typing.cast(bool, data.get("use_gpu", False)),
|
|
63
|
+
volumes=typing.cast(list[JsonValue], data.get("volumes", [])),
|
|
64
|
+
uploads=typing.cast(list[JsonValue], data.get("uploads", [])),
|
|
65
|
+
artifacts_dir=typing.cast(str, data.get("artifacts_dir") or ""),
|
|
66
|
+
on_trusted_miner=typing.cast(bool, data.get("on_trusted_miner", False)),
|
|
67
|
+
)
|
|
68
|
+
return signed_fields
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def signature_from_headers(headers: dict[str, str], prefix: str = "X-CH-") -> Signature:
|
|
72
|
+
"""
|
|
73
|
+
Extracts the signature from the headers
|
|
74
|
+
|
|
75
|
+
:param headers: headers dict
|
|
76
|
+
:return: Signature object
|
|
77
|
+
"""
|
|
78
|
+
try:
|
|
79
|
+
return Signature(
|
|
80
|
+
signature_type=headers[f"{prefix}Signature-Type"],
|
|
81
|
+
signatory=headers[f"{prefix}Signatory"],
|
|
82
|
+
timestamp_ns=int(headers[f"{prefix}Timestamp-NS"]),
|
|
83
|
+
signature=headers[f"{prefix}Signature"].encode("utf-8"),
|
|
84
|
+
signature_scope=SignatureScope(headers.get(f"{prefix}Signature-Scope", SignatureScope.SignedFields.name)),
|
|
85
|
+
)
|
|
86
|
+
except (
|
|
87
|
+
KeyError,
|
|
88
|
+
ValueError,
|
|
89
|
+
TypeError,
|
|
90
|
+
) as e:
|
|
91
|
+
raise SignatureNotFound("Signature not found in headers") from e
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def signature_to_headers(signature: Signature, scope: SignatureScope, prefix: str = "X-CH-") -> dict[str, str]:
|
|
95
|
+
"""
|
|
96
|
+
Converts the signature to headers
|
|
97
|
+
|
|
98
|
+
:param signature: Signature object
|
|
99
|
+
:return: headers dict
|
|
100
|
+
"""
|
|
101
|
+
return {
|
|
102
|
+
f"{prefix}Signature-Type": signature.signature_type,
|
|
103
|
+
f"{prefix}Signatory": signature.signatory,
|
|
104
|
+
f"{prefix}Timestamp-NS": str(signature.timestamp_ns),
|
|
105
|
+
f"{prefix}Signature": base64.b64encode(signature.signature).decode("utf-8"),
|
|
106
|
+
f"{prefix}Signature-Scope": scope.name,
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class SignatureException(Exception):
|
|
111
|
+
pass
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class SignatureNotFound(SignatureException):
|
|
115
|
+
pass
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class SignatureInvalidException(SignatureException):
|
|
119
|
+
pass
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class SignatureTimeoutException(SignatureInvalidException):
|
|
123
|
+
pass
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def hash_message_signature(payload: bytes | JsonValue, signature: Signature) -> bytes:
|
|
127
|
+
"""
|
|
128
|
+
Hashes the message to be signed with the signature parameters
|
|
129
|
+
|
|
130
|
+
:param payload: payload to be signed
|
|
131
|
+
:param signature: incomplete signature object with Signature parameters
|
|
132
|
+
:return:
|
|
133
|
+
"""
|
|
134
|
+
if not isinstance(payload, bytes):
|
|
135
|
+
payload = json.dumps(payload, sort_keys=True).encode("utf-8")
|
|
136
|
+
|
|
137
|
+
hasher = hashlib.blake2b()
|
|
138
|
+
hasher.update(signature.timestamp_ns.to_bytes(8, "big"))
|
|
139
|
+
hasher.update(payload)
|
|
140
|
+
return hasher.digest()
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
_REMOVE_URL_SCHEME_N_HOST_RE = re.compile(r"^\w+://[^/]+")
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def signature_payload(method: str, url: str, headers: dict[str, str], json: JsonValue | None = None) -> JsonValue:
|
|
147
|
+
reduced_url = _REMOVE_URL_SCHEME_N_HOST_RE.sub("", url)
|
|
148
|
+
return {
|
|
149
|
+
"action": f"{method.upper()} {reduced_url}",
|
|
150
|
+
"json": json,
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class SignatureScheme(abc.ABC):
|
|
155
|
+
signature_type: ClassVar[str]
|
|
156
|
+
|
|
157
|
+
def payload_from_request(
|
|
158
|
+
self,
|
|
159
|
+
method: str,
|
|
160
|
+
url: str,
|
|
161
|
+
headers: dict[str, str],
|
|
162
|
+
json: JsonValue | None = None,
|
|
163
|
+
):
|
|
164
|
+
return signature_payload(
|
|
165
|
+
method=method,
|
|
166
|
+
url=url,
|
|
167
|
+
headers=headers,
|
|
168
|
+
json=json,
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class Signer(SignatureScheme):
|
|
173
|
+
def sign(self, payload: JsonValue | bytes) -> Signature:
|
|
174
|
+
signature = Signature(
|
|
175
|
+
signature_type=self.signature_type,
|
|
176
|
+
signatory=self.get_signatory(),
|
|
177
|
+
timestamp_ns=time.time_ns(),
|
|
178
|
+
signature=b"",
|
|
179
|
+
)
|
|
180
|
+
payload_hash = hash_message_signature(payload, signature)
|
|
181
|
+
signature.signature = self._sign(payload_hash)
|
|
182
|
+
return signature
|
|
183
|
+
|
|
184
|
+
def signature_for_request(
|
|
185
|
+
self, method: str, url: str, headers: dict[str, str], json: JsonValue | None = None
|
|
186
|
+
) -> Signature:
|
|
187
|
+
return self.sign(self.payload_from_request(method, url, headers=headers, json=json))
|
|
188
|
+
|
|
189
|
+
@abc.abstractmethod
|
|
190
|
+
def _sign(self, payload: bytes) -> bytes:
|
|
191
|
+
raise NotImplementedError
|
|
192
|
+
|
|
193
|
+
@abc.abstractmethod
|
|
194
|
+
def get_signatory(self) -> str:
|
|
195
|
+
raise NotImplementedError
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
class Verifier(SignatureScheme):
|
|
199
|
+
def verify(
|
|
200
|
+
self,
|
|
201
|
+
payload: JsonValue | bytes,
|
|
202
|
+
signature: Signature,
|
|
203
|
+
newer_than: datetime.datetime | None = None,
|
|
204
|
+
):
|
|
205
|
+
payload_hash = hash_message_signature(payload, signature)
|
|
206
|
+
self._verify(payload_hash, signature)
|
|
207
|
+
|
|
208
|
+
if newer_than is not None:
|
|
209
|
+
if newer_than > datetime.datetime.fromtimestamp(signature.timestamp_ns / 1_000_000_000):
|
|
210
|
+
raise SignatureTimeoutException("Signature is too old")
|
|
211
|
+
|
|
212
|
+
@abc.abstractmethod
|
|
213
|
+
def _verify(self, payload: bytes, signature: Signature) -> None:
|
|
214
|
+
raise NotImplementedError
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class BittensorSignatureScheme:
|
|
218
|
+
signature_type = "bittensor"
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
class BittensorWalletSigner(BittensorSignatureScheme, Signer):
|
|
222
|
+
def __init__(self, wallet: bittensor.wallet | bittensor.Keypair | None = None):
|
|
223
|
+
if isinstance(wallet, bittensor.Keypair):
|
|
224
|
+
keypair = wallet
|
|
225
|
+
else:
|
|
226
|
+
keypair = (wallet or bittensor.wallet()).hotkey
|
|
227
|
+
self._keypair = keypair
|
|
228
|
+
|
|
229
|
+
def _sign(self, payload: bytes) -> bytes:
|
|
230
|
+
signature: bytes = self._keypair.sign(payload)
|
|
231
|
+
return signature
|
|
232
|
+
|
|
233
|
+
def get_signatory(self) -> str:
|
|
234
|
+
signatory: str = self._keypair.ss58_address
|
|
235
|
+
return signatory
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
class BittensorWalletVerifier(BittensorSignatureScheme, Verifier):
|
|
239
|
+
def _verify(self, payload: bytes, signature: Signature) -> None:
|
|
240
|
+
try:
|
|
241
|
+
keypair = bittensor.Keypair(ss58_address=signature.signatory)
|
|
242
|
+
except ValueError:
|
|
243
|
+
raise SignatureInvalidException("Invalid signatory for BittensorWalletVerifier")
|
|
244
|
+
try:
|
|
245
|
+
if not keypair.verify(data=payload, signature=signature.signature):
|
|
246
|
+
raise SignatureInvalidException("Signature is invalid")
|
|
247
|
+
except (ValueError, TypeError) as e:
|
|
248
|
+
raise SignatureInvalidException("Signature is malformed") from e
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
class SignatureExtractor(Protocol):
|
|
252
|
+
def __call__(self, headers: dict[str, str], prefix: str = "") -> Signature: ...
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def verify_signature(
|
|
256
|
+
payload: JsonValue | bytes,
|
|
257
|
+
signature: Signature,
|
|
258
|
+
*,
|
|
259
|
+
newer_than: datetime.datetime | None = None,
|
|
260
|
+
):
|
|
261
|
+
"""
|
|
262
|
+
Verifies the signature of the payload
|
|
263
|
+
|
|
264
|
+
:param payload: payload to be verified
|
|
265
|
+
:param signature: signature object
|
|
266
|
+
:param newer_than: if provided, checks if the signature is newer than the provided timestamp
|
|
267
|
+
:return: None
|
|
268
|
+
:raises SignatureInvalidException: if the signature is invalid
|
|
269
|
+
"""
|
|
270
|
+
verifier = BittensorWalletVerifier()
|
|
271
|
+
verifier.verify(payload, signature, newer_than)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def verify_request(
|
|
275
|
+
method: str,
|
|
276
|
+
url: str,
|
|
277
|
+
headers: dict[str, str],
|
|
278
|
+
json: JsonValue | None = None,
|
|
279
|
+
*,
|
|
280
|
+
newer_than: datetime.datetime | None = None,
|
|
281
|
+
signature_extractor: SignatureExtractor = signature_from_headers,
|
|
282
|
+
) -> Signature | None:
|
|
283
|
+
"""
|
|
284
|
+
Verifies the signature of the request
|
|
285
|
+
|
|
286
|
+
:param method: HTTP method
|
|
287
|
+
:param url: request URL
|
|
288
|
+
:param headers: request headers
|
|
289
|
+
:param json: request JSON payload
|
|
290
|
+
:param newer_than: if provided, checks if the signature is newer than the provided timestamp
|
|
291
|
+
:param signature_extractor: function to extract the signature from the headers
|
|
292
|
+
:return: Signature object or None if no signature found
|
|
293
|
+
:raises SignatureInvalidException: if the signature is invalid
|
|
294
|
+
"""
|
|
295
|
+
try:
|
|
296
|
+
signature = signature_extractor(headers)
|
|
297
|
+
except SignatureNotFound:
|
|
298
|
+
return None
|
|
299
|
+
verifier = BittensorWalletVerifier()
|
|
300
|
+
payload = verifier.payload_from_request(method, url, headers=headers, json=json)
|
|
301
|
+
verifier.verify(payload, signature, newer_than)
|
|
302
|
+
return signature
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import enum
|
|
2
|
+
import re
|
|
3
|
+
from typing import Annotated, Literal
|
|
4
|
+
from urllib.parse import urlparse
|
|
5
|
+
|
|
6
|
+
import pydantic
|
|
7
|
+
from pydantic import Field
|
|
8
|
+
|
|
9
|
+
SAFE_DOMAIN_REGEX = re.compile(r".*")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class VolumeType(str, enum.Enum):
|
|
13
|
+
inline = "inline"
|
|
14
|
+
zip_url = "zip_url"
|
|
15
|
+
single_file = "single_file"
|
|
16
|
+
multi_volume = "multi_volume"
|
|
17
|
+
huggingface_volume = "huggingface_volume"
|
|
18
|
+
|
|
19
|
+
# default __str__ method returns "VolumeType.inline", we want just "inline"
|
|
20
|
+
def __str__(self):
|
|
21
|
+
return str.__str__(self)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class HuggingfaceVolume(pydantic.BaseModel):
|
|
25
|
+
volume_type: Literal[VolumeType.huggingface_volume] = VolumeType.huggingface_volume
|
|
26
|
+
repo_id: str
|
|
27
|
+
# Set to "dataset" or "space" for a dataset or space, None or "model" for a model.
|
|
28
|
+
repo_type: str | None = None
|
|
29
|
+
# Git revision id: branch name / tag / commit hash
|
|
30
|
+
revision: str | None = None
|
|
31
|
+
relative_path: str | None = None
|
|
32
|
+
# If provided, only files matching at least one pattern are downloaded.
|
|
33
|
+
allow_patterns: str | list[str] | None = None
|
|
34
|
+
|
|
35
|
+
def is_safe(self) -> bool:
|
|
36
|
+
return True
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class InlineVolume(pydantic.BaseModel):
|
|
40
|
+
volume_type: Literal[VolumeType.inline] = VolumeType.inline
|
|
41
|
+
contents: str = pydantic.Field(repr=False)
|
|
42
|
+
relative_path: str | None = None
|
|
43
|
+
|
|
44
|
+
def is_safe(self) -> bool:
|
|
45
|
+
return True
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class ZipUrlVolume(pydantic.BaseModel):
|
|
49
|
+
volume_type: Literal[VolumeType.zip_url] = VolumeType.zip_url
|
|
50
|
+
contents: str # backwards compatibility - this is the URL
|
|
51
|
+
relative_path: str | None = Field(default=None)
|
|
52
|
+
|
|
53
|
+
def is_safe(self) -> bool:
|
|
54
|
+
domain = urlparse(self.contents).netloc
|
|
55
|
+
if SAFE_DOMAIN_REGEX.fullmatch(domain):
|
|
56
|
+
return True
|
|
57
|
+
return False
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class SingleFileVolume(pydantic.BaseModel):
|
|
61
|
+
volume_type: Literal[VolumeType.single_file] = VolumeType.single_file
|
|
62
|
+
url: str
|
|
63
|
+
relative_path: str
|
|
64
|
+
|
|
65
|
+
def is_safe(self) -> bool:
|
|
66
|
+
domain = urlparse(self.url).netloc
|
|
67
|
+
if SAFE_DOMAIN_REGEX.fullmatch(domain):
|
|
68
|
+
return True
|
|
69
|
+
return False
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class MultiVolume(pydantic.BaseModel):
|
|
73
|
+
volume_type: Literal[VolumeType.multi_volume] = VolumeType.multi_volume
|
|
74
|
+
volumes: list[
|
|
75
|
+
Annotated[
|
|
76
|
+
InlineVolume | ZipUrlVolume | SingleFileVolume | HuggingfaceVolume,
|
|
77
|
+
Field(discriminator="volume_type"),
|
|
78
|
+
]
|
|
79
|
+
]
|
|
80
|
+
|
|
81
|
+
def is_safe(self) -> bool:
|
|
82
|
+
return all(volume.is_safe() for volume in self.volumes)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
Volume = Annotated[
|
|
86
|
+
InlineVolume | ZipUrlVolume | SingleFileVolume | MultiVolume | HuggingfaceVolume,
|
|
87
|
+
Field(discriminator="volume_type"),
|
|
88
|
+
]
|
|
File without changes
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
class ComputeHordeError(Exception):
|
|
2
|
+
"""Something went wrong on the Compute Horde side."""
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class ComputeHordeNotFoundError(ComputeHordeError):
|
|
6
|
+
"""The requested resource was not found in Compute Horde."""
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ComputeHordeJobTimeoutError(ComputeHordeError, TimeoutError):
|
|
10
|
+
"""Compute Horde job timed out."""
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import io
|
|
3
|
+
import zipfile
|
|
4
|
+
from abc import ABC, abstractmethod
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from enum import StrEnum
|
|
8
|
+
from typing import Literal
|
|
9
|
+
|
|
10
|
+
import pydantic
|
|
11
|
+
|
|
12
|
+
from compute_horde_core import output_upload as compute_horde_output_upload
|
|
13
|
+
from compute_horde_core import volume as compute_horde_volume
|
|
14
|
+
|
|
15
|
+
VOLUME_MOUNT_PATH_PREFIX = "/volume/"
|
|
16
|
+
OUTPUT_MOUNT_PATH_PREFIX = "/output/"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ComputeHordeJobStatus(StrEnum):
|
|
20
|
+
SENT = "Sent"
|
|
21
|
+
ACCEPTED = "Accepted"
|
|
22
|
+
REJECTED = "Rejected"
|
|
23
|
+
COMPLETED = "Completed"
|
|
24
|
+
FAILED = "Failed"
|
|
25
|
+
|
|
26
|
+
def is_in_progress(self) -> bool:
|
|
27
|
+
return self in (self.SENT, self.ACCEPTED)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class ComputeHordeJobResult:
|
|
32
|
+
stdout: str
|
|
33
|
+
artifacts: dict[str, bytes]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class FacilitatorJobResponse(pydantic.BaseModel):
|
|
37
|
+
uuid: str
|
|
38
|
+
executor_class: str
|
|
39
|
+
created_at: str
|
|
40
|
+
# last_update: str
|
|
41
|
+
status: ComputeHordeJobStatus
|
|
42
|
+
docker_image: str
|
|
43
|
+
# raw_script: str
|
|
44
|
+
args: list[str]
|
|
45
|
+
env: dict
|
|
46
|
+
# use_gpu: bool
|
|
47
|
+
# hf_repo_id: str
|
|
48
|
+
# hf_revision: str
|
|
49
|
+
# input_url: str
|
|
50
|
+
# output_download_url: str
|
|
51
|
+
# tag: str
|
|
52
|
+
stdout: str
|
|
53
|
+
volumes: list = []
|
|
54
|
+
uploads: list = []
|
|
55
|
+
# target_validator_hotkey: str
|
|
56
|
+
artifacts: dict = {}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class FacilitatorJobsResponse(pydantic.BaseModel):
|
|
60
|
+
count: int
|
|
61
|
+
next: str | None = None
|
|
62
|
+
previous: str | None = None
|
|
63
|
+
results: list[FacilitatorJobResponse]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class AbstractInputVolume(ABC):
|
|
67
|
+
def get_volume_relative_path(self, mount_path: str) -> str:
|
|
68
|
+
if not mount_path.startswith(VOLUME_MOUNT_PATH_PREFIX):
|
|
69
|
+
raise ValueError(f"Input volume paths must start with {VOLUME_MOUNT_PATH_PREFIX!r}")
|
|
70
|
+
return mount_path.removeprefix(VOLUME_MOUNT_PATH_PREFIX)
|
|
71
|
+
|
|
72
|
+
@abstractmethod
|
|
73
|
+
def to_compute_horde_volume(self, mount_path: str) -> compute_horde_volume.Volume:
|
|
74
|
+
pass
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class InlineInputVolume(pydantic.BaseModel, AbstractInputVolume):
|
|
78
|
+
"""
|
|
79
|
+
Volume for inline base64 encoded files.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
contents: str
|
|
83
|
+
"""Base64 encoded contents of the file"""
|
|
84
|
+
|
|
85
|
+
def to_compute_horde_volume(self, mount_path: str) -> compute_horde_volume.InlineVolume:
|
|
86
|
+
relative_path = self.get_volume_relative_path(mount_path)
|
|
87
|
+
return compute_horde_volume.InlineVolume(
|
|
88
|
+
contents=self.contents,
|
|
89
|
+
relative_path=relative_path,
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
@classmethod
|
|
93
|
+
def from_file_contents(cls, filename: str, contents: bytes):
|
|
94
|
+
in_memory_output = io.BytesIO()
|
|
95
|
+
zipf = zipfile.ZipFile(in_memory_output, "w")
|
|
96
|
+
zipf.writestr(filename, contents)
|
|
97
|
+
zipf.close()
|
|
98
|
+
in_memory_output.seek(0)
|
|
99
|
+
zip_contents = in_memory_output.read()
|
|
100
|
+
encoded_zip_contents = base64.b64encode(zip_contents).decode()
|
|
101
|
+
return cls(
|
|
102
|
+
contents=encoded_zip_contents,
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class HuggingfaceInputVolume(pydantic.BaseModel, AbstractInputVolume):
|
|
107
|
+
"""
|
|
108
|
+
Volume for downloading resources from Huggingface.
|
|
109
|
+
|
|
110
|
+
By default, it downloads the entire repository and copier its structure.
|
|
111
|
+
To narrow it down, use the ``allow_patterns`` field.
|
|
112
|
+
If a file is inside a subfolder, it will be placed under the same path in the volume.
|
|
113
|
+
"""
|
|
114
|
+
|
|
115
|
+
repo_id: str
|
|
116
|
+
"""Huggingface repository ID, in the format "namespace/name"."""
|
|
117
|
+
|
|
118
|
+
repo_type: str | None = None
|
|
119
|
+
"""Set to "dataset" or "space" for a dataset or space, None or "model" for a model."""
|
|
120
|
+
|
|
121
|
+
revision: str | None = None
|
|
122
|
+
"""Git revision ID: branch name / tag / commit hash."""
|
|
123
|
+
|
|
124
|
+
allow_patterns: str | list[str] | None = None
|
|
125
|
+
"""If provided, only files matching at least one pattern are downloaded."""
|
|
126
|
+
|
|
127
|
+
def to_compute_horde_volume(self, mount_path: str) -> compute_horde_volume.HuggingfaceVolume:
|
|
128
|
+
relative_path = self.get_volume_relative_path(mount_path)
|
|
129
|
+
return compute_horde_volume.HuggingfaceVolume(
|
|
130
|
+
relative_path=relative_path,
|
|
131
|
+
repo_id=self.repo_id,
|
|
132
|
+
repo_type=self.repo_type,
|
|
133
|
+
revision=self.revision,
|
|
134
|
+
allow_patterns=self.allow_patterns,
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class HTTPInputVolume(pydantic.BaseModel, AbstractInputVolume):
|
|
139
|
+
"""Volume for downloading files from the Internet via HTTP."""
|
|
140
|
+
|
|
141
|
+
url: str
|
|
142
|
+
"""The URL to download the file from."""
|
|
143
|
+
|
|
144
|
+
def to_compute_horde_volume(self, mount_path: str) -> compute_horde_volume.SingleFileVolume:
|
|
145
|
+
relative_path = self.get_volume_relative_path(mount_path)
|
|
146
|
+
return compute_horde_volume.SingleFileVolume(
|
|
147
|
+
relative_path=relative_path,
|
|
148
|
+
url=self.url,
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
InputVolume = InlineInputVolume | HuggingfaceInputVolume | HTTPInputVolume
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class HTTPOutputVolume(pydantic.BaseModel):
|
|
156
|
+
http_method: Literal["POST", "PUT"]
|
|
157
|
+
"""HTTP method to use, can be POST or PUT."""
|
|
158
|
+
|
|
159
|
+
url: str
|
|
160
|
+
"""The URL to upload the file to."""
|
|
161
|
+
|
|
162
|
+
form_fields: Mapping[str, str] | None = None
|
|
163
|
+
|
|
164
|
+
signed_headers: Mapping[str, str] | None = None
|
|
165
|
+
|
|
166
|
+
def get_volume_relative_path(self, mount_path: str) -> str:
|
|
167
|
+
if not mount_path.startswith(OUTPUT_MOUNT_PATH_PREFIX):
|
|
168
|
+
raise ValueError(f"Output volume paths must start with {OUTPUT_MOUNT_PATH_PREFIX!r}")
|
|
169
|
+
return mount_path.removeprefix(OUTPUT_MOUNT_PATH_PREFIX)
|
|
170
|
+
|
|
171
|
+
def to_compute_horde_output_upload(self, mount_path: str) -> compute_horde_output_upload.OutputUpload:
|
|
172
|
+
relative_path = self.get_volume_relative_path(mount_path)
|
|
173
|
+
|
|
174
|
+
if self.http_method == "POST":
|
|
175
|
+
return compute_horde_output_upload.SingleFilePostUpload(
|
|
176
|
+
relative_path=relative_path,
|
|
177
|
+
url=self.url,
|
|
178
|
+
form_fields=self.form_fields,
|
|
179
|
+
signed_headers=self.signed_headers,
|
|
180
|
+
)
|
|
181
|
+
elif self.http_method == "PUT":
|
|
182
|
+
if self.form_fields:
|
|
183
|
+
raise ValueError("Form fields are not supported with PUT uploads.")
|
|
184
|
+
return compute_horde_output_upload.SingleFilePutUpload(
|
|
185
|
+
relative_path=relative_path,
|
|
186
|
+
url=self.url,
|
|
187
|
+
signed_headers=self.signed_headers,
|
|
188
|
+
)
|
|
189
|
+
else:
|
|
190
|
+
raise ValueError(f"Unsupported HTTP method: {self.http_method}")
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
OutputVolume = HTTPOutputVolume
|
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import base64
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
import time
|
|
6
|
+
from collections.abc import AsyncIterator, Mapping, Sequence
|
|
7
|
+
from datetime import timedelta
|
|
8
|
+
from typing import Self
|
|
9
|
+
from urllib.parse import urljoin
|
|
10
|
+
|
|
11
|
+
import bittensor
|
|
12
|
+
import httpx
|
|
13
|
+
import pydantic
|
|
14
|
+
|
|
15
|
+
from compute_horde_core.executor_class import ExecutorClass
|
|
16
|
+
from compute_horde_core.signature import BittensorWalletSigner, SignatureScope, SignedFields, signature_to_headers
|
|
17
|
+
|
|
18
|
+
from .exceptions import ComputeHordeError, ComputeHordeJobTimeoutError, ComputeHordeNotFoundError
|
|
19
|
+
from .models import (
|
|
20
|
+
ComputeHordeJobResult,
|
|
21
|
+
ComputeHordeJobStatus,
|
|
22
|
+
FacilitatorJobResponse,
|
|
23
|
+
FacilitatorJobsResponse,
|
|
24
|
+
InputVolume,
|
|
25
|
+
OutputVolume,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
logger = logging.getLogger(__name__)
|
|
29
|
+
|
|
30
|
+
JOB_REFRESH_INTERVAL = timedelta(seconds=3)
|
|
31
|
+
|
|
32
|
+
DEFAULT_FACILITATOR_URL = "https://facilitator.computehorde.io/"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ComputeHordeJob:
|
|
36
|
+
"""
|
|
37
|
+
The class representing a job running on the Compute Horde.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(
|
|
41
|
+
self,
|
|
42
|
+
client: "ComputeHordeClient",
|
|
43
|
+
uuid: str,
|
|
44
|
+
status: ComputeHordeJobStatus,
|
|
45
|
+
result: ComputeHordeJobResult | None = None,
|
|
46
|
+
):
|
|
47
|
+
self._client = client
|
|
48
|
+
self.uuid = uuid
|
|
49
|
+
self.status = status
|
|
50
|
+
self.result = result
|
|
51
|
+
|
|
52
|
+
async def wait(self, timeout: float | None = None) -> None:
|
|
53
|
+
"""
|
|
54
|
+
Wait for this job to complete or fail.
|
|
55
|
+
|
|
56
|
+
:param timeout: Maximum number of seconds to wait for.
|
|
57
|
+
:raises ComputeHordeJobTimeoutError: If the job does not complete within ``timeout`` seconds.
|
|
58
|
+
"""
|
|
59
|
+
start_time = time.monotonic()
|
|
60
|
+
|
|
61
|
+
while self.status.is_in_progress():
|
|
62
|
+
if timeout is not None and time.monotonic() - start_time > timeout:
|
|
63
|
+
raise ComputeHordeJobTimeoutError(
|
|
64
|
+
f"Job {self.uuid} did not complete within {timeout} seconds, last status: {self.status}"
|
|
65
|
+
)
|
|
66
|
+
await asyncio.sleep(JOB_REFRESH_INTERVAL.total_seconds())
|
|
67
|
+
await self.refresh_from_facilitator()
|
|
68
|
+
|
|
69
|
+
async def refresh_from_facilitator(self) -> None:
|
|
70
|
+
new_job = await self._client.get_job(self.uuid)
|
|
71
|
+
self.status = new_job.status
|
|
72
|
+
self.result = new_job.result
|
|
73
|
+
|
|
74
|
+
def __repr__(self):
|
|
75
|
+
return f"<{self.__class__.__qualname__}: {self.uuid!r}>"
|
|
76
|
+
|
|
77
|
+
@classmethod
|
|
78
|
+
def _from_response(cls, client: "ComputeHordeClient", response: FacilitatorJobResponse) -> Self:
|
|
79
|
+
result = None
|
|
80
|
+
if not response.status.is_in_progress():
|
|
81
|
+
# TODO: Handle base64 decode errors
|
|
82
|
+
result = ComputeHordeJobResult(
|
|
83
|
+
stdout=response.stdout,
|
|
84
|
+
artifacts={path: base64.b64decode(base64_data) for path, base64_data in response.artifacts.items()},
|
|
85
|
+
)
|
|
86
|
+
return cls(
|
|
87
|
+
client,
|
|
88
|
+
uuid=response.uuid,
|
|
89
|
+
status=response.status,
|
|
90
|
+
result=result,
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class ComputeHordeClient:
|
|
95
|
+
"""
|
|
96
|
+
The class used to communicate with the Compute Horde.
|
|
97
|
+
"""
|
|
98
|
+
|
|
99
|
+
def __init__(
|
|
100
|
+
self,
|
|
101
|
+
hotkey: bittensor.Keypair,
|
|
102
|
+
compute_horde_validator_hotkey: str,
|
|
103
|
+
job_queue: str | None = None,
|
|
104
|
+
facilitator_url: str = DEFAULT_FACILITATOR_URL,
|
|
105
|
+
):
|
|
106
|
+
"""
|
|
107
|
+
Create a new Compute Horde client.
|
|
108
|
+
|
|
109
|
+
:param hotkey: Your wallet hotkey, used for signing requests.
|
|
110
|
+
:param compute_horde_validator_hotkey: The hotkey for the validator that your jobs should go to.
|
|
111
|
+
:param job_queue: A user-defined string value that will allow for retrieving all pending jobs,
|
|
112
|
+
for example after process restart, relevant to this process.
|
|
113
|
+
:param facilitator_url: The URL to use for the Compute Horde Facilitator API.
|
|
114
|
+
"""
|
|
115
|
+
self.hotkey = hotkey
|
|
116
|
+
self.compute_horde_validator_hotkey = compute_horde_validator_hotkey
|
|
117
|
+
self.job_queue = job_queue
|
|
118
|
+
self.facilitator_url = facilitator_url
|
|
119
|
+
self._client = httpx.AsyncClient(base_url=self.facilitator_url, follow_redirects=True)
|
|
120
|
+
self._signer = BittensorWalletSigner(hotkey)
|
|
121
|
+
|
|
122
|
+
async def _make_request(
|
|
123
|
+
self,
|
|
124
|
+
method: str,
|
|
125
|
+
url: str,
|
|
126
|
+
*,
|
|
127
|
+
json: dict | None = None,
|
|
128
|
+
params: Mapping[str, str | int] | None = None,
|
|
129
|
+
headers: Mapping[str, str] | None = None,
|
|
130
|
+
) -> str:
|
|
131
|
+
"""
|
|
132
|
+
:return: Response content as string.
|
|
133
|
+
"""
|
|
134
|
+
auth_headers = self._get_authentication_headers(method, urljoin(self.facilitator_url, url))
|
|
135
|
+
request = self._client.build_request(
|
|
136
|
+
method=method,
|
|
137
|
+
url=url,
|
|
138
|
+
json=json,
|
|
139
|
+
params=params,
|
|
140
|
+
headers={**headers, **auth_headers} if headers else auth_headers,
|
|
141
|
+
)
|
|
142
|
+
logger.debug("%s %s", method, request.url)
|
|
143
|
+
response = await self._client.send(request)
|
|
144
|
+
try:
|
|
145
|
+
response.raise_for_status()
|
|
146
|
+
except httpx.HTTPStatusError as e:
|
|
147
|
+
logger.error("Response status=%d: %s", e.response.status_code, e.response.text)
|
|
148
|
+
if e.response.status_code == 404:
|
|
149
|
+
raise ComputeHordeNotFoundError(f"Resource under {request.url} not found") from e
|
|
150
|
+
raise ComputeHordeError(f"Compute Horde responded with status code {e.response.status_code}") from e
|
|
151
|
+
|
|
152
|
+
return response.text
|
|
153
|
+
|
|
154
|
+
def _get_signature_headers(self, data: dict) -> dict[str, str]:
|
|
155
|
+
signed_fields = SignedFields.from_facilitator_sdk_json(data)
|
|
156
|
+
signature = self._signer.sign(payload=signed_fields.model_dump_json())
|
|
157
|
+
return signature_to_headers(signature, SignatureScope.SignedFields)
|
|
158
|
+
|
|
159
|
+
def _get_cheated_job_headers(self, data: dict) -> dict[str, str]:
|
|
160
|
+
payload = json.dumps(data, sort_keys=True)
|
|
161
|
+
signature = self._signer.sign(payload=payload)
|
|
162
|
+
return signature_to_headers(signature, SignatureScope.FullRequest)
|
|
163
|
+
|
|
164
|
+
def _get_authentication_headers(
|
|
165
|
+
self,
|
|
166
|
+
method: str,
|
|
167
|
+
url: str,
|
|
168
|
+
):
|
|
169
|
+
headers = {
|
|
170
|
+
"Realm": "mainnet",
|
|
171
|
+
"SubnetID": "12",
|
|
172
|
+
"Nonce": str(time.time()),
|
|
173
|
+
"Hotkey": self.hotkey.ss58_address,
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
headers_str = json.dumps(headers, sort_keys=True)
|
|
177
|
+
|
|
178
|
+
data_to_sign = f"{method}{url}{headers_str}".encode()
|
|
179
|
+
|
|
180
|
+
signature = self.hotkey.sign(
|
|
181
|
+
data_to_sign,
|
|
182
|
+
).hex()
|
|
183
|
+
headers["Signature"] = signature
|
|
184
|
+
|
|
185
|
+
return headers
|
|
186
|
+
|
|
187
|
+
async def report_cheated_job(self, job_uuid: str) -> str:
|
|
188
|
+
"""
|
|
189
|
+
Reports to validator that a miner has cheated on a job.
|
|
190
|
+
|
|
191
|
+
:param job_uuid: The UUID of the job that was cheated on.
|
|
192
|
+
:param miner_hotkey: The hotkey of the miner that cheated.
|
|
193
|
+
"""
|
|
194
|
+
data = {"job_uuid": job_uuid}
|
|
195
|
+
signature_headers = self._get_cheated_job_headers(data)
|
|
196
|
+
response = await self._make_request("POST", "/api/v1/cheated-job/", json=data, headers=signature_headers)
|
|
197
|
+
logger.debug("Reported job %s", job_uuid)
|
|
198
|
+
return response
|
|
199
|
+
|
|
200
|
+
async def create_job(
|
|
201
|
+
self,
|
|
202
|
+
executor_class: ExecutorClass,
|
|
203
|
+
job_namespace: str,
|
|
204
|
+
docker_image: str,
|
|
205
|
+
args: Sequence[str] | None = None,
|
|
206
|
+
env: Mapping[str, str] | None = None,
|
|
207
|
+
artifacts_dir: str | None = None,
|
|
208
|
+
input_volumes: Mapping[str, InputVolume] | None = None,
|
|
209
|
+
output_volumes: Mapping[str, OutputVolume] | None = None,
|
|
210
|
+
trusted_output_volumes: Mapping[str, OutputVolume] | None = None,
|
|
211
|
+
on_trusted_miner: bool = False,
|
|
212
|
+
) -> ComputeHordeJob:
|
|
213
|
+
"""
|
|
214
|
+
Create a new job to run in the Compute Horde.
|
|
215
|
+
|
|
216
|
+
:param executor_class: Class of the executor machine to run the job on.
|
|
217
|
+
:param job_namespace: Specifies where the job comes from.
|
|
218
|
+
The recommended format is the subnet number and version, like e.g. ``"SN123.0"``.
|
|
219
|
+
:param docker_image: Docker image of the job, in the form of ``user/image:tag``.
|
|
220
|
+
:param args: Positional arguments and flags to run the job with.
|
|
221
|
+
:param env: Environment variables to run the job with.
|
|
222
|
+
:param artifacts_dir: Path of the directory that the job will write its results to.
|
|
223
|
+
Contents of files found in this directory will be returned after the job completes
|
|
224
|
+
as a part of the job result. It should be an absolute path (starting with ``/``).
|
|
225
|
+
:param input_volumes: The data to be made available to the job in Docker volumes.
|
|
226
|
+
The keys should be absolute file/directory paths under which you want your data to be available.
|
|
227
|
+
The values should be ``InputVolume`` instances representing how to obtain the input data.
|
|
228
|
+
For now, input volume paths must start with ``/volume/``.
|
|
229
|
+
:param output_volumes: The data to be read from the Docker volumes after job completion
|
|
230
|
+
and uploaded to the described destinations. Use this for outputs that are too big
|
|
231
|
+
or too unstable to be treated as ``artifacts``.
|
|
232
|
+
The keys should be absolute file paths under which job output data will be available.
|
|
233
|
+
The values should be ``OutputVolume`` instances representing how to handle the output data.
|
|
234
|
+
For now, output volume paths must start with ``/output/``.
|
|
235
|
+
:param trusted_output_volumes: Output volumes for cross validation on a trusted miner.
|
|
236
|
+
If these are omitted then cross validating on a trusted miner will not result in any uploads.
|
|
237
|
+
:param on_trusted_miner: If true, the job will be run on the sn12 validator's trusted miner.
|
|
238
|
+
:return: A ``ComputeHordeJob`` class instance representing the created job.
|
|
239
|
+
"""
|
|
240
|
+
|
|
241
|
+
# TODO: make this a pydantic model?
|
|
242
|
+
data: dict[str, pydantic.JsonValue] = {
|
|
243
|
+
"target_validator_hotkey": self.compute_horde_validator_hotkey,
|
|
244
|
+
"executor_class": executor_class,
|
|
245
|
+
"docker_image": docker_image,
|
|
246
|
+
"args": args or [], # type: ignore
|
|
247
|
+
"env": env or {}, # type: ignore
|
|
248
|
+
"use_gpu": True,
|
|
249
|
+
"artifacts_dir": artifacts_dir,
|
|
250
|
+
"on_trusted_miner": on_trusted_miner,
|
|
251
|
+
}
|
|
252
|
+
if input_volumes is not None:
|
|
253
|
+
data["volumes"] = [
|
|
254
|
+
input_volume.to_compute_horde_volume(mount_path).model_dump()
|
|
255
|
+
for mount_path, input_volume in input_volumes.items()
|
|
256
|
+
]
|
|
257
|
+
|
|
258
|
+
if output_volumes is not None:
|
|
259
|
+
data["uploads"] = [
|
|
260
|
+
output_volume.to_compute_horde_output_upload(mount_path).model_dump()
|
|
261
|
+
for mount_path, output_volume in output_volumes.items()
|
|
262
|
+
]
|
|
263
|
+
|
|
264
|
+
logger.debug("Creating job from image %s", docker_image)
|
|
265
|
+
signature_headers = self._get_signature_headers(data)
|
|
266
|
+
|
|
267
|
+
response = await self._make_request("POST", "/api/v1/job-docker/", json=data, headers=signature_headers)
|
|
268
|
+
|
|
269
|
+
try:
|
|
270
|
+
job_response = FacilitatorJobResponse.model_validate_json(response)
|
|
271
|
+
except pydantic.ValidationError as e:
|
|
272
|
+
raise ComputeHordeError("Compute Horde returned malformed response") from e
|
|
273
|
+
|
|
274
|
+
job = ComputeHordeJob._from_response(self, job_response)
|
|
275
|
+
logger.debug("Created job with UUID=%s", job.uuid)
|
|
276
|
+
|
|
277
|
+
return job
|
|
278
|
+
|
|
279
|
+
async def get_job(self, job_uuid: str) -> ComputeHordeJob:
|
|
280
|
+
"""
|
|
281
|
+
Retrieve information about a job from the Compute Horde.
|
|
282
|
+
|
|
283
|
+
:param job_uuid: The UUID of the job to retrieve.
|
|
284
|
+
:return: A ``ComputeHordeJob`` instance representing this job.
|
|
285
|
+
:raises ComputeHordeNotFoundError: If the job with this UUID does not exist.
|
|
286
|
+
"""
|
|
287
|
+
logger.debug("Fetching job with UUID=%s", job_uuid)
|
|
288
|
+
|
|
289
|
+
response = await self._make_request("GET", f"/api/v1/jobs/{job_uuid}/")
|
|
290
|
+
|
|
291
|
+
try:
|
|
292
|
+
job_response = FacilitatorJobResponse.model_validate_json(response)
|
|
293
|
+
except pydantic.ValidationError as e:
|
|
294
|
+
raise ComputeHordeError("Compute Horde returned malformed response") from e
|
|
295
|
+
|
|
296
|
+
return ComputeHordeJob._from_response(self, job_response)
|
|
297
|
+
|
|
298
|
+
async def _get_jobs_page(self, page: int = 1, page_size: int = 10) -> FacilitatorJobsResponse:
|
|
299
|
+
params = {"page": page, "page_size": page_size}
|
|
300
|
+
|
|
301
|
+
response = await self._make_request("GET", "/api/v1/jobs/", params=params)
|
|
302
|
+
|
|
303
|
+
try:
|
|
304
|
+
jobs_response = FacilitatorJobsResponse.model_validate_json(response)
|
|
305
|
+
except pydantic.ValidationError as e:
|
|
306
|
+
raise ComputeHordeError("Compute Horde returned malformed response") from e
|
|
307
|
+
|
|
308
|
+
return jobs_response
|
|
309
|
+
|
|
310
|
+
async def get_jobs(self, page: int = 1, page_size: int = 10) -> list[ComputeHordeJob]:
|
|
311
|
+
"""
|
|
312
|
+
Retrieve information about your jobs from the Compute Horde.
|
|
313
|
+
|
|
314
|
+
:param page: The page number.
|
|
315
|
+
:param page_size: The page size.
|
|
316
|
+
:return: A list of ``ComputeHordeJob`` instances representing your jobs.
|
|
317
|
+
:raises ComputeHordeNotFoundError: If the requested page does not exist.
|
|
318
|
+
"""
|
|
319
|
+
logger.debug("Fetching jobs page=%d, page_size%d", page, page_size)
|
|
320
|
+
jobs_response = await self._get_jobs_page(page=page, page_size=page_size)
|
|
321
|
+
|
|
322
|
+
return [ComputeHordeJob._from_response(self, job) for job in jobs_response.results]
|
|
323
|
+
|
|
324
|
+
async def iter_jobs(self) -> AsyncIterator[ComputeHordeJob]:
|
|
325
|
+
"""
|
|
326
|
+
Retrieve information about your jobs from the Compute Horde.
|
|
327
|
+
|
|
328
|
+
:return: An async iterator of ``ComputeHordeJob`` instances representing your jobs.
|
|
329
|
+
|
|
330
|
+
Usage::
|
|
331
|
+
|
|
332
|
+
async for job in client.iter_jobs():
|
|
333
|
+
process(job)
|
|
334
|
+
"""
|
|
335
|
+
logger.debug("Iterating over jobs.")
|
|
336
|
+
page = 1
|
|
337
|
+
page_size = 10
|
|
338
|
+
has_next_page = True
|
|
339
|
+
while has_next_page:
|
|
340
|
+
jobs_response = await self._get_jobs_page(page=page, page_size=page_size)
|
|
341
|
+
for job_response in jobs_response.results:
|
|
342
|
+
yield ComputeHordeJob._from_response(self, job_response)
|
|
343
|
+
|
|
344
|
+
has_next_page = jobs_response.next is not None
|
|
345
|
+
page += 1
|
|
File without changes
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# ruff: noqa
|
|
2
|
+
"""
|
|
3
|
+
Public interface of the compute_horde_sdk package.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from compute_horde_sdk._internal.exceptions import (
|
|
7
|
+
ComputeHordeError,
|
|
8
|
+
ComputeHordeNotFoundError,
|
|
9
|
+
ComputeHordeJobTimeoutError,
|
|
10
|
+
)
|
|
11
|
+
from compute_horde_sdk._internal.models import (
|
|
12
|
+
ComputeHordeJobStatus,
|
|
13
|
+
InputVolume,
|
|
14
|
+
HTTPInputVolume,
|
|
15
|
+
HuggingfaceInputVolume,
|
|
16
|
+
InlineInputVolume,
|
|
17
|
+
OutputVolume,
|
|
18
|
+
HTTPOutputVolume,
|
|
19
|
+
)
|
|
20
|
+
from compute_horde_sdk._internal.sdk import ComputeHordeClient, ComputeHordeJob
|
|
21
|
+
from compute_horde_core.executor_class import ExecutorClass
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: compute-horde-sdk
|
|
3
|
+
Version: 0.0.0
|
|
4
|
+
Author-Email: Reef Technologies <opensource@reef.pl>
|
|
5
|
+
License: MIT
|
|
6
|
+
Classifier: Intended Audience :: Developers
|
|
7
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
8
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
12
|
+
Project-URL: Source, https://github.com/backend-developers-ltd/compute-horde-sdk
|
|
13
|
+
Project-URL: Issue Tracker, https://github.com/backend-developers-ltd/compute-horde-sdk/issues
|
|
14
|
+
Requires-Python: <3.13,>=3.11
|
|
15
|
+
Requires-Dist: pydantic<3,>=2.10
|
|
16
|
+
Requires-Dist: httpx>=0.26.0
|
|
17
|
+
Requires-Dist: bittensor<9.1,>=9.0.0
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# compute_horde_sdk
|
|
21
|
+
[](https://github.com/backend-developers-ltd/compute-horde-sdk/actions?query=workflow%3A%22Continuous+Integration%22) [](https://pypi.python.org/pypi/compute_horde_sdk) [](https://pypi.python.org/pypi/compute_horde_sdk) [](https://pypi.python.org/pypi/compute_horde_sdk)
|
|
22
|
+
|
|
23
|
+
## Installation
|
|
24
|
+
|
|
25
|
+
```
|
|
26
|
+
pip install compute-horde-sdk
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Usage
|
|
30
|
+
|
|
31
|
+
> [!IMPORTANT]
|
|
32
|
+
> This package uses [ApiVer](#versioning), make sure to import `compute_horde_sdk.v1`.
|
|
33
|
+
|
|
34
|
+
Simple example:
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
import asyncio
|
|
38
|
+
import bittensor
|
|
39
|
+
from compute_horde_sdk.v1 import ComputeHordeClient, ExecutorClass
|
|
40
|
+
|
|
41
|
+
wallet = bittensor.wallet(name="...", hotkey="...")
|
|
42
|
+
|
|
43
|
+
compute_horde_client = ComputeHordeClient(
|
|
44
|
+
hotkey=wallet.hotkey,
|
|
45
|
+
compute_horde_validator_hotkey="...", # In the common case it's going to be the same as the ss58 address of the hotkey above.
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
async def main():
|
|
49
|
+
# Create a job to run on the Compute Horde.
|
|
50
|
+
job = await compute_horde_client.create_job(
|
|
51
|
+
executor_class=ExecutorClass.always_on__llm__a6000,
|
|
52
|
+
job_namespace="SN123.0",
|
|
53
|
+
docker_image="my-username/my-image:latest",
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
await job.wait(timeout=10 * 60)
|
|
57
|
+
|
|
58
|
+
print(job.status) # Should be "Completed".
|
|
59
|
+
|
|
60
|
+
asyncio.run(main())
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Advanced example:
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
import asyncio
|
|
67
|
+
import bittensor
|
|
68
|
+
from compute_horde_sdk.v1 import ComputeHordeClient, ExecutorClass, InlineInputVolume, HuggingfaceInputVolume, HTTPInputVolume, HTTPOutputVolume
|
|
69
|
+
|
|
70
|
+
wallet = bittensor.wallet(name="...", hotkey="...")
|
|
71
|
+
|
|
72
|
+
compute_horde_client = ComputeHordeClient(
|
|
73
|
+
hotkey=wallet.hotkey,
|
|
74
|
+
compute_horde_validator_hotkey="...", # In the common case it's going to be the same as the ss58 address of the hotkey above.
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
async def main():
|
|
78
|
+
# Create a job to run on the Compute Horde.
|
|
79
|
+
job = await compute_horde_client.create_job(
|
|
80
|
+
executor_class=ExecutorClass.always_on__llm__a6000,
|
|
81
|
+
job_namespace="SN123.0",
|
|
82
|
+
docker_image="my-username/my-image:latest",
|
|
83
|
+
args=["main.py", "--block", "10000"],
|
|
84
|
+
env={"HF_HUB_ENABLE_HF_TRANSFER": "1"},
|
|
85
|
+
artifacts_dir="/artifacts",
|
|
86
|
+
input_volumes={
|
|
87
|
+
"/volume/models/model01": HuggingfaceInputVolume(
|
|
88
|
+
repo_id="my-username/my-model",
|
|
89
|
+
),
|
|
90
|
+
"/volume/data/version.txt": InlineInputVolume(
|
|
91
|
+
contents="dmVyc2lvbj0y",
|
|
92
|
+
),
|
|
93
|
+
"/volume/data/dataset.json": HTTPInputVolume(
|
|
94
|
+
url="https://my-dataset-bucket.s3.amazonaws.com/sample-dataset/data.json",
|
|
95
|
+
),
|
|
96
|
+
},
|
|
97
|
+
output_volumes={
|
|
98
|
+
"/output/image.png": HTTPOutputVolume(
|
|
99
|
+
http_method="PUT",
|
|
100
|
+
url="https://my-image-bucket.s3.amazonaws.com/images/image.png",
|
|
101
|
+
),
|
|
102
|
+
},
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
await job.wait(timeout=10 * 60)
|
|
106
|
+
|
|
107
|
+
print(job.status) # Should be "Completed".
|
|
108
|
+
print(job.result)
|
|
109
|
+
|
|
110
|
+
asyncio.run(main())
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Get job by UUID:
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
```python
|
|
117
|
+
job = await client.get_job("7b522daa-e807-4094-8d96-99b9a863f960")
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Iterate over all of your jobs:
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
async for job in client.iter_jobs():
|
|
124
|
+
process(job)
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## Versioning
|
|
128
|
+
|
|
129
|
+
This package uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
130
|
+
TL;DR you are safe to use [compatible release version specifier](https://packaging.python.org/en/latest/specifications/version-specifiers/#compatible-release) `~=MAJOR.MINOR` in your `pyproject.toml` or `requirements.txt`.
|
|
131
|
+
|
|
132
|
+
Additionally, this package uses [ApiVer](https://www.youtube.com/watch?v=FgcoAKchPjk) to further reduce the risk of breaking changes.
|
|
133
|
+
This means, the public API of this package is explicitly versioned, e.g. `compute_horde_sdk.v1`, and will not change in a backwards-incompatible way even when `compute_horde_sdk.v2` is released.
|
|
134
|
+
|
|
135
|
+
Internal packages, i.e. prefixed by `compute_horde_sdk._` do not share these guarantees and may change in a backwards-incompatible way at any time even in patch releases.
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
## Development
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
Pre-requisites:
|
|
142
|
+
- [pdm](https://pdm.fming.dev/)
|
|
143
|
+
- [nox](https://nox.thea.codes/en/stable/)
|
|
144
|
+
- [docker](https://www.docker.com/) and [docker compose plugin](https://docs.docker.com/compose/)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
Ideally, you should run `nox -t format lint` before every commit to ensure that the code is properly formatted and linted.
|
|
148
|
+
Before submitting a PR, make sure that tests pass as well, you can do so using:
|
|
149
|
+
```
|
|
150
|
+
nox -t check # equivalent to `nox -t format lint test`
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
If you wish to install dependencies into `.venv` so your IDE can pick them up, you can do so using:
|
|
154
|
+
```
|
|
155
|
+
pdm install --dev
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
### Release process
|
|
159
|
+
|
|
160
|
+
Run `nox -s make_release -- X.Y.Z` where `X.Y.Z` is the version you're releasing and follow the printed instructions.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
compute_horde_core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
compute_horde_core/executor_class.py,sha256=FxPnCzY2hqnmJfSG4vDaSUReo5N-Lj206f8RPXiPds8,207
|
|
3
|
+
compute_horde_core/output_upload.py,sha256=2upWyp4lKg7gr0qIco-a0ccRo8Bt_SNHdtYaULyRBkw,2716
|
|
4
|
+
compute_horde_core/signature.py,sha256=M3Cfr49UpiGKvBGHpkpfrLpm4bpQvylcKMq4jpa4W6g,9588
|
|
5
|
+
compute_horde_core/volume.py,sha256=LUkNLsNV70jbgTmcQWFgX62TphAGYiAripV82k4tXNM,2589
|
|
6
|
+
compute_horde_sdk-0.0.0.dist-info/METADATA,sha256=PdnLPjk5nXr4876Tw3KjS0E9HBCW7hbU0CxgPu_EYa4,5830
|
|
7
|
+
compute_horde_sdk-0.0.0.dist-info/WHEEL,sha256=thaaA2w1JzcGC48WYufAs8nrYZjJm8LqNfnXFOFyCC4,90
|
|
8
|
+
compute_horde_sdk-0.0.0.dist-info/entry_points.txt,sha256=6OYgBcLyFCUgeqLgnvMyOJxPCWzgy7se4rLPKtNonMs,34
|
|
9
|
+
compute_horde_sdk-0.0.0.dist-info/licenses/LICENSE,sha256=nqutK7kEINqDWFYPne5J_kdYi0xNndSJflQ6s1qGd80,1079
|
|
10
|
+
compute_horde_sdk/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
11
|
+
compute_horde_sdk/_internal/__init__.py,sha256=pdsBx0x7n1sIdIQx1u_t0VXHFyJ5rTE6GzA7fJvxo1w,141
|
|
12
|
+
compute_horde_sdk/_internal/exceptions.py,sha256=Mj6j-5JP3XAlHTB3UgRWKA9J74iIeeJv7-Hsg4-b0J0,322
|
|
13
|
+
compute_horde_sdk/_internal/models.py,sha256=1IBn-mGkGxreOdCRwgqGI0dIihYb0BEkGWMvipyzHEE,6180
|
|
14
|
+
compute_horde_sdk/_internal/sdk.py,sha256=ZTkGnbX0LHHM-fXuP_mm-HC47Ym2LPsEatHw_u0AFKQ,13933
|
|
15
|
+
compute_horde_sdk/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
16
|
+
compute_horde_sdk/v1/__init__.py,sha256=Hi3XBDgrCQEUL8IRAE46gJvZ3ZAjzFHX0-2KM_l347s,562
|
|
17
|
+
compute_horde_sdk-0.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 backend-developers-ltd
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|