verify.py 18 KB

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