verify.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. """Utilities for wandb verify."""
  2. from __future__ import annotations
  3. import contextlib
  4. import getpass
  5. import io
  6. import os
  7. import time
  8. from functools import partial
  9. from pathlib import Path
  10. from typing import Any, Callable
  11. import click
  12. import requests
  13. from wandb_gql import gql
  14. import wandb
  15. from wandb.sdk.artifacts.artifact import Artifact
  16. from wandb.sdk.lib import runid
  17. from ...apis.internal import Api
  18. PROJECT_NAME = "verify"
  19. GET_RUN_MAX_TIME = 10
  20. MIN_RETRYS = 3
  21. CHECKMARK = "\u2705"
  22. RED_X = "\u274c"
  23. ID_PREFIX = runid.generate_id()
  24. def nice_id(name):
  25. return ID_PREFIX + "-" + name
  26. def print_results(failed_test_or_tests: str | list[str] | None, warning: bool) -> None:
  27. if warning:
  28. color = "yellow"
  29. else:
  30. color = "red"
  31. if isinstance(failed_test_or_tests, str):
  32. print(RED_X) # noqa: T201
  33. print(click.style(failed_test_or_tests, fg=color, bold=True)) # noqa: T201
  34. elif isinstance(failed_test_or_tests, list) and len(failed_test_or_tests) > 0:
  35. print(RED_X) # noqa: T201
  36. print( # noqa: T201
  37. "\n".join(
  38. [click.style(f, fg=color, bold=True) for f in failed_test_or_tests]
  39. )
  40. )
  41. else:
  42. print(CHECKMARK) # noqa: T201
  43. def check_host(host: str) -> bool:
  44. if host in ("api.wandb.ai", "http://api.wandb.ai", "https://api.wandb.ai"):
  45. print_results("Cannot run wandb verify against api.wandb.ai", False)
  46. return False
  47. return True
  48. def check_logged_in(api: Api, host: str) -> bool:
  49. print("Checking if logged in".ljust(72, "."), end="") # noqa: T201
  50. login_doc_url = "https://docs.wandb.ai/models/ref/cli/wandb-login"
  51. fail_string = None
  52. if api.api_key is None:
  53. fail_string = (
  54. "Not logged in. Please log in using `wandb login`. See the docs: {}".format(
  55. click.style(login_doc_url, underline=True, fg="blue")
  56. )
  57. )
  58. # check that api key is correct
  59. # TODO: Better check for api key is correct
  60. else:
  61. res = api.api.viewer()
  62. if not res:
  63. fail_string = (
  64. "Could not get viewer with default API key. "
  65. f"Please relogin using `WANDB_BASE_URL={host} wandb login --relogin` and try again"
  66. )
  67. print_results(fail_string, False)
  68. return fail_string is None
  69. def check_secure_requests(url: str, test_url_string: str, failure_output: str) -> None:
  70. # check if request is over https
  71. print(test_url_string.ljust(72, "."), end="") # noqa: T201
  72. fail_string = None
  73. if not url.startswith("https"):
  74. fail_string = failure_output
  75. print_results(fail_string, True)
  76. def check_cors_configuration(url: str, origin: str) -> None:
  77. print("Checking CORs configuration of the bucket".ljust(72, "."), end="") # noqa: T201
  78. fail_string = None
  79. res_get = requests.options(
  80. url, headers={"Origin": origin, "Access-Control-Request-Method": "GET"}
  81. )
  82. if res_get.headers.get("Access-Control-Allow-Origin") is None:
  83. fail_string = (
  84. "Your object store does not have a valid CORs configuration, "
  85. f"you must allow GET and PUT to Origin: {origin}"
  86. )
  87. print_results(fail_string, True)
  88. def check_run(api: Api) -> bool:
  89. print( # noqa: T201
  90. "Checking logged metrics, saving and downloading a file".ljust(72, "."), end=""
  91. )
  92. failed_test_strings = []
  93. # set up config
  94. n_epochs = 4
  95. string_test = "A test config"
  96. dict_test = {"config_val": 2, "config_string": "config string"}
  97. list_test = [0, "one", "2"]
  98. config = {
  99. "epochs": n_epochs,
  100. "stringTest": string_test,
  101. "dictTest": dict_test,
  102. "listTest": list_test,
  103. }
  104. # create a file to save
  105. filepath = "./test with_special-characters.txt"
  106. f = open(filepath, "w")
  107. f.write("test")
  108. f.close()
  109. with wandb.init(
  110. id=nice_id("check_run"),
  111. reinit=True,
  112. config=config,
  113. project=PROJECT_NAME,
  114. ) as run:
  115. run_id = run.id
  116. entity = run.entity
  117. logged = True
  118. try:
  119. for i in range(1, 11):
  120. run.log({"loss": 1.0 / i}, step=i)
  121. log_dict = {"val1": 1.0, "val2": 2}
  122. run.log({"dict": log_dict}, step=i + 1)
  123. except Exception:
  124. logged = False
  125. failed_test_strings.append(
  126. "Failed to log values to run. Contact W&B for support."
  127. )
  128. try:
  129. run.log({"HT%3ML ": wandb.Html('<a href="https://mysite">Link</a>')})
  130. except Exception:
  131. failed_test_strings.append(
  132. "Failed to log to media. Contact W&B for support."
  133. )
  134. run.save(filepath)
  135. public_api = wandb.Api()
  136. prev_run = public_api.run(f"{entity}/{PROJECT_NAME}/{run_id}")
  137. # raise Exception(prev_run.__dict__)
  138. if prev_run is None:
  139. failed_test_strings.append(
  140. "Failed to access run through API. Contact W&B for support."
  141. )
  142. print_results(failed_test_strings, False)
  143. return False
  144. for key, value in config.items():
  145. if prev_run.config.get(key) != value:
  146. failed_test_strings.append(
  147. "Read config values don't match run config. Contact W&B for support."
  148. )
  149. break
  150. if logged and (
  151. prev_run.history_keys["keys"]["loss"]["previousValue"] != 0.1
  152. or prev_run.history_keys["lastStep"] != 11
  153. or prev_run.history_keys["keys"]["dict.val1"]["previousValue"] != 1.0
  154. or prev_run.history_keys["keys"]["dict.val2"]["previousValue"] != 2
  155. ):
  156. failed_test_strings.append(
  157. "History metrics don't match logged values. Check database encoding."
  158. )
  159. if logged and prev_run.summary["loss"] != 1.0 / 10:
  160. failed_test_strings.append(
  161. "Read summary values don't match expected value. Check database encoding, or contact W&B for support."
  162. )
  163. # TODO: (kdg) refactor this so it doesn't rely on an exception handler
  164. try:
  165. read_file = retry_fn(partial(prev_run.file, filepath))
  166. # There's a race where the file hasn't been processed in the queue,
  167. # we just retry until we get a download
  168. read_file = retry_fn(partial(read_file.download, replace=True))
  169. except Exception:
  170. failed_test_strings.append(
  171. "Unable to download file. Check SQS configuration, topic configuration and bucket permissions."
  172. )
  173. print_results(failed_test_strings, False)
  174. return False
  175. contents = read_file.read()
  176. if contents != "test":
  177. failed_test_strings.append(
  178. "Contents of downloaded file do not match uploaded contents. Contact W&B for support."
  179. )
  180. print_results(failed_test_strings, False)
  181. return len(failed_test_strings) == 0
  182. def verify_manifest(
  183. downloaded_manifest: dict[str, Any],
  184. computed_manifest: dict[str, Any],
  185. fails_list: list[str],
  186. ) -> None:
  187. try:
  188. for key in computed_manifest:
  189. assert (
  190. computed_manifest[key]["digest"] == downloaded_manifest[key]["digest"]
  191. )
  192. assert computed_manifest[key]["size"] == downloaded_manifest[key]["size"]
  193. except AssertionError:
  194. fails_list.append(
  195. "Artifact manifest does not appear as expected. Contact W&B for support."
  196. )
  197. def verify_digest(
  198. downloaded: Artifact, computed: Artifact, fails_list: list[str]
  199. ) -> None:
  200. if downloaded.digest != computed.digest:
  201. fails_list.append(
  202. "Artifact digest does not appear as expected. Contact W&B for support."
  203. )
  204. def artifact_with_path_or_paths(
  205. name: str, verify_dir: str | None = None, singular: bool = False
  206. ) -> Artifact:
  207. art = wandb.Artifact(type="artsy", name=name)
  208. # internal file
  209. with open("verify_int_test.txt", "w") as f:
  210. f.write("test 1")
  211. f.close()
  212. art.add_file(f.name)
  213. if singular:
  214. return art
  215. if verify_dir is None:
  216. verify_dir = "./"
  217. with art.new_file("verify_a.txt") as f:
  218. f.write("test 2")
  219. if not os.path.exists(verify_dir):
  220. os.makedirs(verify_dir)
  221. with open(f"{verify_dir}/verify_1.txt", "w") as f:
  222. f.write("1")
  223. art.add_dir(verify_dir)
  224. file3 = Path(verify_dir) / "verify_3.txt"
  225. file3.write_text("3")
  226. # reference to local file
  227. art.add_reference(file3.resolve().as_uri())
  228. return art
  229. def log_use_download_artifact(
  230. artifact: Artifact,
  231. alias: str,
  232. name: str,
  233. download_dir: str,
  234. failed_test_strings: list[str],
  235. add_extra_file: bool,
  236. ) -> tuple[bool, Artifact | None, list[str]]:
  237. with wandb.init(
  238. id=nice_id("log_artifact"),
  239. reinit=True,
  240. project=PROJECT_NAME,
  241. config={"test": "artifact log"},
  242. ) as log_art_run:
  243. if add_extra_file:
  244. with open("verify_2.txt", "w") as f:
  245. f.write("2")
  246. f.close()
  247. artifact.add_file(f.name)
  248. try:
  249. log_art_run.log_artifact(artifact, aliases=alias)
  250. except Exception as e:
  251. failed_test_strings.append(f"Unable to log artifact. {e}")
  252. return False, None, failed_test_strings
  253. with wandb.init(
  254. id=nice_id("use_artifact"),
  255. project=PROJECT_NAME,
  256. config={"test": "artifact use"},
  257. ) as use_art_run:
  258. try:
  259. used_art = use_art_run.use_artifact(f"{name}:{alias}")
  260. except Exception as e:
  261. failed_test_strings.append(f"Unable to use artifact. {e}")
  262. return False, None, failed_test_strings
  263. try:
  264. used_art.download(root=download_dir)
  265. except Exception:
  266. failed_test_strings.append(
  267. "Unable to download artifact. Check bucket permissions."
  268. )
  269. return False, None, failed_test_strings
  270. return True, used_art, failed_test_strings
  271. def check_artifacts() -> bool:
  272. print("Checking artifact save and download workflows".ljust(72, "."), end="") # noqa: T201
  273. failed_test_strings: list[str] = []
  274. # test checksum
  275. sing_art_dir = "./verify_sing_art"
  276. alias = "sing_art1"
  277. name = nice_id("sing-artys")
  278. singular_art = artifact_with_path_or_paths(name, singular=True)
  279. cont_test, download_artifact, failed_test_strings = log_use_download_artifact(
  280. singular_art, alias, name, sing_art_dir, failed_test_strings, False
  281. )
  282. if not cont_test or download_artifact is None:
  283. print_results(failed_test_strings, False)
  284. return False
  285. try:
  286. download_artifact.verify(root=sing_art_dir)
  287. except ValueError:
  288. failed_test_strings.append(
  289. "Artifact does not contain expected checksum. Contact W&B for support."
  290. )
  291. # test manifest and digest
  292. multi_art_dir = "./verify_art"
  293. alias = "art1"
  294. name = nice_id("my-artys")
  295. art1 = artifact_with_path_or_paths(name, "./verify_art_dir", singular=False)
  296. cont_test, download_artifact, failed_test_strings = log_use_download_artifact(
  297. art1, alias, name, multi_art_dir, failed_test_strings, True
  298. )
  299. if not cont_test or download_artifact is None:
  300. print_results(failed_test_strings, False)
  301. return False
  302. if set(os.listdir(multi_art_dir)) != {
  303. "verify_a.txt",
  304. "verify_2.txt",
  305. "verify_1.txt",
  306. "verify_3.txt",
  307. "verify_int_test.txt",
  308. }:
  309. failed_test_strings.append(
  310. "Artifact directory is missing files. Contact W&B for support."
  311. )
  312. computed = wandb.Artifact("computed", type="dataset")
  313. computed.add_dir(multi_art_dir)
  314. verify_digest(download_artifact, computed, failed_test_strings)
  315. computed_manifest = computed.manifest.to_manifest_json()["contents"]
  316. downloaded_manifest = download_artifact.manifest.to_manifest_json()["contents"]
  317. verify_manifest(downloaded_manifest, computed_manifest, failed_test_strings)
  318. print_results(failed_test_strings, False)
  319. return len(failed_test_strings) == 0
  320. def check_graphql_put(api: Api, host: str) -> tuple[bool, str | None]:
  321. # check graphql endpoint using an upload
  322. print("Checking signed URL upload".ljust(72, "."), end="") # noqa: T201
  323. failed_test_strings = []
  324. gql_fp = "gql_test_file.txt"
  325. f = open(gql_fp, "w")
  326. f.write("test2")
  327. f.close()
  328. with wandb.init(
  329. id=nice_id("graphql_put"),
  330. reinit=True,
  331. project=PROJECT_NAME,
  332. config={"test": "put to graphql"},
  333. ) as run:
  334. run.save(gql_fp)
  335. public_api = wandb.Api()
  336. prev_run = public_api.run(f"{run.entity}/{PROJECT_NAME}/{run.id}")
  337. if prev_run is None:
  338. failed_test_strings.append(
  339. "Unable to access previous run through public API. Contact W&B for support."
  340. )
  341. print_results(failed_test_strings, False)
  342. return False, None
  343. # TODO: (kdg) refactor this so it doesn't rely on an exception handler
  344. try:
  345. read_file = retry_fn(partial(prev_run.file, gql_fp))
  346. url = read_file.url
  347. read_file = retry_fn(partial(read_file.download, replace=True))
  348. except Exception:
  349. failed_test_strings.append(
  350. "Unable to read file successfully saved through a put request. Check SQS configurations, bucket permissions and topic configs."
  351. )
  352. print_results(failed_test_strings, False)
  353. return False, None
  354. contents = read_file.read()
  355. try:
  356. assert contents == "test2"
  357. except AssertionError:
  358. failed_test_strings.append(
  359. "Read file contents do not match saved file contents. Contact W&B for support."
  360. )
  361. print_results(failed_test_strings, False)
  362. return len(failed_test_strings) == 0, url
  363. def check_large_post() -> bool:
  364. print( # noqa: T201
  365. "Checking ability to send large payloads through proxy".ljust(72, "."), end=""
  366. )
  367. descy = "a" * int(10**7)
  368. username = getpass.getuser()
  369. failed_test_strings = []
  370. query = gql(
  371. """
  372. query Project($entity: String!, $name: String!, $runName: String!, $desc: String!){
  373. project(entityName: $entity, name: $name) {
  374. run(name: $runName, desc: $desc) {
  375. name
  376. summaryMetrics
  377. }
  378. }
  379. }
  380. """
  381. )
  382. public_api = wandb.Api()
  383. client = public_api._base_client
  384. try:
  385. client._get_result(
  386. query,
  387. variable_values={
  388. "entity": username,
  389. "name": PROJECT_NAME,
  390. "runName": "",
  391. "desc": descy,
  392. },
  393. timeout=60,
  394. )
  395. except Exception as e:
  396. if (
  397. isinstance(e, requests.HTTPError)
  398. and e.response is not None
  399. and e.response.status_code == 413
  400. ):
  401. failed_test_strings.append(
  402. 'Failed to send a large payload. Check nginx.ingress.kubernetes.io/proxy-body-size is "0".'
  403. )
  404. else:
  405. failed_test_strings.append(
  406. f"Failed to send a large payload with error: {e}."
  407. )
  408. print_results(failed_test_strings, False)
  409. return len(failed_test_strings) == 0
  410. def check_wandb_version(api: Api) -> None:
  411. print("Checking wandb package version is up to date".ljust(72, "."), end="") # noqa: T201
  412. _, server_info = api.viewer_server_info()
  413. fail_string = None
  414. warning = False
  415. max_cli_version = server_info.get("cliVersionInfo", {}).get("max_cli_version", None)
  416. min_cli_version = server_info.get("cliVersionInfo", {}).get(
  417. "min_cli_version", "0.0.1"
  418. )
  419. from packaging.version import parse
  420. if parse(wandb.__version__) < parse(min_cli_version):
  421. fail_string = f"wandb version out of date, please run pip install --upgrade wandb=={max_cli_version}"
  422. elif parse(wandb.__version__) > parse(max_cli_version):
  423. fail_string = (
  424. "wandb version is not supported by your local installation. This could "
  425. "cause some issues. If you're having problems try: please run `pip "
  426. f"install --upgrade wandb=={max_cli_version}`"
  427. )
  428. warning = True
  429. print_results(fail_string, warning)
  430. def check_sweeps(api: Api) -> bool:
  431. print("Checking sweep creation and agent execution".ljust(72, "."), end="") # noqa: T201
  432. failed_test_strings: list[str] = []
  433. sweep_config = {
  434. "method": "random",
  435. "metric": {"goal": "minimize", "name": "score"},
  436. "parameters": {
  437. "x": {"values": [0.01, 0.05, 0.1]},
  438. "y": {"values": [1, 2, 3]},
  439. },
  440. "name": "verify_sweep",
  441. }
  442. try:
  443. with contextlib.redirect_stdout(io.StringIO()):
  444. sweep_id = wandb.sweep(
  445. sweep=sweep_config, project=PROJECT_NAME, entity=api.default_entity
  446. )
  447. except Exception as e:
  448. failed_test_strings.append(f"Failed to create sweep: {e}")
  449. print_results(failed_test_strings, False)
  450. return False
  451. if not sweep_id:
  452. failed_test_strings.append("Sweep creation returned an invalid ID.")
  453. print_results(failed_test_strings, False)
  454. return False
  455. try:
  456. def objective(config):
  457. score = config.x**3 + config.y
  458. return score
  459. def main():
  460. with wandb.init(project=PROJECT_NAME) as run:
  461. score = objective(run.config)
  462. run.log({"score": score})
  463. wandb.agent(sweep_id, function=main, count=10)
  464. except Exception as e:
  465. failed_test_strings.append(f"Failed to run sweep agent: {e}")
  466. print_results(failed_test_strings, False)
  467. return False
  468. print_results(failed_test_strings, False)
  469. return len(failed_test_strings) == 0
  470. def retry_fn(fn: Callable) -> Any:
  471. ini_time = time.time()
  472. res = None
  473. i = 0
  474. while i < MIN_RETRYS or time.time() - ini_time < GET_RUN_MAX_TIME:
  475. i += 1
  476. try:
  477. res = fn()
  478. break
  479. except Exception:
  480. time.sleep(1)
  481. continue
  482. return res